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;
30 #[derive(Clone, PartialEq)]
32 /// The node_id of the node at this hop.
33 pub pubkey: PublicKey,
34 /// The node_announcement features of the node at this hop. For the last hop, these may be
35 /// amended to match the features present in the invoice this node generated.
36 pub node_features: NodeFeatures,
37 /// The channel that should be used from the previous hop to reach this node.
38 pub short_channel_id: u64,
39 /// The channel_announcement features of the channel that should be used from the previous hop
40 /// to reach this node.
41 pub channel_features: ChannelFeatures,
42 /// The fee taken on this hop (for paying for the use of the *next* channel in the path).
43 /// For the last hop, this should be the full value of the payment (might be more than
44 /// requested if we had to match htlc_minimum_msat).
46 /// The CLTV delta added for this hop. For the last hop, this should be the full CLTV value
47 /// expected at the destination, in excess of the current block height.
48 pub cltv_expiry_delta: u32,
51 impl_writeable_tlv_based!(RouteHop, {
52 (0, pubkey, required),
53 (2, node_features, required),
54 (4, short_channel_id, required),
55 (6, channel_features, required),
56 (8, fee_msat, required),
57 (10, cltv_expiry_delta, required),
60 /// A route directs a payment from the sender (us) to the recipient. If the recipient supports MPP,
61 /// it can take multiple paths. Each path is composed of one or more hops through the network.
62 #[derive(Clone, PartialEq)]
64 /// The list of routes taken for a single (potentially-)multi-part payment. The pubkey of the
65 /// last RouteHop in each path must be the same.
66 /// Each entry represents a list of hops, NOT INCLUDING our own, where the last hop is the
67 /// destination. Thus, this must always be at least length one. While the maximum length of any
68 /// given path is variable, keeping the length of any path to less than 20 should currently
69 /// ensure it is viable.
70 pub paths: Vec<Vec<RouteHop>>,
73 const SERIALIZATION_VERSION: u8 = 1;
74 const MIN_SERIALIZATION_VERSION: u8 = 1;
76 impl Writeable for Route {
77 fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
78 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
79 (self.paths.len() as u64).write(writer)?;
80 for hops in self.paths.iter() {
81 (hops.len() as u8).write(writer)?;
82 for hop in hops.iter() {
86 write_tlv_fields!(writer, {});
91 impl Readable for Route {
92 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
93 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
94 let path_count: u64 = Readable::read(reader)?;
95 let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
96 for _ in 0..path_count {
97 let hop_count: u8 = Readable::read(reader)?;
98 let mut hops = Vec::with_capacity(hop_count as usize);
99 for _ in 0..hop_count {
100 hops.push(Readable::read(reader)?);
104 read_tlv_fields!(reader, {});
109 /// A list of hops along a payment path terminating with a channel to the recipient.
110 #[derive(Eq, PartialEq, Debug, Clone)]
111 pub struct RouteHint(pub Vec<RouteHintHop>);
113 /// A channel descriptor for a hop along a payment path.
114 #[derive(Eq, PartialEq, Debug, Clone)]
115 pub struct RouteHintHop {
116 /// The node_id of the non-target end of the route
117 pub src_node_id: PublicKey,
118 /// The short_channel_id of this channel
119 pub short_channel_id: u64,
120 /// The fees which must be paid to use this channel
121 pub fees: RoutingFees,
122 /// The difference in CLTV values between this node and the next node.
123 pub cltv_expiry_delta: u16,
124 /// The minimum value, in msat, which must be relayed to the next hop.
125 pub htlc_minimum_msat: Option<u64>,
126 /// The maximum value in msat available for routing with a single HTLC.
127 pub htlc_maximum_msat: Option<u64>,
130 #[derive(Eq, PartialEq)]
131 struct RouteGraphNode {
133 lowest_fee_to_peer_through_node: u64,
134 lowest_fee_to_node: u64,
135 // The maximum value a yet-to-be-constructed payment path might flow through this node.
136 // This value is upper-bounded by us by:
137 // - how much is needed for a path being constructed
138 // - how much value can channels following this node (up to the destination) can contribute,
139 // considering their capacity and fees
140 value_contribution_msat: u64,
141 /// The effective htlc_minimum_msat at this hop. If a later hop on the path had a higher HTLC
142 /// minimum, we use it, plus the fees required at each earlier hop to meet it.
143 path_htlc_minimum_msat: u64,
146 impl cmp::Ord for RouteGraphNode {
147 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
148 let other_score = cmp::max(other.lowest_fee_to_peer_through_node, other.path_htlc_minimum_msat);
149 let self_score = cmp::max(self.lowest_fee_to_peer_through_node, self.path_htlc_minimum_msat);
150 other_score.cmp(&self_score).then_with(|| other.pubkey.serialize().cmp(&self.pubkey.serialize()))
154 impl cmp::PartialOrd for RouteGraphNode {
155 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
156 Some(self.cmp(other))
160 struct DummyDirectionalChannelInfo {
161 cltv_expiry_delta: u32,
162 htlc_minimum_msat: u64,
163 htlc_maximum_msat: Option<u64>,
167 /// It's useful to keep track of the hops associated with the fees required to use them,
168 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
169 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
170 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
171 #[derive(Clone, Debug)]
172 struct PathBuildingHop<'a> {
173 // The RouteHintHop fields which will eventually be used if this hop is used in a final Route.
174 // Note that node_features is calculated separately after our initial graph walk.
176 short_channel_id: u64,
177 channel_features: &'a ChannelFeatures,
179 cltv_expiry_delta: u32,
181 /// Minimal fees required to route to the source node of the current hop via any of its inbound channels.
182 src_lowest_inbound_fees: RoutingFees,
183 /// Fees of the channel used in this hop.
184 channel_fees: RoutingFees,
185 /// All the fees paid *after* this channel on the way to the destination
186 next_hops_fee_msat: u64,
187 /// Fee paid for the use of the current channel (see channel_fees).
188 /// The value will be actually deducted from the counterparty balance on the previous link.
189 hop_use_fee_msat: u64,
190 /// Used to compare channels when choosing the for routing.
191 /// Includes paying for the use of a hop and the following hops, as well as
192 /// an estimated cost of reaching this hop.
193 /// Might get stale when fees are recomputed. Primarily for internal use.
195 /// This is useful for update_value_and_recompute_fees to make sure
196 /// we don't fall below the minimum. Should not be updated manually and
197 /// generally should not be accessed.
198 htlc_minimum_msat: u64,
199 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
200 /// walk and may be invalid thereafter.
201 path_htlc_minimum_msat: u64,
202 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
203 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
204 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
205 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
206 /// avoid processing them again.
208 #[cfg(any(test, feature = "fuzztarget"))]
209 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
210 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
211 // value_contribution_msat, which requires tracking it here. See comments below where it is
212 // used for more info.
213 value_contribution_msat: u64,
216 // Instantiated with a list of hops with correct data in them collected during path finding,
217 // an instance of this struct should be further modified only via given methods.
219 struct PaymentPath<'a> {
220 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
223 impl<'a> PaymentPath<'a> {
224 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
225 fn get_value_msat(&self) -> u64 {
226 self.hops.last().unwrap().0.fee_msat
229 fn get_total_fee_paid_msat(&self) -> u64 {
230 if self.hops.len() < 1 {
234 // Can't use next_hops_fee_msat because it gets outdated.
235 for (i, (hop, _)) in self.hops.iter().enumerate() {
236 if i != self.hops.len() - 1 {
237 result += hop.fee_msat;
243 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
244 // to change fees may result in an inconsistency.
246 // Sometimes we call this function right after constructing a path which is inconsistent in
247 // that it the value being transferred has decreased while we were doing path finding, leading
248 // to the fees being paid not lining up with the actual limits.
250 // Note that this function is not aware of the available_liquidity limit, and thus does not
251 // support increasing the value being transferred.
252 fn update_value_and_recompute_fees(&mut self, value_msat: u64) {
253 assert!(value_msat <= self.hops.last().unwrap().0.fee_msat);
255 let mut total_fee_paid_msat = 0 as u64;
256 for i in (0..self.hops.len()).rev() {
257 let last_hop = i == self.hops.len() - 1;
259 // For non-last-hop, this value will represent the fees paid on the current hop. It
260 // will consist of the fees for the use of the next hop, and extra fees to match
261 // htlc_minimum_msat of the current channel. Last hop is handled separately.
262 let mut cur_hop_fees_msat = 0;
264 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
267 let mut cur_hop = &mut self.hops.get_mut(i).unwrap().0;
268 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
269 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
270 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
271 // set it too high just to maliciously take more fees by exploiting this
272 // match htlc_minimum_msat logic.
273 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
274 if let Some(extra_fees_msat) = cur_hop.htlc_minimum_msat.checked_sub(cur_hop_transferred_amount_msat) {
275 // Note that there is a risk that *previous hops* (those closer to us, as we go
276 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
278 // This might make us end up with a broken route, although this should be super-rare
279 // in practice, both because of how healthy channels look like, and how we pick
280 // channels in add_entry.
281 // Also, this can't be exploited more heavily than *announce a free path and fail
283 cur_hop_transferred_amount_msat += extra_fees_msat;
284 total_fee_paid_msat += extra_fees_msat;
285 cur_hop_fees_msat += extra_fees_msat;
289 // Final hop is a special case: it usually has just value_msat (by design), but also
290 // it still could overpay for the htlc_minimum_msat.
291 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
293 // Propagate updated fees for the use of the channels to one hop back, where they
294 // will be actually paid (fee_msat). The last hop is handled above separately.
295 cur_hop.fee_msat = cur_hop_fees_msat;
298 // Fee for the use of the current hop which will be deducted on the previous hop.
299 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
300 // this channel is free for us.
302 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.channel_fees) {
303 cur_hop.hop_use_fee_msat = new_fee;
304 total_fee_paid_msat += new_fee;
306 // It should not be possible because this function is called only to reduce the
307 // value. In that case, compute_fee was already called with the same fees for
308 // larger amount and there was no overflow.
316 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
317 let proportional_fee_millions =
318 amount_msat.checked_mul(channel_fees.proportional_millionths as u64);
319 if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
320 (channel_fees.base_msat as u64).checked_add(part / 1_000_000) }) {
324 // This function may be (indirectly) called without any verification,
325 // with channel_fees provided by a caller. We should handle it gracefully.
330 /// Gets a route from us (payer) to the given target node (payee).
332 /// If the payee provided features in their invoice, they should be provided via payee_features.
333 /// Without this, MPP will only be used if the payee's features are available in the network graph.
335 /// Private routing paths between a public node and the target may be included in `last_hops`.
336 /// Currently, only the last hop in each path is considered.
338 /// If some channels aren't announced, it may be useful to fill in a first_hops with the
339 /// results from a local ChannelManager::list_usable_channels() call. If it is filled in, our
340 /// view of our local channels (from net_graph_msg_handler) will be ignored, and only those
341 /// in first_hops will be used.
343 /// Panics if first_hops contains channels without short_channel_ids
344 /// (ChannelManager::list_usable_channels will never include such channels).
346 /// The fees on channels from us to next-hops are ignored (as they are assumed to all be
347 /// equal), however the enabled/disabled bit on such channels as well as the
348 /// htlc_minimum_msat/htlc_maximum_msat *are* checked as they may change based on the receiving node.
349 pub fn get_route<L: Deref>(our_node_id: &PublicKey, network: &NetworkGraph, payee: &PublicKey, payee_features: Option<InvoiceFeatures>, first_hops: Option<&[&ChannelDetails]>,
350 last_hops: &[&RouteHint], final_value_msat: u64, final_cltv: u32, logger: L) -> Result<Route, LightningError> where L::Target: Logger {
351 // TODO: Obviously *only* using total fee cost sucks. We should consider weighting by
352 // uptime/success in using a node in the past.
353 if *payee == *our_node_id {
354 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
357 if final_value_msat > MAX_VALUE_MSAT {
358 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
361 if final_value_msat == 0 {
362 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
365 let last_hops = last_hops.iter().filter_map(|hops| hops.0.last()).collect::<Vec<_>>();
366 for last_hop in last_hops.iter() {
367 if last_hop.src_node_id == *payee {
368 return Err(LightningError{err: "Last hop cannot have a payee as a source.".to_owned(), action: ErrorAction::IgnoreError});
372 // The general routing idea is the following:
373 // 1. Fill first/last hops communicated by the caller.
374 // 2. Attempt to construct a path from payer to payee for transferring
375 // any ~sufficient (described later) value.
376 // If succeed, remember which channels were used and how much liquidity they have available,
377 // so that future paths don't rely on the same liquidity.
378 // 3. Prooceed to the next step if:
379 // - we hit the recommended target value;
380 // - OR if we could not construct a new path. Any next attempt will fail too.
381 // Otherwise, repeat step 2.
382 // 4. See if we managed to collect paths which aggregately are able to transfer target value
383 // (not recommended value). If yes, proceed. If not, fail routing.
384 // 5. Randomly combine paths into routes having enough to fulfill the payment. (TODO: knapsack)
385 // 6. Of all the found paths, select only those with the lowest total fee.
386 // 7. The last path in every selected route is likely to be more than we need.
387 // Reduce its value-to-transfer and recompute fees.
388 // 8. Choose the best route by the lowest total fee.
390 // As for the actual search algorithm,
391 // we do a payee-to-payer pseudo-Dijkstra's sorting by each node's distance from the payee
392 // plus the minimum per-HTLC fee to get from it to another node (aka "shitty pseudo-A*").
394 // We are not a faithful Dijkstra's implementation because we can change values which impact
395 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
396 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) then
397 // the value we are currently attempting to send over a path, we simply reduce the value being
398 // sent along the path for any hops after that channel. This may imply that later fees (which
399 // we've already tabulated) are lower because a smaller value is passing through the channels
400 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
401 // channels which were selected earlier (and which may still be used for other paths without a
402 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
405 // One potentially problematic case for this algorithm would be if there are many
406 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
407 // graph walking), we may never find a path which is not liquidity-limited and has lower
408 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
409 // Because we only consider paths with at least 5% of the total value being sent, the damage
410 // from such a case should be limited, however this could be further reduced in the future by
411 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
412 // limits for the purposes of fee calculation.
414 // Alternatively, we could store more detailed path information in the heap (targets, below)
415 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
416 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
417 // and practically (as we would need to store dynamically-allocated path information in heap
418 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
419 // results of such an algorithm would likely be biased towards lower-value paths.
421 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
422 // outside of our current search value, running a path search more times to gather candidate
423 // paths at different values. While this may be acceptable, further path searches may increase
424 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
425 // graph for candidate paths, calculating the maximum value which can realistically be sent at
426 // the same time, remaining generic across different payment values.
428 // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
429 // to use as the A* heuristic beyond just the cost to get one node further than the current
432 let dummy_directional_info = DummyDirectionalChannelInfo { // used for first_hops routes
433 cltv_expiry_delta: 0,
434 htlc_minimum_msat: 0,
435 htlc_maximum_msat: None,
438 proportional_millionths: 0,
442 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
443 // it. If the payee supports it they're supposed to include it in the invoice, so that should
445 let allow_mpp = if let Some(features) = &payee_features {
446 features.supports_basic_mpp()
447 } else if let Some(node) = network.get_nodes().get(&payee) {
448 if let Some(node_info) = node.announcement_info.as_ref() {
449 node_info.features.supports_basic_mpp()
454 // Prepare the data we'll use for payee-to-payer search by
455 // inserting first hops suggested by the caller as targets.
456 // Our search will then attempt to reach them while traversing from the payee node.
457 let mut first_hop_targets: HashMap<_, (_, ChannelFeatures, _, NodeFeatures)> =
458 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
459 if let Some(hops) = first_hops {
461 let short_channel_id = chan.short_channel_id.expect("first_hops should be filled in with usable channels, not pending ones");
462 if chan.counterparty.node_id == *our_node_id {
463 return Err(LightningError{err: "First hop cannot have our_node_id as a destination.".to_owned(), action: ErrorAction::IgnoreError});
465 first_hop_targets.insert(chan.counterparty.node_id, (short_channel_id, chan.counterparty.features.to_context(), chan.outbound_capacity_msat, chan.counterparty.features.to_context()));
467 if first_hop_targets.is_empty() {
468 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
472 let empty_channel_features = ChannelFeatures::empty();
474 // The main heap containing all candidate next-hops sorted by their score (max(A* fee,
475 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
476 // adding duplicate entries when we find a better path to a given node.
477 let mut targets = BinaryHeap::new();
479 // Map from node_id to information about the best current path to that node, including feerate
481 let mut dist = HashMap::with_capacity(network.get_nodes().len());
483 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
484 // indicating that we may wish to try again with a higher value, potentially paying to meet an
485 // htlc_minimum with extra fees while still finding a cheaper path.
486 let mut hit_minimum_limit;
488 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
489 // We start with a path_value of the exact amount we want, and if that generates a route we may
490 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
491 // amount we want in total across paths, selecting the best subset at the end.
492 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
493 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
494 let mut path_value_msat = final_value_msat;
496 // We don't want multiple paths (as per MPP) share liquidity of the same channels.
497 // This map allows paths to be aware of the channel use by other paths in the same call.
498 // This would help to make a better path finding decisions and not "overbook" channels.
499 // It is unaware of the directions (except for `outbound_capacity_msat` in `first_hops`).
500 let mut bookkeeped_channels_liquidity_available_msat = HashMap::with_capacity(network.get_nodes().len());
502 // Keeping track of how much value we already collected across other paths. Helps to decide:
503 // - how much a new path should be transferring (upper bound);
504 // - whether a channel should be disregarded because
505 // it's available liquidity is too small comparing to how much more we need to collect;
506 // - when we want to stop looking for new paths.
507 let mut already_collected_value_msat = 0;
509 log_trace!(logger, "Building path from {} (payee) to {} (us/payer) for value {} msat.", payee, our_node_id, final_value_msat);
511 macro_rules! add_entry {
512 // Adds entry which goes from $src_node_id to $dest_node_id
513 // over the channel with id $chan_id with fees described in
514 // $directional_info.
515 // $next_hops_fee_msat represents the fees paid for using all the channel *after* this one,
516 // since that value has to be transferred over this channel.
517 // Returns whether this channel caused an update to `targets`.
518 ( $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,
519 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr ) => { {
520 // We "return" whether we updated the path at the end, via this:
521 let mut did_add_update_path_to_src_node = false;
522 // Channels to self should not be used. This is more of belt-and-suspenders, because in
523 // practice these cases should be caught earlier:
524 // - for regular channels at channel announcement (TODO)
525 // - for first and last hops early in get_route
526 if $src_node_id != $dest_node_id.clone() {
527 let available_liquidity_msat = bookkeeped_channels_liquidity_available_msat.entry($chan_id.clone()).or_insert_with(|| {
528 let mut initial_liquidity_available_msat = None;
529 if let Some(capacity_sats) = $capacity_sats {
530 initial_liquidity_available_msat = Some(capacity_sats * 1000);
533 if let Some(htlc_maximum_msat) = $directional_info.htlc_maximum_msat {
534 if let Some(available_msat) = initial_liquidity_available_msat {
535 initial_liquidity_available_msat = Some(cmp::min(available_msat, htlc_maximum_msat));
537 initial_liquidity_available_msat = Some(htlc_maximum_msat);
541 match initial_liquidity_available_msat {
542 Some(available_msat) => available_msat,
543 // We assume channels with unknown balance have
544 // a capacity of 0.0025 BTC (or 250_000 sats).
545 None => 250_000 * 1000
549 // It is tricky to substract $next_hops_fee_msat from available liquidity here.
550 // It may be misleading because we might later choose to reduce the value transferred
551 // over these channels, and the channel which was insufficient might become sufficient.
552 // Worst case: we drop a good channel here because it can't cover the high following
553 // fees caused by one expensive channel, but then this channel could have been used
554 // if the amount being transferred over this path is lower.
555 // We do this for now, but this is a subject for removal.
556 if let Some(available_value_contribution_msat) = available_liquidity_msat.checked_sub($next_hops_fee_msat) {
558 // Routing Fragmentation Mitigation heuristic:
560 // Routing fragmentation across many payment paths increases the overall routing
561 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
562 // Taking too many smaller paths also increases the chance of payment failure.
563 // Thus to avoid this effect, we require from our collected links to provide
564 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
566 // This requirement is currently 5% of the remaining-to-be-collected value.
567 // This means as we successfully advance in our collection,
568 // the absolute liquidity contribution is lowered,
569 // thus increasing the number of potential channels to be selected.
571 // Derive the minimal liquidity contribution with a ratio of 20 (5%, rounded up)
572 // or 100% if we're not allowed to do multipath payments.
573 let minimal_value_contribution_msat: u64 = if allow_mpp {
574 (recommended_value_msat - already_collected_value_msat + 19) / 20
578 // Verify the liquidity offered by this channel complies to the minimal contribution.
579 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
581 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
582 // Includes paying fees for the use of the following channels.
583 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
584 Some(result) => result,
585 // Can't overflow due to how the values were computed right above.
586 None => unreachable!(),
588 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
589 let over_path_minimum_msat = amount_to_transfer_over_msat >= $directional_info.htlc_minimum_msat &&
590 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
592 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
593 // bother considering this channel.
594 // Since we're choosing amount_to_transfer_over_msat as maximum possible, it can
595 // be only reduced later (not increased), so this channel should just be skipped
596 // as not sufficient.
597 if !over_path_minimum_msat {
598 hit_minimum_limit = true;
599 } else if contributes_sufficient_value {
600 // Note that low contribution here (limited by available_liquidity_msat)
601 // might violate htlc_minimum_msat on the hops which are next along the
602 // payment path (upstream to the payee). To avoid that, we recompute path
603 // path fees knowing the final path contribution after constructing it.
604 let path_htlc_minimum_msat = match compute_fees($next_hops_path_htlc_minimum_msat, $directional_info.fees)
605 .map(|fee_msat| fee_msat.checked_add($next_hops_path_htlc_minimum_msat)) {
606 Some(Some(value_msat)) => cmp::max(value_msat, $directional_info.htlc_minimum_msat),
607 _ => u64::max_value()
609 let hm_entry = dist.entry(&$src_node_id);
610 let old_entry = hm_entry.or_insert_with(|| {
611 // If there was previously no known way to access
612 // the source node (recall it goes payee-to-payer) of $chan_id, first add
613 // a semi-dummy record just to compute the fees to reach the source node.
614 // This will affect our decision on selecting $chan_id
615 // as a way to reach the $dest_node_id.
616 let mut fee_base_msat = u32::max_value();
617 let mut fee_proportional_millionths = u32::max_value();
618 if let Some(Some(fees)) = network.get_nodes().get(&$src_node_id).map(|node| node.lowest_inbound_channel_fees) {
619 fee_base_msat = fees.base_msat;
620 fee_proportional_millionths = fees.proportional_millionths;
623 pubkey: $dest_node_id.clone(),
625 channel_features: $chan_features,
627 cltv_expiry_delta: 0,
628 src_lowest_inbound_fees: RoutingFees {
629 base_msat: fee_base_msat,
630 proportional_millionths: fee_proportional_millionths,
632 channel_fees: $directional_info.fees,
633 next_hops_fee_msat: u64::max_value(),
634 hop_use_fee_msat: u64::max_value(),
635 total_fee_msat: u64::max_value(),
636 htlc_minimum_msat: $directional_info.htlc_minimum_msat,
637 path_htlc_minimum_msat,
638 was_processed: false,
639 #[cfg(any(test, feature = "fuzztarget"))]
640 value_contribution_msat,
644 #[allow(unused_mut)] // We only use the mut in cfg(test)
645 let mut should_process = !old_entry.was_processed;
646 #[cfg(any(test, feature = "fuzztarget"))]
648 // In test/fuzzing builds, we do extra checks to make sure the skipping
649 // of already-seen nodes only happens in cases we expect (see below).
650 if !should_process { should_process = true; }
654 let mut hop_use_fee_msat = 0;
655 let mut total_fee_msat = $next_hops_fee_msat;
657 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
658 // will have the same effective-fee
659 if $src_node_id != *our_node_id {
660 match compute_fees(amount_to_transfer_over_msat, $directional_info.fees) {
661 // max_value means we'll always fail
662 // the old_entry.total_fee_msat > total_fee_msat check
663 None => total_fee_msat = u64::max_value(),
665 hop_use_fee_msat = fee_msat;
666 total_fee_msat += hop_use_fee_msat;
667 // When calculating the lowest inbound fees to a node, we
668 // calculate fees here not based on the actual value we think
669 // will flow over this channel, but on the minimum value that
670 // we'll accept flowing over it. The minimum accepted value
671 // is a constant through each path collection run, ensuring
672 // consistent basis. Otherwise we may later find a
673 // different path to the source node that is more expensive,
674 // but which we consider to be cheaper because we are capacity
675 // constrained and the relative fee becomes lower.
676 match compute_fees(minimal_value_contribution_msat, old_entry.src_lowest_inbound_fees)
677 .map(|a| a.checked_add(total_fee_msat)) {
682 total_fee_msat = u64::max_value();
689 let new_graph_node = RouteGraphNode {
690 pubkey: $src_node_id,
691 lowest_fee_to_peer_through_node: total_fee_msat,
692 lowest_fee_to_node: $next_hops_fee_msat as u64 + hop_use_fee_msat,
693 value_contribution_msat: value_contribution_msat,
694 path_htlc_minimum_msat,
697 // Update the way of reaching $src_node_id with the given $chan_id (from $dest_node_id),
698 // if this way is cheaper than the already known
699 // (considering the cost to "reach" this channel from the route destination,
700 // the cost of using this channel,
701 // and the cost of routing to the source node of this channel).
702 // Also, consider that htlc_minimum_msat_difference, because we might end up
703 // paying it. Consider the following exploit:
704 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
705 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
706 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
707 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
709 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
710 // but it may require additional tracking - we don't want to double-count
711 // the fees included in $next_hops_path_htlc_minimum_msat, but also
712 // can't use something that may decrease on future hops.
713 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat);
714 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat);
716 if !old_entry.was_processed && new_cost < old_cost {
717 targets.push(new_graph_node);
718 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
719 old_entry.hop_use_fee_msat = hop_use_fee_msat;
720 old_entry.total_fee_msat = total_fee_msat;
721 old_entry.pubkey = $dest_node_id.clone();
722 old_entry.short_channel_id = $chan_id.clone();
723 old_entry.channel_features = $chan_features;
724 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
725 old_entry.cltv_expiry_delta = $directional_info.cltv_expiry_delta as u32;
726 old_entry.channel_fees = $directional_info.fees;
727 old_entry.htlc_minimum_msat = $directional_info.htlc_minimum_msat;
728 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
729 #[cfg(any(test, feature = "fuzztarget"))]
731 old_entry.value_contribution_msat = value_contribution_msat;
733 did_add_update_path_to_src_node = true;
734 } else if old_entry.was_processed && new_cost < old_cost {
735 #[cfg(any(test, feature = "fuzztarget"))]
737 // If we're skipping processing a node which was previously
738 // processed even though we found another path to it with a
739 // cheaper fee, check that it was because the second path we
740 // found (which we are processing now) has a lower value
741 // contribution due to an HTLC minimum limit.
743 // e.g. take a graph with two paths from node 1 to node 2, one
744 // through channel A, and one through channel B. Channel A and
745 // B are both in the to-process heap, with their scores set by
746 // a higher htlc_minimum than fee.
747 // Channel A is processed first, and the channels onwards from
748 // node 1 are added to the to-process heap. Thereafter, we pop
749 // Channel B off of the heap, note that it has a much more
750 // restrictive htlc_maximum_msat, and recalculate the fees for
751 // all of node 1's channels using the new, reduced, amount.
753 // This would be bogus - we'd be selecting a higher-fee path
754 // with a lower htlc_maximum_msat instead of the one we'd
755 // already decided to use.
756 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
757 debug_assert!(value_contribution_msat < old_entry.value_contribution_msat);
764 did_add_update_path_to_src_node
768 let empty_node_features = NodeFeatures::empty();
769 // Find ways (channels with destination) to reach a given node and store them
770 // in the corresponding data structures (routing graph etc).
771 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
772 // meaning how much will be paid in fees after this node (to the best of our knowledge).
773 // This data can later be helpful to optimize routing (pay lower fees).
774 macro_rules! add_entries_to_cheapest_to_target_node {
775 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr, $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr ) => {
776 let skip_node = if let Some(elem) = dist.get_mut($node_id) {
777 let was_processed = elem.was_processed;
778 elem.was_processed = true;
781 // Entries are added to dist in add_entry!() when there is a channel from a node.
782 // Because there are no channels from payee, it will not have a dist entry at this point.
783 // If we're processing any other node, it is always be the result of a channel from it.
784 assert_eq!($node_id, payee);
789 if first_hops.is_some() {
790 if let Some(&(ref first_hop, ref features, ref outbound_capacity_msat, _)) = first_hop_targets.get(&$node_id) {
791 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);
795 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
801 if !features.requires_unknown_bits() {
802 for chan_id in $node.channels.iter() {
803 let chan = network.get_channels().get(chan_id).unwrap();
804 if !chan.features.requires_unknown_bits() {
805 if chan.node_one == *$node_id {
806 // ie $node is one, ie next hop in A* is two, via the two_to_one channel
807 if first_hops.is_none() || chan.node_two != *our_node_id {
808 if let Some(two_to_one) = chan.two_to_one.as_ref() {
809 if two_to_one.enabled {
810 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);
815 if first_hops.is_none() || chan.node_one != *our_node_id {
816 if let Some(one_to_two) = chan.one_to_two.as_ref() {
817 if one_to_two.enabled {
818 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);
830 let mut payment_paths = Vec::<PaymentPath>::new();
832 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
833 'paths_collection: loop {
834 // For every new path, start from scratch, except
835 // bookkeeped_channels_liquidity_available_msat, which will improve
836 // the further iterations of path finding. Also don't erase first_hop_targets.
839 hit_minimum_limit = false;
841 // If first hop is a private channel and the only way to reach the payee, this is the only
842 // place where it could be added.
843 if first_hops.is_some() {
844 if let Some(&(ref first_hop, ref features, ref outbound_capacity_msat, _)) = first_hop_targets.get(&payee) {
845 add_entry!(first_hop, *our_node_id, payee, dummy_directional_info, Some(outbound_capacity_msat / 1000), features, 0, path_value_msat, 0);
849 // Add the payee as a target, so that the payee-to-payer
850 // search algorithm knows what to start with.
851 match network.get_nodes().get(payee) {
852 // The payee is not in our network graph, so nothing to add here.
853 // There is still a chance of reaching them via last_hops though,
854 // so don't yet fail the payment here.
855 // If not, targets.pop() will not even let us enter the loop in step 2.
858 add_entries_to_cheapest_to_target_node!(node, payee, 0, path_value_msat, 0);
863 // If a caller provided us with last hops, add them to routing targets. Since this happens
864 // earlier than general path finding, they will be somewhat prioritized, although currently
865 // it matters only if the fees are exactly the same.
866 for hop in last_hops.iter() {
867 let have_hop_src_in_graph =
868 // Only add the last hop to our candidate set if either we have a direct channel or
869 // they are in the regular network graph.
870 first_hop_targets.get(&hop.src_node_id).is_some() ||
871 network.get_nodes().get(&hop.src_node_id).is_some();
872 if have_hop_src_in_graph {
873 // BOLT 11 doesn't allow inclusion of features for the last hop hints, which
874 // really sucks, cause we're gonna need that eventually.
875 let last_hop_htlc_minimum_msat: u64 = match hop.htlc_minimum_msat {
876 Some(htlc_minimum_msat) => htlc_minimum_msat,
879 let directional_info = DummyDirectionalChannelInfo {
880 cltv_expiry_delta: hop.cltv_expiry_delta as u32,
881 htlc_minimum_msat: last_hop_htlc_minimum_msat,
882 htlc_maximum_msat: hop.htlc_maximum_msat,
885 if add_entry!(hop.short_channel_id, hop.src_node_id, payee, directional_info, None::<u64>, &empty_channel_features, 0, path_value_msat, 0) {
886 // If this hop connects to a node with which we have a direct channel,
887 // ignore the network graph and, if the last hop was added, add our
888 // direct channel to the candidate set.
890 // Note that we *must* check if the last hop was added as `add_entry`
891 // always assumes that the third argument is a node to which we have a
893 if let Some(&(ref first_hop, ref features, ref outbound_capacity_msat, _)) = first_hop_targets.get(&hop.src_node_id) {
894 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);
900 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
902 // At this point, targets are filled with the data from first and
903 // last hops communicated by the caller, and the payment receiver.
904 let mut found_new_path = false;
907 // If this loop terminates due the exhaustion of targets, two situations are possible:
908 // - not enough outgoing liquidity:
909 // 0 < already_collected_value_msat < final_value_msat
910 // - enough outgoing liquidity:
911 // final_value_msat <= already_collected_value_msat < recommended_value_msat
912 // Both these cases (and other cases except reaching recommended_value_msat) mean that
913 // paths_collection will be stopped because found_new_path==false.
914 // This is not necessarily a routing failure.
915 'path_construction: while let Some(RouteGraphNode { pubkey, lowest_fee_to_node, value_contribution_msat, path_htlc_minimum_msat, .. }) = targets.pop() {
917 // Since we're going payee-to-payer, hitting our node as a target means we should stop
918 // traversing the graph and arrange the path out of what we found.
919 if pubkey == *our_node_id {
920 let mut new_entry = dist.remove(&our_node_id).unwrap();
921 let mut ordered_hops = vec!((new_entry.clone(), NodeFeatures::empty()));
924 if let Some(&(_, _, _, ref features)) = first_hop_targets.get(&ordered_hops.last().unwrap().0.pubkey) {
925 ordered_hops.last_mut().unwrap().1 = features.clone();
926 } else if let Some(node) = network.get_nodes().get(&ordered_hops.last().unwrap().0.pubkey) {
927 if let Some(node_info) = node.announcement_info.as_ref() {
928 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
930 ordered_hops.last_mut().unwrap().1 = NodeFeatures::empty();
933 // We should be able to fill in features for everything except the last
934 // hop, if the last hop was provided via a BOLT 11 invoice (though we
935 // should be able to extend it further as BOLT 11 does have feature
936 // flags for the last hop node itself).
937 assert!(ordered_hops.last().unwrap().0.pubkey == *payee);
940 // Means we succesfully traversed from the payer to the payee, now
941 // save this path for the payment route. Also, update the liquidity
942 // remaining on the used hops, so that we take them into account
943 // while looking for more paths.
944 if ordered_hops.last().unwrap().0.pubkey == *payee {
948 new_entry = match dist.remove(&ordered_hops.last().unwrap().0.pubkey) {
949 Some(payment_hop) => payment_hop,
950 // We can't arrive at None because, if we ever add an entry to targets,
951 // we also fill in the entry in dist (see add_entry!).
952 None => unreachable!(),
954 // We "propagate" the fees one hop backward (topologically) here,
955 // so that fees paid for a HTLC forwarding on the current channel are
956 // associated with the previous channel (where they will be subtracted).
957 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
958 ordered_hops.last_mut().unwrap().0.cltv_expiry_delta = new_entry.cltv_expiry_delta;
959 ordered_hops.push((new_entry.clone(), NodeFeatures::empty()));
961 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
962 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
963 ordered_hops.last_mut().unwrap().0.cltv_expiry_delta = final_cltv;
965 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: {:?}",
966 ordered_hops.len(), value_contribution_msat, ordered_hops);
968 let mut payment_path = PaymentPath {hops: ordered_hops};
970 // We could have possibly constructed a slightly inconsistent path: since we reduce
971 // value being transferred along the way, we could have violated htlc_minimum_msat
972 // on some channels we already passed (assuming dest->source direction). Here, we
973 // recompute the fees again, so that if that's the case, we match the currently
974 // underpaid htlc_minimum_msat with fees.
975 payment_path.update_value_and_recompute_fees(cmp::min(value_contribution_msat, final_value_msat));
977 // Since a path allows to transfer as much value as
978 // the smallest channel it has ("bottleneck"), we should recompute
979 // the fees so sender HTLC don't overpay fees when traversing
980 // larger channels than the bottleneck. This may happen because
981 // when we were selecting those channels we were not aware how much value
982 // this path will transfer, and the relative fee for them
983 // might have been computed considering a larger value.
984 // Remember that we used these channels so that we don't rely
985 // on the same liquidity in future paths.
986 let mut prevented_redundant_path_selection = false;
987 for (payment_hop, _) in payment_path.hops.iter() {
988 let channel_liquidity_available_msat = bookkeeped_channels_liquidity_available_msat.get_mut(&payment_hop.short_channel_id).unwrap();
989 let mut spent_on_hop_msat = value_contribution_msat;
990 let next_hops_fee_msat = payment_hop.next_hops_fee_msat;
991 spent_on_hop_msat += next_hops_fee_msat;
992 if spent_on_hop_msat == *channel_liquidity_available_msat {
993 // If this path used all of this channel's available liquidity, we know
994 // this path will not be selected again in the next loop iteration.
995 prevented_redundant_path_selection = true;
997 *channel_liquidity_available_msat -= spent_on_hop_msat;
999 if !prevented_redundant_path_selection {
1000 // If we weren't capped by hitting a liquidity limit on a channel in the path,
1001 // we'll probably end up picking the same path again on the next iteration.
1002 // Decrease the available liquidity of a hop in the middle of the path.
1003 let victim_scid = payment_path.hops[(payment_path.hops.len() - 1) / 2].0.short_channel_id;
1004 log_trace!(logger, "Disabling channel {} for future path building iterations to avoid duplicates.", victim_scid);
1005 let victim_liquidity = bookkeeped_channels_liquidity_available_msat.get_mut(&victim_scid).unwrap();
1006 *victim_liquidity = 0;
1009 // Track the total amount all our collected paths allow to send so that we:
1010 // - know when to stop looking for more paths
1011 // - know which of the hops are useless considering how much more sats we need
1012 // (contributes_sufficient_value)
1013 already_collected_value_msat += value_contribution_msat;
1015 payment_paths.push(payment_path);
1016 found_new_path = true;
1017 break 'path_construction;
1020 // If we found a path back to the payee, we shouldn't try to process it again. This is
1021 // the equivalent of the `elem.was_processed` check in
1022 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
1023 if pubkey == *payee { continue 'path_construction; }
1025 // Otherwise, since the current target node is not us,
1026 // keep "unrolling" the payment graph from payee to payer by
1027 // finding a way to reach the current target from the payer side.
1028 match network.get_nodes().get(&pubkey) {
1031 add_entries_to_cheapest_to_target_node!(node, &pubkey, lowest_fee_to_node, value_contribution_msat, path_htlc_minimum_msat);
1037 // If we don't support MPP, no use trying to gather more value ever.
1038 break 'paths_collection;
1042 // Stop either when the recommended value is reached or if no new path was found in this
1044 // In the latter case, making another path finding attempt won't help,
1045 // because we deterministically terminated the search due to low liquidity.
1046 if already_collected_value_msat >= recommended_value_msat || !found_new_path {
1047 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
1048 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
1049 break 'paths_collection;
1050 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
1051 // Further, if this was our first walk of the graph, and we weren't limited by an
1052 // htlc_minimum_msat, return immediately because this path should suffice. If we were
1053 // limited by an htlc_minimum_msat value, find another path with a higher value,
1054 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
1055 // still keeping a lower total fee than this path.
1056 if !hit_minimum_limit {
1057 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
1058 break 'paths_collection;
1060 log_trace!(logger, "Collected our payment amount on the first pass, but running again to collect extra paths with a potentially higher limit.");
1061 path_value_msat = recommended_value_msat;
1066 if payment_paths.len() == 0 {
1067 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1070 if already_collected_value_msat < final_value_msat {
1071 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1074 // Sort by total fees and take the best paths.
1075 payment_paths.sort_by_key(|path| path.get_total_fee_paid_msat());
1076 if payment_paths.len() > 50 {
1077 payment_paths.truncate(50);
1080 // Draw multiple sufficient routes by randomly combining the selected paths.
1081 let mut drawn_routes = Vec::new();
1082 for i in 0..payment_paths.len() {
1083 let mut cur_route = Vec::<PaymentPath>::new();
1084 let mut aggregate_route_value_msat = 0;
1087 // TODO: real random shuffle
1088 // Currently just starts with i_th and goes up to i-1_th in a looped way.
1089 let cur_payment_paths = [&payment_paths[i..], &payment_paths[..i]].concat();
1092 for payment_path in cur_payment_paths {
1093 cur_route.push(payment_path.clone());
1094 aggregate_route_value_msat += payment_path.get_value_msat();
1095 if aggregate_route_value_msat > final_value_msat {
1096 // Last path likely overpaid. Substract it from the most expensive
1097 // (in terms of proportional fee) path in this route and recompute fees.
1098 // This might be not the most economically efficient way, but fewer paths
1099 // also makes routing more reliable.
1100 let mut overpaid_value_msat = aggregate_route_value_msat - final_value_msat;
1102 // First, drop some expensive low-value paths entirely if possible.
1103 // Sort by value so that we drop many really-low values first, since
1104 // fewer paths is better: the payment is less likely to fail.
1105 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1106 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1107 cur_route.sort_by_key(|path| path.get_value_msat());
1108 // We should make sure that at least 1 path left.
1109 let mut paths_left = cur_route.len();
1110 cur_route.retain(|path| {
1111 if paths_left == 1 {
1114 let mut keep = true;
1115 let path_value_msat = path.get_value_msat();
1116 if path_value_msat <= overpaid_value_msat {
1118 overpaid_value_msat -= path_value_msat;
1124 if overpaid_value_msat == 0 {
1128 assert!(cur_route.len() > 0);
1131 // Now, substract the overpaid value from the most-expensive path.
1132 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1133 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1134 cur_route.sort_by_key(|path| { path.hops.iter().map(|hop| hop.0.channel_fees.proportional_millionths as u64).sum::<u64>() });
1135 let expensive_payment_path = cur_route.first_mut().unwrap();
1136 // We already dropped all the small channels above, meaning all the
1137 // remaining channels are larger than remaining overpaid_value_msat.
1138 // Thus, this can't be negative.
1139 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
1140 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
1144 drawn_routes.push(cur_route);
1148 // Select the best route by lowest total fee.
1149 drawn_routes.sort_by_key(|paths| paths.iter().map(|path| path.get_total_fee_paid_msat()).sum::<u64>());
1150 let mut selected_paths = Vec::<Vec<RouteHop>>::new();
1151 for payment_path in drawn_routes.first().unwrap() {
1152 selected_paths.push(payment_path.hops.iter().map(|(payment_hop, node_features)| {
1154 pubkey: payment_hop.pubkey,
1155 node_features: node_features.clone(),
1156 short_channel_id: payment_hop.short_channel_id,
1157 channel_features: payment_hop.channel_features.clone(),
1158 fee_msat: payment_hop.fee_msat,
1159 cltv_expiry_delta: payment_hop.cltv_expiry_delta,
1164 if let Some(features) = &payee_features {
1165 for path in selected_paths.iter_mut() {
1166 path.last_mut().unwrap().node_features = features.to_context();
1170 let route = Route { paths: selected_paths };
1171 log_info!(logger, "Got route to {}: {}", payee, log_route!(route));
1177 use routing::router::{get_route, Route, RouteHint, RouteHintHop, RoutingFees};
1178 use routing::network_graph::{NetworkGraph, NetGraphMsgHandler};
1179 use chain::transaction::OutPoint;
1180 use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
1181 use ln::msgs::{ErrorAction, LightningError, OptionalField, UnsignedChannelAnnouncement, ChannelAnnouncement, RoutingMessageHandler,
1182 NodeAnnouncement, UnsignedNodeAnnouncement, ChannelUpdate, UnsignedChannelUpdate};
1183 use ln::channelmanager;
1184 use util::test_utils;
1185 use util::ser::Writeable;
1187 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
1188 use bitcoin::hashes::Hash;
1189 use bitcoin::network::constants::Network;
1190 use bitcoin::blockdata::constants::genesis_block;
1191 use bitcoin::blockdata::script::Builder;
1192 use bitcoin::blockdata::opcodes;
1193 use bitcoin::blockdata::transaction::TxOut;
1197 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
1198 use bitcoin::secp256k1::{Secp256k1, All};
1203 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
1204 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
1205 channelmanager::ChannelDetails {
1206 channel_id: [0; 32],
1207 counterparty: channelmanager::ChannelCounterparty {
1210 unspendable_punishment_reserve: 0,
1211 forwarding_info: None,
1213 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
1215 channel_value_satoshis: 0,
1217 outbound_capacity_msat,
1218 inbound_capacity_msat: 42,
1219 unspendable_punishment_reserve: None,
1220 confirmations_required: None,
1221 force_close_spend_delay: None,
1222 is_outbound: true, is_funding_locked: true,
1223 is_usable: true, is_public: true,
1227 // Using the same keys for LN and BTC ids
1228 fn add_channel(net_graph_msg_handler: &NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>, secp_ctx: &Secp256k1<All>, node_1_privkey: &SecretKey,
1229 node_2_privkey: &SecretKey, features: ChannelFeatures, short_channel_id: u64) {
1230 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1231 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1233 let unsigned_announcement = UnsignedChannelAnnouncement {
1235 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1239 bitcoin_key_1: node_id_1,
1240 bitcoin_key_2: node_id_2,
1241 excess_data: Vec::new(),
1244 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1245 let valid_announcement = ChannelAnnouncement {
1246 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1247 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1248 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1249 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1250 contents: unsigned_announcement.clone(),
1252 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1253 Ok(res) => assert!(res),
1258 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) {
1259 let msghash = hash_to_message!(&Sha256dHash::hash(&update.encode()[..])[..]);
1260 let valid_channel_update = ChannelUpdate {
1261 signature: secp_ctx.sign(&msghash, node_privkey),
1262 contents: update.clone()
1265 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1266 Ok(res) => assert!(res),
1271 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,
1272 features: NodeFeatures, timestamp: u32) {
1273 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
1274 let unsigned_announcement = UnsignedNodeAnnouncement {
1280 addresses: Vec::new(),
1281 excess_address_data: Vec::new(),
1282 excess_data: Vec::new(),
1284 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1285 let valid_announcement = NodeAnnouncement {
1286 signature: secp_ctx.sign(&msghash, node_privkey),
1287 contents: unsigned_announcement.clone()
1290 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1296 fn get_nodes(secp_ctx: &Secp256k1<All>) -> (SecretKey, PublicKey, Vec<SecretKey>, Vec<PublicKey>) {
1297 let privkeys: Vec<SecretKey> = (2..10).map(|i| {
1298 SecretKey::from_slice(&hex::decode(format!("{:02}", i).repeat(32)).unwrap()[..]).unwrap()
1301 let pubkeys = privkeys.iter().map(|secret| PublicKey::from_secret_key(&secp_ctx, secret)).collect();
1303 let our_privkey = SecretKey::from_slice(&hex::decode("01".repeat(32)).unwrap()[..]).unwrap();
1304 let our_id = PublicKey::from_secret_key(&secp_ctx, &our_privkey);
1306 (our_privkey, our_id, privkeys, pubkeys)
1309 fn id_to_feature_flags(id: u8) -> Vec<u8> {
1310 // Set the feature flags to the id'th odd (ie non-required) feature bit so that we can
1311 // test for it later.
1312 let idx = (id - 1) * 2 + 1;
1314 vec![1 << (idx - 8*3), 0, 0, 0]
1315 } else if idx > 8*2 {
1316 vec![1 << (idx - 8*2), 0, 0]
1317 } else if idx > 8*1 {
1318 vec![1 << (idx - 8*1), 0]
1324 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>) {
1325 let secp_ctx = Secp256k1::new();
1326 let logger = Arc::new(test_utils::TestLogger::new());
1327 let chain_monitor = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1328 let net_graph_msg_handler = NetGraphMsgHandler::new(genesis_block(Network::Testnet).header.block_hash(), None, Arc::clone(&logger));
1329 // Build network from our_id to node7:
1331 // -1(1)2- node0 -1(3)2-
1333 // our_id -1(12)2- node7 -1(13)2--- node2
1335 // -1(2)2- node1 -1(4)2-
1338 // chan1 1-to-2: disabled
1339 // chan1 2-to-1: enabled, 0 fee
1341 // chan2 1-to-2: enabled, ignored fee
1342 // chan2 2-to-1: enabled, 0 fee
1344 // chan3 1-to-2: enabled, 0 fee
1345 // chan3 2-to-1: enabled, 100 msat fee
1347 // chan4 1-to-2: enabled, 100% fee
1348 // chan4 2-to-1: enabled, 0 fee
1350 // chan12 1-to-2: enabled, ignored fee
1351 // chan12 2-to-1: enabled, 0 fee
1353 // chan13 1-to-2: enabled, 200% fee
1354 // chan13 2-to-1: enabled, 0 fee
1357 // -1(5)2- node3 -1(8)2--
1361 // node2--1(6)2- node4 -1(9)2--- node6 (not in global route map)
1363 // -1(7)2- node5 -1(10)2-
1365 // chan5 1-to-2: enabled, 100 msat fee
1366 // chan5 2-to-1: enabled, 0 fee
1368 // chan6 1-to-2: enabled, 0 fee
1369 // chan6 2-to-1: enabled, 0 fee
1371 // chan7 1-to-2: enabled, 100% fee
1372 // chan7 2-to-1: enabled, 0 fee
1374 // chan8 1-to-2: enabled, variable fee (0 then 1000 msat)
1375 // chan8 2-to-1: enabled, 0 fee
1377 // chan9 1-to-2: enabled, 1001 msat fee
1378 // chan9 2-to-1: enabled, 0 fee
1380 // chan10 1-to-2: enabled, 0 fee
1381 // chan10 2-to-1: enabled, 0 fee
1383 // chan11 1-to-2: enabled, 0 fee
1384 // chan11 2-to-1: enabled, 0 fee
1386 let (our_privkey, _, privkeys, _) = get_nodes(&secp_ctx);
1388 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[0], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
1389 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1390 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1391 short_channel_id: 1,
1394 cltv_expiry_delta: 0,
1395 htlc_minimum_msat: 0,
1396 htlc_maximum_msat: OptionalField::Absent,
1398 fee_proportional_millionths: 0,
1399 excess_data: Vec::new()
1402 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
1404 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
1405 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1406 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1407 short_channel_id: 2,
1410 cltv_expiry_delta: u16::max_value(),
1411 htlc_minimum_msat: 0,
1412 htlc_maximum_msat: OptionalField::Absent,
1413 fee_base_msat: u32::max_value(),
1414 fee_proportional_millionths: u32::max_value(),
1415 excess_data: Vec::new()
1417 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1418 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1419 short_channel_id: 2,
1422 cltv_expiry_delta: 0,
1423 htlc_minimum_msat: 0,
1424 htlc_maximum_msat: OptionalField::Absent,
1426 fee_proportional_millionths: 0,
1427 excess_data: Vec::new()
1430 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
1432 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[7], ChannelFeatures::from_le_bytes(id_to_feature_flags(12)), 12);
1433 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1434 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1435 short_channel_id: 12,
1438 cltv_expiry_delta: u16::max_value(),
1439 htlc_minimum_msat: 0,
1440 htlc_maximum_msat: OptionalField::Absent,
1441 fee_base_msat: u32::max_value(),
1442 fee_proportional_millionths: u32::max_value(),
1443 excess_data: Vec::new()
1445 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1446 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1447 short_channel_id: 12,
1450 cltv_expiry_delta: 0,
1451 htlc_minimum_msat: 0,
1452 htlc_maximum_msat: OptionalField::Absent,
1454 fee_proportional_millionths: 0,
1455 excess_data: Vec::new()
1458 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], NodeFeatures::from_le_bytes(id_to_feature_flags(8)), 0);
1460 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
1461 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1462 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1463 short_channel_id: 3,
1466 cltv_expiry_delta: (3 << 8) | 1,
1467 htlc_minimum_msat: 0,
1468 htlc_maximum_msat: OptionalField::Absent,
1470 fee_proportional_millionths: 0,
1471 excess_data: Vec::new()
1473 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1474 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1475 short_channel_id: 3,
1478 cltv_expiry_delta: (3 << 8) | 2,
1479 htlc_minimum_msat: 0,
1480 htlc_maximum_msat: OptionalField::Absent,
1482 fee_proportional_millionths: 0,
1483 excess_data: Vec::new()
1486 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
1487 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1488 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1489 short_channel_id: 4,
1492 cltv_expiry_delta: (4 << 8) | 1,
1493 htlc_minimum_msat: 0,
1494 htlc_maximum_msat: OptionalField::Absent,
1496 fee_proportional_millionths: 1000000,
1497 excess_data: Vec::new()
1499 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1500 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1501 short_channel_id: 4,
1504 cltv_expiry_delta: (4 << 8) | 2,
1505 htlc_minimum_msat: 0,
1506 htlc_maximum_msat: OptionalField::Absent,
1508 fee_proportional_millionths: 0,
1509 excess_data: Vec::new()
1512 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(13)), 13);
1513 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1514 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1515 short_channel_id: 13,
1518 cltv_expiry_delta: (13 << 8) | 1,
1519 htlc_minimum_msat: 0,
1520 htlc_maximum_msat: OptionalField::Absent,
1522 fee_proportional_millionths: 2000000,
1523 excess_data: Vec::new()
1525 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1526 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1527 short_channel_id: 13,
1530 cltv_expiry_delta: (13 << 8) | 2,
1531 htlc_minimum_msat: 0,
1532 htlc_maximum_msat: OptionalField::Absent,
1534 fee_proportional_millionths: 0,
1535 excess_data: Vec::new()
1538 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
1540 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
1541 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1542 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1543 short_channel_id: 6,
1546 cltv_expiry_delta: (6 << 8) | 1,
1547 htlc_minimum_msat: 0,
1548 htlc_maximum_msat: OptionalField::Absent,
1550 fee_proportional_millionths: 0,
1551 excess_data: Vec::new()
1553 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1554 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1555 short_channel_id: 6,
1558 cltv_expiry_delta: (6 << 8) | 2,
1559 htlc_minimum_msat: 0,
1560 htlc_maximum_msat: OptionalField::Absent,
1562 fee_proportional_millionths: 0,
1563 excess_data: Vec::new(),
1566 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(11)), 11);
1567 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1568 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1569 short_channel_id: 11,
1572 cltv_expiry_delta: (11 << 8) | 1,
1573 htlc_minimum_msat: 0,
1574 htlc_maximum_msat: OptionalField::Absent,
1576 fee_proportional_millionths: 0,
1577 excess_data: Vec::new()
1579 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
1580 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1581 short_channel_id: 11,
1584 cltv_expiry_delta: (11 << 8) | 2,
1585 htlc_minimum_msat: 0,
1586 htlc_maximum_msat: OptionalField::Absent,
1588 fee_proportional_millionths: 0,
1589 excess_data: Vec::new()
1592 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(5)), 0);
1594 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
1596 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[5], ChannelFeatures::from_le_bytes(id_to_feature_flags(7)), 7);
1597 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1598 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1599 short_channel_id: 7,
1602 cltv_expiry_delta: (7 << 8) | 1,
1603 htlc_minimum_msat: 0,
1604 htlc_maximum_msat: OptionalField::Absent,
1606 fee_proportional_millionths: 1000000,
1607 excess_data: Vec::new()
1609 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[5], UnsignedChannelUpdate {
1610 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1611 short_channel_id: 7,
1614 cltv_expiry_delta: (7 << 8) | 2,
1615 htlc_minimum_msat: 0,
1616 htlc_maximum_msat: OptionalField::Absent,
1618 fee_proportional_millionths: 0,
1619 excess_data: Vec::new()
1622 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[5], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
1624 (secp_ctx, net_graph_msg_handler, chain_monitor, logger)
1628 fn simple_route_test() {
1629 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1630 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1632 // Simple route to 2 via 1
1634 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)) {
1635 assert_eq!(err, "Cannot send a payment of 0 msat");
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);
1641 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
1642 assert_eq!(route.paths[0][0].short_channel_id, 2);
1643 assert_eq!(route.paths[0][0].fee_msat, 100);
1644 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
1645 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
1646 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
1648 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1649 assert_eq!(route.paths[0][1].short_channel_id, 4);
1650 assert_eq!(route.paths[0][1].fee_msat, 100);
1651 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1652 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1653 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
1657 fn invalid_first_hop_test() {
1658 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1659 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1661 // Simple route to 2 via 1
1663 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
1665 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)) {
1666 assert_eq!(err, "First hop cannot have our_node_id as a destination.");
1667 } else { panic!(); }
1669 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();
1670 assert_eq!(route.paths[0].len(), 2);
1674 fn htlc_minimum_test() {
1675 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1676 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1678 // Simple route to 2 via 1
1680 // Disable other paths
1681 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1682 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1683 short_channel_id: 12,
1685 flags: 2, // to disable
1686 cltv_expiry_delta: 0,
1687 htlc_minimum_msat: 0,
1688 htlc_maximum_msat: OptionalField::Absent,
1690 fee_proportional_millionths: 0,
1691 excess_data: Vec::new()
1693 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1694 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1695 short_channel_id: 3,
1697 flags: 2, // to disable
1698 cltv_expiry_delta: 0,
1699 htlc_minimum_msat: 0,
1700 htlc_maximum_msat: OptionalField::Absent,
1702 fee_proportional_millionths: 0,
1703 excess_data: Vec::new()
1705 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1706 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1707 short_channel_id: 13,
1709 flags: 2, // to disable
1710 cltv_expiry_delta: 0,
1711 htlc_minimum_msat: 0,
1712 htlc_maximum_msat: OptionalField::Absent,
1714 fee_proportional_millionths: 0,
1715 excess_data: Vec::new()
1717 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1718 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1719 short_channel_id: 6,
1721 flags: 2, // to disable
1722 cltv_expiry_delta: 0,
1723 htlc_minimum_msat: 0,
1724 htlc_maximum_msat: OptionalField::Absent,
1726 fee_proportional_millionths: 0,
1727 excess_data: Vec::new()
1729 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1730 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1731 short_channel_id: 7,
1733 flags: 2, // to disable
1734 cltv_expiry_delta: 0,
1735 htlc_minimum_msat: 0,
1736 htlc_maximum_msat: OptionalField::Absent,
1738 fee_proportional_millionths: 0,
1739 excess_data: Vec::new()
1742 // Check against amount_to_transfer_over_msat.
1743 // Set minimal HTLC of 200_000_000 msat.
1744 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1745 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1746 short_channel_id: 2,
1749 cltv_expiry_delta: 0,
1750 htlc_minimum_msat: 200_000_000,
1751 htlc_maximum_msat: OptionalField::Absent,
1753 fee_proportional_millionths: 0,
1754 excess_data: Vec::new()
1757 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
1759 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1760 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1761 short_channel_id: 4,
1764 cltv_expiry_delta: 0,
1765 htlc_minimum_msat: 0,
1766 htlc_maximum_msat: OptionalField::Present(199_999_999),
1768 fee_proportional_millionths: 0,
1769 excess_data: Vec::new()
1772 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
1773 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)) {
1774 assert_eq!(err, "Failed to find a path to the given destination");
1775 } else { panic!(); }
1777 // Lift the restriction on the first hop.
1778 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1779 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1780 short_channel_id: 2,
1783 cltv_expiry_delta: 0,
1784 htlc_minimum_msat: 0,
1785 htlc_maximum_msat: OptionalField::Absent,
1787 fee_proportional_millionths: 0,
1788 excess_data: Vec::new()
1791 // A payment above the minimum should pass
1792 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();
1793 assert_eq!(route.paths[0].len(), 2);
1797 fn htlc_minimum_overpay_test() {
1798 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1799 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1801 // A route to node#2 via two paths.
1802 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
1803 // Thus, they can't send 60 without overpaying.
1804 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1805 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1806 short_channel_id: 2,
1809 cltv_expiry_delta: 0,
1810 htlc_minimum_msat: 35_000,
1811 htlc_maximum_msat: OptionalField::Present(40_000),
1813 fee_proportional_millionths: 0,
1814 excess_data: Vec::new()
1816 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1817 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1818 short_channel_id: 12,
1821 cltv_expiry_delta: 0,
1822 htlc_minimum_msat: 35_000,
1823 htlc_maximum_msat: OptionalField::Present(40_000),
1825 fee_proportional_millionths: 0,
1826 excess_data: Vec::new()
1830 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1831 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1832 short_channel_id: 13,
1835 cltv_expiry_delta: 0,
1836 htlc_minimum_msat: 0,
1837 htlc_maximum_msat: OptionalField::Absent,
1839 fee_proportional_millionths: 0,
1840 excess_data: Vec::new()
1842 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1843 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1844 short_channel_id: 4,
1847 cltv_expiry_delta: 0,
1848 htlc_minimum_msat: 0,
1849 htlc_maximum_msat: OptionalField::Absent,
1851 fee_proportional_millionths: 0,
1852 excess_data: Vec::new()
1855 // Disable other paths
1856 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1857 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1858 short_channel_id: 1,
1860 flags: 2, // to disable
1861 cltv_expiry_delta: 0,
1862 htlc_minimum_msat: 0,
1863 htlc_maximum_msat: OptionalField::Absent,
1865 fee_proportional_millionths: 0,
1866 excess_data: Vec::new()
1869 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
1870 Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger)).unwrap();
1871 // Overpay fees to hit htlc_minimum_msat.
1872 let overpaid_fees = route.paths[0][0].fee_msat + route.paths[1][0].fee_msat;
1873 // TODO: this could be better balanced to overpay 10k and not 15k.
1874 assert_eq!(overpaid_fees, 15_000);
1876 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
1877 // while taking even more fee to match htlc_minimum_msat.
1878 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1879 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1880 short_channel_id: 12,
1883 cltv_expiry_delta: 0,
1884 htlc_minimum_msat: 65_000,
1885 htlc_maximum_msat: OptionalField::Present(80_000),
1887 fee_proportional_millionths: 0,
1888 excess_data: Vec::new()
1890 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1891 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1892 short_channel_id: 2,
1895 cltv_expiry_delta: 0,
1896 htlc_minimum_msat: 0,
1897 htlc_maximum_msat: OptionalField::Absent,
1899 fee_proportional_millionths: 0,
1900 excess_data: Vec::new()
1902 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1903 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1904 short_channel_id: 4,
1907 cltv_expiry_delta: 0,
1908 htlc_minimum_msat: 0,
1909 htlc_maximum_msat: OptionalField::Absent,
1911 fee_proportional_millionths: 100_000,
1912 excess_data: Vec::new()
1915 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
1916 Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger)).unwrap();
1917 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
1918 assert_eq!(route.paths.len(), 1);
1919 assert_eq!(route.paths[0][0].short_channel_id, 12);
1920 let fees = route.paths[0][0].fee_msat;
1921 assert_eq!(fees, 5_000);
1923 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
1924 Some(InvoiceFeatures::known()), None, &Vec::new(), 50_000, 42, Arc::clone(&logger)).unwrap();
1925 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
1926 // the other channel.
1927 assert_eq!(route.paths.len(), 1);
1928 assert_eq!(route.paths[0][0].short_channel_id, 2);
1929 let fees = route.paths[0][0].fee_msat;
1930 assert_eq!(fees, 5_000);
1934 fn disable_channels_test() {
1935 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1936 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1938 // // Disable channels 4 and 12 by flags=2
1939 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1940 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1941 short_channel_id: 4,
1943 flags: 2, // to disable
1944 cltv_expiry_delta: 0,
1945 htlc_minimum_msat: 0,
1946 htlc_maximum_msat: OptionalField::Absent,
1948 fee_proportional_millionths: 0,
1949 excess_data: Vec::new()
1951 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1952 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1953 short_channel_id: 12,
1955 flags: 2, // to disable
1956 cltv_expiry_delta: 0,
1957 htlc_minimum_msat: 0,
1958 htlc_maximum_msat: OptionalField::Absent,
1960 fee_proportional_millionths: 0,
1961 excess_data: Vec::new()
1964 // If all the channels require some features we don't understand, route should fail
1965 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)) {
1966 assert_eq!(err, "Failed to find a path to the given destination");
1967 } else { panic!(); }
1969 // If we specify a channel to node7, that overrides our local channel view and that gets used
1970 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
1971 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();
1972 assert_eq!(route.paths[0].len(), 2);
1974 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
1975 assert_eq!(route.paths[0][0].short_channel_id, 42);
1976 assert_eq!(route.paths[0][0].fee_msat, 200);
1977 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
1978 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
1979 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
1981 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1982 assert_eq!(route.paths[0][1].short_channel_id, 13);
1983 assert_eq!(route.paths[0][1].fee_msat, 100);
1984 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1985 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1986 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
1990 fn disable_node_test() {
1991 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1992 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1994 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
1995 let mut unknown_features = NodeFeatures::known();
1996 unknown_features.set_required_unknown_bits();
1997 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
1998 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
1999 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
2001 // If all nodes require some features we don't understand, route should fail
2002 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)) {
2003 assert_eq!(err, "Failed to find a path to the given destination");
2004 } else { panic!(); }
2006 // If we specify a channel to node7, that overrides our local channel view and that gets used
2007 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2008 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();
2009 assert_eq!(route.paths[0].len(), 2);
2011 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2012 assert_eq!(route.paths[0][0].short_channel_id, 42);
2013 assert_eq!(route.paths[0][0].fee_msat, 200);
2014 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
2015 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2016 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2018 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2019 assert_eq!(route.paths[0][1].short_channel_id, 13);
2020 assert_eq!(route.paths[0][1].fee_msat, 100);
2021 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2022 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2023 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2025 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
2026 // naively) assume that the user checked the feature bits on the invoice, which override
2027 // the node_announcement.
2031 fn our_chans_test() {
2032 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2033 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2035 // Route to 1 via 2 and 3 because our channel to 1 is disabled
2036 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();
2037 assert_eq!(route.paths[0].len(), 3);
2039 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2040 assert_eq!(route.paths[0][0].short_channel_id, 2);
2041 assert_eq!(route.paths[0][0].fee_msat, 200);
2042 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2043 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2044 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2046 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2047 assert_eq!(route.paths[0][1].short_channel_id, 4);
2048 assert_eq!(route.paths[0][1].fee_msat, 100);
2049 assert_eq!(route.paths[0][1].cltv_expiry_delta, (3 << 8) | 2);
2050 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2051 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2053 assert_eq!(route.paths[0][2].pubkey, nodes[0]);
2054 assert_eq!(route.paths[0][2].short_channel_id, 3);
2055 assert_eq!(route.paths[0][2].fee_msat, 100);
2056 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
2057 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(1));
2058 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(3));
2060 // If we specify a channel to node7, that overrides our local channel view and that gets used
2061 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2062 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();
2063 assert_eq!(route.paths[0].len(), 2);
2065 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2066 assert_eq!(route.paths[0][0].short_channel_id, 42);
2067 assert_eq!(route.paths[0][0].fee_msat, 200);
2068 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
2069 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2070 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2072 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2073 assert_eq!(route.paths[0][1].short_channel_id, 13);
2074 assert_eq!(route.paths[0][1].fee_msat, 100);
2075 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2076 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2077 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2080 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2081 let zero_fees = RoutingFees {
2083 proportional_millionths: 0,
2085 vec![RouteHint(vec![RouteHintHop {
2086 src_node_id: nodes[3].clone(),
2087 short_channel_id: 8,
2089 cltv_expiry_delta: (8 << 8) | 1,
2090 htlc_minimum_msat: None,
2091 htlc_maximum_msat: None,
2092 }]), RouteHint(vec![RouteHintHop {
2093 src_node_id: nodes[4].clone(),
2094 short_channel_id: 9,
2097 proportional_millionths: 0,
2099 cltv_expiry_delta: (9 << 8) | 1,
2100 htlc_minimum_msat: None,
2101 htlc_maximum_msat: None,
2102 }]), RouteHint(vec![RouteHintHop {
2103 src_node_id: nodes[5].clone(),
2104 short_channel_id: 10,
2106 cltv_expiry_delta: (10 << 8) | 1,
2107 htlc_minimum_msat: None,
2108 htlc_maximum_msat: None,
2113 fn last_hops_test() {
2114 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2115 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2117 // Simple test across 2, 3, 5, and 4 via a last_hop channel
2119 // First check that last hop can't have its source as the payee.
2120 let invalid_last_hop = RouteHint(vec![RouteHintHop {
2121 src_node_id: nodes[6],
2122 short_channel_id: 8,
2125 proportional_millionths: 0,
2127 cltv_expiry_delta: (8 << 8) | 1,
2128 htlc_minimum_msat: None,
2129 htlc_maximum_msat: None,
2132 let mut invalid_last_hops = last_hops(&nodes);
2133 invalid_last_hops.push(invalid_last_hop);
2135 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)) {
2136 assert_eq!(err, "Last hop cannot have a payee as a source.");
2137 } else { panic!(); }
2140 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();
2141 assert_eq!(route.paths[0].len(), 5);
2143 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2144 assert_eq!(route.paths[0][0].short_channel_id, 2);
2145 assert_eq!(route.paths[0][0].fee_msat, 100);
2146 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2147 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2148 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2150 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2151 assert_eq!(route.paths[0][1].short_channel_id, 4);
2152 assert_eq!(route.paths[0][1].fee_msat, 0);
2153 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2154 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2155 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2157 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2158 assert_eq!(route.paths[0][2].short_channel_id, 6);
2159 assert_eq!(route.paths[0][2].fee_msat, 0);
2160 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2161 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2162 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2164 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2165 assert_eq!(route.paths[0][3].short_channel_id, 11);
2166 assert_eq!(route.paths[0][3].fee_msat, 0);
2167 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2168 // If we have a peer in the node map, we'll use their features here since we don't have
2169 // a way of figuring out their features from the invoice:
2170 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2171 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2173 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2174 assert_eq!(route.paths[0][4].short_channel_id, 8);
2175 assert_eq!(route.paths[0][4].fee_msat, 100);
2176 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2177 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2178 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2182 fn our_chans_last_hop_connect_test() {
2183 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2184 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2186 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
2187 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2188 let mut last_hops = last_hops(&nodes);
2189 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();
2190 assert_eq!(route.paths[0].len(), 2);
2192 assert_eq!(route.paths[0][0].pubkey, nodes[3]);
2193 assert_eq!(route.paths[0][0].short_channel_id, 42);
2194 assert_eq!(route.paths[0][0].fee_msat, 0);
2195 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
2196 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2197 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2199 assert_eq!(route.paths[0][1].pubkey, nodes[6]);
2200 assert_eq!(route.paths[0][1].short_channel_id, 8);
2201 assert_eq!(route.paths[0][1].fee_msat, 100);
2202 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2203 assert_eq!(route.paths[0][1].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2204 assert_eq!(route.paths[0][1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2206 last_hops[0].0[0].fees.base_msat = 1000;
2208 // Revert to via 6 as the fee on 8 goes up
2209 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();
2210 assert_eq!(route.paths[0].len(), 4);
2212 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2213 assert_eq!(route.paths[0][0].short_channel_id, 2);
2214 assert_eq!(route.paths[0][0].fee_msat, 200); // fee increased as its % of value transferred across node
2215 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2216 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2217 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2219 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2220 assert_eq!(route.paths[0][1].short_channel_id, 4);
2221 assert_eq!(route.paths[0][1].fee_msat, 100);
2222 assert_eq!(route.paths[0][1].cltv_expiry_delta, (7 << 8) | 1);
2223 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2224 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2226 assert_eq!(route.paths[0][2].pubkey, nodes[5]);
2227 assert_eq!(route.paths[0][2].short_channel_id, 7);
2228 assert_eq!(route.paths[0][2].fee_msat, 0);
2229 assert_eq!(route.paths[0][2].cltv_expiry_delta, (10 << 8) | 1);
2230 // If we have a peer in the node map, we'll use their features here since we don't have
2231 // a way of figuring out their features from the invoice:
2232 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
2233 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(7));
2235 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2236 assert_eq!(route.paths[0][3].short_channel_id, 10);
2237 assert_eq!(route.paths[0][3].fee_msat, 100);
2238 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2239 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2240 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2242 // ...but still use 8 for larger payments as 6 has a variable feerate
2243 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();
2244 assert_eq!(route.paths[0].len(), 5);
2246 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2247 assert_eq!(route.paths[0][0].short_channel_id, 2);
2248 assert_eq!(route.paths[0][0].fee_msat, 3000);
2249 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2250 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2251 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2253 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2254 assert_eq!(route.paths[0][1].short_channel_id, 4);
2255 assert_eq!(route.paths[0][1].fee_msat, 0);
2256 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2257 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2258 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2260 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2261 assert_eq!(route.paths[0][2].short_channel_id, 6);
2262 assert_eq!(route.paths[0][2].fee_msat, 0);
2263 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2264 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2265 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2267 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2268 assert_eq!(route.paths[0][3].short_channel_id, 11);
2269 assert_eq!(route.paths[0][3].fee_msat, 1000);
2270 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2271 // If we have a peer in the node map, we'll use their features here since we don't have
2272 // a way of figuring out their features from the invoice:
2273 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2274 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2276 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2277 assert_eq!(route.paths[0][4].short_channel_id, 8);
2278 assert_eq!(route.paths[0][4].fee_msat, 2000);
2279 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2280 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2281 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2284 fn do_unannounced_path_test(last_hop_htlc_max: Option<u64>, last_hop_fee_prop: u32, outbound_capacity_msat: u64, route_val: u64) -> Result<Route, LightningError> {
2285 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
2286 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
2287 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
2289 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
2290 let last_hops = RouteHint(vec![RouteHintHop {
2291 src_node_id: middle_node_id,
2292 short_channel_id: 8,
2295 proportional_millionths: last_hop_fee_prop,
2297 cltv_expiry_delta: (8 << 8) | 1,
2298 htlc_minimum_msat: None,
2299 htlc_maximum_msat: last_hop_htlc_max,
2301 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
2302 get_route(&source_node_id, &NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()), &target_node_id, None, Some(&our_chans.iter().collect::<Vec<_>>()), &vec![&last_hops], route_val, 42, Arc::new(test_utils::TestLogger::new()))
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 route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
2312 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
2313 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
2314 assert_eq!(route.paths[0].len(), 2);
2316 assert_eq!(route.paths[0][0].pubkey, middle_node_id);
2317 assert_eq!(route.paths[0][0].short_channel_id, 42);
2318 assert_eq!(route.paths[0][0].fee_msat, 1001);
2319 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
2320 assert_eq!(route.paths[0][0].node_features.le_flags(), &[0b11]);
2321 assert_eq!(route.paths[0][0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
2323 assert_eq!(route.paths[0][1].pubkey, target_node_id);
2324 assert_eq!(route.paths[0][1].short_channel_id, 8);
2325 assert_eq!(route.paths[0][1].fee_msat, 1000000);
2326 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2327 assert_eq!(route.paths[0][1].node_features.le_flags(), &[0; 0]); // We dont pass flags in from invoices yet
2328 assert_eq!(route.paths[0][1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
2332 fn overflow_unannounced_path_test_liquidity_underflow() {
2333 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
2334 // the last-hop had a fee which overflowed a u64, we'd panic.
2335 // This was due to us adding the first-hop from us unconditionally, causing us to think
2336 // we'd built a path (as our node is in the "best candidate" set), when we had not.
2337 // In this test, we previously hit a subtraction underflow due to having less available
2338 // liquidity at the last hop than 0.
2339 assert!(do_unannounced_path_test(Some(21_000_000_0000_0000_000), 0, 21_000_000_0000_0000_000, 21_000_000_0000_0000_000).is_err());
2343 fn overflow_unannounced_path_test_feerate_overflow() {
2344 // This tests for the same case as above, except instead of hitting a subtraction
2345 // underflow, we hit a case where the fee charged at a hop overflowed.
2346 assert!(do_unannounced_path_test(Some(21_000_000_0000_0000_000), 50000, 21_000_000_0000_0000_000, 21_000_000_0000_0000_000).is_err());
2350 fn available_amount_while_routing_test() {
2351 // Tests whether we choose the correct available channel amount while routing.
2353 let (secp_ctx, mut net_graph_msg_handler, chain_monitor, logger) = build_graph();
2354 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2356 // We will use a simple single-path route from
2357 // our node to node2 via node0: channels {1, 3}.
2359 // First disable all other paths.
2360 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2361 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2362 short_channel_id: 2,
2365 cltv_expiry_delta: 0,
2366 htlc_minimum_msat: 0,
2367 htlc_maximum_msat: OptionalField::Present(100_000),
2369 fee_proportional_millionths: 0,
2370 excess_data: Vec::new()
2372 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2373 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2374 short_channel_id: 12,
2377 cltv_expiry_delta: 0,
2378 htlc_minimum_msat: 0,
2379 htlc_maximum_msat: OptionalField::Present(100_000),
2381 fee_proportional_millionths: 0,
2382 excess_data: Vec::new()
2385 // Make the first channel (#1) very permissive,
2386 // and we will be testing all limits on the second channel.
2387 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2388 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2389 short_channel_id: 1,
2392 cltv_expiry_delta: 0,
2393 htlc_minimum_msat: 0,
2394 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2396 fee_proportional_millionths: 0,
2397 excess_data: Vec::new()
2400 // First, let's see if routing works if we have absolutely no idea about the available amount.
2401 // In this case, it should be set to 250_000 sats.
2402 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2403 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2404 short_channel_id: 3,
2407 cltv_expiry_delta: 0,
2408 htlc_minimum_msat: 0,
2409 htlc_maximum_msat: OptionalField::Absent,
2411 fee_proportional_millionths: 0,
2412 excess_data: Vec::new()
2416 // Attempt to route more than available results in a failure.
2417 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2418 Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000_001, 42, Arc::clone(&logger)) {
2419 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2420 } else { panic!(); }
2424 // Now, attempt to route an exact amount we have should be fine.
2425 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2426 Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000_000, 42, Arc::clone(&logger)).unwrap();
2427 assert_eq!(route.paths.len(), 1);
2428 let path = route.paths.last().unwrap();
2429 assert_eq!(path.len(), 2);
2430 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2431 assert_eq!(path.last().unwrap().fee_msat, 250_000_000);
2434 // Check that setting outbound_capacity_msat in first_hops limits the channels.
2435 // Disable channel #1 and use another first hop.
2436 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2437 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2438 short_channel_id: 1,
2441 cltv_expiry_delta: 0,
2442 htlc_minimum_msat: 0,
2443 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2445 fee_proportional_millionths: 0,
2446 excess_data: Vec::new()
2449 // Now, limit the first_hop by the outbound_capacity_msat of 200_000 sats.
2450 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
2453 // Attempt to route more than available results in a failure.
2454 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2455 Some(InvoiceFeatures::known()), Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 200_000_001, 42, Arc::clone(&logger)) {
2456 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2457 } else { panic!(); }
2461 // Now, attempt to route an exact amount we have should be fine.
2462 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2463 Some(InvoiceFeatures::known()), Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 200_000_000, 42, Arc::clone(&logger)).unwrap();
2464 assert_eq!(route.paths.len(), 1);
2465 let path = route.paths.last().unwrap();
2466 assert_eq!(path.len(), 2);
2467 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2468 assert_eq!(path.last().unwrap().fee_msat, 200_000_000);
2471 // Enable channel #1 back.
2472 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2473 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2474 short_channel_id: 1,
2477 cltv_expiry_delta: 0,
2478 htlc_minimum_msat: 0,
2479 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2481 fee_proportional_millionths: 0,
2482 excess_data: Vec::new()
2486 // Now let's see if routing works if we know only htlc_maximum_msat.
2487 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2488 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2489 short_channel_id: 3,
2492 cltv_expiry_delta: 0,
2493 htlc_minimum_msat: 0,
2494 htlc_maximum_msat: OptionalField::Present(15_000),
2496 fee_proportional_millionths: 0,
2497 excess_data: Vec::new()
2501 // Attempt to route more than available results in a failure.
2502 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2503 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_001, 42, Arc::clone(&logger)) {
2504 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2505 } else { panic!(); }
2509 // Now, attempt to route an exact amount we have should be fine.
2510 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2511 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_000, 42, Arc::clone(&logger)).unwrap();
2512 assert_eq!(route.paths.len(), 1);
2513 let path = route.paths.last().unwrap();
2514 assert_eq!(path.len(), 2);
2515 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2516 assert_eq!(path.last().unwrap().fee_msat, 15_000);
2519 // Now let's see if routing works if we know only capacity from the UTXO.
2521 // We can't change UTXO capacity on the fly, so we'll disable
2522 // the existing channel and add another one with the capacity we need.
2523 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2524 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2525 short_channel_id: 3,
2528 cltv_expiry_delta: 0,
2529 htlc_minimum_msat: 0,
2530 htlc_maximum_msat: OptionalField::Absent,
2532 fee_proportional_millionths: 0,
2533 excess_data: Vec::new()
2536 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
2537 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
2538 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
2539 .push_opcode(opcodes::all::OP_PUSHNUM_2)
2540 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
2542 *chain_monitor.utxo_ret.lock().unwrap() = Ok(TxOut { value: 15, script_pubkey: good_script.clone() });
2543 net_graph_msg_handler.add_chain_access(Some(chain_monitor));
2545 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
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: 333,
2551 cltv_expiry_delta: (3 << 8) | 1,
2552 htlc_minimum_msat: 0,
2553 htlc_maximum_msat: OptionalField::Absent,
2555 fee_proportional_millionths: 0,
2556 excess_data: Vec::new()
2558 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2559 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2560 short_channel_id: 333,
2563 cltv_expiry_delta: (3 << 8) | 2,
2564 htlc_minimum_msat: 0,
2565 htlc_maximum_msat: OptionalField::Absent,
2567 fee_proportional_millionths: 0,
2568 excess_data: Vec::new()
2572 // Attempt to route more than available results in a failure.
2573 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2574 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_001, 42, Arc::clone(&logger)) {
2575 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2576 } else { panic!(); }
2580 // Now, attempt to route an exact amount we have should be fine.
2581 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2582 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_000, 42, Arc::clone(&logger)).unwrap();
2583 assert_eq!(route.paths.len(), 1);
2584 let path = route.paths.last().unwrap();
2585 assert_eq!(path.len(), 2);
2586 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2587 assert_eq!(path.last().unwrap().fee_msat, 15_000);
2590 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
2591 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2592 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2593 short_channel_id: 333,
2596 cltv_expiry_delta: 0,
2597 htlc_minimum_msat: 0,
2598 htlc_maximum_msat: OptionalField::Present(10_000),
2600 fee_proportional_millionths: 0,
2601 excess_data: Vec::new()
2605 // Attempt to route more than available results in a failure.
2606 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2607 Some(InvoiceFeatures::known()), None, &Vec::new(), 10_001, 42, Arc::clone(&logger)) {
2608 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2609 } else { panic!(); }
2613 // Now, attempt to route an exact amount we have should be fine.
2614 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2615 Some(InvoiceFeatures::known()), None, &Vec::new(), 10_000, 42, Arc::clone(&logger)).unwrap();
2616 assert_eq!(route.paths.len(), 1);
2617 let path = route.paths.last().unwrap();
2618 assert_eq!(path.len(), 2);
2619 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2620 assert_eq!(path.last().unwrap().fee_msat, 10_000);
2625 fn available_liquidity_last_hop_test() {
2626 // Check that available liquidity properly limits the path even when only
2627 // one of the latter hops is limited.
2628 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2629 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2631 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
2632 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
2633 // Total capacity: 50 sats.
2635 // Disable other potential paths.
2636 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2637 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2638 short_channel_id: 2,
2641 cltv_expiry_delta: 0,
2642 htlc_minimum_msat: 0,
2643 htlc_maximum_msat: OptionalField::Present(100_000),
2645 fee_proportional_millionths: 0,
2646 excess_data: Vec::new()
2648 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2649 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2650 short_channel_id: 7,
2653 cltv_expiry_delta: 0,
2654 htlc_minimum_msat: 0,
2655 htlc_maximum_msat: OptionalField::Present(100_000),
2657 fee_proportional_millionths: 0,
2658 excess_data: Vec::new()
2663 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2664 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2665 short_channel_id: 12,
2668 cltv_expiry_delta: 0,
2669 htlc_minimum_msat: 0,
2670 htlc_maximum_msat: OptionalField::Present(100_000),
2672 fee_proportional_millionths: 0,
2673 excess_data: Vec::new()
2675 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2676 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2677 short_channel_id: 13,
2680 cltv_expiry_delta: 0,
2681 htlc_minimum_msat: 0,
2682 htlc_maximum_msat: OptionalField::Present(100_000),
2684 fee_proportional_millionths: 0,
2685 excess_data: Vec::new()
2688 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2689 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2690 short_channel_id: 6,
2693 cltv_expiry_delta: 0,
2694 htlc_minimum_msat: 0,
2695 htlc_maximum_msat: OptionalField::Present(50_000),
2697 fee_proportional_millionths: 0,
2698 excess_data: Vec::new()
2700 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
2701 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2702 short_channel_id: 11,
2705 cltv_expiry_delta: 0,
2706 htlc_minimum_msat: 0,
2707 htlc_maximum_msat: OptionalField::Present(100_000),
2709 fee_proportional_millionths: 0,
2710 excess_data: Vec::new()
2713 // Attempt to route more than available results in a failure.
2714 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
2715 Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger)) {
2716 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2717 } else { panic!(); }
2721 // Now, attempt to route 49 sats (just a bit below the capacity).
2722 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
2723 Some(InvoiceFeatures::known()), None, &Vec::new(), 49_000, 42, Arc::clone(&logger)).unwrap();
2724 assert_eq!(route.paths.len(), 1);
2725 let mut total_amount_paid_msat = 0;
2726 for path in &route.paths {
2727 assert_eq!(path.len(), 4);
2728 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
2729 total_amount_paid_msat += path.last().unwrap().fee_msat;
2731 assert_eq!(total_amount_paid_msat, 49_000);
2735 // Attempt to route an exact amount is also fine
2736 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
2737 Some(InvoiceFeatures::known()), None, &Vec::new(), 50_000, 42, Arc::clone(&logger)).unwrap();
2738 assert_eq!(route.paths.len(), 1);
2739 let mut total_amount_paid_msat = 0;
2740 for path in &route.paths {
2741 assert_eq!(path.len(), 4);
2742 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
2743 total_amount_paid_msat += path.last().unwrap().fee_msat;
2745 assert_eq!(total_amount_paid_msat, 50_000);
2750 fn ignore_fee_first_hop_test() {
2751 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2752 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2754 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
2755 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2756 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2757 short_channel_id: 1,
2760 cltv_expiry_delta: 0,
2761 htlc_minimum_msat: 0,
2762 htlc_maximum_msat: OptionalField::Present(100_000),
2763 fee_base_msat: 1_000_000,
2764 fee_proportional_millionths: 0,
2765 excess_data: Vec::new()
2767 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2768 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2769 short_channel_id: 3,
2772 cltv_expiry_delta: 0,
2773 htlc_minimum_msat: 0,
2774 htlc_maximum_msat: OptionalField::Present(50_000),
2776 fee_proportional_millionths: 0,
2777 excess_data: Vec::new()
2781 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();
2782 assert_eq!(route.paths.len(), 1);
2783 let mut total_amount_paid_msat = 0;
2784 for path in &route.paths {
2785 assert_eq!(path.len(), 2);
2786 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2787 total_amount_paid_msat += path.last().unwrap().fee_msat;
2789 assert_eq!(total_amount_paid_msat, 50_000);
2794 fn simple_mpp_route_test() {
2795 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2796 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2798 // We need a route consisting of 3 paths:
2799 // From our node to node2 via node0, node7, node1 (three paths one hop each).
2800 // To achieve this, the amount being transferred should be around
2801 // the total capacity of these 3 paths.
2803 // First, we set limits on these (previously unlimited) channels.
2804 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
2806 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
2807 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2808 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2809 short_channel_id: 1,
2812 cltv_expiry_delta: 0,
2813 htlc_minimum_msat: 0,
2814 htlc_maximum_msat: OptionalField::Present(100_000),
2816 fee_proportional_millionths: 0,
2817 excess_data: Vec::new()
2819 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2820 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2821 short_channel_id: 3,
2824 cltv_expiry_delta: 0,
2825 htlc_minimum_msat: 0,
2826 htlc_maximum_msat: OptionalField::Present(50_000),
2828 fee_proportional_millionths: 0,
2829 excess_data: Vec::new()
2832 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
2833 // (total limit 60).
2834 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2835 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2836 short_channel_id: 12,
2839 cltv_expiry_delta: 0,
2840 htlc_minimum_msat: 0,
2841 htlc_maximum_msat: OptionalField::Present(60_000),
2843 fee_proportional_millionths: 0,
2844 excess_data: Vec::new()
2846 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2847 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2848 short_channel_id: 13,
2851 cltv_expiry_delta: 0,
2852 htlc_minimum_msat: 0,
2853 htlc_maximum_msat: OptionalField::Present(60_000),
2855 fee_proportional_millionths: 0,
2856 excess_data: Vec::new()
2859 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
2860 // (total capacity 180 sats).
2861 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2862 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2863 short_channel_id: 2,
2866 cltv_expiry_delta: 0,
2867 htlc_minimum_msat: 0,
2868 htlc_maximum_msat: OptionalField::Present(200_000),
2870 fee_proportional_millionths: 0,
2871 excess_data: Vec::new()
2873 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2874 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2875 short_channel_id: 4,
2878 cltv_expiry_delta: 0,
2879 htlc_minimum_msat: 0,
2880 htlc_maximum_msat: OptionalField::Present(180_000),
2882 fee_proportional_millionths: 0,
2883 excess_data: Vec::new()
2887 // Attempt to route more than available results in a failure.
2888 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(),
2889 &nodes[2], Some(InvoiceFeatures::known()), None, &Vec::new(), 300_000, 42, Arc::clone(&logger)) {
2890 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2891 } else { panic!(); }
2895 // Now, attempt to route 250 sats (just a bit below the capacity).
2896 // Our algorithm should provide us with these 3 paths.
2897 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2898 Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000, 42, Arc::clone(&logger)).unwrap();
2899 assert_eq!(route.paths.len(), 3);
2900 let mut total_amount_paid_msat = 0;
2901 for path in &route.paths {
2902 assert_eq!(path.len(), 2);
2903 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2904 total_amount_paid_msat += path.last().unwrap().fee_msat;
2906 assert_eq!(total_amount_paid_msat, 250_000);
2910 // Attempt to route an exact amount is also fine
2911 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2912 Some(InvoiceFeatures::known()), None, &Vec::new(), 290_000, 42, Arc::clone(&logger)).unwrap();
2913 assert_eq!(route.paths.len(), 3);
2914 let mut total_amount_paid_msat = 0;
2915 for path in &route.paths {
2916 assert_eq!(path.len(), 2);
2917 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2918 total_amount_paid_msat += path.last().unwrap().fee_msat;
2920 assert_eq!(total_amount_paid_msat, 290_000);
2925 fn long_mpp_route_test() {
2926 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2927 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2929 // We need a route consisting of 3 paths:
2930 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
2931 // Note that these paths overlap (channels 5, 12, 13).
2932 // We will route 300 sats.
2933 // Each path will have 100 sats capacity, those channels which
2934 // are used twice will have 200 sats capacity.
2936 // Disable other potential paths.
2937 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2938 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2939 short_channel_id: 2,
2942 cltv_expiry_delta: 0,
2943 htlc_minimum_msat: 0,
2944 htlc_maximum_msat: OptionalField::Present(100_000),
2946 fee_proportional_millionths: 0,
2947 excess_data: Vec::new()
2949 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2950 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2951 short_channel_id: 7,
2954 cltv_expiry_delta: 0,
2955 htlc_minimum_msat: 0,
2956 htlc_maximum_msat: OptionalField::Present(100_000),
2958 fee_proportional_millionths: 0,
2959 excess_data: Vec::new()
2962 // Path via {node0, node2} is channels {1, 3, 5}.
2963 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2964 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2965 short_channel_id: 1,
2968 cltv_expiry_delta: 0,
2969 htlc_minimum_msat: 0,
2970 htlc_maximum_msat: OptionalField::Present(100_000),
2972 fee_proportional_millionths: 0,
2973 excess_data: Vec::new()
2975 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2976 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2977 short_channel_id: 3,
2980 cltv_expiry_delta: 0,
2981 htlc_minimum_msat: 0,
2982 htlc_maximum_msat: OptionalField::Present(100_000),
2984 fee_proportional_millionths: 0,
2985 excess_data: Vec::new()
2988 // Capacity of 200 sats because this channel will be used by 3rd path as well.
2989 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
2990 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2991 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2992 short_channel_id: 5,
2995 cltv_expiry_delta: 0,
2996 htlc_minimum_msat: 0,
2997 htlc_maximum_msat: OptionalField::Present(200_000),
2999 fee_proportional_millionths: 0,
3000 excess_data: Vec::new()
3003 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3004 // Add 100 sats to the capacities of {12, 13}, because these channels
3005 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3006 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3007 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3008 short_channel_id: 12,
3011 cltv_expiry_delta: 0,
3012 htlc_minimum_msat: 0,
3013 htlc_maximum_msat: OptionalField::Present(200_000),
3015 fee_proportional_millionths: 0,
3016 excess_data: Vec::new()
3018 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3019 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3020 short_channel_id: 13,
3023 cltv_expiry_delta: 0,
3024 htlc_minimum_msat: 0,
3025 htlc_maximum_msat: OptionalField::Present(200_000),
3027 fee_proportional_millionths: 0,
3028 excess_data: Vec::new()
3031 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3032 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3033 short_channel_id: 6,
3036 cltv_expiry_delta: 0,
3037 htlc_minimum_msat: 0,
3038 htlc_maximum_msat: OptionalField::Present(100_000),
3040 fee_proportional_millionths: 0,
3041 excess_data: Vec::new()
3043 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3044 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3045 short_channel_id: 11,
3048 cltv_expiry_delta: 0,
3049 htlc_minimum_msat: 0,
3050 htlc_maximum_msat: OptionalField::Present(100_000),
3052 fee_proportional_millionths: 0,
3053 excess_data: Vec::new()
3056 // Path via {node7, node2} is channels {12, 13, 5}.
3057 // We already limited them to 200 sats (they are used twice for 100 sats).
3058 // Nothing to do here.
3061 // Attempt to route more than available results in a failure.
3062 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3063 Some(InvoiceFeatures::known()), None, &Vec::new(), 350_000, 42, Arc::clone(&logger)) {
3064 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3065 } else { panic!(); }
3069 // Now, attempt to route 300 sats (exact amount we can route).
3070 // Our algorithm should provide us with these 3 paths, 100 sats each.
3071 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3072 Some(InvoiceFeatures::known()), None, &Vec::new(), 300_000, 42, Arc::clone(&logger)).unwrap();
3073 assert_eq!(route.paths.len(), 3);
3075 let mut total_amount_paid_msat = 0;
3076 for path in &route.paths {
3077 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3078 total_amount_paid_msat += path.last().unwrap().fee_msat;
3080 assert_eq!(total_amount_paid_msat, 300_000);
3086 fn mpp_cheaper_route_test() {
3087 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3088 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3090 // This test checks that if we have two cheaper paths and one more expensive path,
3091 // so that liquidity-wise any 2 of 3 combination is sufficient,
3092 // two cheaper paths will be taken.
3093 // These paths have equal available liquidity.
3095 // We need a combination of 3 paths:
3096 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3097 // Note that these paths overlap (channels 5, 12, 13).
3098 // Each path will have 100 sats capacity, those channels which
3099 // are used twice will have 200 sats capacity.
3101 // Disable other potential paths.
3102 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3103 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3104 short_channel_id: 2,
3107 cltv_expiry_delta: 0,
3108 htlc_minimum_msat: 0,
3109 htlc_maximum_msat: OptionalField::Present(100_000),
3111 fee_proportional_millionths: 0,
3112 excess_data: Vec::new()
3114 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3115 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3116 short_channel_id: 7,
3119 cltv_expiry_delta: 0,
3120 htlc_minimum_msat: 0,
3121 htlc_maximum_msat: OptionalField::Present(100_000),
3123 fee_proportional_millionths: 0,
3124 excess_data: Vec::new()
3127 // Path via {node0, node2} is channels {1, 3, 5}.
3128 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3129 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3130 short_channel_id: 1,
3133 cltv_expiry_delta: 0,
3134 htlc_minimum_msat: 0,
3135 htlc_maximum_msat: OptionalField::Present(100_000),
3137 fee_proportional_millionths: 0,
3138 excess_data: Vec::new()
3140 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3141 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3142 short_channel_id: 3,
3145 cltv_expiry_delta: 0,
3146 htlc_minimum_msat: 0,
3147 htlc_maximum_msat: OptionalField::Present(100_000),
3149 fee_proportional_millionths: 0,
3150 excess_data: Vec::new()
3153 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3154 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3155 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3156 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3157 short_channel_id: 5,
3160 cltv_expiry_delta: 0,
3161 htlc_minimum_msat: 0,
3162 htlc_maximum_msat: OptionalField::Present(200_000),
3164 fee_proportional_millionths: 0,
3165 excess_data: Vec::new()
3168 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3169 // Add 100 sats to the capacities of {12, 13}, because these channels
3170 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3171 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3172 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3173 short_channel_id: 12,
3176 cltv_expiry_delta: 0,
3177 htlc_minimum_msat: 0,
3178 htlc_maximum_msat: OptionalField::Present(200_000),
3180 fee_proportional_millionths: 0,
3181 excess_data: Vec::new()
3183 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3184 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3185 short_channel_id: 13,
3188 cltv_expiry_delta: 0,
3189 htlc_minimum_msat: 0,
3190 htlc_maximum_msat: OptionalField::Present(200_000),
3192 fee_proportional_millionths: 0,
3193 excess_data: Vec::new()
3196 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3197 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3198 short_channel_id: 6,
3201 cltv_expiry_delta: 0,
3202 htlc_minimum_msat: 0,
3203 htlc_maximum_msat: OptionalField::Present(100_000),
3204 fee_base_msat: 1_000,
3205 fee_proportional_millionths: 0,
3206 excess_data: Vec::new()
3208 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3209 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3210 short_channel_id: 11,
3213 cltv_expiry_delta: 0,
3214 htlc_minimum_msat: 0,
3215 htlc_maximum_msat: OptionalField::Present(100_000),
3217 fee_proportional_millionths: 0,
3218 excess_data: Vec::new()
3221 // Path via {node7, node2} is channels {12, 13, 5}.
3222 // We already limited them to 200 sats (they are used twice for 100 sats).
3223 // Nothing to do here.
3226 // Now, attempt to route 180 sats.
3227 // Our algorithm should provide us with these 2 paths.
3228 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3229 Some(InvoiceFeatures::known()), None, &Vec::new(), 180_000, 42, Arc::clone(&logger)).unwrap();
3230 assert_eq!(route.paths.len(), 2);
3232 let mut total_value_transferred_msat = 0;
3233 let mut total_paid_msat = 0;
3234 for path in &route.paths {
3235 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3236 total_value_transferred_msat += path.last().unwrap().fee_msat;
3238 total_paid_msat += hop.fee_msat;
3241 // If we paid fee, this would be higher.
3242 assert_eq!(total_value_transferred_msat, 180_000);
3243 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
3244 assert_eq!(total_fees_paid, 0);
3249 fn fees_on_mpp_route_test() {
3250 // This test makes sure that MPP algorithm properly takes into account
3251 // fees charged on the channels, by making the fees impactful:
3252 // if the fee is not properly accounted for, the behavior is different.
3253 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3254 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3256 // We need a route consisting of 2 paths:
3257 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
3258 // We will route 200 sats, Each path will have 100 sats capacity.
3260 // This test is not particularly stable: e.g.,
3261 // there's a way to route via {node0, node2, node4}.
3262 // It works while pathfinding is deterministic, but can be broken otherwise.
3263 // It's fine to ignore this concern for now.
3265 // Disable other potential paths.
3266 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3267 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3268 short_channel_id: 2,
3271 cltv_expiry_delta: 0,
3272 htlc_minimum_msat: 0,
3273 htlc_maximum_msat: OptionalField::Present(100_000),
3275 fee_proportional_millionths: 0,
3276 excess_data: Vec::new()
3279 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3280 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3281 short_channel_id: 7,
3284 cltv_expiry_delta: 0,
3285 htlc_minimum_msat: 0,
3286 htlc_maximum_msat: OptionalField::Present(100_000),
3288 fee_proportional_millionths: 0,
3289 excess_data: Vec::new()
3292 // Path via {node0, node2} is channels {1, 3, 5}.
3293 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3294 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3295 short_channel_id: 1,
3298 cltv_expiry_delta: 0,
3299 htlc_minimum_msat: 0,
3300 htlc_maximum_msat: OptionalField::Present(100_000),
3302 fee_proportional_millionths: 0,
3303 excess_data: Vec::new()
3305 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3306 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3307 short_channel_id: 3,
3310 cltv_expiry_delta: 0,
3311 htlc_minimum_msat: 0,
3312 htlc_maximum_msat: OptionalField::Present(100_000),
3314 fee_proportional_millionths: 0,
3315 excess_data: Vec::new()
3318 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3319 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3320 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3321 short_channel_id: 5,
3324 cltv_expiry_delta: 0,
3325 htlc_minimum_msat: 0,
3326 htlc_maximum_msat: OptionalField::Present(100_000),
3328 fee_proportional_millionths: 0,
3329 excess_data: Vec::new()
3332 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3333 // All channels should be 100 sats capacity. But for the fee experiment,
3334 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
3335 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
3336 // 100 sats (and pay 150 sats in fees for the use of channel 6),
3337 // so no matter how large are other channels,
3338 // the whole path will be limited by 100 sats with just these 2 conditions:
3339 // - channel 12 capacity is 250 sats
3340 // - fee for channel 6 is 150 sats
3341 // Let's test this by enforcing these 2 conditions and removing other limits.
3342 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3343 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3344 short_channel_id: 12,
3347 cltv_expiry_delta: 0,
3348 htlc_minimum_msat: 0,
3349 htlc_maximum_msat: OptionalField::Present(250_000),
3351 fee_proportional_millionths: 0,
3352 excess_data: Vec::new()
3354 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3355 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3356 short_channel_id: 13,
3359 cltv_expiry_delta: 0,
3360 htlc_minimum_msat: 0,
3361 htlc_maximum_msat: OptionalField::Absent,
3363 fee_proportional_millionths: 0,
3364 excess_data: Vec::new()
3367 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3368 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3369 short_channel_id: 6,
3372 cltv_expiry_delta: 0,
3373 htlc_minimum_msat: 0,
3374 htlc_maximum_msat: OptionalField::Absent,
3375 fee_base_msat: 150_000,
3376 fee_proportional_millionths: 0,
3377 excess_data: Vec::new()
3379 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3380 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3381 short_channel_id: 11,
3384 cltv_expiry_delta: 0,
3385 htlc_minimum_msat: 0,
3386 htlc_maximum_msat: OptionalField::Absent,
3388 fee_proportional_millionths: 0,
3389 excess_data: Vec::new()
3393 // Attempt to route more than available results in a failure.
3394 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3395 Some(InvoiceFeatures::known()), None, &Vec::new(), 210_000, 42, Arc::clone(&logger)) {
3396 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3397 } else { panic!(); }
3401 // Now, attempt to route 200 sats (exact amount we can route).
3402 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3403 Some(InvoiceFeatures::known()), None, &Vec::new(), 200_000, 42, Arc::clone(&logger)).unwrap();
3404 assert_eq!(route.paths.len(), 2);
3406 let mut total_amount_paid_msat = 0;
3407 for path in &route.paths {
3408 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3409 total_amount_paid_msat += path.last().unwrap().fee_msat;
3411 assert_eq!(total_amount_paid_msat, 200_000);
3417 fn drop_lowest_channel_mpp_route_test() {
3418 // This test checks that low-capacity channel is dropped when after
3419 // path finding we realize that we found more capacity than we need.
3420 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3421 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3423 // We need a route consisting of 3 paths:
3424 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3426 // The first and the second paths should be sufficient, but the third should be
3427 // cheaper, so that we select it but drop later.
3429 // First, we set limits on these (previously unlimited) channels.
3430 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
3432 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
3433 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3434 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3435 short_channel_id: 1,
3438 cltv_expiry_delta: 0,
3439 htlc_minimum_msat: 0,
3440 htlc_maximum_msat: OptionalField::Present(100_000),
3442 fee_proportional_millionths: 0,
3443 excess_data: Vec::new()
3445 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3446 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3447 short_channel_id: 3,
3450 cltv_expiry_delta: 0,
3451 htlc_minimum_msat: 0,
3452 htlc_maximum_msat: OptionalField::Present(50_000),
3454 fee_proportional_millionths: 0,
3455 excess_data: Vec::new()
3458 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
3459 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3460 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3461 short_channel_id: 12,
3464 cltv_expiry_delta: 0,
3465 htlc_minimum_msat: 0,
3466 htlc_maximum_msat: OptionalField::Present(60_000),
3468 fee_proportional_millionths: 0,
3469 excess_data: Vec::new()
3471 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3472 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3473 short_channel_id: 13,
3476 cltv_expiry_delta: 0,
3477 htlc_minimum_msat: 0,
3478 htlc_maximum_msat: OptionalField::Present(60_000),
3480 fee_proportional_millionths: 0,
3481 excess_data: Vec::new()
3484 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
3485 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3486 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3487 short_channel_id: 2,
3490 cltv_expiry_delta: 0,
3491 htlc_minimum_msat: 0,
3492 htlc_maximum_msat: OptionalField::Present(20_000),
3494 fee_proportional_millionths: 0,
3495 excess_data: Vec::new()
3497 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3498 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3499 short_channel_id: 4,
3502 cltv_expiry_delta: 0,
3503 htlc_minimum_msat: 0,
3504 htlc_maximum_msat: OptionalField::Present(20_000),
3506 fee_proportional_millionths: 0,
3507 excess_data: Vec::new()
3511 // Attempt to route more than available results in a failure.
3512 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
3513 Some(InvoiceFeatures::known()), None, &Vec::new(), 150_000, 42, Arc::clone(&logger)) {
3514 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3515 } else { panic!(); }
3519 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
3520 // Our algorithm should provide us with these 3 paths.
3521 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
3522 Some(InvoiceFeatures::known()), None, &Vec::new(), 125_000, 42, Arc::clone(&logger)).unwrap();
3523 assert_eq!(route.paths.len(), 3);
3524 let mut total_amount_paid_msat = 0;
3525 for path in &route.paths {
3526 assert_eq!(path.len(), 2);
3527 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3528 total_amount_paid_msat += path.last().unwrap().fee_msat;
3530 assert_eq!(total_amount_paid_msat, 125_000);
3534 // Attempt to route without the last small cheap channel
3535 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
3536 Some(InvoiceFeatures::known()), None, &Vec::new(), 90_000, 42, Arc::clone(&logger)).unwrap();
3537 assert_eq!(route.paths.len(), 2);
3538 let mut total_amount_paid_msat = 0;
3539 for path in &route.paths {
3540 assert_eq!(path.len(), 2);
3541 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3542 total_amount_paid_msat += path.last().unwrap().fee_msat;
3544 assert_eq!(total_amount_paid_msat, 90_000);
3549 fn min_criteria_consistency() {
3550 // Test that we don't use an inconsistent metric between updating and walking nodes during
3551 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
3552 // was updated with a different criterion from the heap sorting, resulting in loops in
3553 // calculated paths. We test for that specific case here.
3555 // We construct a network that looks like this:
3557 // node2 -1(3)2- node3
3561 // node1 -1(5)2- node4 -1(1)2- node6
3567 // We create a loop on the side of our real path - our destination is node 6, with a
3568 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
3569 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
3570 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
3571 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
3572 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
3573 // "previous hop" being set to node 3, creating a loop in the path.
3574 let secp_ctx = Secp256k1::new();
3575 let logger = Arc::new(test_utils::TestLogger::new());
3576 let net_graph_msg_handler = NetGraphMsgHandler::new(genesis_block(Network::Testnet).header.block_hash(), None, Arc::clone(&logger));
3577 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3579 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
3580 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3581 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3582 short_channel_id: 6,
3585 cltv_expiry_delta: (6 << 8) | 0,
3586 htlc_minimum_msat: 0,
3587 htlc_maximum_msat: OptionalField::Absent,
3589 fee_proportional_millionths: 0,
3590 excess_data: Vec::new()
3592 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
3594 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3595 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3596 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3597 short_channel_id: 5,
3600 cltv_expiry_delta: (5 << 8) | 0,
3601 htlc_minimum_msat: 0,
3602 htlc_maximum_msat: OptionalField::Absent,
3604 fee_proportional_millionths: 0,
3605 excess_data: Vec::new()
3607 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
3609 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
3610 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3611 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3612 short_channel_id: 4,
3615 cltv_expiry_delta: (4 << 8) | 0,
3616 htlc_minimum_msat: 0,
3617 htlc_maximum_msat: OptionalField::Absent,
3619 fee_proportional_millionths: 0,
3620 excess_data: Vec::new()
3622 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
3624 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
3625 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
3626 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3627 short_channel_id: 3,
3630 cltv_expiry_delta: (3 << 8) | 0,
3631 htlc_minimum_msat: 0,
3632 htlc_maximum_msat: OptionalField::Absent,
3634 fee_proportional_millionths: 0,
3635 excess_data: Vec::new()
3637 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
3639 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
3640 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3641 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3642 short_channel_id: 2,
3645 cltv_expiry_delta: (2 << 8) | 0,
3646 htlc_minimum_msat: 0,
3647 htlc_maximum_msat: OptionalField::Absent,
3649 fee_proportional_millionths: 0,
3650 excess_data: Vec::new()
3653 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
3654 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3655 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3656 short_channel_id: 1,
3659 cltv_expiry_delta: (1 << 8) | 0,
3660 htlc_minimum_msat: 100,
3661 htlc_maximum_msat: OptionalField::Absent,
3663 fee_proportional_millionths: 0,
3664 excess_data: Vec::new()
3666 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
3669 // Now ensure the route flows simply over nodes 1 and 4 to 6.
3670 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();
3671 assert_eq!(route.paths.len(), 1);
3672 assert_eq!(route.paths[0].len(), 3);
3674 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3675 assert_eq!(route.paths[0][0].short_channel_id, 6);
3676 assert_eq!(route.paths[0][0].fee_msat, 100);
3677 assert_eq!(route.paths[0][0].cltv_expiry_delta, (5 << 8) | 0);
3678 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(1));
3679 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(6));
3681 assert_eq!(route.paths[0][1].pubkey, nodes[4]);
3682 assert_eq!(route.paths[0][1].short_channel_id, 5);
3683 assert_eq!(route.paths[0][1].fee_msat, 0);
3684 assert_eq!(route.paths[0][1].cltv_expiry_delta, (1 << 8) | 0);
3685 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(4));
3686 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(5));
3688 assert_eq!(route.paths[0][2].pubkey, nodes[6]);
3689 assert_eq!(route.paths[0][2].short_channel_id, 1);
3690 assert_eq!(route.paths[0][2].fee_msat, 10_000);
3691 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
3692 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
3693 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(1));
3699 fn exact_fee_liquidity_limit() {
3700 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
3701 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
3702 // we calculated fees on a higher value, resulting in us ignoring such paths.
3703 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3704 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
3706 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
3708 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3709 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3710 short_channel_id: 2,
3713 cltv_expiry_delta: 0,
3714 htlc_minimum_msat: 0,
3715 htlc_maximum_msat: OptionalField::Present(85_000),
3717 fee_proportional_millionths: 0,
3718 excess_data: Vec::new()
3721 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3722 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3723 short_channel_id: 12,
3726 cltv_expiry_delta: (4 << 8) | 1,
3727 htlc_minimum_msat: 0,
3728 htlc_maximum_msat: OptionalField::Present(270_000),
3730 fee_proportional_millionths: 1000000,
3731 excess_data: Vec::new()
3735 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
3736 // 200% fee charged channel 13 in the 1-to-2 direction.
3737 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();
3738 assert_eq!(route.paths.len(), 1);
3739 assert_eq!(route.paths[0].len(), 2);
3741 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
3742 assert_eq!(route.paths[0][0].short_channel_id, 12);
3743 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
3744 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
3745 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
3746 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
3748 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3749 assert_eq!(route.paths[0][1].short_channel_id, 13);
3750 assert_eq!(route.paths[0][1].fee_msat, 90_000);
3751 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3752 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3753 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
3758 fn htlc_max_reduction_below_min() {
3759 // Test that if, while walking the graph, we reduce the value being sent to meet an
3760 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
3761 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
3762 // resulting in us thinking there is no possible path, even if other paths exist.
3763 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3764 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3766 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
3767 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
3768 // then try to send 90_000.
3769 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3770 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3771 short_channel_id: 2,
3774 cltv_expiry_delta: 0,
3775 htlc_minimum_msat: 0,
3776 htlc_maximum_msat: OptionalField::Present(80_000),
3778 fee_proportional_millionths: 0,
3779 excess_data: Vec::new()
3781 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3782 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3783 short_channel_id: 4,
3786 cltv_expiry_delta: (4 << 8) | 1,
3787 htlc_minimum_msat: 90_000,
3788 htlc_maximum_msat: OptionalField::Absent,
3790 fee_proportional_millionths: 0,
3791 excess_data: Vec::new()
3795 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
3796 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
3797 // expensive) channels 12-13 path.
3798 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();
3799 assert_eq!(route.paths.len(), 1);
3800 assert_eq!(route.paths[0].len(), 2);
3802 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
3803 assert_eq!(route.paths[0][0].short_channel_id, 12);
3804 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
3805 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
3806 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
3807 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
3809 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3810 assert_eq!(route.paths[0][1].short_channel_id, 13);
3811 assert_eq!(route.paths[0][1].fee_msat, 90_000);
3812 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3813 assert_eq!(route.paths[0][1].node_features.le_flags(), InvoiceFeatures::known().le_flags());
3814 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
3818 #[cfg(not(feature = "no_std"))]
3819 pub(super) fn random_init_seed() -> u64 {
3820 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
3821 use core::hash::{BuildHasher, Hasher};
3822 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
3823 println!("Using seed of {}", seed);
3826 #[cfg(not(feature = "no_std"))]
3827 use util::ser::Readable;
3830 #[cfg(not(feature = "no_std"))]
3831 fn generate_routes() {
3832 let mut d = match super::test_utils::get_route_file() {
3839 let graph = NetworkGraph::read(&mut d).unwrap();
3841 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
3842 let mut seed = random_init_seed() as usize;
3843 'load_endpoints: for _ in 0..10 {
3845 seed = seed.overflowing_mul(0xdeadbeef).0;
3846 let src = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3847 seed = seed.overflowing_mul(0xdeadbeef).0;
3848 let dst = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3849 let amt = seed as u64 % 200_000_000;
3850 if get_route(src, &graph, dst, None, None, &[], amt, 42, &test_utils::TestLogger::new()).is_ok() {
3851 continue 'load_endpoints;
3858 #[cfg(not(feature = "no_std"))]
3859 fn generate_routes_mpp() {
3860 let mut d = match super::test_utils::get_route_file() {
3867 let graph = NetworkGraph::read(&mut d).unwrap();
3869 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
3870 let mut seed = random_init_seed() as usize;
3871 'load_endpoints: for _ in 0..10 {
3873 seed = seed.overflowing_mul(0xdeadbeef).0;
3874 let src = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3875 seed = seed.overflowing_mul(0xdeadbeef).0;
3876 let dst = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3877 let amt = seed as u64 % 200_000_000;
3878 if get_route(src, &graph, dst, Some(InvoiceFeatures::known()), None, &[], amt, 42, &test_utils::TestLogger::new()).is_ok() {
3879 continue 'load_endpoints;
3886 #[cfg(all(test, not(feature = "no_std")))]
3887 pub(crate) mod test_utils {
3889 /// Tries to open a network graph file, or panics with a URL to fetch it.
3890 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
3891 let res = File::open("net_graph-2021-05-31.bin") // By default we're run in RL/lightning
3892 .or_else(|_| File::open("lightning/net_graph-2021-05-31.bin")) // We may be run manually in RL/
3893 .or_else(|_| { // Fall back to guessing based on the binary location
3894 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
3895 let mut path = std::env::current_exe().unwrap();
3896 path.pop(); // lightning-...
3898 path.pop(); // debug
3899 path.pop(); // target
3900 path.push("lightning");
3901 path.push("net_graph-2021-05-31.bin");
3902 eprintln!("{}", path.to_str().unwrap());
3905 .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");
3906 #[cfg(require_route_graph_test)]
3907 return Ok(res.unwrap());
3908 #[cfg(not(require_route_graph_test))]
3913 #[cfg(all(test, feature = "unstable", not(feature = "no_std")))]
3916 use util::logger::{Logger, Record};
3920 struct DummyLogger {}
3921 impl Logger for DummyLogger {
3922 fn log(&self, _record: &Record) {}
3926 fn generate_routes(bench: &mut Bencher) {
3927 let mut d = test_utils::get_route_file().unwrap();
3928 let graph = NetworkGraph::read(&mut d).unwrap();
3930 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
3931 let mut path_endpoints = Vec::new();
3932 let mut seed: usize = 0xdeadbeef;
3933 'load_endpoints: for _ in 0..100 {
3936 let src = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3938 let dst = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3939 let amt = seed as u64 % 1_000_000;
3940 if get_route(src, &graph, dst, None, None, &[], amt, 42, &DummyLogger{}).is_ok() {
3941 path_endpoints.push((src, dst, amt));
3942 continue 'load_endpoints;
3947 // ...then benchmark finding paths between the nodes we learned.
3950 let (src, dst, amt) = path_endpoints[idx % path_endpoints.len()];
3951 assert!(get_route(src, &graph, dst, None, None, &[], amt, 42, &DummyLogger{}).is_ok());
3957 fn generate_mpp_routes(bench: &mut Bencher) {
3958 let mut d = test_utils::get_route_file().unwrap();
3959 let graph = NetworkGraph::read(&mut d).unwrap();
3961 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
3962 let mut path_endpoints = Vec::new();
3963 let mut seed: usize = 0xdeadbeef;
3964 'load_endpoints: for _ in 0..100 {
3967 let src = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3969 let dst = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3970 let amt = seed as u64 % 1_000_000;
3971 if get_route(src, &graph, dst, Some(InvoiceFeatures::known()), None, &[], amt, 42, &DummyLogger{}).is_ok() {
3972 path_endpoints.push((src, dst, amt));
3973 continue 'load_endpoints;
3978 // ...then benchmark finding paths between the nodes we learned.
3981 let (src, dst, amt) = path_endpoints[idx % path_endpoints.len()];
3982 assert!(get_route(src, &graph, dst, Some(InvoiceFeatures::known()), None, &[], amt, 42, &DummyLogger{}).is_ok());