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.
44 /// The CLTV delta added for this hop. For the last hop, this should be the full CLTV value
45 /// expected at the destination, in excess of the current block height.
46 pub cltv_expiry_delta: u32,
49 impl Writeable for Vec<RouteHop> {
50 fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
51 (self.len() as u8).write(writer)?;
52 for hop in self.iter() {
53 hop.pubkey.write(writer)?;
54 hop.node_features.write(writer)?;
55 hop.short_channel_id.write(writer)?;
56 hop.channel_features.write(writer)?;
57 hop.fee_msat.write(writer)?;
58 hop.cltv_expiry_delta.write(writer)?;
64 impl Readable for Vec<RouteHop> {
65 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Vec<RouteHop>, DecodeError> {
66 let hops_count: u8 = Readable::read(reader)?;
67 let mut hops = Vec::with_capacity(hops_count as usize);
68 for _ in 0..hops_count {
70 pubkey: Readable::read(reader)?,
71 node_features: Readable::read(reader)?,
72 short_channel_id: Readable::read(reader)?,
73 channel_features: Readable::read(reader)?,
74 fee_msat: Readable::read(reader)?,
75 cltv_expiry_delta: Readable::read(reader)?,
82 /// A route directs a payment from the sender (us) to the recipient. If the recipient supports MPP,
83 /// it can take multiple paths. Each path is composed of one or more hops through the network.
84 #[derive(Clone, PartialEq)]
86 /// The list of routes taken for a single (potentially-)multi-part payment. The pubkey of the
87 /// last RouteHop in each path must be the same.
88 /// Each entry represents a list of hops, NOT INCLUDING our own, where the last hop is the
89 /// destination. Thus, this must always be at least length one. While the maximum length of any
90 /// given path is variable, keeping the length of any path to less than 20 should currently
91 /// ensure it is viable.
92 pub paths: Vec<Vec<RouteHop>>,
95 impl Writeable for Route {
96 fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
97 (self.paths.len() as u64).write(writer)?;
98 for hops in self.paths.iter() {
105 impl Readable for Route {
106 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
107 let path_count: u64 = Readable::read(reader)?;
108 let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
109 for _ in 0..path_count {
110 paths.push(Readable::read(reader)?);
116 /// A channel descriptor which provides a last-hop route to get_route
118 pub struct RouteHint {
119 /// The node_id of the non-target end of the route
120 pub src_node_id: PublicKey,
121 /// The short_channel_id of this channel
122 pub short_channel_id: u64,
123 /// The fees which must be paid to use this channel
124 pub fees: RoutingFees,
125 /// The difference in CLTV values between this node and the next node.
126 pub cltv_expiry_delta: u16,
127 /// The minimum value, in msat, which must be relayed to the next hop.
128 pub htlc_minimum_msat: Option<u64>,
129 /// The maximum value in msat available for routing with a single HTLC.
130 pub htlc_maximum_msat: Option<u64>,
133 #[derive(Eq, PartialEq)]
134 struct RouteGraphNode {
136 lowest_fee_to_peer_through_node: u64,
137 lowest_fee_to_node: u64,
138 // The maximum value a yet-to-be-constructed payment path might flow through this node.
139 // This value is upper-bounded by us by:
140 // - how much is needed for a path being constructed
141 // - how much value can channels following this node (up to the destination) can contribute,
142 // considering their capacity and fees
143 value_contribution_msat: u64
146 impl cmp::Ord for RouteGraphNode {
147 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
148 other.lowest_fee_to_peer_through_node.cmp(&self.lowest_fee_to_peer_through_node)
149 .then_with(|| other.pubkey.serialize().cmp(&self.pubkey.serialize()))
153 impl cmp::PartialOrd for RouteGraphNode {
154 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
155 Some(self.cmp(other))
159 struct DummyDirectionalChannelInfo {
160 cltv_expiry_delta: u32,
161 htlc_minimum_msat: u64,
162 htlc_maximum_msat: Option<u64>,
166 /// It's useful to keep track of the hops associated with the fees required to use them,
167 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
168 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
169 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
171 struct PathBuildingHop {
172 /// Hop-specific details unrelated to the path during the routing phase,
173 /// but rather relevant to the LN graph.
175 /// Minimal fees required to route to the source node of the current hop via any of its inbound channels.
176 src_lowest_inbound_fees: RoutingFees,
177 /// Fees of the channel used in this hop.
178 channel_fees: RoutingFees,
179 /// All the fees paid *after* this channel on the way to the destination
180 next_hops_fee_msat: u64,
181 /// Fee paid for the use of the current channel (see channel_fees).
182 /// The value will be actually deducted from the counterparty balance on the previous link.
183 hop_use_fee_msat: u64,
184 /// Used to compare channels when choosing the for routing.
185 /// Includes paying for the use of a hop and the following hops, as well as
186 /// an estimated cost of reaching this hop.
187 /// Might get stale when fees are recomputed. Primarily for internal use.
191 // Instantiated with a list of hops with correct data in them collected during path finding,
192 // an instance of this struct should be further modified only via given methods.
195 hops: Vec<PathBuildingHop>,
200 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
201 fn get_value_msat(&self) -> u64 {
202 self.hops.last().unwrap().route_hop.fee_msat
205 fn get_total_fee_paid_msat(&self) -> u64 {
206 if self.hops.len() < 1 {
210 // Can't use next_hops_fee_msat because it gets outdated.
211 for (i, hop) in self.hops.iter().enumerate() {
212 if i != self.hops.len() - 1 {
213 result += hop.route_hop.fee_msat;
219 // If an amount transferred by the path is updated, the fees should be adjusted.
220 // Any other way to change fees may result in an inconsistency.
221 // The caller should make sure values don't fall below htlc_minimum_msat of the used channels.
222 fn update_value_and_recompute_fees(&mut self, value_msat: u64) {
223 let mut total_fee_paid_msat = 0 as u64;
224 for i in (1..self.hops.len()).rev() {
225 let cur_hop_amount_msat = total_fee_paid_msat + value_msat;
226 let mut cur_hop = self.hops.get_mut(i).unwrap();
227 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
228 if let Some(new_fee) = compute_fees(cur_hop_amount_msat, cur_hop.channel_fees) {
229 cur_hop.hop_use_fee_msat = new_fee;
230 total_fee_paid_msat += new_fee;
232 // It should not be possible because this function is called only to reduce the
233 // value. In that case, compute_fee was already called with the same fees for
234 // larger amount and there was no overflow.
239 // Propagate updated fees for the use of the channels to one hop back,
240 // where they will be actually paid (fee_msat).
241 // For the last hop it will represent the value being transferred over this path.
242 for i in 0..self.hops.len() - 1 {
243 let next_hop_use_fee_msat = self.hops.get(i + 1).unwrap().hop_use_fee_msat;
244 self.hops.get_mut(i).unwrap().route_hop.fee_msat = next_hop_use_fee_msat;
246 self.hops.last_mut().unwrap().route_hop.fee_msat = value_msat;
247 self.hops.last_mut().unwrap().hop_use_fee_msat = 0;
251 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
252 let proportional_fee_millions =
253 amount_msat.checked_mul(channel_fees.proportional_millionths as u64);
254 if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
255 (channel_fees.base_msat as u64).checked_add(part / 1_000_000) }) {
259 // This function may be (indirectly) called without any verification,
260 // with channel_fees provided by a caller. We should handle it gracefully.
265 /// Gets a route from us (payer) to the given target node (payee).
267 /// Extra routing hops between known nodes and the target will be used if they are included in
270 /// If some channels aren't announced, it may be useful to fill in a first_hops with the
271 /// results from a local ChannelManager::list_usable_channels() call. If it is filled in, our
272 /// view of our local channels (from net_graph_msg_handler) will be ignored, and only those
273 /// in first_hops will be used.
275 /// Panics if first_hops contains channels without short_channel_ids
276 /// (ChannelManager::list_usable_channels will never include such channels).
278 /// The fees on channels from us to next-hops are ignored (as they are assumed to all be
279 /// equal), however the enabled/disabled bit on such channels as well as the
280 /// htlc_minimum_msat/htlc_maximum_msat *are* checked as they may change based on the receiving node.
281 pub fn get_route<L: Deref>(our_node_id: &PublicKey, network: &NetworkGraph, payee: &PublicKey, first_hops: Option<&[&ChannelDetails]>,
282 last_hops: &[&RouteHint], final_value_msat: u64, final_cltv: u32, logger: L) -> Result<Route, LightningError> where L::Target: Logger {
283 // TODO: Obviously *only* using total fee cost sucks. We should consider weighting by
284 // uptime/success in using a node in the past.
285 if *payee == *our_node_id {
286 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
289 if final_value_msat > MAX_VALUE_MSAT {
290 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
293 if final_value_msat == 0 {
294 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
297 for last_hop in last_hops {
298 if last_hop.src_node_id == *payee {
299 return Err(LightningError{err: "Last hop cannot have a payee as a source.".to_owned(), action: ErrorAction::IgnoreError});
303 // The general routing idea is the following:
304 // 1. Fill first/last hops communicated by the caller.
305 // 2. Attempt to construct a path from payer to payee for transferring
306 // any ~sufficient (described later) value.
307 // If succeed, remember which channels were used and how much liquidity they have available,
308 // so that future paths don't rely on the same liquidity.
309 // 3. Prooceed to the next step if:
310 // - we hit the recommended target value;
311 // - OR if we could not construct a new path. Any next attempt will fail too.
312 // Otherwise, repeat step 2.
313 // 4. See if we managed to collect paths which aggregately are able to transfer target value
314 // (not recommended value). If yes, proceed. If not, fail routing.
315 // 5. Randomly combine paths into routes having enough to fulfill the payment. (TODO: knapsack)
316 // 6. Of all the found paths, select only those with the lowest total fee.
317 // 7. The last path in every selected route is likely to be more than we need.
318 // Reduce its value-to-transfer and recompute fees.
319 // 8. Choose the best route by the lowest total fee.
321 // As for the actual search algorithm,
322 // we do a payee-to-payer Dijkstra's sorting by each node's distance from the payee
323 // plus the minimum per-HTLC fee to get from it to another node (aka "shitty A*").
324 // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
325 // to use as the A* heuristic beyond just the cost to get one node further than the current
328 let dummy_directional_info = DummyDirectionalChannelInfo { // used for first_hops routes
329 cltv_expiry_delta: 0,
330 htlc_minimum_msat: 0,
331 htlc_maximum_msat: None,
334 proportional_millionths: 0,
338 let mut targets = BinaryHeap::new(); //TODO: Do we care about switching to eg Fibbonaci heap?
339 let mut dist = HashMap::with_capacity(network.get_nodes().len());
341 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
342 // Don't stop searching for paths when we think they're
343 // sufficient to transfer a given value aggregately.
344 // Search for higher value, so that we collect many more paths,
345 // and then select the best combination among them.
346 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
347 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
350 // Prepare the data we'll use for payee-to-payer search by
351 // inserting first hops suggested by the caller as targets.
352 // Our search will then attempt to reach them while traversing from the payee node.
353 let mut first_hop_targets = HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
354 if let Some(hops) = first_hops {
356 let short_channel_id = chan.short_channel_id.expect("first_hops should be filled in with usable channels, not pending ones");
357 if chan.remote_network_id == *payee {
359 paths: vec![vec![RouteHop {
360 pubkey: chan.remote_network_id,
361 node_features: chan.counterparty_features.to_context(),
363 channel_features: chan.counterparty_features.to_context(),
364 fee_msat: final_value_msat,
365 cltv_expiry_delta: final_cltv,
368 } else if chan.remote_network_id == *our_node_id {
369 return Err(LightningError{err: "First hop cannot have our_node_id as a destination.".to_owned(), action: ErrorAction::IgnoreError});
371 first_hop_targets.insert(chan.remote_network_id, (short_channel_id, chan.counterparty_features.clone()));
373 if first_hop_targets.is_empty() {
374 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
378 // We don't want multiple paths (as per MPP) share liquidity of the same channels.
379 // This map allows paths to be aware of the channel use by other paths in the same call.
380 // This would help to make a better path finding decisions and not "overbook" channels.
381 // It is unaware of the directions.
382 // TODO: we could let a caller specify this. Definitely useful when considering our own channels.
383 let mut bookkeeped_channels_liquidity_available_msat = HashMap::new();
385 // Keeping track of how much value we already collected across other paths. Helps to decide:
386 // - how much a new path should be transferring (upper bound);
387 // - whether a channel should be disregarded because
388 // it's available liquidity is too small comparing to how much more we need to collect;
389 // - when we want to stop looking for new paths.
390 let mut already_collected_value_msat = 0;
392 macro_rules! add_entry {
393 // Adds entry which goes from $src_node_id to $dest_node_id
394 // over the channel with id $chan_id with fees described in
395 // $directional_info.
396 // $next_hops_fee_msat represents the fees paid for using all the channel *after* this one,
397 // since that value has to be transferred over this channel.
398 ( $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,
399 $next_hops_value_contribution: expr ) => {
400 // Channels to self should not be used. This is more of belt-and-suspenders, because in
401 // practice these cases should be caught earlier:
402 // - for regular channels at channel announcement (TODO)
403 // - for first and last hops early in get_route
404 if $src_node_id != $dest_node_id.clone() {
405 let available_liquidity_msat = bookkeeped_channels_liquidity_available_msat.entry($chan_id.clone()).or_insert_with(|| {
406 let mut initial_liquidity_available_msat = None;
407 if let Some(capacity_sats) = $capacity_sats {
408 initial_liquidity_available_msat = Some(capacity_sats * 1000);
411 if let Some(htlc_maximum_msat) = $directional_info.htlc_maximum_msat {
412 if let Some(available_msat) = initial_liquidity_available_msat {
413 initial_liquidity_available_msat = Some(cmp::min(available_msat, htlc_maximum_msat));
415 initial_liquidity_available_msat = Some(htlc_maximum_msat);
419 match initial_liquidity_available_msat {
420 Some(available_msat) => available_msat,
421 // We assume channels with unknown balance have
422 // a capacity of 0.0025 BTC (or 250_000 sats).
423 None => 250_000 * 1000
427 // It is tricky to substract $next_hops_fee_msat from available liquidity here.
428 // It may be misleading because we might later choose to reduce the value transferred
429 // over these channels, and the channel which was insufficient might become sufficient.
430 // Worst case: we drop a good channel here because it can't cover the high following
431 // fees caused by one expensive channel, but then this channel could have been used
432 // if the amount being transferred over this path is lower.
433 // We do this for now, but this is a subject for removal.
434 if let Some(available_value_contribution_msat) = available_liquidity_msat.checked_sub($next_hops_fee_msat) {
436 // Routing Fragmentation Mitigation heuristic:
438 // Routing fragmentation across many payment paths increases the overall routing
439 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
440 // Taking too many smaller paths also increases the chance of payment failure.
441 // Thus to avoid this effect, we require from our collected links to provide
442 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
444 // This requirement is currently 5% of the remaining-to-be-collected value.
445 // This means as we successfully advance in our collection,
446 // the absolute liquidity contribution is lowered,
447 // thus increasing the number of potential channels to be selected.
449 // Derive the minimal liquidity contribution with a ratio of 20 (5%, rounded up).
450 let minimal_value_contribution_msat: u64 = (recommended_value_msat - already_collected_value_msat + 19) / 20;
451 // Verify the liquidity offered by this channel complies to the minimal contribution.
452 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
454 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
455 // Includes paying fees for the use of the following channels.
456 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
457 Some(result) => result,
458 // Can't overflow due to how the values were computed right above.
459 None => unreachable!(),
462 // If HTLC minimum is larger than the whole value we're going to transfer, we shouldn't bother
463 // even considering this channel, because it won't be useful.
464 // TODO: Explore simply adding fee to hit htlc_minimum_msat
465 // This is separate from checking amount_to_transfer_over_msat, which also should be
466 // lower-bounded by htlc_minimum_msat. Since we're choosing it as maximum possible,
467 // this channel should just be skipped if it's not sufficient.
468 // amount_to_transfer_over_msat can be both larger and smaller than final_value_msat,
469 // so this can't be derived.
470 let final_value_satisfies_htlc_minimum_msat = final_value_msat >= $directional_info.htlc_minimum_msat;
471 if final_value_satisfies_htlc_minimum_msat &&
472 contributes_sufficient_value && amount_to_transfer_over_msat >= $directional_info.htlc_minimum_msat {
473 let hm_entry = dist.entry(&$src_node_id);
474 let old_entry = hm_entry.or_insert_with(|| {
475 // If there was previously no known way to access
476 // the source node (recall it goes payee-to-payer) of $chan_id, first add
477 // a semi-dummy record just to compute the fees to reach the source node.
478 // This will affect our decision on selecting $chan_id
479 // as a way to reach the $dest_node_id.
480 let mut fee_base_msat = u32::max_value();
481 let mut fee_proportional_millionths = u32::max_value();
482 if let Some(Some(fees)) = network.get_nodes().get(&$src_node_id).map(|node| node.lowest_inbound_channel_fees) {
483 fee_base_msat = fees.base_msat;
484 fee_proportional_millionths = fees.proportional_millionths;
487 route_hop: RouteHop {
488 pubkey: $dest_node_id.clone(),
489 node_features: NodeFeatures::empty(),
491 channel_features: $chan_features.clone(),
493 cltv_expiry_delta: 0,
495 src_lowest_inbound_fees: RoutingFees {
496 base_msat: fee_base_msat,
497 proportional_millionths: fee_proportional_millionths,
499 channel_fees: $directional_info.fees,
500 next_hops_fee_msat: u64::max_value(),
501 hop_use_fee_msat: u64::max_value(),
502 total_fee_msat: u64::max_value(),
506 let mut hop_use_fee_msat = 0;
507 let mut total_fee_msat = $next_hops_fee_msat;
509 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
510 // will have the same effective-fee
511 if $src_node_id != *our_node_id {
512 match compute_fees(amount_to_transfer_over_msat, $directional_info.fees) {
513 // max_value means we'll always fail
514 // the old_entry.total_fee_msat > total_fee_msat check
515 None => total_fee_msat = u64::max_value(),
517 hop_use_fee_msat = fee_msat;
518 total_fee_msat += hop_use_fee_msat;
519 if let Some(prev_hop_fee_msat) = compute_fees(total_fee_msat + amount_to_transfer_over_msat,
520 old_entry.src_lowest_inbound_fees) {
521 if let Some(incremented_total_fee_msat) = total_fee_msat.checked_add(prev_hop_fee_msat) {
522 total_fee_msat = incremented_total_fee_msat;
525 // max_value means we'll always fail
526 // the old_entry.total_fee_msat > total_fee_msat check
527 total_fee_msat = u64::max_value();
530 // max_value means we'll always fail
531 // the old_entry.total_fee_msat > total_fee_msat check
532 total_fee_msat = u64::max_value();
538 let new_graph_node = RouteGraphNode {
539 pubkey: $src_node_id,
540 lowest_fee_to_peer_through_node: total_fee_msat,
541 lowest_fee_to_node: $next_hops_fee_msat as u64 + hop_use_fee_msat,
542 value_contribution_msat: value_contribution_msat,
545 // Update the way of reaching $src_node_id with the given $chan_id (from $dest_node_id),
546 // if this way is cheaper than the already known
547 // (considering the cost to "reach" this channel from the route destination,
548 // the cost of using this channel,
549 // and the cost of routing to the source node of this channel).
550 if old_entry.total_fee_msat > total_fee_msat {
551 targets.push(new_graph_node);
552 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
553 old_entry.hop_use_fee_msat = hop_use_fee_msat;
554 old_entry.total_fee_msat = total_fee_msat;
555 old_entry.route_hop = RouteHop {
556 pubkey: $dest_node_id.clone(),
557 node_features: NodeFeatures::empty(),
558 short_channel_id: $chan_id.clone(),
559 channel_features: $chan_features.clone(),
560 fee_msat: 0, // This value will be later filled with hop_use_fee_msat of the following channel
561 cltv_expiry_delta: $directional_info.cltv_expiry_delta as u32,
563 old_entry.channel_fees = $directional_info.fees;
571 // Find ways (channels with destination) to reach a given node and store them
572 // in the corresponding data structures (routing graph etc).
573 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
574 // meaning how much will be paid in fees after this node (to the best of our knowledge).
575 // This data can later be helpful to optimize routing (pay lower fees).
576 macro_rules! add_entries_to_cheapest_to_target_node {
577 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr, $next_hops_value_contribution: expr ) => {
578 if first_hops.is_some() {
579 if let Some(&(ref first_hop, ref features)) = first_hop_targets.get(&$node_id) {
580 add_entry!(first_hop, *our_node_id, $node_id, dummy_directional_info, None::<u64>, features.to_context(), $fee_to_target_msat, $next_hops_value_contribution);
585 if let Some(node_info) = $node.announcement_info.as_ref() {
586 features = node_info.features.clone();
588 features = NodeFeatures::empty();
591 if !features.requires_unknown_bits() {
592 for chan_id in $node.channels.iter() {
593 let chan = network.get_channels().get(chan_id).unwrap();
594 if !chan.features.requires_unknown_bits() {
595 if chan.node_one == *$node_id {
596 // ie $node is one, ie next hop in A* is two, via the two_to_one channel
597 if first_hops.is_none() || chan.node_two != *our_node_id {
598 if let Some(two_to_one) = chan.two_to_one.as_ref() {
599 if two_to_one.enabled {
600 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);
605 if first_hops.is_none() || chan.node_one != *our_node_id {
606 if let Some(one_to_two) = chan.one_to_two.as_ref() {
607 if one_to_two.enabled {
608 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);
620 let mut payment_paths = Vec::<PaymentPath>::new();
622 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
623 'paths_collection: loop {
624 // For every new path, start from scratch, except
625 // bookkeeped_channels_liquidity_available_msat, which will improve
626 // the further iterations of path finding. Also don't erase first_hop_targets.
630 // Add the payee as a target, so that the payee-to-payer
631 // search algorithm knows what to start with.
632 match network.get_nodes().get(payee) {
633 // The payee is not in our network graph, so nothing to add here.
634 // There is still a chance of reaching them via last_hops though,
635 // so don't yet fail the payment here.
636 // If not, targets.pop() will not even let us enter the loop in step 2.
639 add_entries_to_cheapest_to_target_node!(node, payee, 0, recommended_value_msat);
644 // If a caller provided us with last hops, add them to routing targets. Since this happens
645 // earlier than general path finding, they will be somewhat prioritized, although currently
646 // it matters only if the fees are exactly the same.
647 for hop in last_hops.iter() {
648 let have_hop_src_in_graph =
649 if let Some(&(ref first_hop, ref features)) = first_hop_targets.get(&hop.src_node_id) {
650 // If this hop connects to a node with which we have a direct channel, ignore
651 // the network graph and add both the hop and our direct channel to
652 // the candidate set.
654 // Currently there are no channel-context features defined, so we are a
655 // bit lazy here. In the future, we should pull them out via our
656 // ChannelManager, but there's no reason to waste the space until we
658 add_entry!(first_hop, *our_node_id , hop.src_node_id, dummy_directional_info, None::<u64>, features.to_context(), 0, recommended_value_msat);
661 // In any other case, only add the hop if the source is in the regular network
663 network.get_nodes().get(&hop.src_node_id).is_some()
665 if have_hop_src_in_graph {
666 // BOLT 11 doesn't allow inclusion of features for the last hop hints, which
667 // really sucks, cause we're gonna need that eventually.
668 let last_hop_htlc_minimum_msat: u64 = match hop.htlc_minimum_msat {
669 Some(htlc_minimum_msat) => htlc_minimum_msat,
672 let directional_info = DummyDirectionalChannelInfo {
673 cltv_expiry_delta: hop.cltv_expiry_delta as u32,
674 htlc_minimum_msat: last_hop_htlc_minimum_msat,
675 htlc_maximum_msat: hop.htlc_maximum_msat,
678 add_entry!(hop.short_channel_id, hop.src_node_id, payee, directional_info, None::<u64>, ChannelFeatures::empty(), 0, recommended_value_msat);
682 // At this point, targets are filled with the data from first and
683 // last hops communicated by the caller, and the payment receiver.
684 let mut found_new_path = false;
687 // If this loop terminates due the exhaustion of targets, two situations are possible:
688 // - not enough outgoing liquidity:
689 // 0 < already_collected_value_msat < final_value_msat
690 // - enough outgoing liquidity:
691 // final_value_msat <= already_collected_value_msat < recommended_value_msat
692 // Both these cases (and other cases except reaching recommended_value_msat) mean that
693 // paths_collection will be stopped because found_new_path==false.
694 // This is not necessarily a routing failure.
695 'path_construction: while let Some(RouteGraphNode { pubkey, lowest_fee_to_node, value_contribution_msat, .. }) = targets.pop() {
697 // Since we're going payee-to-payer, hitting our node as a target means we should stop
698 // traversing the graph and arrange the path out of what we found.
699 if pubkey == *our_node_id {
700 let mut new_entry = dist.remove(&our_node_id).unwrap();
701 let mut ordered_hops = vec!(new_entry.clone());
704 if let Some(&(_, ref features)) = first_hop_targets.get(&ordered_hops.last().unwrap().route_hop.pubkey) {
705 ordered_hops.last_mut().unwrap().route_hop.node_features = features.to_context();
706 } else if let Some(node) = network.get_nodes().get(&ordered_hops.last().unwrap().route_hop.pubkey) {
707 if let Some(node_info) = node.announcement_info.as_ref() {
708 ordered_hops.last_mut().unwrap().route_hop.node_features = node_info.features.clone();
710 ordered_hops.last_mut().unwrap().route_hop.node_features = NodeFeatures::empty();
713 // We should be able to fill in features for everything except the last
714 // hop, if the last hop was provided via a BOLT 11 invoice (though we
715 // should be able to extend it further as BOLT 11 does have feature
716 // flags for the last hop node itself).
717 assert!(ordered_hops.last().unwrap().route_hop.pubkey == *payee);
720 // Means we succesfully traversed from the payer to the payee, now
721 // save this path for the payment route. Also, update the liquidity
722 // remaining on the used hops, so that we take them into account
723 // while looking for more paths.
724 if ordered_hops.last().unwrap().route_hop.pubkey == *payee {
728 new_entry = match dist.remove(&ordered_hops.last().unwrap().route_hop.pubkey) {
729 Some(payment_hop) => payment_hop,
730 // We can't arrive at None because, if we ever add an entry to targets,
731 // we also fill in the entry in dist (see add_entry!).
732 None => unreachable!(),
734 // We "propagate" the fees one hop backward (topologically) here,
735 // so that fees paid for a HTLC forwarding on the current channel are
736 // associated with the previous channel (where they will be subtracted).
737 ordered_hops.last_mut().unwrap().route_hop.fee_msat = new_entry.hop_use_fee_msat;
738 ordered_hops.last_mut().unwrap().route_hop.cltv_expiry_delta = new_entry.route_hop.cltv_expiry_delta;
739 ordered_hops.push(new_entry.clone());
741 ordered_hops.last_mut().unwrap().route_hop.fee_msat = value_contribution_msat;
742 ordered_hops.last_mut().unwrap().hop_use_fee_msat = 0;
743 ordered_hops.last_mut().unwrap().route_hop.cltv_expiry_delta = final_cltv;
745 let payment_path = PaymentPath {hops: ordered_hops};
746 // Since a path allows to transfer as much value as
747 // the smallest channel it has ("bottleneck"), we should recompute
748 // the fees so sender HTLC don't overpay fees when traversing
749 // larger channels than the bottleneck. This may happen because
750 // when we were selecting those channels we were not aware how much value
751 // this path will transfer, and the relative fee for them
752 // might have been computed considering a larger value.
753 // Remember that we used these channels so that we don't rely
754 // on the same liquidity in future paths.
755 for (i, payment_hop) in payment_path.hops.iter().enumerate() {
756 let channel_liquidity_available_msat = bookkeeped_channels_liquidity_available_msat.get_mut(&payment_hop.route_hop.short_channel_id).unwrap();
757 let mut spent_on_hop_msat = value_contribution_msat;
758 let next_hops_fee_msat = payment_hop.next_hops_fee_msat;
759 spent_on_hop_msat += next_hops_fee_msat;
760 if *channel_liquidity_available_msat < spent_on_hop_msat {
761 // This should not happen because we do recompute fees right before,
762 // trying to avoid cases when a hop is not usable due to the fee situation.
763 break 'path_construction;
765 *channel_liquidity_available_msat -= spent_on_hop_msat;
767 // Track the total amount all our collected paths allow to send so that we:
768 // - know when to stop looking for more paths
769 // - know which of the hops are useless considering how much more sats we need
770 // (contributes_sufficient_value)
771 already_collected_value_msat += value_contribution_msat;
773 payment_paths.push(payment_path);
774 found_new_path = true;
775 break 'path_construction;
778 // Otherwise, since the current target node is not us,
779 // keep "unrolling" the payment graph from payee to payer by
780 // finding a way to reach the current target from the payer side.
781 match network.get_nodes().get(&pubkey) {
784 add_entries_to_cheapest_to_target_node!(node, &pubkey, lowest_fee_to_node, value_contribution_msat);
790 // Stop either when recommended value is reached,
791 // or if during last iteration no new path was found.
792 // In the latter case, making another path finding attempt could not help,
793 // because we deterministically terminate the search due to low liquidity.
794 if already_collected_value_msat >= recommended_value_msat || !found_new_path {
795 break 'paths_collection;
800 if payment_paths.len() == 0 {
801 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
804 if already_collected_value_msat < final_value_msat {
805 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
808 // Sort by total fees and take the best paths.
809 payment_paths.sort_by_key(|path| path.get_total_fee_paid_msat());
810 if payment_paths.len() > 50 {
811 payment_paths.truncate(50);
814 // Draw multiple sufficient routes by randomly combining the selected paths.
815 let mut drawn_routes = Vec::new();
816 for i in 0..payment_paths.len() {
817 let mut cur_route = Vec::<PaymentPath>::new();
818 let mut aggregate_route_value_msat = 0;
821 // TODO: real random shuffle
822 // Currently just starts with i_th and goes up to i-1_th in a looped way.
823 let cur_payment_paths = [&payment_paths[i..], &payment_paths[..i]].concat();
826 for payment_path in cur_payment_paths {
827 cur_route.push(payment_path.clone());
828 aggregate_route_value_msat += payment_path.get_value_msat();
829 if aggregate_route_value_msat > final_value_msat {
830 // Last path likely overpaid. Substract it from the most expensive
831 // (in terms of proportional fee) path in this route and recompute fees.
832 // This might be not the most economically efficient way, but fewer paths
833 // also makes routing more reliable.
834 let mut overpaid_value_msat = aggregate_route_value_msat - final_value_msat;
836 // First, drop some expensive low-value paths entirely if possible.
837 // Sort by value so that we drop many really-low values first, since
838 // fewer paths is better: the payment is less likely to fail.
839 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
840 // so that the sender pays less fees overall.
841 cur_route.sort_by_key(|path| path.get_value_msat());
842 // We should make sure that at least 1 path left.
843 let mut paths_left = cur_route.len();
844 cur_route.retain(|path| {
849 let path_value_msat = path.get_value_msat();
850 if path_value_msat <= overpaid_value_msat {
852 overpaid_value_msat -= path_value_msat;
858 if overpaid_value_msat == 0 {
862 assert!(cur_route.len() > 0);
865 // Now, substract the overpaid value from the most-expensive path.
866 cur_route.sort_by_key(|path| { path.hops.iter().map(|hop| hop.channel_fees.proportional_millionths as u64).sum::<u64>() });
867 let expensive_payment_path = cur_route.last_mut().unwrap();
868 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
869 // TODO: make sure expensive_path_new_value_msat doesn't cause to fall behind htlc_minimum_msat.
870 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
874 drawn_routes.push(cur_route);
878 // Select the best route by lowest total fee.
879 drawn_routes.sort_by_key(|paths| paths.iter().map(|path| path.get_total_fee_paid_msat()).sum::<u64>());
880 let mut selected_paths = Vec::<Vec::<RouteHop>>::new();
881 for payment_path in drawn_routes.first().unwrap() {
882 selected_paths.push(payment_path.hops.iter().map(|payment_hop| payment_hop.route_hop.clone()).collect());
885 let route = Route { paths: selected_paths };
886 log_trace!(logger, "Got route: {}", log_route!(route));
892 use routing::router::{get_route, RouteHint, RoutingFees};
893 use routing::network_graph::{NetworkGraph, NetGraphMsgHandler};
894 use ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
895 use ln::msgs::{ErrorAction, LightningError, OptionalField, UnsignedChannelAnnouncement, ChannelAnnouncement, RoutingMessageHandler,
896 NodeAnnouncement, UnsignedNodeAnnouncement, ChannelUpdate, UnsignedChannelUpdate};
897 use ln::channelmanager;
898 use util::test_utils;
899 use util::ser::Writeable;
901 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
902 use bitcoin::hashes::Hash;
903 use bitcoin::network::constants::Network;
904 use bitcoin::blockdata::constants::genesis_block;
905 use bitcoin::blockdata::script::Builder;
906 use bitcoin::blockdata::opcodes;
907 use bitcoin::blockdata::transaction::TxOut;
911 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
912 use bitcoin::secp256k1::{Secp256k1, All};
916 // Using the same keys for LN and BTC ids
917 fn add_channel(net_graph_msg_handler: &NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>, secp_ctx: &Secp256k1<All>, node_1_privkey: &SecretKey,
918 node_2_privkey: &SecretKey, features: ChannelFeatures, short_channel_id: u64) {
919 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
920 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
922 let unsigned_announcement = UnsignedChannelAnnouncement {
924 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
928 bitcoin_key_1: node_id_1,
929 bitcoin_key_2: node_id_2,
930 excess_data: Vec::new(),
933 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
934 let valid_announcement = ChannelAnnouncement {
935 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
936 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
937 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
938 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
939 contents: unsigned_announcement.clone(),
941 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
942 Ok(res) => assert!(res),
947 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) {
948 let msghash = hash_to_message!(&Sha256dHash::hash(&update.encode()[..])[..]);
949 let valid_channel_update = ChannelUpdate {
950 signature: secp_ctx.sign(&msghash, node_privkey),
951 contents: update.clone()
954 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
955 Ok(res) => assert!(res),
960 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,
961 features: NodeFeatures, timestamp: u32) {
962 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
963 let unsigned_announcement = UnsignedNodeAnnouncement {
969 addresses: Vec::new(),
970 excess_address_data: Vec::new(),
971 excess_data: Vec::new(),
973 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
974 let valid_announcement = NodeAnnouncement {
975 signature: secp_ctx.sign(&msghash, node_privkey),
976 contents: unsigned_announcement.clone()
979 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
985 fn get_nodes(secp_ctx: &Secp256k1<All>) -> (SecretKey, PublicKey, Vec<SecretKey>, Vec<PublicKey>) {
986 let privkeys: Vec<SecretKey> = (2..10).map(|i| {
987 SecretKey::from_slice(&hex::decode(format!("{:02}", i).repeat(32)).unwrap()[..]).unwrap()
990 let pubkeys = privkeys.iter().map(|secret| PublicKey::from_secret_key(&secp_ctx, secret)).collect();
992 let our_privkey = SecretKey::from_slice(&hex::decode("01".repeat(32)).unwrap()[..]).unwrap();
993 let our_id = PublicKey::from_secret_key(&secp_ctx, &our_privkey);
995 (our_privkey, our_id, privkeys, pubkeys)
998 fn id_to_feature_flags(id: u8) -> Vec<u8> {
999 // Set the feature flags to the id'th odd (ie non-required) feature bit so that we can
1000 // test for it later.
1001 let idx = (id - 1) * 2 + 1;
1003 vec![1 << (idx - 8*3), 0, 0, 0]
1004 } else if idx > 8*2 {
1005 vec![1 << (idx - 8*2), 0, 0]
1006 } else if idx > 8*1 {
1007 vec![1 << (idx - 8*1), 0]
1013 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>) {
1014 let secp_ctx = Secp256k1::new();
1015 let logger = Arc::new(test_utils::TestLogger::new());
1016 let chain_monitor = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1017 let net_graph_msg_handler = NetGraphMsgHandler::new(genesis_block(Network::Testnet).header.block_hash(), None, Arc::clone(&logger));
1018 // Build network from our_id to node7:
1020 // -1(1)2- node0 -1(3)2-
1022 // our_id -1(12)2- node7 -1(13)2--- node2
1024 // -1(2)2- node1 -1(4)2-
1027 // chan1 1-to-2: disabled
1028 // chan1 2-to-1: enabled, 0 fee
1030 // chan2 1-to-2: enabled, ignored fee
1031 // chan2 2-to-1: enabled, 0 fee
1033 // chan3 1-to-2: enabled, 0 fee
1034 // chan3 2-to-1: enabled, 100 msat fee
1036 // chan4 1-to-2: enabled, 100% fee
1037 // chan4 2-to-1: enabled, 0 fee
1039 // chan12 1-to-2: enabled, ignored fee
1040 // chan12 2-to-1: enabled, 0 fee
1042 // chan13 1-to-2: enabled, 200% fee
1043 // chan13 2-to-1: enabled, 0 fee
1046 // -1(5)2- node3 -1(8)2--
1050 // node2--1(6)2- node4 -1(9)2--- node6 (not in global route map)
1052 // -1(7)2- node5 -1(10)2-
1054 // chan5 1-to-2: enabled, 100 msat fee
1055 // chan5 2-to-1: enabled, 0 fee
1057 // chan6 1-to-2: enabled, 0 fee
1058 // chan6 2-to-1: enabled, 0 fee
1060 // chan7 1-to-2: enabled, 100% fee
1061 // chan7 2-to-1: enabled, 0 fee
1063 // chan8 1-to-2: enabled, variable fee (0 then 1000 msat)
1064 // chan8 2-to-1: enabled, 0 fee
1066 // chan9 1-to-2: enabled, 1001 msat fee
1067 // chan9 2-to-1: enabled, 0 fee
1069 // chan10 1-to-2: enabled, 0 fee
1070 // chan10 2-to-1: enabled, 0 fee
1072 // chan11 1-to-2: enabled, 0 fee
1073 // chan11 2-to-1: enabled, 0 fee
1075 let (our_privkey, _, privkeys, _) = get_nodes(&secp_ctx);
1077 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[0], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
1078 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1079 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1080 short_channel_id: 1,
1083 cltv_expiry_delta: 0,
1084 htlc_minimum_msat: 0,
1085 htlc_maximum_msat: OptionalField::Absent,
1087 fee_proportional_millionths: 0,
1088 excess_data: Vec::new()
1091 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
1093 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
1094 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1095 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1096 short_channel_id: 2,
1099 cltv_expiry_delta: u16::max_value(),
1100 htlc_minimum_msat: 0,
1101 htlc_maximum_msat: OptionalField::Absent,
1102 fee_base_msat: u32::max_value(),
1103 fee_proportional_millionths: u32::max_value(),
1104 excess_data: Vec::new()
1106 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1107 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1108 short_channel_id: 2,
1111 cltv_expiry_delta: 0,
1112 htlc_minimum_msat: 0,
1113 htlc_maximum_msat: OptionalField::Absent,
1115 fee_proportional_millionths: 0,
1116 excess_data: Vec::new()
1119 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
1121 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[7], ChannelFeatures::from_le_bytes(id_to_feature_flags(12)), 12);
1122 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1123 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1124 short_channel_id: 12,
1127 cltv_expiry_delta: u16::max_value(),
1128 htlc_minimum_msat: 0,
1129 htlc_maximum_msat: OptionalField::Absent,
1130 fee_base_msat: u32::max_value(),
1131 fee_proportional_millionths: u32::max_value(),
1132 excess_data: Vec::new()
1134 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1135 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1136 short_channel_id: 12,
1139 cltv_expiry_delta: 0,
1140 htlc_minimum_msat: 0,
1141 htlc_maximum_msat: OptionalField::Absent,
1143 fee_proportional_millionths: 0,
1144 excess_data: Vec::new()
1147 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], NodeFeatures::from_le_bytes(id_to_feature_flags(8)), 0);
1149 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
1150 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1151 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1152 short_channel_id: 3,
1155 cltv_expiry_delta: (3 << 8) | 1,
1156 htlc_minimum_msat: 0,
1157 htlc_maximum_msat: OptionalField::Absent,
1159 fee_proportional_millionths: 0,
1160 excess_data: Vec::new()
1162 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1163 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1164 short_channel_id: 3,
1167 cltv_expiry_delta: (3 << 8) | 2,
1168 htlc_minimum_msat: 0,
1169 htlc_maximum_msat: OptionalField::Absent,
1171 fee_proportional_millionths: 0,
1172 excess_data: Vec::new()
1175 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
1176 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1177 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1178 short_channel_id: 4,
1181 cltv_expiry_delta: (4 << 8) | 1,
1182 htlc_minimum_msat: 0,
1183 htlc_maximum_msat: OptionalField::Absent,
1185 fee_proportional_millionths: 1000000,
1186 excess_data: Vec::new()
1188 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1189 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1190 short_channel_id: 4,
1193 cltv_expiry_delta: (4 << 8) | 2,
1194 htlc_minimum_msat: 0,
1195 htlc_maximum_msat: OptionalField::Absent,
1197 fee_proportional_millionths: 0,
1198 excess_data: Vec::new()
1201 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(13)), 13);
1202 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1203 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1204 short_channel_id: 13,
1207 cltv_expiry_delta: (13 << 8) | 1,
1208 htlc_minimum_msat: 0,
1209 htlc_maximum_msat: OptionalField::Absent,
1211 fee_proportional_millionths: 2000000,
1212 excess_data: Vec::new()
1214 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1215 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1216 short_channel_id: 13,
1219 cltv_expiry_delta: (13 << 8) | 2,
1220 htlc_minimum_msat: 0,
1221 htlc_maximum_msat: OptionalField::Absent,
1223 fee_proportional_millionths: 0,
1224 excess_data: Vec::new()
1227 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
1229 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
1230 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1231 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1232 short_channel_id: 6,
1235 cltv_expiry_delta: (6 << 8) | 1,
1236 htlc_minimum_msat: 0,
1237 htlc_maximum_msat: OptionalField::Absent,
1239 fee_proportional_millionths: 0,
1240 excess_data: Vec::new()
1242 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1243 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1244 short_channel_id: 6,
1247 cltv_expiry_delta: (6 << 8) | 2,
1248 htlc_minimum_msat: 0,
1249 htlc_maximum_msat: OptionalField::Absent,
1251 fee_proportional_millionths: 0,
1252 excess_data: Vec::new(),
1255 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(11)), 11);
1256 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1257 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1258 short_channel_id: 11,
1261 cltv_expiry_delta: (11 << 8) | 1,
1262 htlc_minimum_msat: 0,
1263 htlc_maximum_msat: OptionalField::Absent,
1265 fee_proportional_millionths: 0,
1266 excess_data: Vec::new()
1268 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
1269 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1270 short_channel_id: 11,
1273 cltv_expiry_delta: (11 << 8) | 2,
1274 htlc_minimum_msat: 0,
1275 htlc_maximum_msat: OptionalField::Absent,
1277 fee_proportional_millionths: 0,
1278 excess_data: Vec::new()
1281 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(5)), 0);
1283 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
1285 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[5], ChannelFeatures::from_le_bytes(id_to_feature_flags(7)), 7);
1286 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1287 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1288 short_channel_id: 7,
1291 cltv_expiry_delta: (7 << 8) | 1,
1292 htlc_minimum_msat: 0,
1293 htlc_maximum_msat: OptionalField::Absent,
1295 fee_proportional_millionths: 1000000,
1296 excess_data: Vec::new()
1298 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[5], UnsignedChannelUpdate {
1299 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1300 short_channel_id: 7,
1303 cltv_expiry_delta: (7 << 8) | 2,
1304 htlc_minimum_msat: 0,
1305 htlc_maximum_msat: OptionalField::Absent,
1307 fee_proportional_millionths: 0,
1308 excess_data: Vec::new()
1311 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[5], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
1313 (secp_ctx, net_graph_msg_handler, chain_monitor, logger)
1317 fn simple_route_test() {
1318 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1319 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1321 // Simple route to 2 via 1
1323 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)) {
1324 assert_eq!(err, "Cannot send a payment of 0 msat");
1325 } else { panic!(); }
1327 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();
1328 assert_eq!(route.paths[0].len(), 2);
1330 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
1331 assert_eq!(route.paths[0][0].short_channel_id, 2);
1332 assert_eq!(route.paths[0][0].fee_msat, 100);
1333 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
1334 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
1335 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
1337 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1338 assert_eq!(route.paths[0][1].short_channel_id, 4);
1339 assert_eq!(route.paths[0][1].fee_msat, 100);
1340 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1341 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1342 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
1346 fn invalid_first_hop_test() {
1347 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1348 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1350 // Simple route to 2 via 1
1352 let our_chans = vec![channelmanager::ChannelDetails {
1353 channel_id: [0; 32],
1354 short_channel_id: Some(2),
1355 remote_network_id: our_id,
1356 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1357 channel_value_satoshis: 100000,
1359 outbound_capacity_msat: 100000,
1360 inbound_capacity_msat: 100000,
1364 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)) {
1365 assert_eq!(err, "First hop cannot have our_node_id as a destination.");
1366 } else { panic!(); }
1368 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();
1369 assert_eq!(route.paths[0].len(), 2);
1373 fn htlc_minimum_test() {
1374 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1375 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1377 // Simple route to 2 via 1
1378 // Should fail if htlc_minimum can't be reached
1380 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1381 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1382 short_channel_id: 2,
1385 cltv_expiry_delta: 0,
1386 htlc_minimum_msat: 50_000,
1387 htlc_maximum_msat: OptionalField::Absent,
1389 fee_proportional_millionths: 0,
1390 excess_data: Vec::new()
1393 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1394 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1395 short_channel_id: 4,
1398 cltv_expiry_delta: 0,
1399 htlc_minimum_msat: 0,
1400 htlc_maximum_msat: OptionalField::Absent,
1402 fee_proportional_millionths: 0,
1403 excess_data: Vec::new()
1406 // Disable other paths
1407 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1408 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1409 short_channel_id: 12,
1411 flags: 2, // to disable
1412 cltv_expiry_delta: 0,
1413 htlc_minimum_msat: 0,
1414 htlc_maximum_msat: OptionalField::Absent,
1416 fee_proportional_millionths: 0,
1417 excess_data: Vec::new()
1419 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1420 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1421 short_channel_id: 3,
1423 flags: 2, // to disable
1424 cltv_expiry_delta: 0,
1425 htlc_minimum_msat: 0,
1426 htlc_maximum_msat: OptionalField::Absent,
1428 fee_proportional_millionths: 0,
1429 excess_data: Vec::new()
1431 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1432 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1433 short_channel_id: 13,
1435 flags: 2, // to disable
1436 cltv_expiry_delta: 0,
1437 htlc_minimum_msat: 0,
1438 htlc_maximum_msat: OptionalField::Absent,
1440 fee_proportional_millionths: 0,
1441 excess_data: Vec::new()
1443 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1444 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1445 short_channel_id: 6,
1447 flags: 2, // to disable
1448 cltv_expiry_delta: 0,
1449 htlc_minimum_msat: 0,
1450 htlc_maximum_msat: OptionalField::Absent,
1452 fee_proportional_millionths: 0,
1453 excess_data: Vec::new()
1455 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1456 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1457 short_channel_id: 7,
1459 flags: 2, // to disable
1460 cltv_expiry_delta: 0,
1461 htlc_minimum_msat: 0,
1462 htlc_maximum_msat: OptionalField::Absent,
1464 fee_proportional_millionths: 0,
1465 excess_data: Vec::new()
1468 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(), 49_999, 42, Arc::clone(&logger)) {
1469 assert_eq!(err, "Failed to find a path to the given destination");
1470 } else { panic!(); }
1472 // A payment above the minimum should pass
1473 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();
1474 assert_eq!(route.paths[0].len(), 2);
1476 // This was a check against final_value_msat.
1477 // Now let's check against amount_to_transfer_over_msat.
1478 // Set minimal HTLC of 200_000_000 msat.
1479 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1480 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1481 short_channel_id: 2,
1484 cltv_expiry_delta: 0,
1485 htlc_minimum_msat: 200_000_000,
1486 htlc_maximum_msat: OptionalField::Absent,
1488 fee_proportional_millionths: 0,
1489 excess_data: Vec::new()
1492 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
1494 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1495 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1496 short_channel_id: 4,
1499 cltv_expiry_delta: 0,
1500 htlc_minimum_msat: 0,
1501 htlc_maximum_msat: OptionalField::Present(199_999_999),
1503 fee_proportional_millionths: 0,
1504 excess_data: Vec::new()
1507 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
1508 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)) {
1509 assert_eq!(err, "Failed to find a path to the given destination");
1510 } else { panic!(); }
1512 // Lift the restriction on the first hop.
1513 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1514 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1515 short_channel_id: 2,
1518 cltv_expiry_delta: 0,
1519 htlc_minimum_msat: 0,
1520 htlc_maximum_msat: OptionalField::Absent,
1522 fee_proportional_millionths: 0,
1523 excess_data: Vec::new()
1526 // A payment above the minimum should pass
1527 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();
1528 assert_eq!(route.paths[0].len(), 2);
1532 fn disable_channels_test() {
1533 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1534 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1536 // // Disable channels 4 and 12 by flags=2
1537 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1538 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1539 short_channel_id: 4,
1541 flags: 2, // to disable
1542 cltv_expiry_delta: 0,
1543 htlc_minimum_msat: 0,
1544 htlc_maximum_msat: OptionalField::Absent,
1546 fee_proportional_millionths: 0,
1547 excess_data: Vec::new()
1549 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1550 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1551 short_channel_id: 12,
1553 flags: 2, // to disable
1554 cltv_expiry_delta: 0,
1555 htlc_minimum_msat: 0,
1556 htlc_maximum_msat: OptionalField::Absent,
1558 fee_proportional_millionths: 0,
1559 excess_data: Vec::new()
1562 // If all the channels require some features we don't understand, route should fail
1563 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)) {
1564 assert_eq!(err, "Failed to find a path to the given destination");
1565 } else { panic!(); }
1567 // If we specify a channel to node7, that overrides our local channel view and that gets used
1568 let our_chans = vec![channelmanager::ChannelDetails {
1569 channel_id: [0; 32],
1570 short_channel_id: Some(42),
1571 remote_network_id: nodes[7].clone(),
1572 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1573 channel_value_satoshis: 0,
1575 outbound_capacity_msat: 0,
1576 inbound_capacity_msat: 0,
1579 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();
1580 assert_eq!(route.paths[0].len(), 2);
1582 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
1583 assert_eq!(route.paths[0][0].short_channel_id, 42);
1584 assert_eq!(route.paths[0][0].fee_msat, 200);
1585 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
1586 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
1587 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
1589 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1590 assert_eq!(route.paths[0][1].short_channel_id, 13);
1591 assert_eq!(route.paths[0][1].fee_msat, 100);
1592 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1593 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1594 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
1598 fn disable_node_test() {
1599 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1600 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1602 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
1603 let mut unknown_features = NodeFeatures::known();
1604 unknown_features.set_required_unknown_bits();
1605 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
1606 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
1607 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
1609 // If all nodes require some features we don't understand, route should fail
1610 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)) {
1611 assert_eq!(err, "Failed to find a path to the given destination");
1612 } else { panic!(); }
1614 // If we specify a channel to node7, that overrides our local channel view and that gets used
1615 let our_chans = vec![channelmanager::ChannelDetails {
1616 channel_id: [0; 32],
1617 short_channel_id: Some(42),
1618 remote_network_id: nodes[7].clone(),
1619 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1620 channel_value_satoshis: 0,
1622 outbound_capacity_msat: 0,
1623 inbound_capacity_msat: 0,
1626 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();
1627 assert_eq!(route.paths[0].len(), 2);
1629 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
1630 assert_eq!(route.paths[0][0].short_channel_id, 42);
1631 assert_eq!(route.paths[0][0].fee_msat, 200);
1632 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
1633 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
1634 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
1636 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1637 assert_eq!(route.paths[0][1].short_channel_id, 13);
1638 assert_eq!(route.paths[0][1].fee_msat, 100);
1639 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1640 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1641 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
1643 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
1644 // naively) assume that the user checked the feature bits on the invoice, which override
1645 // the node_announcement.
1649 fn our_chans_test() {
1650 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1651 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1653 // Route to 1 via 2 and 3 because our channel to 1 is disabled
1654 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();
1655 assert_eq!(route.paths[0].len(), 3);
1657 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
1658 assert_eq!(route.paths[0][0].short_channel_id, 2);
1659 assert_eq!(route.paths[0][0].fee_msat, 200);
1660 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
1661 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
1662 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
1664 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1665 assert_eq!(route.paths[0][1].short_channel_id, 4);
1666 assert_eq!(route.paths[0][1].fee_msat, 100);
1667 assert_eq!(route.paths[0][1].cltv_expiry_delta, (3 << 8) | 2);
1668 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1669 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
1671 assert_eq!(route.paths[0][2].pubkey, nodes[0]);
1672 assert_eq!(route.paths[0][2].short_channel_id, 3);
1673 assert_eq!(route.paths[0][2].fee_msat, 100);
1674 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
1675 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(1));
1676 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(3));
1678 // If we specify a channel to node7, that overrides our local channel view and that gets used
1679 let our_chans = vec![channelmanager::ChannelDetails {
1680 channel_id: [0; 32],
1681 short_channel_id: Some(42),
1682 remote_network_id: nodes[7].clone(),
1683 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1684 channel_value_satoshis: 0,
1686 outbound_capacity_msat: 0,
1687 inbound_capacity_msat: 0,
1690 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();
1691 assert_eq!(route.paths[0].len(), 2);
1693 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
1694 assert_eq!(route.paths[0][0].short_channel_id, 42);
1695 assert_eq!(route.paths[0][0].fee_msat, 200);
1696 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
1697 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
1698 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
1700 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1701 assert_eq!(route.paths[0][1].short_channel_id, 13);
1702 assert_eq!(route.paths[0][1].fee_msat, 100);
1703 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1704 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1705 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
1708 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
1709 let zero_fees = RoutingFees {
1711 proportional_millionths: 0,
1714 src_node_id: nodes[3].clone(),
1715 short_channel_id: 8,
1717 cltv_expiry_delta: (8 << 8) | 1,
1718 htlc_minimum_msat: None,
1719 htlc_maximum_msat: None,
1721 src_node_id: nodes[4].clone(),
1722 short_channel_id: 9,
1725 proportional_millionths: 0,
1727 cltv_expiry_delta: (9 << 8) | 1,
1728 htlc_minimum_msat: None,
1729 htlc_maximum_msat: None,
1731 src_node_id: nodes[5].clone(),
1732 short_channel_id: 10,
1734 cltv_expiry_delta: (10 << 8) | 1,
1735 htlc_minimum_msat: None,
1736 htlc_maximum_msat: None,
1741 fn last_hops_test() {
1742 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1743 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1745 // Simple test across 2, 3, 5, and 4 via a last_hop channel
1747 // First check that lst hop can't have its source as the payee.
1748 let invalid_last_hop = RouteHint {
1749 src_node_id: nodes[6],
1750 short_channel_id: 8,
1753 proportional_millionths: 0,
1755 cltv_expiry_delta: (8 << 8) | 1,
1756 htlc_minimum_msat: None,
1757 htlc_maximum_msat: None,
1760 let mut invalid_last_hops = last_hops(&nodes);
1761 invalid_last_hops.push(invalid_last_hop);
1763 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)) {
1764 assert_eq!(err, "Last hop cannot have a payee as a source.");
1765 } else { panic!(); }
1768 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();
1769 assert_eq!(route.paths[0].len(), 5);
1771 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
1772 assert_eq!(route.paths[0][0].short_channel_id, 2);
1773 assert_eq!(route.paths[0][0].fee_msat, 100);
1774 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
1775 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
1776 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
1778 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1779 assert_eq!(route.paths[0][1].short_channel_id, 4);
1780 assert_eq!(route.paths[0][1].fee_msat, 0);
1781 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
1782 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1783 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
1785 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
1786 assert_eq!(route.paths[0][2].short_channel_id, 6);
1787 assert_eq!(route.paths[0][2].fee_msat, 0);
1788 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
1789 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
1790 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
1792 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
1793 assert_eq!(route.paths[0][3].short_channel_id, 11);
1794 assert_eq!(route.paths[0][3].fee_msat, 0);
1795 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
1796 // If we have a peer in the node map, we'll use their features here since we don't have
1797 // a way of figuring out their features from the invoice:
1798 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
1799 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
1801 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
1802 assert_eq!(route.paths[0][4].short_channel_id, 8);
1803 assert_eq!(route.paths[0][4].fee_msat, 100);
1804 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
1805 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
1806 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
1810 fn our_chans_last_hop_connect_test() {
1811 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1812 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1814 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
1815 let our_chans = vec![channelmanager::ChannelDetails {
1816 channel_id: [0; 32],
1817 short_channel_id: Some(42),
1818 remote_network_id: nodes[3].clone(),
1819 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1820 channel_value_satoshis: 0,
1822 outbound_capacity_msat: 0,
1823 inbound_capacity_msat: 0,
1826 let mut last_hops = last_hops(&nodes);
1827 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();
1828 assert_eq!(route.paths[0].len(), 2);
1830 assert_eq!(route.paths[0][0].pubkey, nodes[3]);
1831 assert_eq!(route.paths[0][0].short_channel_id, 42);
1832 assert_eq!(route.paths[0][0].fee_msat, 0);
1833 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
1834 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
1835 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
1837 assert_eq!(route.paths[0][1].pubkey, nodes[6]);
1838 assert_eq!(route.paths[0][1].short_channel_id, 8);
1839 assert_eq!(route.paths[0][1].fee_msat, 100);
1840 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1841 assert_eq!(route.paths[0][1].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
1842 assert_eq!(route.paths[0][1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
1844 last_hops[0].fees.base_msat = 1000;
1846 // Revert to via 6 as the fee on 8 goes up
1847 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();
1848 assert_eq!(route.paths[0].len(), 4);
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); // fee increased as its % of value transferred across node
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, (7 << 8) | 1);
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[5]);
1865 assert_eq!(route.paths[0][2].short_channel_id, 7);
1866 assert_eq!(route.paths[0][2].fee_msat, 0);
1867 assert_eq!(route.paths[0][2].cltv_expiry_delta, (10 << 8) | 1);
1868 // If we have a peer in the node map, we'll use their features here since we don't have
1869 // a way of figuring out their features from the invoice:
1870 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
1871 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(7));
1873 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
1874 assert_eq!(route.paths[0][3].short_channel_id, 10);
1875 assert_eq!(route.paths[0][3].fee_msat, 100);
1876 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
1877 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
1878 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
1880 // ...but still use 8 for larger payments as 6 has a variable feerate
1881 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();
1882 assert_eq!(route.paths[0].len(), 5);
1884 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
1885 assert_eq!(route.paths[0][0].short_channel_id, 2);
1886 assert_eq!(route.paths[0][0].fee_msat, 3000);
1887 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
1888 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
1889 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
1891 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1892 assert_eq!(route.paths[0][1].short_channel_id, 4);
1893 assert_eq!(route.paths[0][1].fee_msat, 0);
1894 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
1895 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1896 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
1898 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
1899 assert_eq!(route.paths[0][2].short_channel_id, 6);
1900 assert_eq!(route.paths[0][2].fee_msat, 0);
1901 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
1902 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
1903 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
1905 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
1906 assert_eq!(route.paths[0][3].short_channel_id, 11);
1907 assert_eq!(route.paths[0][3].fee_msat, 1000);
1908 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
1909 // If we have a peer in the node map, we'll use their features here since we don't have
1910 // a way of figuring out their features from the invoice:
1911 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
1912 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
1914 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
1915 assert_eq!(route.paths[0][4].short_channel_id, 8);
1916 assert_eq!(route.paths[0][4].fee_msat, 2000);
1917 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
1918 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
1919 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
1923 fn unannounced_path_test() {
1924 // We should be able to send a payment to a destination without any help of a routing graph
1925 // if we have a channel with a common counterparty that appears in the first and last hop
1927 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
1928 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
1929 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
1931 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
1932 let last_hops = vec![RouteHint {
1933 src_node_id: middle_node_id,
1934 short_channel_id: 8,
1937 proportional_millionths: 0,
1939 cltv_expiry_delta: (8 << 8) | 1,
1940 htlc_minimum_msat: None,
1941 htlc_maximum_msat: None,
1943 let our_chans = vec![channelmanager::ChannelDetails {
1944 channel_id: [0; 32],
1945 short_channel_id: Some(42),
1946 remote_network_id: middle_node_id,
1947 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1948 channel_value_satoshis: 100000,
1950 outbound_capacity_msat: 100000,
1951 inbound_capacity_msat: 100000,
1954 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();
1956 assert_eq!(route.paths[0].len(), 2);
1958 assert_eq!(route.paths[0][0].pubkey, middle_node_id);
1959 assert_eq!(route.paths[0][0].short_channel_id, 42);
1960 assert_eq!(route.paths[0][0].fee_msat, 1000);
1961 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
1962 assert_eq!(route.paths[0][0].node_features.le_flags(), &[0b11]);
1963 assert_eq!(route.paths[0][0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
1965 assert_eq!(route.paths[0][1].pubkey, target_node_id);
1966 assert_eq!(route.paths[0][1].short_channel_id, 8);
1967 assert_eq!(route.paths[0][1].fee_msat, 100);
1968 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1969 assert_eq!(route.paths[0][1].node_features.le_flags(), &[0; 0]); // We dont pass flags in from invoices yet
1970 assert_eq!(route.paths[0][1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
1974 fn available_amount_while_routing_test() {
1975 // Tests whether we choose the correct available channel amount while routing.
1977 let (secp_ctx, mut net_graph_msg_handler, chain_monitor, logger) = build_graph();
1978 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1980 // We will use a simple single-path route from
1981 // our node to node2 via node0: channels {1, 3}.
1983 // First disable all other paths.
1984 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1985 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1986 short_channel_id: 2,
1989 cltv_expiry_delta: 0,
1990 htlc_minimum_msat: 0,
1991 htlc_maximum_msat: OptionalField::Present(100_000),
1993 fee_proportional_millionths: 0,
1994 excess_data: Vec::new()
1996 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1997 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1998 short_channel_id: 12,
2001 cltv_expiry_delta: 0,
2002 htlc_minimum_msat: 0,
2003 htlc_maximum_msat: OptionalField::Present(100_000),
2005 fee_proportional_millionths: 0,
2006 excess_data: Vec::new()
2009 // Make the first channel (#1) very permissive,
2010 // and we will be testing all limits on the second channel.
2011 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2012 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2013 short_channel_id: 1,
2016 cltv_expiry_delta: 0,
2017 htlc_minimum_msat: 0,
2018 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2020 fee_proportional_millionths: 0,
2021 excess_data: Vec::new()
2024 // First, let's see if routing works if we have absolutely no idea about the available amount.
2025 // In this case, it should be set to 250_000 sats.
2026 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2027 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2028 short_channel_id: 3,
2031 cltv_expiry_delta: 0,
2032 htlc_minimum_msat: 0,
2033 htlc_maximum_msat: OptionalField::Absent,
2035 fee_proportional_millionths: 0,
2036 excess_data: Vec::new()
2040 // Attempt to route more than available results in a failure.
2041 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)) {
2042 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2043 } else { panic!(); }
2047 // Now, attempt to route an exact amount we have should be fine.
2048 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();
2049 assert_eq!(route.paths.len(), 1);
2050 let path = route.paths.last().unwrap();
2051 assert_eq!(path.len(), 2);
2052 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2053 assert_eq!(path.last().unwrap().fee_msat, 250_000_000);
2056 // Now let's see if routing works if we know only htlc_maximum_msat.
2057 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2058 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2059 short_channel_id: 3,
2062 cltv_expiry_delta: 0,
2063 htlc_minimum_msat: 0,
2064 htlc_maximum_msat: OptionalField::Present(15_000),
2066 fee_proportional_millionths: 0,
2067 excess_data: Vec::new()
2071 // Attempt to route more than available results in a failure.
2072 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)) {
2073 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2074 } else { panic!(); }
2078 // Now, attempt to route an exact amount we have should be fine.
2079 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();
2080 assert_eq!(route.paths.len(), 1);
2081 let path = route.paths.last().unwrap();
2082 assert_eq!(path.len(), 2);
2083 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2084 assert_eq!(path.last().unwrap().fee_msat, 15_000);
2087 // Now let's see if routing works if we know only capacity from the UTXO.
2089 // We can't change UTXO capacity on the fly, so we'll disable
2090 // the existing channel and add another one with the capacity we need.
2091 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2092 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2093 short_channel_id: 3,
2096 cltv_expiry_delta: 0,
2097 htlc_minimum_msat: 0,
2098 htlc_maximum_msat: OptionalField::Absent,
2100 fee_proportional_millionths: 0,
2101 excess_data: Vec::new()
2104 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
2105 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
2106 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
2107 .push_opcode(opcodes::all::OP_PUSHNUM_2)
2108 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
2110 *chain_monitor.utxo_ret.lock().unwrap() = Ok(TxOut { value: 15, script_pubkey: good_script.clone() });
2111 net_graph_msg_handler.add_chain_access(Some(chain_monitor));
2113 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
2114 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2115 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2116 short_channel_id: 333,
2119 cltv_expiry_delta: (3 << 8) | 1,
2120 htlc_minimum_msat: 0,
2121 htlc_maximum_msat: OptionalField::Absent,
2123 fee_proportional_millionths: 0,
2124 excess_data: Vec::new()
2126 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2127 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2128 short_channel_id: 333,
2131 cltv_expiry_delta: (3 << 8) | 2,
2132 htlc_minimum_msat: 0,
2133 htlc_maximum_msat: OptionalField::Absent,
2135 fee_proportional_millionths: 0,
2136 excess_data: Vec::new()
2140 // Attempt to route more than available results in a failure.
2141 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)) {
2142 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2143 } else { panic!(); }
2147 // Now, attempt to route an exact amount we have should be fine.
2148 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();
2149 assert_eq!(route.paths.len(), 1);
2150 let path = route.paths.last().unwrap();
2151 assert_eq!(path.len(), 2);
2152 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2153 assert_eq!(path.last().unwrap().fee_msat, 15_000);
2156 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
2157 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2158 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2159 short_channel_id: 333,
2162 cltv_expiry_delta: 0,
2163 htlc_minimum_msat: 0,
2164 htlc_maximum_msat: OptionalField::Present(10_000),
2166 fee_proportional_millionths: 0,
2167 excess_data: Vec::new()
2171 // Attempt to route more than available results in a failure.
2172 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)) {
2173 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2174 } else { panic!(); }
2178 // Now, attempt to route an exact amount we have should be fine.
2179 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();
2180 assert_eq!(route.paths.len(), 1);
2181 let path = route.paths.last().unwrap();
2182 assert_eq!(path.len(), 2);
2183 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2184 assert_eq!(path.last().unwrap().fee_msat, 10_000);
2189 fn available_liquidity_last_hop_test() {
2190 // Check that available liquidity properly limits the path even when only
2191 // one of the latter hops is limited.
2192 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2193 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2195 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
2196 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
2197 // Total capacity: 50 sats.
2199 // Disable other potential paths.
2200 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2201 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2202 short_channel_id: 2,
2205 cltv_expiry_delta: 0,
2206 htlc_minimum_msat: 0,
2207 htlc_maximum_msat: OptionalField::Present(100_000),
2209 fee_proportional_millionths: 0,
2210 excess_data: Vec::new()
2212 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2213 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2214 short_channel_id: 7,
2217 cltv_expiry_delta: 0,
2218 htlc_minimum_msat: 0,
2219 htlc_maximum_msat: OptionalField::Present(100_000),
2221 fee_proportional_millionths: 0,
2222 excess_data: Vec::new()
2227 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2228 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2229 short_channel_id: 12,
2232 cltv_expiry_delta: 0,
2233 htlc_minimum_msat: 0,
2234 htlc_maximum_msat: OptionalField::Present(100_000),
2236 fee_proportional_millionths: 0,
2237 excess_data: Vec::new()
2239 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2240 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2241 short_channel_id: 13,
2244 cltv_expiry_delta: 0,
2245 htlc_minimum_msat: 0,
2246 htlc_maximum_msat: OptionalField::Present(100_000),
2248 fee_proportional_millionths: 0,
2249 excess_data: Vec::new()
2252 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2253 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2254 short_channel_id: 6,
2257 cltv_expiry_delta: 0,
2258 htlc_minimum_msat: 0,
2259 htlc_maximum_msat: OptionalField::Present(50_000),
2261 fee_proportional_millionths: 0,
2262 excess_data: Vec::new()
2264 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
2265 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2266 short_channel_id: 11,
2269 cltv_expiry_delta: 0,
2270 htlc_minimum_msat: 0,
2271 htlc_maximum_msat: OptionalField::Present(100_000),
2273 fee_proportional_millionths: 0,
2274 excess_data: Vec::new()
2277 // Attempt to route more than available results in a failure.
2278 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)) {
2279 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2280 } else { panic!(); }
2284 // Now, attempt to route 49 sats (just a bit below the capacity).
2285 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();
2286 assert_eq!(route.paths.len(), 1);
2287 let mut total_amount_paid_msat = 0;
2288 for path in &route.paths {
2289 assert_eq!(path.len(), 4);
2290 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
2291 total_amount_paid_msat += path.last().unwrap().fee_msat;
2293 assert_eq!(total_amount_paid_msat, 49_000);
2297 // Attempt to route an exact amount is also fine
2298 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();
2299 assert_eq!(route.paths.len(), 1);
2300 let mut total_amount_paid_msat = 0;
2301 for path in &route.paths {
2302 assert_eq!(path.len(), 4);
2303 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
2304 total_amount_paid_msat += path.last().unwrap().fee_msat;
2306 assert_eq!(total_amount_paid_msat, 50_000);
2311 fn ignore_fee_first_hop_test() {
2312 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2313 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2315 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
2316 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2317 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2318 short_channel_id: 1,
2321 cltv_expiry_delta: 0,
2322 htlc_minimum_msat: 0,
2323 htlc_maximum_msat: OptionalField::Present(100_000),
2324 fee_base_msat: 1_000_000,
2325 fee_proportional_millionths: 0,
2326 excess_data: Vec::new()
2328 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2329 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2330 short_channel_id: 3,
2333 cltv_expiry_delta: 0,
2334 htlc_minimum_msat: 0,
2335 htlc_maximum_msat: OptionalField::Present(50_000),
2337 fee_proportional_millionths: 0,
2338 excess_data: Vec::new()
2342 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();
2343 assert_eq!(route.paths.len(), 1);
2344 let mut total_amount_paid_msat = 0;
2345 for path in &route.paths {
2346 assert_eq!(path.len(), 2);
2347 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2348 total_amount_paid_msat += path.last().unwrap().fee_msat;
2350 assert_eq!(total_amount_paid_msat, 50_000);
2355 fn simple_mpp_route_test() {
2356 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2357 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2359 // We need a route consisting of 3 paths:
2360 // From our node to node2 via node0, node7, node1 (three paths one hop each).
2361 // To achieve this, the amount being transferred should be around
2362 // the total capacity of these 3 paths.
2364 // First, we set limits on these (previously unlimited) channels.
2365 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
2367 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
2368 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2369 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2370 short_channel_id: 1,
2373 cltv_expiry_delta: 0,
2374 htlc_minimum_msat: 0,
2375 htlc_maximum_msat: OptionalField::Present(100_000),
2377 fee_proportional_millionths: 0,
2378 excess_data: Vec::new()
2380 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2381 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2382 short_channel_id: 3,
2385 cltv_expiry_delta: 0,
2386 htlc_minimum_msat: 0,
2387 htlc_maximum_msat: OptionalField::Present(50_000),
2389 fee_proportional_millionths: 0,
2390 excess_data: Vec::new()
2393 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
2394 // (total limit 60).
2395 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2396 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2397 short_channel_id: 12,
2400 cltv_expiry_delta: 0,
2401 htlc_minimum_msat: 0,
2402 htlc_maximum_msat: OptionalField::Present(60_000),
2404 fee_proportional_millionths: 0,
2405 excess_data: Vec::new()
2407 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2408 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2409 short_channel_id: 13,
2412 cltv_expiry_delta: 0,
2413 htlc_minimum_msat: 0,
2414 htlc_maximum_msat: OptionalField::Present(60_000),
2416 fee_proportional_millionths: 0,
2417 excess_data: Vec::new()
2420 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
2421 // (total capacity 180 sats).
2422 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2423 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2424 short_channel_id: 2,
2427 cltv_expiry_delta: 0,
2428 htlc_minimum_msat: 0,
2429 htlc_maximum_msat: OptionalField::Present(200_000),
2431 fee_proportional_millionths: 0,
2432 excess_data: Vec::new()
2434 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2435 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2436 short_channel_id: 4,
2439 cltv_expiry_delta: 0,
2440 htlc_minimum_msat: 0,
2441 htlc_maximum_msat: OptionalField::Present(180_000),
2443 fee_proportional_millionths: 0,
2444 excess_data: Vec::new()
2448 // Attempt to route more than available results in a failure.
2449 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)) {
2450 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2451 } else { panic!(); }
2455 // Now, attempt to route 250 sats (just a bit below the capacity).
2456 // Our algorithm should provide us with these 3 paths.
2457 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();
2458 assert_eq!(route.paths.len(), 3);
2459 let mut total_amount_paid_msat = 0;
2460 for path in &route.paths {
2461 assert_eq!(path.len(), 2);
2462 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2463 total_amount_paid_msat += path.last().unwrap().fee_msat;
2465 assert_eq!(total_amount_paid_msat, 250_000);
2469 // Attempt to route an exact amount is also fine
2470 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();
2471 assert_eq!(route.paths.len(), 3);
2472 let mut total_amount_paid_msat = 0;
2473 for path in &route.paths {
2474 assert_eq!(path.len(), 2);
2475 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2476 total_amount_paid_msat += path.last().unwrap().fee_msat;
2478 assert_eq!(total_amount_paid_msat, 290_000);
2483 fn long_mpp_route_test() {
2484 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2485 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2487 // We need a route consisting of 3 paths:
2488 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
2489 // Note that these paths overlap (channels 5, 12, 13).
2490 // We will route 300 sats.
2491 // Each path will have 100 sats capacity, those channels which
2492 // are used twice will have 200 sats capacity.
2494 // Disable other potential paths.
2495 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2496 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2497 short_channel_id: 2,
2500 cltv_expiry_delta: 0,
2501 htlc_minimum_msat: 0,
2502 htlc_maximum_msat: OptionalField::Present(100_000),
2504 fee_proportional_millionths: 0,
2505 excess_data: Vec::new()
2507 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2508 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2509 short_channel_id: 7,
2512 cltv_expiry_delta: 0,
2513 htlc_minimum_msat: 0,
2514 htlc_maximum_msat: OptionalField::Present(100_000),
2516 fee_proportional_millionths: 0,
2517 excess_data: Vec::new()
2520 // Path via {node0, node2} is channels {1, 3, 5}.
2521 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2522 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2523 short_channel_id: 1,
2526 cltv_expiry_delta: 0,
2527 htlc_minimum_msat: 0,
2528 htlc_maximum_msat: OptionalField::Present(100_000),
2530 fee_proportional_millionths: 0,
2531 excess_data: Vec::new()
2533 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2534 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2535 short_channel_id: 3,
2538 cltv_expiry_delta: 0,
2539 htlc_minimum_msat: 0,
2540 htlc_maximum_msat: OptionalField::Present(100_000),
2542 fee_proportional_millionths: 0,
2543 excess_data: Vec::new()
2546 // Capacity of 200 sats because this channel will be used by 3rd path as well.
2547 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
2548 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2549 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2550 short_channel_id: 5,
2553 cltv_expiry_delta: 0,
2554 htlc_minimum_msat: 0,
2555 htlc_maximum_msat: OptionalField::Present(200_000),
2557 fee_proportional_millionths: 0,
2558 excess_data: Vec::new()
2561 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
2562 // Add 100 sats to the capacities of {12, 13}, because these channels
2563 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
2564 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2565 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2566 short_channel_id: 12,
2569 cltv_expiry_delta: 0,
2570 htlc_minimum_msat: 0,
2571 htlc_maximum_msat: OptionalField::Present(200_000),
2573 fee_proportional_millionths: 0,
2574 excess_data: Vec::new()
2576 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2577 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2578 short_channel_id: 13,
2581 cltv_expiry_delta: 0,
2582 htlc_minimum_msat: 0,
2583 htlc_maximum_msat: OptionalField::Present(200_000),
2585 fee_proportional_millionths: 0,
2586 excess_data: Vec::new()
2589 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2590 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2591 short_channel_id: 6,
2594 cltv_expiry_delta: 0,
2595 htlc_minimum_msat: 0,
2596 htlc_maximum_msat: OptionalField::Present(100_000),
2598 fee_proportional_millionths: 0,
2599 excess_data: Vec::new()
2601 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
2602 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2603 short_channel_id: 11,
2606 cltv_expiry_delta: 0,
2607 htlc_minimum_msat: 0,
2608 htlc_maximum_msat: OptionalField::Present(100_000),
2610 fee_proportional_millionths: 0,
2611 excess_data: Vec::new()
2614 // Path via {node7, node2} is channels {12, 13, 5}.
2615 // We already limited them to 200 sats (they are used twice for 100 sats).
2616 // Nothing to do here.
2619 // Attempt to route more than available results in a failure.
2620 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)) {
2621 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2622 } else { panic!(); }
2626 // Now, attempt to route 300 sats (exact amount we can route).
2627 // Our algorithm should provide us with these 3 paths, 100 sats each.
2628 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();
2629 assert_eq!(route.paths.len(), 3);
2631 let mut total_amount_paid_msat = 0;
2632 for path in &route.paths {
2633 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
2634 total_amount_paid_msat += path.last().unwrap().fee_msat;
2636 assert_eq!(total_amount_paid_msat, 300_000);
2642 fn mpp_cheaper_route_test() {
2643 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2644 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2646 // This test checks that if we have two cheaper paths and one more expensive path,
2647 // so that liquidity-wise any 2 of 3 combination is sufficient,
2648 // two cheaper paths will be taken.
2649 // These paths have equal available liquidity.
2651 // We need a combination of 3 paths:
2652 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
2653 // Note that these paths overlap (channels 5, 12, 13).
2654 // Each path will have 100 sats capacity, those channels which
2655 // are used twice will have 200 sats capacity.
2657 // Disable other potential paths.
2658 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2659 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2660 short_channel_id: 2,
2663 cltv_expiry_delta: 0,
2664 htlc_minimum_msat: 0,
2665 htlc_maximum_msat: OptionalField::Present(100_000),
2667 fee_proportional_millionths: 0,
2668 excess_data: Vec::new()
2670 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2671 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2672 short_channel_id: 7,
2675 cltv_expiry_delta: 0,
2676 htlc_minimum_msat: 0,
2677 htlc_maximum_msat: OptionalField::Present(100_000),
2679 fee_proportional_millionths: 0,
2680 excess_data: Vec::new()
2683 // Path via {node0, node2} is channels {1, 3, 5}.
2684 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2685 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2686 short_channel_id: 1,
2689 cltv_expiry_delta: 0,
2690 htlc_minimum_msat: 0,
2691 htlc_maximum_msat: OptionalField::Present(100_000),
2693 fee_proportional_millionths: 0,
2694 excess_data: Vec::new()
2696 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2697 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2698 short_channel_id: 3,
2701 cltv_expiry_delta: 0,
2702 htlc_minimum_msat: 0,
2703 htlc_maximum_msat: OptionalField::Present(100_000),
2705 fee_proportional_millionths: 0,
2706 excess_data: Vec::new()
2709 // Capacity of 200 sats because this channel will be used by 3rd path as well.
2710 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
2711 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2712 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2713 short_channel_id: 5,
2716 cltv_expiry_delta: 0,
2717 htlc_minimum_msat: 0,
2718 htlc_maximum_msat: OptionalField::Present(200_000),
2720 fee_proportional_millionths: 0,
2721 excess_data: Vec::new()
2724 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
2725 // Add 100 sats to the capacities of {12, 13}, because these channels
2726 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
2727 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2728 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2729 short_channel_id: 12,
2732 cltv_expiry_delta: 0,
2733 htlc_minimum_msat: 0,
2734 htlc_maximum_msat: OptionalField::Present(200_000),
2736 fee_proportional_millionths: 0,
2737 excess_data: Vec::new()
2739 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2740 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2741 short_channel_id: 13,
2744 cltv_expiry_delta: 0,
2745 htlc_minimum_msat: 0,
2746 htlc_maximum_msat: OptionalField::Present(200_000),
2748 fee_proportional_millionths: 0,
2749 excess_data: Vec::new()
2752 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2753 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2754 short_channel_id: 6,
2757 cltv_expiry_delta: 0,
2758 htlc_minimum_msat: 0,
2759 htlc_maximum_msat: OptionalField::Present(100_000),
2760 fee_base_msat: 1_000,
2761 fee_proportional_millionths: 0,
2762 excess_data: Vec::new()
2764 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
2765 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2766 short_channel_id: 11,
2769 cltv_expiry_delta: 0,
2770 htlc_minimum_msat: 0,
2771 htlc_maximum_msat: OptionalField::Present(100_000),
2773 fee_proportional_millionths: 0,
2774 excess_data: Vec::new()
2777 // Path via {node7, node2} is channels {12, 13, 5}.
2778 // We already limited them to 200 sats (they are used twice for 100 sats).
2779 // Nothing to do here.
2782 // Now, attempt to route 180 sats.
2783 // Our algorithm should provide us with these 2 paths.
2784 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();
2785 assert_eq!(route.paths.len(), 2);
2787 let mut total_value_transferred_msat = 0;
2788 let mut total_paid_msat = 0;
2789 for path in &route.paths {
2790 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
2791 total_value_transferred_msat += path.last().unwrap().fee_msat;
2793 total_paid_msat += hop.fee_msat;
2796 // If we paid fee, this would be higher.
2797 assert_eq!(total_value_transferred_msat, 180_000);
2798 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
2799 assert_eq!(total_fees_paid, 0);
2804 fn fees_on_mpp_route_test() {
2805 // This test makes sure that MPP algorithm properly takes into account
2806 // fees charged on the channels, by making the fees impactful:
2807 // if the fee is not properly accounted for, the behavior is different.
2808 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2809 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2811 // We need a route consisting of 2 paths:
2812 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
2813 // We will route 200 sats, Each path will have 100 sats capacity.
2815 // This test is not particularly stable: e.g.,
2816 // there's a way to route via {node0, node2, node4}.
2817 // It works while pathfinding is deterministic, but can be broken otherwise.
2818 // It's fine to ignore this concern for now.
2820 // Disable other potential paths.
2821 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2822 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2823 short_channel_id: 2,
2826 cltv_expiry_delta: 0,
2827 htlc_minimum_msat: 0,
2828 htlc_maximum_msat: OptionalField::Present(100_000),
2830 fee_proportional_millionths: 0,
2831 excess_data: Vec::new()
2834 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2835 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2836 short_channel_id: 7,
2839 cltv_expiry_delta: 0,
2840 htlc_minimum_msat: 0,
2841 htlc_maximum_msat: OptionalField::Present(100_000),
2843 fee_proportional_millionths: 0,
2844 excess_data: Vec::new()
2847 // Path via {node0, node2} is channels {1, 3, 5}.
2848 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2849 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2850 short_channel_id: 1,
2853 cltv_expiry_delta: 0,
2854 htlc_minimum_msat: 0,
2855 htlc_maximum_msat: OptionalField::Present(100_000),
2857 fee_proportional_millionths: 0,
2858 excess_data: Vec::new()
2860 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2861 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2862 short_channel_id: 3,
2865 cltv_expiry_delta: 0,
2866 htlc_minimum_msat: 0,
2867 htlc_maximum_msat: OptionalField::Present(100_000),
2869 fee_proportional_millionths: 0,
2870 excess_data: Vec::new()
2873 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
2874 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2875 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2876 short_channel_id: 5,
2879 cltv_expiry_delta: 0,
2880 htlc_minimum_msat: 0,
2881 htlc_maximum_msat: OptionalField::Present(100_000),
2883 fee_proportional_millionths: 0,
2884 excess_data: Vec::new()
2887 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
2888 // All channels should be 100 sats capacity. But for the fee experiment,
2889 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
2890 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
2891 // 100 sats (and pay 150 sats in fees for the use of channel 6),
2892 // so no matter how large are other channels,
2893 // the whole path will be limited by 100 sats with just these 2 conditions:
2894 // - channel 12 capacity is 250 sats
2895 // - fee for channel 6 is 150 sats
2896 // Let's test this by enforcing these 2 conditions and removing other limits.
2897 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2898 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2899 short_channel_id: 12,
2902 cltv_expiry_delta: 0,
2903 htlc_minimum_msat: 0,
2904 htlc_maximum_msat: OptionalField::Present(250_000),
2906 fee_proportional_millionths: 0,
2907 excess_data: Vec::new()
2909 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2910 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2911 short_channel_id: 13,
2914 cltv_expiry_delta: 0,
2915 htlc_minimum_msat: 0,
2916 htlc_maximum_msat: OptionalField::Absent,
2918 fee_proportional_millionths: 0,
2919 excess_data: Vec::new()
2922 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2923 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2924 short_channel_id: 6,
2927 cltv_expiry_delta: 0,
2928 htlc_minimum_msat: 0,
2929 htlc_maximum_msat: OptionalField::Absent,
2930 fee_base_msat: 150_000,
2931 fee_proportional_millionths: 0,
2932 excess_data: Vec::new()
2934 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
2935 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2936 short_channel_id: 11,
2939 cltv_expiry_delta: 0,
2940 htlc_minimum_msat: 0,
2941 htlc_maximum_msat: OptionalField::Absent,
2943 fee_proportional_millionths: 0,
2944 excess_data: Vec::new()
2948 // Attempt to route more than available results in a failure.
2949 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)) {
2950 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2951 } else { panic!(); }
2955 // Now, attempt to route 200 sats (exact amount we can route).
2956 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();
2957 assert_eq!(route.paths.len(), 2);
2959 let mut total_amount_paid_msat = 0;
2960 for path in &route.paths {
2961 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
2962 total_amount_paid_msat += path.last().unwrap().fee_msat;
2964 assert_eq!(total_amount_paid_msat, 200_000);
2970 fn drop_lowest_channel_mpp_route_test() {
2971 // This test checks that low-capacity channel is dropped when after
2972 // path finding we realize that we found more capacity than we need.
2973 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2974 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2976 // We need a route consisting of 3 paths:
2977 // From our node to node2 via node0, node7, node1 (three paths one hop each).
2979 // The first and the second paths should be sufficient, but the third should be
2980 // cheaper, so that we select it but drop later.
2982 // First, we set limits on these (previously unlimited) channels.
2983 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
2985 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
2986 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2987 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2988 short_channel_id: 1,
2991 cltv_expiry_delta: 0,
2992 htlc_minimum_msat: 0,
2993 htlc_maximum_msat: OptionalField::Present(100_000),
2995 fee_proportional_millionths: 0,
2996 excess_data: Vec::new()
2998 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2999 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3000 short_channel_id: 3,
3003 cltv_expiry_delta: 0,
3004 htlc_minimum_msat: 0,
3005 htlc_maximum_msat: OptionalField::Present(50_000),
3007 fee_proportional_millionths: 0,
3008 excess_data: Vec::new()
3011 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
3012 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3013 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3014 short_channel_id: 12,
3017 cltv_expiry_delta: 0,
3018 htlc_minimum_msat: 0,
3019 htlc_maximum_msat: OptionalField::Present(60_000),
3021 fee_proportional_millionths: 0,
3022 excess_data: Vec::new()
3024 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3025 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3026 short_channel_id: 13,
3029 cltv_expiry_delta: 0,
3030 htlc_minimum_msat: 0,
3031 htlc_maximum_msat: OptionalField::Present(60_000),
3033 fee_proportional_millionths: 0,
3034 excess_data: Vec::new()
3037 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
3038 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3039 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3040 short_channel_id: 2,
3043 cltv_expiry_delta: 0,
3044 htlc_minimum_msat: 0,
3045 htlc_maximum_msat: OptionalField::Present(20_000),
3047 fee_proportional_millionths: 0,
3048 excess_data: Vec::new()
3050 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3051 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3052 short_channel_id: 4,
3055 cltv_expiry_delta: 0,
3056 htlc_minimum_msat: 0,
3057 htlc_maximum_msat: OptionalField::Present(20_000),
3059 fee_proportional_millionths: 0,
3060 excess_data: Vec::new()
3064 // Attempt to route more than available results in a failure.
3065 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)) {
3066 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3067 } else { panic!(); }
3071 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
3072 // Our algorithm should provide us with these 3 paths.
3073 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();
3074 assert_eq!(route.paths.len(), 3);
3075 let mut total_amount_paid_msat = 0;
3076 for path in &route.paths {
3077 assert_eq!(path.len(), 2);
3078 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3079 total_amount_paid_msat += path.last().unwrap().fee_msat;
3081 assert_eq!(total_amount_paid_msat, 125_000);
3085 // Attempt to route without the last small cheap channel
3086 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();
3087 assert_eq!(route.paths.len(), 2);
3088 let mut total_amount_paid_msat = 0;
3089 for path in &route.paths {
3090 assert_eq!(path.len(), 2);
3091 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3092 total_amount_paid_msat += path.last().unwrap().fee_msat;
3094 assert_eq!(total_amount_paid_msat, 90_000);