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 alloc::collections::BinaryHeap;
27 use std::collections::HashMap;
31 #[derive(Clone, PartialEq)]
33 /// The node_id of the node at this hop.
34 pub pubkey: PublicKey,
35 /// The node_announcement features of the node at this hop. For the last hop, these may be
36 /// amended to match the features present in the invoice this node generated.
37 pub node_features: NodeFeatures,
38 /// The channel that should be used from the previous hop to reach this node.
39 pub short_channel_id: u64,
40 /// The channel_announcement features of the channel that should be used from the previous hop
41 /// to reach this node.
42 pub channel_features: ChannelFeatures,
43 /// The fee taken on this hop (for paying for the use of the *next* channel in the path).
44 /// For the last hop, this should be the full value of the payment (might be more than
45 /// requested if we had to match htlc_minimum_msat).
47 /// The CLTV delta added for this hop. For the last hop, this should be the full CLTV value
48 /// expected at the destination, in excess of the current block height.
49 pub cltv_expiry_delta: u32,
52 impl_writeable_tlv_based!(RouteHop, {
55 (4, short_channel_id),
56 (6, channel_features),
58 (10, cltv_expiry_delta),
61 /// A route directs a payment from the sender (us) to the recipient. If the recipient supports MPP,
62 /// it can take multiple paths. Each path is composed of one or more hops through the network.
63 #[derive(Clone, PartialEq)]
65 /// The list of routes taken for a single (potentially-)multi-part payment. The pubkey of the
66 /// last RouteHop in each path must be the same.
67 /// Each entry represents a list of hops, NOT INCLUDING our own, where the last hop is the
68 /// destination. Thus, this must always be at least length one. While the maximum length of any
69 /// given path is variable, keeping the length of any path to less than 20 should currently
70 /// ensure it is viable.
71 pub paths: Vec<Vec<RouteHop>>,
74 const SERIALIZATION_VERSION: u8 = 1;
75 const MIN_SERIALIZATION_VERSION: u8 = 1;
77 impl Writeable for Route {
78 fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
79 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
80 (self.paths.len() as u64).write(writer)?;
81 for hops in self.paths.iter() {
82 (hops.len() as u8).write(writer)?;
83 for hop in hops.iter() {
87 write_tlv_fields!(writer, {}, {});
92 impl Readable for Route {
93 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
94 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
95 let path_count: u64 = Readable::read(reader)?;
96 let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
97 for _ in 0..path_count {
98 let hop_count: u8 = Readable::read(reader)?;
99 let mut hops = Vec::with_capacity(hop_count as usize);
100 for _ in 0..hop_count {
101 hops.push(Readable::read(reader)?);
105 read_tlv_fields!(reader, {}, {});
110 /// A channel descriptor which provides a last-hop route to get_route
111 #[derive(Eq, PartialEq, Debug, Clone)]
112 pub struct RouteHintHop {
113 /// The node_id of the non-target end of the route
114 pub src_node_id: PublicKey,
115 /// The short_channel_id of this channel
116 pub short_channel_id: u64,
117 /// The fees which must be paid to use this channel
118 pub fees: RoutingFees,
119 /// The difference in CLTV values between this node and the next node.
120 pub cltv_expiry_delta: u16,
121 /// The minimum value, in msat, which must be relayed to the next hop.
122 pub htlc_minimum_msat: Option<u64>,
123 /// The maximum value in msat available for routing with a single HTLC.
124 pub htlc_maximum_msat: Option<u64>,
127 #[derive(Eq, PartialEq)]
128 struct RouteGraphNode {
130 lowest_fee_to_peer_through_node: u64,
131 lowest_fee_to_node: u64,
132 // The maximum value a yet-to-be-constructed payment path might flow through this node.
133 // This value is upper-bounded by us by:
134 // - how much is needed for a path being constructed
135 // - how much value can channels following this node (up to the destination) can contribute,
136 // considering their capacity and fees
137 value_contribution_msat: u64,
138 /// The effective htlc_minimum_msat at this hop. If a later hop on the path had a higher HTLC
139 /// minimum, we use it, plus the fees required at each earlier hop to meet it.
140 path_htlc_minimum_msat: u64,
143 impl cmp::Ord for RouteGraphNode {
144 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
145 let other_score = cmp::max(other.lowest_fee_to_peer_through_node, other.path_htlc_minimum_msat);
146 let self_score = cmp::max(self.lowest_fee_to_peer_through_node, self.path_htlc_minimum_msat);
147 other_score.cmp(&self_score).then_with(|| other.pubkey.serialize().cmp(&self.pubkey.serialize()))
151 impl cmp::PartialOrd for RouteGraphNode {
152 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
153 Some(self.cmp(other))
157 struct DummyDirectionalChannelInfo {
158 cltv_expiry_delta: u32,
159 htlc_minimum_msat: u64,
160 htlc_maximum_msat: Option<u64>,
164 /// It's useful to keep track of the hops associated with the fees required to use them,
165 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
166 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
167 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
169 struct PathBuildingHop<'a> {
170 // The RouteHintHop fields which will eventually be used if this hop is used in a final Route.
171 // Note that node_features is calculated separately after our initial graph walk.
173 short_channel_id: u64,
174 channel_features: &'a ChannelFeatures,
176 cltv_expiry_delta: u32,
178 /// Minimal fees required to route to the source node of the current hop via any of its inbound channels.
179 src_lowest_inbound_fees: RoutingFees,
180 /// Fees of the channel used in this hop.
181 channel_fees: RoutingFees,
182 /// All the fees paid *after* this channel on the way to the destination
183 next_hops_fee_msat: u64,
184 /// Fee paid for the use of the current channel (see channel_fees).
185 /// The value will be actually deducted from the counterparty balance on the previous link.
186 hop_use_fee_msat: u64,
187 /// Used to compare channels when choosing the for routing.
188 /// Includes paying for the use of a hop and the following hops, as well as
189 /// an estimated cost of reaching this hop.
190 /// Might get stale when fees are recomputed. Primarily for internal use.
192 /// This is useful for update_value_and_recompute_fees to make sure
193 /// we don't fall below the minimum. Should not be updated manually and
194 /// generally should not be accessed.
195 htlc_minimum_msat: u64,
196 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
197 /// walk and may be invalid thereafter.
198 path_htlc_minimum_msat: u64,
199 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
200 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
201 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
202 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
203 /// avoid processing them again.
205 #[cfg(any(test, feature = "fuzztarget"))]
206 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
207 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
208 // value_contribution_msat, which requires tracking it here. See comments below where it is
209 // used for more info.
210 value_contribution_msat: u64,
213 // Instantiated with a list of hops with correct data in them collected during path finding,
214 // an instance of this struct should be further modified only via given methods.
216 struct PaymentPath<'a> {
217 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
220 impl<'a> PaymentPath<'a> {
221 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
222 fn get_value_msat(&self) -> u64 {
223 self.hops.last().unwrap().0.fee_msat
226 fn get_total_fee_paid_msat(&self) -> u64 {
227 if self.hops.len() < 1 {
231 // Can't use next_hops_fee_msat because it gets outdated.
232 for (i, (hop, _)) in self.hops.iter().enumerate() {
233 if i != self.hops.len() - 1 {
234 result += hop.fee_msat;
240 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
241 // to change fees may result in an inconsistency.
243 // Sometimes we call this function right after constructing a path which is inconsistent in
244 // that it the value being transferred has decreased while we were doing path finding, leading
245 // to the fees being paid not lining up with the actual limits.
247 // Note that this function is not aware of the available_liquidity limit, and thus does not
248 // support increasing the value being transferred.
249 fn update_value_and_recompute_fees(&mut self, value_msat: u64) {
250 assert!(value_msat <= self.hops.last().unwrap().0.fee_msat);
252 let mut total_fee_paid_msat = 0 as u64;
253 for i in (0..self.hops.len()).rev() {
254 let last_hop = i == self.hops.len() - 1;
256 // For non-last-hop, this value will represent the fees paid on the current hop. It
257 // will consist of the fees for the use of the next hop, and extra fees to match
258 // htlc_minimum_msat of the current channel. Last hop is handled separately.
259 let mut cur_hop_fees_msat = 0;
261 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
264 let mut cur_hop = &mut self.hops.get_mut(i).unwrap().0;
265 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
266 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
267 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
268 // set it too high just to maliciously take more fees by exploiting this
269 // match htlc_minimum_msat logic.
270 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
271 if let Some(extra_fees_msat) = cur_hop.htlc_minimum_msat.checked_sub(cur_hop_transferred_amount_msat) {
272 // Note that there is a risk that *previous hops* (those closer to us, as we go
273 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
275 // This might make us end up with a broken route, although this should be super-rare
276 // in practice, both because of how healthy channels look like, and how we pick
277 // channels in add_entry.
278 // Also, this can't be exploited more heavily than *announce a free path and fail
280 cur_hop_transferred_amount_msat += extra_fees_msat;
281 total_fee_paid_msat += extra_fees_msat;
282 cur_hop_fees_msat += extra_fees_msat;
286 // Final hop is a special case: it usually has just value_msat (by design), but also
287 // it still could overpay for the htlc_minimum_msat.
288 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
290 // Propagate updated fees for the use of the channels to one hop back, where they
291 // will be actually paid (fee_msat). The last hop is handled above separately.
292 cur_hop.fee_msat = cur_hop_fees_msat;
295 // Fee for the use of the current hop which will be deducted on the previous hop.
296 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
297 // this channel is free for us.
299 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.channel_fees) {
300 cur_hop.hop_use_fee_msat = new_fee;
301 total_fee_paid_msat += new_fee;
303 // It should not be possible because this function is called only to reduce the
304 // value. In that case, compute_fee was already called with the same fees for
305 // larger amount and there was no overflow.
313 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
314 let proportional_fee_millions =
315 amount_msat.checked_mul(channel_fees.proportional_millionths as u64);
316 if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
317 (channel_fees.base_msat as u64).checked_add(part / 1_000_000) }) {
321 // This function may be (indirectly) called without any verification,
322 // with channel_fees provided by a caller. We should handle it gracefully.
327 /// Gets a route from us (payer) to the given target node (payee).
329 /// If the payee provided features in their invoice, they should be provided via payee_features.
330 /// Without this, MPP will only be used if the payee's features are available in the network graph.
332 /// Extra routing hops between known nodes and the target will be used if they are included in
335 /// If some channels aren't announced, it may be useful to fill in a first_hops with the
336 /// results from a local ChannelManager::list_usable_channels() call. If it is filled in, our
337 /// view of our local channels (from net_graph_msg_handler) will be ignored, and only those
338 /// in first_hops will be used.
340 /// Panics if first_hops contains channels without short_channel_ids
341 /// (ChannelManager::list_usable_channels will never include such channels).
343 /// The fees on channels from us to next-hops are ignored (as they are assumed to all be
344 /// equal), however the enabled/disabled bit on such channels as well as the
345 /// htlc_minimum_msat/htlc_maximum_msat *are* checked as they may change based on the receiving node.
346 pub fn get_route<L: Deref>(our_node_id: &PublicKey, network: &NetworkGraph, payee: &PublicKey, payee_features: Option<InvoiceFeatures>, first_hops: Option<&[&ChannelDetails]>,
347 last_hops: &[&RouteHintHop], final_value_msat: u64, final_cltv: u32, logger: L) -> Result<Route, LightningError> where L::Target: Logger {
348 // TODO: Obviously *only* using total fee cost sucks. We should consider weighting by
349 // uptime/success in using a node in the past.
350 if *payee == *our_node_id {
351 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
354 if final_value_msat > MAX_VALUE_MSAT {
355 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
358 if final_value_msat == 0 {
359 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
362 for last_hop in last_hops {
363 if last_hop.src_node_id == *payee {
364 return Err(LightningError{err: "Last hop cannot have a payee as a source.".to_owned(), action: ErrorAction::IgnoreError});
368 // The general routing idea is the following:
369 // 1. Fill first/last hops communicated by the caller.
370 // 2. Attempt to construct a path from payer to payee for transferring
371 // any ~sufficient (described later) value.
372 // If succeed, remember which channels were used and how much liquidity they have available,
373 // so that future paths don't rely on the same liquidity.
374 // 3. Prooceed to the next step if:
375 // - we hit the recommended target value;
376 // - OR if we could not construct a new path. Any next attempt will fail too.
377 // Otherwise, repeat step 2.
378 // 4. See if we managed to collect paths which aggregately are able to transfer target value
379 // (not recommended value). If yes, proceed. If not, fail routing.
380 // 5. Randomly combine paths into routes having enough to fulfill the payment. (TODO: knapsack)
381 // 6. Of all the found paths, select only those with the lowest total fee.
382 // 7. The last path in every selected route is likely to be more than we need.
383 // Reduce its value-to-transfer and recompute fees.
384 // 8. Choose the best route by the lowest total fee.
386 // As for the actual search algorithm,
387 // we do a payee-to-payer pseudo-Dijkstra's sorting by each node's distance from the payee
388 // plus the minimum per-HTLC fee to get from it to another node (aka "shitty pseudo-A*").
390 // We are not a faithful Dijkstra's implementation because we can change values which impact
391 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
392 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) then
393 // the value we are currently attempting to send over a path, we simply reduce the value being
394 // sent along the path for any hops after that channel. This may imply that later fees (which
395 // we've already tabulated) are lower because a smaller value is passing through the channels
396 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
397 // channels which were selected earlier (and which may still be used for other paths without a
398 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
401 // One potentially problematic case for this algorithm would be if there are many
402 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
403 // graph walking), we may never find a path which is not liquidity-limited and has lower
404 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
405 // Because we only consider paths with at least 5% of the total value being sent, the damage
406 // from such a case should be limited, however this could be further reduced in the future by
407 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
408 // limits for the purposes of fee calculation.
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 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
439 // it. If the payee supports it they're supposed to include it in the invoice, so that should
441 let allow_mpp = if let Some(features) = &payee_features {
442 features.supports_basic_mpp()
443 } else if let Some(node) = network.get_nodes().get(&payee) {
444 if let Some(node_info) = node.announcement_info.as_ref() {
445 node_info.features.supports_basic_mpp()
450 // Prepare the data we'll use for payee-to-payer search by
451 // inserting first hops suggested by the caller as targets.
452 // Our search will then attempt to reach them while traversing from the payee node.
453 let mut first_hop_targets: HashMap<_, (_, ChannelFeatures, _, NodeFeatures)> =
454 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
455 if let Some(hops) = first_hops {
457 let short_channel_id = chan.short_channel_id.expect("first_hops should be filled in with usable channels, not pending ones");
458 if chan.remote_network_id == *our_node_id {
459 return Err(LightningError{err: "First hop cannot have our_node_id as a destination.".to_owned(), action: ErrorAction::IgnoreError});
461 first_hop_targets.insert(chan.remote_network_id, (short_channel_id, chan.counterparty_features.to_context(), chan.outbound_capacity_msat, chan.counterparty_features.to_context()));
463 if first_hop_targets.is_empty() {
464 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
468 let empty_channel_features = ChannelFeatures::empty();
470 // The main heap containing all candidate next-hops sorted by their score (max(A* fee,
471 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
472 // adding duplicate entries when we find a better path to a given node.
473 let mut targets = BinaryHeap::new();
475 // Map from node_id to information about the best current path to that node, including feerate
477 let mut dist = HashMap::with_capacity(network.get_nodes().len());
479 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
480 // indicating that we may wish to try again with a higher value, potentially paying to meet an
481 // htlc_minimum with extra fees while still finding a cheaper path.
482 let mut hit_minimum_limit;
484 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
485 // We start with a path_value of the exact amount we want, and if that generates a route we may
486 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
487 // amount we want in total across paths, selecting the best subset at the end.
488 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
489 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
490 let mut path_value_msat = final_value_msat;
492 // We don't want multiple paths (as per MPP) share liquidity of the same channels.
493 // This map allows paths to be aware of the channel use by other paths in the same call.
494 // This would help to make a better path finding decisions and not "overbook" channels.
495 // It is unaware of the directions (except for `outbound_capacity_msat` in `first_hops`).
496 let mut bookkeeped_channels_liquidity_available_msat = HashMap::with_capacity(network.get_nodes().len());
498 // Keeping track of how much value we already collected across other paths. Helps to decide:
499 // - how much a new path should be transferring (upper bound);
500 // - whether a channel should be disregarded because
501 // it's available liquidity is too small comparing to how much more we need to collect;
502 // - when we want to stop looking for new paths.
503 let mut already_collected_value_msat = 0;
505 macro_rules! add_entry {
506 // Adds entry which goes from $src_node_id to $dest_node_id
507 // over the channel with id $chan_id with fees described in
508 // $directional_info.
509 // $next_hops_fee_msat represents the fees paid for using all the channel *after* this one,
510 // since that value has to be transferred over this channel.
511 ( $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,
512 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr ) => {
513 // Channels to self should not be used. This is more of belt-and-suspenders, because in
514 // practice these cases should be caught earlier:
515 // - for regular channels at channel announcement (TODO)
516 // - for first and last hops early in get_route
517 if $src_node_id != $dest_node_id.clone() {
518 let available_liquidity_msat = bookkeeped_channels_liquidity_available_msat.entry($chan_id.clone()).or_insert_with(|| {
519 let mut initial_liquidity_available_msat = None;
520 if let Some(capacity_sats) = $capacity_sats {
521 initial_liquidity_available_msat = Some(capacity_sats * 1000);
524 if let Some(htlc_maximum_msat) = $directional_info.htlc_maximum_msat {
525 if let Some(available_msat) = initial_liquidity_available_msat {
526 initial_liquidity_available_msat = Some(cmp::min(available_msat, htlc_maximum_msat));
528 initial_liquidity_available_msat = Some(htlc_maximum_msat);
532 match initial_liquidity_available_msat {
533 Some(available_msat) => available_msat,
534 // We assume channels with unknown balance have
535 // a capacity of 0.0025 BTC (or 250_000 sats).
536 None => 250_000 * 1000
540 // It is tricky to substract $next_hops_fee_msat from available liquidity here.
541 // It may be misleading because we might later choose to reduce the value transferred
542 // over these channels, and the channel which was insufficient might become sufficient.
543 // Worst case: we drop a good channel here because it can't cover the high following
544 // fees caused by one expensive channel, but then this channel could have been used
545 // if the amount being transferred over this path is lower.
546 // We do this for now, but this is a subject for removal.
547 if let Some(available_value_contribution_msat) = available_liquidity_msat.checked_sub($next_hops_fee_msat) {
549 // Routing Fragmentation Mitigation heuristic:
551 // Routing fragmentation across many payment paths increases the overall routing
552 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
553 // Taking too many smaller paths also increases the chance of payment failure.
554 // Thus to avoid this effect, we require from our collected links to provide
555 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
557 // This requirement is currently 5% of the remaining-to-be-collected value.
558 // This means as we successfully advance in our collection,
559 // the absolute liquidity contribution is lowered,
560 // thus increasing the number of potential channels to be selected.
562 // Derive the minimal liquidity contribution with a ratio of 20 (5%, rounded up)
563 // or 100% if we're not allowed to do multipath payments.
564 let minimal_value_contribution_msat: u64 = if allow_mpp {
565 (recommended_value_msat - already_collected_value_msat + 19) / 20
569 // Verify the liquidity offered by this channel complies to the minimal contribution.
570 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
572 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
573 // Includes paying fees for the use of the following channels.
574 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
575 Some(result) => result,
576 // Can't overflow due to how the values were computed right above.
577 None => unreachable!(),
579 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
580 let over_path_minimum_msat = amount_to_transfer_over_msat >= $directional_info.htlc_minimum_msat &&
581 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
583 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
584 // bother considering this channel.
585 // Since we're choosing amount_to_transfer_over_msat as maximum possible, it can
586 // be only reduced later (not increased), so this channel should just be skipped
587 // as not sufficient.
588 if !over_path_minimum_msat {
589 hit_minimum_limit = true;
590 } else if contributes_sufficient_value {
591 // Note that low contribution here (limited by available_liquidity_msat)
592 // might violate htlc_minimum_msat on the hops which are next along the
593 // payment path (upstream to the payee). To avoid that, we recompute path
594 // path fees knowing the final path contribution after constructing it.
595 let path_htlc_minimum_msat = match compute_fees($next_hops_path_htlc_minimum_msat, $directional_info.fees)
596 .map(|fee_msat| fee_msat.checked_add($next_hops_path_htlc_minimum_msat)) {
597 Some(Some(value_msat)) => cmp::max(value_msat, $directional_info.htlc_minimum_msat),
598 _ => u64::max_value()
600 let hm_entry = dist.entry(&$src_node_id);
601 let old_entry = hm_entry.or_insert_with(|| {
602 // If there was previously no known way to access
603 // the source node (recall it goes payee-to-payer) of $chan_id, first add
604 // a semi-dummy record just to compute the fees to reach the source node.
605 // This will affect our decision on selecting $chan_id
606 // as a way to reach the $dest_node_id.
607 let mut fee_base_msat = u32::max_value();
608 let mut fee_proportional_millionths = u32::max_value();
609 if let Some(Some(fees)) = network.get_nodes().get(&$src_node_id).map(|node| node.lowest_inbound_channel_fees) {
610 fee_base_msat = fees.base_msat;
611 fee_proportional_millionths = fees.proportional_millionths;
614 pubkey: $dest_node_id.clone(),
616 channel_features: $chan_features,
618 cltv_expiry_delta: 0,
619 src_lowest_inbound_fees: RoutingFees {
620 base_msat: fee_base_msat,
621 proportional_millionths: fee_proportional_millionths,
623 channel_fees: $directional_info.fees,
624 next_hops_fee_msat: u64::max_value(),
625 hop_use_fee_msat: u64::max_value(),
626 total_fee_msat: u64::max_value(),
627 htlc_minimum_msat: $directional_info.htlc_minimum_msat,
628 path_htlc_minimum_msat,
629 was_processed: false,
630 #[cfg(any(test, feature = "fuzztarget"))]
631 value_contribution_msat,
635 #[allow(unused_mut)] // We only use the mut in cfg(test)
636 let mut should_process = !old_entry.was_processed;
637 #[cfg(any(test, feature = "fuzztarget"))]
639 // In test/fuzzing builds, we do extra checks to make sure the skipping
640 // of already-seen nodes only happens in cases we expect (see below).
641 if !should_process { should_process = true; }
645 let mut hop_use_fee_msat = 0;
646 let mut total_fee_msat = $next_hops_fee_msat;
648 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
649 // will have the same effective-fee
650 if $src_node_id != *our_node_id {
651 match compute_fees(amount_to_transfer_over_msat, $directional_info.fees) {
652 // max_value means we'll always fail
653 // the old_entry.total_fee_msat > total_fee_msat check
654 None => total_fee_msat = u64::max_value(),
656 hop_use_fee_msat = fee_msat;
657 total_fee_msat += hop_use_fee_msat;
658 // When calculating the lowest inbound fees to a node, we
659 // calculate fees here not based on the actual value we think
660 // will flow over this channel, but on the minimum value that
661 // we'll accept flowing over it. The minimum accepted value
662 // is a constant through each path collection run, ensuring
663 // consistent basis. Otherwise we may later find a
664 // different path to the source node that is more expensive,
665 // but which we consider to be cheaper because we are capacity
666 // constrained and the relative fee becomes lower.
667 match compute_fees(minimal_value_contribution_msat, old_entry.src_lowest_inbound_fees)
668 .map(|a| a.checked_add(total_fee_msat)) {
673 total_fee_msat = u64::max_value();
680 let new_graph_node = RouteGraphNode {
681 pubkey: $src_node_id,
682 lowest_fee_to_peer_through_node: total_fee_msat,
683 lowest_fee_to_node: $next_hops_fee_msat as u64 + hop_use_fee_msat,
684 value_contribution_msat: value_contribution_msat,
685 path_htlc_minimum_msat,
688 // Update the way of reaching $src_node_id with the given $chan_id (from $dest_node_id),
689 // if this way is cheaper than the already known
690 // (considering the cost to "reach" this channel from the route destination,
691 // the cost of using this channel,
692 // and the cost of routing to the source node of this channel).
693 // Also, consider that htlc_minimum_msat_difference, because we might end up
694 // paying it. Consider the following exploit:
695 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
696 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
697 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
698 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
700 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
701 // but it may require additional tracking - we don't want to double-count
702 // the fees included in $next_hops_path_htlc_minimum_msat, but also
703 // can't use something that may decrease on future hops.
704 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat);
705 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat);
707 if !old_entry.was_processed && new_cost < old_cost {
708 targets.push(new_graph_node);
709 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
710 old_entry.hop_use_fee_msat = hop_use_fee_msat;
711 old_entry.total_fee_msat = total_fee_msat;
712 old_entry.pubkey = $dest_node_id.clone();
713 old_entry.short_channel_id = $chan_id.clone();
714 old_entry.channel_features = $chan_features;
715 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
716 old_entry.cltv_expiry_delta = $directional_info.cltv_expiry_delta as u32;
717 old_entry.channel_fees = $directional_info.fees;
718 old_entry.htlc_minimum_msat = $directional_info.htlc_minimum_msat;
719 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
720 #[cfg(any(test, feature = "fuzztarget"))]
722 old_entry.value_contribution_msat = value_contribution_msat;
724 } else if old_entry.was_processed && new_cost < old_cost {
725 #[cfg(any(test, feature = "fuzztarget"))]
727 // If we're skipping processing a node which was previously
728 // processed even though we found another path to it with a
729 // cheaper fee, check that it was because the second path we
730 // found (which we are processing now) has a lower value
731 // contribution due to an HTLC minimum limit.
733 // e.g. take a graph with two paths from node 1 to node 2, one
734 // through channel A, and one through channel B. Channel A and
735 // B are both in the to-process heap, with their scores set by
736 // a higher htlc_minimum than fee.
737 // Channel A is processed first, and the channels onwards from
738 // node 1 are added to the to-process heap. Thereafter, we pop
739 // Channel B off of the heap, note that it has a much more
740 // restrictive htlc_maximum_msat, and recalculate the fees for
741 // all of node 1's channels using the new, reduced, amount.
743 // This would be bogus - we'd be selecting a higher-fee path
744 // with a lower htlc_maximum_msat instead of the one we'd
745 // already decided to use.
746 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
747 debug_assert!(value_contribution_msat < old_entry.value_contribution_msat);
757 let empty_node_features = NodeFeatures::empty();
758 // Find ways (channels with destination) to reach a given node and store them
759 // in the corresponding data structures (routing graph etc).
760 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
761 // meaning how much will be paid in fees after this node (to the best of our knowledge).
762 // This data can later be helpful to optimize routing (pay lower fees).
763 macro_rules! add_entries_to_cheapest_to_target_node {
764 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr, $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr ) => {
765 let skip_node = if let Some(elem) = dist.get_mut($node_id) {
766 let was_processed = elem.was_processed;
767 elem.was_processed = true;
770 // Entries are added to dist in add_entry!() when there is a channel from a node.
771 // Because there are no channels from payee, it will not have a dist entry at this point.
772 // If we're processing any other node, it is always be the result of a channel from it.
773 assert_eq!($node_id, payee);
778 if first_hops.is_some() {
779 if let Some(&(ref first_hop, ref features, ref outbound_capacity_msat, _)) = first_hop_targets.get(&$node_id) {
780 add_entry!(first_hop, *our_node_id, $node_id, dummy_directional_info, Some(outbound_capacity_msat / 1000), features, $fee_to_target_msat, $next_hops_value_contribution, $next_hops_path_htlc_minimum_msat);
784 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
790 if !features.requires_unknown_bits() {
791 for chan_id in $node.channels.iter() {
792 let chan = network.get_channels().get(chan_id).unwrap();
793 if !chan.features.requires_unknown_bits() {
794 if chan.node_one == *$node_id {
795 // ie $node is one, ie next hop in A* is two, via the two_to_one channel
796 if first_hops.is_none() || chan.node_two != *our_node_id {
797 if let Some(two_to_one) = chan.two_to_one.as_ref() {
798 if two_to_one.enabled {
799 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, $next_hops_path_htlc_minimum_msat);
804 if first_hops.is_none() || chan.node_one != *our_node_id {
805 if let Some(one_to_two) = chan.one_to_two.as_ref() {
806 if one_to_two.enabled {
807 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, $next_hops_path_htlc_minimum_msat);
819 let mut payment_paths = Vec::<PaymentPath>::new();
821 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
822 'paths_collection: loop {
823 // For every new path, start from scratch, except
824 // bookkeeped_channels_liquidity_available_msat, which will improve
825 // the further iterations of path finding. Also don't erase first_hop_targets.
828 hit_minimum_limit = false;
830 // If first hop is a private channel and the only way to reach the payee, this is the only
831 // place where it could be added.
832 if first_hops.is_some() {
833 if let Some(&(ref first_hop, ref features, ref outbound_capacity_msat, _)) = first_hop_targets.get(&payee) {
834 add_entry!(first_hop, *our_node_id, payee, dummy_directional_info, Some(outbound_capacity_msat / 1000), features, 0, path_value_msat, 0);
838 // Add the payee as a target, so that the payee-to-payer
839 // search algorithm knows what to start with.
840 match network.get_nodes().get(payee) {
841 // The payee is not in our network graph, so nothing to add here.
842 // There is still a chance of reaching them via last_hops though,
843 // so don't yet fail the payment here.
844 // If not, targets.pop() will not even let us enter the loop in step 2.
847 add_entries_to_cheapest_to_target_node!(node, payee, 0, path_value_msat, 0);
852 // If a caller provided us with last hops, add them to routing targets. Since this happens
853 // earlier than general path finding, they will be somewhat prioritized, although currently
854 // it matters only if the fees are exactly the same.
855 for hop in last_hops.iter() {
856 let have_hop_src_in_graph =
857 if let Some(&(ref first_hop, ref features, ref outbound_capacity_msat, _)) = first_hop_targets.get(&hop.src_node_id) {
858 // If this hop connects to a node with which we have a direct channel, ignore
859 // the network graph and add both the hop and our direct channel to
860 // the candidate set.
862 // Currently there are no channel-context features defined, so we are a
863 // bit lazy here. In the future, we should pull them out via our
864 // ChannelManager, but there's no reason to waste the space until we
866 add_entry!(first_hop, *our_node_id , hop.src_node_id, dummy_directional_info, Some(outbound_capacity_msat / 1000), features, 0, path_value_msat, 0);
869 // In any other case, only add the hop if the source is in the regular network
871 network.get_nodes().get(&hop.src_node_id).is_some()
873 if have_hop_src_in_graph {
874 // BOLT 11 doesn't allow inclusion of features for the last hop hints, which
875 // really sucks, cause we're gonna need that eventually.
876 let last_hop_htlc_minimum_msat: u64 = match hop.htlc_minimum_msat {
877 Some(htlc_minimum_msat) => htlc_minimum_msat,
880 let directional_info = DummyDirectionalChannelInfo {
881 cltv_expiry_delta: hop.cltv_expiry_delta as u32,
882 htlc_minimum_msat: last_hop_htlc_minimum_msat,
883 htlc_maximum_msat: hop.htlc_maximum_msat,
886 add_entry!(hop.short_channel_id, hop.src_node_id, payee, directional_info, None::<u64>, &empty_channel_features, 0, path_value_msat, 0);
890 // At this point, targets are filled with the data from first and
891 // last hops communicated by the caller, and the payment receiver.
892 let mut found_new_path = false;
895 // If this loop terminates due the exhaustion of targets, two situations are possible:
896 // - not enough outgoing liquidity:
897 // 0 < already_collected_value_msat < final_value_msat
898 // - enough outgoing liquidity:
899 // final_value_msat <= already_collected_value_msat < recommended_value_msat
900 // Both these cases (and other cases except reaching recommended_value_msat) mean that
901 // paths_collection will be stopped because found_new_path==false.
902 // This is not necessarily a routing failure.
903 'path_construction: while let Some(RouteGraphNode { pubkey, lowest_fee_to_node, value_contribution_msat, path_htlc_minimum_msat, .. }) = targets.pop() {
905 // Since we're going payee-to-payer, hitting our node as a target means we should stop
906 // traversing the graph and arrange the path out of what we found.
907 if pubkey == *our_node_id {
908 let mut new_entry = dist.remove(&our_node_id).unwrap();
909 let mut ordered_hops = vec!((new_entry.clone(), NodeFeatures::empty()));
912 if let Some(&(_, _, _, ref features)) = first_hop_targets.get(&ordered_hops.last().unwrap().0.pubkey) {
913 ordered_hops.last_mut().unwrap().1 = features.clone();
914 } else if let Some(node) = network.get_nodes().get(&ordered_hops.last().unwrap().0.pubkey) {
915 if let Some(node_info) = node.announcement_info.as_ref() {
916 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
918 ordered_hops.last_mut().unwrap().1 = NodeFeatures::empty();
921 // We should be able to fill in features for everything except the last
922 // hop, if the last hop was provided via a BOLT 11 invoice (though we
923 // should be able to extend it further as BOLT 11 does have feature
924 // flags for the last hop node itself).
925 assert!(ordered_hops.last().unwrap().0.pubkey == *payee);
928 // Means we succesfully traversed from the payer to the payee, now
929 // save this path for the payment route. Also, update the liquidity
930 // remaining on the used hops, so that we take them into account
931 // while looking for more paths.
932 if ordered_hops.last().unwrap().0.pubkey == *payee {
936 new_entry = match dist.remove(&ordered_hops.last().unwrap().0.pubkey) {
937 Some(payment_hop) => payment_hop,
938 // We can't arrive at None because, if we ever add an entry to targets,
939 // we also fill in the entry in dist (see add_entry!).
940 None => unreachable!(),
942 // We "propagate" the fees one hop backward (topologically) here,
943 // so that fees paid for a HTLC forwarding on the current channel are
944 // associated with the previous channel (where they will be subtracted).
945 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
946 ordered_hops.last_mut().unwrap().0.cltv_expiry_delta = new_entry.cltv_expiry_delta;
947 ordered_hops.push((new_entry.clone(), NodeFeatures::empty()));
949 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
950 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
951 ordered_hops.last_mut().unwrap().0.cltv_expiry_delta = final_cltv;
953 let mut payment_path = PaymentPath {hops: ordered_hops};
955 // We could have possibly constructed a slightly inconsistent path: since we reduce
956 // value being transferred along the way, we could have violated htlc_minimum_msat
957 // on some channels we already passed (assuming dest->source direction). Here, we
958 // recompute the fees again, so that if that's the case, we match the currently
959 // underpaid htlc_minimum_msat with fees.
960 payment_path.update_value_and_recompute_fees(cmp::min(value_contribution_msat, final_value_msat));
962 // Since a path allows to transfer as much value as
963 // the smallest channel it has ("bottleneck"), we should recompute
964 // the fees so sender HTLC don't overpay fees when traversing
965 // larger channels than the bottleneck. This may happen because
966 // when we were selecting those channels we were not aware how much value
967 // this path will transfer, and the relative fee for them
968 // might have been computed considering a larger value.
969 // Remember that we used these channels so that we don't rely
970 // on the same liquidity in future paths.
971 let mut prevented_redundant_path_selection = false;
972 for (payment_hop, _) in payment_path.hops.iter() {
973 let channel_liquidity_available_msat = bookkeeped_channels_liquidity_available_msat.get_mut(&payment_hop.short_channel_id).unwrap();
974 let mut spent_on_hop_msat = value_contribution_msat;
975 let next_hops_fee_msat = payment_hop.next_hops_fee_msat;
976 spent_on_hop_msat += next_hops_fee_msat;
977 if spent_on_hop_msat == *channel_liquidity_available_msat {
978 // If this path used all of this channel's available liquidity, we know
979 // this path will not be selected again in the next loop iteration.
980 prevented_redundant_path_selection = true;
982 *channel_liquidity_available_msat -= spent_on_hop_msat;
984 if !prevented_redundant_path_selection {
985 // If we weren't capped by hitting a liquidity limit on a channel in the path,
986 // we'll probably end up picking the same path again on the next iteration.
987 // Decrease the available liquidity of a hop in the middle of the path.
988 let victim_liquidity = bookkeeped_channels_liquidity_available_msat.get_mut(
989 &payment_path.hops[(payment_path.hops.len() - 1) / 2].0.short_channel_id).unwrap();
990 *victim_liquidity = 0;
993 // Track the total amount all our collected paths allow to send so that we:
994 // - know when to stop looking for more paths
995 // - know which of the hops are useless considering how much more sats we need
996 // (contributes_sufficient_value)
997 already_collected_value_msat += value_contribution_msat;
999 payment_paths.push(payment_path);
1000 found_new_path = true;
1001 break 'path_construction;
1004 // If we found a path back to the payee, we shouldn't try to process it again. This is
1005 // the equivalent of the `elem.was_processed` check in
1006 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
1007 if pubkey == *payee { continue 'path_construction; }
1009 // Otherwise, since the current target node is not us,
1010 // keep "unrolling" the payment graph from payee to payer by
1011 // finding a way to reach the current target from the payer side.
1012 match network.get_nodes().get(&pubkey) {
1015 add_entries_to_cheapest_to_target_node!(node, &pubkey, lowest_fee_to_node, value_contribution_msat, path_htlc_minimum_msat);
1021 // If we don't support MPP, no use trying to gather more value ever.
1022 break 'paths_collection;
1026 // Stop either when the recommended value is reached or if no new path was found in this
1028 // In the latter case, making another path finding attempt won't help,
1029 // because we deterministically terminated the search due to low liquidity.
1030 if already_collected_value_msat >= recommended_value_msat || !found_new_path {
1031 break 'paths_collection;
1032 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
1033 // Further, if this was our first walk of the graph, and we weren't limited by an
1034 // htlc_minimum_msat, return immediately because this path should suffice. If we were
1035 // limited by an htlc_minimum_msat value, find another path with a higher value,
1036 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
1037 // still keeping a lower total fee than this path.
1038 if !hit_minimum_limit {
1039 break 'paths_collection;
1041 path_value_msat = recommended_value_msat;
1046 if payment_paths.len() == 0 {
1047 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1050 if already_collected_value_msat < final_value_msat {
1051 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1054 // Sort by total fees and take the best paths.
1055 payment_paths.sort_by_key(|path| path.get_total_fee_paid_msat());
1056 if payment_paths.len() > 50 {
1057 payment_paths.truncate(50);
1060 // Draw multiple sufficient routes by randomly combining the selected paths.
1061 let mut drawn_routes = Vec::new();
1062 for i in 0..payment_paths.len() {
1063 let mut cur_route = Vec::<PaymentPath>::new();
1064 let mut aggregate_route_value_msat = 0;
1067 // TODO: real random shuffle
1068 // Currently just starts with i_th and goes up to i-1_th in a looped way.
1069 let cur_payment_paths = [&payment_paths[i..], &payment_paths[..i]].concat();
1072 for payment_path in cur_payment_paths {
1073 cur_route.push(payment_path.clone());
1074 aggregate_route_value_msat += payment_path.get_value_msat();
1075 if aggregate_route_value_msat > final_value_msat {
1076 // Last path likely overpaid. Substract it from the most expensive
1077 // (in terms of proportional fee) path in this route and recompute fees.
1078 // This might be not the most economically efficient way, but fewer paths
1079 // also makes routing more reliable.
1080 let mut overpaid_value_msat = aggregate_route_value_msat - final_value_msat;
1082 // First, drop some expensive low-value paths entirely if possible.
1083 // Sort by value so that we drop many really-low values first, since
1084 // fewer paths is better: the payment is less likely to fail.
1085 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1086 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1087 cur_route.sort_by_key(|path| path.get_value_msat());
1088 // We should make sure that at least 1 path left.
1089 let mut paths_left = cur_route.len();
1090 cur_route.retain(|path| {
1091 if paths_left == 1 {
1094 let mut keep = true;
1095 let path_value_msat = path.get_value_msat();
1096 if path_value_msat <= overpaid_value_msat {
1098 overpaid_value_msat -= path_value_msat;
1104 if overpaid_value_msat == 0 {
1108 assert!(cur_route.len() > 0);
1111 // Now, substract the overpaid value from the most-expensive path.
1112 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1113 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1114 cur_route.sort_by_key(|path| { path.hops.iter().map(|hop| hop.0.channel_fees.proportional_millionths as u64).sum::<u64>() });
1115 let expensive_payment_path = cur_route.first_mut().unwrap();
1116 // We already dropped all the small channels above, meaning all the
1117 // remaining channels are larger than remaining overpaid_value_msat.
1118 // Thus, this can't be negative.
1119 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
1120 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
1124 drawn_routes.push(cur_route);
1128 // Select the best route by lowest total fee.
1129 drawn_routes.sort_by_key(|paths| paths.iter().map(|path| path.get_total_fee_paid_msat()).sum::<u64>());
1130 let mut selected_paths = Vec::<Vec<RouteHop>>::new();
1131 for payment_path in drawn_routes.first().unwrap() {
1132 selected_paths.push(payment_path.hops.iter().map(|(payment_hop, node_features)| {
1134 pubkey: payment_hop.pubkey,
1135 node_features: node_features.clone(),
1136 short_channel_id: payment_hop.short_channel_id,
1137 channel_features: payment_hop.channel_features.clone(),
1138 fee_msat: payment_hop.fee_msat,
1139 cltv_expiry_delta: payment_hop.cltv_expiry_delta,
1144 if let Some(features) = &payee_features {
1145 for path in selected_paths.iter_mut() {
1146 path.last_mut().unwrap().node_features = features.to_context();
1150 let route = Route { paths: selected_paths };
1151 log_trace!(logger, "Got route: {}", log_route!(route));
1157 use routing::router::{get_route, RouteHintHop, RoutingFees};
1158 use routing::network_graph::{NetworkGraph, NetGraphMsgHandler};
1159 use chain::transaction::OutPoint;
1160 use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
1161 use ln::msgs::{ErrorAction, LightningError, OptionalField, UnsignedChannelAnnouncement, ChannelAnnouncement, RoutingMessageHandler,
1162 NodeAnnouncement, UnsignedNodeAnnouncement, ChannelUpdate, UnsignedChannelUpdate};
1163 use ln::channelmanager;
1164 use util::test_utils;
1165 use util::ser::Writeable;
1167 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
1168 use bitcoin::hashes::Hash;
1169 use bitcoin::network::constants::Network;
1170 use bitcoin::blockdata::constants::genesis_block;
1171 use bitcoin::blockdata::script::Builder;
1172 use bitcoin::blockdata::opcodes;
1173 use bitcoin::blockdata::transaction::TxOut;
1177 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
1178 use bitcoin::secp256k1::{Secp256k1, All};
1183 // Using the same keys for LN and BTC ids
1184 fn add_channel(net_graph_msg_handler: &NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>, secp_ctx: &Secp256k1<All>, node_1_privkey: &SecretKey,
1185 node_2_privkey: &SecretKey, features: ChannelFeatures, short_channel_id: u64) {
1186 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1187 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1189 let unsigned_announcement = UnsignedChannelAnnouncement {
1191 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1195 bitcoin_key_1: node_id_1,
1196 bitcoin_key_2: node_id_2,
1197 excess_data: Vec::new(),
1200 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1201 let valid_announcement = ChannelAnnouncement {
1202 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1203 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1204 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1205 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1206 contents: unsigned_announcement.clone(),
1208 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1209 Ok(res) => assert!(res),
1214 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) {
1215 let msghash = hash_to_message!(&Sha256dHash::hash(&update.encode()[..])[..]);
1216 let valid_channel_update = ChannelUpdate {
1217 signature: secp_ctx.sign(&msghash, node_privkey),
1218 contents: update.clone()
1221 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1222 Ok(res) => assert!(res),
1227 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,
1228 features: NodeFeatures, timestamp: u32) {
1229 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
1230 let unsigned_announcement = UnsignedNodeAnnouncement {
1236 addresses: Vec::new(),
1237 excess_address_data: Vec::new(),
1238 excess_data: Vec::new(),
1240 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1241 let valid_announcement = NodeAnnouncement {
1242 signature: secp_ctx.sign(&msghash, node_privkey),
1243 contents: unsigned_announcement.clone()
1246 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1252 fn get_nodes(secp_ctx: &Secp256k1<All>) -> (SecretKey, PublicKey, Vec<SecretKey>, Vec<PublicKey>) {
1253 let privkeys: Vec<SecretKey> = (2..10).map(|i| {
1254 SecretKey::from_slice(&hex::decode(format!("{:02}", i).repeat(32)).unwrap()[..]).unwrap()
1257 let pubkeys = privkeys.iter().map(|secret| PublicKey::from_secret_key(&secp_ctx, secret)).collect();
1259 let our_privkey = SecretKey::from_slice(&hex::decode("01".repeat(32)).unwrap()[..]).unwrap();
1260 let our_id = PublicKey::from_secret_key(&secp_ctx, &our_privkey);
1262 (our_privkey, our_id, privkeys, pubkeys)
1265 fn id_to_feature_flags(id: u8) -> Vec<u8> {
1266 // Set the feature flags to the id'th odd (ie non-required) feature bit so that we can
1267 // test for it later.
1268 let idx = (id - 1) * 2 + 1;
1270 vec![1 << (idx - 8*3), 0, 0, 0]
1271 } else if idx > 8*2 {
1272 vec![1 << (idx - 8*2), 0, 0]
1273 } else if idx > 8*1 {
1274 vec![1 << (idx - 8*1), 0]
1280 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>) {
1281 let secp_ctx = Secp256k1::new();
1282 let logger = Arc::new(test_utils::TestLogger::new());
1283 let chain_monitor = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1284 let net_graph_msg_handler = NetGraphMsgHandler::new(genesis_block(Network::Testnet).header.block_hash(), None, Arc::clone(&logger));
1285 // Build network from our_id to node7:
1287 // -1(1)2- node0 -1(3)2-
1289 // our_id -1(12)2- node7 -1(13)2--- node2
1291 // -1(2)2- node1 -1(4)2-
1294 // chan1 1-to-2: disabled
1295 // chan1 2-to-1: enabled, 0 fee
1297 // chan2 1-to-2: enabled, ignored fee
1298 // chan2 2-to-1: enabled, 0 fee
1300 // chan3 1-to-2: enabled, 0 fee
1301 // chan3 2-to-1: enabled, 100 msat fee
1303 // chan4 1-to-2: enabled, 100% fee
1304 // chan4 2-to-1: enabled, 0 fee
1306 // chan12 1-to-2: enabled, ignored fee
1307 // chan12 2-to-1: enabled, 0 fee
1309 // chan13 1-to-2: enabled, 200% fee
1310 // chan13 2-to-1: enabled, 0 fee
1313 // -1(5)2- node3 -1(8)2--
1317 // node2--1(6)2- node4 -1(9)2--- node6 (not in global route map)
1319 // -1(7)2- node5 -1(10)2-
1321 // chan5 1-to-2: enabled, 100 msat fee
1322 // chan5 2-to-1: enabled, 0 fee
1324 // chan6 1-to-2: enabled, 0 fee
1325 // chan6 2-to-1: enabled, 0 fee
1327 // chan7 1-to-2: enabled, 100% fee
1328 // chan7 2-to-1: enabled, 0 fee
1330 // chan8 1-to-2: enabled, variable fee (0 then 1000 msat)
1331 // chan8 2-to-1: enabled, 0 fee
1333 // chan9 1-to-2: enabled, 1001 msat fee
1334 // chan9 2-to-1: enabled, 0 fee
1336 // chan10 1-to-2: enabled, 0 fee
1337 // chan10 2-to-1: enabled, 0 fee
1339 // chan11 1-to-2: enabled, 0 fee
1340 // chan11 2-to-1: enabled, 0 fee
1342 let (our_privkey, _, privkeys, _) = get_nodes(&secp_ctx);
1344 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[0], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
1345 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1346 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1347 short_channel_id: 1,
1350 cltv_expiry_delta: 0,
1351 htlc_minimum_msat: 0,
1352 htlc_maximum_msat: OptionalField::Absent,
1354 fee_proportional_millionths: 0,
1355 excess_data: Vec::new()
1358 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
1360 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
1361 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1362 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1363 short_channel_id: 2,
1366 cltv_expiry_delta: u16::max_value(),
1367 htlc_minimum_msat: 0,
1368 htlc_maximum_msat: OptionalField::Absent,
1369 fee_base_msat: u32::max_value(),
1370 fee_proportional_millionths: u32::max_value(),
1371 excess_data: Vec::new()
1373 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1374 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1375 short_channel_id: 2,
1378 cltv_expiry_delta: 0,
1379 htlc_minimum_msat: 0,
1380 htlc_maximum_msat: OptionalField::Absent,
1382 fee_proportional_millionths: 0,
1383 excess_data: Vec::new()
1386 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
1388 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[7], ChannelFeatures::from_le_bytes(id_to_feature_flags(12)), 12);
1389 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1390 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1391 short_channel_id: 12,
1394 cltv_expiry_delta: u16::max_value(),
1395 htlc_minimum_msat: 0,
1396 htlc_maximum_msat: OptionalField::Absent,
1397 fee_base_msat: u32::max_value(),
1398 fee_proportional_millionths: u32::max_value(),
1399 excess_data: Vec::new()
1401 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1402 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1403 short_channel_id: 12,
1406 cltv_expiry_delta: 0,
1407 htlc_minimum_msat: 0,
1408 htlc_maximum_msat: OptionalField::Absent,
1410 fee_proportional_millionths: 0,
1411 excess_data: Vec::new()
1414 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], NodeFeatures::from_le_bytes(id_to_feature_flags(8)), 0);
1416 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
1417 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1418 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1419 short_channel_id: 3,
1422 cltv_expiry_delta: (3 << 8) | 1,
1423 htlc_minimum_msat: 0,
1424 htlc_maximum_msat: OptionalField::Absent,
1426 fee_proportional_millionths: 0,
1427 excess_data: Vec::new()
1429 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1430 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1431 short_channel_id: 3,
1434 cltv_expiry_delta: (3 << 8) | 2,
1435 htlc_minimum_msat: 0,
1436 htlc_maximum_msat: OptionalField::Absent,
1438 fee_proportional_millionths: 0,
1439 excess_data: Vec::new()
1442 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
1443 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1444 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1445 short_channel_id: 4,
1448 cltv_expiry_delta: (4 << 8) | 1,
1449 htlc_minimum_msat: 0,
1450 htlc_maximum_msat: OptionalField::Absent,
1452 fee_proportional_millionths: 1000000,
1453 excess_data: Vec::new()
1455 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1456 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1457 short_channel_id: 4,
1460 cltv_expiry_delta: (4 << 8) | 2,
1461 htlc_minimum_msat: 0,
1462 htlc_maximum_msat: OptionalField::Absent,
1464 fee_proportional_millionths: 0,
1465 excess_data: Vec::new()
1468 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(13)), 13);
1469 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1470 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1471 short_channel_id: 13,
1474 cltv_expiry_delta: (13 << 8) | 1,
1475 htlc_minimum_msat: 0,
1476 htlc_maximum_msat: OptionalField::Absent,
1478 fee_proportional_millionths: 2000000,
1479 excess_data: Vec::new()
1481 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1482 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1483 short_channel_id: 13,
1486 cltv_expiry_delta: (13 << 8) | 2,
1487 htlc_minimum_msat: 0,
1488 htlc_maximum_msat: OptionalField::Absent,
1490 fee_proportional_millionths: 0,
1491 excess_data: Vec::new()
1494 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
1496 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
1497 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1498 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1499 short_channel_id: 6,
1502 cltv_expiry_delta: (6 << 8) | 1,
1503 htlc_minimum_msat: 0,
1504 htlc_maximum_msat: OptionalField::Absent,
1506 fee_proportional_millionths: 0,
1507 excess_data: Vec::new()
1509 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1510 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1511 short_channel_id: 6,
1514 cltv_expiry_delta: (6 << 8) | 2,
1515 htlc_minimum_msat: 0,
1516 htlc_maximum_msat: OptionalField::Absent,
1518 fee_proportional_millionths: 0,
1519 excess_data: Vec::new(),
1522 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(11)), 11);
1523 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1524 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1525 short_channel_id: 11,
1528 cltv_expiry_delta: (11 << 8) | 1,
1529 htlc_minimum_msat: 0,
1530 htlc_maximum_msat: OptionalField::Absent,
1532 fee_proportional_millionths: 0,
1533 excess_data: Vec::new()
1535 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
1536 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1537 short_channel_id: 11,
1540 cltv_expiry_delta: (11 << 8) | 2,
1541 htlc_minimum_msat: 0,
1542 htlc_maximum_msat: OptionalField::Absent,
1544 fee_proportional_millionths: 0,
1545 excess_data: Vec::new()
1548 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(5)), 0);
1550 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
1552 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[5], ChannelFeatures::from_le_bytes(id_to_feature_flags(7)), 7);
1553 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1554 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1555 short_channel_id: 7,
1558 cltv_expiry_delta: (7 << 8) | 1,
1559 htlc_minimum_msat: 0,
1560 htlc_maximum_msat: OptionalField::Absent,
1562 fee_proportional_millionths: 1000000,
1563 excess_data: Vec::new()
1565 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[5], UnsignedChannelUpdate {
1566 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1567 short_channel_id: 7,
1570 cltv_expiry_delta: (7 << 8) | 2,
1571 htlc_minimum_msat: 0,
1572 htlc_maximum_msat: OptionalField::Absent,
1574 fee_proportional_millionths: 0,
1575 excess_data: Vec::new()
1578 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[5], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
1580 (secp_ctx, net_graph_msg_handler, chain_monitor, logger)
1584 fn simple_route_test() {
1585 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1586 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1588 // Simple route to 2 via 1
1590 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)) {
1591 assert_eq!(err, "Cannot send a payment of 0 msat");
1592 } else { panic!(); }
1594 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();
1595 assert_eq!(route.paths[0].len(), 2);
1597 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
1598 assert_eq!(route.paths[0][0].short_channel_id, 2);
1599 assert_eq!(route.paths[0][0].fee_msat, 100);
1600 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
1601 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
1602 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
1604 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1605 assert_eq!(route.paths[0][1].short_channel_id, 4);
1606 assert_eq!(route.paths[0][1].fee_msat, 100);
1607 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1608 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1609 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
1613 fn invalid_first_hop_test() {
1614 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1615 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1617 // Simple route to 2 via 1
1619 let our_chans = vec![channelmanager::ChannelDetails {
1620 channel_id: [0; 32],
1621 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
1622 short_channel_id: Some(2),
1623 remote_network_id: our_id,
1624 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1625 channel_value_satoshis: 100000,
1627 outbound_capacity_msat: 100000,
1628 inbound_capacity_msat: 100000,
1629 is_outbound: true, is_funding_locked: true,
1630 is_usable: true, is_public: true,
1631 counterparty_forwarding_info: None,
1634 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)) {
1635 assert_eq!(err, "First hop cannot have our_node_id as a destination.");
1636 } else { panic!(); }
1638 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();
1639 assert_eq!(route.paths[0].len(), 2);
1643 fn htlc_minimum_test() {
1644 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1645 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1647 // Simple route to 2 via 1
1649 // Disable other paths
1650 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1651 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1652 short_channel_id: 12,
1654 flags: 2, // to disable
1655 cltv_expiry_delta: 0,
1656 htlc_minimum_msat: 0,
1657 htlc_maximum_msat: OptionalField::Absent,
1659 fee_proportional_millionths: 0,
1660 excess_data: Vec::new()
1662 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1663 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1664 short_channel_id: 3,
1666 flags: 2, // to disable
1667 cltv_expiry_delta: 0,
1668 htlc_minimum_msat: 0,
1669 htlc_maximum_msat: OptionalField::Absent,
1671 fee_proportional_millionths: 0,
1672 excess_data: Vec::new()
1674 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1675 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1676 short_channel_id: 13,
1678 flags: 2, // to disable
1679 cltv_expiry_delta: 0,
1680 htlc_minimum_msat: 0,
1681 htlc_maximum_msat: OptionalField::Absent,
1683 fee_proportional_millionths: 0,
1684 excess_data: Vec::new()
1686 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1687 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1688 short_channel_id: 6,
1690 flags: 2, // to disable
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()
1698 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1699 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1700 short_channel_id: 7,
1702 flags: 2, // to disable
1703 cltv_expiry_delta: 0,
1704 htlc_minimum_msat: 0,
1705 htlc_maximum_msat: OptionalField::Absent,
1707 fee_proportional_millionths: 0,
1708 excess_data: Vec::new()
1711 // Check against amount_to_transfer_over_msat.
1712 // Set minimal HTLC of 200_000_000 msat.
1713 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1714 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1715 short_channel_id: 2,
1718 cltv_expiry_delta: 0,
1719 htlc_minimum_msat: 200_000_000,
1720 htlc_maximum_msat: OptionalField::Absent,
1722 fee_proportional_millionths: 0,
1723 excess_data: Vec::new()
1726 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
1728 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1729 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1730 short_channel_id: 4,
1733 cltv_expiry_delta: 0,
1734 htlc_minimum_msat: 0,
1735 htlc_maximum_msat: OptionalField::Present(199_999_999),
1737 fee_proportional_millionths: 0,
1738 excess_data: Vec::new()
1741 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
1742 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)) {
1743 assert_eq!(err, "Failed to find a path to the given destination");
1744 } else { panic!(); }
1746 // Lift the restriction on the first hop.
1747 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1748 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1749 short_channel_id: 2,
1752 cltv_expiry_delta: 0,
1753 htlc_minimum_msat: 0,
1754 htlc_maximum_msat: OptionalField::Absent,
1756 fee_proportional_millionths: 0,
1757 excess_data: Vec::new()
1760 // A payment above the minimum should pass
1761 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();
1762 assert_eq!(route.paths[0].len(), 2);
1766 fn htlc_minimum_overpay_test() {
1767 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1768 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1770 // A route to node#2 via two paths.
1771 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
1772 // Thus, they can't send 60 without overpaying.
1773 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1774 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1775 short_channel_id: 2,
1778 cltv_expiry_delta: 0,
1779 htlc_minimum_msat: 35_000,
1780 htlc_maximum_msat: OptionalField::Present(40_000),
1782 fee_proportional_millionths: 0,
1783 excess_data: Vec::new()
1785 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1786 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1787 short_channel_id: 12,
1790 cltv_expiry_delta: 0,
1791 htlc_minimum_msat: 35_000,
1792 htlc_maximum_msat: OptionalField::Present(40_000),
1794 fee_proportional_millionths: 0,
1795 excess_data: Vec::new()
1799 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1800 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1801 short_channel_id: 13,
1804 cltv_expiry_delta: 0,
1805 htlc_minimum_msat: 0,
1806 htlc_maximum_msat: OptionalField::Absent,
1808 fee_proportional_millionths: 0,
1809 excess_data: Vec::new()
1811 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1812 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1813 short_channel_id: 4,
1816 cltv_expiry_delta: 0,
1817 htlc_minimum_msat: 0,
1818 htlc_maximum_msat: OptionalField::Absent,
1820 fee_proportional_millionths: 0,
1821 excess_data: Vec::new()
1824 // Disable other paths
1825 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1826 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1827 short_channel_id: 1,
1829 flags: 2, // to disable
1830 cltv_expiry_delta: 0,
1831 htlc_minimum_msat: 0,
1832 htlc_maximum_msat: OptionalField::Absent,
1834 fee_proportional_millionths: 0,
1835 excess_data: Vec::new()
1838 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
1839 Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger)).unwrap();
1840 // Overpay fees to hit htlc_minimum_msat.
1841 let overpaid_fees = route.paths[0][0].fee_msat + route.paths[1][0].fee_msat;
1842 // TODO: this could be better balanced to overpay 10k and not 15k.
1843 assert_eq!(overpaid_fees, 15_000);
1845 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
1846 // while taking even more fee to match htlc_minimum_msat.
1847 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1848 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1849 short_channel_id: 12,
1852 cltv_expiry_delta: 0,
1853 htlc_minimum_msat: 65_000,
1854 htlc_maximum_msat: OptionalField::Present(80_000),
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: 2,
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()
1871 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1872 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1873 short_channel_id: 4,
1876 cltv_expiry_delta: 0,
1877 htlc_minimum_msat: 0,
1878 htlc_maximum_msat: OptionalField::Absent,
1880 fee_proportional_millionths: 100_000,
1881 excess_data: Vec::new()
1884 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
1885 Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger)).unwrap();
1886 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
1887 assert_eq!(route.paths.len(), 1);
1888 assert_eq!(route.paths[0][0].short_channel_id, 12);
1889 let fees = route.paths[0][0].fee_msat;
1890 assert_eq!(fees, 5_000);
1892 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
1893 Some(InvoiceFeatures::known()), None, &Vec::new(), 50_000, 42, Arc::clone(&logger)).unwrap();
1894 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
1895 // the other channel.
1896 assert_eq!(route.paths.len(), 1);
1897 assert_eq!(route.paths[0][0].short_channel_id, 2);
1898 let fees = route.paths[0][0].fee_msat;
1899 assert_eq!(fees, 5_000);
1903 fn disable_channels_test() {
1904 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1905 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1907 // // Disable channels 4 and 12 by flags=2
1908 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1909 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1910 short_channel_id: 4,
1912 flags: 2, // to disable
1913 cltv_expiry_delta: 0,
1914 htlc_minimum_msat: 0,
1915 htlc_maximum_msat: OptionalField::Absent,
1917 fee_proportional_millionths: 0,
1918 excess_data: Vec::new()
1920 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1921 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1922 short_channel_id: 12,
1924 flags: 2, // to disable
1925 cltv_expiry_delta: 0,
1926 htlc_minimum_msat: 0,
1927 htlc_maximum_msat: OptionalField::Absent,
1929 fee_proportional_millionths: 0,
1930 excess_data: Vec::new()
1933 // If all the channels require some features we don't understand, route should fail
1934 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)) {
1935 assert_eq!(err, "Failed to find a path to the given destination");
1936 } else { panic!(); }
1938 // If we specify a channel to node7, that overrides our local channel view and that gets used
1939 let our_chans = vec![channelmanager::ChannelDetails {
1940 channel_id: [0; 32],
1941 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
1942 short_channel_id: Some(42),
1943 remote_network_id: nodes[7].clone(),
1944 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1945 channel_value_satoshis: 0,
1947 outbound_capacity_msat: 250_000_000,
1948 inbound_capacity_msat: 0,
1949 is_outbound: true, is_funding_locked: true,
1950 is_usable: true, is_public: true,
1951 counterparty_forwarding_info: None,
1953 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();
1954 assert_eq!(route.paths[0].len(), 2);
1956 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
1957 assert_eq!(route.paths[0][0].short_channel_id, 42);
1958 assert_eq!(route.paths[0][0].fee_msat, 200);
1959 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
1960 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
1961 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
1963 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1964 assert_eq!(route.paths[0][1].short_channel_id, 13);
1965 assert_eq!(route.paths[0][1].fee_msat, 100);
1966 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1967 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1968 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
1972 fn disable_node_test() {
1973 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1974 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1976 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
1977 let mut unknown_features = NodeFeatures::known();
1978 unknown_features.set_required_unknown_bits();
1979 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
1980 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
1981 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
1983 // If all nodes require some features we don't understand, route should fail
1984 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)) {
1985 assert_eq!(err, "Failed to find a path to the given destination");
1986 } else { panic!(); }
1988 // If we specify a channel to node7, that overrides our local channel view and that gets used
1989 let our_chans = vec![channelmanager::ChannelDetails {
1990 channel_id: [0; 32],
1991 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
1992 short_channel_id: Some(42),
1993 remote_network_id: nodes[7].clone(),
1994 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1995 channel_value_satoshis: 0,
1997 outbound_capacity_msat: 250_000_000,
1998 inbound_capacity_msat: 0,
1999 is_outbound: true, is_funding_locked: true,
2000 is_usable: true, is_public: true,
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]); // it should also override our view of their features
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));
2020 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
2021 // naively) assume that the user checked the feature bits on the invoice, which override
2022 // the node_announcement.
2026 fn our_chans_test() {
2027 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2028 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2030 // Route to 1 via 2 and 3 because our channel to 1 is disabled
2031 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();
2032 assert_eq!(route.paths[0].len(), 3);
2034 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2035 assert_eq!(route.paths[0][0].short_channel_id, 2);
2036 assert_eq!(route.paths[0][0].fee_msat, 200);
2037 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2038 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2039 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2041 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2042 assert_eq!(route.paths[0][1].short_channel_id, 4);
2043 assert_eq!(route.paths[0][1].fee_msat, 100);
2044 assert_eq!(route.paths[0][1].cltv_expiry_delta, (3 << 8) | 2);
2045 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2046 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2048 assert_eq!(route.paths[0][2].pubkey, nodes[0]);
2049 assert_eq!(route.paths[0][2].short_channel_id, 3);
2050 assert_eq!(route.paths[0][2].fee_msat, 100);
2051 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
2052 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(1));
2053 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(3));
2055 // If we specify a channel to node7, that overrides our local channel view and that gets used
2056 let our_chans = vec![channelmanager::ChannelDetails {
2057 channel_id: [0; 32],
2058 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
2059 short_channel_id: Some(42),
2060 remote_network_id: nodes[7].clone(),
2061 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
2062 channel_value_satoshis: 0,
2064 outbound_capacity_msat: 250_000_000,
2065 inbound_capacity_msat: 0,
2066 is_outbound: true, is_funding_locked: true,
2067 is_usable: true, is_public: true,
2068 counterparty_forwarding_info: None,
2070 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();
2071 assert_eq!(route.paths[0].len(), 2);
2073 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2074 assert_eq!(route.paths[0][0].short_channel_id, 42);
2075 assert_eq!(route.paths[0][0].fee_msat, 200);
2076 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
2077 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2078 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2080 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2081 assert_eq!(route.paths[0][1].short_channel_id, 13);
2082 assert_eq!(route.paths[0][1].fee_msat, 100);
2083 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2084 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2085 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2088 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHintHop> {
2089 let zero_fees = RoutingFees {
2091 proportional_millionths: 0,
2094 src_node_id: nodes[3].clone(),
2095 short_channel_id: 8,
2097 cltv_expiry_delta: (8 << 8) | 1,
2098 htlc_minimum_msat: None,
2099 htlc_maximum_msat: None,
2101 src_node_id: nodes[4].clone(),
2102 short_channel_id: 9,
2105 proportional_millionths: 0,
2107 cltv_expiry_delta: (9 << 8) | 1,
2108 htlc_minimum_msat: None,
2109 htlc_maximum_msat: None,
2111 src_node_id: nodes[5].clone(),
2112 short_channel_id: 10,
2114 cltv_expiry_delta: (10 << 8) | 1,
2115 htlc_minimum_msat: None,
2116 htlc_maximum_msat: None,
2121 fn last_hops_test() {
2122 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2123 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2125 // Simple test across 2, 3, 5, and 4 via a last_hop channel
2127 // First check that lst hop can't have its source as the payee.
2128 let invalid_last_hop = RouteHintHop {
2129 src_node_id: nodes[6],
2130 short_channel_id: 8,
2133 proportional_millionths: 0,
2135 cltv_expiry_delta: (8 << 8) | 1,
2136 htlc_minimum_msat: None,
2137 htlc_maximum_msat: None,
2140 let mut invalid_last_hops = last_hops(&nodes);
2141 invalid_last_hops.push(invalid_last_hop);
2143 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)) {
2144 assert_eq!(err, "Last hop cannot have a payee as a source.");
2145 } else { panic!(); }
2148 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();
2149 assert_eq!(route.paths[0].len(), 5);
2151 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2152 assert_eq!(route.paths[0][0].short_channel_id, 2);
2153 assert_eq!(route.paths[0][0].fee_msat, 100);
2154 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2155 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2156 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2158 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2159 assert_eq!(route.paths[0][1].short_channel_id, 4);
2160 assert_eq!(route.paths[0][1].fee_msat, 0);
2161 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2162 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2163 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2165 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2166 assert_eq!(route.paths[0][2].short_channel_id, 6);
2167 assert_eq!(route.paths[0][2].fee_msat, 0);
2168 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2169 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2170 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2172 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2173 assert_eq!(route.paths[0][3].short_channel_id, 11);
2174 assert_eq!(route.paths[0][3].fee_msat, 0);
2175 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2176 // If we have a peer in the node map, we'll use their features here since we don't have
2177 // a way of figuring out their features from the invoice:
2178 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2179 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2181 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2182 assert_eq!(route.paths[0][4].short_channel_id, 8);
2183 assert_eq!(route.paths[0][4].fee_msat, 100);
2184 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2185 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2186 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2190 fn our_chans_last_hop_connect_test() {
2191 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2192 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2194 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
2195 let our_chans = vec![channelmanager::ChannelDetails {
2196 channel_id: [0; 32],
2197 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
2198 short_channel_id: Some(42),
2199 remote_network_id: nodes[3].clone(),
2200 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
2201 channel_value_satoshis: 0,
2203 outbound_capacity_msat: 250_000_000,
2204 inbound_capacity_msat: 0,
2205 is_outbound: true, is_funding_locked: true,
2206 is_usable: true, is_public: true,
2207 counterparty_forwarding_info: None,
2209 let mut last_hops = last_hops(&nodes);
2210 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();
2211 assert_eq!(route.paths[0].len(), 2);
2213 assert_eq!(route.paths[0][0].pubkey, nodes[3]);
2214 assert_eq!(route.paths[0][0].short_channel_id, 42);
2215 assert_eq!(route.paths[0][0].fee_msat, 0);
2216 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
2217 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2218 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2220 assert_eq!(route.paths[0][1].pubkey, nodes[6]);
2221 assert_eq!(route.paths[0][1].short_channel_id, 8);
2222 assert_eq!(route.paths[0][1].fee_msat, 100);
2223 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2224 assert_eq!(route.paths[0][1].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2225 assert_eq!(route.paths[0][1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2227 last_hops[0].fees.base_msat = 1000;
2229 // Revert to via 6 as the fee on 8 goes up
2230 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();
2231 assert_eq!(route.paths[0].len(), 4);
2233 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2234 assert_eq!(route.paths[0][0].short_channel_id, 2);
2235 assert_eq!(route.paths[0][0].fee_msat, 200); // fee increased as its % of value transferred across node
2236 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2237 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2238 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2240 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2241 assert_eq!(route.paths[0][1].short_channel_id, 4);
2242 assert_eq!(route.paths[0][1].fee_msat, 100);
2243 assert_eq!(route.paths[0][1].cltv_expiry_delta, (7 << 8) | 1);
2244 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2245 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2247 assert_eq!(route.paths[0][2].pubkey, nodes[5]);
2248 assert_eq!(route.paths[0][2].short_channel_id, 7);
2249 assert_eq!(route.paths[0][2].fee_msat, 0);
2250 assert_eq!(route.paths[0][2].cltv_expiry_delta, (10 << 8) | 1);
2251 // If we have a peer in the node map, we'll use their features here since we don't have
2252 // a way of figuring out their features from the invoice:
2253 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
2254 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(7));
2256 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2257 assert_eq!(route.paths[0][3].short_channel_id, 10);
2258 assert_eq!(route.paths[0][3].fee_msat, 100);
2259 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2260 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2261 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2263 // ...but still use 8 for larger payments as 6 has a variable feerate
2264 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();
2265 assert_eq!(route.paths[0].len(), 5);
2267 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2268 assert_eq!(route.paths[0][0].short_channel_id, 2);
2269 assert_eq!(route.paths[0][0].fee_msat, 3000);
2270 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2271 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2272 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2274 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2275 assert_eq!(route.paths[0][1].short_channel_id, 4);
2276 assert_eq!(route.paths[0][1].fee_msat, 0);
2277 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2278 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2279 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2281 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2282 assert_eq!(route.paths[0][2].short_channel_id, 6);
2283 assert_eq!(route.paths[0][2].fee_msat, 0);
2284 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2285 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2286 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2288 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2289 assert_eq!(route.paths[0][3].short_channel_id, 11);
2290 assert_eq!(route.paths[0][3].fee_msat, 1000);
2291 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2292 // If we have a peer in the node map, we'll use their features here since we don't have
2293 // a way of figuring out their features from the invoice:
2294 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2295 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2297 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2298 assert_eq!(route.paths[0][4].short_channel_id, 8);
2299 assert_eq!(route.paths[0][4].fee_msat, 2000);
2300 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2301 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2302 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2306 fn unannounced_path_test() {
2307 // We should be able to send a payment to a destination without any help of a routing graph
2308 // if we have a channel with a common counterparty that appears in the first and last hop
2310 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
2311 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
2312 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
2314 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
2315 let last_hops = vec![RouteHintHop {
2316 src_node_id: middle_node_id,
2317 short_channel_id: 8,
2320 proportional_millionths: 0,
2322 cltv_expiry_delta: (8 << 8) | 1,
2323 htlc_minimum_msat: None,
2324 htlc_maximum_msat: None,
2326 let our_chans = vec![channelmanager::ChannelDetails {
2327 channel_id: [0; 32],
2328 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
2329 short_channel_id: Some(42),
2330 remote_network_id: middle_node_id,
2331 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
2332 channel_value_satoshis: 100000,
2334 outbound_capacity_msat: 100000,
2335 inbound_capacity_msat: 100000,
2336 is_outbound: true, is_funding_locked: true,
2337 is_usable: true, is_public: true,
2338 counterparty_forwarding_info: None,
2340 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();
2342 assert_eq!(route.paths[0].len(), 2);
2344 assert_eq!(route.paths[0][0].pubkey, middle_node_id);
2345 assert_eq!(route.paths[0][0].short_channel_id, 42);
2346 assert_eq!(route.paths[0][0].fee_msat, 1000);
2347 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
2348 assert_eq!(route.paths[0][0].node_features.le_flags(), &[0b11]);
2349 assert_eq!(route.paths[0][0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
2351 assert_eq!(route.paths[0][1].pubkey, target_node_id);
2352 assert_eq!(route.paths[0][1].short_channel_id, 8);
2353 assert_eq!(route.paths[0][1].fee_msat, 100);
2354 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2355 assert_eq!(route.paths[0][1].node_features.le_flags(), &[0; 0]); // We dont pass flags in from invoices yet
2356 assert_eq!(route.paths[0][1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
2360 fn available_amount_while_routing_test() {
2361 // Tests whether we choose the correct available channel amount while routing.
2363 let (secp_ctx, mut net_graph_msg_handler, chain_monitor, logger) = build_graph();
2364 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2366 // We will use a simple single-path route from
2367 // our node to node2 via node0: channels {1, 3}.
2369 // First disable all other paths.
2370 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2371 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2372 short_channel_id: 2,
2375 cltv_expiry_delta: 0,
2376 htlc_minimum_msat: 0,
2377 htlc_maximum_msat: OptionalField::Present(100_000),
2379 fee_proportional_millionths: 0,
2380 excess_data: Vec::new()
2382 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2383 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2384 short_channel_id: 12,
2387 cltv_expiry_delta: 0,
2388 htlc_minimum_msat: 0,
2389 htlc_maximum_msat: OptionalField::Present(100_000),
2391 fee_proportional_millionths: 0,
2392 excess_data: Vec::new()
2395 // Make the first channel (#1) very permissive,
2396 // and we will be testing all limits on the second channel.
2397 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2398 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2399 short_channel_id: 1,
2402 cltv_expiry_delta: 0,
2403 htlc_minimum_msat: 0,
2404 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2406 fee_proportional_millionths: 0,
2407 excess_data: Vec::new()
2410 // First, let's see if routing works if we have absolutely no idea about the available amount.
2411 // In this case, it should be set to 250_000 sats.
2412 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2413 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2414 short_channel_id: 3,
2417 cltv_expiry_delta: 0,
2418 htlc_minimum_msat: 0,
2419 htlc_maximum_msat: OptionalField::Absent,
2421 fee_proportional_millionths: 0,
2422 excess_data: Vec::new()
2426 // Attempt to route more than available results in a failure.
2427 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2428 Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000_001, 42, Arc::clone(&logger)) {
2429 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2430 } else { panic!(); }
2434 // Now, attempt to route an exact amount we have should be fine.
2435 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2436 Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000_000, 42, Arc::clone(&logger)).unwrap();
2437 assert_eq!(route.paths.len(), 1);
2438 let path = route.paths.last().unwrap();
2439 assert_eq!(path.len(), 2);
2440 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2441 assert_eq!(path.last().unwrap().fee_msat, 250_000_000);
2444 // Check that setting outbound_capacity_msat in first_hops limits the channels.
2445 // Disable channel #1 and use another first hop.
2446 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2447 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2448 short_channel_id: 1,
2451 cltv_expiry_delta: 0,
2452 htlc_minimum_msat: 0,
2453 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2455 fee_proportional_millionths: 0,
2456 excess_data: Vec::new()
2459 // Now, limit the first_hop by the outbound_capacity_msat of 200_000 sats.
2460 let our_chans = vec![channelmanager::ChannelDetails {
2461 channel_id: [0; 32],
2462 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
2463 short_channel_id: Some(42),
2464 remote_network_id: nodes[0].clone(),
2465 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
2466 channel_value_satoshis: 0,
2468 outbound_capacity_msat: 200_000_000,
2469 inbound_capacity_msat: 0,
2470 is_outbound: true, is_funding_locked: true,
2471 is_usable: true, is_public: true,
2472 counterparty_forwarding_info: None,
2476 // Attempt to route more than available results in a failure.
2477 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2478 Some(InvoiceFeatures::known()), Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 200_000_001, 42, Arc::clone(&logger)) {
2479 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2480 } else { panic!(); }
2484 // Now, attempt to route an exact amount we have should be fine.
2485 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2486 Some(InvoiceFeatures::known()), Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 200_000_000, 42, Arc::clone(&logger)).unwrap();
2487 assert_eq!(route.paths.len(), 1);
2488 let path = route.paths.last().unwrap();
2489 assert_eq!(path.len(), 2);
2490 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2491 assert_eq!(path.last().unwrap().fee_msat, 200_000_000);
2494 // Enable channel #1 back.
2495 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2496 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2497 short_channel_id: 1,
2500 cltv_expiry_delta: 0,
2501 htlc_minimum_msat: 0,
2502 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2504 fee_proportional_millionths: 0,
2505 excess_data: Vec::new()
2509 // Now let's see if routing works if we know only htlc_maximum_msat.
2510 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2511 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2512 short_channel_id: 3,
2515 cltv_expiry_delta: 0,
2516 htlc_minimum_msat: 0,
2517 htlc_maximum_msat: OptionalField::Present(15_000),
2519 fee_proportional_millionths: 0,
2520 excess_data: Vec::new()
2524 // Attempt to route more than available results in a failure.
2525 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2526 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_001, 42, Arc::clone(&logger)) {
2527 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2528 } else { panic!(); }
2532 // Now, attempt to route an exact amount we have should be fine.
2533 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2534 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_000, 42, Arc::clone(&logger)).unwrap();
2535 assert_eq!(route.paths.len(), 1);
2536 let path = route.paths.last().unwrap();
2537 assert_eq!(path.len(), 2);
2538 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2539 assert_eq!(path.last().unwrap().fee_msat, 15_000);
2542 // Now let's see if routing works if we know only capacity from the UTXO.
2544 // We can't change UTXO capacity on the fly, so we'll disable
2545 // the existing channel and add another one with the capacity we need.
2546 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2547 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2548 short_channel_id: 3,
2551 cltv_expiry_delta: 0,
2552 htlc_minimum_msat: 0,
2553 htlc_maximum_msat: OptionalField::Absent,
2555 fee_proportional_millionths: 0,
2556 excess_data: Vec::new()
2559 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
2560 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
2561 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
2562 .push_opcode(opcodes::all::OP_PUSHNUM_2)
2563 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
2565 *chain_monitor.utxo_ret.lock().unwrap() = Ok(TxOut { value: 15, script_pubkey: good_script.clone() });
2566 net_graph_msg_handler.add_chain_access(Some(chain_monitor));
2568 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
2569 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2570 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2571 short_channel_id: 333,
2574 cltv_expiry_delta: (3 << 8) | 1,
2575 htlc_minimum_msat: 0,
2576 htlc_maximum_msat: OptionalField::Absent,
2578 fee_proportional_millionths: 0,
2579 excess_data: Vec::new()
2581 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2582 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2583 short_channel_id: 333,
2586 cltv_expiry_delta: (3 << 8) | 2,
2587 htlc_minimum_msat: 0,
2588 htlc_maximum_msat: OptionalField::Absent,
2590 fee_proportional_millionths: 0,
2591 excess_data: Vec::new()
2595 // Attempt to route more than available results in a failure.
2596 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2597 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_001, 42, Arc::clone(&logger)) {
2598 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2599 } else { panic!(); }
2603 // Now, attempt to route an exact amount we have should be fine.
2604 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2605 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_000, 42, Arc::clone(&logger)).unwrap();
2606 assert_eq!(route.paths.len(), 1);
2607 let path = route.paths.last().unwrap();
2608 assert_eq!(path.len(), 2);
2609 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2610 assert_eq!(path.last().unwrap().fee_msat, 15_000);
2613 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
2614 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2615 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2616 short_channel_id: 333,
2619 cltv_expiry_delta: 0,
2620 htlc_minimum_msat: 0,
2621 htlc_maximum_msat: OptionalField::Present(10_000),
2623 fee_proportional_millionths: 0,
2624 excess_data: Vec::new()
2628 // Attempt to route more than available results in a failure.
2629 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2630 Some(InvoiceFeatures::known()), None, &Vec::new(), 10_001, 42, Arc::clone(&logger)) {
2631 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2632 } else { panic!(); }
2636 // Now, attempt to route an exact amount we have should be fine.
2637 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2638 Some(InvoiceFeatures::known()), None, &Vec::new(), 10_000, 42, Arc::clone(&logger)).unwrap();
2639 assert_eq!(route.paths.len(), 1);
2640 let path = route.paths.last().unwrap();
2641 assert_eq!(path.len(), 2);
2642 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2643 assert_eq!(path.last().unwrap().fee_msat, 10_000);
2648 fn available_liquidity_last_hop_test() {
2649 // Check that available liquidity properly limits the path even when only
2650 // one of the latter hops is limited.
2651 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2652 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2654 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
2655 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
2656 // Total capacity: 50 sats.
2658 // Disable other potential paths.
2659 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2660 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2661 short_channel_id: 2,
2664 cltv_expiry_delta: 0,
2665 htlc_minimum_msat: 0,
2666 htlc_maximum_msat: OptionalField::Present(100_000),
2668 fee_proportional_millionths: 0,
2669 excess_data: Vec::new()
2671 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2672 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2673 short_channel_id: 7,
2676 cltv_expiry_delta: 0,
2677 htlc_minimum_msat: 0,
2678 htlc_maximum_msat: OptionalField::Present(100_000),
2680 fee_proportional_millionths: 0,
2681 excess_data: Vec::new()
2686 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2687 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2688 short_channel_id: 12,
2691 cltv_expiry_delta: 0,
2692 htlc_minimum_msat: 0,
2693 htlc_maximum_msat: OptionalField::Present(100_000),
2695 fee_proportional_millionths: 0,
2696 excess_data: Vec::new()
2698 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2699 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2700 short_channel_id: 13,
2703 cltv_expiry_delta: 0,
2704 htlc_minimum_msat: 0,
2705 htlc_maximum_msat: OptionalField::Present(100_000),
2707 fee_proportional_millionths: 0,
2708 excess_data: Vec::new()
2711 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2712 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2713 short_channel_id: 6,
2716 cltv_expiry_delta: 0,
2717 htlc_minimum_msat: 0,
2718 htlc_maximum_msat: OptionalField::Present(50_000),
2720 fee_proportional_millionths: 0,
2721 excess_data: Vec::new()
2723 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
2724 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2725 short_channel_id: 11,
2728 cltv_expiry_delta: 0,
2729 htlc_minimum_msat: 0,
2730 htlc_maximum_msat: OptionalField::Present(100_000),
2732 fee_proportional_millionths: 0,
2733 excess_data: Vec::new()
2736 // Attempt to route more than available results in a failure.
2737 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
2738 Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger)) {
2739 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2740 } else { panic!(); }
2744 // Now, attempt to route 49 sats (just a bit below the capacity).
2745 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
2746 Some(InvoiceFeatures::known()), None, &Vec::new(), 49_000, 42, Arc::clone(&logger)).unwrap();
2747 assert_eq!(route.paths.len(), 1);
2748 let mut total_amount_paid_msat = 0;
2749 for path in &route.paths {
2750 assert_eq!(path.len(), 4);
2751 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
2752 total_amount_paid_msat += path.last().unwrap().fee_msat;
2754 assert_eq!(total_amount_paid_msat, 49_000);
2758 // Attempt to route an exact amount is also fine
2759 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
2760 Some(InvoiceFeatures::known()), None, &Vec::new(), 50_000, 42, Arc::clone(&logger)).unwrap();
2761 assert_eq!(route.paths.len(), 1);
2762 let mut total_amount_paid_msat = 0;
2763 for path in &route.paths {
2764 assert_eq!(path.len(), 4);
2765 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
2766 total_amount_paid_msat += path.last().unwrap().fee_msat;
2768 assert_eq!(total_amount_paid_msat, 50_000);
2773 fn ignore_fee_first_hop_test() {
2774 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2775 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2777 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
2778 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2779 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2780 short_channel_id: 1,
2783 cltv_expiry_delta: 0,
2784 htlc_minimum_msat: 0,
2785 htlc_maximum_msat: OptionalField::Present(100_000),
2786 fee_base_msat: 1_000_000,
2787 fee_proportional_millionths: 0,
2788 excess_data: Vec::new()
2790 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2791 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2792 short_channel_id: 3,
2795 cltv_expiry_delta: 0,
2796 htlc_minimum_msat: 0,
2797 htlc_maximum_msat: OptionalField::Present(50_000),
2799 fee_proportional_millionths: 0,
2800 excess_data: Vec::new()
2804 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();
2805 assert_eq!(route.paths.len(), 1);
2806 let mut total_amount_paid_msat = 0;
2807 for path in &route.paths {
2808 assert_eq!(path.len(), 2);
2809 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2810 total_amount_paid_msat += path.last().unwrap().fee_msat;
2812 assert_eq!(total_amount_paid_msat, 50_000);
2817 fn simple_mpp_route_test() {
2818 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2819 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2821 // We need a route consisting of 3 paths:
2822 // From our node to node2 via node0, node7, node1 (three paths one hop each).
2823 // To achieve this, the amount being transferred should be around
2824 // the total capacity of these 3 paths.
2826 // First, we set limits on these (previously unlimited) channels.
2827 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
2829 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
2830 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2831 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2832 short_channel_id: 1,
2835 cltv_expiry_delta: 0,
2836 htlc_minimum_msat: 0,
2837 htlc_maximum_msat: OptionalField::Present(100_000),
2839 fee_proportional_millionths: 0,
2840 excess_data: Vec::new()
2842 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2843 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2844 short_channel_id: 3,
2847 cltv_expiry_delta: 0,
2848 htlc_minimum_msat: 0,
2849 htlc_maximum_msat: OptionalField::Present(50_000),
2851 fee_proportional_millionths: 0,
2852 excess_data: Vec::new()
2855 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
2856 // (total limit 60).
2857 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2858 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2859 short_channel_id: 12,
2862 cltv_expiry_delta: 0,
2863 htlc_minimum_msat: 0,
2864 htlc_maximum_msat: OptionalField::Present(60_000),
2866 fee_proportional_millionths: 0,
2867 excess_data: Vec::new()
2869 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2870 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2871 short_channel_id: 13,
2874 cltv_expiry_delta: 0,
2875 htlc_minimum_msat: 0,
2876 htlc_maximum_msat: OptionalField::Present(60_000),
2878 fee_proportional_millionths: 0,
2879 excess_data: Vec::new()
2882 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
2883 // (total capacity 180 sats).
2884 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2885 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2886 short_channel_id: 2,
2889 cltv_expiry_delta: 0,
2890 htlc_minimum_msat: 0,
2891 htlc_maximum_msat: OptionalField::Present(200_000),
2893 fee_proportional_millionths: 0,
2894 excess_data: Vec::new()
2896 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2897 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2898 short_channel_id: 4,
2901 cltv_expiry_delta: 0,
2902 htlc_minimum_msat: 0,
2903 htlc_maximum_msat: OptionalField::Present(180_000),
2905 fee_proportional_millionths: 0,
2906 excess_data: Vec::new()
2910 // Attempt to route more than available results in a failure.
2911 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(),
2912 &nodes[2], Some(InvoiceFeatures::known()), None, &Vec::new(), 300_000, 42, Arc::clone(&logger)) {
2913 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2914 } else { panic!(); }
2918 // Now, attempt to route 250 sats (just a bit below the capacity).
2919 // Our algorithm should provide us with these 3 paths.
2920 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2921 Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000, 42, Arc::clone(&logger)).unwrap();
2922 assert_eq!(route.paths.len(), 3);
2923 let mut total_amount_paid_msat = 0;
2924 for path in &route.paths {
2925 assert_eq!(path.len(), 2);
2926 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2927 total_amount_paid_msat += path.last().unwrap().fee_msat;
2929 assert_eq!(total_amount_paid_msat, 250_000);
2933 // Attempt to route an exact amount is also fine
2934 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2935 Some(InvoiceFeatures::known()), None, &Vec::new(), 290_000, 42, Arc::clone(&logger)).unwrap();
2936 assert_eq!(route.paths.len(), 3);
2937 let mut total_amount_paid_msat = 0;
2938 for path in &route.paths {
2939 assert_eq!(path.len(), 2);
2940 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2941 total_amount_paid_msat += path.last().unwrap().fee_msat;
2943 assert_eq!(total_amount_paid_msat, 290_000);
2948 fn long_mpp_route_test() {
2949 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2950 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2952 // We need a route consisting of 3 paths:
2953 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
2954 // Note that these paths overlap (channels 5, 12, 13).
2955 // We will route 300 sats.
2956 // Each path will have 100 sats capacity, those channels which
2957 // are used twice will have 200 sats capacity.
2959 // Disable other potential paths.
2960 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2961 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2962 short_channel_id: 2,
2965 cltv_expiry_delta: 0,
2966 htlc_minimum_msat: 0,
2967 htlc_maximum_msat: OptionalField::Present(100_000),
2969 fee_proportional_millionths: 0,
2970 excess_data: Vec::new()
2972 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2973 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2974 short_channel_id: 7,
2977 cltv_expiry_delta: 0,
2978 htlc_minimum_msat: 0,
2979 htlc_maximum_msat: OptionalField::Present(100_000),
2981 fee_proportional_millionths: 0,
2982 excess_data: Vec::new()
2985 // Path via {node0, node2} is channels {1, 3, 5}.
2986 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2987 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2988 short_channel_id: 1,
2991 cltv_expiry_delta: 0,
2992 htlc_minimum_msat: 0,
2993 htlc_maximum_msat: OptionalField::Present(100_000),
2995 fee_proportional_millionths: 0,
2996 excess_data: Vec::new()
2998 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2999 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3000 short_channel_id: 3,
3003 cltv_expiry_delta: 0,
3004 htlc_minimum_msat: 0,
3005 htlc_maximum_msat: OptionalField::Present(100_000),
3007 fee_proportional_millionths: 0,
3008 excess_data: Vec::new()
3011 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3012 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3013 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3014 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3015 short_channel_id: 5,
3018 cltv_expiry_delta: 0,
3019 htlc_minimum_msat: 0,
3020 htlc_maximum_msat: OptionalField::Present(200_000),
3022 fee_proportional_millionths: 0,
3023 excess_data: Vec::new()
3026 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3027 // Add 100 sats to the capacities of {12, 13}, because these channels
3028 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3029 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3030 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3031 short_channel_id: 12,
3034 cltv_expiry_delta: 0,
3035 htlc_minimum_msat: 0,
3036 htlc_maximum_msat: OptionalField::Present(200_000),
3038 fee_proportional_millionths: 0,
3039 excess_data: Vec::new()
3041 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3042 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3043 short_channel_id: 13,
3046 cltv_expiry_delta: 0,
3047 htlc_minimum_msat: 0,
3048 htlc_maximum_msat: OptionalField::Present(200_000),
3050 fee_proportional_millionths: 0,
3051 excess_data: Vec::new()
3054 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3055 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3056 short_channel_id: 6,
3059 cltv_expiry_delta: 0,
3060 htlc_minimum_msat: 0,
3061 htlc_maximum_msat: OptionalField::Present(100_000),
3063 fee_proportional_millionths: 0,
3064 excess_data: Vec::new()
3066 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3067 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3068 short_channel_id: 11,
3071 cltv_expiry_delta: 0,
3072 htlc_minimum_msat: 0,
3073 htlc_maximum_msat: OptionalField::Present(100_000),
3075 fee_proportional_millionths: 0,
3076 excess_data: Vec::new()
3079 // Path via {node7, node2} is channels {12, 13, 5}.
3080 // We already limited them to 200 sats (they are used twice for 100 sats).
3081 // Nothing to do here.
3084 // Attempt to route more than available results in a failure.
3085 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3086 Some(InvoiceFeatures::known()), None, &Vec::new(), 350_000, 42, Arc::clone(&logger)) {
3087 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3088 } else { panic!(); }
3092 // Now, attempt to route 300 sats (exact amount we can route).
3093 // Our algorithm should provide us with these 3 paths, 100 sats each.
3094 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3095 Some(InvoiceFeatures::known()), None, &Vec::new(), 300_000, 42, Arc::clone(&logger)).unwrap();
3096 assert_eq!(route.paths.len(), 3);
3098 let mut total_amount_paid_msat = 0;
3099 for path in &route.paths {
3100 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3101 total_amount_paid_msat += path.last().unwrap().fee_msat;
3103 assert_eq!(total_amount_paid_msat, 300_000);
3109 fn mpp_cheaper_route_test() {
3110 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3111 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3113 // This test checks that if we have two cheaper paths and one more expensive path,
3114 // so that liquidity-wise any 2 of 3 combination is sufficient,
3115 // two cheaper paths will be taken.
3116 // These paths have equal available liquidity.
3118 // We need a combination of 3 paths:
3119 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3120 // Note that these paths overlap (channels 5, 12, 13).
3121 // Each path will have 100 sats capacity, those channels which
3122 // are used twice will have 200 sats capacity.
3124 // Disable other potential paths.
3125 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3126 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3127 short_channel_id: 2,
3130 cltv_expiry_delta: 0,
3131 htlc_minimum_msat: 0,
3132 htlc_maximum_msat: OptionalField::Present(100_000),
3134 fee_proportional_millionths: 0,
3135 excess_data: Vec::new()
3137 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3138 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3139 short_channel_id: 7,
3142 cltv_expiry_delta: 0,
3143 htlc_minimum_msat: 0,
3144 htlc_maximum_msat: OptionalField::Present(100_000),
3146 fee_proportional_millionths: 0,
3147 excess_data: Vec::new()
3150 // Path via {node0, node2} is channels {1, 3, 5}.
3151 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3152 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3153 short_channel_id: 1,
3156 cltv_expiry_delta: 0,
3157 htlc_minimum_msat: 0,
3158 htlc_maximum_msat: OptionalField::Present(100_000),
3160 fee_proportional_millionths: 0,
3161 excess_data: Vec::new()
3163 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3164 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3165 short_channel_id: 3,
3168 cltv_expiry_delta: 0,
3169 htlc_minimum_msat: 0,
3170 htlc_maximum_msat: OptionalField::Present(100_000),
3172 fee_proportional_millionths: 0,
3173 excess_data: Vec::new()
3176 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3177 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3178 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3179 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3180 short_channel_id: 5,
3183 cltv_expiry_delta: 0,
3184 htlc_minimum_msat: 0,
3185 htlc_maximum_msat: OptionalField::Present(200_000),
3187 fee_proportional_millionths: 0,
3188 excess_data: Vec::new()
3191 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3192 // Add 100 sats to the capacities of {12, 13}, because these channels
3193 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3194 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3195 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3196 short_channel_id: 12,
3199 cltv_expiry_delta: 0,
3200 htlc_minimum_msat: 0,
3201 htlc_maximum_msat: OptionalField::Present(200_000),
3203 fee_proportional_millionths: 0,
3204 excess_data: Vec::new()
3206 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3207 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3208 short_channel_id: 13,
3211 cltv_expiry_delta: 0,
3212 htlc_minimum_msat: 0,
3213 htlc_maximum_msat: OptionalField::Present(200_000),
3215 fee_proportional_millionths: 0,
3216 excess_data: Vec::new()
3219 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3220 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3221 short_channel_id: 6,
3224 cltv_expiry_delta: 0,
3225 htlc_minimum_msat: 0,
3226 htlc_maximum_msat: OptionalField::Present(100_000),
3227 fee_base_msat: 1_000,
3228 fee_proportional_millionths: 0,
3229 excess_data: Vec::new()
3231 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3232 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3233 short_channel_id: 11,
3236 cltv_expiry_delta: 0,
3237 htlc_minimum_msat: 0,
3238 htlc_maximum_msat: OptionalField::Present(100_000),
3240 fee_proportional_millionths: 0,
3241 excess_data: Vec::new()
3244 // Path via {node7, node2} is channels {12, 13, 5}.
3245 // We already limited them to 200 sats (they are used twice for 100 sats).
3246 // Nothing to do here.
3249 // Now, attempt to route 180 sats.
3250 // Our algorithm should provide us with these 2 paths.
3251 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3252 Some(InvoiceFeatures::known()), None, &Vec::new(), 180_000, 42, Arc::clone(&logger)).unwrap();
3253 assert_eq!(route.paths.len(), 2);
3255 let mut total_value_transferred_msat = 0;
3256 let mut total_paid_msat = 0;
3257 for path in &route.paths {
3258 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3259 total_value_transferred_msat += path.last().unwrap().fee_msat;
3261 total_paid_msat += hop.fee_msat;
3264 // If we paid fee, this would be higher.
3265 assert_eq!(total_value_transferred_msat, 180_000);
3266 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
3267 assert_eq!(total_fees_paid, 0);
3272 fn fees_on_mpp_route_test() {
3273 // This test makes sure that MPP algorithm properly takes into account
3274 // fees charged on the channels, by making the fees impactful:
3275 // if the fee is not properly accounted for, the behavior is different.
3276 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3277 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3279 // We need a route consisting of 2 paths:
3280 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
3281 // We will route 200 sats, Each path will have 100 sats capacity.
3283 // This test is not particularly stable: e.g.,
3284 // there's a way to route via {node0, node2, node4}.
3285 // It works while pathfinding is deterministic, but can be broken otherwise.
3286 // It's fine to ignore this concern for now.
3288 // Disable other potential paths.
3289 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3290 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3291 short_channel_id: 2,
3294 cltv_expiry_delta: 0,
3295 htlc_minimum_msat: 0,
3296 htlc_maximum_msat: OptionalField::Present(100_000),
3298 fee_proportional_millionths: 0,
3299 excess_data: Vec::new()
3302 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3303 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3304 short_channel_id: 7,
3307 cltv_expiry_delta: 0,
3308 htlc_minimum_msat: 0,
3309 htlc_maximum_msat: OptionalField::Present(100_000),
3311 fee_proportional_millionths: 0,
3312 excess_data: Vec::new()
3315 // Path via {node0, node2} is channels {1, 3, 5}.
3316 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3317 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3318 short_channel_id: 1,
3321 cltv_expiry_delta: 0,
3322 htlc_minimum_msat: 0,
3323 htlc_maximum_msat: OptionalField::Present(100_000),
3325 fee_proportional_millionths: 0,
3326 excess_data: Vec::new()
3328 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3329 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3330 short_channel_id: 3,
3333 cltv_expiry_delta: 0,
3334 htlc_minimum_msat: 0,
3335 htlc_maximum_msat: OptionalField::Present(100_000),
3337 fee_proportional_millionths: 0,
3338 excess_data: Vec::new()
3341 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3342 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3343 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3344 short_channel_id: 5,
3347 cltv_expiry_delta: 0,
3348 htlc_minimum_msat: 0,
3349 htlc_maximum_msat: OptionalField::Present(100_000),
3351 fee_proportional_millionths: 0,
3352 excess_data: Vec::new()
3355 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3356 // All channels should be 100 sats capacity. But for the fee experiment,
3357 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
3358 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
3359 // 100 sats (and pay 150 sats in fees for the use of channel 6),
3360 // so no matter how large are other channels,
3361 // the whole path will be limited by 100 sats with just these 2 conditions:
3362 // - channel 12 capacity is 250 sats
3363 // - fee for channel 6 is 150 sats
3364 // Let's test this by enforcing these 2 conditions and removing other limits.
3365 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3366 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3367 short_channel_id: 12,
3370 cltv_expiry_delta: 0,
3371 htlc_minimum_msat: 0,
3372 htlc_maximum_msat: OptionalField::Present(250_000),
3374 fee_proportional_millionths: 0,
3375 excess_data: Vec::new()
3377 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3378 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3379 short_channel_id: 13,
3382 cltv_expiry_delta: 0,
3383 htlc_minimum_msat: 0,
3384 htlc_maximum_msat: OptionalField::Absent,
3386 fee_proportional_millionths: 0,
3387 excess_data: Vec::new()
3390 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3391 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3392 short_channel_id: 6,
3395 cltv_expiry_delta: 0,
3396 htlc_minimum_msat: 0,
3397 htlc_maximum_msat: OptionalField::Absent,
3398 fee_base_msat: 150_000,
3399 fee_proportional_millionths: 0,
3400 excess_data: Vec::new()
3402 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3403 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3404 short_channel_id: 11,
3407 cltv_expiry_delta: 0,
3408 htlc_minimum_msat: 0,
3409 htlc_maximum_msat: OptionalField::Absent,
3411 fee_proportional_millionths: 0,
3412 excess_data: Vec::new()
3416 // Attempt to route more than available results in a failure.
3417 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3418 Some(InvoiceFeatures::known()), None, &Vec::new(), 210_000, 42, Arc::clone(&logger)) {
3419 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3420 } else { panic!(); }
3424 // Now, attempt to route 200 sats (exact amount we can route).
3425 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3426 Some(InvoiceFeatures::known()), None, &Vec::new(), 200_000, 42, Arc::clone(&logger)).unwrap();
3427 assert_eq!(route.paths.len(), 2);
3429 let mut total_amount_paid_msat = 0;
3430 for path in &route.paths {
3431 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3432 total_amount_paid_msat += path.last().unwrap().fee_msat;
3434 assert_eq!(total_amount_paid_msat, 200_000);
3440 fn drop_lowest_channel_mpp_route_test() {
3441 // This test checks that low-capacity channel is dropped when after
3442 // path finding we realize that we found more capacity than we need.
3443 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3444 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3446 // We need a route consisting of 3 paths:
3447 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3449 // The first and the second paths should be sufficient, but the third should be
3450 // cheaper, so that we select it but drop later.
3452 // First, we set limits on these (previously unlimited) channels.
3453 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
3455 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
3456 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3457 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3458 short_channel_id: 1,
3461 cltv_expiry_delta: 0,
3462 htlc_minimum_msat: 0,
3463 htlc_maximum_msat: OptionalField::Present(100_000),
3465 fee_proportional_millionths: 0,
3466 excess_data: Vec::new()
3468 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3469 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3470 short_channel_id: 3,
3473 cltv_expiry_delta: 0,
3474 htlc_minimum_msat: 0,
3475 htlc_maximum_msat: OptionalField::Present(50_000),
3477 fee_proportional_millionths: 0,
3478 excess_data: Vec::new()
3481 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
3482 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3483 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3484 short_channel_id: 12,
3487 cltv_expiry_delta: 0,
3488 htlc_minimum_msat: 0,
3489 htlc_maximum_msat: OptionalField::Present(60_000),
3491 fee_proportional_millionths: 0,
3492 excess_data: Vec::new()
3494 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3495 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3496 short_channel_id: 13,
3499 cltv_expiry_delta: 0,
3500 htlc_minimum_msat: 0,
3501 htlc_maximum_msat: OptionalField::Present(60_000),
3503 fee_proportional_millionths: 0,
3504 excess_data: Vec::new()
3507 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
3508 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3509 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3510 short_channel_id: 2,
3513 cltv_expiry_delta: 0,
3514 htlc_minimum_msat: 0,
3515 htlc_maximum_msat: OptionalField::Present(20_000),
3517 fee_proportional_millionths: 0,
3518 excess_data: Vec::new()
3520 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3521 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3522 short_channel_id: 4,
3525 cltv_expiry_delta: 0,
3526 htlc_minimum_msat: 0,
3527 htlc_maximum_msat: OptionalField::Present(20_000),
3529 fee_proportional_millionths: 0,
3530 excess_data: Vec::new()
3534 // Attempt to route more than available results in a failure.
3535 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
3536 Some(InvoiceFeatures::known()), None, &Vec::new(), 150_000, 42, Arc::clone(&logger)) {
3537 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3538 } else { panic!(); }
3542 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
3543 // Our algorithm should provide us with these 3 paths.
3544 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
3545 Some(InvoiceFeatures::known()), None, &Vec::new(), 125_000, 42, Arc::clone(&logger)).unwrap();
3546 assert_eq!(route.paths.len(), 3);
3547 let mut total_amount_paid_msat = 0;
3548 for path in &route.paths {
3549 assert_eq!(path.len(), 2);
3550 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3551 total_amount_paid_msat += path.last().unwrap().fee_msat;
3553 assert_eq!(total_amount_paid_msat, 125_000);
3557 // Attempt to route without the last small cheap channel
3558 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
3559 Some(InvoiceFeatures::known()), None, &Vec::new(), 90_000, 42, Arc::clone(&logger)).unwrap();
3560 assert_eq!(route.paths.len(), 2);
3561 let mut total_amount_paid_msat = 0;
3562 for path in &route.paths {
3563 assert_eq!(path.len(), 2);
3564 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3565 total_amount_paid_msat += path.last().unwrap().fee_msat;
3567 assert_eq!(total_amount_paid_msat, 90_000);
3572 fn min_criteria_consistency() {
3573 // Test that we don't use an inconsistent metric between updating and walking nodes during
3574 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
3575 // was updated with a different criterion from the heap sorting, resulting in loops in
3576 // calculated paths. We test for that specific case here.
3578 // We construct a network that looks like this:
3580 // node2 -1(3)2- node3
3584 // node1 -1(5)2- node4 -1(1)2- node6
3590 // We create a loop on the side of our real path - our destination is node 6, with a
3591 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
3592 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
3593 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
3594 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
3595 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
3596 // "previous hop" being set to node 3, creating a loop in the path.
3597 let secp_ctx = Secp256k1::new();
3598 let logger = Arc::new(test_utils::TestLogger::new());
3599 let net_graph_msg_handler = NetGraphMsgHandler::new(genesis_block(Network::Testnet).header.block_hash(), None, Arc::clone(&logger));
3600 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3602 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
3603 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3604 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3605 short_channel_id: 6,
3608 cltv_expiry_delta: (6 << 8) | 0,
3609 htlc_minimum_msat: 0,
3610 htlc_maximum_msat: OptionalField::Absent,
3612 fee_proportional_millionths: 0,
3613 excess_data: Vec::new()
3615 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
3617 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3618 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3619 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3620 short_channel_id: 5,
3623 cltv_expiry_delta: (5 << 8) | 0,
3624 htlc_minimum_msat: 0,
3625 htlc_maximum_msat: OptionalField::Absent,
3627 fee_proportional_millionths: 0,
3628 excess_data: Vec::new()
3630 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
3632 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
3633 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3634 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3635 short_channel_id: 4,
3638 cltv_expiry_delta: (4 << 8) | 0,
3639 htlc_minimum_msat: 0,
3640 htlc_maximum_msat: OptionalField::Absent,
3642 fee_proportional_millionths: 0,
3643 excess_data: Vec::new()
3645 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
3647 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
3648 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
3649 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3650 short_channel_id: 3,
3653 cltv_expiry_delta: (3 << 8) | 0,
3654 htlc_minimum_msat: 0,
3655 htlc_maximum_msat: OptionalField::Absent,
3657 fee_proportional_millionths: 0,
3658 excess_data: Vec::new()
3660 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
3662 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
3663 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3664 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3665 short_channel_id: 2,
3668 cltv_expiry_delta: (2 << 8) | 0,
3669 htlc_minimum_msat: 0,
3670 htlc_maximum_msat: OptionalField::Absent,
3672 fee_proportional_millionths: 0,
3673 excess_data: Vec::new()
3676 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
3677 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3678 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3679 short_channel_id: 1,
3682 cltv_expiry_delta: (1 << 8) | 0,
3683 htlc_minimum_msat: 100,
3684 htlc_maximum_msat: OptionalField::Absent,
3686 fee_proportional_millionths: 0,
3687 excess_data: Vec::new()
3689 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
3692 // Now ensure the route flows simply over nodes 1 and 4 to 6.
3693 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();
3694 assert_eq!(route.paths.len(), 1);
3695 assert_eq!(route.paths[0].len(), 3);
3697 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3698 assert_eq!(route.paths[0][0].short_channel_id, 6);
3699 assert_eq!(route.paths[0][0].fee_msat, 100);
3700 assert_eq!(route.paths[0][0].cltv_expiry_delta, (5 << 8) | 0);
3701 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(1));
3702 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(6));
3704 assert_eq!(route.paths[0][1].pubkey, nodes[4]);
3705 assert_eq!(route.paths[0][1].short_channel_id, 5);
3706 assert_eq!(route.paths[0][1].fee_msat, 0);
3707 assert_eq!(route.paths[0][1].cltv_expiry_delta, (1 << 8) | 0);
3708 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(4));
3709 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(5));
3711 assert_eq!(route.paths[0][2].pubkey, nodes[6]);
3712 assert_eq!(route.paths[0][2].short_channel_id, 1);
3713 assert_eq!(route.paths[0][2].fee_msat, 10_000);
3714 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
3715 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
3716 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(1));
3722 fn exact_fee_liquidity_limit() {
3723 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
3724 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
3725 // we calculated fees on a higher value, resulting in us ignoring such paths.
3726 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3727 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
3729 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
3731 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3732 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3733 short_channel_id: 2,
3736 cltv_expiry_delta: 0,
3737 htlc_minimum_msat: 0,
3738 htlc_maximum_msat: OptionalField::Present(85_000),
3740 fee_proportional_millionths: 0,
3741 excess_data: Vec::new()
3744 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3745 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3746 short_channel_id: 12,
3749 cltv_expiry_delta: (4 << 8) | 1,
3750 htlc_minimum_msat: 0,
3751 htlc_maximum_msat: OptionalField::Present(270_000),
3753 fee_proportional_millionths: 1000000,
3754 excess_data: Vec::new()
3758 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
3759 // 200% fee charged channel 13 in the 1-to-2 direction.
3760 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();
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(), &id_to_feature_flags(3));
3776 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
3781 fn htlc_max_reduction_below_min() {
3782 // Test that if, while walking the graph, we reduce the value being sent to meet an
3783 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
3784 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
3785 // resulting in us thinking there is no possible path, even if other paths exist.
3786 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3787 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3789 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
3790 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
3791 // then try to send 90_000.
3792 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3793 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3794 short_channel_id: 2,
3797 cltv_expiry_delta: 0,
3798 htlc_minimum_msat: 0,
3799 htlc_maximum_msat: OptionalField::Present(80_000),
3801 fee_proportional_millionths: 0,
3802 excess_data: Vec::new()
3804 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3805 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3806 short_channel_id: 4,
3809 cltv_expiry_delta: (4 << 8) | 1,
3810 htlc_minimum_msat: 90_000,
3811 htlc_maximum_msat: OptionalField::Absent,
3813 fee_proportional_millionths: 0,
3814 excess_data: Vec::new()
3818 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
3819 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
3820 // expensive) channels 12-13 path.
3821 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();
3822 assert_eq!(route.paths.len(), 1);
3823 assert_eq!(route.paths[0].len(), 2);
3825 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
3826 assert_eq!(route.paths[0][0].short_channel_id, 12);
3827 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
3828 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
3829 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
3830 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
3832 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3833 assert_eq!(route.paths[0][1].short_channel_id, 13);
3834 assert_eq!(route.paths[0][1].fee_msat, 90_000);
3835 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3836 assert_eq!(route.paths[0][1].node_features.le_flags(), InvoiceFeatures::known().le_flags());
3837 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
3841 pub(super) fn random_init_seed() -> u64 {
3842 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
3843 use core::hash::{BuildHasher, Hasher};
3844 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
3845 println!("Using seed of {}", seed);
3848 use util::ser::Readable;
3851 fn generate_routes() {
3852 let mut d = match super::test_utils::get_route_file() {
3859 let graph = NetworkGraph::read(&mut d).unwrap();
3861 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
3862 let mut seed = random_init_seed() as usize;
3863 'load_endpoints: for _ in 0..10 {
3865 seed = seed.overflowing_mul(0xdeadbeef).0;
3866 let src = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3867 seed = seed.overflowing_mul(0xdeadbeef).0;
3868 let dst = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3869 let amt = seed as u64 % 200_000_000;
3870 if get_route(src, &graph, dst, None, None, &[], amt, 42, &test_utils::TestLogger::new()).is_ok() {
3871 continue 'load_endpoints;
3878 fn generate_routes_mpp() {
3879 let mut d = match super::test_utils::get_route_file() {
3886 let graph = NetworkGraph::read(&mut d).unwrap();
3888 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
3889 let mut seed = random_init_seed() as usize;
3890 'load_endpoints: for _ in 0..10 {
3892 seed = seed.overflowing_mul(0xdeadbeef).0;
3893 let src = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3894 seed = seed.overflowing_mul(0xdeadbeef).0;
3895 let dst = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3896 let amt = seed as u64 % 200_000_000;
3897 if get_route(src, &graph, dst, Some(InvoiceFeatures::known()), None, &[], amt, 42, &test_utils::TestLogger::new()).is_ok() {
3898 continue 'load_endpoints;
3906 pub(crate) mod test_utils {
3908 /// Tries to open a network graph file, or panics with a URL to fetch it.
3909 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
3910 let res = File::open("net_graph-2021-05-31.bin") // By default we're run in RL/lightning
3911 .or_else(|_| File::open("lightning/net_graph-2021-05-31.bin")) // We may be run manually in RL/
3912 .or_else(|_| { // Fall back to guessing based on the binary location
3913 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
3914 let mut path = std::env::current_exe().unwrap();
3915 path.pop(); // lightning-...
3917 path.pop(); // debug
3918 path.pop(); // target
3919 path.push("lightning");
3920 path.push("net_graph-2021-05-31.bin");
3921 eprintln!("{}", path.to_str().unwrap());
3924 .map_err(|_| "Please fetch https://bitcoin.ninja/ldk-net_graph-v0.0.15-2021-05-31.bin and place it at lightning/net_graph-2021-05-31.bin");
3925 #[cfg(require_route_graph_test)]
3926 return Ok(res.unwrap());
3927 #[cfg(not(require_route_graph_test))]
3932 #[cfg(all(test, feature = "unstable"))]
3935 use util::logger::{Logger, Record};
3939 struct DummyLogger {}
3940 impl Logger for DummyLogger {
3941 fn log(&self, _record: &Record) {}
3945 fn generate_routes(bench: &mut Bencher) {
3946 let mut d = test_utils::get_route_file().unwrap();
3947 let graph = NetworkGraph::read(&mut d).unwrap();
3949 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
3950 let mut path_endpoints = Vec::new();
3951 let mut seed: usize = 0xdeadbeef;
3952 'load_endpoints: for _ in 0..100 {
3955 let src = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3957 let dst = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3958 let amt = seed as u64 % 1_000_000;
3959 if get_route(src, &graph, dst, None, None, &[], amt, 42, &DummyLogger{}).is_ok() {
3960 path_endpoints.push((src, dst, amt));
3961 continue 'load_endpoints;
3966 // ...then benchmark finding paths between the nodes we learned.
3969 let (src, dst, amt) = path_endpoints[idx % path_endpoints.len()];
3970 assert!(get_route(src, &graph, dst, None, None, &[], amt, 42, &DummyLogger{}).is_ok());
3976 fn generate_mpp_routes(bench: &mut Bencher) {
3977 let mut d = test_utils::get_route_file().unwrap();
3978 let graph = NetworkGraph::read(&mut d).unwrap();
3980 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
3981 let mut path_endpoints = Vec::new();
3982 let mut seed: usize = 0xdeadbeef;
3983 'load_endpoints: for _ in 0..100 {
3986 let src = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3988 let dst = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3989 let amt = seed as u64 % 1_000_000;
3990 if get_route(src, &graph, dst, Some(InvoiceFeatures::known()), None, &[], amt, 42, &DummyLogger{}).is_ok() {
3991 path_endpoints.push((src, dst, amt));
3992 continue 'load_endpoints;
3997 // ...then benchmark finding paths between the nodes we learned.
4000 let (src, dst, amt) = path_endpoints[idx % path_endpoints.len()];
4001 assert!(get_route(src, &graph, dst, Some(InvoiceFeatures::known()), None, &[], amt, 42, &DummyLogger{}).is_ok());