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,
50 impl Writeable for Vec<RouteHop> {
51 fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
52 (self.len() as u8).write(writer)?;
53 for hop in self.iter() {
54 hop.pubkey.write(writer)?;
55 hop.node_features.write(writer)?;
56 hop.short_channel_id.write(writer)?;
57 hop.channel_features.write(writer)?;
58 hop.fee_msat.write(writer)?;
59 hop.cltv_expiry_delta.write(writer)?;
65 impl Readable for Vec<RouteHop> {
66 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Vec<RouteHop>, DecodeError> {
67 let hops_count: u8 = Readable::read(reader)?;
68 let mut hops = Vec::with_capacity(hops_count as usize);
69 for _ in 0..hops_count {
71 pubkey: Readable::read(reader)?,
72 node_features: Readable::read(reader)?,
73 short_channel_id: Readable::read(reader)?,
74 channel_features: Readable::read(reader)?,
75 fee_msat: Readable::read(reader)?,
76 cltv_expiry_delta: Readable::read(reader)?,
83 /// A route directs a payment from the sender (us) to the recipient. If the recipient supports MPP,
84 /// it can take multiple paths. Each path is composed of one or more hops through the network.
85 #[derive(Clone, PartialEq)]
87 /// The list of routes taken for a single (potentially-)multi-part payment. The pubkey of the
88 /// last RouteHop in each path must be the same.
89 /// Each entry represents a list of hops, NOT INCLUDING our own, where the last hop is the
90 /// destination. Thus, this must always be at least length one. While the maximum length of any
91 /// given path is variable, keeping the length of any path to less than 20 should currently
92 /// ensure it is viable.
93 pub paths: Vec<Vec<RouteHop>>,
96 impl Writeable for Route {
97 fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
98 (self.paths.len() as u64).write(writer)?;
99 for hops in self.paths.iter() {
106 impl Readable for Route {
107 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
108 let path_count: u64 = Readable::read(reader)?;
109 let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
110 for _ in 0..path_count {
111 paths.push(Readable::read(reader)?);
117 /// A channel descriptor which provides a last-hop route to get_route
119 pub struct RouteHint {
120 /// The node_id of the non-target end of the route
121 pub src_node_id: PublicKey,
122 /// The short_channel_id of this channel
123 pub short_channel_id: u64,
124 /// The fees which must be paid to use this channel
125 pub fees: RoutingFees,
126 /// The difference in CLTV values between this node and the next node.
127 pub cltv_expiry_delta: u16,
128 /// The minimum value, in msat, which must be relayed to the next hop.
129 pub htlc_minimum_msat: Option<u64>,
130 /// The maximum value in msat available for routing with a single HTLC.
131 pub htlc_maximum_msat: Option<u64>,
134 #[derive(Eq, PartialEq)]
135 struct RouteGraphNode {
137 lowest_fee_to_peer_through_node: u64,
138 lowest_fee_to_node: u64,
139 // The maximum value a yet-to-be-constructed payment path might flow through this node.
140 // This value is upper-bounded by us by:
141 // - how much is needed for a path being constructed
142 // - how much value can channels following this node (up to the destination) can contribute,
143 // considering their capacity and fees
144 value_contribution_msat: u64,
145 /// The maximum htlc_minimum_msat along the path, taking into consideration the fees required
146 /// to meet the minimum over the hops required to get there.
147 path_htlc_minimum_msat: u64,
150 impl cmp::Ord for RouteGraphNode {
151 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
152 other.lowest_fee_to_peer_through_node.cmp(&self.lowest_fee_to_peer_through_node)
153 .then_with(|| other.pubkey.serialize().cmp(&self.pubkey.serialize()))
157 impl cmp::PartialOrd for RouteGraphNode {
158 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
159 Some(self.cmp(other))
163 struct DummyDirectionalChannelInfo {
164 cltv_expiry_delta: u32,
165 htlc_minimum_msat: u64,
166 htlc_maximum_msat: Option<u64>,
170 /// It's useful to keep track of the hops associated with the fees required to use them,
171 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
172 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
173 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
175 struct PathBuildingHop {
176 /// Hop-specific details unrelated to the path during the routing phase,
177 /// but rather relevant to the LN graph.
179 /// Minimal fees required to route to the source node of the current hop via any of its inbound channels.
180 src_lowest_inbound_fees: RoutingFees,
181 /// Fees of the channel used in this hop.
182 channel_fees: RoutingFees,
183 /// All the fees paid *after* this channel on the way to the destination
184 next_hops_fee_msat: u64,
185 /// Fee paid for the use of the current channel (see channel_fees).
186 /// The value will be actually deducted from the counterparty balance on the previous link.
187 hop_use_fee_msat: u64,
188 /// Used to compare channels when choosing the for routing.
189 /// Includes paying for the use of a hop and the following hops, as well as
190 /// an estimated cost of reaching this hop.
191 /// Might get stale when fees are recomputed. Primarily for internal use.
193 /// This is useful for update_value_and_recompute_fees to make sure
194 /// we don't fall below the minimum. Should not be updated manually and
195 /// generally should not be accessed.
196 htlc_minimum_msat: u64,
199 impl PathBuildingHop {
200 // What we are paying for the use of this channels and the following channels.
201 fn get_fee_paid_msat(&self) -> u64 {
202 if let Some(fee_paid_msat) =
203 self.next_hops_fee_msat.checked_add(self.hop_use_fee_msat) {
204 return fee_paid_msat;
206 return u64::max_value();
211 // Instantiated with a list of hops with correct data in them collected during path finding,
212 // an instance of this struct should be further modified only via given methods.
215 hops: Vec<PathBuildingHop>,
220 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
221 fn get_value_msat(&self) -> u64 {
222 self.hops.last().unwrap().route_hop.fee_msat
225 fn get_total_fee_paid_msat(&self) -> u64 {
226 if self.hops.len() < 1 {
230 // Can't use next_hops_fee_msat because it gets outdated.
231 for (i, hop) in self.hops.iter().enumerate() {
232 if i != self.hops.len() - 1 {
233 result += hop.route_hop.fee_msat;
239 // If an amount transferred by the path is updated, the fees should be adjusted.
240 // Any other way to change fees may result in an inconsistency.
241 // Also, it's only safe to reduce the value, to not violate limits like
242 // htlc_minimum_msat.
243 fn update_value_and_recompute_fees(&mut self, value_msat: u64) {
244 if value_msat == self.hops.last().unwrap().route_hop.fee_msat {
245 // Nothing to change.
248 assert!(value_msat < self.hops.last().unwrap().route_hop.fee_msat);
250 let mut total_fee_paid_msat = 0 as u64;
251 for i in (0..self.hops.len()).rev() {
252 let last_hop = i == self.hops.len() - 1;
254 // For non-last-hop, this value will represent the fees paid on the current hop. It
255 // will consist of the fees for the use of the next hop, and extra fees to match
256 // htlc_minimum_msat of the current channel. Last hop is handled separately.
257 let mut cur_hop_fees_msat = 0;
259 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().hop_use_fee_msat;
262 let mut cur_hop = self.hops.get_mut(i).unwrap();
263 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
264 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
265 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
266 // set it too high just to maliciously take more fees by exploiting this
267 // match htlc_minimum_msat logic.
268 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
269 if let Some(extra_fees_msat) = cur_hop.htlc_minimum_msat.checked_sub(cur_hop_transferred_amount_msat) {
270 cur_hop_transferred_amount_msat += extra_fees_msat;
271 total_fee_paid_msat += extra_fees_msat;
272 cur_hop_fees_msat += extra_fees_msat;
276 // Final hop is a special case: it usually has just value_msat (by design), but also
277 // it still could overpay for the htlc_minimum_msat.
278 cur_hop.route_hop.fee_msat = cur_hop_transferred_amount_msat;
280 // Propagate updated fees for the use of the channels to one hop back, where they
281 // will be actually paid (fee_msat). The last hop is handled above separately.
282 cur_hop.route_hop.fee_msat = cur_hop_fees_msat;
285 // Fee for the use of the current hop which will be deducted on the previous hop.
286 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
287 // this channel is free for us.
289 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.channel_fees) {
290 cur_hop.hop_use_fee_msat = new_fee;
291 total_fee_paid_msat += new_fee;
293 // It should not be possible because this function is called only to reduce the
294 // value. In that case, compute_fee was already called with the same fees for
295 // larger amount and there was no overflow.
303 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
304 let proportional_fee_millions =
305 amount_msat.checked_mul(channel_fees.proportional_millionths as u64);
306 if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
307 (channel_fees.base_msat as u64).checked_add(part / 1_000_000) }) {
311 // This function may be (indirectly) called without any verification,
312 // with channel_fees provided by a caller. We should handle it gracefully.
317 /// Gets a route from us (payer) to the given target node (payee).
319 /// Extra routing hops between known nodes and the target will be used if they are included in
322 /// If some channels aren't announced, it may be useful to fill in a first_hops with the
323 /// results from a local ChannelManager::list_usable_channels() call. If it is filled in, our
324 /// view of our local channels (from net_graph_msg_handler) will be ignored, and only those
325 /// in first_hops will be used.
327 /// Panics if first_hops contains channels without short_channel_ids
328 /// (ChannelManager::list_usable_channels will never include such channels).
330 /// The fees on channels from us to next-hops are ignored (as they are assumed to all be
331 /// equal), however the enabled/disabled bit on such channels as well as the
332 /// htlc_minimum_msat/htlc_maximum_msat *are* checked as they may change based on the receiving node.
333 pub fn get_route<L: Deref>(our_node_id: &PublicKey, network: &NetworkGraph, payee: &PublicKey, first_hops: Option<&[&ChannelDetails]>,
334 last_hops: &[&RouteHint], final_value_msat: u64, final_cltv: u32, logger: L) -> Result<Route, LightningError> where L::Target: Logger {
335 // TODO: Obviously *only* using total fee cost sucks. We should consider weighting by
336 // uptime/success in using a node in the past.
337 if *payee == *our_node_id {
338 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
341 if final_value_msat > MAX_VALUE_MSAT {
342 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
345 if final_value_msat == 0 {
346 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
349 for last_hop in last_hops {
350 if last_hop.src_node_id == *payee {
351 return Err(LightningError{err: "Last hop cannot have a payee as a source.".to_owned(), action: ErrorAction::IgnoreError});
355 // The general routing idea is the following:
356 // 1. Fill first/last hops communicated by the caller.
357 // 2. Attempt to construct a path from payer to payee for transferring
358 // any ~sufficient (described later) value.
359 // If succeed, remember which channels were used and how much liquidity they have available,
360 // so that future paths don't rely on the same liquidity.
361 // 3. Prooceed to the next step if:
362 // - we hit the recommended target value;
363 // - OR if we could not construct a new path. Any next attempt will fail too.
364 // Otherwise, repeat step 2.
365 // 4. See if we managed to collect paths which aggregately are able to transfer target value
366 // (not recommended value). If yes, proceed. If not, fail routing.
367 // 5. Randomly combine paths into routes having enough to fulfill the payment. (TODO: knapsack)
368 // 6. Of all the found paths, select only those with the lowest total fee.
369 // 7. The last path in every selected route is likely to be more than we need.
370 // Reduce its value-to-transfer and recompute fees.
371 // 8. Choose the best route by the lowest total fee.
373 // As for the actual search algorithm,
374 // we do a payee-to-payer Dijkstra's sorting by each node's distance from the payee
375 // plus the minimum per-HTLC fee to get from it to another node (aka "shitty A*").
376 // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
377 // to use as the A* heuristic beyond just the cost to get one node further than the current
380 let dummy_directional_info = DummyDirectionalChannelInfo { // used for first_hops routes
381 cltv_expiry_delta: 0,
382 htlc_minimum_msat: 0,
383 htlc_maximum_msat: None,
386 proportional_millionths: 0,
390 let mut targets = BinaryHeap::new(); //TODO: Do we care about switching to eg Fibbonaci heap?
391 let mut dist = HashMap::with_capacity(network.get_nodes().len());
393 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
394 // Don't stop searching for paths when we think they're
395 // sufficient to transfer a given value aggregately.
396 // Search for higher value, so that we collect many more paths,
397 // and then select the best combination among them.
398 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
399 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
402 // Prepare the data we'll use for payee-to-payer search by
403 // inserting first hops suggested by the caller as targets.
404 // Our search will then attempt to reach them while traversing from the payee node.
405 let mut first_hop_targets = HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
406 if let Some(hops) = first_hops {
408 let short_channel_id = chan.short_channel_id.expect("first_hops should be filled in with usable channels, not pending ones");
409 if chan.remote_network_id == *our_node_id {
410 return Err(LightningError{err: "First hop cannot have our_node_id as a destination.".to_owned(), action: ErrorAction::IgnoreError});
412 first_hop_targets.insert(chan.remote_network_id, (short_channel_id, chan.counterparty_features.clone(), chan.outbound_capacity_msat));
414 if first_hop_targets.is_empty() {
415 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
419 // We don't want multiple paths (as per MPP) share liquidity of the same channels.
420 // This map allows paths to be aware of the channel use by other paths in the same call.
421 // This would help to make a better path finding decisions and not "overbook" channels.
422 // It is unaware of the directions (except for `outbound_capacity_msat` in `first_hops`).
423 let mut bookkeeped_channels_liquidity_available_msat = HashMap::new();
425 // Keeping track of how much value we already collected across other paths. Helps to decide:
426 // - how much a new path should be transferring (upper bound);
427 // - whether a channel should be disregarded because
428 // it's available liquidity is too small comparing to how much more we need to collect;
429 // - when we want to stop looking for new paths.
430 let mut already_collected_value_msat = 0;
432 macro_rules! add_entry {
433 // Adds entry which goes from $src_node_id to $dest_node_id
434 // over the channel with id $chan_id with fees described in
435 // $directional_info.
436 // $next_hops_fee_msat represents the fees paid for using all the channel *after* this one,
437 // since that value has to be transferred over this channel.
438 ( $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,
439 $next_hops_value_contribution: expr, $incl_fee_next_hops_htlc_minimum_msat: expr ) => {
440 // Channels to self should not be used. This is more of belt-and-suspenders, because in
441 // practice these cases should be caught earlier:
442 // - for regular channels at channel announcement (TODO)
443 // - for first and last hops early in get_route
444 if $src_node_id != $dest_node_id.clone() {
445 let available_liquidity_msat = bookkeeped_channels_liquidity_available_msat.entry($chan_id.clone()).or_insert_with(|| {
446 let mut initial_liquidity_available_msat = None;
447 if let Some(capacity_sats) = $capacity_sats {
448 initial_liquidity_available_msat = Some(capacity_sats * 1000);
451 if let Some(htlc_maximum_msat) = $directional_info.htlc_maximum_msat {
452 if let Some(available_msat) = initial_liquidity_available_msat {
453 initial_liquidity_available_msat = Some(cmp::min(available_msat, htlc_maximum_msat));
455 initial_liquidity_available_msat = Some(htlc_maximum_msat);
459 match initial_liquidity_available_msat {
460 Some(available_msat) => available_msat,
461 // We assume channels with unknown balance have
462 // a capacity of 0.0025 BTC (or 250_000 sats).
463 None => 250_000 * 1000
467 // It is tricky to substract $next_hops_fee_msat from available liquidity here.
468 // It may be misleading because we might later choose to reduce the value transferred
469 // over these channels, and the channel which was insufficient might become sufficient.
470 // Worst case: we drop a good channel here because it can't cover the high following
471 // fees caused by one expensive channel, but then this channel could have been used
472 // if the amount being transferred over this path is lower.
473 // We do this for now, but this is a subject for removal.
474 if let Some(available_value_contribution_msat) = available_liquidity_msat.checked_sub($next_hops_fee_msat) {
476 // Routing Fragmentation Mitigation heuristic:
478 // Routing fragmentation across many payment paths increases the overall routing
479 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
480 // Taking too many smaller paths also increases the chance of payment failure.
481 // Thus to avoid this effect, we require from our collected links to provide
482 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
484 // This requirement is currently 5% of the remaining-to-be-collected value.
485 // This means as we successfully advance in our collection,
486 // the absolute liquidity contribution is lowered,
487 // thus increasing the number of potential channels to be selected.
489 // Derive the minimal liquidity contribution with a ratio of 20 (5%, rounded up).
490 let minimal_value_contribution_msat: u64 = (recommended_value_msat - already_collected_value_msat + 19) / 20;
491 // Verify the liquidity offered by this channel complies to the minimal contribution.
492 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
494 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
495 // Includes paying fees for the use of the following channels.
496 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
497 Some(result) => result,
498 // Can't overflow due to how the values were computed right above.
499 None => unreachable!(),
501 let over_path_minimum_msat = amount_to_transfer_over_msat >= $directional_info.htlc_minimum_msat &&
502 amount_to_transfer_over_msat >= $incl_fee_next_hops_htlc_minimum_msat;
504 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
505 // bother considering this channel.
506 // Since we're choosing amount_to_transfer_over_msat as maximum possible, it can
507 // be only reduced later (not increased), so this channel should just be skipped
508 // as not sufficient.
509 // TODO: Explore simply adding fee to hit htlc_minimum_msat
510 if contributes_sufficient_value && over_path_minimum_msat {
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,
582 path_htlc_minimum_msat: match compute_fees($incl_fee_next_hops_htlc_minimum_msat, $directional_info.fees) {
583 Some(fee_msat) => cmp::max(fee_msat, $directional_info.htlc_minimum_msat),
584 None => u64::max_value(),
588 // Update the way of reaching $src_node_id with the given $chan_id (from $dest_node_id),
589 // if this way is cheaper than the already known
590 // (considering the cost to "reach" this channel from the route destination,
591 // the cost of using this channel,
592 // and the cost of routing to the source node of this channel).
593 // Also, consider that htlc_minimum_msat_difference, because we might end up
594 // paying it. Consider the following exploit:
595 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
596 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
597 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
598 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
600 // TODO: this scoring could be smarter (e.g. 0.5*htlc_minimum_msat here).
601 let mut old_cost = old_entry.total_fee_msat;
602 if let Some(increased_old_cost) = old_cost.checked_add(old_entry.htlc_minimum_msat) {
603 old_cost = increased_old_cost;
605 old_cost = u64::max_value();
608 let mut new_cost = total_fee_msat;
609 if let Some(increased_new_cost) = new_cost.checked_add($directional_info.htlc_minimum_msat) {
610 new_cost = increased_new_cost;
612 new_cost = u64::max_value();
615 if new_cost < old_cost {
616 targets.push(new_graph_node);
617 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
618 old_entry.hop_use_fee_msat = hop_use_fee_msat;
619 old_entry.total_fee_msat = total_fee_msat;
620 old_entry.route_hop = RouteHop {
621 pubkey: $dest_node_id.clone(),
622 node_features: NodeFeatures::empty(),
623 short_channel_id: $chan_id.clone(),
624 channel_features: $chan_features.clone(),
625 fee_msat: 0, // This value will be later filled with hop_use_fee_msat of the following channel
626 cltv_expiry_delta: $directional_info.cltv_expiry_delta as u32,
628 old_entry.channel_fees = $directional_info.fees;
629 // It's probably fine to replace the old entry, because the new one
630 // passed the htlc_minimum-related checks above.
631 old_entry.htlc_minimum_msat = $directional_info.htlc_minimum_msat;
639 // Find ways (channels with destination) to reach a given node and store them
640 // in the corresponding data structures (routing graph etc).
641 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
642 // meaning how much will be paid in fees after this node (to the best of our knowledge).
643 // This data can later be helpful to optimize routing (pay lower fees).
644 macro_rules! add_entries_to_cheapest_to_target_node {
645 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr, $next_hops_value_contribution: expr, $incl_fee_next_hops_htlc_minimum_msat: expr ) => {
646 if first_hops.is_some() {
647 if let Some(&(ref first_hop, ref features, ref outbound_capacity_msat)) = first_hop_targets.get(&$node_id) {
648 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, $incl_fee_next_hops_htlc_minimum_msat);
653 if let Some(node_info) = $node.announcement_info.as_ref() {
654 features = node_info.features.clone();
656 features = NodeFeatures::empty();
659 if !features.requires_unknown_bits() {
660 for chan_id in $node.channels.iter() {
661 let chan = network.get_channels().get(chan_id).unwrap();
662 if !chan.features.requires_unknown_bits() {
663 if chan.node_one == *$node_id {
664 // ie $node is one, ie next hop in A* is two, via the two_to_one channel
665 if first_hops.is_none() || chan.node_two != *our_node_id {
666 if let Some(two_to_one) = chan.two_to_one.as_ref() {
667 if two_to_one.enabled {
668 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, $incl_fee_next_hops_htlc_minimum_msat);
673 if first_hops.is_none() || chan.node_one != *our_node_id {
674 if let Some(one_to_two) = chan.one_to_two.as_ref() {
675 if one_to_two.enabled {
676 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, $incl_fee_next_hops_htlc_minimum_msat);
688 let mut payment_paths = Vec::<PaymentPath>::new();
690 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
691 'paths_collection: loop {
692 // For every new path, start from scratch, except
693 // bookkeeped_channels_liquidity_available_msat, which will improve
694 // the further iterations of path finding. Also don't erase first_hop_targets.
698 // If first hop is a private channel and the only way to reach the payee, this is the only
699 // place where it could be added.
700 if first_hops.is_some() {
701 if let Some(&(ref first_hop, ref features, ref outbound_capacity_msat)) = first_hop_targets.get(&payee) {
702 add_entry!(first_hop, *our_node_id, payee, dummy_directional_info, Some(outbound_capacity_msat / 1000), features.to_context(), 0, recommended_value_msat, 0);
706 // Add the payee as a target, so that the payee-to-payer
707 // search algorithm knows what to start with.
708 match network.get_nodes().get(payee) {
709 // The payee is not in our network graph, so nothing to add here.
710 // There is still a chance of reaching them via last_hops though,
711 // so don't yet fail the payment here.
712 // If not, targets.pop() will not even let us enter the loop in step 2.
715 add_entries_to_cheapest_to_target_node!(node, payee, 0, recommended_value_msat, 0);
720 // If a caller provided us with last hops, add them to routing targets. Since this happens
721 // earlier than general path finding, they will be somewhat prioritized, although currently
722 // it matters only if the fees are exactly the same.
723 for hop in last_hops.iter() {
724 let have_hop_src_in_graph =
725 if let Some(&(ref first_hop, ref features, ref outbound_capacity_msat)) = first_hop_targets.get(&hop.src_node_id) {
726 // If this hop connects to a node with which we have a direct channel, ignore
727 // the network graph and add both the hop and our direct channel to
728 // the candidate set.
730 // Currently there are no channel-context features defined, so we are a
731 // bit lazy here. In the future, we should pull them out via our
732 // ChannelManager, but there's no reason to waste the space until we
734 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, 0);
737 // In any other case, only add the hop if the source is in the regular network
739 network.get_nodes().get(&hop.src_node_id).is_some()
741 if have_hop_src_in_graph {
742 // BOLT 11 doesn't allow inclusion of features for the last hop hints, which
743 // really sucks, cause we're gonna need that eventually.
744 let last_path_htlc_minimum_msat: u64 = match hop.htlc_minimum_msat {
745 Some(htlc_minimum_msat) => htlc_minimum_msat,
748 let directional_info = DummyDirectionalChannelInfo {
749 cltv_expiry_delta: hop.cltv_expiry_delta as u32,
750 htlc_minimum_msat: last_path_htlc_minimum_msat,
751 htlc_maximum_msat: hop.htlc_maximum_msat,
754 add_entry!(hop.short_channel_id, hop.src_node_id, payee, directional_info, None::<u64>, ChannelFeatures::empty(), 0, recommended_value_msat, 0);
758 // At this point, targets are filled with the data from first and
759 // last hops communicated by the caller, and the payment receiver.
760 let mut found_new_path = false;
763 // If this loop terminates due the exhaustion of targets, two situations are possible:
764 // - not enough outgoing liquidity:
765 // 0 < already_collected_value_msat < final_value_msat
766 // - enough outgoing liquidity:
767 // final_value_msat <= already_collected_value_msat < recommended_value_msat
768 // Both these cases (and other cases except reaching recommended_value_msat) mean that
769 // paths_collection will be stopped because found_new_path==false.
770 // This is not necessarily a routing failure.
771 'path_construction: while let Some(RouteGraphNode { pubkey, lowest_fee_to_node, value_contribution_msat, path_htlc_minimum_msat, .. }) = targets.pop() {
773 // Since we're going payee-to-payer, hitting our node as a target means we should stop
774 // traversing the graph and arrange the path out of what we found.
775 if pubkey == *our_node_id {
776 let mut new_entry = dist.remove(&our_node_id).unwrap();
777 let mut ordered_hops = vec!(new_entry.clone());
780 if let Some(&(_, ref features, _)) = first_hop_targets.get(&ordered_hops.last().unwrap().route_hop.pubkey) {
781 ordered_hops.last_mut().unwrap().route_hop.node_features = features.to_context();
782 } else if let Some(node) = network.get_nodes().get(&ordered_hops.last().unwrap().route_hop.pubkey) {
783 if let Some(node_info) = node.announcement_info.as_ref() {
784 ordered_hops.last_mut().unwrap().route_hop.node_features = node_info.features.clone();
786 ordered_hops.last_mut().unwrap().route_hop.node_features = NodeFeatures::empty();
789 // We should be able to fill in features for everything except the last
790 // hop, if the last hop was provided via a BOLT 11 invoice (though we
791 // should be able to extend it further as BOLT 11 does have feature
792 // flags for the last hop node itself).
793 assert!(ordered_hops.last().unwrap().route_hop.pubkey == *payee);
796 // Means we succesfully traversed from the payer to the payee, now
797 // save this path for the payment route. Also, update the liquidity
798 // remaining on the used hops, so that we take them into account
799 // while looking for more paths.
800 if ordered_hops.last().unwrap().route_hop.pubkey == *payee {
804 new_entry = match dist.remove(&ordered_hops.last().unwrap().route_hop.pubkey) {
805 Some(payment_hop) => payment_hop,
807 // If we can't reach a given node, something went wrong
808 // during path traverse.
809 // Stop looking for more paths here because next iterations
810 // will face the exact same issue.
811 break 'paths_collection;
814 // We "propagate" the fees one hop backward (topologically) here,
815 // so that fees paid for a HTLC forwarding on the current channel are
816 // associated with the previous channel (where they will be subtracted).
817 ordered_hops.last_mut().unwrap().route_hop.fee_msat = new_entry.hop_use_fee_msat;
818 ordered_hops.last_mut().unwrap().route_hop.cltv_expiry_delta = new_entry.route_hop.cltv_expiry_delta;
819 ordered_hops.push(new_entry.clone());
821 ordered_hops.last_mut().unwrap().route_hop.fee_msat = value_contribution_msat;
822 ordered_hops.last_mut().unwrap().hop_use_fee_msat = 0;
823 ordered_hops.last_mut().unwrap().route_hop.cltv_expiry_delta = final_cltv;
825 let payment_path = PaymentPath {hops: ordered_hops};
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 (i, payment_hop) in payment_path.hops.iter().enumerate() {
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 hop_and_after_fee = payment_hop.get_fee_paid_msat();
839 if i == payment_path.hops.len() - 1 {
840 // For the last hop the fee should always be 0.
841 assert_eq!(hop_and_after_fee, 0);
843 spent_on_hop_msat += hop_and_after_fee;
844 if *channel_liquidity_available_msat < spent_on_hop_msat {
845 // This should not happen because we do recompute fees right before,
846 // trying to avoid cases when a hop is not usable due to the fee situation.
847 break 'path_construction;
849 *channel_liquidity_available_msat -= spent_on_hop_msat;
851 // Track the total amount all our collected paths allow to send so that we:
852 // - know when to stop looking for more paths
853 // - know which of the hops are useless considering how much more sats we need
854 // (contributes_sufficient_value)
855 already_collected_value_msat += value_contribution_msat;
857 payment_paths.push(payment_path);
858 found_new_path = true;
859 break 'path_construction;
862 // Otherwise, since the current target node is not us,
863 // keep "unrolling" the payment graph from payee to payer by
864 // finding a way to reach the current target from the payer side.
865 match network.get_nodes().get(&pubkey) {
868 add_entries_to_cheapest_to_target_node!(node, &pubkey, lowest_fee_to_node, value_contribution_msat, path_htlc_minimum_msat);
874 // Stop either when recommended value is reached,
875 // or if during last iteration no new path was found.
876 // In the latter case, making another path finding attempt could not help,
877 // because we deterministically terminate the search due to low liquidity.
878 if already_collected_value_msat >= recommended_value_msat || !found_new_path {
879 break 'paths_collection;
884 if payment_paths.len() == 0 {
885 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
888 if already_collected_value_msat < final_value_msat {
889 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
892 // Sort by total fees and take the best paths.
893 payment_paths.sort_by_key(|path| path.get_total_fee_paid_msat());
894 if payment_paths.len() > 50 {
895 payment_paths.truncate(50);
898 // Draw multiple sufficient routes by randomly combining the selected paths.
899 let mut drawn_routes = Vec::new();
900 for i in 0..payment_paths.len() {
901 let mut cur_route = Vec::<PaymentPath>::new();
902 let mut aggregate_route_value_msat = 0;
905 // TODO: real random shuffle
906 // Currently just starts with i_th and goes up to i-1_th in a looped way.
907 let cur_payment_paths = [&payment_paths[i..], &payment_paths[..i]].concat();
910 for payment_path in cur_payment_paths {
911 cur_route.push(payment_path.clone());
912 aggregate_route_value_msat += payment_path.get_value_msat();
913 if aggregate_route_value_msat > final_value_msat {
914 // Last path likely overpaid. Substract it from the most expensive
915 // (in terms of proportional fee) path in this route and recompute fees.
916 // This might be not the most economically efficient way, but fewer paths
917 // also makes routing more reliable.
918 let mut overpaid_value_msat = aggregate_route_value_msat - final_value_msat;
920 // First, drop some expensive low-value paths entirely if possible.
921 // Sort by value so that we drop many really-low values first, since
922 // fewer paths is better: the payment is less likely to fail.
923 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
924 // so that the sender pays less fees overall. And also htlc_minimum_msat.
925 cur_route.sort_by_key(|path| path.get_value_msat());
926 // We should make sure that at least 1 path left.
927 let mut paths_left = cur_route.len();
928 cur_route.retain(|path| {
933 let path_value_msat = path.get_value_msat();
934 if path_value_msat <= overpaid_value_msat {
936 overpaid_value_msat -= path_value_msat;
942 if overpaid_value_msat == 0 {
946 assert!(cur_route.len() > 0);
949 // Now, substract the overpaid value from the most-expensive path.
950 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
951 // so that the sender pays less fees overall. And also htlc_minimum_msat.
952 cur_route.sort_by_key(|path| { path.hops.iter().map(|hop| hop.channel_fees.proportional_millionths as u64).sum::<u64>() });
953 for expensive_payment_path in &mut cur_route {
954 if let Some(expensive_path_new_value_msat) = expensive_payment_path.get_value_msat().checked_sub(overpaid_value_msat) {
955 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
958 // We already dropped all the small channels above, meaning all the
959 // remaining channels are larger than remaining overpaid_value_msat.
960 // Thus, this can't be negative.
967 drawn_routes.push(cur_route);
971 // Select the best route by lowest total fee.
972 drawn_routes.sort_by_key(|paths| paths.iter().map(|path| path.get_total_fee_paid_msat()).sum::<u64>());
973 let mut selected_paths = Vec::<Vec::<RouteHop>>::new();
974 for payment_path in drawn_routes.first().unwrap() {
975 selected_paths.push(payment_path.hops.iter().map(|payment_hop| payment_hop.route_hop.clone()).collect());
978 let route = Route { paths: selected_paths };
979 log_trace!(logger, "Got route: {}", log_route!(route));
985 use routing::router::{get_route, RouteHint, RoutingFees};
986 use routing::network_graph::{NetworkGraph, NetGraphMsgHandler};
987 use ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
988 use ln::msgs::{ErrorAction, LightningError, OptionalField, UnsignedChannelAnnouncement, ChannelAnnouncement, RoutingMessageHandler,
989 NodeAnnouncement, UnsignedNodeAnnouncement, ChannelUpdate, UnsignedChannelUpdate};
990 use ln::channelmanager;
991 use util::test_utils;
992 use util::ser::Writeable;
994 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
995 use bitcoin::hashes::Hash;
996 use bitcoin::network::constants::Network;
997 use bitcoin::blockdata::constants::genesis_block;
998 use bitcoin::blockdata::script::Builder;
999 use bitcoin::blockdata::opcodes;
1000 use bitcoin::blockdata::transaction::TxOut;
1004 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
1005 use bitcoin::secp256k1::{Secp256k1, All};
1009 // Using the same keys for LN and BTC ids
1010 fn add_channel(net_graph_msg_handler: &NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>, secp_ctx: &Secp256k1<All>, node_1_privkey: &SecretKey,
1011 node_2_privkey: &SecretKey, features: ChannelFeatures, short_channel_id: u64) {
1012 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1013 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1015 let unsigned_announcement = UnsignedChannelAnnouncement {
1017 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1021 bitcoin_key_1: node_id_1,
1022 bitcoin_key_2: node_id_2,
1023 excess_data: Vec::new(),
1026 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1027 let valid_announcement = ChannelAnnouncement {
1028 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1029 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1030 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1031 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1032 contents: unsigned_announcement.clone(),
1034 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1035 Ok(res) => assert!(res),
1040 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) {
1041 let msghash = hash_to_message!(&Sha256dHash::hash(&update.encode()[..])[..]);
1042 let valid_channel_update = ChannelUpdate {
1043 signature: secp_ctx.sign(&msghash, node_privkey),
1044 contents: update.clone()
1047 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1048 Ok(res) => assert!(res),
1053 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,
1054 features: NodeFeatures, timestamp: u32) {
1055 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
1056 let unsigned_announcement = UnsignedNodeAnnouncement {
1062 addresses: Vec::new(),
1063 excess_address_data: Vec::new(),
1064 excess_data: Vec::new(),
1066 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1067 let valid_announcement = NodeAnnouncement {
1068 signature: secp_ctx.sign(&msghash, node_privkey),
1069 contents: unsigned_announcement.clone()
1072 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1078 fn get_nodes(secp_ctx: &Secp256k1<All>) -> (SecretKey, PublicKey, Vec<SecretKey>, Vec<PublicKey>) {
1079 let privkeys: Vec<SecretKey> = (2..10).map(|i| {
1080 SecretKey::from_slice(&hex::decode(format!("{:02}", i).repeat(32)).unwrap()[..]).unwrap()
1083 let pubkeys = privkeys.iter().map(|secret| PublicKey::from_secret_key(&secp_ctx, secret)).collect();
1085 let our_privkey = SecretKey::from_slice(&hex::decode("01".repeat(32)).unwrap()[..]).unwrap();
1086 let our_id = PublicKey::from_secret_key(&secp_ctx, &our_privkey);
1088 (our_privkey, our_id, privkeys, pubkeys)
1091 fn id_to_feature_flags(id: u8) -> Vec<u8> {
1092 // Set the feature flags to the id'th odd (ie non-required) feature bit so that we can
1093 // test for it later.
1094 let idx = (id - 1) * 2 + 1;
1096 vec![1 << (idx - 8*3), 0, 0, 0]
1097 } else if idx > 8*2 {
1098 vec![1 << (idx - 8*2), 0, 0]
1099 } else if idx > 8*1 {
1100 vec![1 << (idx - 8*1), 0]
1106 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>) {
1107 let secp_ctx = Secp256k1::new();
1108 let logger = Arc::new(test_utils::TestLogger::new());
1109 let chain_monitor = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1110 let net_graph_msg_handler = NetGraphMsgHandler::new(genesis_block(Network::Testnet).header.block_hash(), None, Arc::clone(&logger));
1111 // Build network from our_id to node7:
1113 // -1(1)2- node0 -1(3)2-
1115 // our_id -1(12)2- node7 -1(13)2--- node2
1117 // -1(2)2- node1 -1(4)2-
1120 // chan1 1-to-2: disabled
1121 // chan1 2-to-1: enabled, 0 fee
1123 // chan2 1-to-2: enabled, ignored fee
1124 // chan2 2-to-1: enabled, 0 fee
1126 // chan3 1-to-2: enabled, 0 fee
1127 // chan3 2-to-1: enabled, 100 msat fee
1129 // chan4 1-to-2: enabled, 100% fee
1130 // chan4 2-to-1: enabled, 0 fee
1132 // chan12 1-to-2: enabled, ignored fee
1133 // chan12 2-to-1: enabled, 0 fee
1135 // chan13 1-to-2: enabled, 200% fee
1136 // chan13 2-to-1: enabled, 0 fee
1139 // -1(5)2- node3 -1(8)2--
1143 // node2--1(6)2- node4 -1(9)2--- node6 (not in global route map)
1145 // -1(7)2- node5 -1(10)2-
1147 // chan5 1-to-2: enabled, 100 msat fee
1148 // chan5 2-to-1: enabled, 0 fee
1150 // chan6 1-to-2: enabled, 0 fee
1151 // chan6 2-to-1: enabled, 0 fee
1153 // chan7 1-to-2: enabled, 100% fee
1154 // chan7 2-to-1: enabled, 0 fee
1156 // chan8 1-to-2: enabled, variable fee (0 then 1000 msat)
1157 // chan8 2-to-1: enabled, 0 fee
1159 // chan9 1-to-2: enabled, 1001 msat fee
1160 // chan9 2-to-1: enabled, 0 fee
1162 // chan10 1-to-2: enabled, 0 fee
1163 // chan10 2-to-1: enabled, 0 fee
1165 // chan11 1-to-2: enabled, 0 fee
1166 // chan11 2-to-1: enabled, 0 fee
1168 let (our_privkey, _, privkeys, _) = get_nodes(&secp_ctx);
1170 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[0], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
1171 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1172 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1173 short_channel_id: 1,
1176 cltv_expiry_delta: 0,
1177 htlc_minimum_msat: 0,
1178 htlc_maximum_msat: OptionalField::Absent,
1180 fee_proportional_millionths: 0,
1181 excess_data: Vec::new()
1184 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
1186 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
1187 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1188 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1189 short_channel_id: 2,
1192 cltv_expiry_delta: u16::max_value(),
1193 htlc_minimum_msat: 0,
1194 htlc_maximum_msat: OptionalField::Absent,
1195 fee_base_msat: u32::max_value(),
1196 fee_proportional_millionths: u32::max_value(),
1197 excess_data: Vec::new()
1199 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1200 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1201 short_channel_id: 2,
1204 cltv_expiry_delta: 0,
1205 htlc_minimum_msat: 0,
1206 htlc_maximum_msat: OptionalField::Absent,
1208 fee_proportional_millionths: 0,
1209 excess_data: Vec::new()
1212 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
1214 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[7], ChannelFeatures::from_le_bytes(id_to_feature_flags(12)), 12);
1215 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1216 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1217 short_channel_id: 12,
1220 cltv_expiry_delta: u16::max_value(),
1221 htlc_minimum_msat: 0,
1222 htlc_maximum_msat: OptionalField::Absent,
1223 fee_base_msat: u32::max_value(),
1224 fee_proportional_millionths: u32::max_value(),
1225 excess_data: Vec::new()
1227 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1228 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1229 short_channel_id: 12,
1232 cltv_expiry_delta: 0,
1233 htlc_minimum_msat: 0,
1234 htlc_maximum_msat: OptionalField::Absent,
1236 fee_proportional_millionths: 0,
1237 excess_data: Vec::new()
1240 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], NodeFeatures::from_le_bytes(id_to_feature_flags(8)), 0);
1242 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
1243 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1244 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1245 short_channel_id: 3,
1248 cltv_expiry_delta: (3 << 8) | 1,
1249 htlc_minimum_msat: 0,
1250 htlc_maximum_msat: OptionalField::Absent,
1252 fee_proportional_millionths: 0,
1253 excess_data: Vec::new()
1255 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1256 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1257 short_channel_id: 3,
1260 cltv_expiry_delta: (3 << 8) | 2,
1261 htlc_minimum_msat: 0,
1262 htlc_maximum_msat: OptionalField::Absent,
1264 fee_proportional_millionths: 0,
1265 excess_data: Vec::new()
1268 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
1269 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1270 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1271 short_channel_id: 4,
1274 cltv_expiry_delta: (4 << 8) | 1,
1275 htlc_minimum_msat: 0,
1276 htlc_maximum_msat: OptionalField::Absent,
1278 fee_proportional_millionths: 1000000,
1279 excess_data: Vec::new()
1281 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1282 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1283 short_channel_id: 4,
1286 cltv_expiry_delta: (4 << 8) | 2,
1287 htlc_minimum_msat: 0,
1288 htlc_maximum_msat: OptionalField::Absent,
1290 fee_proportional_millionths: 0,
1291 excess_data: Vec::new()
1294 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(13)), 13);
1295 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1296 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1297 short_channel_id: 13,
1300 cltv_expiry_delta: (13 << 8) | 1,
1301 htlc_minimum_msat: 0,
1302 htlc_maximum_msat: OptionalField::Absent,
1304 fee_proportional_millionths: 2000000,
1305 excess_data: Vec::new()
1307 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1308 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1309 short_channel_id: 13,
1312 cltv_expiry_delta: (13 << 8) | 2,
1313 htlc_minimum_msat: 0,
1314 htlc_maximum_msat: OptionalField::Absent,
1316 fee_proportional_millionths: 0,
1317 excess_data: Vec::new()
1320 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
1322 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
1323 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1324 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1325 short_channel_id: 6,
1328 cltv_expiry_delta: (6 << 8) | 1,
1329 htlc_minimum_msat: 0,
1330 htlc_maximum_msat: OptionalField::Absent,
1332 fee_proportional_millionths: 0,
1333 excess_data: Vec::new()
1335 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1336 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1337 short_channel_id: 6,
1340 cltv_expiry_delta: (6 << 8) | 2,
1341 htlc_minimum_msat: 0,
1342 htlc_maximum_msat: OptionalField::Absent,
1344 fee_proportional_millionths: 0,
1345 excess_data: Vec::new(),
1348 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(11)), 11);
1349 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1350 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1351 short_channel_id: 11,
1354 cltv_expiry_delta: (11 << 8) | 1,
1355 htlc_minimum_msat: 0,
1356 htlc_maximum_msat: OptionalField::Absent,
1358 fee_proportional_millionths: 0,
1359 excess_data: Vec::new()
1361 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
1362 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1363 short_channel_id: 11,
1366 cltv_expiry_delta: (11 << 8) | 2,
1367 htlc_minimum_msat: 0,
1368 htlc_maximum_msat: OptionalField::Absent,
1370 fee_proportional_millionths: 0,
1371 excess_data: Vec::new()
1374 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(5)), 0);
1376 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
1378 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[5], ChannelFeatures::from_le_bytes(id_to_feature_flags(7)), 7);
1379 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1380 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1381 short_channel_id: 7,
1384 cltv_expiry_delta: (7 << 8) | 1,
1385 htlc_minimum_msat: 0,
1386 htlc_maximum_msat: OptionalField::Absent,
1388 fee_proportional_millionths: 1000000,
1389 excess_data: Vec::new()
1391 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[5], UnsignedChannelUpdate {
1392 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1393 short_channel_id: 7,
1396 cltv_expiry_delta: (7 << 8) | 2,
1397 htlc_minimum_msat: 0,
1398 htlc_maximum_msat: OptionalField::Absent,
1400 fee_proportional_millionths: 0,
1401 excess_data: Vec::new()
1404 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[5], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
1406 (secp_ctx, net_graph_msg_handler, chain_monitor, logger)
1410 fn simple_route_test() {
1411 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1412 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1414 // Simple route to 2 via 1
1416 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)) {
1417 assert_eq!(err, "Cannot send a payment of 0 msat");
1418 } else { panic!(); }
1420 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();
1421 assert_eq!(route.paths[0].len(), 2);
1423 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
1424 assert_eq!(route.paths[0][0].short_channel_id, 2);
1425 assert_eq!(route.paths[0][0].fee_msat, 100);
1426 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
1427 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
1428 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
1430 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1431 assert_eq!(route.paths[0][1].short_channel_id, 4);
1432 assert_eq!(route.paths[0][1].fee_msat, 100);
1433 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1434 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1435 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
1439 fn invalid_first_hop_test() {
1440 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1441 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1443 // Simple route to 2 via 1
1445 let our_chans = vec![channelmanager::ChannelDetails {
1446 channel_id: [0; 32],
1447 short_channel_id: Some(2),
1448 remote_network_id: our_id,
1449 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1450 channel_value_satoshis: 100000,
1452 outbound_capacity_msat: 100000,
1453 inbound_capacity_msat: 100000,
1457 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)) {
1458 assert_eq!(err, "First hop cannot have our_node_id as a destination.");
1459 } else { panic!(); }
1461 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();
1462 assert_eq!(route.paths[0].len(), 2);
1466 fn htlc_minimum_test() {
1467 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1468 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1470 // Simple route to 2 via 1
1472 // Disable other paths
1473 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1474 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1475 short_channel_id: 12,
1477 flags: 2, // to disable
1478 cltv_expiry_delta: 0,
1479 htlc_minimum_msat: 0,
1480 htlc_maximum_msat: OptionalField::Absent,
1482 fee_proportional_millionths: 0,
1483 excess_data: Vec::new()
1485 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1486 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1487 short_channel_id: 3,
1489 flags: 2, // to disable
1490 cltv_expiry_delta: 0,
1491 htlc_minimum_msat: 0,
1492 htlc_maximum_msat: OptionalField::Absent,
1494 fee_proportional_millionths: 0,
1495 excess_data: Vec::new()
1497 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1498 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1499 short_channel_id: 13,
1501 flags: 2, // to disable
1502 cltv_expiry_delta: 0,
1503 htlc_minimum_msat: 0,
1504 htlc_maximum_msat: OptionalField::Absent,
1506 fee_proportional_millionths: 0,
1507 excess_data: Vec::new()
1509 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1510 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1511 short_channel_id: 6,
1513 flags: 2, // to disable
1514 cltv_expiry_delta: 0,
1515 htlc_minimum_msat: 0,
1516 htlc_maximum_msat: OptionalField::Absent,
1518 fee_proportional_millionths: 0,
1519 excess_data: Vec::new()
1521 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1522 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1523 short_channel_id: 7,
1525 flags: 2, // to disable
1526 cltv_expiry_delta: 0,
1527 htlc_minimum_msat: 0,
1528 htlc_maximum_msat: OptionalField::Absent,
1530 fee_proportional_millionths: 0,
1531 excess_data: Vec::new()
1534 // Check against amount_to_transfer_over_msat.
1535 // We will be transferring 300_000_000 msat.
1536 // Set minimal HTLC of 200_000_000 msat.
1537 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1538 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1539 short_channel_id: 2,
1542 cltv_expiry_delta: 0,
1543 htlc_minimum_msat: 200_000_000,
1544 htlc_maximum_msat: OptionalField::Absent,
1546 fee_proportional_millionths: 0,
1547 excess_data: Vec::new()
1550 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
1552 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1553 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1554 short_channel_id: 4,
1557 cltv_expiry_delta: 0,
1558 htlc_minimum_msat: 0,
1559 htlc_maximum_msat: OptionalField::Present(199_999_999),
1561 fee_proportional_millionths: 0,
1562 excess_data: Vec::new()
1565 // Not possible to send 299_999_999: we first allocate 200_000_000 for the channel#12,
1566 // and then the amount_to_transfer_over_msat over channel#2 is less than our limit.
1567 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)) {
1568 assert_eq!(err, "Failed to find a path to the given destination");
1569 } else { panic!(); }
1571 // Lift the restriction on the first hop.
1572 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1573 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1574 short_channel_id: 2,
1577 cltv_expiry_delta: 0,
1578 htlc_minimum_msat: 0,
1579 htlc_maximum_msat: OptionalField::Absent,
1581 fee_proportional_millionths: 0,
1582 excess_data: Vec::new()
1585 // A payment above the minimum should pass
1586 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();
1587 assert_eq!(route.paths[0].len(), 2);
1591 fn htlc_minimum_overpay_test() {
1592 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1593 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1595 // A route to node#2 via two paths.
1596 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
1597 // Thus, they can't send 60 without overpaying.
1598 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1599 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1600 short_channel_id: 2,
1603 cltv_expiry_delta: 0,
1604 htlc_minimum_msat: 35_000,
1605 htlc_maximum_msat: OptionalField::Present(40_000),
1607 fee_proportional_millionths: 0,
1608 excess_data: Vec::new()
1610 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1611 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1612 short_channel_id: 12,
1615 cltv_expiry_delta: 0,
1616 htlc_minimum_msat: 35_000,
1617 htlc_maximum_msat: OptionalField::Present(40_000),
1619 fee_proportional_millionths: 0,
1620 excess_data: Vec::new()
1624 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1625 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1626 short_channel_id: 13,
1629 cltv_expiry_delta: 0,
1630 htlc_minimum_msat: 0,
1631 htlc_maximum_msat: OptionalField::Absent,
1633 fee_proportional_millionths: 0,
1634 excess_data: Vec::new()
1636 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1637 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1638 short_channel_id: 4,
1641 cltv_expiry_delta: 0,
1642 htlc_minimum_msat: 0,
1643 htlc_maximum_msat: OptionalField::Absent,
1645 fee_proportional_millionths: 0,
1646 excess_data: Vec::new()
1649 // Disable other paths
1650 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1651 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1652 short_channel_id: 1,
1654 flags: 2, // to disable
1655 cltv_expiry_delta: 0,
1656 htlc_minimum_msat: 0,
1657 htlc_maximum_msat: OptionalField::Absent,
1659 fee_proportional_millionths: 0,
1660 excess_data: Vec::new()
1663 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();
1664 // Overpay fees to hit htlc_minimum_msat.
1665 let overpaid_fees = route.paths[0][0].fee_msat + route.paths[1][0].fee_msat;
1666 // TODO: this could be better balanced to overpay 10k and not 15k.
1667 assert_eq!(overpaid_fees, 15_000);
1669 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
1670 // while taking even more fee to match htlc_minimum_msat.
1671 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1672 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1673 short_channel_id: 12,
1676 cltv_expiry_delta: 0,
1677 htlc_minimum_msat: 65_000,
1678 htlc_maximum_msat: OptionalField::Present(80_000),
1680 fee_proportional_millionths: 0,
1681 excess_data: Vec::new()
1683 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1684 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1685 short_channel_id: 2,
1688 cltv_expiry_delta: 0,
1689 htlc_minimum_msat: 0,
1690 htlc_maximum_msat: OptionalField::Absent,
1692 fee_proportional_millionths: 0,
1693 excess_data: Vec::new()
1695 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1696 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1697 short_channel_id: 4,
1700 cltv_expiry_delta: 0,
1701 htlc_minimum_msat: 0,
1702 htlc_maximum_msat: OptionalField::Absent,
1704 fee_proportional_millionths: 100_000,
1705 excess_data: Vec::new()
1708 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();
1709 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
1710 assert_eq!(route.paths.len(), 1);
1711 assert_eq!(route.paths[0][0].short_channel_id, 12);
1712 let fees = route.paths[0][0].fee_msat;
1713 assert_eq!(fees, 5_000);
1715 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();
1716 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
1717 // the other channel.
1718 assert_eq!(route.paths.len(), 1);
1719 assert_eq!(route.paths[0][0].short_channel_id, 2);
1720 let fees = route.paths[0][0].fee_msat;
1721 assert_eq!(fees, 5_000);
1725 fn disable_channels_test() {
1726 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1727 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1729 // // Disable channels 4 and 12 by flags=2
1730 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1731 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1732 short_channel_id: 4,
1734 flags: 2, // to disable
1735 cltv_expiry_delta: 0,
1736 htlc_minimum_msat: 0,
1737 htlc_maximum_msat: OptionalField::Absent,
1739 fee_proportional_millionths: 0,
1740 excess_data: Vec::new()
1742 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1743 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1744 short_channel_id: 12,
1746 flags: 2, // to disable
1747 cltv_expiry_delta: 0,
1748 htlc_minimum_msat: 0,
1749 htlc_maximum_msat: OptionalField::Absent,
1751 fee_proportional_millionths: 0,
1752 excess_data: Vec::new()
1755 // If all the channels require some features we don't understand, route should fail
1756 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)) {
1757 assert_eq!(err, "Failed to find a path to the given destination");
1758 } else { panic!(); }
1760 // If we specify a channel to node7, that overrides our local channel view and that gets used
1761 let our_chans = vec![channelmanager::ChannelDetails {
1762 channel_id: [0; 32],
1763 short_channel_id: Some(42),
1764 remote_network_id: nodes[7].clone(),
1765 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1766 channel_value_satoshis: 0,
1768 outbound_capacity_msat: 250_000_000,
1769 inbound_capacity_msat: 0,
1772 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();
1773 assert_eq!(route.paths[0].len(), 2);
1775 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
1776 assert_eq!(route.paths[0][0].short_channel_id, 42);
1777 assert_eq!(route.paths[0][0].fee_msat, 200);
1778 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
1779 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
1780 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
1782 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1783 assert_eq!(route.paths[0][1].short_channel_id, 13);
1784 assert_eq!(route.paths[0][1].fee_msat, 100);
1785 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1786 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1787 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
1791 fn disable_node_test() {
1792 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1793 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1795 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
1796 let mut unknown_features = NodeFeatures::known();
1797 unknown_features.set_required_unknown_bits();
1798 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
1799 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
1800 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
1802 // If all nodes require some features we don't understand, route should fail
1803 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)) {
1804 assert_eq!(err, "Failed to find a path to the given destination");
1805 } else { panic!(); }
1807 // If we specify a channel to node7, that overrides our local channel view and that gets used
1808 let our_chans = vec![channelmanager::ChannelDetails {
1809 channel_id: [0; 32],
1810 short_channel_id: Some(42),
1811 remote_network_id: nodes[7].clone(),
1812 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1813 channel_value_satoshis: 0,
1815 outbound_capacity_msat: 250_000_000,
1816 inbound_capacity_msat: 0,
1819 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();
1820 assert_eq!(route.paths[0].len(), 2);
1822 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
1823 assert_eq!(route.paths[0][0].short_channel_id, 42);
1824 assert_eq!(route.paths[0][0].fee_msat, 200);
1825 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
1826 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
1827 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
1829 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1830 assert_eq!(route.paths[0][1].short_channel_id, 13);
1831 assert_eq!(route.paths[0][1].fee_msat, 100);
1832 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1833 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1834 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
1836 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
1837 // naively) assume that the user checked the feature bits on the invoice, which override
1838 // the node_announcement.
1842 fn our_chans_test() {
1843 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1844 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1846 // Route to 1 via 2 and 3 because our channel to 1 is disabled
1847 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();
1848 assert_eq!(route.paths[0].len(), 3);
1850 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
1851 assert_eq!(route.paths[0][0].short_channel_id, 2);
1852 assert_eq!(route.paths[0][0].fee_msat, 200);
1853 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
1854 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
1855 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
1857 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1858 assert_eq!(route.paths[0][1].short_channel_id, 4);
1859 assert_eq!(route.paths[0][1].fee_msat, 100);
1860 assert_eq!(route.paths[0][1].cltv_expiry_delta, (3 << 8) | 2);
1861 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1862 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
1864 assert_eq!(route.paths[0][2].pubkey, nodes[0]);
1865 assert_eq!(route.paths[0][2].short_channel_id, 3);
1866 assert_eq!(route.paths[0][2].fee_msat, 100);
1867 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
1868 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(1));
1869 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(3));
1871 // If we specify a channel to node7, that overrides our local channel view and that gets used
1872 let our_chans = vec![channelmanager::ChannelDetails {
1873 channel_id: [0; 32],
1874 short_channel_id: Some(42),
1875 remote_network_id: nodes[7].clone(),
1876 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1877 channel_value_satoshis: 0,
1879 outbound_capacity_msat: 250_000_000,
1880 inbound_capacity_msat: 0,
1883 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();
1884 assert_eq!(route.paths[0].len(), 2);
1886 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
1887 assert_eq!(route.paths[0][0].short_channel_id, 42);
1888 assert_eq!(route.paths[0][0].fee_msat, 200);
1889 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
1890 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
1891 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
1893 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1894 assert_eq!(route.paths[0][1].short_channel_id, 13);
1895 assert_eq!(route.paths[0][1].fee_msat, 100);
1896 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1897 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1898 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
1901 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
1902 let zero_fees = RoutingFees {
1904 proportional_millionths: 0,
1907 src_node_id: nodes[3].clone(),
1908 short_channel_id: 8,
1910 cltv_expiry_delta: (8 << 8) | 1,
1911 htlc_minimum_msat: None,
1912 htlc_maximum_msat: None,
1914 src_node_id: nodes[4].clone(),
1915 short_channel_id: 9,
1918 proportional_millionths: 0,
1920 cltv_expiry_delta: (9 << 8) | 1,
1921 htlc_minimum_msat: None,
1922 htlc_maximum_msat: None,
1924 src_node_id: nodes[5].clone(),
1925 short_channel_id: 10,
1927 cltv_expiry_delta: (10 << 8) | 1,
1928 htlc_minimum_msat: None,
1929 htlc_maximum_msat: None,
1934 fn last_hops_test() {
1935 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1936 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1938 // Simple test across 2, 3, 5, and 4 via a last_hop channel
1940 // First check that lst hop can't have its source as the payee.
1941 let invalid_last_hop = RouteHint {
1942 src_node_id: nodes[6],
1943 short_channel_id: 8,
1946 proportional_millionths: 0,
1948 cltv_expiry_delta: (8 << 8) | 1,
1949 htlc_minimum_msat: None,
1950 htlc_maximum_msat: None,
1953 let mut invalid_last_hops = last_hops(&nodes);
1954 invalid_last_hops.push(invalid_last_hop);
1956 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)) {
1957 assert_eq!(err, "Last hop cannot have a payee as a source.");
1958 } else { panic!(); }
1961 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();
1962 assert_eq!(route.paths[0].len(), 5);
1964 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
1965 assert_eq!(route.paths[0][0].short_channel_id, 2);
1966 assert_eq!(route.paths[0][0].fee_msat, 100);
1967 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
1968 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
1969 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
1971 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1972 assert_eq!(route.paths[0][1].short_channel_id, 4);
1973 assert_eq!(route.paths[0][1].fee_msat, 0);
1974 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
1975 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1976 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
1978 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
1979 assert_eq!(route.paths[0][2].short_channel_id, 6);
1980 assert_eq!(route.paths[0][2].fee_msat, 0);
1981 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
1982 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
1983 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
1985 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
1986 assert_eq!(route.paths[0][3].short_channel_id, 11);
1987 assert_eq!(route.paths[0][3].fee_msat, 0);
1988 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
1989 // If we have a peer in the node map, we'll use their features here since we don't have
1990 // a way of figuring out their features from the invoice:
1991 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
1992 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
1994 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
1995 assert_eq!(route.paths[0][4].short_channel_id, 8);
1996 assert_eq!(route.paths[0][4].fee_msat, 100);
1997 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
1998 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
1999 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2003 fn our_chans_last_hop_connect_test() {
2004 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2005 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2007 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
2008 let our_chans = vec![channelmanager::ChannelDetails {
2009 channel_id: [0; 32],
2010 short_channel_id: Some(42),
2011 remote_network_id: nodes[3].clone(),
2012 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
2013 channel_value_satoshis: 0,
2015 outbound_capacity_msat: 250_000_000,
2016 inbound_capacity_msat: 0,
2019 let mut last_hops = last_hops(&nodes);
2020 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();
2021 assert_eq!(route.paths[0].len(), 2);
2023 assert_eq!(route.paths[0][0].pubkey, nodes[3]);
2024 assert_eq!(route.paths[0][0].short_channel_id, 42);
2025 assert_eq!(route.paths[0][0].fee_msat, 0);
2026 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
2027 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2028 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2030 assert_eq!(route.paths[0][1].pubkey, nodes[6]);
2031 assert_eq!(route.paths[0][1].short_channel_id, 8);
2032 assert_eq!(route.paths[0][1].fee_msat, 100);
2033 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2034 assert_eq!(route.paths[0][1].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2035 assert_eq!(route.paths[0][1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2037 last_hops[0].fees.base_msat = 1000;
2039 // Revert to via 6 as the fee on 8 goes up
2040 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();
2041 assert_eq!(route.paths[0].len(), 4);
2043 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2044 assert_eq!(route.paths[0][0].short_channel_id, 2);
2045 assert_eq!(route.paths[0][0].fee_msat, 200); // fee increased as its % of value transferred across node
2046 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2047 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2048 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2050 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2051 assert_eq!(route.paths[0][1].short_channel_id, 4);
2052 assert_eq!(route.paths[0][1].fee_msat, 100);
2053 assert_eq!(route.paths[0][1].cltv_expiry_delta, (7 << 8) | 1);
2054 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2055 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2057 assert_eq!(route.paths[0][2].pubkey, nodes[5]);
2058 assert_eq!(route.paths[0][2].short_channel_id, 7);
2059 assert_eq!(route.paths[0][2].fee_msat, 0);
2060 assert_eq!(route.paths[0][2].cltv_expiry_delta, (10 << 8) | 1);
2061 // If we have a peer in the node map, we'll use their features here since we don't have
2062 // a way of figuring out their features from the invoice:
2063 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
2064 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(7));
2066 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2067 assert_eq!(route.paths[0][3].short_channel_id, 10);
2068 assert_eq!(route.paths[0][3].fee_msat, 100);
2069 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2070 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2071 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2073 // ...but still use 8 for larger payments as 6 has a variable feerate
2074 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();
2075 assert_eq!(route.paths[0].len(), 5);
2077 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2078 assert_eq!(route.paths[0][0].short_channel_id, 2);
2079 assert_eq!(route.paths[0][0].fee_msat, 3000);
2080 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2081 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2082 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2084 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2085 assert_eq!(route.paths[0][1].short_channel_id, 4);
2086 assert_eq!(route.paths[0][1].fee_msat, 0);
2087 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2088 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2089 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2091 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2092 assert_eq!(route.paths[0][2].short_channel_id, 6);
2093 assert_eq!(route.paths[0][2].fee_msat, 0);
2094 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2095 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2096 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2098 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2099 assert_eq!(route.paths[0][3].short_channel_id, 11);
2100 assert_eq!(route.paths[0][3].fee_msat, 1000);
2101 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2102 // If we have a peer in the node map, we'll use their features here since we don't have
2103 // a way of figuring out their features from the invoice:
2104 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2105 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2107 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2108 assert_eq!(route.paths[0][4].short_channel_id, 8);
2109 assert_eq!(route.paths[0][4].fee_msat, 2000);
2110 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2111 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2112 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2116 fn unannounced_path_test() {
2117 // We should be able to send a payment to a destination without any help of a routing graph
2118 // if we have a channel with a common counterparty that appears in the first and last hop
2120 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
2121 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
2122 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
2124 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
2125 let last_hops = vec![RouteHint {
2126 src_node_id: middle_node_id,
2127 short_channel_id: 8,
2130 proportional_millionths: 0,
2132 cltv_expiry_delta: (8 << 8) | 1,
2133 htlc_minimum_msat: None,
2134 htlc_maximum_msat: None,
2136 let our_chans = vec![channelmanager::ChannelDetails {
2137 channel_id: [0; 32],
2138 short_channel_id: Some(42),
2139 remote_network_id: middle_node_id,
2140 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
2141 channel_value_satoshis: 100000,
2143 outbound_capacity_msat: 100000,
2144 inbound_capacity_msat: 100000,
2147 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();
2149 assert_eq!(route.paths[0].len(), 2);
2151 assert_eq!(route.paths[0][0].pubkey, middle_node_id);
2152 assert_eq!(route.paths[0][0].short_channel_id, 42);
2153 assert_eq!(route.paths[0][0].fee_msat, 1000);
2154 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
2155 assert_eq!(route.paths[0][0].node_features.le_flags(), &[0b11]);
2156 assert_eq!(route.paths[0][0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
2158 assert_eq!(route.paths[0][1].pubkey, target_node_id);
2159 assert_eq!(route.paths[0][1].short_channel_id, 8);
2160 assert_eq!(route.paths[0][1].fee_msat, 100);
2161 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2162 assert_eq!(route.paths[0][1].node_features.le_flags(), &[0; 0]); // We dont pass flags in from invoices yet
2163 assert_eq!(route.paths[0][1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
2167 fn available_amount_while_routing_test() {
2168 // Tests whether we choose the correct available channel amount while routing.
2170 let (secp_ctx, mut net_graph_msg_handler, chain_monitor, logger) = build_graph();
2171 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2173 // We will use a simple single-path route from
2174 // our node to node2 via node0: channels {1, 3}.
2176 // First disable all other paths.
2177 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2178 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2179 short_channel_id: 2,
2182 cltv_expiry_delta: 0,
2183 htlc_minimum_msat: 0,
2184 htlc_maximum_msat: OptionalField::Present(100_000),
2186 fee_proportional_millionths: 0,
2187 excess_data: Vec::new()
2189 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2190 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2191 short_channel_id: 12,
2194 cltv_expiry_delta: 0,
2195 htlc_minimum_msat: 0,
2196 htlc_maximum_msat: OptionalField::Present(100_000),
2198 fee_proportional_millionths: 0,
2199 excess_data: Vec::new()
2202 // Make the first channel (#1) very permissive,
2203 // and we will be testing all limits on the second channel.
2204 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2205 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2206 short_channel_id: 1,
2209 cltv_expiry_delta: 0,
2210 htlc_minimum_msat: 0,
2211 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2213 fee_proportional_millionths: 0,
2214 excess_data: Vec::new()
2217 // First, let's see if routing works if we have absolutely no idea about the available amount.
2218 // In this case, it should be set to 250_000 sats.
2219 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2220 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2221 short_channel_id: 3,
2224 cltv_expiry_delta: 0,
2225 htlc_minimum_msat: 0,
2226 htlc_maximum_msat: OptionalField::Absent,
2228 fee_proportional_millionths: 0,
2229 excess_data: Vec::new()
2233 // Attempt to route more than available results in a failure.
2234 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)) {
2235 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2236 } else { panic!(); }
2240 // Now, attempt to route an exact amount we have should be fine.
2241 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();
2242 assert_eq!(route.paths.len(), 1);
2243 let path = route.paths.last().unwrap();
2244 assert_eq!(path.len(), 2);
2245 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2246 assert_eq!(path.last().unwrap().fee_msat, 250_000_000);
2249 // Check that setting outbound_capacity_msat in first_hops limits the channels.
2250 // Disable channel #1 and use another first hop.
2251 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2252 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2253 short_channel_id: 1,
2256 cltv_expiry_delta: 0,
2257 htlc_minimum_msat: 0,
2258 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2260 fee_proportional_millionths: 0,
2261 excess_data: Vec::new()
2264 // Now, limit the first_hop by the outbound_capacity_msat of 200_000 sats.
2265 let our_chans = vec![channelmanager::ChannelDetails {
2266 channel_id: [0; 32],
2267 short_channel_id: Some(42),
2268 remote_network_id: nodes[0].clone(),
2269 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
2270 channel_value_satoshis: 0,
2272 outbound_capacity_msat: 200_000_000,
2273 inbound_capacity_msat: 0,
2278 // Attempt to route more than available results in a failure.
2279 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)) {
2280 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2281 } else { panic!(); }
2285 // Now, attempt to route an exact amount we have should be fine.
2286 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();
2287 assert_eq!(route.paths.len(), 1);
2288 let path = route.paths.last().unwrap();
2289 assert_eq!(path.len(), 2);
2290 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2291 assert_eq!(path.last().unwrap().fee_msat, 200_000_000);
2294 // Enable channel #1 back.
2295 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2296 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2297 short_channel_id: 1,
2300 cltv_expiry_delta: 0,
2301 htlc_minimum_msat: 0,
2302 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2304 fee_proportional_millionths: 0,
2305 excess_data: Vec::new()
2309 // Now let's see if routing works if we know only htlc_maximum_msat.
2310 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2311 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2312 short_channel_id: 3,
2315 cltv_expiry_delta: 0,
2316 htlc_minimum_msat: 0,
2317 htlc_maximum_msat: OptionalField::Present(15_000),
2319 fee_proportional_millionths: 0,
2320 excess_data: Vec::new()
2324 // Attempt to route more than available results in a failure.
2325 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)) {
2326 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2327 } else { panic!(); }
2331 // Now, attempt to route an exact amount we have should be fine.
2332 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();
2333 assert_eq!(route.paths.len(), 1);
2334 let path = route.paths.last().unwrap();
2335 assert_eq!(path.len(), 2);
2336 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2337 assert_eq!(path.last().unwrap().fee_msat, 15_000);
2340 // Now let's see if routing works if we know only capacity from the UTXO.
2342 // We can't change UTXO capacity on the fly, so we'll disable
2343 // the existing channel and add another one with the capacity we need.
2344 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2345 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2346 short_channel_id: 3,
2349 cltv_expiry_delta: 0,
2350 htlc_minimum_msat: 0,
2351 htlc_maximum_msat: OptionalField::Absent,
2353 fee_proportional_millionths: 0,
2354 excess_data: Vec::new()
2357 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
2358 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
2359 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
2360 .push_opcode(opcodes::all::OP_PUSHNUM_2)
2361 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
2363 *chain_monitor.utxo_ret.lock().unwrap() = Ok(TxOut { value: 15, script_pubkey: good_script.clone() });
2364 net_graph_msg_handler.add_chain_access(Some(chain_monitor));
2366 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
2367 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2368 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2369 short_channel_id: 333,
2372 cltv_expiry_delta: (3 << 8) | 1,
2373 htlc_minimum_msat: 0,
2374 htlc_maximum_msat: OptionalField::Absent,
2376 fee_proportional_millionths: 0,
2377 excess_data: Vec::new()
2379 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2380 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2381 short_channel_id: 333,
2384 cltv_expiry_delta: (3 << 8) | 2,
2385 htlc_minimum_msat: 0,
2386 htlc_maximum_msat: OptionalField::Absent,
2388 fee_proportional_millionths: 0,
2389 excess_data: Vec::new()
2393 // Attempt to route more than available results in a failure.
2394 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)) {
2395 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2396 } else { panic!(); }
2400 // Now, attempt to route an exact amount we have should be fine.
2401 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();
2402 assert_eq!(route.paths.len(), 1);
2403 let path = route.paths.last().unwrap();
2404 assert_eq!(path.len(), 2);
2405 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2406 assert_eq!(path.last().unwrap().fee_msat, 15_000);
2409 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
2410 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2411 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2412 short_channel_id: 333,
2415 cltv_expiry_delta: 0,
2416 htlc_minimum_msat: 0,
2417 htlc_maximum_msat: OptionalField::Present(10_000),
2419 fee_proportional_millionths: 0,
2420 excess_data: Vec::new()
2424 // Attempt to route more than available results in a failure.
2425 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)) {
2426 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2427 } else { panic!(); }
2431 // Now, attempt to route an exact amount we have should be fine.
2432 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();
2433 assert_eq!(route.paths.len(), 1);
2434 let path = route.paths.last().unwrap();
2435 assert_eq!(path.len(), 2);
2436 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2437 assert_eq!(path.last().unwrap().fee_msat, 10_000);
2442 fn available_liquidity_last_hop_test() {
2443 // Check that available liquidity properly limits the path even when only
2444 // one of the latter hops is limited.
2445 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2446 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2448 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
2449 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
2450 // Total capacity: 50 sats.
2452 // Disable other potential paths.
2453 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2454 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2455 short_channel_id: 2,
2458 cltv_expiry_delta: 0,
2459 htlc_minimum_msat: 0,
2460 htlc_maximum_msat: OptionalField::Present(100_000),
2462 fee_proportional_millionths: 0,
2463 excess_data: Vec::new()
2465 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2466 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2467 short_channel_id: 7,
2470 cltv_expiry_delta: 0,
2471 htlc_minimum_msat: 0,
2472 htlc_maximum_msat: OptionalField::Present(100_000),
2474 fee_proportional_millionths: 0,
2475 excess_data: Vec::new()
2480 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2481 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2482 short_channel_id: 12,
2485 cltv_expiry_delta: 0,
2486 htlc_minimum_msat: 0,
2487 htlc_maximum_msat: OptionalField::Present(100_000),
2489 fee_proportional_millionths: 0,
2490 excess_data: Vec::new()
2492 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2493 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2494 short_channel_id: 13,
2497 cltv_expiry_delta: 0,
2498 htlc_minimum_msat: 0,
2499 htlc_maximum_msat: OptionalField::Present(100_000),
2501 fee_proportional_millionths: 0,
2502 excess_data: Vec::new()
2505 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2506 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2507 short_channel_id: 6,
2510 cltv_expiry_delta: 0,
2511 htlc_minimum_msat: 0,
2512 htlc_maximum_msat: OptionalField::Present(50_000),
2514 fee_proportional_millionths: 0,
2515 excess_data: Vec::new()
2517 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
2518 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2519 short_channel_id: 11,
2522 cltv_expiry_delta: 0,
2523 htlc_minimum_msat: 0,
2524 htlc_maximum_msat: OptionalField::Present(100_000),
2526 fee_proportional_millionths: 0,
2527 excess_data: Vec::new()
2530 // Attempt to route more than available results in a failure.
2531 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)) {
2532 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2533 } else { panic!(); }
2537 // Now, attempt to route 49 sats (just a bit below the capacity).
2538 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();
2539 assert_eq!(route.paths.len(), 1);
2540 let mut total_amount_paid_msat = 0;
2541 for path in &route.paths {
2542 assert_eq!(path.len(), 4);
2543 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
2544 total_amount_paid_msat += path.last().unwrap().fee_msat;
2546 assert_eq!(total_amount_paid_msat, 49_000);
2550 // Attempt to route an exact amount is also fine
2551 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();
2552 assert_eq!(route.paths.len(), 1);
2553 let mut total_amount_paid_msat = 0;
2554 for path in &route.paths {
2555 assert_eq!(path.len(), 4);
2556 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
2557 total_amount_paid_msat += path.last().unwrap().fee_msat;
2559 assert_eq!(total_amount_paid_msat, 50_000);
2564 fn ignore_fee_first_hop_test() {
2565 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2566 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2568 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
2569 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2570 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2571 short_channel_id: 1,
2574 cltv_expiry_delta: 0,
2575 htlc_minimum_msat: 0,
2576 htlc_maximum_msat: OptionalField::Present(100_000),
2577 fee_base_msat: 1_000_000,
2578 fee_proportional_millionths: 0,
2579 excess_data: Vec::new()
2581 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2582 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2583 short_channel_id: 3,
2586 cltv_expiry_delta: 0,
2587 htlc_minimum_msat: 0,
2588 htlc_maximum_msat: OptionalField::Present(50_000),
2590 fee_proportional_millionths: 0,
2591 excess_data: Vec::new()
2595 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();
2596 assert_eq!(route.paths.len(), 1);
2597 let mut total_amount_paid_msat = 0;
2598 for path in &route.paths {
2599 assert_eq!(path.len(), 2);
2600 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2601 total_amount_paid_msat += path.last().unwrap().fee_msat;
2603 assert_eq!(total_amount_paid_msat, 50_000);
2608 fn simple_mpp_route_test() {
2609 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2610 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2612 // We need a route consisting of 3 paths:
2613 // From our node to node2 via node0, node7, node1 (three paths one hop each).
2614 // To achieve this, the amount being transferred should be around
2615 // the total capacity of these 3 paths.
2617 // First, we set limits on these (previously unlimited) channels.
2618 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
2620 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
2621 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2622 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2623 short_channel_id: 1,
2626 cltv_expiry_delta: 0,
2627 htlc_minimum_msat: 0,
2628 htlc_maximum_msat: OptionalField::Present(100_000),
2630 fee_proportional_millionths: 0,
2631 excess_data: Vec::new()
2633 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2634 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2635 short_channel_id: 3,
2638 cltv_expiry_delta: 0,
2639 htlc_minimum_msat: 0,
2640 htlc_maximum_msat: OptionalField::Present(50_000),
2642 fee_proportional_millionths: 0,
2643 excess_data: Vec::new()
2646 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
2647 // (total limit 60).
2648 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2649 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2650 short_channel_id: 12,
2653 cltv_expiry_delta: 0,
2654 htlc_minimum_msat: 0,
2655 htlc_maximum_msat: OptionalField::Present(60_000),
2657 fee_proportional_millionths: 0,
2658 excess_data: Vec::new()
2660 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2661 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2662 short_channel_id: 13,
2665 cltv_expiry_delta: 0,
2666 htlc_minimum_msat: 0,
2667 htlc_maximum_msat: OptionalField::Present(60_000),
2669 fee_proportional_millionths: 0,
2670 excess_data: Vec::new()
2673 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
2674 // (total capacity 180 sats).
2675 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2676 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2677 short_channel_id: 2,
2680 cltv_expiry_delta: 0,
2681 htlc_minimum_msat: 0,
2682 htlc_maximum_msat: OptionalField::Present(200_000),
2684 fee_proportional_millionths: 0,
2685 excess_data: Vec::new()
2687 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2688 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2689 short_channel_id: 4,
2692 cltv_expiry_delta: 0,
2693 htlc_minimum_msat: 0,
2694 htlc_maximum_msat: OptionalField::Present(180_000),
2696 fee_proportional_millionths: 0,
2697 excess_data: Vec::new()
2701 // Attempt to route more than available results in a failure.
2702 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)) {
2703 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2704 } else { panic!(); }
2708 // Now, attempt to route 250 sats (just a bit below the capacity).
2709 // Our algorithm should provide us with these 3 paths.
2710 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();
2711 assert_eq!(route.paths.len(), 3);
2712 let mut total_amount_paid_msat = 0;
2713 for path in &route.paths {
2714 assert_eq!(path.len(), 2);
2715 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2716 total_amount_paid_msat += path.last().unwrap().fee_msat;
2718 assert_eq!(total_amount_paid_msat, 250_000);
2722 // Attempt to route an exact amount is also fine
2723 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();
2724 assert_eq!(route.paths.len(), 3);
2725 let mut total_amount_paid_msat = 0;
2726 for path in &route.paths {
2727 assert_eq!(path.len(), 2);
2728 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2729 total_amount_paid_msat += path.last().unwrap().fee_msat;
2731 assert_eq!(total_amount_paid_msat, 290_000);
2736 fn long_mpp_route_test() {
2737 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2738 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2740 // We need a route consisting of 3 paths:
2741 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
2742 // Note that these paths overlap (channels 5, 12, 13).
2743 // We will route 300 sats.
2744 // Each path will have 100 sats capacity, those channels which
2745 // are used twice will have 200 sats capacity.
2747 // Disable other potential paths.
2748 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2749 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2750 short_channel_id: 2,
2753 cltv_expiry_delta: 0,
2754 htlc_minimum_msat: 0,
2755 htlc_maximum_msat: OptionalField::Present(100_000),
2757 fee_proportional_millionths: 0,
2758 excess_data: Vec::new()
2760 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2761 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2762 short_channel_id: 7,
2765 cltv_expiry_delta: 0,
2766 htlc_minimum_msat: 0,
2767 htlc_maximum_msat: OptionalField::Present(100_000),
2769 fee_proportional_millionths: 0,
2770 excess_data: Vec::new()
2773 // Path via {node0, node2} is channels {1, 3, 5}.
2774 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2775 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2776 short_channel_id: 1,
2779 cltv_expiry_delta: 0,
2780 htlc_minimum_msat: 0,
2781 htlc_maximum_msat: OptionalField::Present(100_000),
2783 fee_proportional_millionths: 0,
2784 excess_data: Vec::new()
2786 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2787 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2788 short_channel_id: 3,
2791 cltv_expiry_delta: 0,
2792 htlc_minimum_msat: 0,
2793 htlc_maximum_msat: OptionalField::Present(100_000),
2795 fee_proportional_millionths: 0,
2796 excess_data: Vec::new()
2799 // Capacity of 200 sats because this channel will be used by 3rd path as well.
2800 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
2801 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2802 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2803 short_channel_id: 5,
2806 cltv_expiry_delta: 0,
2807 htlc_minimum_msat: 0,
2808 htlc_maximum_msat: OptionalField::Present(200_000),
2810 fee_proportional_millionths: 0,
2811 excess_data: Vec::new()
2814 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
2815 // Add 100 sats to the capacities of {12, 13}, because these channels
2816 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
2817 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2818 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2819 short_channel_id: 12,
2822 cltv_expiry_delta: 0,
2823 htlc_minimum_msat: 0,
2824 htlc_maximum_msat: OptionalField::Present(200_000),
2826 fee_proportional_millionths: 0,
2827 excess_data: Vec::new()
2829 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2830 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2831 short_channel_id: 13,
2834 cltv_expiry_delta: 0,
2835 htlc_minimum_msat: 0,
2836 htlc_maximum_msat: OptionalField::Present(200_000),
2838 fee_proportional_millionths: 0,
2839 excess_data: Vec::new()
2842 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2843 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2844 short_channel_id: 6,
2847 cltv_expiry_delta: 0,
2848 htlc_minimum_msat: 0,
2849 htlc_maximum_msat: OptionalField::Present(100_000),
2851 fee_proportional_millionths: 0,
2852 excess_data: Vec::new()
2854 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
2855 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2856 short_channel_id: 11,
2859 cltv_expiry_delta: 0,
2860 htlc_minimum_msat: 0,
2861 htlc_maximum_msat: OptionalField::Present(100_000),
2863 fee_proportional_millionths: 0,
2864 excess_data: Vec::new()
2867 // Path via {node7, node2} is channels {12, 13, 5}.
2868 // We already limited them to 200 sats (they are used twice for 100 sats).
2869 // Nothing to do here.
2872 // Attempt to route more than available results in a failure.
2873 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)) {
2874 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2875 } else { panic!(); }
2879 // Now, attempt to route 300 sats (exact amount we can route).
2880 // Our algorithm should provide us with these 3 paths, 100 sats each.
2881 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();
2882 assert_eq!(route.paths.len(), 3);
2884 let mut total_amount_paid_msat = 0;
2885 for path in &route.paths {
2886 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
2887 total_amount_paid_msat += path.last().unwrap().fee_msat;
2889 assert_eq!(total_amount_paid_msat, 300_000);
2895 fn mpp_cheaper_route_test() {
2896 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2897 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2899 // This test checks that if we have two cheaper paths and one more expensive path,
2900 // so that liquidity-wise any 2 of 3 combination is sufficient,
2901 // two cheaper paths will be taken.
2902 // These paths have equal available liquidity.
2904 // We need a combination of 3 paths:
2905 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
2906 // Note that these paths overlap (channels 5, 12, 13).
2907 // Each path will have 100 sats capacity, those channels which
2908 // are used twice will have 200 sats capacity.
2910 // Disable other potential paths.
2911 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2912 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2913 short_channel_id: 2,
2916 cltv_expiry_delta: 0,
2917 htlc_minimum_msat: 0,
2918 htlc_maximum_msat: OptionalField::Present(100_000),
2920 fee_proportional_millionths: 0,
2921 excess_data: Vec::new()
2923 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2924 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2925 short_channel_id: 7,
2928 cltv_expiry_delta: 0,
2929 htlc_minimum_msat: 0,
2930 htlc_maximum_msat: OptionalField::Present(100_000),
2932 fee_proportional_millionths: 0,
2933 excess_data: Vec::new()
2936 // Path via {node0, node2} is channels {1, 3, 5}.
2937 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2938 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2939 short_channel_id: 1,
2942 cltv_expiry_delta: 0,
2943 htlc_minimum_msat: 0,
2944 htlc_maximum_msat: OptionalField::Present(100_000),
2946 fee_proportional_millionths: 0,
2947 excess_data: Vec::new()
2949 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2950 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2951 short_channel_id: 3,
2954 cltv_expiry_delta: 0,
2955 htlc_minimum_msat: 0,
2956 htlc_maximum_msat: OptionalField::Present(100_000),
2958 fee_proportional_millionths: 0,
2959 excess_data: Vec::new()
2962 // Capacity of 200 sats because this channel will be used by 3rd path as well.
2963 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
2964 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2965 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2966 short_channel_id: 5,
2969 cltv_expiry_delta: 0,
2970 htlc_minimum_msat: 0,
2971 htlc_maximum_msat: OptionalField::Present(200_000),
2973 fee_proportional_millionths: 0,
2974 excess_data: Vec::new()
2977 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
2978 // Add 100 sats to the capacities of {12, 13}, because these channels
2979 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
2980 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2981 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2982 short_channel_id: 12,
2985 cltv_expiry_delta: 0,
2986 htlc_minimum_msat: 0,
2987 htlc_maximum_msat: OptionalField::Present(200_000),
2989 fee_proportional_millionths: 0,
2990 excess_data: Vec::new()
2992 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2993 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2994 short_channel_id: 13,
2997 cltv_expiry_delta: 0,
2998 htlc_minimum_msat: 0,
2999 htlc_maximum_msat: OptionalField::Present(200_000),
3001 fee_proportional_millionths: 0,
3002 excess_data: Vec::new()
3005 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3006 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3007 short_channel_id: 6,
3010 cltv_expiry_delta: 0,
3011 htlc_minimum_msat: 0,
3012 htlc_maximum_msat: OptionalField::Present(100_000),
3013 fee_base_msat: 1_000,
3014 fee_proportional_millionths: 0,
3015 excess_data: Vec::new()
3017 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3018 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3019 short_channel_id: 11,
3022 cltv_expiry_delta: 0,
3023 htlc_minimum_msat: 0,
3024 htlc_maximum_msat: OptionalField::Present(100_000),
3026 fee_proportional_millionths: 0,
3027 excess_data: Vec::new()
3030 // Path via {node7, node2} is channels {12, 13, 5}.
3031 // We already limited them to 200 sats (they are used twice for 100 sats).
3032 // Nothing to do here.
3035 // Now, attempt to route 180 sats.
3036 // Our algorithm should provide us with these 2 paths.
3037 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();
3038 assert_eq!(route.paths.len(), 2);
3040 let mut total_value_transferred_msat = 0;
3041 let mut total_paid_msat = 0;
3042 for path in &route.paths {
3043 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3044 total_value_transferred_msat += path.last().unwrap().fee_msat;
3046 total_paid_msat += hop.fee_msat;
3049 // If we paid fee, this would be higher.
3050 assert_eq!(total_value_transferred_msat, 180_000);
3051 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
3052 assert_eq!(total_fees_paid, 0);
3057 fn fees_on_mpp_route_test() {
3058 // This test makes sure that MPP algorithm properly takes into account
3059 // fees charged on the channels, by making the fees impactful:
3060 // if the fee is not properly accounted for, the behavior is different.
3061 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3062 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3064 // We need a route consisting of 2 paths:
3065 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
3066 // We will route 200 sats, Each path will have 100 sats capacity.
3068 // This test is not particularly stable: e.g.,
3069 // there's a way to route via {node0, node2, node4}.
3070 // It works while pathfinding is deterministic, but can be broken otherwise.
3071 // It's fine to ignore this concern for now.
3073 // Disable other potential paths.
3074 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3075 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3076 short_channel_id: 2,
3079 cltv_expiry_delta: 0,
3080 htlc_minimum_msat: 0,
3081 htlc_maximum_msat: OptionalField::Present(100_000),
3083 fee_proportional_millionths: 0,
3084 excess_data: Vec::new()
3087 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3088 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3089 short_channel_id: 7,
3092 cltv_expiry_delta: 0,
3093 htlc_minimum_msat: 0,
3094 htlc_maximum_msat: OptionalField::Present(100_000),
3096 fee_proportional_millionths: 0,
3097 excess_data: Vec::new()
3100 // Path via {node0, node2} is channels {1, 3, 5}.
3101 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3102 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3103 short_channel_id: 1,
3106 cltv_expiry_delta: 0,
3107 htlc_minimum_msat: 0,
3108 htlc_maximum_msat: OptionalField::Present(100_000),
3110 fee_proportional_millionths: 0,
3111 excess_data: Vec::new()
3113 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3114 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3115 short_channel_id: 3,
3118 cltv_expiry_delta: 0,
3119 htlc_minimum_msat: 0,
3120 htlc_maximum_msat: OptionalField::Present(100_000),
3122 fee_proportional_millionths: 0,
3123 excess_data: Vec::new()
3126 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3127 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3128 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3129 short_channel_id: 5,
3132 cltv_expiry_delta: 0,
3133 htlc_minimum_msat: 0,
3134 htlc_maximum_msat: OptionalField::Present(100_000),
3136 fee_proportional_millionths: 0,
3137 excess_data: Vec::new()
3140 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3141 // All channels should be 100 sats capacity. But for the fee experiment,
3142 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
3143 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
3144 // 100 sats (and pay 150 sats in fees for the use of channel 6),
3145 // so no matter how large are other channels,
3146 // the whole path will be limited by 100 sats with just these 2 conditions:
3147 // - channel 12 capacity is 250 sats
3148 // - fee for channel 6 is 150 sats
3149 // Let's test this by enforcing these 2 conditions and removing other limits.
3150 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3151 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3152 short_channel_id: 12,
3155 cltv_expiry_delta: 0,
3156 htlc_minimum_msat: 0,
3157 htlc_maximum_msat: OptionalField::Present(250_000),
3159 fee_proportional_millionths: 0,
3160 excess_data: Vec::new()
3162 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3163 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3164 short_channel_id: 13,
3167 cltv_expiry_delta: 0,
3168 htlc_minimum_msat: 0,
3169 htlc_maximum_msat: OptionalField::Absent,
3171 fee_proportional_millionths: 0,
3172 excess_data: Vec::new()
3175 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3176 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3177 short_channel_id: 6,
3180 cltv_expiry_delta: 0,
3181 htlc_minimum_msat: 0,
3182 htlc_maximum_msat: OptionalField::Absent,
3183 fee_base_msat: 150_000,
3184 fee_proportional_millionths: 0,
3185 excess_data: Vec::new()
3187 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3188 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3189 short_channel_id: 11,
3192 cltv_expiry_delta: 0,
3193 htlc_minimum_msat: 0,
3194 htlc_maximum_msat: OptionalField::Absent,
3196 fee_proportional_millionths: 0,
3197 excess_data: Vec::new()
3201 // Attempt to route more than available results in a failure.
3202 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)) {
3203 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3204 } else { panic!(); }
3208 // Now, attempt to route 200 sats (exact amount we can route).
3209 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();
3210 assert_eq!(route.paths.len(), 2);
3212 let mut total_amount_paid_msat = 0;
3213 for path in &route.paths {
3214 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3215 total_amount_paid_msat += path.last().unwrap().fee_msat;
3217 assert_eq!(total_amount_paid_msat, 200_000);
3223 fn drop_lowest_channel_mpp_route_test() {
3224 // This test checks that low-capacity channel is dropped when after
3225 // path finding we realize that we found more capacity than we need.
3226 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3227 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3229 // We need a route consisting of 3 paths:
3230 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3232 // The first and the second paths should be sufficient, but the third should be
3233 // cheaper, so that we select it but drop later.
3235 // First, we set limits on these (previously unlimited) channels.
3236 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
3238 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
3239 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3240 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3241 short_channel_id: 1,
3244 cltv_expiry_delta: 0,
3245 htlc_minimum_msat: 0,
3246 htlc_maximum_msat: OptionalField::Present(100_000),
3248 fee_proportional_millionths: 0,
3249 excess_data: Vec::new()
3251 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3252 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3253 short_channel_id: 3,
3256 cltv_expiry_delta: 0,
3257 htlc_minimum_msat: 0,
3258 htlc_maximum_msat: OptionalField::Present(50_000),
3260 fee_proportional_millionths: 0,
3261 excess_data: Vec::new()
3264 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
3265 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3266 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3267 short_channel_id: 12,
3270 cltv_expiry_delta: 0,
3271 htlc_minimum_msat: 0,
3272 htlc_maximum_msat: OptionalField::Present(60_000),
3274 fee_proportional_millionths: 0,
3275 excess_data: Vec::new()
3277 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3278 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3279 short_channel_id: 13,
3282 cltv_expiry_delta: 0,
3283 htlc_minimum_msat: 0,
3284 htlc_maximum_msat: OptionalField::Present(60_000),
3286 fee_proportional_millionths: 0,
3287 excess_data: Vec::new()
3290 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
3291 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3292 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3293 short_channel_id: 2,
3296 cltv_expiry_delta: 0,
3297 htlc_minimum_msat: 0,
3298 htlc_maximum_msat: OptionalField::Present(20_000),
3300 fee_proportional_millionths: 0,
3301 excess_data: Vec::new()
3303 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3304 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3305 short_channel_id: 4,
3308 cltv_expiry_delta: 0,
3309 htlc_minimum_msat: 0,
3310 htlc_maximum_msat: OptionalField::Present(20_000),
3312 fee_proportional_millionths: 0,
3313 excess_data: Vec::new()
3317 // Attempt to route more than available results in a failure.
3318 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)) {
3319 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3320 } else { panic!(); }
3324 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
3325 // Our algorithm should provide us with these 3 paths.
3326 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();
3327 assert_eq!(route.paths.len(), 3);
3328 let mut total_amount_paid_msat = 0;
3329 for path in &route.paths {
3330 assert_eq!(path.len(), 2);
3331 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3332 total_amount_paid_msat += path.last().unwrap().fee_msat;
3334 assert_eq!(total_amount_paid_msat, 125_000);
3338 // Attempt to route without the last small cheap channel
3339 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();
3340 assert_eq!(route.paths.len(), 2);
3341 let mut total_amount_paid_msat = 0;
3342 for path in &route.paths {
3343 assert_eq!(path.len(), 2);
3344 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3345 total_amount_paid_msat += path.last().unwrap().fee_msat;
3347 assert_eq!(total_amount_paid_msat, 90_000);