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,
147 /// The maximum htlc_minimum_msat along the path, taking into consideration the fees required
148 /// to meet the minimum over the hops required to get there.
149 path_htlc_minimum_msat: u64,
152 impl cmp::Ord for RouteGraphNode {
153 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
154 cmp::max(other.lowest_fee_to_peer_through_node, other.path_htlc_minimum_msat)
155 .cmp(&cmp::max(self.lowest_fee_to_peer_through_node, self.path_htlc_minimum_msat))
156 .then_with(|| other.pubkey.serialize().cmp(&self.pubkey.serialize()))
160 impl cmp::PartialOrd for RouteGraphNode {
161 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
162 Some(self.cmp(other))
166 struct DummyDirectionalChannelInfo {
167 cltv_expiry_delta: u32,
168 htlc_minimum_msat: u64,
169 htlc_maximum_msat: Option<u64>,
173 /// It's useful to keep track of the hops associated with the fees required to use them,
174 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
175 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
176 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
178 struct PathBuildingHop {
179 /// Hop-specific details unrelated to the path during the routing phase,
180 /// but rather relevant to the LN graph.
182 /// Minimal fees required to route to the source node of the current hop via any of its inbound channels.
183 src_lowest_inbound_fees: RoutingFees,
184 /// Fees of the channel used in this hop.
185 channel_fees: RoutingFees,
186 /// All the fees paid *after* this channel on the way to the destination
187 next_hops_fee_msat: u64,
188 /// Fee paid for the use of the current channel (see channel_fees).
189 /// The value will be actually deducted from the counterparty balance on the previous link.
190 hop_use_fee_msat: u64,
191 /// Used to compare channels when choosing the for routing.
192 /// Includes paying for the use of a hop and the following hops, as well as
193 /// an estimated cost of reaching this hop.
194 /// Might get stale when fees are recomputed. Primarily for internal use.
196 /// This is useful for update_value_and_recompute_fees to make sure
197 /// we don't fall below the minimum. Should not be updated manually and
198 /// generally should not be accessed.
199 htlc_minimum_msat: u64,
200 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
201 /// walk and may be invalid thereafter.
202 path_htlc_minimum_msat: u64,
203 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
204 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
205 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
206 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
207 /// avoid processing them again.
211 // Instantiated with a list of hops with correct data in them collected during path finding,
212 // an instance of this struct should be further modified only via given methods.
215 hops: Vec<PathBuildingHop>,
220 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
221 fn get_value_msat(&self) -> u64 {
222 self.hops.last().unwrap().route_hop.fee_msat
225 fn get_total_fee_paid_msat(&self) -> u64 {
226 if self.hops.len() < 1 {
230 // Can't use next_hops_fee_msat because it gets outdated.
231 for (i, hop) in self.hops.iter().enumerate() {
232 if i != self.hops.len() - 1 {
233 result += hop.route_hop.fee_msat;
239 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
240 // to change fees may result in an inconsistency.
242 // Sometimes we call this function right after constructing a path which has inconsistent
243 // (in terms of reaching htlc_minimum_msat), so that this function puts the fees in order.
244 // In that case we call it on the "same" amount we initially allocated for this path, and which
245 // could have been reduced on the way. In that case, there is also a risk of exceeding
246 // available_liquidity inside this function, because the function is unaware of this bound.
247 // In our specific recomputation cases where we never increase the value the risk is pretty low.
248 // This function, however, does not support arbitrarily increasing the value being transferred,
249 // and the exception will be triggered.
250 fn update_value_and_recompute_fees(&mut self, value_msat: u64) {
251 assert!(value_msat <= self.hops.last().unwrap().route_hop.fee_msat);
253 let mut total_fee_paid_msat = 0 as u64;
254 for i in (0..self.hops.len()).rev() {
255 let last_hop = i == self.hops.len() - 1;
257 // For non-last-hop, this value will represent the fees paid on the current hop. It
258 // will consist of the fees for the use of the next hop, and extra fees to match
259 // htlc_minimum_msat of the current channel. Last hop is handled separately.
260 let mut cur_hop_fees_msat = 0;
262 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().hop_use_fee_msat;
265 let mut cur_hop = self.hops.get_mut(i).unwrap();
266 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
267 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
268 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
269 // set it too high just to maliciously take more fees by exploiting this
270 // match htlc_minimum_msat logic.
271 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
272 if let Some(extra_fees_msat) = cur_hop.htlc_minimum_msat.checked_sub(cur_hop_transferred_amount_msat) {
273 // Note that there is a risk that *previous hops* (those closer to us, as we go
274 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
276 // This might make us end up with a broken route, although this should be super-rare
277 // in practice, both because of how healthy channels look like, and how we pick
278 // channels in add_entry.
279 // Also, this can't be exploited more heavily than *announce a free path and fail
281 cur_hop_transferred_amount_msat += extra_fees_msat;
282 total_fee_paid_msat += extra_fees_msat;
283 cur_hop_fees_msat += extra_fees_msat;
287 // Final hop is a special case: it usually has just value_msat (by design), but also
288 // it still could overpay for the htlc_minimum_msat.
289 cur_hop.route_hop.fee_msat = cur_hop_transferred_amount_msat;
291 // Propagate updated fees for the use of the channels to one hop back, where they
292 // will be actually paid (fee_msat). The last hop is handled above separately.
293 cur_hop.route_hop.fee_msat = cur_hop_fees_msat;
296 // Fee for the use of the current hop which will be deducted on the previous hop.
297 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
298 // this channel is free for us.
300 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.channel_fees) {
301 cur_hop.hop_use_fee_msat = new_fee;
302 total_fee_paid_msat += new_fee;
304 // It should not be possible because this function is called only to reduce the
305 // value. In that case, compute_fee was already called with the same fees for
306 // larger amount and there was no overflow.
314 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
315 let proportional_fee_millions =
316 amount_msat.checked_mul(channel_fees.proportional_millionths as u64);
317 if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
318 (channel_fees.base_msat as u64).checked_add(part / 1_000_000) }) {
322 // This function may be (indirectly) called without any verification,
323 // with channel_fees provided by a caller. We should handle it gracefully.
328 /// Gets a route from us (payer) to the given target node (payee).
330 /// If the payee provided features in their invoice, they should be provided via payee_features.
331 /// Without this, MPP will only be used if the payee's features are available in the network graph.
333 /// Extra routing hops between known nodes and the target will be used if they are included in
336 /// If some channels aren't announced, it may be useful to fill in a first_hops with the
337 /// results from a local ChannelManager::list_usable_channels() call. If it is filled in, our
338 /// view of our local channels (from net_graph_msg_handler) will be ignored, and only those
339 /// in first_hops will be used.
341 /// Panics if first_hops contains channels without short_channel_ids
342 /// (ChannelManager::list_usable_channels will never include such channels).
344 /// The fees on channels from us to next-hops are ignored (as they are assumed to all be
345 /// equal), however the enabled/disabled bit on such channels as well as the
346 /// htlc_minimum_msat/htlc_maximum_msat *are* checked as they may change based on the receiving node.
347 pub fn get_route<L: Deref>(our_node_id: &PublicKey, network: &NetworkGraph, payee: &PublicKey, payee_features: Option<InvoiceFeatures>, first_hops: Option<&[&ChannelDetails]>,
348 last_hops: &[&RouteHint], final_value_msat: u64, final_cltv: u32, logger: L) -> Result<Route, LightningError> where L::Target: Logger {
349 // TODO: Obviously *only* using total fee cost sucks. We should consider weighting by
350 // uptime/success in using a node in the past.
351 if *payee == *our_node_id {
352 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
355 if final_value_msat > MAX_VALUE_MSAT {
356 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
359 if final_value_msat == 0 {
360 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
363 for last_hop in last_hops {
364 if last_hop.src_node_id == *payee {
365 return Err(LightningError{err: "Last hop cannot have a payee as a source.".to_owned(), action: ErrorAction::IgnoreError});
369 // The general routing idea is the following:
370 // 1. Fill first/last hops communicated by the caller.
371 // 2. Attempt to construct a path from payer to payee for transferring
372 // any ~sufficient (described later) value.
373 // If succeed, remember which channels were used and how much liquidity they have available,
374 // so that future paths don't rely on the same liquidity.
375 // 3. Prooceed to the next step if:
376 // - we hit the recommended target value;
377 // - OR if we could not construct a new path. Any next attempt will fail too.
378 // Otherwise, repeat step 2.
379 // 4. See if we managed to collect paths which aggregately are able to transfer target value
380 // (not recommended value). If yes, proceed. If not, fail routing.
381 // 5. Randomly combine paths into routes having enough to fulfill the payment. (TODO: knapsack)
382 // 6. Of all the found paths, select only those with the lowest total fee.
383 // 7. The last path in every selected route is likely to be more than we need.
384 // Reduce its value-to-transfer and recompute fees.
385 // 8. Choose the best route by the lowest total fee.
387 // As for the actual search algorithm,
388 // we do a payee-to-payer pseudo-Dijkstra's sorting by each node's distance from the payee
389 // plus the minimum per-HTLC fee to get from it to another node (aka "shitty pseudo-A*").
391 // We are not a faithful Dijkstra's implementation because we can change values which impact
392 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
393 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) then
394 // the value we are currently attempting to send over a path, we simply reduce the value being
395 // sent along the path for any hops after that channel. This may imply that later fees (which
396 // we've already tabulated) are lower because a smaller value is passing through the channels
397 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
398 // channels which were selected earlier (and which may still be used for other paths without a
399 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
402 // One potentially problematic case for this algorithm would be if there are many
403 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
404 // graph walking), we may never find a liquidity-unlimited path which has lower proportional
405 // fee (and only lower absolute fee when considering the ultimate value sent). Because we only
406 // consider paths with at least 5% of the total value being sent, the damage from such a case
407 // should be limited, however this could be further reduced in the future by calculating fees
408 // on the amount we wish to route over a path, not the amount we are routing over a path.
410 // Alternatively, we could store more detailed path information in the heap (targets, below)
411 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
412 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
413 // and practically (as we would need to store dynamically-allocated path information in heap
414 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
415 // results of such an algorithm would likely be biased towards lower-value paths.
417 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
418 // outside of our current search value, running a path search more times to gather candidate
419 // paths at different values. While this may be acceptable, further path searches may increase
420 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
421 // graph for candidate paths, calculating the maximum value which can realistically be sent at
422 // the same time, remaining generic across different payment values.
424 // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
425 // to use as the A* heuristic beyond just the cost to get one node further than the current
428 let dummy_directional_info = DummyDirectionalChannelInfo { // used for first_hops routes
429 cltv_expiry_delta: 0,
430 htlc_minimum_msat: 0,
431 htlc_maximum_msat: None,
434 proportional_millionths: 0,
438 let mut targets = BinaryHeap::new(); //TODO: Do we care about switching to eg Fibbonaci heap?
439 let mut dist = HashMap::with_capacity(network.get_nodes().len());
441 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
442 // indicating that we may wish to try again with a higher value, potentially paying to meet an
443 // htlc_minimum with extra fees while still finding a cheaper path.
444 let mut hit_minimum_limit;
446 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
447 // We start with a path_value of the exact amount we want, and if that generates a route we may
448 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
449 // amount we want in total across paths, selecting the best subset at the end.
450 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
451 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
452 let mut path_value_msat = final_value_msat;
454 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
455 // it. If the payee supports it they're supposed to include it in the invoice, so that should
457 let allow_mpp = if let Some(features) = &payee_features {
458 features.supports_basic_mpp()
459 } else if let Some(node) = network.get_nodes().get(&payee) {
460 if let Some(node_info) = node.announcement_info.as_ref() {
461 node_info.features.supports_basic_mpp()
466 // Prepare the data we'll use for payee-to-payer search by
467 // inserting first hops suggested by the caller as targets.
468 // Our search will then attempt to reach them while traversing from the payee node.
469 let mut first_hop_targets = HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
470 if let Some(hops) = first_hops {
472 let short_channel_id = chan.short_channel_id.expect("first_hops should be filled in with usable channels, not pending ones");
473 if chan.remote_network_id == *our_node_id {
474 return Err(LightningError{err: "First hop cannot have our_node_id as a destination.".to_owned(), action: ErrorAction::IgnoreError});
476 first_hop_targets.insert(chan.remote_network_id, (short_channel_id, chan.counterparty_features.clone(), chan.outbound_capacity_msat));
478 if first_hop_targets.is_empty() {
479 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
483 // We don't want multiple paths (as per MPP) share liquidity of the same channels.
484 // This map allows paths to be aware of the channel use by other paths in the same call.
485 // This would help to make a better path finding decisions and not "overbook" channels.
486 // It is unaware of the directions (except for `outbound_capacity_msat` in `first_hops`).
487 let mut bookkeeped_channels_liquidity_available_msat = HashMap::new();
489 // Keeping track of how much value we already collected across other paths. Helps to decide:
490 // - how much a new path should be transferring (upper bound);
491 // - whether a channel should be disregarded because
492 // it's available liquidity is too small comparing to how much more we need to collect;
493 // - when we want to stop looking for new paths.
494 let mut already_collected_value_msat = 0;
496 macro_rules! add_entry {
497 // Adds entry which goes from $src_node_id to $dest_node_id
498 // over the channel with id $chan_id with fees described in
499 // $directional_info.
500 // $next_hops_fee_msat represents the fees paid for using all the channel *after* this one,
501 // since that value has to be transferred over this channel.
502 ( $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,
503 $next_hops_value_contribution: expr, $incl_fee_next_hops_htlc_minimum_msat: expr ) => {
504 // Channels to self should not be used. This is more of belt-and-suspenders, because in
505 // practice these cases should be caught earlier:
506 // - for regular channels at channel announcement (TODO)
507 // - for first and last hops early in get_route
508 if $src_node_id != $dest_node_id.clone() {
509 let available_liquidity_msat = bookkeeped_channels_liquidity_available_msat.entry($chan_id.clone()).or_insert_with(|| {
510 let mut initial_liquidity_available_msat = None;
511 if let Some(capacity_sats) = $capacity_sats {
512 initial_liquidity_available_msat = Some(capacity_sats * 1000);
515 if let Some(htlc_maximum_msat) = $directional_info.htlc_maximum_msat {
516 if let Some(available_msat) = initial_liquidity_available_msat {
517 initial_liquidity_available_msat = Some(cmp::min(available_msat, htlc_maximum_msat));
519 initial_liquidity_available_msat = Some(htlc_maximum_msat);
523 match initial_liquidity_available_msat {
524 Some(available_msat) => available_msat,
525 // We assume channels with unknown balance have
526 // a capacity of 0.0025 BTC (or 250_000 sats).
527 None => 250_000 * 1000
531 // It is tricky to substract $next_hops_fee_msat from available liquidity here.
532 // It may be misleading because we might later choose to reduce the value transferred
533 // over these channels, and the channel which was insufficient might become sufficient.
534 // Worst case: we drop a good channel here because it can't cover the high following
535 // fees caused by one expensive channel, but then this channel could have been used
536 // if the amount being transferred over this path is lower.
537 // We do this for now, but this is a subject for removal.
538 if let Some(available_value_contribution_msat) = available_liquidity_msat.checked_sub($next_hops_fee_msat) {
540 // Routing Fragmentation Mitigation heuristic:
542 // Routing fragmentation across many payment paths increases the overall routing
543 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
544 // Taking too many smaller paths also increases the chance of payment failure.
545 // Thus to avoid this effect, we require from our collected links to provide
546 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
548 // This requirement is currently 5% of the remaining-to-be-collected value.
549 // This means as we successfully advance in our collection,
550 // the absolute liquidity contribution is lowered,
551 // thus increasing the number of potential channels to be selected.
553 // Derive the minimal liquidity contribution with a ratio of 20 (5%, rounded up)
554 // or 100% if we're not allowed to do multipath payments.
555 let minimal_value_contribution_msat: u64 = if allow_mpp {
556 (recommended_value_msat - already_collected_value_msat + 19) / 20
560 // Verify the liquidity offered by this channel complies to the minimal contribution.
561 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
563 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
564 // Includes paying fees for the use of the following channels.
565 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
566 Some(result) => result,
567 // Can't overflow due to how the values were computed right above.
568 None => unreachable!(),
570 #[allow(unused_comparisons)] // $incl_fee_next_hops_htlc_minimum_msat is 0 in some calls so rustc complains
571 let over_path_minimum_msat = amount_to_transfer_over_msat >= $directional_info.htlc_minimum_msat &&
572 amount_to_transfer_over_msat >= $incl_fee_next_hops_htlc_minimum_msat;
574 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
575 // bother considering this channel.
576 // Since we're choosing amount_to_transfer_over_msat as maximum possible, it can
577 // be only reduced later (not increased), so this channel should just be skipped
578 // as not sufficient.
579 if !over_path_minimum_msat {
580 hit_minimum_limit = true;
581 } else if contributes_sufficient_value {
582 // Note that low contribution here (limited by available_liquidity_msat)
583 // might violate htlc_minimum_msat on the hops which are next along the
584 // payment path (upstream to the payee). To avoid that, we recompute path
585 // path fees knowing the final path contribution after constructing it.
586 let path_htlc_minimum_msat = match compute_fees($incl_fee_next_hops_htlc_minimum_msat, $directional_info.fees)
587 .map(|fee_msat| fee_msat.checked_add($incl_fee_next_hops_htlc_minimum_msat)) {
588 Some(Some(value_msat)) => cmp::max(value_msat, $directional_info.htlc_minimum_msat),
589 _ => u64::max_value()
591 let hm_entry = dist.entry(&$src_node_id);
592 let old_entry = hm_entry.or_insert_with(|| {
593 // If there was previously no known way to access
594 // the source node (recall it goes payee-to-payer) of $chan_id, first add
595 // a semi-dummy record just to compute the fees to reach the source node.
596 // This will affect our decision on selecting $chan_id
597 // as a way to reach the $dest_node_id.
598 let mut fee_base_msat = u32::max_value();
599 let mut fee_proportional_millionths = u32::max_value();
600 if let Some(Some(fees)) = network.get_nodes().get(&$src_node_id).map(|node| node.lowest_inbound_channel_fees) {
601 fee_base_msat = fees.base_msat;
602 fee_proportional_millionths = fees.proportional_millionths;
605 route_hop: RouteHop {
606 pubkey: $dest_node_id.clone(),
607 node_features: NodeFeatures::empty(),
609 channel_features: $chan_features.clone(),
611 cltv_expiry_delta: 0,
613 src_lowest_inbound_fees: RoutingFees {
614 base_msat: fee_base_msat,
615 proportional_millionths: fee_proportional_millionths,
617 channel_fees: $directional_info.fees,
618 next_hops_fee_msat: u64::max_value(),
619 hop_use_fee_msat: u64::max_value(),
620 total_fee_msat: u64::max_value(),
621 htlc_minimum_msat: $directional_info.htlc_minimum_msat,
622 path_htlc_minimum_msat,
623 was_processed: false,
627 if !old_entry.was_processed {
628 let mut hop_use_fee_msat = 0;
629 let mut total_fee_msat = $next_hops_fee_msat;
631 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
632 // will have the same effective-fee
633 if $src_node_id != *our_node_id {
634 match compute_fees(amount_to_transfer_over_msat, $directional_info.fees) {
635 // max_value means we'll always fail
636 // the old_entry.total_fee_msat > total_fee_msat check
637 None => total_fee_msat = u64::max_value(),
639 hop_use_fee_msat = fee_msat;
640 total_fee_msat += hop_use_fee_msat;
641 match compute_fees(minimal_value_contribution_msat, old_entry.src_lowest_inbound_fees).map(|a| a.checked_add(total_fee_msat)) {
646 total_fee_msat = u64::max_value();
653 let new_graph_node = RouteGraphNode {
654 pubkey: $src_node_id,
655 lowest_fee_to_peer_through_node: total_fee_msat,
656 lowest_fee_to_node: $next_hops_fee_msat as u64 + hop_use_fee_msat,
657 value_contribution_msat: value_contribution_msat,
658 path_htlc_minimum_msat,
661 // Update the way of reaching $src_node_id with the given $chan_id (from $dest_node_id),
662 // if this way is cheaper than the already known
663 // (considering the cost to "reach" this channel from the route destination,
664 // the cost of using this channel,
665 // and the cost of routing to the source node of this channel).
666 // Also, consider that htlc_minimum_msat_difference, because we might end up
667 // paying it. Consider the following exploit:
668 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
669 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
670 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
671 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
673 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
674 // but it may require additional tracking - we don't want to double-count
675 // the fees included in $incl_fee_next_hops_htlc_minimum_msat, but also
676 // can't use something that may decrease on future hops.
677 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat);
678 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat);
680 if new_cost < old_cost {
681 targets.push(new_graph_node);
682 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
683 old_entry.hop_use_fee_msat = hop_use_fee_msat;
684 old_entry.total_fee_msat = total_fee_msat;
685 old_entry.route_hop = RouteHop {
686 pubkey: $dest_node_id.clone(),
687 node_features: NodeFeatures::empty(),
688 short_channel_id: $chan_id.clone(),
689 channel_features: $chan_features.clone(),
690 fee_msat: 0, // This value will be later filled with hop_use_fee_msat of the following channel
691 cltv_expiry_delta: $directional_info.cltv_expiry_delta as u32,
693 old_entry.channel_fees = $directional_info.fees;
694 old_entry.htlc_minimum_msat = $directional_info.htlc_minimum_msat;
695 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
704 // Find ways (channels with destination) to reach a given node and store them
705 // in the corresponding data structures (routing graph etc).
706 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
707 // meaning how much will be paid in fees after this node (to the best of our knowledge).
708 // This data can later be helpful to optimize routing (pay lower fees).
709 macro_rules! add_entries_to_cheapest_to_target_node {
710 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr, $next_hops_value_contribution: expr, $incl_fee_next_hops_htlc_minimum_msat: expr ) => {
711 let skip_node = if let Some(elem) = dist.get_mut($node_id) {
712 let v = elem.was_processed;
713 elem.was_processed = true;
716 // Entries are added to dist in add_entry!() when there is a channel from a node.
717 // Because there are no channels from payee, it will not have a dist entry at this point.
718 // If we're processing any other node, it is always be the result of a channel from it.
719 assert_eq!($node_id, payee);
723 if !skip_node && first_hops.is_some() {
724 if let Some(&(ref first_hop, ref features, ref outbound_capacity_msat)) = first_hop_targets.get(&$node_id) {
725 add_entry!(first_hop, *our_node_id, $node_id, dummy_directional_info, Some(outbound_capacity_msat / 1000), features.to_context(), $fee_to_target_msat, $next_hops_value_contribution, $incl_fee_next_hops_htlc_minimum_msat);
730 if let Some(node_info) = $node.announcement_info.as_ref() {
731 features = node_info.features.clone();
733 features = NodeFeatures::empty();
736 if !skip_node && !features.requires_unknown_bits() {
737 for chan_id in $node.channels.iter() {
738 let chan = network.get_channels().get(chan_id).unwrap();
739 if !chan.features.requires_unknown_bits() {
740 if chan.node_one == *$node_id {
741 // ie $node is one, ie next hop in A* is two, via the two_to_one channel
742 if first_hops.is_none() || chan.node_two != *our_node_id {
743 if let Some(two_to_one) = chan.two_to_one.as_ref() {
744 if two_to_one.enabled {
745 add_entry!(chan_id, chan.node_two, chan.node_one, two_to_one, chan.capacity_sats, chan.features, $fee_to_target_msat, $next_hops_value_contribution, $incl_fee_next_hops_htlc_minimum_msat);
750 if first_hops.is_none() || chan.node_one != *our_node_id {
751 if let Some(one_to_two) = chan.one_to_two.as_ref() {
752 if one_to_two.enabled {
753 add_entry!(chan_id, chan.node_one, chan.node_two, one_to_two, chan.capacity_sats, chan.features, $fee_to_target_msat, $next_hops_value_contribution, $incl_fee_next_hops_htlc_minimum_msat);
765 let mut payment_paths = Vec::<PaymentPath>::new();
767 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
768 'paths_collection: loop {
769 // For every new path, start from scratch, except
770 // bookkeeped_channels_liquidity_available_msat, which will improve
771 // the further iterations of path finding. Also don't erase first_hop_targets.
774 hit_minimum_limit = false;
776 // If first hop is a private channel and the only way to reach the payee, this is the only
777 // place where it could be added.
778 if first_hops.is_some() {
779 if let Some(&(ref first_hop, ref features, ref outbound_capacity_msat)) = first_hop_targets.get(&payee) {
780 add_entry!(first_hop, *our_node_id, payee, dummy_directional_info, Some(outbound_capacity_msat / 1000), features.to_context(), 0, path_value_msat, 0);
784 // Add the payee as a target, so that the payee-to-payer
785 // search algorithm knows what to start with.
786 match network.get_nodes().get(payee) {
787 // The payee is not in our network graph, so nothing to add here.
788 // There is still a chance of reaching them via last_hops though,
789 // so don't yet fail the payment here.
790 // If not, targets.pop() will not even let us enter the loop in step 2.
793 add_entries_to_cheapest_to_target_node!(node, payee, 0, path_value_msat, 0);
798 // If a caller provided us with last hops, add them to routing targets. Since this happens
799 // earlier than general path finding, they will be somewhat prioritized, although currently
800 // it matters only if the fees are exactly the same.
801 for hop in last_hops.iter() {
802 let have_hop_src_in_graph =
803 if let Some(&(ref first_hop, ref features, ref outbound_capacity_msat)) = first_hop_targets.get(&hop.src_node_id) {
804 // If this hop connects to a node with which we have a direct channel, ignore
805 // the network graph and add both the hop and our direct channel to
806 // the candidate set.
808 // Currently there are no channel-context features defined, so we are a
809 // bit lazy here. In the future, we should pull them out via our
810 // ChannelManager, but there's no reason to waste the space until we
812 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, 0);
815 // In any other case, only add the hop if the source is in the regular network
817 network.get_nodes().get(&hop.src_node_id).is_some()
819 if have_hop_src_in_graph {
820 // BOLT 11 doesn't allow inclusion of features for the last hop hints, which
821 // really sucks, cause we're gonna need that eventually.
822 let last_path_htlc_minimum_msat: u64 = match hop.htlc_minimum_msat {
823 Some(htlc_minimum_msat) => htlc_minimum_msat,
826 let directional_info = DummyDirectionalChannelInfo {
827 cltv_expiry_delta: hop.cltv_expiry_delta as u32,
828 htlc_minimum_msat: last_path_htlc_minimum_msat,
829 htlc_maximum_msat: hop.htlc_maximum_msat,
832 add_entry!(hop.short_channel_id, hop.src_node_id, payee, directional_info, None::<u64>, ChannelFeatures::empty(), 0, path_value_msat, 0);
836 // At this point, targets are filled with the data from first and
837 // last hops communicated by the caller, and the payment receiver.
838 let mut found_new_path = false;
841 // If this loop terminates due the exhaustion of targets, two situations are possible:
842 // - not enough outgoing liquidity:
843 // 0 < already_collected_value_msat < final_value_msat
844 // - enough outgoing liquidity:
845 // final_value_msat <= already_collected_value_msat < recommended_value_msat
846 // Both these cases (and other cases except reaching recommended_value_msat) mean that
847 // paths_collection will be stopped because found_new_path==false.
848 // This is not necessarily a routing failure.
849 'path_construction: while let Some(RouteGraphNode { pubkey, lowest_fee_to_node, value_contribution_msat, path_htlc_minimum_msat, .. }) = targets.pop() {
851 // Since we're going payee-to-payer, hitting our node as a target means we should stop
852 // traversing the graph and arrange the path out of what we found.
853 if pubkey == *our_node_id {
854 let mut new_entry = dist.remove(&our_node_id).unwrap();
855 let mut ordered_hops = vec!(new_entry.clone());
858 if let Some(&(_, ref features, _)) = first_hop_targets.get(&ordered_hops.last().unwrap().route_hop.pubkey) {
859 ordered_hops.last_mut().unwrap().route_hop.node_features = features.to_context();
860 } else if let Some(node) = network.get_nodes().get(&ordered_hops.last().unwrap().route_hop.pubkey) {
861 if let Some(node_info) = node.announcement_info.as_ref() {
862 ordered_hops.last_mut().unwrap().route_hop.node_features = node_info.features.clone();
864 ordered_hops.last_mut().unwrap().route_hop.node_features = NodeFeatures::empty();
867 // We should be able to fill in features for everything except the last
868 // hop, if the last hop was provided via a BOLT 11 invoice (though we
869 // should be able to extend it further as BOLT 11 does have feature
870 // flags for the last hop node itself).
871 assert!(ordered_hops.last().unwrap().route_hop.pubkey == *payee);
874 // Means we succesfully traversed from the payer to the payee, now
875 // save this path for the payment route. Also, update the liquidity
876 // remaining on the used hops, so that we take them into account
877 // while looking for more paths.
878 if ordered_hops.last().unwrap().route_hop.pubkey == *payee {
882 new_entry = match dist.remove(&ordered_hops.last().unwrap().route_hop.pubkey) {
883 Some(payment_hop) => payment_hop,
884 // We can't arrive at None because, if we ever add an entry to targets,
885 // we also fill in the entry in dist (see add_entry!).
886 None => unreachable!(),
888 // We "propagate" the fees one hop backward (topologically) here,
889 // so that fees paid for a HTLC forwarding on the current channel are
890 // associated with the previous channel (where they will be subtracted).
891 ordered_hops.last_mut().unwrap().route_hop.fee_msat = new_entry.hop_use_fee_msat;
892 ordered_hops.last_mut().unwrap().route_hop.cltv_expiry_delta = new_entry.route_hop.cltv_expiry_delta;
893 ordered_hops.push(new_entry.clone());
895 ordered_hops.last_mut().unwrap().route_hop.fee_msat = value_contribution_msat;
896 ordered_hops.last_mut().unwrap().hop_use_fee_msat = 0;
897 ordered_hops.last_mut().unwrap().route_hop.cltv_expiry_delta = final_cltv;
899 let mut payment_path = PaymentPath {hops: ordered_hops};
901 // We could have possibly constructed a slightly inconsistent path: since we reduce
902 // value being transferred along the way, we could have violated htlc_minimum_msat
903 // on some channels we already passed (assuming dest->source direction). Here, we
904 // recompute the fees again, so that if that's the case, we match the currently
905 // underpaid htlc_minimum_msat with fees.
906 payment_path.update_value_and_recompute_fees(cmp::min(value_contribution_msat, final_value_msat));
908 // Since a path allows to transfer as much value as
909 // the smallest channel it has ("bottleneck"), we should recompute
910 // the fees so sender HTLC don't overpay fees when traversing
911 // larger channels than the bottleneck. This may happen because
912 // when we were selecting those channels we were not aware how much value
913 // this path will transfer, and the relative fee for them
914 // might have been computed considering a larger value.
915 // Remember that we used these channels so that we don't rely
916 // on the same liquidity in future paths.
917 let mut prevented_redundant_path_selection = false;
918 for payment_hop in payment_path.hops.iter() {
919 let channel_liquidity_available_msat = bookkeeped_channels_liquidity_available_msat.get_mut(&payment_hop.route_hop.short_channel_id).unwrap();
920 let mut spent_on_hop_msat = value_contribution_msat;
921 let next_hops_fee_msat = payment_hop.next_hops_fee_msat;
922 spent_on_hop_msat += next_hops_fee_msat;
923 if *channel_liquidity_available_msat < spent_on_hop_msat {
924 // This should not happen because we do recompute fees right before,
925 // trying to avoid cases when a hop is not usable due to the fee situation.
926 break 'path_construction;
928 if *channel_liquidity_available_msat < path_value_msat {
929 // If we use at least half of a channel's available liquidity, assume that
930 // it will not be selected again in the next loop iteration (see below).
931 prevented_redundant_path_selection = true;
933 *channel_liquidity_available_msat -= spent_on_hop_msat;
935 if !prevented_redundant_path_selection {
936 // If we weren't capped by hitting a liquidity limit on a channel in the path,
937 // we'll probably end up picking the same path again on the next iteration.
938 // Randomly decrease the available liquidity of a hop in the middle of the
940 let victim_liquidity = bookkeeped_channels_liquidity_available_msat.get_mut(
941 &payment_path.hops[(payment_path.hops.len() - 1) / 2].route_hop.short_channel_id).unwrap();
942 *victim_liquidity = 0;
945 // Track the total amount all our collected paths allow to send so that we:
946 // - know when to stop looking for more paths
947 // - know which of the hops are useless considering how much more sats we need
948 // (contributes_sufficient_value)
949 already_collected_value_msat += value_contribution_msat;
951 payment_paths.push(payment_path);
952 found_new_path = true;
953 break 'path_construction;
956 // If we found a path back to the payee, we shouldn't try to process it again. This is
957 // the equivalent of the `elem.was_processed` check in
958 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
959 if pubkey == *payee { continue 'path_construction; }
961 // Otherwise, since the current target node is not us,
962 // keep "unrolling" the payment graph from payee to payer by
963 // finding a way to reach the current target from the payer side.
964 match network.get_nodes().get(&pubkey) {
967 add_entries_to_cheapest_to_target_node!(node, &pubkey, lowest_fee_to_node, value_contribution_msat, path_htlc_minimum_msat);
973 // If we don't support MPP, no use trying to gather more value ever.
974 break 'paths_collection;
978 // Stop either when the recommended value is reached or if no new path was found in this
980 // In the latter case, making another path finding attempt won't help,
981 // because we deterministically terminated the search due to low liquidity.
982 if already_collected_value_msat >= recommended_value_msat || !found_new_path {
983 break 'paths_collection;
985 // Further, if this was our first walk of the graph, and we weren't limited by an
986 // htlc_minim_msat, return immediately because this path should suffice. If we were limited
987 // by an htlc_minimum_msat value, find another path with a higher value, potentially
988 // allowing us to pay fees to meet the htlc_minimum while still keeping a lower total fee.
989 if already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
990 if !hit_minimum_limit {
991 break 'paths_collection;
993 path_value_msat = recommended_value_msat;
998 if payment_paths.len() == 0 {
999 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1002 if already_collected_value_msat < final_value_msat {
1003 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1006 // Sort by total fees and take the best paths.
1007 payment_paths.sort_by_key(|path| path.get_total_fee_paid_msat());
1008 if payment_paths.len() > 50 {
1009 payment_paths.truncate(50);
1012 // Draw multiple sufficient routes by randomly combining the selected paths.
1013 let mut drawn_routes = Vec::new();
1014 for i in 0..payment_paths.len() {
1015 let mut cur_route = Vec::<PaymentPath>::new();
1016 let mut aggregate_route_value_msat = 0;
1019 // TODO: real random shuffle
1020 // Currently just starts with i_th and goes up to i-1_th in a looped way.
1021 let cur_payment_paths = [&payment_paths[i..], &payment_paths[..i]].concat();
1024 for payment_path in cur_payment_paths {
1025 cur_route.push(payment_path.clone());
1026 aggregate_route_value_msat += payment_path.get_value_msat();
1027 if aggregate_route_value_msat > final_value_msat {
1028 // Last path likely overpaid. Substract it from the most expensive
1029 // (in terms of proportional fee) path in this route and recompute fees.
1030 // This might be not the most economically efficient way, but fewer paths
1031 // also makes routing more reliable.
1032 let mut overpaid_value_msat = aggregate_route_value_msat - final_value_msat;
1034 // First, drop some expensive low-value paths entirely if possible.
1035 // Sort by value so that we drop many really-low values first, since
1036 // fewer paths is better: the payment is less likely to fail.
1037 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1038 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1039 cur_route.sort_by_key(|path| path.get_value_msat());
1040 // We should make sure that at least 1 path left.
1041 let mut paths_left = cur_route.len();
1042 cur_route.retain(|path| {
1043 if paths_left == 1 {
1046 let mut keep = true;
1047 let path_value_msat = path.get_value_msat();
1048 if path_value_msat <= overpaid_value_msat {
1050 overpaid_value_msat -= path_value_msat;
1056 if overpaid_value_msat == 0 {
1060 assert!(cur_route.len() > 0);
1063 // Now, substract the overpaid value from the most-expensive path.
1064 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1065 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1066 cur_route.sort_by_key(|path| { path.hops.iter().map(|hop| hop.channel_fees.proportional_millionths as u64).sum::<u64>() });
1067 let expensive_payment_path = cur_route.first_mut().unwrap();
1068 // We already dropped all the small channels above, meaning all the
1069 // remaining channels are larger than remaining overpaid_value_msat.
1070 // Thus, this can't be negative.
1071 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
1072 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
1076 drawn_routes.push(cur_route);
1080 // Select the best route by lowest total fee.
1081 drawn_routes.sort_by_key(|paths| paths.iter().map(|path| path.get_total_fee_paid_msat()).sum::<u64>());
1082 let mut selected_paths = Vec::<Vec<RouteHop>>::new();
1083 for payment_path in drawn_routes.first().unwrap() {
1084 selected_paths.push(payment_path.hops.iter().map(|payment_hop| payment_hop.route_hop.clone()).collect());
1087 if let Some(features) = &payee_features {
1088 for path in selected_paths.iter_mut() {
1089 path.last_mut().unwrap().node_features = features.to_context();
1093 let route = Route { paths: selected_paths };
1094 log_trace!(logger, "Got route: {}", log_route!(route));
1100 use routing::router::{get_route, RouteHint, RoutingFees};
1101 use routing::network_graph::{NetworkGraph, NetGraphMsgHandler};
1102 use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
1103 use ln::msgs::{ErrorAction, LightningError, OptionalField, UnsignedChannelAnnouncement, ChannelAnnouncement, RoutingMessageHandler,
1104 NodeAnnouncement, UnsignedNodeAnnouncement, ChannelUpdate, UnsignedChannelUpdate};
1105 use ln::channelmanager;
1106 use util::test_utils;
1107 use util::ser::Writeable;
1109 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
1110 use bitcoin::hashes::Hash;
1111 use bitcoin::network::constants::Network;
1112 use bitcoin::blockdata::constants::genesis_block;
1113 use bitcoin::blockdata::script::Builder;
1114 use bitcoin::blockdata::opcodes;
1115 use bitcoin::blockdata::transaction::TxOut;
1119 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
1120 use bitcoin::secp256k1::{Secp256k1, All};
1124 // Using the same keys for LN and BTC ids
1125 fn add_channel(net_graph_msg_handler: &NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>, secp_ctx: &Secp256k1<All>, node_1_privkey: &SecretKey,
1126 node_2_privkey: &SecretKey, features: ChannelFeatures, short_channel_id: u64) {
1127 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1128 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1130 let unsigned_announcement = UnsignedChannelAnnouncement {
1132 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1136 bitcoin_key_1: node_id_1,
1137 bitcoin_key_2: node_id_2,
1138 excess_data: Vec::new(),
1141 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1142 let valid_announcement = ChannelAnnouncement {
1143 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1144 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1145 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1146 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1147 contents: unsigned_announcement.clone(),
1149 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1150 Ok(res) => assert!(res),
1155 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) {
1156 let msghash = hash_to_message!(&Sha256dHash::hash(&update.encode()[..])[..]);
1157 let valid_channel_update = ChannelUpdate {
1158 signature: secp_ctx.sign(&msghash, node_privkey),
1159 contents: update.clone()
1162 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1163 Ok(res) => assert!(res),
1168 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,
1169 features: NodeFeatures, timestamp: u32) {
1170 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
1171 let unsigned_announcement = UnsignedNodeAnnouncement {
1177 addresses: Vec::new(),
1178 excess_address_data: Vec::new(),
1179 excess_data: Vec::new(),
1181 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1182 let valid_announcement = NodeAnnouncement {
1183 signature: secp_ctx.sign(&msghash, node_privkey),
1184 contents: unsigned_announcement.clone()
1187 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1193 fn get_nodes(secp_ctx: &Secp256k1<All>) -> (SecretKey, PublicKey, Vec<SecretKey>, Vec<PublicKey>) {
1194 let privkeys: Vec<SecretKey> = (2..10).map(|i| {
1195 SecretKey::from_slice(&hex::decode(format!("{:02}", i).repeat(32)).unwrap()[..]).unwrap()
1198 let pubkeys = privkeys.iter().map(|secret| PublicKey::from_secret_key(&secp_ctx, secret)).collect();
1200 let our_privkey = SecretKey::from_slice(&hex::decode("01".repeat(32)).unwrap()[..]).unwrap();
1201 let our_id = PublicKey::from_secret_key(&secp_ctx, &our_privkey);
1203 (our_privkey, our_id, privkeys, pubkeys)
1206 fn id_to_feature_flags(id: u8) -> Vec<u8> {
1207 // Set the feature flags to the id'th odd (ie non-required) feature bit so that we can
1208 // test for it later.
1209 let idx = (id - 1) * 2 + 1;
1211 vec![1 << (idx - 8*3), 0, 0, 0]
1212 } else if idx > 8*2 {
1213 vec![1 << (idx - 8*2), 0, 0]
1214 } else if idx > 8*1 {
1215 vec![1 << (idx - 8*1), 0]
1221 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>) {
1222 let secp_ctx = Secp256k1::new();
1223 let logger = Arc::new(test_utils::TestLogger::new());
1224 let chain_monitor = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1225 let net_graph_msg_handler = NetGraphMsgHandler::new(genesis_block(Network::Testnet).header.block_hash(), None, Arc::clone(&logger));
1226 // Build network from our_id to node7:
1228 // -1(1)2- node0 -1(3)2-
1230 // our_id -1(12)2- node7 -1(13)2--- node2
1232 // -1(2)2- node1 -1(4)2-
1235 // chan1 1-to-2: disabled
1236 // chan1 2-to-1: enabled, 0 fee
1238 // chan2 1-to-2: enabled, ignored fee
1239 // chan2 2-to-1: enabled, 0 fee
1241 // chan3 1-to-2: enabled, 0 fee
1242 // chan3 2-to-1: enabled, 100 msat fee
1244 // chan4 1-to-2: enabled, 100% fee
1245 // chan4 2-to-1: enabled, 0 fee
1247 // chan12 1-to-2: enabled, ignored fee
1248 // chan12 2-to-1: enabled, 0 fee
1250 // chan13 1-to-2: enabled, 200% fee
1251 // chan13 2-to-1: enabled, 0 fee
1254 // -1(5)2- node3 -1(8)2--
1258 // node2--1(6)2- node4 -1(9)2--- node6 (not in global route map)
1260 // -1(7)2- node5 -1(10)2-
1262 // chan5 1-to-2: enabled, 100 msat fee
1263 // chan5 2-to-1: enabled, 0 fee
1265 // chan6 1-to-2: enabled, 0 fee
1266 // chan6 2-to-1: enabled, 0 fee
1268 // chan7 1-to-2: enabled, 100% fee
1269 // chan7 2-to-1: enabled, 0 fee
1271 // chan8 1-to-2: enabled, variable fee (0 then 1000 msat)
1272 // chan8 2-to-1: enabled, 0 fee
1274 // chan9 1-to-2: enabled, 1001 msat fee
1275 // chan9 2-to-1: enabled, 0 fee
1277 // chan10 1-to-2: enabled, 0 fee
1278 // chan10 2-to-1: enabled, 0 fee
1280 // chan11 1-to-2: enabled, 0 fee
1281 // chan11 2-to-1: enabled, 0 fee
1283 let (our_privkey, _, privkeys, _) = get_nodes(&secp_ctx);
1285 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[0], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
1286 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1287 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1288 short_channel_id: 1,
1291 cltv_expiry_delta: 0,
1292 htlc_minimum_msat: 0,
1293 htlc_maximum_msat: OptionalField::Absent,
1295 fee_proportional_millionths: 0,
1296 excess_data: Vec::new()
1299 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
1301 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
1302 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1303 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1304 short_channel_id: 2,
1307 cltv_expiry_delta: u16::max_value(),
1308 htlc_minimum_msat: 0,
1309 htlc_maximum_msat: OptionalField::Absent,
1310 fee_base_msat: u32::max_value(),
1311 fee_proportional_millionths: u32::max_value(),
1312 excess_data: Vec::new()
1314 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1315 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1316 short_channel_id: 2,
1319 cltv_expiry_delta: 0,
1320 htlc_minimum_msat: 0,
1321 htlc_maximum_msat: OptionalField::Absent,
1323 fee_proportional_millionths: 0,
1324 excess_data: Vec::new()
1327 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
1329 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[7], ChannelFeatures::from_le_bytes(id_to_feature_flags(12)), 12);
1330 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1331 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1332 short_channel_id: 12,
1335 cltv_expiry_delta: u16::max_value(),
1336 htlc_minimum_msat: 0,
1337 htlc_maximum_msat: OptionalField::Absent,
1338 fee_base_msat: u32::max_value(),
1339 fee_proportional_millionths: u32::max_value(),
1340 excess_data: Vec::new()
1342 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1343 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1344 short_channel_id: 12,
1347 cltv_expiry_delta: 0,
1348 htlc_minimum_msat: 0,
1349 htlc_maximum_msat: OptionalField::Absent,
1351 fee_proportional_millionths: 0,
1352 excess_data: Vec::new()
1355 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], NodeFeatures::from_le_bytes(id_to_feature_flags(8)), 0);
1357 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
1358 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1359 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1360 short_channel_id: 3,
1363 cltv_expiry_delta: (3 << 8) | 1,
1364 htlc_minimum_msat: 0,
1365 htlc_maximum_msat: OptionalField::Absent,
1367 fee_proportional_millionths: 0,
1368 excess_data: Vec::new()
1370 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1371 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1372 short_channel_id: 3,
1375 cltv_expiry_delta: (3 << 8) | 2,
1376 htlc_minimum_msat: 0,
1377 htlc_maximum_msat: OptionalField::Absent,
1379 fee_proportional_millionths: 0,
1380 excess_data: Vec::new()
1383 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
1384 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1385 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1386 short_channel_id: 4,
1389 cltv_expiry_delta: (4 << 8) | 1,
1390 htlc_minimum_msat: 0,
1391 htlc_maximum_msat: OptionalField::Absent,
1393 fee_proportional_millionths: 1000000,
1394 excess_data: Vec::new()
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: 4,
1401 cltv_expiry_delta: (4 << 8) | 2,
1402 htlc_minimum_msat: 0,
1403 htlc_maximum_msat: OptionalField::Absent,
1405 fee_proportional_millionths: 0,
1406 excess_data: Vec::new()
1409 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(13)), 13);
1410 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1411 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1412 short_channel_id: 13,
1415 cltv_expiry_delta: (13 << 8) | 1,
1416 htlc_minimum_msat: 0,
1417 htlc_maximum_msat: OptionalField::Absent,
1419 fee_proportional_millionths: 2000000,
1420 excess_data: Vec::new()
1422 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1423 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1424 short_channel_id: 13,
1427 cltv_expiry_delta: (13 << 8) | 2,
1428 htlc_minimum_msat: 0,
1429 htlc_maximum_msat: OptionalField::Absent,
1431 fee_proportional_millionths: 0,
1432 excess_data: Vec::new()
1435 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
1437 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
1438 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1439 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1440 short_channel_id: 6,
1443 cltv_expiry_delta: (6 << 8) | 1,
1444 htlc_minimum_msat: 0,
1445 htlc_maximum_msat: OptionalField::Absent,
1447 fee_proportional_millionths: 0,
1448 excess_data: Vec::new()
1450 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1451 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1452 short_channel_id: 6,
1455 cltv_expiry_delta: (6 << 8) | 2,
1456 htlc_minimum_msat: 0,
1457 htlc_maximum_msat: OptionalField::Absent,
1459 fee_proportional_millionths: 0,
1460 excess_data: Vec::new(),
1463 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(11)), 11);
1464 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1465 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1466 short_channel_id: 11,
1469 cltv_expiry_delta: (11 << 8) | 1,
1470 htlc_minimum_msat: 0,
1471 htlc_maximum_msat: OptionalField::Absent,
1473 fee_proportional_millionths: 0,
1474 excess_data: Vec::new()
1476 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
1477 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1478 short_channel_id: 11,
1481 cltv_expiry_delta: (11 << 8) | 2,
1482 htlc_minimum_msat: 0,
1483 htlc_maximum_msat: OptionalField::Absent,
1485 fee_proportional_millionths: 0,
1486 excess_data: Vec::new()
1489 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(5)), 0);
1491 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
1493 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[5], ChannelFeatures::from_le_bytes(id_to_feature_flags(7)), 7);
1494 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1495 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1496 short_channel_id: 7,
1499 cltv_expiry_delta: (7 << 8) | 1,
1500 htlc_minimum_msat: 0,
1501 htlc_maximum_msat: OptionalField::Absent,
1503 fee_proportional_millionths: 1000000,
1504 excess_data: Vec::new()
1506 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[5], UnsignedChannelUpdate {
1507 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1508 short_channel_id: 7,
1511 cltv_expiry_delta: (7 << 8) | 2,
1512 htlc_minimum_msat: 0,
1513 htlc_maximum_msat: OptionalField::Absent,
1515 fee_proportional_millionths: 0,
1516 excess_data: Vec::new()
1519 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[5], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
1521 (secp_ctx, net_graph_msg_handler, chain_monitor, logger)
1525 fn simple_route_test() {
1526 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1527 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1529 // Simple route to 2 via 1
1531 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)) {
1532 assert_eq!(err, "Cannot send a payment of 0 msat");
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);
1538 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
1539 assert_eq!(route.paths[0][0].short_channel_id, 2);
1540 assert_eq!(route.paths[0][0].fee_msat, 100);
1541 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
1542 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
1543 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
1545 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1546 assert_eq!(route.paths[0][1].short_channel_id, 4);
1547 assert_eq!(route.paths[0][1].fee_msat, 100);
1548 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1549 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1550 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
1554 fn invalid_first_hop_test() {
1555 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1556 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1558 // Simple route to 2 via 1
1560 let our_chans = vec![channelmanager::ChannelDetails {
1561 channel_id: [0; 32],
1562 short_channel_id: Some(2),
1563 remote_network_id: our_id,
1564 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1565 channel_value_satoshis: 100000,
1567 outbound_capacity_msat: 100000,
1568 inbound_capacity_msat: 100000,
1570 counterparty_forwarding_info: None,
1573 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)) {
1574 assert_eq!(err, "First hop cannot have our_node_id as a destination.");
1575 } else { panic!(); }
1577 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();
1578 assert_eq!(route.paths[0].len(), 2);
1582 fn htlc_minimum_test() {
1583 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1584 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1586 // Simple route to 2 via 1
1588 // Disable other paths
1589 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1590 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1591 short_channel_id: 12,
1593 flags: 2, // to disable
1594 cltv_expiry_delta: 0,
1595 htlc_minimum_msat: 0,
1596 htlc_maximum_msat: OptionalField::Absent,
1598 fee_proportional_millionths: 0,
1599 excess_data: Vec::new()
1601 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1602 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1603 short_channel_id: 3,
1605 flags: 2, // to disable
1606 cltv_expiry_delta: 0,
1607 htlc_minimum_msat: 0,
1608 htlc_maximum_msat: OptionalField::Absent,
1610 fee_proportional_millionths: 0,
1611 excess_data: Vec::new()
1613 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1614 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1615 short_channel_id: 13,
1617 flags: 2, // to disable
1618 cltv_expiry_delta: 0,
1619 htlc_minimum_msat: 0,
1620 htlc_maximum_msat: OptionalField::Absent,
1622 fee_proportional_millionths: 0,
1623 excess_data: Vec::new()
1625 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1626 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1627 short_channel_id: 6,
1629 flags: 2, // to disable
1630 cltv_expiry_delta: 0,
1631 htlc_minimum_msat: 0,
1632 htlc_maximum_msat: OptionalField::Absent,
1634 fee_proportional_millionths: 0,
1635 excess_data: Vec::new()
1637 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1638 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1639 short_channel_id: 7,
1641 flags: 2, // to disable
1642 cltv_expiry_delta: 0,
1643 htlc_minimum_msat: 0,
1644 htlc_maximum_msat: OptionalField::Absent,
1646 fee_proportional_millionths: 0,
1647 excess_data: Vec::new()
1650 // Check against amount_to_transfer_over_msat.
1651 // Set minimal HTLC of 200_000_000 msat.
1652 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1653 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1654 short_channel_id: 2,
1657 cltv_expiry_delta: 0,
1658 htlc_minimum_msat: 200_000_000,
1659 htlc_maximum_msat: OptionalField::Absent,
1661 fee_proportional_millionths: 0,
1662 excess_data: Vec::new()
1665 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
1667 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1668 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1669 short_channel_id: 4,
1672 cltv_expiry_delta: 0,
1673 htlc_minimum_msat: 0,
1674 htlc_maximum_msat: OptionalField::Present(199_999_999),
1676 fee_proportional_millionths: 0,
1677 excess_data: Vec::new()
1680 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
1681 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)) {
1682 assert_eq!(err, "Failed to find a path to the given destination");
1683 } else { panic!(); }
1685 // Lift the restriction on the first hop.
1686 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1687 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1688 short_channel_id: 2,
1691 cltv_expiry_delta: 0,
1692 htlc_minimum_msat: 0,
1693 htlc_maximum_msat: OptionalField::Absent,
1695 fee_proportional_millionths: 0,
1696 excess_data: Vec::new()
1699 // A payment above the minimum should pass
1700 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();
1701 assert_eq!(route.paths[0].len(), 2);
1705 fn htlc_minimum_overpay_test() {
1706 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1707 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1709 // A route to node#2 via two paths.
1710 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
1711 // Thus, they can't send 60 without overpaying.
1712 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1713 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1714 short_channel_id: 2,
1717 cltv_expiry_delta: 0,
1718 htlc_minimum_msat: 35_000,
1719 htlc_maximum_msat: OptionalField::Present(40_000),
1721 fee_proportional_millionths: 0,
1722 excess_data: Vec::new()
1724 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1725 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1726 short_channel_id: 12,
1729 cltv_expiry_delta: 0,
1730 htlc_minimum_msat: 35_000,
1731 htlc_maximum_msat: OptionalField::Present(40_000),
1733 fee_proportional_millionths: 0,
1734 excess_data: Vec::new()
1738 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1739 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1740 short_channel_id: 13,
1743 cltv_expiry_delta: 0,
1744 htlc_minimum_msat: 0,
1745 htlc_maximum_msat: OptionalField::Absent,
1747 fee_proportional_millionths: 0,
1748 excess_data: Vec::new()
1750 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1751 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1752 short_channel_id: 4,
1755 cltv_expiry_delta: 0,
1756 htlc_minimum_msat: 0,
1757 htlc_maximum_msat: OptionalField::Absent,
1759 fee_proportional_millionths: 0,
1760 excess_data: Vec::new()
1763 // Disable other paths
1764 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1765 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1766 short_channel_id: 1,
1768 flags: 2, // to disable
1769 cltv_expiry_delta: 0,
1770 htlc_minimum_msat: 0,
1771 htlc_maximum_msat: OptionalField::Absent,
1773 fee_proportional_millionths: 0,
1774 excess_data: Vec::new()
1777 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
1778 Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger)).unwrap();
1779 // Overpay fees to hit htlc_minimum_msat.
1780 let overpaid_fees = route.paths[0][0].fee_msat + route.paths[1][0].fee_msat;
1781 // TODO: this could be better balanced to overpay 10k and not 15k.
1782 assert_eq!(overpaid_fees, 15_000);
1784 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
1785 // while taking even more fee to match htlc_minimum_msat.
1786 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1787 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1788 short_channel_id: 12,
1791 cltv_expiry_delta: 0,
1792 htlc_minimum_msat: 65_000,
1793 htlc_maximum_msat: OptionalField::Present(80_000),
1795 fee_proportional_millionths: 0,
1796 excess_data: Vec::new()
1798 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1799 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1800 short_channel_id: 2,
1803 cltv_expiry_delta: 0,
1804 htlc_minimum_msat: 0,
1805 htlc_maximum_msat: OptionalField::Absent,
1807 fee_proportional_millionths: 0,
1808 excess_data: Vec::new()
1810 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1811 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1812 short_channel_id: 4,
1815 cltv_expiry_delta: 0,
1816 htlc_minimum_msat: 0,
1817 htlc_maximum_msat: OptionalField::Absent,
1819 fee_proportional_millionths: 100_000,
1820 excess_data: Vec::new()
1823 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
1824 Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger)).unwrap();
1825 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
1826 assert_eq!(route.paths.len(), 1);
1827 assert_eq!(route.paths[0][0].short_channel_id, 12);
1828 let fees = route.paths[0][0].fee_msat;
1829 assert_eq!(fees, 5_000);
1831 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
1832 Some(InvoiceFeatures::known()), None, &Vec::new(), 50_000, 42, Arc::clone(&logger)).unwrap();
1833 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
1834 // the other channel.
1835 assert_eq!(route.paths.len(), 1);
1836 assert_eq!(route.paths[0][0].short_channel_id, 2);
1837 let fees = route.paths[0][0].fee_msat;
1838 assert_eq!(fees, 5_000);
1842 fn disable_channels_test() {
1843 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1844 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1846 // // Disable channels 4 and 12 by flags=2
1847 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1848 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1849 short_channel_id: 4,
1851 flags: 2, // to disable
1852 cltv_expiry_delta: 0,
1853 htlc_minimum_msat: 0,
1854 htlc_maximum_msat: OptionalField::Absent,
1856 fee_proportional_millionths: 0,
1857 excess_data: Vec::new()
1859 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1860 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1861 short_channel_id: 12,
1863 flags: 2, // to disable
1864 cltv_expiry_delta: 0,
1865 htlc_minimum_msat: 0,
1866 htlc_maximum_msat: OptionalField::Absent,
1868 fee_proportional_millionths: 0,
1869 excess_data: Vec::new()
1872 // If all the channels require some features we don't understand, route should fail
1873 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)) {
1874 assert_eq!(err, "Failed to find a path to the given destination");
1875 } else { panic!(); }
1877 // If we specify a channel to node7, that overrides our local channel view and that gets used
1878 let our_chans = vec![channelmanager::ChannelDetails {
1879 channel_id: [0; 32],
1880 short_channel_id: Some(42),
1881 remote_network_id: nodes[7].clone(),
1882 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1883 channel_value_satoshis: 0,
1885 outbound_capacity_msat: 250_000_000,
1886 inbound_capacity_msat: 0,
1888 counterparty_forwarding_info: None,
1890 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();
1891 assert_eq!(route.paths[0].len(), 2);
1893 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
1894 assert_eq!(route.paths[0][0].short_channel_id, 42);
1895 assert_eq!(route.paths[0][0].fee_msat, 200);
1896 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
1897 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
1898 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
1900 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1901 assert_eq!(route.paths[0][1].short_channel_id, 13);
1902 assert_eq!(route.paths[0][1].fee_msat, 100);
1903 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1904 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1905 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
1909 fn disable_node_test() {
1910 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1911 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1913 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
1914 let mut unknown_features = NodeFeatures::known();
1915 unknown_features.set_required_unknown_bits();
1916 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
1917 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
1918 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
1920 // If all nodes require some features we don't understand, route should fail
1921 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)) {
1922 assert_eq!(err, "Failed to find a path to the given destination");
1923 } else { panic!(); }
1925 // If we specify a channel to node7, that overrides our local channel view and that gets used
1926 let our_chans = vec![channelmanager::ChannelDetails {
1927 channel_id: [0; 32],
1928 short_channel_id: Some(42),
1929 remote_network_id: nodes[7].clone(),
1930 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1931 channel_value_satoshis: 0,
1933 outbound_capacity_msat: 250_000_000,
1934 inbound_capacity_msat: 0,
1936 counterparty_forwarding_info: None,
1938 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();
1939 assert_eq!(route.paths[0].len(), 2);
1941 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
1942 assert_eq!(route.paths[0][0].short_channel_id, 42);
1943 assert_eq!(route.paths[0][0].fee_msat, 200);
1944 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
1945 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
1946 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
1948 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1949 assert_eq!(route.paths[0][1].short_channel_id, 13);
1950 assert_eq!(route.paths[0][1].fee_msat, 100);
1951 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1952 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1953 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
1955 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
1956 // naively) assume that the user checked the feature bits on the invoice, which override
1957 // the node_announcement.
1961 fn our_chans_test() {
1962 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1963 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1965 // Route to 1 via 2 and 3 because our channel to 1 is disabled
1966 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();
1967 assert_eq!(route.paths[0].len(), 3);
1969 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
1970 assert_eq!(route.paths[0][0].short_channel_id, 2);
1971 assert_eq!(route.paths[0][0].fee_msat, 200);
1972 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
1973 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
1974 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
1976 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1977 assert_eq!(route.paths[0][1].short_channel_id, 4);
1978 assert_eq!(route.paths[0][1].fee_msat, 100);
1979 assert_eq!(route.paths[0][1].cltv_expiry_delta, (3 << 8) | 2);
1980 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1981 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
1983 assert_eq!(route.paths[0][2].pubkey, nodes[0]);
1984 assert_eq!(route.paths[0][2].short_channel_id, 3);
1985 assert_eq!(route.paths[0][2].fee_msat, 100);
1986 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
1987 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(1));
1988 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(3));
1990 // If we specify a channel to node7, that overrides our local channel view and that gets used
1991 let our_chans = vec![channelmanager::ChannelDetails {
1992 channel_id: [0; 32],
1993 short_channel_id: Some(42),
1994 remote_network_id: nodes[7].clone(),
1995 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1996 channel_value_satoshis: 0,
1998 outbound_capacity_msat: 250_000_000,
1999 inbound_capacity_msat: 0,
2001 counterparty_forwarding_info: None,
2003 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();
2004 assert_eq!(route.paths[0].len(), 2);
2006 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2007 assert_eq!(route.paths[0][0].short_channel_id, 42);
2008 assert_eq!(route.paths[0][0].fee_msat, 200);
2009 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
2010 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2011 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2013 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2014 assert_eq!(route.paths[0][1].short_channel_id, 13);
2015 assert_eq!(route.paths[0][1].fee_msat, 100);
2016 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2017 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2018 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2021 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2022 let zero_fees = RoutingFees {
2024 proportional_millionths: 0,
2027 src_node_id: nodes[3].clone(),
2028 short_channel_id: 8,
2030 cltv_expiry_delta: (8 << 8) | 1,
2031 htlc_minimum_msat: None,
2032 htlc_maximum_msat: None,
2034 src_node_id: nodes[4].clone(),
2035 short_channel_id: 9,
2038 proportional_millionths: 0,
2040 cltv_expiry_delta: (9 << 8) | 1,
2041 htlc_minimum_msat: None,
2042 htlc_maximum_msat: None,
2044 src_node_id: nodes[5].clone(),
2045 short_channel_id: 10,
2047 cltv_expiry_delta: (10 << 8) | 1,
2048 htlc_minimum_msat: None,
2049 htlc_maximum_msat: None,
2054 fn last_hops_test() {
2055 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2056 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2058 // Simple test across 2, 3, 5, and 4 via a last_hop channel
2060 // First check that lst hop can't have its source as the payee.
2061 let invalid_last_hop = RouteHint {
2062 src_node_id: nodes[6],
2063 short_channel_id: 8,
2066 proportional_millionths: 0,
2068 cltv_expiry_delta: (8 << 8) | 1,
2069 htlc_minimum_msat: None,
2070 htlc_maximum_msat: None,
2073 let mut invalid_last_hops = last_hops(&nodes);
2074 invalid_last_hops.push(invalid_last_hop);
2076 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)) {
2077 assert_eq!(err, "Last hop cannot have a payee as a source.");
2078 } else { panic!(); }
2081 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();
2082 assert_eq!(route.paths[0].len(), 5);
2084 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2085 assert_eq!(route.paths[0][0].short_channel_id, 2);
2086 assert_eq!(route.paths[0][0].fee_msat, 100);
2087 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2088 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2089 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2091 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2092 assert_eq!(route.paths[0][1].short_channel_id, 4);
2093 assert_eq!(route.paths[0][1].fee_msat, 0);
2094 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2095 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2096 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2098 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2099 assert_eq!(route.paths[0][2].short_channel_id, 6);
2100 assert_eq!(route.paths[0][2].fee_msat, 0);
2101 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2102 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2103 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2105 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2106 assert_eq!(route.paths[0][3].short_channel_id, 11);
2107 assert_eq!(route.paths[0][3].fee_msat, 0);
2108 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2109 // If we have a peer in the node map, we'll use their features here since we don't have
2110 // a way of figuring out their features from the invoice:
2111 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2112 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2114 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2115 assert_eq!(route.paths[0][4].short_channel_id, 8);
2116 assert_eq!(route.paths[0][4].fee_msat, 100);
2117 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2118 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2119 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2123 fn our_chans_last_hop_connect_test() {
2124 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2125 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2127 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
2128 let our_chans = vec![channelmanager::ChannelDetails {
2129 channel_id: [0; 32],
2130 short_channel_id: Some(42),
2131 remote_network_id: nodes[3].clone(),
2132 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
2133 channel_value_satoshis: 0,
2135 outbound_capacity_msat: 250_000_000,
2136 inbound_capacity_msat: 0,
2138 counterparty_forwarding_info: None,
2140 let mut last_hops = last_hops(&nodes);
2141 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();
2142 assert_eq!(route.paths[0].len(), 2);
2144 assert_eq!(route.paths[0][0].pubkey, nodes[3]);
2145 assert_eq!(route.paths[0][0].short_channel_id, 42);
2146 assert_eq!(route.paths[0][0].fee_msat, 0);
2147 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
2148 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2149 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2151 assert_eq!(route.paths[0][1].pubkey, nodes[6]);
2152 assert_eq!(route.paths[0][1].short_channel_id, 8);
2153 assert_eq!(route.paths[0][1].fee_msat, 100);
2154 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2155 assert_eq!(route.paths[0][1].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2156 assert_eq!(route.paths[0][1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2158 last_hops[0].fees.base_msat = 1000;
2160 // Revert to via 6 as the fee on 8 goes up
2161 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();
2162 assert_eq!(route.paths[0].len(), 4);
2164 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2165 assert_eq!(route.paths[0][0].short_channel_id, 2);
2166 assert_eq!(route.paths[0][0].fee_msat, 200); // fee increased as its % of value transferred across node
2167 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2168 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2169 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2171 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2172 assert_eq!(route.paths[0][1].short_channel_id, 4);
2173 assert_eq!(route.paths[0][1].fee_msat, 100);
2174 assert_eq!(route.paths[0][1].cltv_expiry_delta, (7 << 8) | 1);
2175 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2176 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2178 assert_eq!(route.paths[0][2].pubkey, nodes[5]);
2179 assert_eq!(route.paths[0][2].short_channel_id, 7);
2180 assert_eq!(route.paths[0][2].fee_msat, 0);
2181 assert_eq!(route.paths[0][2].cltv_expiry_delta, (10 << 8) | 1);
2182 // If we have a peer in the node map, we'll use their features here since we don't have
2183 // a way of figuring out their features from the invoice:
2184 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
2185 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(7));
2187 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2188 assert_eq!(route.paths[0][3].short_channel_id, 10);
2189 assert_eq!(route.paths[0][3].fee_msat, 100);
2190 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2191 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2192 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2194 // ...but still use 8 for larger payments as 6 has a variable feerate
2195 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();
2196 assert_eq!(route.paths[0].len(), 5);
2198 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2199 assert_eq!(route.paths[0][0].short_channel_id, 2);
2200 assert_eq!(route.paths[0][0].fee_msat, 3000);
2201 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2202 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2203 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2205 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2206 assert_eq!(route.paths[0][1].short_channel_id, 4);
2207 assert_eq!(route.paths[0][1].fee_msat, 0);
2208 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2209 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2210 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2212 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2213 assert_eq!(route.paths[0][2].short_channel_id, 6);
2214 assert_eq!(route.paths[0][2].fee_msat, 0);
2215 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2216 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2217 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2219 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2220 assert_eq!(route.paths[0][3].short_channel_id, 11);
2221 assert_eq!(route.paths[0][3].fee_msat, 1000);
2222 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2223 // If we have a peer in the node map, we'll use their features here since we don't have
2224 // a way of figuring out their features from the invoice:
2225 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2226 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2228 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2229 assert_eq!(route.paths[0][4].short_channel_id, 8);
2230 assert_eq!(route.paths[0][4].fee_msat, 2000);
2231 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2232 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2233 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2237 fn unannounced_path_test() {
2238 // We should be able to send a payment to a destination without any help of a routing graph
2239 // if we have a channel with a common counterparty that appears in the first and last hop
2241 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
2242 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
2243 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
2245 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
2246 let last_hops = vec![RouteHint {
2247 src_node_id: middle_node_id,
2248 short_channel_id: 8,
2251 proportional_millionths: 0,
2253 cltv_expiry_delta: (8 << 8) | 1,
2254 htlc_minimum_msat: None,
2255 htlc_maximum_msat: None,
2257 let our_chans = vec![channelmanager::ChannelDetails {
2258 channel_id: [0; 32],
2259 short_channel_id: Some(42),
2260 remote_network_id: middle_node_id,
2261 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
2262 channel_value_satoshis: 100000,
2264 outbound_capacity_msat: 100000,
2265 inbound_capacity_msat: 100000,
2267 counterparty_forwarding_info: None,
2269 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();
2271 assert_eq!(route.paths[0].len(), 2);
2273 assert_eq!(route.paths[0][0].pubkey, middle_node_id);
2274 assert_eq!(route.paths[0][0].short_channel_id, 42);
2275 assert_eq!(route.paths[0][0].fee_msat, 1000);
2276 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
2277 assert_eq!(route.paths[0][0].node_features.le_flags(), &[0b11]);
2278 assert_eq!(route.paths[0][0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
2280 assert_eq!(route.paths[0][1].pubkey, target_node_id);
2281 assert_eq!(route.paths[0][1].short_channel_id, 8);
2282 assert_eq!(route.paths[0][1].fee_msat, 100);
2283 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2284 assert_eq!(route.paths[0][1].node_features.le_flags(), &[0; 0]); // We dont pass flags in from invoices yet
2285 assert_eq!(route.paths[0][1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
2289 fn available_amount_while_routing_test() {
2290 // Tests whether we choose the correct available channel amount while routing.
2292 let (secp_ctx, mut net_graph_msg_handler, chain_monitor, logger) = build_graph();
2293 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2295 // We will use a simple single-path route from
2296 // our node to node2 via node0: channels {1, 3}.
2298 // First disable all other paths.
2299 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2300 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2301 short_channel_id: 2,
2304 cltv_expiry_delta: 0,
2305 htlc_minimum_msat: 0,
2306 htlc_maximum_msat: OptionalField::Present(100_000),
2308 fee_proportional_millionths: 0,
2309 excess_data: Vec::new()
2311 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2312 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2313 short_channel_id: 12,
2316 cltv_expiry_delta: 0,
2317 htlc_minimum_msat: 0,
2318 htlc_maximum_msat: OptionalField::Present(100_000),
2320 fee_proportional_millionths: 0,
2321 excess_data: Vec::new()
2324 // Make the first channel (#1) very permissive,
2325 // and we will be testing all limits on the second channel.
2326 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2327 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2328 short_channel_id: 1,
2331 cltv_expiry_delta: 0,
2332 htlc_minimum_msat: 0,
2333 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2335 fee_proportional_millionths: 0,
2336 excess_data: Vec::new()
2339 // First, let's see if routing works if we have absolutely no idea about the available amount.
2340 // In this case, it should be set to 250_000 sats.
2341 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2342 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2343 short_channel_id: 3,
2346 cltv_expiry_delta: 0,
2347 htlc_minimum_msat: 0,
2348 htlc_maximum_msat: OptionalField::Absent,
2350 fee_proportional_millionths: 0,
2351 excess_data: Vec::new()
2355 // Attempt to route more than available results in a failure.
2356 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2357 Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000_001, 42, Arc::clone(&logger)) {
2358 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2359 } else { panic!(); }
2363 // Now, attempt to route an exact amount we have should be fine.
2364 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2365 Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000_000, 42, Arc::clone(&logger)).unwrap();
2366 assert_eq!(route.paths.len(), 1);
2367 let path = route.paths.last().unwrap();
2368 assert_eq!(path.len(), 2);
2369 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2370 assert_eq!(path.last().unwrap().fee_msat, 250_000_000);
2373 // Check that setting outbound_capacity_msat in first_hops limits the channels.
2374 // Disable channel #1 and use another first hop.
2375 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2376 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2377 short_channel_id: 1,
2380 cltv_expiry_delta: 0,
2381 htlc_minimum_msat: 0,
2382 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2384 fee_proportional_millionths: 0,
2385 excess_data: Vec::new()
2388 // Now, limit the first_hop by the outbound_capacity_msat of 200_000 sats.
2389 let our_chans = vec![channelmanager::ChannelDetails {
2390 channel_id: [0; 32],
2391 short_channel_id: Some(42),
2392 remote_network_id: nodes[0].clone(),
2393 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
2394 channel_value_satoshis: 0,
2396 outbound_capacity_msat: 200_000_000,
2397 inbound_capacity_msat: 0,
2399 counterparty_forwarding_info: None,
2403 // Attempt to route more than available results in a failure.
2404 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2405 Some(InvoiceFeatures::known()), Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 200_000_001, 42, Arc::clone(&logger)) {
2406 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2407 } else { panic!(); }
2411 // Now, attempt to route an exact amount we have should be fine.
2412 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2413 Some(InvoiceFeatures::known()), Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 200_000_000, 42, Arc::clone(&logger)).unwrap();
2414 assert_eq!(route.paths.len(), 1);
2415 let path = route.paths.last().unwrap();
2416 assert_eq!(path.len(), 2);
2417 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2418 assert_eq!(path.last().unwrap().fee_msat, 200_000_000);
2421 // Enable channel #1 back.
2422 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2423 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2424 short_channel_id: 1,
2427 cltv_expiry_delta: 0,
2428 htlc_minimum_msat: 0,
2429 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2431 fee_proportional_millionths: 0,
2432 excess_data: Vec::new()
2436 // Now let's see if routing works if we know only htlc_maximum_msat.
2437 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2438 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2439 short_channel_id: 3,
2442 cltv_expiry_delta: 0,
2443 htlc_minimum_msat: 0,
2444 htlc_maximum_msat: OptionalField::Present(15_000),
2446 fee_proportional_millionths: 0,
2447 excess_data: Vec::new()
2451 // Attempt to route more than available results in a failure.
2452 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2453 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_001, 42, Arc::clone(&logger)) {
2454 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2455 } else { panic!(); }
2459 // Now, attempt to route an exact amount we have should be fine.
2460 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2461 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_000, 42, Arc::clone(&logger)).unwrap();
2462 assert_eq!(route.paths.len(), 1);
2463 let path = route.paths.last().unwrap();
2464 assert_eq!(path.len(), 2);
2465 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2466 assert_eq!(path.last().unwrap().fee_msat, 15_000);
2469 // Now let's see if routing works if we know only capacity from the UTXO.
2471 // We can't change UTXO capacity on the fly, so we'll disable
2472 // the existing channel and add another one with the capacity we need.
2473 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2474 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2475 short_channel_id: 3,
2478 cltv_expiry_delta: 0,
2479 htlc_minimum_msat: 0,
2480 htlc_maximum_msat: OptionalField::Absent,
2482 fee_proportional_millionths: 0,
2483 excess_data: Vec::new()
2486 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
2487 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
2488 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
2489 .push_opcode(opcodes::all::OP_PUSHNUM_2)
2490 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
2492 *chain_monitor.utxo_ret.lock().unwrap() = Ok(TxOut { value: 15, script_pubkey: good_script.clone() });
2493 net_graph_msg_handler.add_chain_access(Some(chain_monitor));
2495 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
2496 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2497 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2498 short_channel_id: 333,
2501 cltv_expiry_delta: (3 << 8) | 1,
2502 htlc_minimum_msat: 0,
2503 htlc_maximum_msat: OptionalField::Absent,
2505 fee_proportional_millionths: 0,
2506 excess_data: Vec::new()
2508 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2509 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2510 short_channel_id: 333,
2513 cltv_expiry_delta: (3 << 8) | 2,
2514 htlc_minimum_msat: 0,
2515 htlc_maximum_msat: OptionalField::Absent,
2517 fee_proportional_millionths: 0,
2518 excess_data: Vec::new()
2522 // Attempt to route more than available results in a failure.
2523 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2524 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_001, 42, Arc::clone(&logger)) {
2525 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2526 } else { panic!(); }
2530 // Now, attempt to route an exact amount we have should be fine.
2531 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2532 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_000, 42, Arc::clone(&logger)).unwrap();
2533 assert_eq!(route.paths.len(), 1);
2534 let path = route.paths.last().unwrap();
2535 assert_eq!(path.len(), 2);
2536 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2537 assert_eq!(path.last().unwrap().fee_msat, 15_000);
2540 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
2541 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2542 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2543 short_channel_id: 333,
2546 cltv_expiry_delta: 0,
2547 htlc_minimum_msat: 0,
2548 htlc_maximum_msat: OptionalField::Present(10_000),
2550 fee_proportional_millionths: 0,
2551 excess_data: Vec::new()
2555 // Attempt to route more than available results in a failure.
2556 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2557 Some(InvoiceFeatures::known()), None, &Vec::new(), 10_001, 42, Arc::clone(&logger)) {
2558 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2559 } else { panic!(); }
2563 // Now, attempt to route an exact amount we have should be fine.
2564 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2565 Some(InvoiceFeatures::known()), None, &Vec::new(), 10_000, 42, Arc::clone(&logger)).unwrap();
2566 assert_eq!(route.paths.len(), 1);
2567 let path = route.paths.last().unwrap();
2568 assert_eq!(path.len(), 2);
2569 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2570 assert_eq!(path.last().unwrap().fee_msat, 10_000);
2575 fn available_liquidity_last_hop_test() {
2576 // Check that available liquidity properly limits the path even when only
2577 // one of the latter hops is limited.
2578 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2579 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2581 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
2582 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
2583 // Total capacity: 50 sats.
2585 // Disable other potential paths.
2586 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2587 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2588 short_channel_id: 2,
2591 cltv_expiry_delta: 0,
2592 htlc_minimum_msat: 0,
2593 htlc_maximum_msat: OptionalField::Present(100_000),
2595 fee_proportional_millionths: 0,
2596 excess_data: Vec::new()
2598 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2599 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2600 short_channel_id: 7,
2603 cltv_expiry_delta: 0,
2604 htlc_minimum_msat: 0,
2605 htlc_maximum_msat: OptionalField::Present(100_000),
2607 fee_proportional_millionths: 0,
2608 excess_data: Vec::new()
2613 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2614 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2615 short_channel_id: 12,
2618 cltv_expiry_delta: 0,
2619 htlc_minimum_msat: 0,
2620 htlc_maximum_msat: OptionalField::Present(100_000),
2622 fee_proportional_millionths: 0,
2623 excess_data: Vec::new()
2625 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2626 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2627 short_channel_id: 13,
2630 cltv_expiry_delta: 0,
2631 htlc_minimum_msat: 0,
2632 htlc_maximum_msat: OptionalField::Present(100_000),
2634 fee_proportional_millionths: 0,
2635 excess_data: Vec::new()
2638 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2639 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2640 short_channel_id: 6,
2643 cltv_expiry_delta: 0,
2644 htlc_minimum_msat: 0,
2645 htlc_maximum_msat: OptionalField::Present(50_000),
2647 fee_proportional_millionths: 0,
2648 excess_data: Vec::new()
2650 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
2651 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2652 short_channel_id: 11,
2655 cltv_expiry_delta: 0,
2656 htlc_minimum_msat: 0,
2657 htlc_maximum_msat: OptionalField::Present(100_000),
2659 fee_proportional_millionths: 0,
2660 excess_data: Vec::new()
2663 // Attempt to route more than available results in a failure.
2664 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
2665 Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger)) {
2666 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2667 } else { panic!(); }
2671 // Now, attempt to route 49 sats (just a bit below the capacity).
2672 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
2673 Some(InvoiceFeatures::known()), None, &Vec::new(), 49_000, 42, Arc::clone(&logger)).unwrap();
2674 assert_eq!(route.paths.len(), 1);
2675 let mut total_amount_paid_msat = 0;
2676 for path in &route.paths {
2677 assert_eq!(path.len(), 4);
2678 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
2679 total_amount_paid_msat += path.last().unwrap().fee_msat;
2681 assert_eq!(total_amount_paid_msat, 49_000);
2685 // Attempt to route an exact amount is also fine
2686 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
2687 Some(InvoiceFeatures::known()), None, &Vec::new(), 50_000, 42, Arc::clone(&logger)).unwrap();
2688 assert_eq!(route.paths.len(), 1);
2689 let mut total_amount_paid_msat = 0;
2690 for path in &route.paths {
2691 assert_eq!(path.len(), 4);
2692 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
2693 total_amount_paid_msat += path.last().unwrap().fee_msat;
2695 assert_eq!(total_amount_paid_msat, 50_000);
2700 fn ignore_fee_first_hop_test() {
2701 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2702 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2704 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
2705 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2706 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2707 short_channel_id: 1,
2710 cltv_expiry_delta: 0,
2711 htlc_minimum_msat: 0,
2712 htlc_maximum_msat: OptionalField::Present(100_000),
2713 fee_base_msat: 1_000_000,
2714 fee_proportional_millionths: 0,
2715 excess_data: Vec::new()
2717 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2718 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2719 short_channel_id: 3,
2722 cltv_expiry_delta: 0,
2723 htlc_minimum_msat: 0,
2724 htlc_maximum_msat: OptionalField::Present(50_000),
2726 fee_proportional_millionths: 0,
2727 excess_data: Vec::new()
2731 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();
2732 assert_eq!(route.paths.len(), 1);
2733 let mut total_amount_paid_msat = 0;
2734 for path in &route.paths {
2735 assert_eq!(path.len(), 2);
2736 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2737 total_amount_paid_msat += path.last().unwrap().fee_msat;
2739 assert_eq!(total_amount_paid_msat, 50_000);
2744 fn simple_mpp_route_test() {
2745 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2746 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2748 // We need a route consisting of 3 paths:
2749 // From our node to node2 via node0, node7, node1 (three paths one hop each).
2750 // To achieve this, the amount being transferred should be around
2751 // the total capacity of these 3 paths.
2753 // First, we set limits on these (previously unlimited) channels.
2754 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
2756 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
2757 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2758 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2759 short_channel_id: 1,
2762 cltv_expiry_delta: 0,
2763 htlc_minimum_msat: 0,
2764 htlc_maximum_msat: OptionalField::Present(100_000),
2766 fee_proportional_millionths: 0,
2767 excess_data: Vec::new()
2769 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2770 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2771 short_channel_id: 3,
2774 cltv_expiry_delta: 0,
2775 htlc_minimum_msat: 0,
2776 htlc_maximum_msat: OptionalField::Present(50_000),
2778 fee_proportional_millionths: 0,
2779 excess_data: Vec::new()
2782 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
2783 // (total limit 60).
2784 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2785 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2786 short_channel_id: 12,
2789 cltv_expiry_delta: 0,
2790 htlc_minimum_msat: 0,
2791 htlc_maximum_msat: OptionalField::Present(60_000),
2793 fee_proportional_millionths: 0,
2794 excess_data: Vec::new()
2796 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2797 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2798 short_channel_id: 13,
2801 cltv_expiry_delta: 0,
2802 htlc_minimum_msat: 0,
2803 htlc_maximum_msat: OptionalField::Present(60_000),
2805 fee_proportional_millionths: 0,
2806 excess_data: Vec::new()
2809 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
2810 // (total capacity 180 sats).
2811 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2812 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2813 short_channel_id: 2,
2816 cltv_expiry_delta: 0,
2817 htlc_minimum_msat: 0,
2818 htlc_maximum_msat: OptionalField::Present(200_000),
2820 fee_proportional_millionths: 0,
2821 excess_data: Vec::new()
2823 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2824 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2825 short_channel_id: 4,
2828 cltv_expiry_delta: 0,
2829 htlc_minimum_msat: 0,
2830 htlc_maximum_msat: OptionalField::Present(180_000),
2832 fee_proportional_millionths: 0,
2833 excess_data: Vec::new()
2837 // Attempt to route more than available results in a failure.
2838 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(),
2839 &nodes[2], Some(InvoiceFeatures::known()), None, &Vec::new(), 300_000, 42, Arc::clone(&logger)) {
2840 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2841 } else { panic!(); }
2845 // Now, attempt to route 250 sats (just a bit below the capacity).
2846 // Our algorithm should provide us with these 3 paths.
2847 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2848 Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000, 42, Arc::clone(&logger)).unwrap();
2849 assert_eq!(route.paths.len(), 3);
2850 let mut total_amount_paid_msat = 0;
2851 for path in &route.paths {
2852 assert_eq!(path.len(), 2);
2853 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2854 total_amount_paid_msat += path.last().unwrap().fee_msat;
2856 assert_eq!(total_amount_paid_msat, 250_000);
2860 // Attempt to route an exact amount is also fine
2861 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2862 Some(InvoiceFeatures::known()), None, &Vec::new(), 290_000, 42, Arc::clone(&logger)).unwrap();
2863 assert_eq!(route.paths.len(), 3);
2864 let mut total_amount_paid_msat = 0;
2865 for path in &route.paths {
2866 assert_eq!(path.len(), 2);
2867 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2868 total_amount_paid_msat += path.last().unwrap().fee_msat;
2870 assert_eq!(total_amount_paid_msat, 290_000);
2875 fn long_mpp_route_test() {
2876 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2877 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2879 // We need a route consisting of 3 paths:
2880 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
2881 // Note that these paths overlap (channels 5, 12, 13).
2882 // We will route 300 sats.
2883 // Each path will have 100 sats capacity, those channels which
2884 // are used twice will have 200 sats capacity.
2886 // Disable other potential paths.
2887 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2888 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2889 short_channel_id: 2,
2892 cltv_expiry_delta: 0,
2893 htlc_minimum_msat: 0,
2894 htlc_maximum_msat: OptionalField::Present(100_000),
2896 fee_proportional_millionths: 0,
2897 excess_data: Vec::new()
2899 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2900 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2901 short_channel_id: 7,
2904 cltv_expiry_delta: 0,
2905 htlc_minimum_msat: 0,
2906 htlc_maximum_msat: OptionalField::Present(100_000),
2908 fee_proportional_millionths: 0,
2909 excess_data: Vec::new()
2912 // Path via {node0, node2} is channels {1, 3, 5}.
2913 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2914 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2915 short_channel_id: 1,
2918 cltv_expiry_delta: 0,
2919 htlc_minimum_msat: 0,
2920 htlc_maximum_msat: OptionalField::Present(100_000),
2922 fee_proportional_millionths: 0,
2923 excess_data: Vec::new()
2925 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2926 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2927 short_channel_id: 3,
2930 cltv_expiry_delta: 0,
2931 htlc_minimum_msat: 0,
2932 htlc_maximum_msat: OptionalField::Present(100_000),
2934 fee_proportional_millionths: 0,
2935 excess_data: Vec::new()
2938 // Capacity of 200 sats because this channel will be used by 3rd path as well.
2939 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
2940 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2941 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2942 short_channel_id: 5,
2945 cltv_expiry_delta: 0,
2946 htlc_minimum_msat: 0,
2947 htlc_maximum_msat: OptionalField::Present(200_000),
2949 fee_proportional_millionths: 0,
2950 excess_data: Vec::new()
2953 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
2954 // Add 100 sats to the capacities of {12, 13}, because these channels
2955 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
2956 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2957 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2958 short_channel_id: 12,
2961 cltv_expiry_delta: 0,
2962 htlc_minimum_msat: 0,
2963 htlc_maximum_msat: OptionalField::Present(200_000),
2965 fee_proportional_millionths: 0,
2966 excess_data: Vec::new()
2968 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2969 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2970 short_channel_id: 13,
2973 cltv_expiry_delta: 0,
2974 htlc_minimum_msat: 0,
2975 htlc_maximum_msat: OptionalField::Present(200_000),
2977 fee_proportional_millionths: 0,
2978 excess_data: Vec::new()
2981 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2982 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2983 short_channel_id: 6,
2986 cltv_expiry_delta: 0,
2987 htlc_minimum_msat: 0,
2988 htlc_maximum_msat: OptionalField::Present(100_000),
2990 fee_proportional_millionths: 0,
2991 excess_data: Vec::new()
2993 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
2994 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2995 short_channel_id: 11,
2998 cltv_expiry_delta: 0,
2999 htlc_minimum_msat: 0,
3000 htlc_maximum_msat: OptionalField::Present(100_000),
3002 fee_proportional_millionths: 0,
3003 excess_data: Vec::new()
3006 // Path via {node7, node2} is channels {12, 13, 5}.
3007 // We already limited them to 200 sats (they are used twice for 100 sats).
3008 // Nothing to do here.
3011 // Attempt to route more than available results in a failure.
3012 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3013 Some(InvoiceFeatures::known()), None, &Vec::new(), 350_000, 42, Arc::clone(&logger)) {
3014 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3015 } else { panic!(); }
3019 // Now, attempt to route 300 sats (exact amount we can route).
3020 // Our algorithm should provide us with these 3 paths, 100 sats each.
3021 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3022 Some(InvoiceFeatures::known()), None, &Vec::new(), 300_000, 42, Arc::clone(&logger)).unwrap();
3023 assert_eq!(route.paths.len(), 3);
3025 let mut total_amount_paid_msat = 0;
3026 for path in &route.paths {
3027 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3028 total_amount_paid_msat += path.last().unwrap().fee_msat;
3030 assert_eq!(total_amount_paid_msat, 300_000);
3036 fn mpp_cheaper_route_test() {
3037 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3038 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3040 // This test checks that if we have two cheaper paths and one more expensive path,
3041 // so that liquidity-wise any 2 of 3 combination is sufficient,
3042 // two cheaper paths will be taken.
3043 // These paths have equal available liquidity.
3045 // We need a combination of 3 paths:
3046 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3047 // Note that these paths overlap (channels 5, 12, 13).
3048 // Each path will have 100 sats capacity, those channels which
3049 // are used twice will have 200 sats capacity.
3051 // Disable other potential paths.
3052 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3053 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3054 short_channel_id: 2,
3057 cltv_expiry_delta: 0,
3058 htlc_minimum_msat: 0,
3059 htlc_maximum_msat: OptionalField::Present(100_000),
3061 fee_proportional_millionths: 0,
3062 excess_data: Vec::new()
3064 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3065 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3066 short_channel_id: 7,
3069 cltv_expiry_delta: 0,
3070 htlc_minimum_msat: 0,
3071 htlc_maximum_msat: OptionalField::Present(100_000),
3073 fee_proportional_millionths: 0,
3074 excess_data: Vec::new()
3077 // Path via {node0, node2} is channels {1, 3, 5}.
3078 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3079 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3080 short_channel_id: 1,
3083 cltv_expiry_delta: 0,
3084 htlc_minimum_msat: 0,
3085 htlc_maximum_msat: OptionalField::Present(100_000),
3087 fee_proportional_millionths: 0,
3088 excess_data: Vec::new()
3090 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3091 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3092 short_channel_id: 3,
3095 cltv_expiry_delta: 0,
3096 htlc_minimum_msat: 0,
3097 htlc_maximum_msat: OptionalField::Present(100_000),
3099 fee_proportional_millionths: 0,
3100 excess_data: Vec::new()
3103 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3104 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3105 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3106 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3107 short_channel_id: 5,
3110 cltv_expiry_delta: 0,
3111 htlc_minimum_msat: 0,
3112 htlc_maximum_msat: OptionalField::Present(200_000),
3114 fee_proportional_millionths: 0,
3115 excess_data: Vec::new()
3118 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3119 // Add 100 sats to the capacities of {12, 13}, because these channels
3120 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3121 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3122 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3123 short_channel_id: 12,
3126 cltv_expiry_delta: 0,
3127 htlc_minimum_msat: 0,
3128 htlc_maximum_msat: OptionalField::Present(200_000),
3130 fee_proportional_millionths: 0,
3131 excess_data: Vec::new()
3133 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3134 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3135 short_channel_id: 13,
3138 cltv_expiry_delta: 0,
3139 htlc_minimum_msat: 0,
3140 htlc_maximum_msat: OptionalField::Present(200_000),
3142 fee_proportional_millionths: 0,
3143 excess_data: Vec::new()
3146 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3147 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3148 short_channel_id: 6,
3151 cltv_expiry_delta: 0,
3152 htlc_minimum_msat: 0,
3153 htlc_maximum_msat: OptionalField::Present(100_000),
3154 fee_base_msat: 1_000,
3155 fee_proportional_millionths: 0,
3156 excess_data: Vec::new()
3158 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3159 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3160 short_channel_id: 11,
3163 cltv_expiry_delta: 0,
3164 htlc_minimum_msat: 0,
3165 htlc_maximum_msat: OptionalField::Present(100_000),
3167 fee_proportional_millionths: 0,
3168 excess_data: Vec::new()
3171 // Path via {node7, node2} is channels {12, 13, 5}.
3172 // We already limited them to 200 sats (they are used twice for 100 sats).
3173 // Nothing to do here.
3176 // Now, attempt to route 180 sats.
3177 // Our algorithm should provide us with these 2 paths.
3178 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3179 Some(InvoiceFeatures::known()), None, &Vec::new(), 180_000, 42, Arc::clone(&logger)).unwrap();
3180 assert_eq!(route.paths.len(), 2);
3182 let mut total_value_transferred_msat = 0;
3183 let mut total_paid_msat = 0;
3184 for path in &route.paths {
3185 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3186 total_value_transferred_msat += path.last().unwrap().fee_msat;
3188 total_paid_msat += hop.fee_msat;
3191 // If we paid fee, this would be higher.
3192 assert_eq!(total_value_transferred_msat, 180_000);
3193 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
3194 assert_eq!(total_fees_paid, 0);
3199 fn fees_on_mpp_route_test() {
3200 // This test makes sure that MPP algorithm properly takes into account
3201 // fees charged on the channels, by making the fees impactful:
3202 // if the fee is not properly accounted for, the behavior is different.
3203 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3204 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3206 // We need a route consisting of 2 paths:
3207 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
3208 // We will route 200 sats, Each path will have 100 sats capacity.
3210 // This test is not particularly stable: e.g.,
3211 // there's a way to route via {node0, node2, node4}.
3212 // It works while pathfinding is deterministic, but can be broken otherwise.
3213 // It's fine to ignore this concern for now.
3215 // Disable other potential paths.
3216 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3217 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3218 short_channel_id: 2,
3221 cltv_expiry_delta: 0,
3222 htlc_minimum_msat: 0,
3223 htlc_maximum_msat: OptionalField::Present(100_000),
3225 fee_proportional_millionths: 0,
3226 excess_data: Vec::new()
3229 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3230 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3231 short_channel_id: 7,
3234 cltv_expiry_delta: 0,
3235 htlc_minimum_msat: 0,
3236 htlc_maximum_msat: OptionalField::Present(100_000),
3238 fee_proportional_millionths: 0,
3239 excess_data: Vec::new()
3242 // Path via {node0, node2} is channels {1, 3, 5}.
3243 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3244 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3245 short_channel_id: 1,
3248 cltv_expiry_delta: 0,
3249 htlc_minimum_msat: 0,
3250 htlc_maximum_msat: OptionalField::Present(100_000),
3252 fee_proportional_millionths: 0,
3253 excess_data: Vec::new()
3255 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3256 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3257 short_channel_id: 3,
3260 cltv_expiry_delta: 0,
3261 htlc_minimum_msat: 0,
3262 htlc_maximum_msat: OptionalField::Present(100_000),
3264 fee_proportional_millionths: 0,
3265 excess_data: Vec::new()
3268 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3269 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3270 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3271 short_channel_id: 5,
3274 cltv_expiry_delta: 0,
3275 htlc_minimum_msat: 0,
3276 htlc_maximum_msat: OptionalField::Present(100_000),
3278 fee_proportional_millionths: 0,
3279 excess_data: Vec::new()
3282 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3283 // All channels should be 100 sats capacity. But for the fee experiment,
3284 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
3285 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
3286 // 100 sats (and pay 150 sats in fees for the use of channel 6),
3287 // so no matter how large are other channels,
3288 // the whole path will be limited by 100 sats with just these 2 conditions:
3289 // - channel 12 capacity is 250 sats
3290 // - fee for channel 6 is 150 sats
3291 // Let's test this by enforcing these 2 conditions and removing other limits.
3292 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3293 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3294 short_channel_id: 12,
3297 cltv_expiry_delta: 0,
3298 htlc_minimum_msat: 0,
3299 htlc_maximum_msat: OptionalField::Present(250_000),
3301 fee_proportional_millionths: 0,
3302 excess_data: Vec::new()
3304 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3305 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3306 short_channel_id: 13,
3309 cltv_expiry_delta: 0,
3310 htlc_minimum_msat: 0,
3311 htlc_maximum_msat: OptionalField::Absent,
3313 fee_proportional_millionths: 0,
3314 excess_data: Vec::new()
3317 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3318 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3319 short_channel_id: 6,
3322 cltv_expiry_delta: 0,
3323 htlc_minimum_msat: 0,
3324 htlc_maximum_msat: OptionalField::Absent,
3325 fee_base_msat: 150_000,
3326 fee_proportional_millionths: 0,
3327 excess_data: Vec::new()
3329 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3330 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3331 short_channel_id: 11,
3334 cltv_expiry_delta: 0,
3335 htlc_minimum_msat: 0,
3336 htlc_maximum_msat: OptionalField::Absent,
3338 fee_proportional_millionths: 0,
3339 excess_data: Vec::new()
3343 // Attempt to route more than available results in a failure.
3344 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3345 Some(InvoiceFeatures::known()), None, &Vec::new(), 210_000, 42, Arc::clone(&logger)) {
3346 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3347 } else { panic!(); }
3351 // Now, attempt to route 200 sats (exact amount we can route).
3352 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3353 Some(InvoiceFeatures::known()), None, &Vec::new(), 200_000, 42, Arc::clone(&logger)).unwrap();
3354 assert_eq!(route.paths.len(), 2);
3356 let mut total_amount_paid_msat = 0;
3357 for path in &route.paths {
3358 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3359 total_amount_paid_msat += path.last().unwrap().fee_msat;
3361 assert_eq!(total_amount_paid_msat, 200_000);
3367 fn drop_lowest_channel_mpp_route_test() {
3368 // This test checks that low-capacity channel is dropped when after
3369 // path finding we realize that we found more capacity than we need.
3370 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3371 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3373 // We need a route consisting of 3 paths:
3374 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3376 // The first and the second paths should be sufficient, but the third should be
3377 // cheaper, so that we select it but drop later.
3379 // First, we set limits on these (previously unlimited) channels.
3380 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
3382 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
3383 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3384 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3385 short_channel_id: 1,
3388 cltv_expiry_delta: 0,
3389 htlc_minimum_msat: 0,
3390 htlc_maximum_msat: OptionalField::Present(100_000),
3392 fee_proportional_millionths: 0,
3393 excess_data: Vec::new()
3395 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3396 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3397 short_channel_id: 3,
3400 cltv_expiry_delta: 0,
3401 htlc_minimum_msat: 0,
3402 htlc_maximum_msat: OptionalField::Present(50_000),
3404 fee_proportional_millionths: 0,
3405 excess_data: Vec::new()
3408 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
3409 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3410 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3411 short_channel_id: 12,
3414 cltv_expiry_delta: 0,
3415 htlc_minimum_msat: 0,
3416 htlc_maximum_msat: OptionalField::Present(60_000),
3418 fee_proportional_millionths: 0,
3419 excess_data: Vec::new()
3421 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3422 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3423 short_channel_id: 13,
3426 cltv_expiry_delta: 0,
3427 htlc_minimum_msat: 0,
3428 htlc_maximum_msat: OptionalField::Present(60_000),
3430 fee_proportional_millionths: 0,
3431 excess_data: Vec::new()
3434 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
3435 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3436 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3437 short_channel_id: 2,
3440 cltv_expiry_delta: 0,
3441 htlc_minimum_msat: 0,
3442 htlc_maximum_msat: OptionalField::Present(20_000),
3444 fee_proportional_millionths: 0,
3445 excess_data: Vec::new()
3447 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3448 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3449 short_channel_id: 4,
3452 cltv_expiry_delta: 0,
3453 htlc_minimum_msat: 0,
3454 htlc_maximum_msat: OptionalField::Present(20_000),
3456 fee_proportional_millionths: 0,
3457 excess_data: Vec::new()
3461 // Attempt to route more than available results in a failure.
3462 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
3463 Some(InvoiceFeatures::known()), None, &Vec::new(), 150_000, 42, Arc::clone(&logger)) {
3464 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3465 } else { panic!(); }
3469 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
3470 // Our algorithm should provide us with these 3 paths.
3471 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
3472 Some(InvoiceFeatures::known()), None, &Vec::new(), 125_000, 42, Arc::clone(&logger)).unwrap();
3473 assert_eq!(route.paths.len(), 3);
3474 let mut total_amount_paid_msat = 0;
3475 for path in &route.paths {
3476 assert_eq!(path.len(), 2);
3477 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3478 total_amount_paid_msat += path.last().unwrap().fee_msat;
3480 assert_eq!(total_amount_paid_msat, 125_000);
3484 // Attempt to route without the last small cheap channel
3485 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
3486 Some(InvoiceFeatures::known()), None, &Vec::new(), 90_000, 42, Arc::clone(&logger)).unwrap();
3487 assert_eq!(route.paths.len(), 2);
3488 let mut total_amount_paid_msat = 0;
3489 for path in &route.paths {
3490 assert_eq!(path.len(), 2);
3491 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3492 total_amount_paid_msat += path.last().unwrap().fee_msat;
3494 assert_eq!(total_amount_paid_msat, 90_000);
3499 fn min_criteria_consistency() {
3500 // Test that we don't use an inconsistent metric between updating and walking nodes during
3501 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
3502 // was updated with a different critera from the heap sorting, resulting in loops in
3503 // calculated paths. We test for that specific case here.
3505 // We construct a network that looks like this:
3507 // node2 -1(3)2- node3
3511 // node1 -1(5)2- node4 -1(1)2- node6
3517 // We create a loop on the side of our real path - our destination is node 6, with a
3518 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
3519 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
3520 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
3521 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
3522 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
3523 // "previous hop" being set to node 3, creating a loop in the path.
3524 let secp_ctx = Secp256k1::new();
3525 let logger = Arc::new(test_utils::TestLogger::new());
3526 let net_graph_msg_handler = NetGraphMsgHandler::new(genesis_block(Network::Testnet).header.block_hash(), None, Arc::clone(&logger));
3527 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3529 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
3530 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3531 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3532 short_channel_id: 6,
3535 cltv_expiry_delta: (6 << 8) | 0,
3536 htlc_minimum_msat: 0,
3537 htlc_maximum_msat: OptionalField::Absent,
3539 fee_proportional_millionths: 0,
3540 excess_data: Vec::new()
3542 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
3544 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3545 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3546 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3547 short_channel_id: 5,
3550 cltv_expiry_delta: (5 << 8) | 0,
3551 htlc_minimum_msat: 0,
3552 htlc_maximum_msat: OptionalField::Absent,
3554 fee_proportional_millionths: 0,
3555 excess_data: Vec::new()
3557 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
3559 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
3560 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3561 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3562 short_channel_id: 4,
3565 cltv_expiry_delta: (4 << 8) | 0,
3566 htlc_minimum_msat: 0,
3567 htlc_maximum_msat: OptionalField::Absent,
3569 fee_proportional_millionths: 0,
3570 excess_data: Vec::new()
3572 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
3574 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
3575 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
3576 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3577 short_channel_id: 3,
3580 cltv_expiry_delta: (3 << 8) | 0,
3581 htlc_minimum_msat: 0,
3582 htlc_maximum_msat: OptionalField::Absent,
3584 fee_proportional_millionths: 0,
3585 excess_data: Vec::new()
3587 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
3589 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
3590 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3591 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3592 short_channel_id: 2,
3595 cltv_expiry_delta: (2 << 8) | 0,
3596 htlc_minimum_msat: 0,
3597 htlc_maximum_msat: OptionalField::Absent,
3599 fee_proportional_millionths: 0,
3600 excess_data: Vec::new()
3603 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
3604 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3605 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3606 short_channel_id: 1,
3609 cltv_expiry_delta: (1 << 8) | 0,
3610 htlc_minimum_msat: 100,
3611 htlc_maximum_msat: OptionalField::Absent,
3613 fee_proportional_millionths: 0,
3614 excess_data: Vec::new()
3616 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
3619 // Now ensure the route flows simply over nodes 1 and 4 to 6.
3620 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[6], None, None, &Vec::new(), 10_000, 42, Arc::clone(&logger)).unwrap();
3621 assert_eq!(route.paths.len(), 1);
3622 assert_eq!(route.paths[0].len(), 3);
3624 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3625 assert_eq!(route.paths[0][0].short_channel_id, 6);
3626 assert_eq!(route.paths[0][0].fee_msat, 100);
3627 assert_eq!(route.paths[0][0].cltv_expiry_delta, (5 << 8) | 0);
3628 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(1));
3629 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(6));
3631 assert_eq!(route.paths[0][1].pubkey, nodes[4]);
3632 assert_eq!(route.paths[0][1].short_channel_id, 5);
3633 assert_eq!(route.paths[0][1].fee_msat, 0);
3634 assert_eq!(route.paths[0][1].cltv_expiry_delta, (1 << 8) | 0);
3635 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(4));
3636 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(5));
3638 assert_eq!(route.paths[0][2].pubkey, nodes[6]);
3639 assert_eq!(route.paths[0][2].short_channel_id, 1);
3640 assert_eq!(route.paths[0][2].fee_msat, 10_000);
3641 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
3642 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
3643 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(1));
3649 fn exact_fee_liquidity_limit() {
3650 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
3651 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
3652 // we calculated fees on a higher value, resulting in us ignoring such paths.
3653 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3654 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3656 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
3658 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3659 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3660 short_channel_id: 2,
3663 cltv_expiry_delta: 0,
3664 htlc_minimum_msat: 0,
3665 htlc_maximum_msat: OptionalField::Present(85_000),
3667 fee_proportional_millionths: 0,
3668 excess_data: Vec::new()
3671 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3672 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3673 short_channel_id: 12,
3676 cltv_expiry_delta: (4 << 8) | 1,
3677 htlc_minimum_msat: 0,
3678 htlc_maximum_msat: OptionalField::Present(270_000),
3680 fee_proportional_millionths: 1000000,
3681 excess_data: Vec::new()
3684 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3685 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3686 short_channel_id: 13,
3689 cltv_expiry_delta: (13 << 8) | 2,
3690 htlc_minimum_msat: 0,
3691 htlc_maximum_msat: OptionalField::Absent,
3693 fee_proportional_millionths: 0,
3694 excess_data: Vec::new()
3698 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
3699 // Our algorithm should provide us with these 3 paths.
3700 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();
3701 assert_eq!(route.paths.len(), 1);
3702 assert_eq!(route.paths[0].len(), 2);
3704 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
3705 assert_eq!(route.paths[0][0].short_channel_id, 12);
3706 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
3707 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
3708 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
3709 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
3711 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3712 assert_eq!(route.paths[0][1].short_channel_id, 13);
3713 assert_eq!(route.paths[0][1].fee_msat, 90_000);
3714 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3715 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3716 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
3721 fn htlc_max_reduction_below_min() {
3722 // Test that if, while walking the graph, we reduce the value being sent to meet an
3723 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
3724 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
3725 // resulting in us thinking there is no possible path, even if other paths exist.
3726 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3727 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3729 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
3730 // gets an htlc_minimum_msat of 80_000 and channel 4 an htlc_maximum_msat of 90_000. We
3731 // then try to send 90_000.
3732 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3733 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3734 short_channel_id: 2,
3737 cltv_expiry_delta: 0,
3738 htlc_minimum_msat: 0,
3739 htlc_maximum_msat: OptionalField::Present(80_000),
3741 fee_proportional_millionths: 0,
3742 excess_data: Vec::new()
3744 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3745 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3746 short_channel_id: 4,
3749 cltv_expiry_delta: (4 << 8) | 1,
3750 htlc_minimum_msat: 90_000,
3751 htlc_maximum_msat: OptionalField::Absent,
3753 fee_proportional_millionths: 0,
3754 excess_data: Vec::new()
3758 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
3759 // Our algorithm should provide us with these 3 paths.
3760 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], Some(InvoiceFeatures::known()), None, &Vec::new(), 90_000, 42, Arc::clone(&logger)).unwrap();
3761 assert_eq!(route.paths.len(), 1);
3762 assert_eq!(route.paths[0].len(), 2);
3764 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
3765 assert_eq!(route.paths[0][0].short_channel_id, 12);
3766 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
3767 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
3768 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
3769 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
3771 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3772 assert_eq!(route.paths[0][1].short_channel_id, 13);
3773 assert_eq!(route.paths[0][1].fee_msat, 90_000);
3774 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3775 assert_eq!(route.paths[0][1].node_features.le_flags(), InvoiceFeatures::known().le_flags());
3776 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
3780 /// Tries to open a network graph file, or panics with a URL to fetch it.
3781 pub(super) fn get_route_file() -> std::fs::File {
3782 File::open("net_graph-2021-02-12.bin") // By default we're run in RL/lightning
3783 .or_else(|_| File::open("lightning/net_graph-2021-02-12.bin")) // We may be run manually in RL/
3784 .or_else(|_| { // Fall back to guessing based on the binary location
3785 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
3786 let mut path = std::env::current_exe().unwrap();
3787 path.pop(); // lightning-...
3789 path.pop(); // debug
3790 path.pop(); // target
3791 path.push("lightning");
3792 path.push("net_graph-2021-02-12.bin");
3793 eprintln!("{}", path.to_str().unwrap());
3796 .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")
3799 pub(super) fn random_init_seed() -> u64 {
3800 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
3801 use std::hash::{BuildHasher, Hasher};
3802 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
3803 println!("Using seed of {}", seed);
3808 use util::ser::Readable;
3810 fn generate_routes() {
3811 let mut d = get_route_file();
3812 let graph = NetworkGraph::read(&mut d).unwrap();
3814 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
3815 let mut seed = random_init_seed() as usize;
3816 'load_endpoints: for _ in 0..10 {
3818 seed = seed.overflowing_mul(0xdeadbeef).0;
3819 let src = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3820 seed = seed.overflowing_mul(0xdeadbeef).0;
3821 let dst = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3822 let amt = seed as u64 % 200_000_000;
3823 if get_route(src, &graph, dst, None, None, &[], amt, 42, &test_utils::TestLogger::new()).is_ok() {
3824 continue 'load_endpoints;
3831 fn generate_routes_mpp() {
3832 let mut d = get_route_file();
3833 let graph = NetworkGraph::read(&mut d).unwrap();
3835 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
3836 let mut seed = random_init_seed() as usize;
3837 'load_endpoints: for _ in 0..10 {
3839 seed = seed.overflowing_mul(0xdeadbeef).0;
3840 let src = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3841 seed = seed.overflowing_mul(0xdeadbeef).0;
3842 let dst = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3843 let amt = seed as u64 % 200_000_000;
3844 if get_route(src, &graph, dst, Some(InvoiceFeatures::known()), None, &[], amt, 42, &test_utils::TestLogger::new()).is_ok() {
3845 continue 'load_endpoints;
3852 #[cfg(all(test, feature = "unstable"))]
3855 use util::logger::{Logger, Record};
3860 struct DummyLogger {}
3861 impl Logger for DummyLogger {
3862 fn log(&self, _record: &Record) {}
3866 fn generate_routes(bench: &mut Bencher) {
3867 let mut d = tests::get_route_file();
3868 let graph = NetworkGraph::read(&mut d).unwrap();
3870 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
3871 let mut path_endpoints = Vec::new();
3872 let mut seed: usize = 0xdeadbeef;
3873 'load_endpoints: for _ in 0..100 {
3876 let src = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3878 let dst = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3879 let amt = seed as u64 % 1_000_000;
3880 if get_route(src, &graph, dst, None, None, &[], amt, 42, &DummyLogger{}).is_ok() {
3881 path_endpoints.push((src, dst, amt));
3882 continue 'load_endpoints;
3887 // ...then benchmark finding paths between the nodes we learned.
3890 let (src, dst, amt) = path_endpoints[idx % path_endpoints.len()];
3891 assert!(get_route(src, &graph, dst, None, None, &[], amt, 42, &DummyLogger{}).is_ok());
3897 fn generate_mpp_routes(bench: &mut Bencher) {
3898 let mut d = tests::get_route_file();
3899 let graph = NetworkGraph::read(&mut d).unwrap();
3901 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
3902 let mut path_endpoints = Vec::new();
3903 let mut seed: usize = 0xdeadbeef;
3904 'load_endpoints: for _ in 0..100 {
3907 let src = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3909 let dst = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3910 let amt = seed as u64 % 1_000_000;
3911 if get_route(src, &graph, dst, Some(InvoiceFeatures::known()), None, &[], amt, 42, &DummyLogger{}).is_ok() {
3912 path_endpoints.push((src, dst, amt));
3913 continue 'load_endpoints;
3918 // ...then benchmark finding paths between the nodes we learned.
3921 let (src, dst, amt) = path_endpoints[idx % path_endpoints.len()];
3922 assert!(get_route(src, &graph, dst, Some(InvoiceFeatures::known()), None, &[], amt, 42, &DummyLogger{}).is_ok());