1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! The top-level routing/network map tracking logic lives here.
12 //! You probably want to create a NetGraphMsgHandler and use that as your RoutingMessageHandler and then
13 //! interrogate it to get routes for your own payments.
15 use bitcoin::secp256k1::key::PublicKey;
17 use ln::channelmanager::ChannelDetails;
18 use ln::features::{ChannelFeatures, InvoiceFeatures, NodeFeatures};
19 use ln::msgs::{DecodeError, ErrorAction, LightningError, MAX_VALUE_MSAT};
20 use routing::network_graph::{NetworkGraph, RoutingFees};
21 use util::ser::{Writeable, Readable};
22 use util::logger::Logger;
25 use std::collections::{HashMap, BinaryHeap};
29 #[derive(Clone, PartialEq)]
31 /// The node_id of the node at this hop.
32 pub pubkey: PublicKey,
33 /// The node_announcement features of the node at this hop. For the last hop, these may be
34 /// amended to match the features present in the invoice this node generated.
35 pub node_features: NodeFeatures,
36 /// The channel that should be used from the previous hop to reach this node.
37 pub short_channel_id: u64,
38 /// The channel_announcement features of the channel that should be used from the previous hop
39 /// to reach this node.
40 pub channel_features: ChannelFeatures,
41 /// The fee taken on this hop (for paying for the use of the *next* channel in the path).
42 /// For the last hop, this should be the full value of the payment (might be more than
43 /// requested if we had to match htlc_minimum_msat).
45 /// The CLTV delta added for this hop. For the last hop, this should be the full CLTV value
46 /// expected at the destination, in excess of the current block height.
47 pub cltv_expiry_delta: u32,
51 impl Writeable for Vec<RouteHop> {
52 fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
53 (self.len() as u8).write(writer)?;
54 for hop in self.iter() {
55 hop.pubkey.write(writer)?;
56 hop.node_features.write(writer)?;
57 hop.short_channel_id.write(writer)?;
58 hop.channel_features.write(writer)?;
59 hop.fee_msat.write(writer)?;
60 hop.cltv_expiry_delta.write(writer)?;
67 impl Readable for Vec<RouteHop> {
68 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Vec<RouteHop>, DecodeError> {
69 let hops_count: u8 = Readable::read(reader)?;
70 let mut hops = Vec::with_capacity(hops_count as usize);
71 for _ in 0..hops_count {
73 pubkey: Readable::read(reader)?,
74 node_features: Readable::read(reader)?,
75 short_channel_id: Readable::read(reader)?,
76 channel_features: Readable::read(reader)?,
77 fee_msat: Readable::read(reader)?,
78 cltv_expiry_delta: Readable::read(reader)?,
85 /// A route directs a payment from the sender (us) to the recipient. If the recipient supports MPP,
86 /// it can take multiple paths. Each path is composed of one or more hops through the network.
87 #[derive(Clone, PartialEq)]
89 /// The list of routes taken for a single (potentially-)multi-part payment. The pubkey of the
90 /// last RouteHop in each path must be the same.
91 /// Each entry represents a list of hops, NOT INCLUDING our own, where the last hop is the
92 /// destination. Thus, this must always be at least length one. While the maximum length of any
93 /// given path is variable, keeping the length of any path to less than 20 should currently
94 /// ensure it is viable.
95 pub paths: Vec<Vec<RouteHop>>,
98 impl Writeable for Route {
99 fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
100 (self.paths.len() as u64).write(writer)?;
101 for hops in self.paths.iter() {
108 impl Readable for Route {
109 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
110 let path_count: u64 = Readable::read(reader)?;
111 let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
112 for _ in 0..path_count {
113 paths.push(Readable::read(reader)?);
119 /// A channel descriptor which provides a last-hop route to get_route
121 pub struct RouteHint {
122 /// The node_id of the non-target end of the route
123 pub src_node_id: PublicKey,
124 /// The short_channel_id of this channel
125 pub short_channel_id: u64,
126 /// The fees which must be paid to use this channel
127 pub fees: RoutingFees,
128 /// The difference in CLTV values between this node and the next node.
129 pub cltv_expiry_delta: u16,
130 /// The minimum value, in msat, which must be relayed to the next hop.
131 pub htlc_minimum_msat: Option<u64>,
132 /// The maximum value in msat available for routing with a single HTLC.
133 pub htlc_maximum_msat: Option<u64>,
136 #[derive(Eq, PartialEq)]
137 struct RouteGraphNode {
139 lowest_fee_to_peer_through_node: u64,
140 lowest_fee_to_node: u64,
141 // The maximum value a yet-to-be-constructed payment path might flow through this node.
142 // This value is upper-bounded by us by:
143 // - how much is needed for a path being constructed
144 // - how much value can channels following this node (up to the destination) can contribute,
145 // considering their capacity and fees
146 value_contribution_msat: u64
149 impl cmp::Ord for RouteGraphNode {
150 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
151 other.lowest_fee_to_peer_through_node.cmp(&self.lowest_fee_to_peer_through_node)
152 .then_with(|| other.pubkey.serialize().cmp(&self.pubkey.serialize()))
156 impl cmp::PartialOrd for RouteGraphNode {
157 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
158 Some(self.cmp(other))
162 struct DummyDirectionalChannelInfo {
163 cltv_expiry_delta: u32,
164 htlc_minimum_msat: u64,
165 htlc_maximum_msat: Option<u64>,
169 /// It's useful to keep track of the hops associated with the fees required to use them,
170 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
171 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
172 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
174 struct PathBuildingHop {
175 /// Hop-specific details unrelated to the path during the routing phase,
176 /// but rather relevant to the LN graph.
178 /// Minimal fees required to route to the source node of the current hop via any of its inbound channels.
179 src_lowest_inbound_fees: RoutingFees,
180 /// Fees of the channel used in this hop.
181 channel_fees: RoutingFees,
182 /// All the fees paid *after* this channel on the way to the destination
183 next_hops_fee_msat: u64,
184 /// Fee paid for the use of the current channel (see channel_fees).
185 /// The value will be actually deducted from the counterparty balance on the previous link.
186 hop_use_fee_msat: u64,
187 /// Used to compare channels when choosing the for routing.
188 /// Includes paying for the use of a hop and the following hops, as well as
189 /// an estimated cost of reaching this hop.
190 /// Might get stale when fees are recomputed. Primarily for internal use.
192 /// This is useful for update_value_and_recompute_fees to make sure
193 /// we don't fall below the minimum. Should not be updated manually and
194 /// generally should not be accessed.
195 htlc_minimum_msat: u64,
198 // Instantiated with a list of hops with correct data in them collected during path finding,
199 // an instance of this struct should be further modified only via given methods.
202 hops: Vec<PathBuildingHop>,
207 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
208 fn get_value_msat(&self) -> u64 {
209 self.hops.last().unwrap().route_hop.fee_msat
212 fn get_total_fee_paid_msat(&self) -> u64 {
213 if self.hops.len() < 1 {
217 // Can't use next_hops_fee_msat because it gets outdated.
218 for (i, hop) in self.hops.iter().enumerate() {
219 if i != self.hops.len() - 1 {
220 result += hop.route_hop.fee_msat;
226 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
227 // to change fees may result in an inconsistency.
229 // Sometimes we call this function right after constructing a path which has inconsistent
230 // (in terms of reaching htlc_minimum_msat), so that this function puts the fees in order.
231 // In that case we call it on the "same" amount we initially allocated for this path, and which
232 // could have been reduced on the way. In that case, there is also a risk of exceeding
233 // available_liquidity inside this function, because the function is unaware of this bound.
234 // In our specific recomputation cases where we never increase the value the risk is pretty low.
235 // This function, however, does not support arbitrarily increasing the value being transferred,
236 // and the exception will be triggered.
237 fn update_value_and_recompute_fees(&mut self, value_msat: u64) {
238 assert!(value_msat <= self.hops.last().unwrap().route_hop.fee_msat);
240 let mut total_fee_paid_msat = 0 as u64;
241 for i in (0..self.hops.len()).rev() {
242 let last_hop = i == self.hops.len() - 1;
244 // For non-last-hop, this value will represent the fees paid on the current hop. It
245 // will consist of the fees for the use of the next hop, and extra fees to match
246 // htlc_minimum_msat of the current channel. Last hop is handled separately.
247 let mut cur_hop_fees_msat = 0;
249 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().hop_use_fee_msat;
252 let mut cur_hop = self.hops.get_mut(i).unwrap();
253 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
254 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
255 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
256 // set it too high just to maliciously take more fees by exploiting this
257 // match htlc_minimum_msat logic.
258 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
259 if let Some(extra_fees_msat) = cur_hop.htlc_minimum_msat.checked_sub(cur_hop_transferred_amount_msat) {
260 // Note that there is a risk that *previous hops* (those closer to us, as we go
261 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
263 // This might make us end up with a broken route, although this should be super-rare
264 // in practice, both because of how healthy channels look like, and how we pick
265 // channels in add_entry.
266 // Also, this can't be exploited more heavily than *announce a free path and fail
268 cur_hop_transferred_amount_msat += extra_fees_msat;
269 total_fee_paid_msat += extra_fees_msat;
270 cur_hop_fees_msat += extra_fees_msat;
274 // Final hop is a special case: it usually has just value_msat (by design), but also
275 // it still could overpay for the htlc_minimum_msat.
276 cur_hop.route_hop.fee_msat = cur_hop_transferred_amount_msat;
278 // Propagate updated fees for the use of the channels to one hop back, where they
279 // will be actually paid (fee_msat). The last hop is handled above separately.
280 cur_hop.route_hop.fee_msat = cur_hop_fees_msat;
283 // Fee for the use of the current hop which will be deducted on the previous hop.
284 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
285 // this channel is free for us.
287 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.channel_fees) {
288 cur_hop.hop_use_fee_msat = new_fee;
289 total_fee_paid_msat += new_fee;
291 // It should not be possible because this function is called only to reduce the
292 // value. In that case, compute_fee was already called with the same fees for
293 // larger amount and there was no overflow.
301 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
302 let proportional_fee_millions =
303 amount_msat.checked_mul(channel_fees.proportional_millionths as u64);
304 if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
305 (channel_fees.base_msat as u64).checked_add(part / 1_000_000) }) {
309 // This function may be (indirectly) called without any verification,
310 // with channel_fees provided by a caller. We should handle it gracefully.
315 /// Gets a route from us (payer) to the given target node (payee).
317 /// If the payee provided features in their invoice, they should be provided via payee_features.
318 /// Without this, MPP will only be used if the payee's features are available in the network graph.
320 /// Extra routing hops between known nodes and the target will be used if they are included in
323 /// If some channels aren't announced, it may be useful to fill in a first_hops with the
324 /// results from a local ChannelManager::list_usable_channels() call. If it is filled in, our
325 /// view of our local channels (from net_graph_msg_handler) will be ignored, and only those
326 /// in first_hops will be used.
328 /// Panics if first_hops contains channels without short_channel_ids
329 /// (ChannelManager::list_usable_channels will never include such channels).
331 /// The fees on channels from us to next-hops are ignored (as they are assumed to all be
332 /// equal), however the enabled/disabled bit on such channels as well as the
333 /// htlc_minimum_msat/htlc_maximum_msat *are* checked as they may change based on the receiving node.
334 pub fn get_route<L: Deref>(our_node_id: &PublicKey, network: &NetworkGraph, payee: &PublicKey, payee_features: Option<InvoiceFeatures>, first_hops: Option<&[&ChannelDetails]>,
335 last_hops: &[&RouteHint], final_value_msat: u64, final_cltv: u32, logger: L) -> Result<Route, LightningError> where L::Target: Logger {
336 // TODO: Obviously *only* using total fee cost sucks. We should consider weighting by
337 // uptime/success in using a node in the past.
338 if *payee == *our_node_id {
339 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
342 if final_value_msat > MAX_VALUE_MSAT {
343 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
346 if final_value_msat == 0 {
347 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
350 for last_hop in last_hops {
351 if last_hop.src_node_id == *payee {
352 return Err(LightningError{err: "Last hop cannot have a payee as a source.".to_owned(), action: ErrorAction::IgnoreError});
356 // The general routing idea is the following:
357 // 1. Fill first/last hops communicated by the caller.
358 // 2. Attempt to construct a path from payer to payee for transferring
359 // any ~sufficient (described later) value.
360 // If succeed, remember which channels were used and how much liquidity they have available,
361 // so that future paths don't rely on the same liquidity.
362 // 3. Prooceed to the next step if:
363 // - we hit the recommended target value;
364 // - OR if we could not construct a new path. Any next attempt will fail too.
365 // Otherwise, repeat step 2.
366 // 4. See if we managed to collect paths which aggregately are able to transfer target value
367 // (not recommended value). If yes, proceed. If not, fail routing.
368 // 5. Randomly combine paths into routes having enough to fulfill the payment. (TODO: knapsack)
369 // 6. Of all the found paths, select only those with the lowest total fee.
370 // 7. The last path in every selected route is likely to be more than we need.
371 // Reduce its value-to-transfer and recompute fees.
372 // 8. Choose the best route by the lowest total fee.
374 // As for the actual search algorithm,
375 // we do a payee-to-payer pseudo-Dijkstra's sorting by each node's distance from the payee
376 // plus the minimum per-HTLC fee to get from it to another node (aka "shitty pseudo-A*").
378 // We are not a faithful Dijkstra's implementation because we can change values which impact
379 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
380 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) then
381 // the value we are currently attempting to send over a path, we simply reduce the value being
382 // sent along the path for any hops after that channel. This may imply that later fees (which
383 // we've already tabulated) are lower because a smaller value is passing through the channels
384 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
385 // channels which were selected earlier (and which may still be used for other paths without a
386 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
389 // One potentially problematic case for this algorithm would be if there are many
390 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
391 // graph walking), we may never find a path which is not liquidity-limited and has lower
392 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
393 // Because we only consider paths with at least 5% of the total value being sent, the damage
394 // from such a case should be limited, however this could be further reduced in the future by
395 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
396 // limits for the purposes of fee calculation.
398 // Alternatively, we could store more detailed path information in the heap (targets, below)
399 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
400 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
401 // and practically (as we would need to store dynamically-allocated path information in heap
402 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
403 // results of such an algorithm would likely be biased towards lower-value paths.
405 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
406 // outside of our current search value, running a path search more times to gather candidate
407 // paths at different values. While this may be acceptable, further path searches may increase
408 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
409 // graph for candidate paths, calculating the maximum value which can realistically be sent at
410 // the same time, remaining generic across different payment values.
412 // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
413 // to use as the A* heuristic beyond just the cost to get one node further than the current
416 let dummy_directional_info = DummyDirectionalChannelInfo { // used for first_hops routes
417 cltv_expiry_delta: 0,
418 htlc_minimum_msat: 0,
419 htlc_maximum_msat: None,
422 proportional_millionths: 0,
426 let mut targets = BinaryHeap::new(); //TODO: Do we care about switching to eg Fibbonaci heap?
427 let mut dist = HashMap::with_capacity(network.get_nodes().len());
429 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
430 // indicating that we may wish to try again with a higher value, potentially paying to meet an
431 // htlc_minimum with extra fees while still finding a cheaper path.
432 let mut hit_minimum_limit;
434 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
435 // We start with a path_value of the exact amount we want, and if that generates a route we may
436 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
437 // amount we want in total across paths, selecting the best subset at the end.
438 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
439 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
440 let mut path_value_msat = final_value_msat;
442 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
443 // it. If the payee supports it they're supposed to include it in the invoice, so that should
445 let allow_mpp = if let Some(features) = &payee_features {
446 features.supports_basic_mpp()
447 } else if let Some(node) = network.get_nodes().get(&payee) {
448 if let Some(node_info) = node.announcement_info.as_ref() {
449 node_info.features.supports_basic_mpp()
454 // Prepare the data we'll use for payee-to-payer search by
455 // inserting first hops suggested by the caller as targets.
456 // Our search will then attempt to reach them while traversing from the payee node.
457 let mut first_hop_targets = HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
458 if let Some(hops) = first_hops {
460 let short_channel_id = chan.short_channel_id.expect("first_hops should be filled in with usable channels, not pending ones");
461 if chan.remote_network_id == *our_node_id {
462 return Err(LightningError{err: "First hop cannot have our_node_id as a destination.".to_owned(), action: ErrorAction::IgnoreError});
464 first_hop_targets.insert(chan.remote_network_id, (short_channel_id, chan.counterparty_features.clone(), chan.outbound_capacity_msat));
466 if first_hop_targets.is_empty() {
467 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
471 // We don't want multiple paths (as per MPP) share liquidity of the same channels.
472 // This map allows paths to be aware of the channel use by other paths in the same call.
473 // This would help to make a better path finding decisions and not "overbook" channels.
474 // It is unaware of the directions (except for `outbound_capacity_msat` in `first_hops`).
475 let mut bookkeeped_channels_liquidity_available_msat = HashMap::new();
477 // Keeping track of how much value we already collected across other paths. Helps to decide:
478 // - how much a new path should be transferring (upper bound);
479 // - whether a channel should be disregarded because
480 // it's available liquidity is too small comparing to how much more we need to collect;
481 // - when we want to stop looking for new paths.
482 let mut already_collected_value_msat = 0;
484 macro_rules! add_entry {
485 // Adds entry which goes from $src_node_id to $dest_node_id
486 // over the channel with id $chan_id with fees described in
487 // $directional_info.
488 // $next_hops_fee_msat represents the fees paid for using all the channel *after* this one,
489 // since that value has to be transferred over this channel.
490 ( $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,
491 $next_hops_value_contribution: expr ) => {
492 // Channels to self should not be used. This is more of belt-and-suspenders, because in
493 // practice these cases should be caught earlier:
494 // - for regular channels at channel announcement (TODO)
495 // - for first and last hops early in get_route
496 if $src_node_id != $dest_node_id.clone() {
497 let available_liquidity_msat = bookkeeped_channels_liquidity_available_msat.entry($chan_id.clone()).or_insert_with(|| {
498 let mut initial_liquidity_available_msat = None;
499 if let Some(capacity_sats) = $capacity_sats {
500 initial_liquidity_available_msat = Some(capacity_sats * 1000);
503 if let Some(htlc_maximum_msat) = $directional_info.htlc_maximum_msat {
504 if let Some(available_msat) = initial_liquidity_available_msat {
505 initial_liquidity_available_msat = Some(cmp::min(available_msat, htlc_maximum_msat));
507 initial_liquidity_available_msat = Some(htlc_maximum_msat);
511 match initial_liquidity_available_msat {
512 Some(available_msat) => available_msat,
513 // We assume channels with unknown balance have
514 // a capacity of 0.0025 BTC (or 250_000 sats).
515 None => 250_000 * 1000
519 // It is tricky to substract $next_hops_fee_msat from available liquidity here.
520 // It may be misleading because we might later choose to reduce the value transferred
521 // over these channels, and the channel which was insufficient might become sufficient.
522 // Worst case: we drop a good channel here because it can't cover the high following
523 // fees caused by one expensive channel, but then this channel could have been used
524 // if the amount being transferred over this path is lower.
525 // We do this for now, but this is a subject for removal.
526 if let Some(available_value_contribution_msat) = available_liquidity_msat.checked_sub($next_hops_fee_msat) {
528 // Routing Fragmentation Mitigation heuristic:
530 // Routing fragmentation across many payment paths increases the overall routing
531 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
532 // Taking too many smaller paths also increases the chance of payment failure.
533 // Thus to avoid this effect, we require from our collected links to provide
534 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
536 // This requirement is currently 5% of the remaining-to-be-collected value.
537 // This means as we successfully advance in our collection,
538 // the absolute liquidity contribution is lowered,
539 // thus increasing the number of potential channels to be selected.
541 // Derive the minimal liquidity contribution with a ratio of 20 (5%, rounded up)
542 // or 100% if we're not allowed to do multipath payments.
543 let minimal_value_contribution_msat: u64 = if allow_mpp {
544 (recommended_value_msat - already_collected_value_msat + 19) / 20
548 // Verify the liquidity offered by this channel complies to the minimal contribution.
549 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
551 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
552 // Includes paying fees for the use of the following channels.
553 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
554 Some(result) => result,
555 // Can't overflow due to how the values were computed right above.
556 None => unreachable!(),
559 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
560 // bother considering this channel.
561 // Since we're choosing amount_to_transfer_over_msat as maximum possible, it can
562 // be only reduced later (not increased), so this channel should just be skipped
563 // as not sufficient.
564 if amount_to_transfer_over_msat < $directional_info.htlc_minimum_msat {
565 hit_minimum_limit = true;
566 } else if contributes_sufficient_value {
567 // Note that low contribution here (limited by available_liquidity_msat)
568 // might violate htlc_minimum_msat on the hops which are next along the
569 // payment path (upstream to the payee). To avoid that, we recompute path
570 // path fees knowing the final path contribution after constructing it.
571 let hm_entry = dist.entry(&$src_node_id);
572 let old_entry = hm_entry.or_insert_with(|| {
573 // If there was previously no known way to access
574 // the source node (recall it goes payee-to-payer) of $chan_id, first add
575 // a semi-dummy record just to compute the fees to reach the source node.
576 // This will affect our decision on selecting $chan_id
577 // as a way to reach the $dest_node_id.
578 let mut fee_base_msat = u32::max_value();
579 let mut fee_proportional_millionths = u32::max_value();
580 if let Some(Some(fees)) = network.get_nodes().get(&$src_node_id).map(|node| node.lowest_inbound_channel_fees) {
581 fee_base_msat = fees.base_msat;
582 fee_proportional_millionths = fees.proportional_millionths;
585 route_hop: RouteHop {
586 pubkey: $dest_node_id.clone(),
587 node_features: NodeFeatures::empty(),
589 channel_features: $chan_features.clone(),
591 cltv_expiry_delta: 0,
593 src_lowest_inbound_fees: RoutingFees {
594 base_msat: fee_base_msat,
595 proportional_millionths: fee_proportional_millionths,
597 channel_fees: $directional_info.fees,
598 next_hops_fee_msat: u64::max_value(),
599 hop_use_fee_msat: u64::max_value(),
600 total_fee_msat: u64::max_value(),
601 htlc_minimum_msat: $directional_info.htlc_minimum_msat,
605 let mut hop_use_fee_msat = 0;
606 let mut total_fee_msat = $next_hops_fee_msat;
608 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
609 // will have the same effective-fee
610 if $src_node_id != *our_node_id {
611 match compute_fees(amount_to_transfer_over_msat, $directional_info.fees) {
612 // max_value means we'll always fail
613 // the old_entry.total_fee_msat > total_fee_msat check
614 None => total_fee_msat = u64::max_value(),
616 hop_use_fee_msat = fee_msat;
617 total_fee_msat += hop_use_fee_msat;
618 if let Some(prev_hop_fee_msat) = compute_fees(total_fee_msat + amount_to_transfer_over_msat,
619 old_entry.src_lowest_inbound_fees) {
620 if let Some(incremented_total_fee_msat) = total_fee_msat.checked_add(prev_hop_fee_msat) {
621 total_fee_msat = incremented_total_fee_msat;
624 // max_value means we'll always fail
625 // the old_entry.total_fee_msat > total_fee_msat check
626 total_fee_msat = u64::max_value();
629 // max_value means we'll always fail
630 // the old_entry.total_fee_msat > total_fee_msat check
631 total_fee_msat = u64::max_value();
637 let new_graph_node = RouteGraphNode {
638 pubkey: $src_node_id,
639 lowest_fee_to_peer_through_node: total_fee_msat,
640 lowest_fee_to_node: $next_hops_fee_msat as u64 + hop_use_fee_msat,
641 value_contribution_msat: value_contribution_msat,
644 // Update the way of reaching $src_node_id with the given $chan_id (from $dest_node_id),
645 // if this way is cheaper than the already known
646 // (considering the cost to "reach" this channel from the route destination,
647 // the cost of using this channel,
648 // and the cost of routing to the source node of this channel).
649 // Also, consider that htlc_minimum_msat_difference, because we might end up
650 // paying it. Consider the following exploit:
651 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
652 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
653 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
654 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
656 // TODO: this scoring could be smarter (e.g. 0.5*htlc_minimum_msat here).
657 let mut old_cost = old_entry.total_fee_msat;
658 if let Some(increased_old_cost) = old_cost.checked_add(old_entry.htlc_minimum_msat) {
659 old_cost = increased_old_cost;
661 old_cost = u64::max_value();
664 let mut new_cost = total_fee_msat;
665 if let Some(increased_new_cost) = new_cost.checked_add($directional_info.htlc_minimum_msat) {
666 new_cost = increased_new_cost;
668 new_cost = u64::max_value();
671 if new_cost < old_cost {
672 targets.push(new_graph_node);
673 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
674 old_entry.hop_use_fee_msat = hop_use_fee_msat;
675 old_entry.total_fee_msat = total_fee_msat;
676 old_entry.route_hop = RouteHop {
677 pubkey: $dest_node_id.clone(),
678 node_features: NodeFeatures::empty(),
679 short_channel_id: $chan_id.clone(),
680 channel_features: $chan_features.clone(),
681 fee_msat: 0, // This value will be later filled with hop_use_fee_msat of the following channel
682 cltv_expiry_delta: $directional_info.cltv_expiry_delta as u32,
684 old_entry.channel_fees = $directional_info.fees;
685 // It's probably fine to replace the old entry, because the new one
686 // passed the htlc_minimum-related checks above.
687 old_entry.htlc_minimum_msat = $directional_info.htlc_minimum_msat;
695 // Find ways (channels with destination) to reach a given node and store them
696 // in the corresponding data structures (routing graph etc).
697 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
698 // meaning how much will be paid in fees after this node (to the best of our knowledge).
699 // This data can later be helpful to optimize routing (pay lower fees).
700 macro_rules! add_entries_to_cheapest_to_target_node {
701 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr, $next_hops_value_contribution: expr ) => {
702 if first_hops.is_some() {
703 if let Some(&(ref first_hop, ref features, ref outbound_capacity_msat)) = first_hop_targets.get(&$node_id) {
704 add_entry!(first_hop, *our_node_id, $node_id, dummy_directional_info, Some(outbound_capacity_msat / 1000), features.to_context(), $fee_to_target_msat, $next_hops_value_contribution);
709 if let Some(node_info) = $node.announcement_info.as_ref() {
710 features = node_info.features.clone();
712 features = NodeFeatures::empty();
715 if !features.requires_unknown_bits() {
716 for chan_id in $node.channels.iter() {
717 let chan = network.get_channels().get(chan_id).unwrap();
718 if !chan.features.requires_unknown_bits() {
719 if chan.node_one == *$node_id {
720 // ie $node is one, ie next hop in A* is two, via the two_to_one channel
721 if first_hops.is_none() || chan.node_two != *our_node_id {
722 if let Some(two_to_one) = chan.two_to_one.as_ref() {
723 if two_to_one.enabled {
724 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);
729 if first_hops.is_none() || chan.node_one != *our_node_id {
730 if let Some(one_to_two) = chan.one_to_two.as_ref() {
731 if one_to_two.enabled {
732 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);
744 let mut payment_paths = Vec::<PaymentPath>::new();
746 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
747 'paths_collection: loop {
748 // For every new path, start from scratch, except
749 // bookkeeped_channels_liquidity_available_msat, which will improve
750 // the further iterations of path finding. Also don't erase first_hop_targets.
753 hit_minimum_limit = false;
755 // If first hop is a private channel and the only way to reach the payee, this is the only
756 // place where it could be added.
757 if first_hops.is_some() {
758 if let Some(&(ref first_hop, ref features, ref outbound_capacity_msat)) = first_hop_targets.get(&payee) {
759 add_entry!(first_hop, *our_node_id, payee, dummy_directional_info, Some(outbound_capacity_msat / 1000), features.to_context(), 0, path_value_msat);
763 // Add the payee as a target, so that the payee-to-payer
764 // search algorithm knows what to start with.
765 match network.get_nodes().get(payee) {
766 // The payee is not in our network graph, so nothing to add here.
767 // There is still a chance of reaching them via last_hops though,
768 // so don't yet fail the payment here.
769 // If not, targets.pop() will not even let us enter the loop in step 2.
772 add_entries_to_cheapest_to_target_node!(node, payee, 0, path_value_msat);
777 // If a caller provided us with last hops, add them to routing targets. Since this happens
778 // earlier than general path finding, they will be somewhat prioritized, although currently
779 // it matters only if the fees are exactly the same.
780 for hop in last_hops.iter() {
781 let have_hop_src_in_graph =
782 if let Some(&(ref first_hop, ref features, ref outbound_capacity_msat)) = first_hop_targets.get(&hop.src_node_id) {
783 // If this hop connects to a node with which we have a direct channel, ignore
784 // the network graph and add both the hop and our direct channel to
785 // the candidate set.
787 // Currently there are no channel-context features defined, so we are a
788 // bit lazy here. In the future, we should pull them out via our
789 // ChannelManager, but there's no reason to waste the space until we
791 add_entry!(first_hop, *our_node_id , hop.src_node_id, dummy_directional_info, Some(outbound_capacity_msat / 1000), features.to_context(), 0, path_value_msat);
794 // In any other case, only add the hop if the source is in the regular network
796 network.get_nodes().get(&hop.src_node_id).is_some()
798 if have_hop_src_in_graph {
799 // BOLT 11 doesn't allow inclusion of features for the last hop hints, which
800 // really sucks, cause we're gonna need that eventually.
801 let last_hop_htlc_minimum_msat: u64 = match hop.htlc_minimum_msat {
802 Some(htlc_minimum_msat) => htlc_minimum_msat,
805 let directional_info = DummyDirectionalChannelInfo {
806 cltv_expiry_delta: hop.cltv_expiry_delta as u32,
807 htlc_minimum_msat: last_hop_htlc_minimum_msat,
808 htlc_maximum_msat: hop.htlc_maximum_msat,
811 add_entry!(hop.short_channel_id, hop.src_node_id, payee, directional_info, None::<u64>, ChannelFeatures::empty(), 0, path_value_msat);
815 // At this point, targets are filled with the data from first and
816 // last hops communicated by the caller, and the payment receiver.
817 let mut found_new_path = false;
820 // If this loop terminates due the exhaustion of targets, two situations are possible:
821 // - not enough outgoing liquidity:
822 // 0 < already_collected_value_msat < final_value_msat
823 // - enough outgoing liquidity:
824 // final_value_msat <= already_collected_value_msat < recommended_value_msat
825 // Both these cases (and other cases except reaching recommended_value_msat) mean that
826 // paths_collection will be stopped because found_new_path==false.
827 // This is not necessarily a routing failure.
828 'path_construction: while let Some(RouteGraphNode { pubkey, lowest_fee_to_node, value_contribution_msat, .. }) = targets.pop() {
830 // Since we're going payee-to-payer, hitting our node as a target means we should stop
831 // traversing the graph and arrange the path out of what we found.
832 if pubkey == *our_node_id {
833 let mut new_entry = dist.remove(&our_node_id).unwrap();
834 let mut ordered_hops = vec!(new_entry.clone());
837 if let Some(&(_, ref features, _)) = first_hop_targets.get(&ordered_hops.last().unwrap().route_hop.pubkey) {
838 ordered_hops.last_mut().unwrap().route_hop.node_features = features.to_context();
839 } else if let Some(node) = network.get_nodes().get(&ordered_hops.last().unwrap().route_hop.pubkey) {
840 if let Some(node_info) = node.announcement_info.as_ref() {
841 ordered_hops.last_mut().unwrap().route_hop.node_features = node_info.features.clone();
843 ordered_hops.last_mut().unwrap().route_hop.node_features = NodeFeatures::empty();
846 // We should be able to fill in features for everything except the last
847 // hop, if the last hop was provided via a BOLT 11 invoice (though we
848 // should be able to extend it further as BOLT 11 does have feature
849 // flags for the last hop node itself).
850 assert!(ordered_hops.last().unwrap().route_hop.pubkey == *payee);
853 // Means we succesfully traversed from the payer to the payee, now
854 // save this path for the payment route. Also, update the liquidity
855 // remaining on the used hops, so that we take them into account
856 // while looking for more paths.
857 if ordered_hops.last().unwrap().route_hop.pubkey == *payee {
861 new_entry = match dist.remove(&ordered_hops.last().unwrap().route_hop.pubkey) {
862 Some(payment_hop) => payment_hop,
863 // We can't arrive at None because, if we ever add an entry to targets,
864 // we also fill in the entry in dist (see add_entry!).
865 None => unreachable!(),
867 // We "propagate" the fees one hop backward (topologically) here,
868 // so that fees paid for a HTLC forwarding on the current channel are
869 // associated with the previous channel (where they will be subtracted).
870 ordered_hops.last_mut().unwrap().route_hop.fee_msat = new_entry.hop_use_fee_msat;
871 ordered_hops.last_mut().unwrap().route_hop.cltv_expiry_delta = new_entry.route_hop.cltv_expiry_delta;
872 ordered_hops.push(new_entry.clone());
874 ordered_hops.last_mut().unwrap().route_hop.fee_msat = value_contribution_msat;
875 ordered_hops.last_mut().unwrap().hop_use_fee_msat = 0;
876 ordered_hops.last_mut().unwrap().route_hop.cltv_expiry_delta = final_cltv;
878 let mut payment_path = PaymentPath {hops: ordered_hops};
880 // We could have possibly constructed a slightly inconsistent path: since we reduce
881 // value being transferred along the way, we could have violated htlc_minimum_msat
882 // on some channels we already passed (assuming dest->source direction). Here, we
883 // recompute the fees again, so that if that's the case, we match the currently
884 // underpaid htlc_minimum_msat with fees.
885 payment_path.update_value_and_recompute_fees(value_contribution_msat);
887 // Since a path allows to transfer as much value as
888 // the smallest channel it has ("bottleneck"), we should recompute
889 // the fees so sender HTLC don't overpay fees when traversing
890 // larger channels than the bottleneck. This may happen because
891 // when we were selecting those channels we were not aware how much value
892 // this path will transfer, and the relative fee for them
893 // might have been computed considering a larger value.
894 // Remember that we used these channels so that we don't rely
895 // on the same liquidity in future paths.
896 for payment_hop in payment_path.hops.iter() {
897 let channel_liquidity_available_msat = bookkeeped_channels_liquidity_available_msat.get_mut(&payment_hop.route_hop.short_channel_id).unwrap();
898 let mut spent_on_hop_msat = value_contribution_msat;
899 let next_hops_fee_msat = payment_hop.next_hops_fee_msat;
900 spent_on_hop_msat += next_hops_fee_msat;
901 if *channel_liquidity_available_msat < spent_on_hop_msat {
902 // This should not happen because we do recompute fees right before,
903 // trying to avoid cases when a hop is not usable due to the fee situation.
904 break 'path_construction;
906 *channel_liquidity_available_msat -= spent_on_hop_msat;
908 // Track the total amount all our collected paths allow to send so that we:
909 // - know when to stop looking for more paths
910 // - know which of the hops are useless considering how much more sats we need
911 // (contributes_sufficient_value)
912 already_collected_value_msat += value_contribution_msat;
914 payment_paths.push(payment_path);
915 found_new_path = true;
916 break 'path_construction;
919 // Otherwise, since the current target node is not us,
920 // keep "unrolling" the payment graph from payee to payer by
921 // finding a way to reach the current target from the payer side.
922 match network.get_nodes().get(&pubkey) {
925 add_entries_to_cheapest_to_target_node!(node, &pubkey, lowest_fee_to_node, value_contribution_msat);
931 // If we don't support MPP, no use trying to gather more value ever.
932 break 'paths_collection;
936 // Stop either when the recommended value is reached or if no new path was found in this
938 // In the latter case, making another path finding attempt won't help,
939 // because we deterministically terminated the search due to low liquidity.
940 if already_collected_value_msat >= recommended_value_msat || !found_new_path {
941 break 'paths_collection;
942 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
943 // Further, if this was our first walk of the graph, and we weren't limited by an
944 // htlc_minimum_msat, return immediately because this path should suffice. If we were
945 // limited by an htlc_minimum_msat value, find another path with a higher value,
946 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
947 // still keeping a lower total fee than this path.
948 if !hit_minimum_limit {
949 break 'paths_collection;
951 path_value_msat = recommended_value_msat;
956 if payment_paths.len() == 0 {
957 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
960 if already_collected_value_msat < final_value_msat {
961 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
964 // Sort by total fees and take the best paths.
965 payment_paths.sort_by_key(|path| path.get_total_fee_paid_msat());
966 if payment_paths.len() > 50 {
967 payment_paths.truncate(50);
970 // Draw multiple sufficient routes by randomly combining the selected paths.
971 let mut drawn_routes = Vec::new();
972 for i in 0..payment_paths.len() {
973 let mut cur_route = Vec::<PaymentPath>::new();
974 let mut aggregate_route_value_msat = 0;
977 // TODO: real random shuffle
978 // Currently just starts with i_th and goes up to i-1_th in a looped way.
979 let cur_payment_paths = [&payment_paths[i..], &payment_paths[..i]].concat();
982 for payment_path in cur_payment_paths {
983 cur_route.push(payment_path.clone());
984 aggregate_route_value_msat += payment_path.get_value_msat();
985 if aggregate_route_value_msat > final_value_msat {
986 // Last path likely overpaid. Substract it from the most expensive
987 // (in terms of proportional fee) path in this route and recompute fees.
988 // This might be not the most economically efficient way, but fewer paths
989 // also makes routing more reliable.
990 let mut overpaid_value_msat = aggregate_route_value_msat - final_value_msat;
992 // First, drop some expensive low-value paths entirely if possible.
993 // Sort by value so that we drop many really-low values first, since
994 // fewer paths is better: the payment is less likely to fail.
995 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
996 // so that the sender pays less fees overall. And also htlc_minimum_msat.
997 cur_route.sort_by_key(|path| path.get_value_msat());
998 // We should make sure that at least 1 path left.
999 let mut paths_left = cur_route.len();
1000 cur_route.retain(|path| {
1001 if paths_left == 1 {
1004 let mut keep = true;
1005 let path_value_msat = path.get_value_msat();
1006 if path_value_msat <= overpaid_value_msat {
1008 overpaid_value_msat -= path_value_msat;
1014 if overpaid_value_msat == 0 {
1018 assert!(cur_route.len() > 0);
1021 // Now, substract the overpaid value from the most-expensive path.
1022 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1023 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1024 cur_route.sort_by_key(|path| { path.hops.iter().map(|hop| hop.channel_fees.proportional_millionths as u64).sum::<u64>() });
1025 let expensive_payment_path = cur_route.first_mut().unwrap();
1026 // We already dropped all the small channels above, meaning all the
1027 // remaining channels are larger than remaining overpaid_value_msat.
1028 // Thus, this can't be negative.
1029 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
1030 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
1034 drawn_routes.push(cur_route);
1038 // Select the best route by lowest total fee.
1039 drawn_routes.sort_by_key(|paths| paths.iter().map(|path| path.get_total_fee_paid_msat()).sum::<u64>());
1040 let mut selected_paths = Vec::<Vec<RouteHop>>::new();
1041 for payment_path in drawn_routes.first().unwrap() {
1042 selected_paths.push(payment_path.hops.iter().map(|payment_hop| payment_hop.route_hop.clone()).collect());
1045 if let Some(features) = &payee_features {
1046 for path in selected_paths.iter_mut() {
1047 path.last_mut().unwrap().node_features = features.to_context();
1051 let route = Route { paths: selected_paths };
1052 log_trace!(logger, "Got route: {}", log_route!(route));
1058 use routing::router::{get_route, RouteHint, RoutingFees};
1059 use routing::network_graph::{NetworkGraph, NetGraphMsgHandler};
1060 use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
1061 use ln::msgs::{ErrorAction, LightningError, OptionalField, UnsignedChannelAnnouncement, ChannelAnnouncement, RoutingMessageHandler,
1062 NodeAnnouncement, UnsignedNodeAnnouncement, ChannelUpdate, UnsignedChannelUpdate};
1063 use ln::channelmanager;
1064 use util::test_utils;
1065 use util::ser::Writeable;
1067 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
1068 use bitcoin::hashes::Hash;
1069 use bitcoin::network::constants::Network;
1070 use bitcoin::blockdata::constants::genesis_block;
1071 use bitcoin::blockdata::script::Builder;
1072 use bitcoin::blockdata::opcodes;
1073 use bitcoin::blockdata::transaction::TxOut;
1077 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
1078 use bitcoin::secp256k1::{Secp256k1, All};
1082 // Using the same keys for LN and BTC ids
1083 fn add_channel(net_graph_msg_handler: &NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>, secp_ctx: &Secp256k1<All>, node_1_privkey: &SecretKey,
1084 node_2_privkey: &SecretKey, features: ChannelFeatures, short_channel_id: u64) {
1085 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1086 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1088 let unsigned_announcement = UnsignedChannelAnnouncement {
1090 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1094 bitcoin_key_1: node_id_1,
1095 bitcoin_key_2: node_id_2,
1096 excess_data: Vec::new(),
1099 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1100 let valid_announcement = ChannelAnnouncement {
1101 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1102 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1103 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1104 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1105 contents: unsigned_announcement.clone(),
1107 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1108 Ok(res) => assert!(res),
1113 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) {
1114 let msghash = hash_to_message!(&Sha256dHash::hash(&update.encode()[..])[..]);
1115 let valid_channel_update = ChannelUpdate {
1116 signature: secp_ctx.sign(&msghash, node_privkey),
1117 contents: update.clone()
1120 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1121 Ok(res) => assert!(res),
1126 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,
1127 features: NodeFeatures, timestamp: u32) {
1128 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
1129 let unsigned_announcement = UnsignedNodeAnnouncement {
1135 addresses: Vec::new(),
1136 excess_address_data: Vec::new(),
1137 excess_data: Vec::new(),
1139 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1140 let valid_announcement = NodeAnnouncement {
1141 signature: secp_ctx.sign(&msghash, node_privkey),
1142 contents: unsigned_announcement.clone()
1145 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1151 fn get_nodes(secp_ctx: &Secp256k1<All>) -> (SecretKey, PublicKey, Vec<SecretKey>, Vec<PublicKey>) {
1152 let privkeys: Vec<SecretKey> = (2..10).map(|i| {
1153 SecretKey::from_slice(&hex::decode(format!("{:02}", i).repeat(32)).unwrap()[..]).unwrap()
1156 let pubkeys = privkeys.iter().map(|secret| PublicKey::from_secret_key(&secp_ctx, secret)).collect();
1158 let our_privkey = SecretKey::from_slice(&hex::decode("01".repeat(32)).unwrap()[..]).unwrap();
1159 let our_id = PublicKey::from_secret_key(&secp_ctx, &our_privkey);
1161 (our_privkey, our_id, privkeys, pubkeys)
1164 fn id_to_feature_flags(id: u8) -> Vec<u8> {
1165 // Set the feature flags to the id'th odd (ie non-required) feature bit so that we can
1166 // test for it later.
1167 let idx = (id - 1) * 2 + 1;
1169 vec![1 << (idx - 8*3), 0, 0, 0]
1170 } else if idx > 8*2 {
1171 vec![1 << (idx - 8*2), 0, 0]
1172 } else if idx > 8*1 {
1173 vec![1 << (idx - 8*1), 0]
1179 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>) {
1180 let secp_ctx = Secp256k1::new();
1181 let logger = Arc::new(test_utils::TestLogger::new());
1182 let chain_monitor = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1183 let net_graph_msg_handler = NetGraphMsgHandler::new(genesis_block(Network::Testnet).header.block_hash(), None, Arc::clone(&logger));
1184 // Build network from our_id to node7:
1186 // -1(1)2- node0 -1(3)2-
1188 // our_id -1(12)2- node7 -1(13)2--- node2
1190 // -1(2)2- node1 -1(4)2-
1193 // chan1 1-to-2: disabled
1194 // chan1 2-to-1: enabled, 0 fee
1196 // chan2 1-to-2: enabled, ignored fee
1197 // chan2 2-to-1: enabled, 0 fee
1199 // chan3 1-to-2: enabled, 0 fee
1200 // chan3 2-to-1: enabled, 100 msat fee
1202 // chan4 1-to-2: enabled, 100% fee
1203 // chan4 2-to-1: enabled, 0 fee
1205 // chan12 1-to-2: enabled, ignored fee
1206 // chan12 2-to-1: enabled, 0 fee
1208 // chan13 1-to-2: enabled, 200% fee
1209 // chan13 2-to-1: enabled, 0 fee
1212 // -1(5)2- node3 -1(8)2--
1216 // node2--1(6)2- node4 -1(9)2--- node6 (not in global route map)
1218 // -1(7)2- node5 -1(10)2-
1220 // chan5 1-to-2: enabled, 100 msat fee
1221 // chan5 2-to-1: enabled, 0 fee
1223 // chan6 1-to-2: enabled, 0 fee
1224 // chan6 2-to-1: enabled, 0 fee
1226 // chan7 1-to-2: enabled, 100% fee
1227 // chan7 2-to-1: enabled, 0 fee
1229 // chan8 1-to-2: enabled, variable fee (0 then 1000 msat)
1230 // chan8 2-to-1: enabled, 0 fee
1232 // chan9 1-to-2: enabled, 1001 msat fee
1233 // chan9 2-to-1: enabled, 0 fee
1235 // chan10 1-to-2: enabled, 0 fee
1236 // chan10 2-to-1: enabled, 0 fee
1238 // chan11 1-to-2: enabled, 0 fee
1239 // chan11 2-to-1: enabled, 0 fee
1241 let (our_privkey, _, privkeys, _) = get_nodes(&secp_ctx);
1243 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[0], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
1244 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1245 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1246 short_channel_id: 1,
1249 cltv_expiry_delta: 0,
1250 htlc_minimum_msat: 0,
1251 htlc_maximum_msat: OptionalField::Absent,
1253 fee_proportional_millionths: 0,
1254 excess_data: Vec::new()
1257 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
1259 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
1260 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1261 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1262 short_channel_id: 2,
1265 cltv_expiry_delta: u16::max_value(),
1266 htlc_minimum_msat: 0,
1267 htlc_maximum_msat: OptionalField::Absent,
1268 fee_base_msat: u32::max_value(),
1269 fee_proportional_millionths: u32::max_value(),
1270 excess_data: Vec::new()
1272 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1273 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1274 short_channel_id: 2,
1277 cltv_expiry_delta: 0,
1278 htlc_minimum_msat: 0,
1279 htlc_maximum_msat: OptionalField::Absent,
1281 fee_proportional_millionths: 0,
1282 excess_data: Vec::new()
1285 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
1287 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[7], ChannelFeatures::from_le_bytes(id_to_feature_flags(12)), 12);
1288 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1289 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1290 short_channel_id: 12,
1293 cltv_expiry_delta: u16::max_value(),
1294 htlc_minimum_msat: 0,
1295 htlc_maximum_msat: OptionalField::Absent,
1296 fee_base_msat: u32::max_value(),
1297 fee_proportional_millionths: u32::max_value(),
1298 excess_data: Vec::new()
1300 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1301 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1302 short_channel_id: 12,
1305 cltv_expiry_delta: 0,
1306 htlc_minimum_msat: 0,
1307 htlc_maximum_msat: OptionalField::Absent,
1309 fee_proportional_millionths: 0,
1310 excess_data: Vec::new()
1313 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], NodeFeatures::from_le_bytes(id_to_feature_flags(8)), 0);
1315 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
1316 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1317 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1318 short_channel_id: 3,
1321 cltv_expiry_delta: (3 << 8) | 1,
1322 htlc_minimum_msat: 0,
1323 htlc_maximum_msat: OptionalField::Absent,
1325 fee_proportional_millionths: 0,
1326 excess_data: Vec::new()
1328 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1329 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1330 short_channel_id: 3,
1333 cltv_expiry_delta: (3 << 8) | 2,
1334 htlc_minimum_msat: 0,
1335 htlc_maximum_msat: OptionalField::Absent,
1337 fee_proportional_millionths: 0,
1338 excess_data: Vec::new()
1341 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
1342 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1343 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1344 short_channel_id: 4,
1347 cltv_expiry_delta: (4 << 8) | 1,
1348 htlc_minimum_msat: 0,
1349 htlc_maximum_msat: OptionalField::Absent,
1351 fee_proportional_millionths: 1000000,
1352 excess_data: Vec::new()
1354 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1355 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1356 short_channel_id: 4,
1359 cltv_expiry_delta: (4 << 8) | 2,
1360 htlc_minimum_msat: 0,
1361 htlc_maximum_msat: OptionalField::Absent,
1363 fee_proportional_millionths: 0,
1364 excess_data: Vec::new()
1367 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(13)), 13);
1368 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1369 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1370 short_channel_id: 13,
1373 cltv_expiry_delta: (13 << 8) | 1,
1374 htlc_minimum_msat: 0,
1375 htlc_maximum_msat: OptionalField::Absent,
1377 fee_proportional_millionths: 2000000,
1378 excess_data: Vec::new()
1380 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1381 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1382 short_channel_id: 13,
1385 cltv_expiry_delta: (13 << 8) | 2,
1386 htlc_minimum_msat: 0,
1387 htlc_maximum_msat: OptionalField::Absent,
1389 fee_proportional_millionths: 0,
1390 excess_data: Vec::new()
1393 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
1395 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
1396 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1397 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1398 short_channel_id: 6,
1401 cltv_expiry_delta: (6 << 8) | 1,
1402 htlc_minimum_msat: 0,
1403 htlc_maximum_msat: OptionalField::Absent,
1405 fee_proportional_millionths: 0,
1406 excess_data: Vec::new()
1408 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1409 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1410 short_channel_id: 6,
1413 cltv_expiry_delta: (6 << 8) | 2,
1414 htlc_minimum_msat: 0,
1415 htlc_maximum_msat: OptionalField::Absent,
1417 fee_proportional_millionths: 0,
1418 excess_data: Vec::new(),
1421 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(11)), 11);
1422 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1423 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1424 short_channel_id: 11,
1427 cltv_expiry_delta: (11 << 8) | 1,
1428 htlc_minimum_msat: 0,
1429 htlc_maximum_msat: OptionalField::Absent,
1431 fee_proportional_millionths: 0,
1432 excess_data: Vec::new()
1434 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
1435 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1436 short_channel_id: 11,
1439 cltv_expiry_delta: (11 << 8) | 2,
1440 htlc_minimum_msat: 0,
1441 htlc_maximum_msat: OptionalField::Absent,
1443 fee_proportional_millionths: 0,
1444 excess_data: Vec::new()
1447 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(5)), 0);
1449 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
1451 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[5], ChannelFeatures::from_le_bytes(id_to_feature_flags(7)), 7);
1452 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1453 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1454 short_channel_id: 7,
1457 cltv_expiry_delta: (7 << 8) | 1,
1458 htlc_minimum_msat: 0,
1459 htlc_maximum_msat: OptionalField::Absent,
1461 fee_proportional_millionths: 1000000,
1462 excess_data: Vec::new()
1464 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[5], UnsignedChannelUpdate {
1465 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1466 short_channel_id: 7,
1469 cltv_expiry_delta: (7 << 8) | 2,
1470 htlc_minimum_msat: 0,
1471 htlc_maximum_msat: OptionalField::Absent,
1473 fee_proportional_millionths: 0,
1474 excess_data: Vec::new()
1477 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[5], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
1479 (secp_ctx, net_graph_msg_handler, chain_monitor, logger)
1483 fn simple_route_test() {
1484 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1485 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1487 // Simple route to 2 via 1
1489 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, None, &Vec::new(), 0, 42, Arc::clone(&logger)) {
1490 assert_eq!(err, "Cannot send a payment of 0 msat");
1491 } else { panic!(); }
1493 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, None, &Vec::new(), 100, 42, Arc::clone(&logger)).unwrap();
1494 assert_eq!(route.paths[0].len(), 2);
1496 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
1497 assert_eq!(route.paths[0][0].short_channel_id, 2);
1498 assert_eq!(route.paths[0][0].fee_msat, 100);
1499 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
1500 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
1501 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
1503 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1504 assert_eq!(route.paths[0][1].short_channel_id, 4);
1505 assert_eq!(route.paths[0][1].fee_msat, 100);
1506 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1507 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1508 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
1512 fn invalid_first_hop_test() {
1513 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1514 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1516 // Simple route to 2 via 1
1518 let our_chans = vec![channelmanager::ChannelDetails {
1519 channel_id: [0; 32],
1520 short_channel_id: Some(2),
1521 remote_network_id: our_id,
1522 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1523 channel_value_satoshis: 100000,
1525 outbound_capacity_msat: 100000,
1526 inbound_capacity_msat: 100000,
1528 counterparty_forwarding_info: None,
1531 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 100, 42, Arc::clone(&logger)) {
1532 assert_eq!(err, "First hop cannot have our_node_id as a destination.");
1533 } else { panic!(); }
1535 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, None, &Vec::new(), 100, 42, Arc::clone(&logger)).unwrap();
1536 assert_eq!(route.paths[0].len(), 2);
1540 fn htlc_minimum_test() {
1541 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1542 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1544 // Simple route to 2 via 1
1546 // Disable other paths
1547 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1548 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1549 short_channel_id: 12,
1551 flags: 2, // to disable
1552 cltv_expiry_delta: 0,
1553 htlc_minimum_msat: 0,
1554 htlc_maximum_msat: OptionalField::Absent,
1556 fee_proportional_millionths: 0,
1557 excess_data: Vec::new()
1559 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1560 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1561 short_channel_id: 3,
1563 flags: 2, // to disable
1564 cltv_expiry_delta: 0,
1565 htlc_minimum_msat: 0,
1566 htlc_maximum_msat: OptionalField::Absent,
1568 fee_proportional_millionths: 0,
1569 excess_data: Vec::new()
1571 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1572 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1573 short_channel_id: 13,
1575 flags: 2, // to disable
1576 cltv_expiry_delta: 0,
1577 htlc_minimum_msat: 0,
1578 htlc_maximum_msat: OptionalField::Absent,
1580 fee_proportional_millionths: 0,
1581 excess_data: Vec::new()
1583 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1584 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1585 short_channel_id: 6,
1587 flags: 2, // to disable
1588 cltv_expiry_delta: 0,
1589 htlc_minimum_msat: 0,
1590 htlc_maximum_msat: OptionalField::Absent,
1592 fee_proportional_millionths: 0,
1593 excess_data: Vec::new()
1595 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1596 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1597 short_channel_id: 7,
1599 flags: 2, // to disable
1600 cltv_expiry_delta: 0,
1601 htlc_minimum_msat: 0,
1602 htlc_maximum_msat: OptionalField::Absent,
1604 fee_proportional_millionths: 0,
1605 excess_data: Vec::new()
1608 // Check against amount_to_transfer_over_msat.
1609 // Set minimal HTLC of 200_000_000 msat.
1610 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1611 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1612 short_channel_id: 2,
1615 cltv_expiry_delta: 0,
1616 htlc_minimum_msat: 200_000_000,
1617 htlc_maximum_msat: OptionalField::Absent,
1619 fee_proportional_millionths: 0,
1620 excess_data: Vec::new()
1623 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
1625 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1626 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1627 short_channel_id: 4,
1630 cltv_expiry_delta: 0,
1631 htlc_minimum_msat: 0,
1632 htlc_maximum_msat: OptionalField::Present(199_999_999),
1634 fee_proportional_millionths: 0,
1635 excess_data: Vec::new()
1638 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
1639 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, None, &Vec::new(), 199_999_999, 42, Arc::clone(&logger)) {
1640 assert_eq!(err, "Failed to find a path to the given destination");
1641 } else { panic!(); }
1643 // Lift the restriction on the first hop.
1644 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1645 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1646 short_channel_id: 2,
1649 cltv_expiry_delta: 0,
1650 htlc_minimum_msat: 0,
1651 htlc_maximum_msat: OptionalField::Absent,
1653 fee_proportional_millionths: 0,
1654 excess_data: Vec::new()
1657 // A payment above the minimum should pass
1658 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, None, &Vec::new(), 199_999_999, 42, Arc::clone(&logger)).unwrap();
1659 assert_eq!(route.paths[0].len(), 2);
1663 fn htlc_minimum_overpay_test() {
1664 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1665 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1667 // A route to node#2 via two paths.
1668 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
1669 // Thus, they can't send 60 without overpaying.
1670 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1671 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1672 short_channel_id: 2,
1675 cltv_expiry_delta: 0,
1676 htlc_minimum_msat: 35_000,
1677 htlc_maximum_msat: OptionalField::Present(40_000),
1679 fee_proportional_millionths: 0,
1680 excess_data: Vec::new()
1682 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1683 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1684 short_channel_id: 12,
1687 cltv_expiry_delta: 0,
1688 htlc_minimum_msat: 35_000,
1689 htlc_maximum_msat: OptionalField::Present(40_000),
1691 fee_proportional_millionths: 0,
1692 excess_data: Vec::new()
1696 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1697 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1698 short_channel_id: 13,
1701 cltv_expiry_delta: 0,
1702 htlc_minimum_msat: 0,
1703 htlc_maximum_msat: OptionalField::Absent,
1705 fee_proportional_millionths: 0,
1706 excess_data: Vec::new()
1708 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1709 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1710 short_channel_id: 4,
1713 cltv_expiry_delta: 0,
1714 htlc_minimum_msat: 0,
1715 htlc_maximum_msat: OptionalField::Absent,
1717 fee_proportional_millionths: 0,
1718 excess_data: Vec::new()
1721 // Disable other paths
1722 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1723 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1724 short_channel_id: 1,
1726 flags: 2, // to disable
1727 cltv_expiry_delta: 0,
1728 htlc_minimum_msat: 0,
1729 htlc_maximum_msat: OptionalField::Absent,
1731 fee_proportional_millionths: 0,
1732 excess_data: Vec::new()
1735 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
1736 Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger)).unwrap();
1737 // Overpay fees to hit htlc_minimum_msat.
1738 let overpaid_fees = route.paths[0][0].fee_msat + route.paths[1][0].fee_msat;
1739 // TODO: this could be better balanced to overpay 10k and not 15k.
1740 assert_eq!(overpaid_fees, 15_000);
1742 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
1743 // while taking even more fee to match htlc_minimum_msat.
1744 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1745 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1746 short_channel_id: 12,
1749 cltv_expiry_delta: 0,
1750 htlc_minimum_msat: 65_000,
1751 htlc_maximum_msat: OptionalField::Present(80_000),
1753 fee_proportional_millionths: 0,
1754 excess_data: Vec::new()
1756 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1757 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1758 short_channel_id: 2,
1761 cltv_expiry_delta: 0,
1762 htlc_minimum_msat: 0,
1763 htlc_maximum_msat: OptionalField::Absent,
1765 fee_proportional_millionths: 0,
1766 excess_data: Vec::new()
1768 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1769 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1770 short_channel_id: 4,
1773 cltv_expiry_delta: 0,
1774 htlc_minimum_msat: 0,
1775 htlc_maximum_msat: OptionalField::Absent,
1777 fee_proportional_millionths: 100_000,
1778 excess_data: Vec::new()
1781 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
1782 Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger)).unwrap();
1783 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
1784 assert_eq!(route.paths.len(), 1);
1785 assert_eq!(route.paths[0][0].short_channel_id, 12);
1786 let fees = route.paths[0][0].fee_msat;
1787 assert_eq!(fees, 5_000);
1789 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
1790 Some(InvoiceFeatures::known()), None, &Vec::new(), 50_000, 42, Arc::clone(&logger)).unwrap();
1791 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
1792 // the other channel.
1793 assert_eq!(route.paths.len(), 1);
1794 assert_eq!(route.paths[0][0].short_channel_id, 2);
1795 let fees = route.paths[0][0].fee_msat;
1796 assert_eq!(fees, 5_000);
1800 fn disable_channels_test() {
1801 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1802 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1804 // // Disable channels 4 and 12 by flags=2
1805 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1806 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1807 short_channel_id: 4,
1809 flags: 2, // to disable
1810 cltv_expiry_delta: 0,
1811 htlc_minimum_msat: 0,
1812 htlc_maximum_msat: OptionalField::Absent,
1814 fee_proportional_millionths: 0,
1815 excess_data: Vec::new()
1817 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1818 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1819 short_channel_id: 12,
1821 flags: 2, // to disable
1822 cltv_expiry_delta: 0,
1823 htlc_minimum_msat: 0,
1824 htlc_maximum_msat: OptionalField::Absent,
1826 fee_proportional_millionths: 0,
1827 excess_data: Vec::new()
1830 // If all the channels require some features we don't understand, route should fail
1831 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, None, &Vec::new(), 100, 42, Arc::clone(&logger)) {
1832 assert_eq!(err, "Failed to find a path to the given destination");
1833 } else { panic!(); }
1835 // If we specify a channel to node7, that overrides our local channel view and that gets used
1836 let our_chans = vec![channelmanager::ChannelDetails {
1837 channel_id: [0; 32],
1838 short_channel_id: Some(42),
1839 remote_network_id: nodes[7].clone(),
1840 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1841 channel_value_satoshis: 0,
1843 outbound_capacity_msat: 250_000_000,
1844 inbound_capacity_msat: 0,
1846 counterparty_forwarding_info: None,
1848 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 100, 42, Arc::clone(&logger)).unwrap();
1849 assert_eq!(route.paths[0].len(), 2);
1851 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
1852 assert_eq!(route.paths[0][0].short_channel_id, 42);
1853 assert_eq!(route.paths[0][0].fee_msat, 200);
1854 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
1855 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
1856 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
1858 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1859 assert_eq!(route.paths[0][1].short_channel_id, 13);
1860 assert_eq!(route.paths[0][1].fee_msat, 100);
1861 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1862 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1863 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
1867 fn disable_node_test() {
1868 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1869 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1871 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
1872 let mut unknown_features = NodeFeatures::known();
1873 unknown_features.set_required_unknown_bits();
1874 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
1875 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
1876 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
1878 // If all nodes require some features we don't understand, route should fail
1879 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, None, &Vec::new(), 100, 42, Arc::clone(&logger)) {
1880 assert_eq!(err, "Failed to find a path to the given destination");
1881 } else { panic!(); }
1883 // If we specify a channel to node7, that overrides our local channel view and that gets used
1884 let our_chans = vec![channelmanager::ChannelDetails {
1885 channel_id: [0; 32],
1886 short_channel_id: Some(42),
1887 remote_network_id: nodes[7].clone(),
1888 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1889 channel_value_satoshis: 0,
1891 outbound_capacity_msat: 250_000_000,
1892 inbound_capacity_msat: 0,
1894 counterparty_forwarding_info: None,
1896 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 100, 42, Arc::clone(&logger)).unwrap();
1897 assert_eq!(route.paths[0].len(), 2);
1899 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
1900 assert_eq!(route.paths[0][0].short_channel_id, 42);
1901 assert_eq!(route.paths[0][0].fee_msat, 200);
1902 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
1903 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
1904 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
1906 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1907 assert_eq!(route.paths[0][1].short_channel_id, 13);
1908 assert_eq!(route.paths[0][1].fee_msat, 100);
1909 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1910 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1911 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
1913 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
1914 // naively) assume that the user checked the feature bits on the invoice, which override
1915 // the node_announcement.
1919 fn our_chans_test() {
1920 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1921 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1923 // Route to 1 via 2 and 3 because our channel to 1 is disabled
1924 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[0], None, None, &Vec::new(), 100, 42, Arc::clone(&logger)).unwrap();
1925 assert_eq!(route.paths[0].len(), 3);
1927 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
1928 assert_eq!(route.paths[0][0].short_channel_id, 2);
1929 assert_eq!(route.paths[0][0].fee_msat, 200);
1930 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
1931 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
1932 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
1934 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1935 assert_eq!(route.paths[0][1].short_channel_id, 4);
1936 assert_eq!(route.paths[0][1].fee_msat, 100);
1937 assert_eq!(route.paths[0][1].cltv_expiry_delta, (3 << 8) | 2);
1938 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1939 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
1941 assert_eq!(route.paths[0][2].pubkey, nodes[0]);
1942 assert_eq!(route.paths[0][2].short_channel_id, 3);
1943 assert_eq!(route.paths[0][2].fee_msat, 100);
1944 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
1945 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(1));
1946 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(3));
1948 // If we specify a channel to node7, that overrides our local channel view and that gets used
1949 let our_chans = vec![channelmanager::ChannelDetails {
1950 channel_id: [0; 32],
1951 short_channel_id: Some(42),
1952 remote_network_id: nodes[7].clone(),
1953 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1954 channel_value_satoshis: 0,
1956 outbound_capacity_msat: 250_000_000,
1957 inbound_capacity_msat: 0,
1959 counterparty_forwarding_info: None,
1961 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 100, 42, Arc::clone(&logger)).unwrap();
1962 assert_eq!(route.paths[0].len(), 2);
1964 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
1965 assert_eq!(route.paths[0][0].short_channel_id, 42);
1966 assert_eq!(route.paths[0][0].fee_msat, 200);
1967 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
1968 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
1969 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
1971 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1972 assert_eq!(route.paths[0][1].short_channel_id, 13);
1973 assert_eq!(route.paths[0][1].fee_msat, 100);
1974 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1975 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1976 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
1979 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
1980 let zero_fees = RoutingFees {
1982 proportional_millionths: 0,
1985 src_node_id: nodes[3].clone(),
1986 short_channel_id: 8,
1988 cltv_expiry_delta: (8 << 8) | 1,
1989 htlc_minimum_msat: None,
1990 htlc_maximum_msat: None,
1992 src_node_id: nodes[4].clone(),
1993 short_channel_id: 9,
1996 proportional_millionths: 0,
1998 cltv_expiry_delta: (9 << 8) | 1,
1999 htlc_minimum_msat: None,
2000 htlc_maximum_msat: None,
2002 src_node_id: nodes[5].clone(),
2003 short_channel_id: 10,
2005 cltv_expiry_delta: (10 << 8) | 1,
2006 htlc_minimum_msat: None,
2007 htlc_maximum_msat: None,
2012 fn last_hops_test() {
2013 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2014 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2016 // Simple test across 2, 3, 5, and 4 via a last_hop channel
2018 // First check that lst hop can't have its source as the payee.
2019 let invalid_last_hop = RouteHint {
2020 src_node_id: nodes[6],
2021 short_channel_id: 8,
2024 proportional_millionths: 0,
2026 cltv_expiry_delta: (8 << 8) | 1,
2027 htlc_minimum_msat: None,
2028 htlc_maximum_msat: None,
2031 let mut invalid_last_hops = last_hops(&nodes);
2032 invalid_last_hops.push(invalid_last_hop);
2034 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[6], None, None, &invalid_last_hops.iter().collect::<Vec<_>>(), 100, 42, Arc::clone(&logger)) {
2035 assert_eq!(err, "Last hop cannot have a payee as a source.");
2036 } else { panic!(); }
2039 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[6], None, None, &last_hops(&nodes).iter().collect::<Vec<_>>(), 100, 42, Arc::clone(&logger)).unwrap();
2040 assert_eq!(route.paths[0].len(), 5);
2042 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2043 assert_eq!(route.paths[0][0].short_channel_id, 2);
2044 assert_eq!(route.paths[0][0].fee_msat, 100);
2045 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2046 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2047 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2049 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2050 assert_eq!(route.paths[0][1].short_channel_id, 4);
2051 assert_eq!(route.paths[0][1].fee_msat, 0);
2052 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2053 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2054 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2056 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2057 assert_eq!(route.paths[0][2].short_channel_id, 6);
2058 assert_eq!(route.paths[0][2].fee_msat, 0);
2059 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2060 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2061 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2063 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2064 assert_eq!(route.paths[0][3].short_channel_id, 11);
2065 assert_eq!(route.paths[0][3].fee_msat, 0);
2066 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2067 // If we have a peer in the node map, we'll use their features here since we don't have
2068 // a way of figuring out their features from the invoice:
2069 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2070 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2072 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2073 assert_eq!(route.paths[0][4].short_channel_id, 8);
2074 assert_eq!(route.paths[0][4].fee_msat, 100);
2075 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2076 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2077 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2081 fn our_chans_last_hop_connect_test() {
2082 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2083 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2085 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
2086 let our_chans = vec![channelmanager::ChannelDetails {
2087 channel_id: [0; 32],
2088 short_channel_id: Some(42),
2089 remote_network_id: nodes[3].clone(),
2090 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
2091 channel_value_satoshis: 0,
2093 outbound_capacity_msat: 250_000_000,
2094 inbound_capacity_msat: 0,
2096 counterparty_forwarding_info: None,
2098 let mut last_hops = last_hops(&nodes);
2099 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[6], None, Some(&our_chans.iter().collect::<Vec<_>>()), &last_hops.iter().collect::<Vec<_>>(), 100, 42, Arc::clone(&logger)).unwrap();
2100 assert_eq!(route.paths[0].len(), 2);
2102 assert_eq!(route.paths[0][0].pubkey, nodes[3]);
2103 assert_eq!(route.paths[0][0].short_channel_id, 42);
2104 assert_eq!(route.paths[0][0].fee_msat, 0);
2105 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
2106 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2107 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2109 assert_eq!(route.paths[0][1].pubkey, nodes[6]);
2110 assert_eq!(route.paths[0][1].short_channel_id, 8);
2111 assert_eq!(route.paths[0][1].fee_msat, 100);
2112 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2113 assert_eq!(route.paths[0][1].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2114 assert_eq!(route.paths[0][1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2116 last_hops[0].fees.base_msat = 1000;
2118 // Revert to via 6 as the fee on 8 goes up
2119 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[6], None, None, &last_hops.iter().collect::<Vec<_>>(), 100, 42, Arc::clone(&logger)).unwrap();
2120 assert_eq!(route.paths[0].len(), 4);
2122 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2123 assert_eq!(route.paths[0][0].short_channel_id, 2);
2124 assert_eq!(route.paths[0][0].fee_msat, 200); // fee increased as its % of value transferred across node
2125 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2126 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2127 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2129 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2130 assert_eq!(route.paths[0][1].short_channel_id, 4);
2131 assert_eq!(route.paths[0][1].fee_msat, 100);
2132 assert_eq!(route.paths[0][1].cltv_expiry_delta, (7 << 8) | 1);
2133 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2134 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2136 assert_eq!(route.paths[0][2].pubkey, nodes[5]);
2137 assert_eq!(route.paths[0][2].short_channel_id, 7);
2138 assert_eq!(route.paths[0][2].fee_msat, 0);
2139 assert_eq!(route.paths[0][2].cltv_expiry_delta, (10 << 8) | 1);
2140 // If we have a peer in the node map, we'll use their features here since we don't have
2141 // a way of figuring out their features from the invoice:
2142 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
2143 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(7));
2145 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2146 assert_eq!(route.paths[0][3].short_channel_id, 10);
2147 assert_eq!(route.paths[0][3].fee_msat, 100);
2148 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2149 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2150 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2152 // ...but still use 8 for larger payments as 6 has a variable feerate
2153 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[6], None, None, &last_hops.iter().collect::<Vec<_>>(), 2000, 42, Arc::clone(&logger)).unwrap();
2154 assert_eq!(route.paths[0].len(), 5);
2156 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2157 assert_eq!(route.paths[0][0].short_channel_id, 2);
2158 assert_eq!(route.paths[0][0].fee_msat, 3000);
2159 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2160 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2161 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2163 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2164 assert_eq!(route.paths[0][1].short_channel_id, 4);
2165 assert_eq!(route.paths[0][1].fee_msat, 0);
2166 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2167 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2168 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2170 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2171 assert_eq!(route.paths[0][2].short_channel_id, 6);
2172 assert_eq!(route.paths[0][2].fee_msat, 0);
2173 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2174 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2175 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2177 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2178 assert_eq!(route.paths[0][3].short_channel_id, 11);
2179 assert_eq!(route.paths[0][3].fee_msat, 1000);
2180 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2181 // If we have a peer in the node map, we'll use their features here since we don't have
2182 // a way of figuring out their features from the invoice:
2183 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2184 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2186 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2187 assert_eq!(route.paths[0][4].short_channel_id, 8);
2188 assert_eq!(route.paths[0][4].fee_msat, 2000);
2189 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2190 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2191 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2195 fn unannounced_path_test() {
2196 // We should be able to send a payment to a destination without any help of a routing graph
2197 // if we have a channel with a common counterparty that appears in the first and last hop
2199 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
2200 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
2201 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
2203 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
2204 let last_hops = vec![RouteHint {
2205 src_node_id: middle_node_id,
2206 short_channel_id: 8,
2209 proportional_millionths: 0,
2211 cltv_expiry_delta: (8 << 8) | 1,
2212 htlc_minimum_msat: None,
2213 htlc_maximum_msat: None,
2215 let our_chans = vec![channelmanager::ChannelDetails {
2216 channel_id: [0; 32],
2217 short_channel_id: Some(42),
2218 remote_network_id: middle_node_id,
2219 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
2220 channel_value_satoshis: 100000,
2222 outbound_capacity_msat: 100000,
2223 inbound_capacity_msat: 100000,
2225 counterparty_forwarding_info: None,
2227 let route = get_route(&source_node_id, &NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()), &target_node_id, None, Some(&our_chans.iter().collect::<Vec<_>>()), &last_hops.iter().collect::<Vec<_>>(), 100, 42, Arc::new(test_utils::TestLogger::new())).unwrap();
2229 assert_eq!(route.paths[0].len(), 2);
2231 assert_eq!(route.paths[0][0].pubkey, middle_node_id);
2232 assert_eq!(route.paths[0][0].short_channel_id, 42);
2233 assert_eq!(route.paths[0][0].fee_msat, 1000);
2234 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
2235 assert_eq!(route.paths[0][0].node_features.le_flags(), &[0b11]);
2236 assert_eq!(route.paths[0][0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
2238 assert_eq!(route.paths[0][1].pubkey, target_node_id);
2239 assert_eq!(route.paths[0][1].short_channel_id, 8);
2240 assert_eq!(route.paths[0][1].fee_msat, 100);
2241 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2242 assert_eq!(route.paths[0][1].node_features.le_flags(), &[0; 0]); // We dont pass flags in from invoices yet
2243 assert_eq!(route.paths[0][1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
2247 fn available_amount_while_routing_test() {
2248 // Tests whether we choose the correct available channel amount while routing.
2250 let (secp_ctx, mut net_graph_msg_handler, chain_monitor, logger) = build_graph();
2251 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2253 // We will use a simple single-path route from
2254 // our node to node2 via node0: channels {1, 3}.
2256 // First disable all other paths.
2257 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2258 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2259 short_channel_id: 2,
2262 cltv_expiry_delta: 0,
2263 htlc_minimum_msat: 0,
2264 htlc_maximum_msat: OptionalField::Present(100_000),
2266 fee_proportional_millionths: 0,
2267 excess_data: Vec::new()
2269 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2270 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2271 short_channel_id: 12,
2274 cltv_expiry_delta: 0,
2275 htlc_minimum_msat: 0,
2276 htlc_maximum_msat: OptionalField::Present(100_000),
2278 fee_proportional_millionths: 0,
2279 excess_data: Vec::new()
2282 // Make the first channel (#1) very permissive,
2283 // and we will be testing all limits on the second channel.
2284 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2285 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2286 short_channel_id: 1,
2289 cltv_expiry_delta: 0,
2290 htlc_minimum_msat: 0,
2291 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2293 fee_proportional_millionths: 0,
2294 excess_data: Vec::new()
2297 // First, let's see if routing works if we have absolutely no idea about the available amount.
2298 // In this case, it should be set to 250_000 sats.
2299 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2300 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2301 short_channel_id: 3,
2304 cltv_expiry_delta: 0,
2305 htlc_minimum_msat: 0,
2306 htlc_maximum_msat: OptionalField::Absent,
2308 fee_proportional_millionths: 0,
2309 excess_data: Vec::new()
2313 // Attempt to route more than available results in a failure.
2314 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2315 Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000_001, 42, Arc::clone(&logger)) {
2316 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2317 } else { panic!(); }
2321 // Now, attempt to route an exact amount we have should be fine.
2322 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2323 Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000_000, 42, Arc::clone(&logger)).unwrap();
2324 assert_eq!(route.paths.len(), 1);
2325 let path = route.paths.last().unwrap();
2326 assert_eq!(path.len(), 2);
2327 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2328 assert_eq!(path.last().unwrap().fee_msat, 250_000_000);
2331 // Check that setting outbound_capacity_msat in first_hops limits the channels.
2332 // Disable channel #1 and use another first hop.
2333 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2334 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2335 short_channel_id: 1,
2338 cltv_expiry_delta: 0,
2339 htlc_minimum_msat: 0,
2340 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2342 fee_proportional_millionths: 0,
2343 excess_data: Vec::new()
2346 // Now, limit the first_hop by the outbound_capacity_msat of 200_000 sats.
2347 let our_chans = vec![channelmanager::ChannelDetails {
2348 channel_id: [0; 32],
2349 short_channel_id: Some(42),
2350 remote_network_id: nodes[0].clone(),
2351 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
2352 channel_value_satoshis: 0,
2354 outbound_capacity_msat: 200_000_000,
2355 inbound_capacity_msat: 0,
2357 counterparty_forwarding_info: None,
2361 // Attempt to route more than available results in a failure.
2362 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2363 Some(InvoiceFeatures::known()), Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 200_000_001, 42, Arc::clone(&logger)) {
2364 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2365 } else { panic!(); }
2369 // Now, attempt to route an exact amount we have should be fine.
2370 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2371 Some(InvoiceFeatures::known()), Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 200_000_000, 42, Arc::clone(&logger)).unwrap();
2372 assert_eq!(route.paths.len(), 1);
2373 let path = route.paths.last().unwrap();
2374 assert_eq!(path.len(), 2);
2375 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2376 assert_eq!(path.last().unwrap().fee_msat, 200_000_000);
2379 // Enable channel #1 back.
2380 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2381 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2382 short_channel_id: 1,
2385 cltv_expiry_delta: 0,
2386 htlc_minimum_msat: 0,
2387 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2389 fee_proportional_millionths: 0,
2390 excess_data: Vec::new()
2394 // Now let's see if routing works if we know only htlc_maximum_msat.
2395 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2396 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2397 short_channel_id: 3,
2400 cltv_expiry_delta: 0,
2401 htlc_minimum_msat: 0,
2402 htlc_maximum_msat: OptionalField::Present(15_000),
2404 fee_proportional_millionths: 0,
2405 excess_data: Vec::new()
2409 // Attempt to route more than available results in a failure.
2410 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2411 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_001, 42, Arc::clone(&logger)) {
2412 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2413 } else { panic!(); }
2417 // Now, attempt to route an exact amount we have should be fine.
2418 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2419 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_000, 42, Arc::clone(&logger)).unwrap();
2420 assert_eq!(route.paths.len(), 1);
2421 let path = route.paths.last().unwrap();
2422 assert_eq!(path.len(), 2);
2423 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2424 assert_eq!(path.last().unwrap().fee_msat, 15_000);
2427 // Now let's see if routing works if we know only capacity from the UTXO.
2429 // We can't change UTXO capacity on the fly, so we'll disable
2430 // the existing channel and add another one with the capacity we need.
2431 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2432 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2433 short_channel_id: 3,
2436 cltv_expiry_delta: 0,
2437 htlc_minimum_msat: 0,
2438 htlc_maximum_msat: OptionalField::Absent,
2440 fee_proportional_millionths: 0,
2441 excess_data: Vec::new()
2444 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
2445 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
2446 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
2447 .push_opcode(opcodes::all::OP_PUSHNUM_2)
2448 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
2450 *chain_monitor.utxo_ret.lock().unwrap() = Ok(TxOut { value: 15, script_pubkey: good_script.clone() });
2451 net_graph_msg_handler.add_chain_access(Some(chain_monitor));
2453 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
2454 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2455 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2456 short_channel_id: 333,
2459 cltv_expiry_delta: (3 << 8) | 1,
2460 htlc_minimum_msat: 0,
2461 htlc_maximum_msat: OptionalField::Absent,
2463 fee_proportional_millionths: 0,
2464 excess_data: Vec::new()
2466 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2467 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2468 short_channel_id: 333,
2471 cltv_expiry_delta: (3 << 8) | 2,
2472 htlc_minimum_msat: 0,
2473 htlc_maximum_msat: OptionalField::Absent,
2475 fee_proportional_millionths: 0,
2476 excess_data: Vec::new()
2480 // Attempt to route more than available results in a failure.
2481 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2482 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_001, 42, Arc::clone(&logger)) {
2483 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2484 } else { panic!(); }
2488 // Now, attempt to route an exact amount we have should be fine.
2489 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2490 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_000, 42, Arc::clone(&logger)).unwrap();
2491 assert_eq!(route.paths.len(), 1);
2492 let path = route.paths.last().unwrap();
2493 assert_eq!(path.len(), 2);
2494 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2495 assert_eq!(path.last().unwrap().fee_msat, 15_000);
2498 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
2499 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2500 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2501 short_channel_id: 333,
2504 cltv_expiry_delta: 0,
2505 htlc_minimum_msat: 0,
2506 htlc_maximum_msat: OptionalField::Present(10_000),
2508 fee_proportional_millionths: 0,
2509 excess_data: Vec::new()
2513 // Attempt to route more than available results in a failure.
2514 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2515 Some(InvoiceFeatures::known()), None, &Vec::new(), 10_001, 42, Arc::clone(&logger)) {
2516 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2517 } else { panic!(); }
2521 // Now, attempt to route an exact amount we have should be fine.
2522 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2523 Some(InvoiceFeatures::known()), None, &Vec::new(), 10_000, 42, Arc::clone(&logger)).unwrap();
2524 assert_eq!(route.paths.len(), 1);
2525 let path = route.paths.last().unwrap();
2526 assert_eq!(path.len(), 2);
2527 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2528 assert_eq!(path.last().unwrap().fee_msat, 10_000);
2533 fn available_liquidity_last_hop_test() {
2534 // Check that available liquidity properly limits the path even when only
2535 // one of the latter hops is limited.
2536 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2537 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2539 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
2540 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
2541 // Total capacity: 50 sats.
2543 // Disable other potential paths.
2544 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2545 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2546 short_channel_id: 2,
2549 cltv_expiry_delta: 0,
2550 htlc_minimum_msat: 0,
2551 htlc_maximum_msat: OptionalField::Present(100_000),
2553 fee_proportional_millionths: 0,
2554 excess_data: Vec::new()
2556 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2557 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2558 short_channel_id: 7,
2561 cltv_expiry_delta: 0,
2562 htlc_minimum_msat: 0,
2563 htlc_maximum_msat: OptionalField::Present(100_000),
2565 fee_proportional_millionths: 0,
2566 excess_data: Vec::new()
2571 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2572 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2573 short_channel_id: 12,
2576 cltv_expiry_delta: 0,
2577 htlc_minimum_msat: 0,
2578 htlc_maximum_msat: OptionalField::Present(100_000),
2580 fee_proportional_millionths: 0,
2581 excess_data: Vec::new()
2583 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2584 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2585 short_channel_id: 13,
2588 cltv_expiry_delta: 0,
2589 htlc_minimum_msat: 0,
2590 htlc_maximum_msat: OptionalField::Present(100_000),
2592 fee_proportional_millionths: 0,
2593 excess_data: Vec::new()
2596 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2597 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2598 short_channel_id: 6,
2601 cltv_expiry_delta: 0,
2602 htlc_minimum_msat: 0,
2603 htlc_maximum_msat: OptionalField::Present(50_000),
2605 fee_proportional_millionths: 0,
2606 excess_data: Vec::new()
2608 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
2609 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2610 short_channel_id: 11,
2613 cltv_expiry_delta: 0,
2614 htlc_minimum_msat: 0,
2615 htlc_maximum_msat: OptionalField::Present(100_000),
2617 fee_proportional_millionths: 0,
2618 excess_data: Vec::new()
2621 // Attempt to route more than available results in a failure.
2622 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
2623 Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger)) {
2624 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2625 } else { panic!(); }
2629 // Now, attempt to route 49 sats (just a bit below the capacity).
2630 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
2631 Some(InvoiceFeatures::known()), None, &Vec::new(), 49_000, 42, Arc::clone(&logger)).unwrap();
2632 assert_eq!(route.paths.len(), 1);
2633 let mut total_amount_paid_msat = 0;
2634 for path in &route.paths {
2635 assert_eq!(path.len(), 4);
2636 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
2637 total_amount_paid_msat += path.last().unwrap().fee_msat;
2639 assert_eq!(total_amount_paid_msat, 49_000);
2643 // Attempt to route an exact amount is also fine
2644 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
2645 Some(InvoiceFeatures::known()), None, &Vec::new(), 50_000, 42, Arc::clone(&logger)).unwrap();
2646 assert_eq!(route.paths.len(), 1);
2647 let mut total_amount_paid_msat = 0;
2648 for path in &route.paths {
2649 assert_eq!(path.len(), 4);
2650 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
2651 total_amount_paid_msat += path.last().unwrap().fee_msat;
2653 assert_eq!(total_amount_paid_msat, 50_000);
2658 fn ignore_fee_first_hop_test() {
2659 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2660 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2662 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
2663 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2664 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2665 short_channel_id: 1,
2668 cltv_expiry_delta: 0,
2669 htlc_minimum_msat: 0,
2670 htlc_maximum_msat: OptionalField::Present(100_000),
2671 fee_base_msat: 1_000_000,
2672 fee_proportional_millionths: 0,
2673 excess_data: Vec::new()
2675 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2676 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2677 short_channel_id: 3,
2680 cltv_expiry_delta: 0,
2681 htlc_minimum_msat: 0,
2682 htlc_maximum_msat: OptionalField::Present(50_000),
2684 fee_proportional_millionths: 0,
2685 excess_data: Vec::new()
2689 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, None, &Vec::new(), 50_000, 42, Arc::clone(&logger)).unwrap();
2690 assert_eq!(route.paths.len(), 1);
2691 let mut total_amount_paid_msat = 0;
2692 for path in &route.paths {
2693 assert_eq!(path.len(), 2);
2694 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2695 total_amount_paid_msat += path.last().unwrap().fee_msat;
2697 assert_eq!(total_amount_paid_msat, 50_000);
2702 fn simple_mpp_route_test() {
2703 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2704 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2706 // We need a route consisting of 3 paths:
2707 // From our node to node2 via node0, node7, node1 (three paths one hop each).
2708 // To achieve this, the amount being transferred should be around
2709 // the total capacity of these 3 paths.
2711 // First, we set limits on these (previously unlimited) channels.
2712 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
2714 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
2715 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2716 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2717 short_channel_id: 1,
2720 cltv_expiry_delta: 0,
2721 htlc_minimum_msat: 0,
2722 htlc_maximum_msat: OptionalField::Present(100_000),
2724 fee_proportional_millionths: 0,
2725 excess_data: Vec::new()
2727 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2728 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2729 short_channel_id: 3,
2732 cltv_expiry_delta: 0,
2733 htlc_minimum_msat: 0,
2734 htlc_maximum_msat: OptionalField::Present(50_000),
2736 fee_proportional_millionths: 0,
2737 excess_data: Vec::new()
2740 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
2741 // (total limit 60).
2742 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2743 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2744 short_channel_id: 12,
2747 cltv_expiry_delta: 0,
2748 htlc_minimum_msat: 0,
2749 htlc_maximum_msat: OptionalField::Present(60_000),
2751 fee_proportional_millionths: 0,
2752 excess_data: Vec::new()
2754 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2755 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2756 short_channel_id: 13,
2759 cltv_expiry_delta: 0,
2760 htlc_minimum_msat: 0,
2761 htlc_maximum_msat: OptionalField::Present(60_000),
2763 fee_proportional_millionths: 0,
2764 excess_data: Vec::new()
2767 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
2768 // (total capacity 180 sats).
2769 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2770 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2771 short_channel_id: 2,
2774 cltv_expiry_delta: 0,
2775 htlc_minimum_msat: 0,
2776 htlc_maximum_msat: OptionalField::Present(200_000),
2778 fee_proportional_millionths: 0,
2779 excess_data: Vec::new()
2781 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2782 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2783 short_channel_id: 4,
2786 cltv_expiry_delta: 0,
2787 htlc_minimum_msat: 0,
2788 htlc_maximum_msat: OptionalField::Present(180_000),
2790 fee_proportional_millionths: 0,
2791 excess_data: Vec::new()
2795 // Attempt to route more than available results in a failure.
2796 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(),
2797 &nodes[2], Some(InvoiceFeatures::known()), None, &Vec::new(), 300_000, 42, Arc::clone(&logger)) {
2798 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2799 } else { panic!(); }
2803 // Now, attempt to route 250 sats (just a bit below the capacity).
2804 // Our algorithm should provide us with these 3 paths.
2805 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2806 Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000, 42, Arc::clone(&logger)).unwrap();
2807 assert_eq!(route.paths.len(), 3);
2808 let mut total_amount_paid_msat = 0;
2809 for path in &route.paths {
2810 assert_eq!(path.len(), 2);
2811 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2812 total_amount_paid_msat += path.last().unwrap().fee_msat;
2814 assert_eq!(total_amount_paid_msat, 250_000);
2818 // Attempt to route an exact amount is also fine
2819 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2820 Some(InvoiceFeatures::known()), None, &Vec::new(), 290_000, 42, Arc::clone(&logger)).unwrap();
2821 assert_eq!(route.paths.len(), 3);
2822 let mut total_amount_paid_msat = 0;
2823 for path in &route.paths {
2824 assert_eq!(path.len(), 2);
2825 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2826 total_amount_paid_msat += path.last().unwrap().fee_msat;
2828 assert_eq!(total_amount_paid_msat, 290_000);
2833 fn long_mpp_route_test() {
2834 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2835 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2837 // We need a route consisting of 3 paths:
2838 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
2839 // Note that these paths overlap (channels 5, 12, 13).
2840 // We will route 300 sats.
2841 // Each path will have 100 sats capacity, those channels which
2842 // are used twice will have 200 sats capacity.
2844 // Disable other potential paths.
2845 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2846 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2847 short_channel_id: 2,
2850 cltv_expiry_delta: 0,
2851 htlc_minimum_msat: 0,
2852 htlc_maximum_msat: OptionalField::Present(100_000),
2854 fee_proportional_millionths: 0,
2855 excess_data: Vec::new()
2857 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2858 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2859 short_channel_id: 7,
2862 cltv_expiry_delta: 0,
2863 htlc_minimum_msat: 0,
2864 htlc_maximum_msat: OptionalField::Present(100_000),
2866 fee_proportional_millionths: 0,
2867 excess_data: Vec::new()
2870 // Path via {node0, node2} is channels {1, 3, 5}.
2871 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2872 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2873 short_channel_id: 1,
2876 cltv_expiry_delta: 0,
2877 htlc_minimum_msat: 0,
2878 htlc_maximum_msat: OptionalField::Present(100_000),
2880 fee_proportional_millionths: 0,
2881 excess_data: Vec::new()
2883 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2884 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2885 short_channel_id: 3,
2888 cltv_expiry_delta: 0,
2889 htlc_minimum_msat: 0,
2890 htlc_maximum_msat: OptionalField::Present(100_000),
2892 fee_proportional_millionths: 0,
2893 excess_data: Vec::new()
2896 // Capacity of 200 sats because this channel will be used by 3rd path as well.
2897 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
2898 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2899 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2900 short_channel_id: 5,
2903 cltv_expiry_delta: 0,
2904 htlc_minimum_msat: 0,
2905 htlc_maximum_msat: OptionalField::Present(200_000),
2907 fee_proportional_millionths: 0,
2908 excess_data: Vec::new()
2911 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
2912 // Add 100 sats to the capacities of {12, 13}, because these channels
2913 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
2914 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2915 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2916 short_channel_id: 12,
2919 cltv_expiry_delta: 0,
2920 htlc_minimum_msat: 0,
2921 htlc_maximum_msat: OptionalField::Present(200_000),
2923 fee_proportional_millionths: 0,
2924 excess_data: Vec::new()
2926 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2927 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2928 short_channel_id: 13,
2931 cltv_expiry_delta: 0,
2932 htlc_minimum_msat: 0,
2933 htlc_maximum_msat: OptionalField::Present(200_000),
2935 fee_proportional_millionths: 0,
2936 excess_data: Vec::new()
2939 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2940 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2941 short_channel_id: 6,
2944 cltv_expiry_delta: 0,
2945 htlc_minimum_msat: 0,
2946 htlc_maximum_msat: OptionalField::Present(100_000),
2948 fee_proportional_millionths: 0,
2949 excess_data: Vec::new()
2951 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
2952 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2953 short_channel_id: 11,
2956 cltv_expiry_delta: 0,
2957 htlc_minimum_msat: 0,
2958 htlc_maximum_msat: OptionalField::Present(100_000),
2960 fee_proportional_millionths: 0,
2961 excess_data: Vec::new()
2964 // Path via {node7, node2} is channels {12, 13, 5}.
2965 // We already limited them to 200 sats (they are used twice for 100 sats).
2966 // Nothing to do here.
2969 // Attempt to route more than available results in a failure.
2970 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
2971 Some(InvoiceFeatures::known()), None, &Vec::new(), 350_000, 42, Arc::clone(&logger)) {
2972 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2973 } else { panic!(); }
2977 // Now, attempt to route 300 sats (exact amount we can route).
2978 // Our algorithm should provide us with these 3 paths, 100 sats each.
2979 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
2980 Some(InvoiceFeatures::known()), None, &Vec::new(), 300_000, 42, Arc::clone(&logger)).unwrap();
2981 assert_eq!(route.paths.len(), 3);
2983 let mut total_amount_paid_msat = 0;
2984 for path in &route.paths {
2985 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
2986 total_amount_paid_msat += path.last().unwrap().fee_msat;
2988 assert_eq!(total_amount_paid_msat, 300_000);
2994 fn mpp_cheaper_route_test() {
2995 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2996 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2998 // This test checks that if we have two cheaper paths and one more expensive path,
2999 // so that liquidity-wise any 2 of 3 combination is sufficient,
3000 // two cheaper paths will be taken.
3001 // These paths have equal available liquidity.
3003 // We need a combination of 3 paths:
3004 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3005 // Note that these paths overlap (channels 5, 12, 13).
3006 // Each path will have 100 sats capacity, those channels which
3007 // are used twice will have 200 sats capacity.
3009 // Disable other potential paths.
3010 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3011 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3012 short_channel_id: 2,
3015 cltv_expiry_delta: 0,
3016 htlc_minimum_msat: 0,
3017 htlc_maximum_msat: OptionalField::Present(100_000),
3019 fee_proportional_millionths: 0,
3020 excess_data: Vec::new()
3022 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3023 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3024 short_channel_id: 7,
3027 cltv_expiry_delta: 0,
3028 htlc_minimum_msat: 0,
3029 htlc_maximum_msat: OptionalField::Present(100_000),
3031 fee_proportional_millionths: 0,
3032 excess_data: Vec::new()
3035 // Path via {node0, node2} is channels {1, 3, 5}.
3036 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3037 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3038 short_channel_id: 1,
3041 cltv_expiry_delta: 0,
3042 htlc_minimum_msat: 0,
3043 htlc_maximum_msat: OptionalField::Present(100_000),
3045 fee_proportional_millionths: 0,
3046 excess_data: Vec::new()
3048 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3049 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3050 short_channel_id: 3,
3053 cltv_expiry_delta: 0,
3054 htlc_minimum_msat: 0,
3055 htlc_maximum_msat: OptionalField::Present(100_000),
3057 fee_proportional_millionths: 0,
3058 excess_data: Vec::new()
3061 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3062 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3063 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3064 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3065 short_channel_id: 5,
3068 cltv_expiry_delta: 0,
3069 htlc_minimum_msat: 0,
3070 htlc_maximum_msat: OptionalField::Present(200_000),
3072 fee_proportional_millionths: 0,
3073 excess_data: Vec::new()
3076 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3077 // Add 100 sats to the capacities of {12, 13}, because these channels
3078 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3079 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3080 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3081 short_channel_id: 12,
3084 cltv_expiry_delta: 0,
3085 htlc_minimum_msat: 0,
3086 htlc_maximum_msat: OptionalField::Present(200_000),
3088 fee_proportional_millionths: 0,
3089 excess_data: Vec::new()
3091 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3092 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3093 short_channel_id: 13,
3096 cltv_expiry_delta: 0,
3097 htlc_minimum_msat: 0,
3098 htlc_maximum_msat: OptionalField::Present(200_000),
3100 fee_proportional_millionths: 0,
3101 excess_data: Vec::new()
3104 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3105 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3106 short_channel_id: 6,
3109 cltv_expiry_delta: 0,
3110 htlc_minimum_msat: 0,
3111 htlc_maximum_msat: OptionalField::Present(100_000),
3112 fee_base_msat: 1_000,
3113 fee_proportional_millionths: 0,
3114 excess_data: Vec::new()
3116 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3117 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3118 short_channel_id: 11,
3121 cltv_expiry_delta: 0,
3122 htlc_minimum_msat: 0,
3123 htlc_maximum_msat: OptionalField::Present(100_000),
3125 fee_proportional_millionths: 0,
3126 excess_data: Vec::new()
3129 // Path via {node7, node2} is channels {12, 13, 5}.
3130 // We already limited them to 200 sats (they are used twice for 100 sats).
3131 // Nothing to do here.
3134 // Now, attempt to route 180 sats.
3135 // Our algorithm should provide us with these 2 paths.
3136 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3137 Some(InvoiceFeatures::known()), None, &Vec::new(), 180_000, 42, Arc::clone(&logger)).unwrap();
3138 assert_eq!(route.paths.len(), 2);
3140 let mut total_value_transferred_msat = 0;
3141 let mut total_paid_msat = 0;
3142 for path in &route.paths {
3143 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3144 total_value_transferred_msat += path.last().unwrap().fee_msat;
3146 total_paid_msat += hop.fee_msat;
3149 // If we paid fee, this would be higher.
3150 assert_eq!(total_value_transferred_msat, 180_000);
3151 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
3152 assert_eq!(total_fees_paid, 0);
3157 fn fees_on_mpp_route_test() {
3158 // This test makes sure that MPP algorithm properly takes into account
3159 // fees charged on the channels, by making the fees impactful:
3160 // if the fee is not properly accounted for, the behavior is different.
3161 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3162 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3164 // We need a route consisting of 2 paths:
3165 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
3166 // We will route 200 sats, Each path will have 100 sats capacity.
3168 // This test is not particularly stable: e.g.,
3169 // there's a way to route via {node0, node2, node4}.
3170 // It works while pathfinding is deterministic, but can be broken otherwise.
3171 // It's fine to ignore this concern for now.
3173 // Disable other potential paths.
3174 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3175 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3176 short_channel_id: 2,
3179 cltv_expiry_delta: 0,
3180 htlc_minimum_msat: 0,
3181 htlc_maximum_msat: OptionalField::Present(100_000),
3183 fee_proportional_millionths: 0,
3184 excess_data: Vec::new()
3187 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3188 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3189 short_channel_id: 7,
3192 cltv_expiry_delta: 0,
3193 htlc_minimum_msat: 0,
3194 htlc_maximum_msat: OptionalField::Present(100_000),
3196 fee_proportional_millionths: 0,
3197 excess_data: Vec::new()
3200 // Path via {node0, node2} is channels {1, 3, 5}.
3201 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3202 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3203 short_channel_id: 1,
3206 cltv_expiry_delta: 0,
3207 htlc_minimum_msat: 0,
3208 htlc_maximum_msat: OptionalField::Present(100_000),
3210 fee_proportional_millionths: 0,
3211 excess_data: Vec::new()
3213 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3214 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3215 short_channel_id: 3,
3218 cltv_expiry_delta: 0,
3219 htlc_minimum_msat: 0,
3220 htlc_maximum_msat: OptionalField::Present(100_000),
3222 fee_proportional_millionths: 0,
3223 excess_data: Vec::new()
3226 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3227 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3228 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3229 short_channel_id: 5,
3232 cltv_expiry_delta: 0,
3233 htlc_minimum_msat: 0,
3234 htlc_maximum_msat: OptionalField::Present(100_000),
3236 fee_proportional_millionths: 0,
3237 excess_data: Vec::new()
3240 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3241 // All channels should be 100 sats capacity. But for the fee experiment,
3242 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
3243 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
3244 // 100 sats (and pay 150 sats in fees for the use of channel 6),
3245 // so no matter how large are other channels,
3246 // the whole path will be limited by 100 sats with just these 2 conditions:
3247 // - channel 12 capacity is 250 sats
3248 // - fee for channel 6 is 150 sats
3249 // Let's test this by enforcing these 2 conditions and removing other limits.
3250 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3251 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3252 short_channel_id: 12,
3255 cltv_expiry_delta: 0,
3256 htlc_minimum_msat: 0,
3257 htlc_maximum_msat: OptionalField::Present(250_000),
3259 fee_proportional_millionths: 0,
3260 excess_data: Vec::new()
3262 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3263 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3264 short_channel_id: 13,
3267 cltv_expiry_delta: 0,
3268 htlc_minimum_msat: 0,
3269 htlc_maximum_msat: OptionalField::Absent,
3271 fee_proportional_millionths: 0,
3272 excess_data: Vec::new()
3275 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3276 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3277 short_channel_id: 6,
3280 cltv_expiry_delta: 0,
3281 htlc_minimum_msat: 0,
3282 htlc_maximum_msat: OptionalField::Absent,
3283 fee_base_msat: 150_000,
3284 fee_proportional_millionths: 0,
3285 excess_data: Vec::new()
3287 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3288 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3289 short_channel_id: 11,
3292 cltv_expiry_delta: 0,
3293 htlc_minimum_msat: 0,
3294 htlc_maximum_msat: OptionalField::Absent,
3296 fee_proportional_millionths: 0,
3297 excess_data: Vec::new()
3301 // Attempt to route more than available results in a failure.
3302 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3303 Some(InvoiceFeatures::known()), None, &Vec::new(), 210_000, 42, Arc::clone(&logger)) {
3304 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3305 } else { panic!(); }
3309 // Now, attempt to route 200 sats (exact amount we can route).
3310 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3311 Some(InvoiceFeatures::known()), None, &Vec::new(), 200_000, 42, Arc::clone(&logger)).unwrap();
3312 assert_eq!(route.paths.len(), 2);
3314 let mut total_amount_paid_msat = 0;
3315 for path in &route.paths {
3316 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3317 total_amount_paid_msat += path.last().unwrap().fee_msat;
3319 assert_eq!(total_amount_paid_msat, 200_000);
3325 fn drop_lowest_channel_mpp_route_test() {
3326 // This test checks that low-capacity channel is dropped when after
3327 // path finding we realize that we found more capacity than we need.
3328 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3329 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3331 // We need a route consisting of 3 paths:
3332 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3334 // The first and the second paths should be sufficient, but the third should be
3335 // cheaper, so that we select it but drop later.
3337 // First, we set limits on these (previously unlimited) channels.
3338 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
3340 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
3341 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3342 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3343 short_channel_id: 1,
3346 cltv_expiry_delta: 0,
3347 htlc_minimum_msat: 0,
3348 htlc_maximum_msat: OptionalField::Present(100_000),
3350 fee_proportional_millionths: 0,
3351 excess_data: Vec::new()
3353 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3354 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3355 short_channel_id: 3,
3358 cltv_expiry_delta: 0,
3359 htlc_minimum_msat: 0,
3360 htlc_maximum_msat: OptionalField::Present(50_000),
3362 fee_proportional_millionths: 0,
3363 excess_data: Vec::new()
3366 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
3367 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3368 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3369 short_channel_id: 12,
3372 cltv_expiry_delta: 0,
3373 htlc_minimum_msat: 0,
3374 htlc_maximum_msat: OptionalField::Present(60_000),
3376 fee_proportional_millionths: 0,
3377 excess_data: Vec::new()
3379 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3380 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3381 short_channel_id: 13,
3384 cltv_expiry_delta: 0,
3385 htlc_minimum_msat: 0,
3386 htlc_maximum_msat: OptionalField::Present(60_000),
3388 fee_proportional_millionths: 0,
3389 excess_data: Vec::new()
3392 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
3393 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3394 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3395 short_channel_id: 2,
3398 cltv_expiry_delta: 0,
3399 htlc_minimum_msat: 0,
3400 htlc_maximum_msat: OptionalField::Present(20_000),
3402 fee_proportional_millionths: 0,
3403 excess_data: Vec::new()
3405 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3406 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3407 short_channel_id: 4,
3410 cltv_expiry_delta: 0,
3411 htlc_minimum_msat: 0,
3412 htlc_maximum_msat: OptionalField::Present(20_000),
3414 fee_proportional_millionths: 0,
3415 excess_data: Vec::new()
3419 // Attempt to route more than available results in a failure.
3420 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
3421 Some(InvoiceFeatures::known()), None, &Vec::new(), 150_000, 42, Arc::clone(&logger)) {
3422 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3423 } else { panic!(); }
3427 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
3428 // Our algorithm should provide us with these 3 paths.
3429 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
3430 Some(InvoiceFeatures::known()), None, &Vec::new(), 125_000, 42, Arc::clone(&logger)).unwrap();
3431 assert_eq!(route.paths.len(), 3);
3432 let mut total_amount_paid_msat = 0;
3433 for path in &route.paths {
3434 assert_eq!(path.len(), 2);
3435 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3436 total_amount_paid_msat += path.last().unwrap().fee_msat;
3438 assert_eq!(total_amount_paid_msat, 125_000);
3442 // Attempt to route without the last small cheap channel
3443 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
3444 Some(InvoiceFeatures::known()), None, &Vec::new(), 90_000, 42, Arc::clone(&logger)).unwrap();
3445 assert_eq!(route.paths.len(), 2);
3446 let mut total_amount_paid_msat = 0;
3447 for path in &route.paths {
3448 assert_eq!(path.len(), 2);
3449 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3450 total_amount_paid_msat += path.last().unwrap().fee_msat;
3452 assert_eq!(total_amount_paid_msat, 90_000);
3457 fn exact_fee_liquidity_limit() {
3458 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
3459 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
3460 // we calculated fees on a higher value, resulting in us ignoring such paths.
3461 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3462 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
3464 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
3466 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3467 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3468 short_channel_id: 2,
3471 cltv_expiry_delta: 0,
3472 htlc_minimum_msat: 0,
3473 htlc_maximum_msat: OptionalField::Present(85_000),
3475 fee_proportional_millionths: 0,
3476 excess_data: Vec::new()
3479 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3480 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3481 short_channel_id: 12,
3484 cltv_expiry_delta: (4 << 8) | 1,
3485 htlc_minimum_msat: 0,
3486 htlc_maximum_msat: OptionalField::Present(270_000),
3488 fee_proportional_millionths: 1000000,
3489 excess_data: Vec::new()
3493 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
3494 // 200% fee charged channel 13 in the 1-to-2 direction.
3495 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, None, &Vec::new(), 90_000, 42, Arc::clone(&logger)).unwrap();
3496 assert_eq!(route.paths.len(), 1);
3497 assert_eq!(route.paths[0].len(), 2);
3499 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
3500 assert_eq!(route.paths[0][0].short_channel_id, 12);
3501 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
3502 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
3503 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
3504 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
3506 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3507 assert_eq!(route.paths[0][1].short_channel_id, 13);
3508 assert_eq!(route.paths[0][1].fee_msat, 90_000);
3509 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3510 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3511 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
3516 #[cfg(all(test, feature = "unstable"))]
3519 use util::logger::{Logger, Record};
3524 struct DummyLogger {}
3525 impl Logger for DummyLogger {
3526 fn log(&self, _record: &Record) {}
3530 fn generate_routes(bench: &mut Bencher) {
3531 let mut d = File::open("net_graph-2021-02-12.bin").expect("Please fetch https://bitcoin.ninja/ldk-net_graph-879e309c128-2020-02-12.bin and place it at lightning/net_graph-2021-02-12.bin");
3532 let graph = NetworkGraph::read(&mut d).unwrap();
3534 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
3535 let mut path_endpoints = Vec::new();
3536 let mut seed: usize = 0xdeadbeef;
3537 'load_endpoints: for _ in 0..100 {
3540 let src = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3542 let dst = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3543 let amt = seed as u64 % 1_000_000;
3544 if get_route(src, &graph, dst, None, None, &[], amt, 42, &DummyLogger{}).is_ok() {
3545 path_endpoints.push((src, dst, amt));
3546 continue 'load_endpoints;
3551 // ...then benchmark finding paths between the nodes we learned.
3554 let (src, dst, amt) = path_endpoints[idx % path_endpoints.len()];
3555 assert!(get_route(src, &graph, dst, None, None, &[], amt, 42, &DummyLogger{}).is_ok());
3561 fn generate_mpp_routes(bench: &mut Bencher) {
3562 let mut d = File::open("net_graph-2021-02-12.bin").expect("Please fetch https://bitcoin.ninja/ldk-net_graph-879e309c128-2020-02-12.bin and place it at lightning/net_graph-2021-02-12.bin");
3563 let graph = NetworkGraph::read(&mut d).unwrap();
3565 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
3566 let mut path_endpoints = Vec::new();
3567 let mut seed: usize = 0xdeadbeef;
3568 'load_endpoints: for _ in 0..100 {
3571 let src = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3573 let dst = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3574 let amt = seed as u64 % 1_000_000;
3575 if get_route(src, &graph, dst, Some(InvoiceFeatures::known()), None, &[], amt, 42, &DummyLogger{}).is_ok() {
3576 path_endpoints.push((src, dst, amt));
3577 continue 'load_endpoints;
3582 // ...then benchmark finding paths between the nodes we learned.
3585 let (src, dst, amt) = path_endpoints[idx % path_endpoints.len()];
3586 assert!(get_route(src, &graph, dst, Some(InvoiceFeatures::known()), None, &[], amt, 42, &DummyLogger{}).is_ok());