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.remote_network_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.remote_network_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 ( $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,
518 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr ) => {
519 // Channels to self should not be used. This is more of belt-and-suspenders, because in
520 // practice these cases should be caught earlier:
521 // - for regular channels at channel announcement (TODO)
522 // - for first and last hops early in get_route
523 if $src_node_id != $dest_node_id.clone() {
524 let available_liquidity_msat = bookkeeped_channels_liquidity_available_msat.entry($chan_id.clone()).or_insert_with(|| {
525 let mut initial_liquidity_available_msat = None;
526 if let Some(capacity_sats) = $capacity_sats {
527 initial_liquidity_available_msat = Some(capacity_sats * 1000);
530 if let Some(htlc_maximum_msat) = $directional_info.htlc_maximum_msat {
531 if let Some(available_msat) = initial_liquidity_available_msat {
532 initial_liquidity_available_msat = Some(cmp::min(available_msat, htlc_maximum_msat));
534 initial_liquidity_available_msat = Some(htlc_maximum_msat);
538 match initial_liquidity_available_msat {
539 Some(available_msat) => available_msat,
540 // We assume channels with unknown balance have
541 // a capacity of 0.0025 BTC (or 250_000 sats).
542 None => 250_000 * 1000
546 // It is tricky to substract $next_hops_fee_msat from available liquidity here.
547 // It may be misleading because we might later choose to reduce the value transferred
548 // over these channels, and the channel which was insufficient might become sufficient.
549 // Worst case: we drop a good channel here because it can't cover the high following
550 // fees caused by one expensive channel, but then this channel could have been used
551 // if the amount being transferred over this path is lower.
552 // We do this for now, but this is a subject for removal.
553 if let Some(available_value_contribution_msat) = available_liquidity_msat.checked_sub($next_hops_fee_msat) {
555 // Routing Fragmentation Mitigation heuristic:
557 // Routing fragmentation across many payment paths increases the overall routing
558 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
559 // Taking too many smaller paths also increases the chance of payment failure.
560 // Thus to avoid this effect, we require from our collected links to provide
561 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
563 // This requirement is currently 5% of the remaining-to-be-collected value.
564 // This means as we successfully advance in our collection,
565 // the absolute liquidity contribution is lowered,
566 // thus increasing the number of potential channels to be selected.
568 // Derive the minimal liquidity contribution with a ratio of 20 (5%, rounded up)
569 // or 100% if we're not allowed to do multipath payments.
570 let minimal_value_contribution_msat: u64 = if allow_mpp {
571 (recommended_value_msat - already_collected_value_msat + 19) / 20
575 // Verify the liquidity offered by this channel complies to the minimal contribution.
576 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
578 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
579 // Includes paying fees for the use of the following channels.
580 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
581 Some(result) => result,
582 // Can't overflow due to how the values were computed right above.
583 None => unreachable!(),
585 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
586 let over_path_minimum_msat = amount_to_transfer_over_msat >= $directional_info.htlc_minimum_msat &&
587 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
589 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
590 // bother considering this channel.
591 // Since we're choosing amount_to_transfer_over_msat as maximum possible, it can
592 // be only reduced later (not increased), so this channel should just be skipped
593 // as not sufficient.
594 if !over_path_minimum_msat {
595 hit_minimum_limit = true;
596 } else if contributes_sufficient_value {
597 // Note that low contribution here (limited by available_liquidity_msat)
598 // might violate htlc_minimum_msat on the hops which are next along the
599 // payment path (upstream to the payee). To avoid that, we recompute path
600 // path fees knowing the final path contribution after constructing it.
601 let path_htlc_minimum_msat = match compute_fees($next_hops_path_htlc_minimum_msat, $directional_info.fees)
602 .map(|fee_msat| fee_msat.checked_add($next_hops_path_htlc_minimum_msat)) {
603 Some(Some(value_msat)) => cmp::max(value_msat, $directional_info.htlc_minimum_msat),
604 _ => u64::max_value()
606 let hm_entry = dist.entry(&$src_node_id);
607 let old_entry = hm_entry.or_insert_with(|| {
608 // If there was previously no known way to access
609 // the source node (recall it goes payee-to-payer) of $chan_id, first add
610 // a semi-dummy record just to compute the fees to reach the source node.
611 // This will affect our decision on selecting $chan_id
612 // as a way to reach the $dest_node_id.
613 let mut fee_base_msat = u32::max_value();
614 let mut fee_proportional_millionths = u32::max_value();
615 if let Some(Some(fees)) = network.get_nodes().get(&$src_node_id).map(|node| node.lowest_inbound_channel_fees) {
616 fee_base_msat = fees.base_msat;
617 fee_proportional_millionths = fees.proportional_millionths;
620 pubkey: $dest_node_id.clone(),
622 channel_features: $chan_features,
624 cltv_expiry_delta: 0,
625 src_lowest_inbound_fees: RoutingFees {
626 base_msat: fee_base_msat,
627 proportional_millionths: fee_proportional_millionths,
629 channel_fees: $directional_info.fees,
630 next_hops_fee_msat: u64::max_value(),
631 hop_use_fee_msat: u64::max_value(),
632 total_fee_msat: u64::max_value(),
633 htlc_minimum_msat: $directional_info.htlc_minimum_msat,
634 path_htlc_minimum_msat,
635 was_processed: false,
636 #[cfg(any(test, feature = "fuzztarget"))]
637 value_contribution_msat,
641 #[allow(unused_mut)] // We only use the mut in cfg(test)
642 let mut should_process = !old_entry.was_processed;
643 #[cfg(any(test, feature = "fuzztarget"))]
645 // In test/fuzzing builds, we do extra checks to make sure the skipping
646 // of already-seen nodes only happens in cases we expect (see below).
647 if !should_process { should_process = true; }
651 let mut hop_use_fee_msat = 0;
652 let mut total_fee_msat = $next_hops_fee_msat;
654 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
655 // will have the same effective-fee
656 if $src_node_id != *our_node_id {
657 match compute_fees(amount_to_transfer_over_msat, $directional_info.fees) {
658 // max_value means we'll always fail
659 // the old_entry.total_fee_msat > total_fee_msat check
660 None => total_fee_msat = u64::max_value(),
662 hop_use_fee_msat = fee_msat;
663 total_fee_msat += hop_use_fee_msat;
664 // When calculating the lowest inbound fees to a node, we
665 // calculate fees here not based on the actual value we think
666 // will flow over this channel, but on the minimum value that
667 // we'll accept flowing over it. The minimum accepted value
668 // is a constant through each path collection run, ensuring
669 // consistent basis. Otherwise we may later find a
670 // different path to the source node that is more expensive,
671 // but which we consider to be cheaper because we are capacity
672 // constrained and the relative fee becomes lower.
673 match compute_fees(minimal_value_contribution_msat, old_entry.src_lowest_inbound_fees)
674 .map(|a| a.checked_add(total_fee_msat)) {
679 total_fee_msat = u64::max_value();
686 let new_graph_node = RouteGraphNode {
687 pubkey: $src_node_id,
688 lowest_fee_to_peer_through_node: total_fee_msat,
689 lowest_fee_to_node: $next_hops_fee_msat as u64 + hop_use_fee_msat,
690 value_contribution_msat: value_contribution_msat,
691 path_htlc_minimum_msat,
694 // Update the way of reaching $src_node_id with the given $chan_id (from $dest_node_id),
695 // if this way is cheaper than the already known
696 // (considering the cost to "reach" this channel from the route destination,
697 // the cost of using this channel,
698 // and the cost of routing to the source node of this channel).
699 // Also, consider that htlc_minimum_msat_difference, because we might end up
700 // paying it. Consider the following exploit:
701 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
702 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
703 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
704 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
706 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
707 // but it may require additional tracking - we don't want to double-count
708 // the fees included in $next_hops_path_htlc_minimum_msat, but also
709 // can't use something that may decrease on future hops.
710 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat);
711 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat);
713 if !old_entry.was_processed && new_cost < old_cost {
714 targets.push(new_graph_node);
715 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
716 old_entry.hop_use_fee_msat = hop_use_fee_msat;
717 old_entry.total_fee_msat = total_fee_msat;
718 old_entry.pubkey = $dest_node_id.clone();
719 old_entry.short_channel_id = $chan_id.clone();
720 old_entry.channel_features = $chan_features;
721 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
722 old_entry.cltv_expiry_delta = $directional_info.cltv_expiry_delta as u32;
723 old_entry.channel_fees = $directional_info.fees;
724 old_entry.htlc_minimum_msat = $directional_info.htlc_minimum_msat;
725 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
726 #[cfg(any(test, feature = "fuzztarget"))]
728 old_entry.value_contribution_msat = value_contribution_msat;
730 } else if old_entry.was_processed && new_cost < old_cost {
731 #[cfg(any(test, feature = "fuzztarget"))]
733 // If we're skipping processing a node which was previously
734 // processed even though we found another path to it with a
735 // cheaper fee, check that it was because the second path we
736 // found (which we are processing now) has a lower value
737 // contribution due to an HTLC minimum limit.
739 // e.g. take a graph with two paths from node 1 to node 2, one
740 // through channel A, and one through channel B. Channel A and
741 // B are both in the to-process heap, with their scores set by
742 // a higher htlc_minimum than fee.
743 // Channel A is processed first, and the channels onwards from
744 // node 1 are added to the to-process heap. Thereafter, we pop
745 // Channel B off of the heap, note that it has a much more
746 // restrictive htlc_maximum_msat, and recalculate the fees for
747 // all of node 1's channels using the new, reduced, amount.
749 // This would be bogus - we'd be selecting a higher-fee path
750 // with a lower htlc_maximum_msat instead of the one we'd
751 // already decided to use.
752 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
753 debug_assert!(value_contribution_msat < old_entry.value_contribution_msat);
763 let empty_node_features = NodeFeatures::empty();
764 // Find ways (channels with destination) to reach a given node and store them
765 // in the corresponding data structures (routing graph etc).
766 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
767 // meaning how much will be paid in fees after this node (to the best of our knowledge).
768 // This data can later be helpful to optimize routing (pay lower fees).
769 macro_rules! add_entries_to_cheapest_to_target_node {
770 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr, $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr ) => {
771 let skip_node = if let Some(elem) = dist.get_mut($node_id) {
772 let was_processed = elem.was_processed;
773 elem.was_processed = true;
776 // Entries are added to dist in add_entry!() when there is a channel from a node.
777 // Because there are no channels from payee, it will not have a dist entry at this point.
778 // If we're processing any other node, it is always be the result of a channel from it.
779 assert_eq!($node_id, payee);
784 if first_hops.is_some() {
785 if let Some(&(ref first_hop, ref features, ref outbound_capacity_msat, _)) = first_hop_targets.get(&$node_id) {
786 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);
790 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
796 if !features.requires_unknown_bits() {
797 for chan_id in $node.channels.iter() {
798 let chan = network.get_channels().get(chan_id).unwrap();
799 if !chan.features.requires_unknown_bits() {
800 if chan.node_one == *$node_id {
801 // ie $node is one, ie next hop in A* is two, via the two_to_one channel
802 if first_hops.is_none() || chan.node_two != *our_node_id {
803 if let Some(two_to_one) = chan.two_to_one.as_ref() {
804 if two_to_one.enabled {
805 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);
810 if first_hops.is_none() || chan.node_one != *our_node_id {
811 if let Some(one_to_two) = chan.one_to_two.as_ref() {
812 if one_to_two.enabled {
813 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);
825 let mut payment_paths = Vec::<PaymentPath>::new();
827 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
828 'paths_collection: loop {
829 // For every new path, start from scratch, except
830 // bookkeeped_channels_liquidity_available_msat, which will improve
831 // the further iterations of path finding. Also don't erase first_hop_targets.
834 hit_minimum_limit = false;
836 // If first hop is a private channel and the only way to reach the payee, this is the only
837 // place where it could be added.
838 if first_hops.is_some() {
839 if let Some(&(ref first_hop, ref features, ref outbound_capacity_msat, _)) = first_hop_targets.get(&payee) {
840 add_entry!(first_hop, *our_node_id, payee, dummy_directional_info, Some(outbound_capacity_msat / 1000), features, 0, path_value_msat, 0);
844 // Add the payee as a target, so that the payee-to-payer
845 // search algorithm knows what to start with.
846 match network.get_nodes().get(payee) {
847 // The payee is not in our network graph, so nothing to add here.
848 // There is still a chance of reaching them via last_hops though,
849 // so don't yet fail the payment here.
850 // If not, targets.pop() will not even let us enter the loop in step 2.
853 add_entries_to_cheapest_to_target_node!(node, payee, 0, path_value_msat, 0);
858 // If a caller provided us with last hops, add them to routing targets. Since this happens
859 // earlier than general path finding, they will be somewhat prioritized, although currently
860 // it matters only if the fees are exactly the same.
861 for hop in last_hops.iter() {
862 let have_hop_src_in_graph =
863 if let Some(&(ref first_hop, ref features, ref outbound_capacity_msat, _)) = first_hop_targets.get(&hop.src_node_id) {
864 // If this hop connects to a node with which we have a direct channel, ignore
865 // the network graph and add both the hop and our direct channel to
866 // the candidate set.
868 // Currently there are no channel-context features defined, so we are a
869 // bit lazy here. In the future, we should pull them out via our
870 // ChannelManager, but there's no reason to waste the space until we
872 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);
875 // In any other case, only add the hop if the source is in the regular network
877 network.get_nodes().get(&hop.src_node_id).is_some()
879 if have_hop_src_in_graph {
880 // BOLT 11 doesn't allow inclusion of features for the last hop hints, which
881 // really sucks, cause we're gonna need that eventually.
882 let last_hop_htlc_minimum_msat: u64 = match hop.htlc_minimum_msat {
883 Some(htlc_minimum_msat) => htlc_minimum_msat,
886 let directional_info = DummyDirectionalChannelInfo {
887 cltv_expiry_delta: hop.cltv_expiry_delta as u32,
888 htlc_minimum_msat: last_hop_htlc_minimum_msat,
889 htlc_maximum_msat: hop.htlc_maximum_msat,
892 add_entry!(hop.short_channel_id, hop.src_node_id, payee, directional_info, None::<u64>, &empty_channel_features, 0, path_value_msat, 0);
896 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
898 // At this point, targets are filled with the data from first and
899 // last hops communicated by the caller, and the payment receiver.
900 let mut found_new_path = false;
903 // If this loop terminates due the exhaustion of targets, two situations are possible:
904 // - not enough outgoing liquidity:
905 // 0 < already_collected_value_msat < final_value_msat
906 // - enough outgoing liquidity:
907 // final_value_msat <= already_collected_value_msat < recommended_value_msat
908 // Both these cases (and other cases except reaching recommended_value_msat) mean that
909 // paths_collection will be stopped because found_new_path==false.
910 // This is not necessarily a routing failure.
911 'path_construction: while let Some(RouteGraphNode { pubkey, lowest_fee_to_node, value_contribution_msat, path_htlc_minimum_msat, .. }) = targets.pop() {
913 // Since we're going payee-to-payer, hitting our node as a target means we should stop
914 // traversing the graph and arrange the path out of what we found.
915 if pubkey == *our_node_id {
916 let mut new_entry = dist.remove(&our_node_id).unwrap();
917 let mut ordered_hops = vec!((new_entry.clone(), NodeFeatures::empty()));
920 if let Some(&(_, _, _, ref features)) = first_hop_targets.get(&ordered_hops.last().unwrap().0.pubkey) {
921 ordered_hops.last_mut().unwrap().1 = features.clone();
922 } else if let Some(node) = network.get_nodes().get(&ordered_hops.last().unwrap().0.pubkey) {
923 if let Some(node_info) = node.announcement_info.as_ref() {
924 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
926 ordered_hops.last_mut().unwrap().1 = NodeFeatures::empty();
929 // We should be able to fill in features for everything except the last
930 // hop, if the last hop was provided via a BOLT 11 invoice (though we
931 // should be able to extend it further as BOLT 11 does have feature
932 // flags for the last hop node itself).
933 assert!(ordered_hops.last().unwrap().0.pubkey == *payee);
936 // Means we succesfully traversed from the payer to the payee, now
937 // save this path for the payment route. Also, update the liquidity
938 // remaining on the used hops, so that we take them into account
939 // while looking for more paths.
940 if ordered_hops.last().unwrap().0.pubkey == *payee {
944 new_entry = match dist.remove(&ordered_hops.last().unwrap().0.pubkey) {
945 Some(payment_hop) => payment_hop,
946 // We can't arrive at None because, if we ever add an entry to targets,
947 // we also fill in the entry in dist (see add_entry!).
948 None => unreachable!(),
950 // We "propagate" the fees one hop backward (topologically) here,
951 // so that fees paid for a HTLC forwarding on the current channel are
952 // associated with the previous channel (where they will be subtracted).
953 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
954 ordered_hops.last_mut().unwrap().0.cltv_expiry_delta = new_entry.cltv_expiry_delta;
955 ordered_hops.push((new_entry.clone(), NodeFeatures::empty()));
957 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
958 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
959 ordered_hops.last_mut().unwrap().0.cltv_expiry_delta = final_cltv;
961 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: {:?}",
962 ordered_hops.len(), value_contribution_msat, ordered_hops);
964 let mut payment_path = PaymentPath {hops: ordered_hops};
966 // We could have possibly constructed a slightly inconsistent path: since we reduce
967 // value being transferred along the way, we could have violated htlc_minimum_msat
968 // on some channels we already passed (assuming dest->source direction). Here, we
969 // recompute the fees again, so that if that's the case, we match the currently
970 // underpaid htlc_minimum_msat with fees.
971 payment_path.update_value_and_recompute_fees(cmp::min(value_contribution_msat, final_value_msat));
973 // Since a path allows to transfer as much value as
974 // the smallest channel it has ("bottleneck"), we should recompute
975 // the fees so sender HTLC don't overpay fees when traversing
976 // larger channels than the bottleneck. This may happen because
977 // when we were selecting those channels we were not aware how much value
978 // this path will transfer, and the relative fee for them
979 // might have been computed considering a larger value.
980 // Remember that we used these channels so that we don't rely
981 // on the same liquidity in future paths.
982 let mut prevented_redundant_path_selection = false;
983 for (payment_hop, _) in payment_path.hops.iter() {
984 let channel_liquidity_available_msat = bookkeeped_channels_liquidity_available_msat.get_mut(&payment_hop.short_channel_id).unwrap();
985 let mut spent_on_hop_msat = value_contribution_msat;
986 let next_hops_fee_msat = payment_hop.next_hops_fee_msat;
987 spent_on_hop_msat += next_hops_fee_msat;
988 if spent_on_hop_msat == *channel_liquidity_available_msat {
989 // If this path used all of this channel's available liquidity, we know
990 // this path will not be selected again in the next loop iteration.
991 prevented_redundant_path_selection = true;
993 *channel_liquidity_available_msat -= spent_on_hop_msat;
995 if !prevented_redundant_path_selection {
996 // If we weren't capped by hitting a liquidity limit on a channel in the path,
997 // we'll probably end up picking the same path again on the next iteration.
998 // Decrease the available liquidity of a hop in the middle of the path.
999 let victim_scid = payment_path.hops[(payment_path.hops.len() - 1) / 2].0.short_channel_id;
1000 log_trace!(logger, "Disabling channel {} for future path building iterations to avoid duplicates.", victim_scid);
1001 let victim_liquidity = bookkeeped_channels_liquidity_available_msat.get_mut(&victim_scid).unwrap();
1002 *victim_liquidity = 0;
1005 // Track the total amount all our collected paths allow to send so that we:
1006 // - know when to stop looking for more paths
1007 // - know which of the hops are useless considering how much more sats we need
1008 // (contributes_sufficient_value)
1009 already_collected_value_msat += value_contribution_msat;
1011 payment_paths.push(payment_path);
1012 found_new_path = true;
1013 break 'path_construction;
1016 // If we found a path back to the payee, we shouldn't try to process it again. This is
1017 // the equivalent of the `elem.was_processed` check in
1018 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
1019 if pubkey == *payee { continue 'path_construction; }
1021 // Otherwise, since the current target node is not us,
1022 // keep "unrolling" the payment graph from payee to payer by
1023 // finding a way to reach the current target from the payer side.
1024 match network.get_nodes().get(&pubkey) {
1027 add_entries_to_cheapest_to_target_node!(node, &pubkey, lowest_fee_to_node, value_contribution_msat, path_htlc_minimum_msat);
1033 // If we don't support MPP, no use trying to gather more value ever.
1034 break 'paths_collection;
1038 // Stop either when the recommended value is reached or if no new path was found in this
1040 // In the latter case, making another path finding attempt won't help,
1041 // because we deterministically terminated the search due to low liquidity.
1042 if already_collected_value_msat >= recommended_value_msat || !found_new_path {
1043 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
1044 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
1045 break 'paths_collection;
1046 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
1047 // Further, if this was our first walk of the graph, and we weren't limited by an
1048 // htlc_minimum_msat, return immediately because this path should suffice. If we were
1049 // limited by an htlc_minimum_msat value, find another path with a higher value,
1050 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
1051 // still keeping a lower total fee than this path.
1052 if !hit_minimum_limit {
1053 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
1054 break 'paths_collection;
1056 log_trace!(logger, "Collected our payment amount on the first pass, but running again to collect extra paths with a potentially higher limit.");
1057 path_value_msat = recommended_value_msat;
1062 if payment_paths.len() == 0 {
1063 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1066 if already_collected_value_msat < final_value_msat {
1067 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1070 // Sort by total fees and take the best paths.
1071 payment_paths.sort_by_key(|path| path.get_total_fee_paid_msat());
1072 if payment_paths.len() > 50 {
1073 payment_paths.truncate(50);
1076 // Draw multiple sufficient routes by randomly combining the selected paths.
1077 let mut drawn_routes = Vec::new();
1078 for i in 0..payment_paths.len() {
1079 let mut cur_route = Vec::<PaymentPath>::new();
1080 let mut aggregate_route_value_msat = 0;
1083 // TODO: real random shuffle
1084 // Currently just starts with i_th and goes up to i-1_th in a looped way.
1085 let cur_payment_paths = [&payment_paths[i..], &payment_paths[..i]].concat();
1088 for payment_path in cur_payment_paths {
1089 cur_route.push(payment_path.clone());
1090 aggregate_route_value_msat += payment_path.get_value_msat();
1091 if aggregate_route_value_msat > final_value_msat {
1092 // Last path likely overpaid. Substract it from the most expensive
1093 // (in terms of proportional fee) path in this route and recompute fees.
1094 // This might be not the most economically efficient way, but fewer paths
1095 // also makes routing more reliable.
1096 let mut overpaid_value_msat = aggregate_route_value_msat - final_value_msat;
1098 // First, drop some expensive low-value paths entirely if possible.
1099 // Sort by value so that we drop many really-low values first, since
1100 // fewer paths is better: the payment is less likely to fail.
1101 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1102 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1103 cur_route.sort_by_key(|path| path.get_value_msat());
1104 // We should make sure that at least 1 path left.
1105 let mut paths_left = cur_route.len();
1106 cur_route.retain(|path| {
1107 if paths_left == 1 {
1110 let mut keep = true;
1111 let path_value_msat = path.get_value_msat();
1112 if path_value_msat <= overpaid_value_msat {
1114 overpaid_value_msat -= path_value_msat;
1120 if overpaid_value_msat == 0 {
1124 assert!(cur_route.len() > 0);
1127 // Now, substract the overpaid value from the most-expensive path.
1128 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1129 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1130 cur_route.sort_by_key(|path| { path.hops.iter().map(|hop| hop.0.channel_fees.proportional_millionths as u64).sum::<u64>() });
1131 let expensive_payment_path = cur_route.first_mut().unwrap();
1132 // We already dropped all the small channels above, meaning all the
1133 // remaining channels are larger than remaining overpaid_value_msat.
1134 // Thus, this can't be negative.
1135 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
1136 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
1140 drawn_routes.push(cur_route);
1144 // Select the best route by lowest total fee.
1145 drawn_routes.sort_by_key(|paths| paths.iter().map(|path| path.get_total_fee_paid_msat()).sum::<u64>());
1146 let mut selected_paths = Vec::<Vec<RouteHop>>::new();
1147 for payment_path in drawn_routes.first().unwrap() {
1148 selected_paths.push(payment_path.hops.iter().map(|(payment_hop, node_features)| {
1150 pubkey: payment_hop.pubkey,
1151 node_features: node_features.clone(),
1152 short_channel_id: payment_hop.short_channel_id,
1153 channel_features: payment_hop.channel_features.clone(),
1154 fee_msat: payment_hop.fee_msat,
1155 cltv_expiry_delta: payment_hop.cltv_expiry_delta,
1160 if let Some(features) = &payee_features {
1161 for path in selected_paths.iter_mut() {
1162 path.last_mut().unwrap().node_features = features.to_context();
1166 let route = Route { paths: selected_paths };
1167 log_info!(logger, "Got route to {}: {}", payee, log_route!(route));
1173 use routing::router::{get_route, RouteHint, RouteHintHop, RoutingFees};
1174 use routing::network_graph::{NetworkGraph, NetGraphMsgHandler};
1175 use chain::transaction::OutPoint;
1176 use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
1177 use ln::msgs::{ErrorAction, LightningError, OptionalField, UnsignedChannelAnnouncement, ChannelAnnouncement, RoutingMessageHandler,
1178 NodeAnnouncement, UnsignedNodeAnnouncement, ChannelUpdate, UnsignedChannelUpdate};
1179 use ln::channelmanager;
1180 use util::test_utils;
1181 use util::ser::Writeable;
1183 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
1184 use bitcoin::hashes::Hash;
1185 use bitcoin::network::constants::Network;
1186 use bitcoin::blockdata::constants::genesis_block;
1187 use bitcoin::blockdata::script::Builder;
1188 use bitcoin::blockdata::opcodes;
1189 use bitcoin::blockdata::transaction::TxOut;
1193 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
1194 use bitcoin::secp256k1::{Secp256k1, All};
1199 // Using the same keys for LN and BTC ids
1200 fn add_channel(net_graph_msg_handler: &NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>, secp_ctx: &Secp256k1<All>, node_1_privkey: &SecretKey,
1201 node_2_privkey: &SecretKey, features: ChannelFeatures, short_channel_id: u64) {
1202 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1203 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1205 let unsigned_announcement = UnsignedChannelAnnouncement {
1207 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1211 bitcoin_key_1: node_id_1,
1212 bitcoin_key_2: node_id_2,
1213 excess_data: Vec::new(),
1216 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1217 let valid_announcement = ChannelAnnouncement {
1218 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1219 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1220 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1221 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1222 contents: unsigned_announcement.clone(),
1224 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1225 Ok(res) => assert!(res),
1230 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) {
1231 let msghash = hash_to_message!(&Sha256dHash::hash(&update.encode()[..])[..]);
1232 let valid_channel_update = ChannelUpdate {
1233 signature: secp_ctx.sign(&msghash, node_privkey),
1234 contents: update.clone()
1237 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1238 Ok(res) => assert!(res),
1243 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,
1244 features: NodeFeatures, timestamp: u32) {
1245 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
1246 let unsigned_announcement = UnsignedNodeAnnouncement {
1252 addresses: Vec::new(),
1253 excess_address_data: Vec::new(),
1254 excess_data: Vec::new(),
1256 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1257 let valid_announcement = NodeAnnouncement {
1258 signature: secp_ctx.sign(&msghash, node_privkey),
1259 contents: unsigned_announcement.clone()
1262 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1268 fn get_nodes(secp_ctx: &Secp256k1<All>) -> (SecretKey, PublicKey, Vec<SecretKey>, Vec<PublicKey>) {
1269 let privkeys: Vec<SecretKey> = (2..10).map(|i| {
1270 SecretKey::from_slice(&hex::decode(format!("{:02}", i).repeat(32)).unwrap()[..]).unwrap()
1273 let pubkeys = privkeys.iter().map(|secret| PublicKey::from_secret_key(&secp_ctx, secret)).collect();
1275 let our_privkey = SecretKey::from_slice(&hex::decode("01".repeat(32)).unwrap()[..]).unwrap();
1276 let our_id = PublicKey::from_secret_key(&secp_ctx, &our_privkey);
1278 (our_privkey, our_id, privkeys, pubkeys)
1281 fn id_to_feature_flags(id: u8) -> Vec<u8> {
1282 // Set the feature flags to the id'th odd (ie non-required) feature bit so that we can
1283 // test for it later.
1284 let idx = (id - 1) * 2 + 1;
1286 vec![1 << (idx - 8*3), 0, 0, 0]
1287 } else if idx > 8*2 {
1288 vec![1 << (idx - 8*2), 0, 0]
1289 } else if idx > 8*1 {
1290 vec![1 << (idx - 8*1), 0]
1296 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>) {
1297 let secp_ctx = Secp256k1::new();
1298 let logger = Arc::new(test_utils::TestLogger::new());
1299 let chain_monitor = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1300 let net_graph_msg_handler = NetGraphMsgHandler::new(genesis_block(Network::Testnet).header.block_hash(), None, Arc::clone(&logger));
1301 // Build network from our_id to node7:
1303 // -1(1)2- node0 -1(3)2-
1305 // our_id -1(12)2- node7 -1(13)2--- node2
1307 // -1(2)2- node1 -1(4)2-
1310 // chan1 1-to-2: disabled
1311 // chan1 2-to-1: enabled, 0 fee
1313 // chan2 1-to-2: enabled, ignored fee
1314 // chan2 2-to-1: enabled, 0 fee
1316 // chan3 1-to-2: enabled, 0 fee
1317 // chan3 2-to-1: enabled, 100 msat fee
1319 // chan4 1-to-2: enabled, 100% fee
1320 // chan4 2-to-1: enabled, 0 fee
1322 // chan12 1-to-2: enabled, ignored fee
1323 // chan12 2-to-1: enabled, 0 fee
1325 // chan13 1-to-2: enabled, 200% fee
1326 // chan13 2-to-1: enabled, 0 fee
1329 // -1(5)2- node3 -1(8)2--
1333 // node2--1(6)2- node4 -1(9)2--- node6 (not in global route map)
1335 // -1(7)2- node5 -1(10)2-
1337 // chan5 1-to-2: enabled, 100 msat fee
1338 // chan5 2-to-1: enabled, 0 fee
1340 // chan6 1-to-2: enabled, 0 fee
1341 // chan6 2-to-1: enabled, 0 fee
1343 // chan7 1-to-2: enabled, 100% fee
1344 // chan7 2-to-1: enabled, 0 fee
1346 // chan8 1-to-2: enabled, variable fee (0 then 1000 msat)
1347 // chan8 2-to-1: enabled, 0 fee
1349 // chan9 1-to-2: enabled, 1001 msat fee
1350 // chan9 2-to-1: enabled, 0 fee
1352 // chan10 1-to-2: enabled, 0 fee
1353 // chan10 2-to-1: enabled, 0 fee
1355 // chan11 1-to-2: enabled, 0 fee
1356 // chan11 2-to-1: enabled, 0 fee
1358 let (our_privkey, _, privkeys, _) = get_nodes(&secp_ctx);
1360 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[0], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
1361 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1362 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1363 short_channel_id: 1,
1366 cltv_expiry_delta: 0,
1367 htlc_minimum_msat: 0,
1368 htlc_maximum_msat: OptionalField::Absent,
1370 fee_proportional_millionths: 0,
1371 excess_data: Vec::new()
1374 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
1376 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
1377 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1378 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1379 short_channel_id: 2,
1382 cltv_expiry_delta: u16::max_value(),
1383 htlc_minimum_msat: 0,
1384 htlc_maximum_msat: OptionalField::Absent,
1385 fee_base_msat: u32::max_value(),
1386 fee_proportional_millionths: u32::max_value(),
1387 excess_data: Vec::new()
1389 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1390 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1391 short_channel_id: 2,
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[1], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
1404 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[7], ChannelFeatures::from_le_bytes(id_to_feature_flags(12)), 12);
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: 12,
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[7], UnsignedChannelUpdate {
1418 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1419 short_channel_id: 12,
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[7], NodeFeatures::from_le_bytes(id_to_feature_flags(8)), 0);
1432 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
1433 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1434 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1435 short_channel_id: 3,
1438 cltv_expiry_delta: (3 << 8) | 1,
1439 htlc_minimum_msat: 0,
1440 htlc_maximum_msat: OptionalField::Absent,
1442 fee_proportional_millionths: 0,
1443 excess_data: Vec::new()
1445 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1446 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1447 short_channel_id: 3,
1450 cltv_expiry_delta: (3 << 8) | 2,
1451 htlc_minimum_msat: 0,
1452 htlc_maximum_msat: OptionalField::Absent,
1454 fee_proportional_millionths: 0,
1455 excess_data: Vec::new()
1458 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
1459 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1460 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1461 short_channel_id: 4,
1464 cltv_expiry_delta: (4 << 8) | 1,
1465 htlc_minimum_msat: 0,
1466 htlc_maximum_msat: OptionalField::Absent,
1468 fee_proportional_millionths: 1000000,
1469 excess_data: Vec::new()
1471 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1472 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1473 short_channel_id: 4,
1476 cltv_expiry_delta: (4 << 8) | 2,
1477 htlc_minimum_msat: 0,
1478 htlc_maximum_msat: OptionalField::Absent,
1480 fee_proportional_millionths: 0,
1481 excess_data: Vec::new()
1484 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(13)), 13);
1485 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1486 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1487 short_channel_id: 13,
1490 cltv_expiry_delta: (13 << 8) | 1,
1491 htlc_minimum_msat: 0,
1492 htlc_maximum_msat: OptionalField::Absent,
1494 fee_proportional_millionths: 2000000,
1495 excess_data: Vec::new()
1497 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1498 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1499 short_channel_id: 13,
1502 cltv_expiry_delta: (13 << 8) | 2,
1503 htlc_minimum_msat: 0,
1504 htlc_maximum_msat: OptionalField::Absent,
1506 fee_proportional_millionths: 0,
1507 excess_data: Vec::new()
1510 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
1512 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
1513 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1514 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1515 short_channel_id: 6,
1518 cltv_expiry_delta: (6 << 8) | 1,
1519 htlc_minimum_msat: 0,
1520 htlc_maximum_msat: OptionalField::Absent,
1522 fee_proportional_millionths: 0,
1523 excess_data: Vec::new()
1525 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1526 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1527 short_channel_id: 6,
1530 cltv_expiry_delta: (6 << 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_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(11)), 11);
1539 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1540 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1541 short_channel_id: 11,
1544 cltv_expiry_delta: (11 << 8) | 1,
1545 htlc_minimum_msat: 0,
1546 htlc_maximum_msat: OptionalField::Absent,
1548 fee_proportional_millionths: 0,
1549 excess_data: Vec::new()
1551 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
1552 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1553 short_channel_id: 11,
1556 cltv_expiry_delta: (11 << 8) | 2,
1557 htlc_minimum_msat: 0,
1558 htlc_maximum_msat: OptionalField::Absent,
1560 fee_proportional_millionths: 0,
1561 excess_data: Vec::new()
1564 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(5)), 0);
1566 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
1568 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[5], ChannelFeatures::from_le_bytes(id_to_feature_flags(7)), 7);
1569 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1570 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1571 short_channel_id: 7,
1574 cltv_expiry_delta: (7 << 8) | 1,
1575 htlc_minimum_msat: 0,
1576 htlc_maximum_msat: OptionalField::Absent,
1578 fee_proportional_millionths: 1000000,
1579 excess_data: Vec::new()
1581 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[5], UnsignedChannelUpdate {
1582 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1583 short_channel_id: 7,
1586 cltv_expiry_delta: (7 << 8) | 2,
1587 htlc_minimum_msat: 0,
1588 htlc_maximum_msat: OptionalField::Absent,
1590 fee_proportional_millionths: 0,
1591 excess_data: Vec::new()
1594 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[5], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
1596 (secp_ctx, net_graph_msg_handler, chain_monitor, logger)
1600 fn simple_route_test() {
1601 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1602 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1604 // Simple route to 2 via 1
1606 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)) {
1607 assert_eq!(err, "Cannot send a payment of 0 msat");
1608 } else { panic!(); }
1610 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();
1611 assert_eq!(route.paths[0].len(), 2);
1613 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
1614 assert_eq!(route.paths[0][0].short_channel_id, 2);
1615 assert_eq!(route.paths[0][0].fee_msat, 100);
1616 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
1617 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
1618 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
1620 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1621 assert_eq!(route.paths[0][1].short_channel_id, 4);
1622 assert_eq!(route.paths[0][1].fee_msat, 100);
1623 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1624 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1625 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
1629 fn invalid_first_hop_test() {
1630 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1631 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1633 // Simple route to 2 via 1
1635 let our_chans = vec![channelmanager::ChannelDetails {
1636 channel_id: [0; 32],
1637 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
1638 short_channel_id: Some(2),
1639 remote_network_id: our_id,
1640 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1641 channel_value_satoshis: 100000,
1643 outbound_capacity_msat: 100000,
1644 inbound_capacity_msat: 100000,
1645 is_outbound: true, is_funding_locked: true,
1646 is_usable: true, is_public: true,
1647 counterparty_forwarding_info: None,
1650 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)) {
1651 assert_eq!(err, "First hop cannot have our_node_id as a destination.");
1652 } else { panic!(); }
1654 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();
1655 assert_eq!(route.paths[0].len(), 2);
1659 fn htlc_minimum_test() {
1660 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1661 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1663 // Simple route to 2 via 1
1665 // Disable other paths
1666 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1667 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1668 short_channel_id: 12,
1670 flags: 2, // to disable
1671 cltv_expiry_delta: 0,
1672 htlc_minimum_msat: 0,
1673 htlc_maximum_msat: OptionalField::Absent,
1675 fee_proportional_millionths: 0,
1676 excess_data: Vec::new()
1678 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1679 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1680 short_channel_id: 3,
1682 flags: 2, // to disable
1683 cltv_expiry_delta: 0,
1684 htlc_minimum_msat: 0,
1685 htlc_maximum_msat: OptionalField::Absent,
1687 fee_proportional_millionths: 0,
1688 excess_data: Vec::new()
1690 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1691 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1692 short_channel_id: 13,
1694 flags: 2, // to disable
1695 cltv_expiry_delta: 0,
1696 htlc_minimum_msat: 0,
1697 htlc_maximum_msat: OptionalField::Absent,
1699 fee_proportional_millionths: 0,
1700 excess_data: Vec::new()
1702 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1703 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1704 short_channel_id: 6,
1706 flags: 2, // to disable
1707 cltv_expiry_delta: 0,
1708 htlc_minimum_msat: 0,
1709 htlc_maximum_msat: OptionalField::Absent,
1711 fee_proportional_millionths: 0,
1712 excess_data: Vec::new()
1714 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1715 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1716 short_channel_id: 7,
1718 flags: 2, // to disable
1719 cltv_expiry_delta: 0,
1720 htlc_minimum_msat: 0,
1721 htlc_maximum_msat: OptionalField::Absent,
1723 fee_proportional_millionths: 0,
1724 excess_data: Vec::new()
1727 // Check against amount_to_transfer_over_msat.
1728 // Set minimal HTLC of 200_000_000 msat.
1729 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1730 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1731 short_channel_id: 2,
1734 cltv_expiry_delta: 0,
1735 htlc_minimum_msat: 200_000_000,
1736 htlc_maximum_msat: OptionalField::Absent,
1738 fee_proportional_millionths: 0,
1739 excess_data: Vec::new()
1742 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
1744 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1745 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1746 short_channel_id: 4,
1749 cltv_expiry_delta: 0,
1750 htlc_minimum_msat: 0,
1751 htlc_maximum_msat: OptionalField::Present(199_999_999),
1753 fee_proportional_millionths: 0,
1754 excess_data: Vec::new()
1757 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
1758 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)) {
1759 assert_eq!(err, "Failed to find a path to the given destination");
1760 } else { panic!(); }
1762 // Lift the restriction on the first hop.
1763 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1764 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1765 short_channel_id: 2,
1768 cltv_expiry_delta: 0,
1769 htlc_minimum_msat: 0,
1770 htlc_maximum_msat: OptionalField::Absent,
1772 fee_proportional_millionths: 0,
1773 excess_data: Vec::new()
1776 // A payment above the minimum should pass
1777 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();
1778 assert_eq!(route.paths[0].len(), 2);
1782 fn htlc_minimum_overpay_test() {
1783 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1784 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1786 // A route to node#2 via two paths.
1787 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
1788 // Thus, they can't send 60 without overpaying.
1789 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1790 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1791 short_channel_id: 2,
1794 cltv_expiry_delta: 0,
1795 htlc_minimum_msat: 35_000,
1796 htlc_maximum_msat: OptionalField::Present(40_000),
1798 fee_proportional_millionths: 0,
1799 excess_data: Vec::new()
1801 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1802 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1803 short_channel_id: 12,
1806 cltv_expiry_delta: 0,
1807 htlc_minimum_msat: 35_000,
1808 htlc_maximum_msat: OptionalField::Present(40_000),
1810 fee_proportional_millionths: 0,
1811 excess_data: Vec::new()
1815 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1816 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1817 short_channel_id: 13,
1820 cltv_expiry_delta: 0,
1821 htlc_minimum_msat: 0,
1822 htlc_maximum_msat: OptionalField::Absent,
1824 fee_proportional_millionths: 0,
1825 excess_data: Vec::new()
1827 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1828 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1829 short_channel_id: 4,
1832 cltv_expiry_delta: 0,
1833 htlc_minimum_msat: 0,
1834 htlc_maximum_msat: OptionalField::Absent,
1836 fee_proportional_millionths: 0,
1837 excess_data: Vec::new()
1840 // Disable other paths
1841 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1842 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1843 short_channel_id: 1,
1845 flags: 2, // to disable
1846 cltv_expiry_delta: 0,
1847 htlc_minimum_msat: 0,
1848 htlc_maximum_msat: OptionalField::Absent,
1850 fee_proportional_millionths: 0,
1851 excess_data: Vec::new()
1854 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
1855 Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger)).unwrap();
1856 // Overpay fees to hit htlc_minimum_msat.
1857 let overpaid_fees = route.paths[0][0].fee_msat + route.paths[1][0].fee_msat;
1858 // TODO: this could be better balanced to overpay 10k and not 15k.
1859 assert_eq!(overpaid_fees, 15_000);
1861 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
1862 // while taking even more fee to match htlc_minimum_msat.
1863 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1864 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1865 short_channel_id: 12,
1868 cltv_expiry_delta: 0,
1869 htlc_minimum_msat: 65_000,
1870 htlc_maximum_msat: OptionalField::Present(80_000),
1872 fee_proportional_millionths: 0,
1873 excess_data: Vec::new()
1875 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1876 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1877 short_channel_id: 2,
1880 cltv_expiry_delta: 0,
1881 htlc_minimum_msat: 0,
1882 htlc_maximum_msat: OptionalField::Absent,
1884 fee_proportional_millionths: 0,
1885 excess_data: Vec::new()
1887 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1888 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1889 short_channel_id: 4,
1892 cltv_expiry_delta: 0,
1893 htlc_minimum_msat: 0,
1894 htlc_maximum_msat: OptionalField::Absent,
1896 fee_proportional_millionths: 100_000,
1897 excess_data: Vec::new()
1900 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
1901 Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger)).unwrap();
1902 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
1903 assert_eq!(route.paths.len(), 1);
1904 assert_eq!(route.paths[0][0].short_channel_id, 12);
1905 let fees = route.paths[0][0].fee_msat;
1906 assert_eq!(fees, 5_000);
1908 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
1909 Some(InvoiceFeatures::known()), None, &Vec::new(), 50_000, 42, Arc::clone(&logger)).unwrap();
1910 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
1911 // the other channel.
1912 assert_eq!(route.paths.len(), 1);
1913 assert_eq!(route.paths[0][0].short_channel_id, 2);
1914 let fees = route.paths[0][0].fee_msat;
1915 assert_eq!(fees, 5_000);
1919 fn disable_channels_test() {
1920 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1921 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1923 // // Disable channels 4 and 12 by flags=2
1924 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1925 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1926 short_channel_id: 4,
1928 flags: 2, // to disable
1929 cltv_expiry_delta: 0,
1930 htlc_minimum_msat: 0,
1931 htlc_maximum_msat: OptionalField::Absent,
1933 fee_proportional_millionths: 0,
1934 excess_data: Vec::new()
1936 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1937 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1938 short_channel_id: 12,
1940 flags: 2, // to disable
1941 cltv_expiry_delta: 0,
1942 htlc_minimum_msat: 0,
1943 htlc_maximum_msat: OptionalField::Absent,
1945 fee_proportional_millionths: 0,
1946 excess_data: Vec::new()
1949 // If all the channels require some features we don't understand, route should fail
1950 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)) {
1951 assert_eq!(err, "Failed to find a path to the given destination");
1952 } else { panic!(); }
1954 // If we specify a channel to node7, that overrides our local channel view and that gets used
1955 let our_chans = vec![channelmanager::ChannelDetails {
1956 channel_id: [0; 32],
1957 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
1958 short_channel_id: Some(42),
1959 remote_network_id: nodes[7].clone(),
1960 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1961 channel_value_satoshis: 0,
1963 outbound_capacity_msat: 250_000_000,
1964 inbound_capacity_msat: 0,
1965 is_outbound: true, is_funding_locked: true,
1966 is_usable: true, is_public: true,
1967 counterparty_forwarding_info: None,
1969 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();
1970 assert_eq!(route.paths[0].len(), 2);
1972 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
1973 assert_eq!(route.paths[0][0].short_channel_id, 42);
1974 assert_eq!(route.paths[0][0].fee_msat, 200);
1975 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
1976 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
1977 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
1979 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1980 assert_eq!(route.paths[0][1].short_channel_id, 13);
1981 assert_eq!(route.paths[0][1].fee_msat, 100);
1982 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1983 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1984 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
1988 fn disable_node_test() {
1989 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1990 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1992 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
1993 let mut unknown_features = NodeFeatures::known();
1994 unknown_features.set_required_unknown_bits();
1995 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
1996 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
1997 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
1999 // If all nodes require some features we don't understand, route should fail
2000 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)) {
2001 assert_eq!(err, "Failed to find a path to the given destination");
2002 } else { panic!(); }
2004 // If we specify a channel to node7, that overrides our local channel view and that gets used
2005 let our_chans = vec![channelmanager::ChannelDetails {
2006 channel_id: [0; 32],
2007 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
2008 short_channel_id: Some(42),
2009 remote_network_id: nodes[7].clone(),
2010 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
2011 channel_value_satoshis: 0,
2013 outbound_capacity_msat: 250_000_000,
2014 inbound_capacity_msat: 0,
2015 is_outbound: true, is_funding_locked: true,
2016 is_usable: true, is_public: true,
2017 counterparty_forwarding_info: None,
2019 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();
2020 assert_eq!(route.paths[0].len(), 2);
2022 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2023 assert_eq!(route.paths[0][0].short_channel_id, 42);
2024 assert_eq!(route.paths[0][0].fee_msat, 200);
2025 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
2026 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2027 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2029 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2030 assert_eq!(route.paths[0][1].short_channel_id, 13);
2031 assert_eq!(route.paths[0][1].fee_msat, 100);
2032 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2033 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2034 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2036 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
2037 // naively) assume that the user checked the feature bits on the invoice, which override
2038 // the node_announcement.
2042 fn our_chans_test() {
2043 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2044 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2046 // Route to 1 via 2 and 3 because our channel to 1 is disabled
2047 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();
2048 assert_eq!(route.paths[0].len(), 3);
2050 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2051 assert_eq!(route.paths[0][0].short_channel_id, 2);
2052 assert_eq!(route.paths[0][0].fee_msat, 200);
2053 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2054 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2055 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2057 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2058 assert_eq!(route.paths[0][1].short_channel_id, 4);
2059 assert_eq!(route.paths[0][1].fee_msat, 100);
2060 assert_eq!(route.paths[0][1].cltv_expiry_delta, (3 << 8) | 2);
2061 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2062 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2064 assert_eq!(route.paths[0][2].pubkey, nodes[0]);
2065 assert_eq!(route.paths[0][2].short_channel_id, 3);
2066 assert_eq!(route.paths[0][2].fee_msat, 100);
2067 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
2068 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(1));
2069 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(3));
2071 // If we specify a channel to node7, that overrides our local channel view and that gets used
2072 let our_chans = vec![channelmanager::ChannelDetails {
2073 channel_id: [0; 32],
2074 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
2075 short_channel_id: Some(42),
2076 remote_network_id: nodes[7].clone(),
2077 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
2078 channel_value_satoshis: 0,
2080 outbound_capacity_msat: 250_000_000,
2081 inbound_capacity_msat: 0,
2082 is_outbound: true, is_funding_locked: true,
2083 is_usable: true, is_public: true,
2084 counterparty_forwarding_info: None,
2086 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();
2087 assert_eq!(route.paths[0].len(), 2);
2089 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2090 assert_eq!(route.paths[0][0].short_channel_id, 42);
2091 assert_eq!(route.paths[0][0].fee_msat, 200);
2092 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
2093 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2094 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2096 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2097 assert_eq!(route.paths[0][1].short_channel_id, 13);
2098 assert_eq!(route.paths[0][1].fee_msat, 100);
2099 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2100 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2101 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2104 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2105 let zero_fees = RoutingFees {
2107 proportional_millionths: 0,
2109 vec![RouteHint(vec![RouteHintHop {
2110 src_node_id: nodes[3].clone(),
2111 short_channel_id: 8,
2113 cltv_expiry_delta: (8 << 8) | 1,
2114 htlc_minimum_msat: None,
2115 htlc_maximum_msat: None,
2116 }]), RouteHint(vec![RouteHintHop {
2117 src_node_id: nodes[4].clone(),
2118 short_channel_id: 9,
2121 proportional_millionths: 0,
2123 cltv_expiry_delta: (9 << 8) | 1,
2124 htlc_minimum_msat: None,
2125 htlc_maximum_msat: None,
2126 }]), RouteHint(vec![RouteHintHop {
2127 src_node_id: nodes[5].clone(),
2128 short_channel_id: 10,
2130 cltv_expiry_delta: (10 << 8) | 1,
2131 htlc_minimum_msat: None,
2132 htlc_maximum_msat: None,
2137 fn last_hops_test() {
2138 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2139 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2141 // Simple test across 2, 3, 5, and 4 via a last_hop channel
2143 // First check that last hop can't have its source as the payee.
2144 let invalid_last_hop = RouteHint(vec![RouteHintHop {
2145 src_node_id: nodes[6],
2146 short_channel_id: 8,
2149 proportional_millionths: 0,
2151 cltv_expiry_delta: (8 << 8) | 1,
2152 htlc_minimum_msat: None,
2153 htlc_maximum_msat: None,
2156 let mut invalid_last_hops = last_hops(&nodes);
2157 invalid_last_hops.push(invalid_last_hop);
2159 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)) {
2160 assert_eq!(err, "Last hop cannot have a payee as a source.");
2161 } else { panic!(); }
2164 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();
2165 assert_eq!(route.paths[0].len(), 5);
2167 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2168 assert_eq!(route.paths[0][0].short_channel_id, 2);
2169 assert_eq!(route.paths[0][0].fee_msat, 100);
2170 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2171 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2172 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2174 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2175 assert_eq!(route.paths[0][1].short_channel_id, 4);
2176 assert_eq!(route.paths[0][1].fee_msat, 0);
2177 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2178 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2179 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2181 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2182 assert_eq!(route.paths[0][2].short_channel_id, 6);
2183 assert_eq!(route.paths[0][2].fee_msat, 0);
2184 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2185 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2186 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2188 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2189 assert_eq!(route.paths[0][3].short_channel_id, 11);
2190 assert_eq!(route.paths[0][3].fee_msat, 0);
2191 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2192 // If we have a peer in the node map, we'll use their features here since we don't have
2193 // a way of figuring out their features from the invoice:
2194 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2195 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2197 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2198 assert_eq!(route.paths[0][4].short_channel_id, 8);
2199 assert_eq!(route.paths[0][4].fee_msat, 100);
2200 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2201 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2202 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2206 fn our_chans_last_hop_connect_test() {
2207 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2208 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2210 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
2211 let our_chans = vec![channelmanager::ChannelDetails {
2212 channel_id: [0; 32],
2213 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
2214 short_channel_id: Some(42),
2215 remote_network_id: nodes[3].clone(),
2216 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
2217 channel_value_satoshis: 0,
2219 outbound_capacity_msat: 250_000_000,
2220 inbound_capacity_msat: 0,
2221 is_outbound: true, is_funding_locked: true,
2222 is_usable: true, is_public: true,
2223 counterparty_forwarding_info: None,
2225 let mut last_hops = last_hops(&nodes);
2226 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();
2227 assert_eq!(route.paths[0].len(), 2);
2229 assert_eq!(route.paths[0][0].pubkey, nodes[3]);
2230 assert_eq!(route.paths[0][0].short_channel_id, 42);
2231 assert_eq!(route.paths[0][0].fee_msat, 0);
2232 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
2233 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2234 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2236 assert_eq!(route.paths[0][1].pubkey, nodes[6]);
2237 assert_eq!(route.paths[0][1].short_channel_id, 8);
2238 assert_eq!(route.paths[0][1].fee_msat, 100);
2239 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2240 assert_eq!(route.paths[0][1].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2241 assert_eq!(route.paths[0][1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2243 last_hops[0].0[0].fees.base_msat = 1000;
2245 // Revert to via 6 as the fee on 8 goes up
2246 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();
2247 assert_eq!(route.paths[0].len(), 4);
2249 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2250 assert_eq!(route.paths[0][0].short_channel_id, 2);
2251 assert_eq!(route.paths[0][0].fee_msat, 200); // fee increased as its % of value transferred across node
2252 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2253 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2254 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2256 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2257 assert_eq!(route.paths[0][1].short_channel_id, 4);
2258 assert_eq!(route.paths[0][1].fee_msat, 100);
2259 assert_eq!(route.paths[0][1].cltv_expiry_delta, (7 << 8) | 1);
2260 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2261 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2263 assert_eq!(route.paths[0][2].pubkey, nodes[5]);
2264 assert_eq!(route.paths[0][2].short_channel_id, 7);
2265 assert_eq!(route.paths[0][2].fee_msat, 0);
2266 assert_eq!(route.paths[0][2].cltv_expiry_delta, (10 << 8) | 1);
2267 // If we have a peer in the node map, we'll use their features here since we don't have
2268 // a way of figuring out their features from the invoice:
2269 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
2270 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(7));
2272 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2273 assert_eq!(route.paths[0][3].short_channel_id, 10);
2274 assert_eq!(route.paths[0][3].fee_msat, 100);
2275 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2276 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2277 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2279 // ...but still use 8 for larger payments as 6 has a variable feerate
2280 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();
2281 assert_eq!(route.paths[0].len(), 5);
2283 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2284 assert_eq!(route.paths[0][0].short_channel_id, 2);
2285 assert_eq!(route.paths[0][0].fee_msat, 3000);
2286 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2287 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2288 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2290 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2291 assert_eq!(route.paths[0][1].short_channel_id, 4);
2292 assert_eq!(route.paths[0][1].fee_msat, 0);
2293 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2294 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2295 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2297 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2298 assert_eq!(route.paths[0][2].short_channel_id, 6);
2299 assert_eq!(route.paths[0][2].fee_msat, 0);
2300 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2301 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2302 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2304 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2305 assert_eq!(route.paths[0][3].short_channel_id, 11);
2306 assert_eq!(route.paths[0][3].fee_msat, 1000);
2307 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2308 // If we have a peer in the node map, we'll use their features here since we don't have
2309 // a way of figuring out their features from the invoice:
2310 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2311 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2313 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2314 assert_eq!(route.paths[0][4].short_channel_id, 8);
2315 assert_eq!(route.paths[0][4].fee_msat, 2000);
2316 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2317 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2318 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2322 fn unannounced_path_test() {
2323 // We should be able to send a payment to a destination without any help of a routing graph
2324 // if we have a channel with a common counterparty that appears in the first and last hop
2326 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
2327 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
2328 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
2330 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
2331 let last_hops = RouteHint(vec![RouteHintHop {
2332 src_node_id: middle_node_id,
2333 short_channel_id: 8,
2336 proportional_millionths: 0,
2338 cltv_expiry_delta: (8 << 8) | 1,
2339 htlc_minimum_msat: None,
2340 htlc_maximum_msat: None,
2342 let our_chans = vec![channelmanager::ChannelDetails {
2343 channel_id: [0; 32],
2344 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
2345 short_channel_id: Some(42),
2346 remote_network_id: middle_node_id,
2347 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
2348 channel_value_satoshis: 100000,
2350 outbound_capacity_msat: 100000,
2351 inbound_capacity_msat: 100000,
2352 is_outbound: true, is_funding_locked: true,
2353 is_usable: true, is_public: true,
2354 counterparty_forwarding_info: None,
2356 let route = get_route(&source_node_id, &NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()), &target_node_id, None, Some(&our_chans.iter().collect::<Vec<_>>()), &vec![&last_hops], 100, 42, Arc::new(test_utils::TestLogger::new())).unwrap();
2358 assert_eq!(route.paths[0].len(), 2);
2360 assert_eq!(route.paths[0][0].pubkey, middle_node_id);
2361 assert_eq!(route.paths[0][0].short_channel_id, 42);
2362 assert_eq!(route.paths[0][0].fee_msat, 1000);
2363 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
2364 assert_eq!(route.paths[0][0].node_features.le_flags(), &[0b11]);
2365 assert_eq!(route.paths[0][0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
2367 assert_eq!(route.paths[0][1].pubkey, target_node_id);
2368 assert_eq!(route.paths[0][1].short_channel_id, 8);
2369 assert_eq!(route.paths[0][1].fee_msat, 100);
2370 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2371 assert_eq!(route.paths[0][1].node_features.le_flags(), &[0; 0]); // We dont pass flags in from invoices yet
2372 assert_eq!(route.paths[0][1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
2376 fn available_amount_while_routing_test() {
2377 // Tests whether we choose the correct available channel amount while routing.
2379 let (secp_ctx, mut net_graph_msg_handler, chain_monitor, logger) = build_graph();
2380 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2382 // We will use a simple single-path route from
2383 // our node to node2 via node0: channels {1, 3}.
2385 // First disable all other paths.
2386 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2387 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2388 short_channel_id: 2,
2391 cltv_expiry_delta: 0,
2392 htlc_minimum_msat: 0,
2393 htlc_maximum_msat: OptionalField::Present(100_000),
2395 fee_proportional_millionths: 0,
2396 excess_data: Vec::new()
2398 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2399 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2400 short_channel_id: 12,
2403 cltv_expiry_delta: 0,
2404 htlc_minimum_msat: 0,
2405 htlc_maximum_msat: OptionalField::Present(100_000),
2407 fee_proportional_millionths: 0,
2408 excess_data: Vec::new()
2411 // Make the first channel (#1) very permissive,
2412 // and we will be testing all limits on the second channel.
2413 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2414 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2415 short_channel_id: 1,
2418 cltv_expiry_delta: 0,
2419 htlc_minimum_msat: 0,
2420 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2422 fee_proportional_millionths: 0,
2423 excess_data: Vec::new()
2426 // First, let's see if routing works if we have absolutely no idea about the available amount.
2427 // In this case, it should be set to 250_000 sats.
2428 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2429 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2430 short_channel_id: 3,
2433 cltv_expiry_delta: 0,
2434 htlc_minimum_msat: 0,
2435 htlc_maximum_msat: OptionalField::Absent,
2437 fee_proportional_millionths: 0,
2438 excess_data: Vec::new()
2442 // Attempt to route more than available results in a failure.
2443 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2444 Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000_001, 42, Arc::clone(&logger)) {
2445 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2446 } else { panic!(); }
2450 // Now, attempt to route an exact amount we have should be fine.
2451 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2452 Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000_000, 42, Arc::clone(&logger)).unwrap();
2453 assert_eq!(route.paths.len(), 1);
2454 let path = route.paths.last().unwrap();
2455 assert_eq!(path.len(), 2);
2456 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2457 assert_eq!(path.last().unwrap().fee_msat, 250_000_000);
2460 // Check that setting outbound_capacity_msat in first_hops limits the channels.
2461 // Disable channel #1 and use another first hop.
2462 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2463 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2464 short_channel_id: 1,
2467 cltv_expiry_delta: 0,
2468 htlc_minimum_msat: 0,
2469 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2471 fee_proportional_millionths: 0,
2472 excess_data: Vec::new()
2475 // Now, limit the first_hop by the outbound_capacity_msat of 200_000 sats.
2476 let our_chans = vec![channelmanager::ChannelDetails {
2477 channel_id: [0; 32],
2478 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
2479 short_channel_id: Some(42),
2480 remote_network_id: nodes[0].clone(),
2481 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
2482 channel_value_satoshis: 0,
2484 outbound_capacity_msat: 200_000_000,
2485 inbound_capacity_msat: 0,
2486 is_outbound: true, is_funding_locked: true,
2487 is_usable: true, is_public: true,
2488 counterparty_forwarding_info: None,
2492 // Attempt to route more than available results in a failure.
2493 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2494 Some(InvoiceFeatures::known()), Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 200_000_001, 42, Arc::clone(&logger)) {
2495 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2496 } else { panic!(); }
2500 // Now, attempt to route an exact amount we have should be fine.
2501 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2502 Some(InvoiceFeatures::known()), Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 200_000_000, 42, Arc::clone(&logger)).unwrap();
2503 assert_eq!(route.paths.len(), 1);
2504 let path = route.paths.last().unwrap();
2505 assert_eq!(path.len(), 2);
2506 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2507 assert_eq!(path.last().unwrap().fee_msat, 200_000_000);
2510 // Enable channel #1 back.
2511 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2512 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2513 short_channel_id: 1,
2516 cltv_expiry_delta: 0,
2517 htlc_minimum_msat: 0,
2518 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2520 fee_proportional_millionths: 0,
2521 excess_data: Vec::new()
2525 // Now let's see if routing works if we know only htlc_maximum_msat.
2526 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2527 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2528 short_channel_id: 3,
2531 cltv_expiry_delta: 0,
2532 htlc_minimum_msat: 0,
2533 htlc_maximum_msat: OptionalField::Present(15_000),
2535 fee_proportional_millionths: 0,
2536 excess_data: Vec::new()
2540 // Attempt to route more than available results in a failure.
2541 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2542 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_001, 42, Arc::clone(&logger)) {
2543 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2544 } else { panic!(); }
2548 // Now, attempt to route an exact amount we have should be fine.
2549 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2550 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_000, 42, Arc::clone(&logger)).unwrap();
2551 assert_eq!(route.paths.len(), 1);
2552 let path = route.paths.last().unwrap();
2553 assert_eq!(path.len(), 2);
2554 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2555 assert_eq!(path.last().unwrap().fee_msat, 15_000);
2558 // Now let's see if routing works if we know only capacity from the UTXO.
2560 // We can't change UTXO capacity on the fly, so we'll disable
2561 // the existing channel and add another one with the capacity we need.
2562 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2563 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2564 short_channel_id: 3,
2567 cltv_expiry_delta: 0,
2568 htlc_minimum_msat: 0,
2569 htlc_maximum_msat: OptionalField::Absent,
2571 fee_proportional_millionths: 0,
2572 excess_data: Vec::new()
2575 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
2576 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
2577 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
2578 .push_opcode(opcodes::all::OP_PUSHNUM_2)
2579 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
2581 *chain_monitor.utxo_ret.lock().unwrap() = Ok(TxOut { value: 15, script_pubkey: good_script.clone() });
2582 net_graph_msg_handler.add_chain_access(Some(chain_monitor));
2584 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
2585 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2586 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2587 short_channel_id: 333,
2590 cltv_expiry_delta: (3 << 8) | 1,
2591 htlc_minimum_msat: 0,
2592 htlc_maximum_msat: OptionalField::Absent,
2594 fee_proportional_millionths: 0,
2595 excess_data: Vec::new()
2597 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2598 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2599 short_channel_id: 333,
2602 cltv_expiry_delta: (3 << 8) | 2,
2603 htlc_minimum_msat: 0,
2604 htlc_maximum_msat: OptionalField::Absent,
2606 fee_proportional_millionths: 0,
2607 excess_data: Vec::new()
2611 // Attempt to route more than available results in a failure.
2612 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2613 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_001, 42, Arc::clone(&logger)) {
2614 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2615 } else { panic!(); }
2619 // Now, attempt to route an exact amount we have should be fine.
2620 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2621 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_000, 42, Arc::clone(&logger)).unwrap();
2622 assert_eq!(route.paths.len(), 1);
2623 let path = route.paths.last().unwrap();
2624 assert_eq!(path.len(), 2);
2625 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2626 assert_eq!(path.last().unwrap().fee_msat, 15_000);
2629 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
2630 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2631 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2632 short_channel_id: 333,
2635 cltv_expiry_delta: 0,
2636 htlc_minimum_msat: 0,
2637 htlc_maximum_msat: OptionalField::Present(10_000),
2639 fee_proportional_millionths: 0,
2640 excess_data: Vec::new()
2644 // Attempt to route more than available results in a failure.
2645 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2646 Some(InvoiceFeatures::known()), None, &Vec::new(), 10_001, 42, Arc::clone(&logger)) {
2647 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2648 } else { panic!(); }
2652 // Now, attempt to route an exact amount we have should be fine.
2653 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2654 Some(InvoiceFeatures::known()), None, &Vec::new(), 10_000, 42, Arc::clone(&logger)).unwrap();
2655 assert_eq!(route.paths.len(), 1);
2656 let path = route.paths.last().unwrap();
2657 assert_eq!(path.len(), 2);
2658 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2659 assert_eq!(path.last().unwrap().fee_msat, 10_000);
2664 fn available_liquidity_last_hop_test() {
2665 // Check that available liquidity properly limits the path even when only
2666 // one of the latter hops is limited.
2667 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2668 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2670 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
2671 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
2672 // Total capacity: 50 sats.
2674 // Disable other potential paths.
2675 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2676 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2677 short_channel_id: 2,
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()
2687 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2688 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2689 short_channel_id: 7,
2692 cltv_expiry_delta: 0,
2693 htlc_minimum_msat: 0,
2694 htlc_maximum_msat: OptionalField::Present(100_000),
2696 fee_proportional_millionths: 0,
2697 excess_data: Vec::new()
2702 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2703 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2704 short_channel_id: 12,
2707 cltv_expiry_delta: 0,
2708 htlc_minimum_msat: 0,
2709 htlc_maximum_msat: OptionalField::Present(100_000),
2711 fee_proportional_millionths: 0,
2712 excess_data: Vec::new()
2714 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2715 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2716 short_channel_id: 13,
2719 cltv_expiry_delta: 0,
2720 htlc_minimum_msat: 0,
2721 htlc_maximum_msat: OptionalField::Present(100_000),
2723 fee_proportional_millionths: 0,
2724 excess_data: Vec::new()
2727 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2728 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2729 short_channel_id: 6,
2732 cltv_expiry_delta: 0,
2733 htlc_minimum_msat: 0,
2734 htlc_maximum_msat: OptionalField::Present(50_000),
2736 fee_proportional_millionths: 0,
2737 excess_data: Vec::new()
2739 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
2740 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2741 short_channel_id: 11,
2744 cltv_expiry_delta: 0,
2745 htlc_minimum_msat: 0,
2746 htlc_maximum_msat: OptionalField::Present(100_000),
2748 fee_proportional_millionths: 0,
2749 excess_data: Vec::new()
2752 // Attempt to route more than available results in a failure.
2753 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
2754 Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger)) {
2755 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2756 } else { panic!(); }
2760 // Now, attempt to route 49 sats (just a bit below the capacity).
2761 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
2762 Some(InvoiceFeatures::known()), None, &Vec::new(), 49_000, 42, Arc::clone(&logger)).unwrap();
2763 assert_eq!(route.paths.len(), 1);
2764 let mut total_amount_paid_msat = 0;
2765 for path in &route.paths {
2766 assert_eq!(path.len(), 4);
2767 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
2768 total_amount_paid_msat += path.last().unwrap().fee_msat;
2770 assert_eq!(total_amount_paid_msat, 49_000);
2774 // Attempt to route an exact amount is also fine
2775 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
2776 Some(InvoiceFeatures::known()), None, &Vec::new(), 50_000, 42, Arc::clone(&logger)).unwrap();
2777 assert_eq!(route.paths.len(), 1);
2778 let mut total_amount_paid_msat = 0;
2779 for path in &route.paths {
2780 assert_eq!(path.len(), 4);
2781 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
2782 total_amount_paid_msat += path.last().unwrap().fee_msat;
2784 assert_eq!(total_amount_paid_msat, 50_000);
2789 fn ignore_fee_first_hop_test() {
2790 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2791 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2793 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
2794 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2795 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2796 short_channel_id: 1,
2799 cltv_expiry_delta: 0,
2800 htlc_minimum_msat: 0,
2801 htlc_maximum_msat: OptionalField::Present(100_000),
2802 fee_base_msat: 1_000_000,
2803 fee_proportional_millionths: 0,
2804 excess_data: Vec::new()
2806 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2807 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2808 short_channel_id: 3,
2811 cltv_expiry_delta: 0,
2812 htlc_minimum_msat: 0,
2813 htlc_maximum_msat: OptionalField::Present(50_000),
2815 fee_proportional_millionths: 0,
2816 excess_data: Vec::new()
2820 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();
2821 assert_eq!(route.paths.len(), 1);
2822 let mut total_amount_paid_msat = 0;
2823 for path in &route.paths {
2824 assert_eq!(path.len(), 2);
2825 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2826 total_amount_paid_msat += path.last().unwrap().fee_msat;
2828 assert_eq!(total_amount_paid_msat, 50_000);
2833 fn simple_mpp_route_test() {
2834 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2835 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2837 // We need a route consisting of 3 paths:
2838 // From our node to node2 via node0, node7, node1 (three paths one hop each).
2839 // To achieve this, the amount being transferred should be around
2840 // the total capacity of these 3 paths.
2842 // First, we set limits on these (previously unlimited) channels.
2843 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
2845 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
2846 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2847 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2848 short_channel_id: 1,
2851 cltv_expiry_delta: 0,
2852 htlc_minimum_msat: 0,
2853 htlc_maximum_msat: OptionalField::Present(100_000),
2855 fee_proportional_millionths: 0,
2856 excess_data: Vec::new()
2858 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2859 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2860 short_channel_id: 3,
2863 cltv_expiry_delta: 0,
2864 htlc_minimum_msat: 0,
2865 htlc_maximum_msat: OptionalField::Present(50_000),
2867 fee_proportional_millionths: 0,
2868 excess_data: Vec::new()
2871 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
2872 // (total limit 60).
2873 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2874 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2875 short_channel_id: 12,
2878 cltv_expiry_delta: 0,
2879 htlc_minimum_msat: 0,
2880 htlc_maximum_msat: OptionalField::Present(60_000),
2882 fee_proportional_millionths: 0,
2883 excess_data: Vec::new()
2885 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2886 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2887 short_channel_id: 13,
2890 cltv_expiry_delta: 0,
2891 htlc_minimum_msat: 0,
2892 htlc_maximum_msat: OptionalField::Present(60_000),
2894 fee_proportional_millionths: 0,
2895 excess_data: Vec::new()
2898 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
2899 // (total capacity 180 sats).
2900 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2901 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2902 short_channel_id: 2,
2905 cltv_expiry_delta: 0,
2906 htlc_minimum_msat: 0,
2907 htlc_maximum_msat: OptionalField::Present(200_000),
2909 fee_proportional_millionths: 0,
2910 excess_data: Vec::new()
2912 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2913 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2914 short_channel_id: 4,
2917 cltv_expiry_delta: 0,
2918 htlc_minimum_msat: 0,
2919 htlc_maximum_msat: OptionalField::Present(180_000),
2921 fee_proportional_millionths: 0,
2922 excess_data: Vec::new()
2926 // Attempt to route more than available results in a failure.
2927 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(),
2928 &nodes[2], Some(InvoiceFeatures::known()), None, &Vec::new(), 300_000, 42, Arc::clone(&logger)) {
2929 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2930 } else { panic!(); }
2934 // Now, attempt to route 250 sats (just a bit below the capacity).
2935 // Our algorithm should provide us with these 3 paths.
2936 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2937 Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000, 42, Arc::clone(&logger)).unwrap();
2938 assert_eq!(route.paths.len(), 3);
2939 let mut total_amount_paid_msat = 0;
2940 for path in &route.paths {
2941 assert_eq!(path.len(), 2);
2942 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2943 total_amount_paid_msat += path.last().unwrap().fee_msat;
2945 assert_eq!(total_amount_paid_msat, 250_000);
2949 // Attempt to route an exact amount is also fine
2950 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2951 Some(InvoiceFeatures::known()), None, &Vec::new(), 290_000, 42, Arc::clone(&logger)).unwrap();
2952 assert_eq!(route.paths.len(), 3);
2953 let mut total_amount_paid_msat = 0;
2954 for path in &route.paths {
2955 assert_eq!(path.len(), 2);
2956 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2957 total_amount_paid_msat += path.last().unwrap().fee_msat;
2959 assert_eq!(total_amount_paid_msat, 290_000);
2964 fn long_mpp_route_test() {
2965 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2966 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2968 // We need a route consisting of 3 paths:
2969 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
2970 // Note that these paths overlap (channels 5, 12, 13).
2971 // We will route 300 sats.
2972 // Each path will have 100 sats capacity, those channels which
2973 // are used twice will have 200 sats capacity.
2975 // Disable other potential paths.
2976 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2977 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2978 short_channel_id: 2,
2981 cltv_expiry_delta: 0,
2982 htlc_minimum_msat: 0,
2983 htlc_maximum_msat: OptionalField::Present(100_000),
2985 fee_proportional_millionths: 0,
2986 excess_data: Vec::new()
2988 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2989 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2990 short_channel_id: 7,
2993 cltv_expiry_delta: 0,
2994 htlc_minimum_msat: 0,
2995 htlc_maximum_msat: OptionalField::Present(100_000),
2997 fee_proportional_millionths: 0,
2998 excess_data: Vec::new()
3001 // Path via {node0, node2} is channels {1, 3, 5}.
3002 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3003 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3004 short_channel_id: 1,
3007 cltv_expiry_delta: 0,
3008 htlc_minimum_msat: 0,
3009 htlc_maximum_msat: OptionalField::Present(100_000),
3011 fee_proportional_millionths: 0,
3012 excess_data: Vec::new()
3014 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3015 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3016 short_channel_id: 3,
3019 cltv_expiry_delta: 0,
3020 htlc_minimum_msat: 0,
3021 htlc_maximum_msat: OptionalField::Present(100_000),
3023 fee_proportional_millionths: 0,
3024 excess_data: Vec::new()
3027 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3028 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3029 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3030 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3031 short_channel_id: 5,
3034 cltv_expiry_delta: 0,
3035 htlc_minimum_msat: 0,
3036 htlc_maximum_msat: OptionalField::Present(200_000),
3038 fee_proportional_millionths: 0,
3039 excess_data: Vec::new()
3042 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3043 // Add 100 sats to the capacities of {12, 13}, because these channels
3044 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3045 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3046 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3047 short_channel_id: 12,
3050 cltv_expiry_delta: 0,
3051 htlc_minimum_msat: 0,
3052 htlc_maximum_msat: OptionalField::Present(200_000),
3054 fee_proportional_millionths: 0,
3055 excess_data: Vec::new()
3057 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3058 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3059 short_channel_id: 13,
3062 cltv_expiry_delta: 0,
3063 htlc_minimum_msat: 0,
3064 htlc_maximum_msat: OptionalField::Present(200_000),
3066 fee_proportional_millionths: 0,
3067 excess_data: Vec::new()
3070 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3071 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3072 short_channel_id: 6,
3075 cltv_expiry_delta: 0,
3076 htlc_minimum_msat: 0,
3077 htlc_maximum_msat: OptionalField::Present(100_000),
3079 fee_proportional_millionths: 0,
3080 excess_data: Vec::new()
3082 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3083 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3084 short_channel_id: 11,
3087 cltv_expiry_delta: 0,
3088 htlc_minimum_msat: 0,
3089 htlc_maximum_msat: OptionalField::Present(100_000),
3091 fee_proportional_millionths: 0,
3092 excess_data: Vec::new()
3095 // Path via {node7, node2} is channels {12, 13, 5}.
3096 // We already limited them to 200 sats (they are used twice for 100 sats).
3097 // Nothing to do here.
3100 // Attempt to route more than available results in a failure.
3101 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3102 Some(InvoiceFeatures::known()), None, &Vec::new(), 350_000, 42, Arc::clone(&logger)) {
3103 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3104 } else { panic!(); }
3108 // Now, attempt to route 300 sats (exact amount we can route).
3109 // Our algorithm should provide us with these 3 paths, 100 sats each.
3110 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3111 Some(InvoiceFeatures::known()), None, &Vec::new(), 300_000, 42, Arc::clone(&logger)).unwrap();
3112 assert_eq!(route.paths.len(), 3);
3114 let mut total_amount_paid_msat = 0;
3115 for path in &route.paths {
3116 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3117 total_amount_paid_msat += path.last().unwrap().fee_msat;
3119 assert_eq!(total_amount_paid_msat, 300_000);
3125 fn mpp_cheaper_route_test() {
3126 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3127 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3129 // This test checks that if we have two cheaper paths and one more expensive path,
3130 // so that liquidity-wise any 2 of 3 combination is sufficient,
3131 // two cheaper paths will be taken.
3132 // These paths have equal available liquidity.
3134 // We need a combination of 3 paths:
3135 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3136 // Note that these paths overlap (channels 5, 12, 13).
3137 // Each path will have 100 sats capacity, those channels which
3138 // are used twice will have 200 sats capacity.
3140 // Disable other potential paths.
3141 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3142 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3143 short_channel_id: 2,
3146 cltv_expiry_delta: 0,
3147 htlc_minimum_msat: 0,
3148 htlc_maximum_msat: OptionalField::Present(100_000),
3150 fee_proportional_millionths: 0,
3151 excess_data: Vec::new()
3153 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3154 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3155 short_channel_id: 7,
3158 cltv_expiry_delta: 0,
3159 htlc_minimum_msat: 0,
3160 htlc_maximum_msat: OptionalField::Present(100_000),
3162 fee_proportional_millionths: 0,
3163 excess_data: Vec::new()
3166 // Path via {node0, node2} is channels {1, 3, 5}.
3167 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3168 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3169 short_channel_id: 1,
3172 cltv_expiry_delta: 0,
3173 htlc_minimum_msat: 0,
3174 htlc_maximum_msat: OptionalField::Present(100_000),
3176 fee_proportional_millionths: 0,
3177 excess_data: Vec::new()
3179 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3180 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3181 short_channel_id: 3,
3184 cltv_expiry_delta: 0,
3185 htlc_minimum_msat: 0,
3186 htlc_maximum_msat: OptionalField::Present(100_000),
3188 fee_proportional_millionths: 0,
3189 excess_data: Vec::new()
3192 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3193 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3194 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3195 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3196 short_channel_id: 5,
3199 cltv_expiry_delta: 0,
3200 htlc_minimum_msat: 0,
3201 htlc_maximum_msat: OptionalField::Present(200_000),
3203 fee_proportional_millionths: 0,
3204 excess_data: Vec::new()
3207 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3208 // Add 100 sats to the capacities of {12, 13}, because these channels
3209 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3210 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3211 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3212 short_channel_id: 12,
3215 cltv_expiry_delta: 0,
3216 htlc_minimum_msat: 0,
3217 htlc_maximum_msat: OptionalField::Present(200_000),
3219 fee_proportional_millionths: 0,
3220 excess_data: Vec::new()
3222 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3223 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3224 short_channel_id: 13,
3227 cltv_expiry_delta: 0,
3228 htlc_minimum_msat: 0,
3229 htlc_maximum_msat: OptionalField::Present(200_000),
3231 fee_proportional_millionths: 0,
3232 excess_data: Vec::new()
3235 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3236 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3237 short_channel_id: 6,
3240 cltv_expiry_delta: 0,
3241 htlc_minimum_msat: 0,
3242 htlc_maximum_msat: OptionalField::Present(100_000),
3243 fee_base_msat: 1_000,
3244 fee_proportional_millionths: 0,
3245 excess_data: Vec::new()
3247 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3248 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3249 short_channel_id: 11,
3252 cltv_expiry_delta: 0,
3253 htlc_minimum_msat: 0,
3254 htlc_maximum_msat: OptionalField::Present(100_000),
3256 fee_proportional_millionths: 0,
3257 excess_data: Vec::new()
3260 // Path via {node7, node2} is channels {12, 13, 5}.
3261 // We already limited them to 200 sats (they are used twice for 100 sats).
3262 // Nothing to do here.
3265 // Now, attempt to route 180 sats.
3266 // Our algorithm should provide us with these 2 paths.
3267 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3268 Some(InvoiceFeatures::known()), None, &Vec::new(), 180_000, 42, Arc::clone(&logger)).unwrap();
3269 assert_eq!(route.paths.len(), 2);
3271 let mut total_value_transferred_msat = 0;
3272 let mut total_paid_msat = 0;
3273 for path in &route.paths {
3274 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3275 total_value_transferred_msat += path.last().unwrap().fee_msat;
3277 total_paid_msat += hop.fee_msat;
3280 // If we paid fee, this would be higher.
3281 assert_eq!(total_value_transferred_msat, 180_000);
3282 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
3283 assert_eq!(total_fees_paid, 0);
3288 fn fees_on_mpp_route_test() {
3289 // This test makes sure that MPP algorithm properly takes into account
3290 // fees charged on the channels, by making the fees impactful:
3291 // if the fee is not properly accounted for, the behavior is different.
3292 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3293 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3295 // We need a route consisting of 2 paths:
3296 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
3297 // We will route 200 sats, Each path will have 100 sats capacity.
3299 // This test is not particularly stable: e.g.,
3300 // there's a way to route via {node0, node2, node4}.
3301 // It works while pathfinding is deterministic, but can be broken otherwise.
3302 // It's fine to ignore this concern for now.
3304 // Disable other potential paths.
3305 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3306 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3307 short_channel_id: 2,
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 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3319 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3320 short_channel_id: 7,
3323 cltv_expiry_delta: 0,
3324 htlc_minimum_msat: 0,
3325 htlc_maximum_msat: OptionalField::Present(100_000),
3327 fee_proportional_millionths: 0,
3328 excess_data: Vec::new()
3331 // Path via {node0, node2} is channels {1, 3, 5}.
3332 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3333 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3334 short_channel_id: 1,
3337 cltv_expiry_delta: 0,
3338 htlc_minimum_msat: 0,
3339 htlc_maximum_msat: OptionalField::Present(100_000),
3341 fee_proportional_millionths: 0,
3342 excess_data: Vec::new()
3344 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3345 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3346 short_channel_id: 3,
3349 cltv_expiry_delta: 0,
3350 htlc_minimum_msat: 0,
3351 htlc_maximum_msat: OptionalField::Present(100_000),
3353 fee_proportional_millionths: 0,
3354 excess_data: Vec::new()
3357 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3358 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3359 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3360 short_channel_id: 5,
3363 cltv_expiry_delta: 0,
3364 htlc_minimum_msat: 0,
3365 htlc_maximum_msat: OptionalField::Present(100_000),
3367 fee_proportional_millionths: 0,
3368 excess_data: Vec::new()
3371 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3372 // All channels should be 100 sats capacity. But for the fee experiment,
3373 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
3374 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
3375 // 100 sats (and pay 150 sats in fees for the use of channel 6),
3376 // so no matter how large are other channels,
3377 // the whole path will be limited by 100 sats with just these 2 conditions:
3378 // - channel 12 capacity is 250 sats
3379 // - fee for channel 6 is 150 sats
3380 // Let's test this by enforcing these 2 conditions and removing other limits.
3381 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3382 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3383 short_channel_id: 12,
3386 cltv_expiry_delta: 0,
3387 htlc_minimum_msat: 0,
3388 htlc_maximum_msat: OptionalField::Present(250_000),
3390 fee_proportional_millionths: 0,
3391 excess_data: Vec::new()
3393 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3394 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3395 short_channel_id: 13,
3398 cltv_expiry_delta: 0,
3399 htlc_minimum_msat: 0,
3400 htlc_maximum_msat: OptionalField::Absent,
3402 fee_proportional_millionths: 0,
3403 excess_data: Vec::new()
3406 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3407 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3408 short_channel_id: 6,
3411 cltv_expiry_delta: 0,
3412 htlc_minimum_msat: 0,
3413 htlc_maximum_msat: OptionalField::Absent,
3414 fee_base_msat: 150_000,
3415 fee_proportional_millionths: 0,
3416 excess_data: Vec::new()
3418 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3419 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3420 short_channel_id: 11,
3423 cltv_expiry_delta: 0,
3424 htlc_minimum_msat: 0,
3425 htlc_maximum_msat: OptionalField::Absent,
3427 fee_proportional_millionths: 0,
3428 excess_data: Vec::new()
3432 // Attempt to route more than available results in a failure.
3433 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3434 Some(InvoiceFeatures::known()), None, &Vec::new(), 210_000, 42, Arc::clone(&logger)) {
3435 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3436 } else { panic!(); }
3440 // Now, attempt to route 200 sats (exact amount we can route).
3441 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3442 Some(InvoiceFeatures::known()), None, &Vec::new(), 200_000, 42, Arc::clone(&logger)).unwrap();
3443 assert_eq!(route.paths.len(), 2);
3445 let mut total_amount_paid_msat = 0;
3446 for path in &route.paths {
3447 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3448 total_amount_paid_msat += path.last().unwrap().fee_msat;
3450 assert_eq!(total_amount_paid_msat, 200_000);
3456 fn drop_lowest_channel_mpp_route_test() {
3457 // This test checks that low-capacity channel is dropped when after
3458 // path finding we realize that we found more capacity than we need.
3459 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3460 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3462 // We need a route consisting of 3 paths:
3463 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3465 // The first and the second paths should be sufficient, but the third should be
3466 // cheaper, so that we select it but drop later.
3468 // First, we set limits on these (previously unlimited) channels.
3469 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
3471 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
3472 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3473 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3474 short_channel_id: 1,
3477 cltv_expiry_delta: 0,
3478 htlc_minimum_msat: 0,
3479 htlc_maximum_msat: OptionalField::Present(100_000),
3481 fee_proportional_millionths: 0,
3482 excess_data: Vec::new()
3484 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3485 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3486 short_channel_id: 3,
3489 cltv_expiry_delta: 0,
3490 htlc_minimum_msat: 0,
3491 htlc_maximum_msat: OptionalField::Present(50_000),
3493 fee_proportional_millionths: 0,
3494 excess_data: Vec::new()
3497 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
3498 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3499 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3500 short_channel_id: 12,
3503 cltv_expiry_delta: 0,
3504 htlc_minimum_msat: 0,
3505 htlc_maximum_msat: OptionalField::Present(60_000),
3507 fee_proportional_millionths: 0,
3508 excess_data: Vec::new()
3510 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3511 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3512 short_channel_id: 13,
3515 cltv_expiry_delta: 0,
3516 htlc_minimum_msat: 0,
3517 htlc_maximum_msat: OptionalField::Present(60_000),
3519 fee_proportional_millionths: 0,
3520 excess_data: Vec::new()
3523 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
3524 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3525 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3526 short_channel_id: 2,
3529 cltv_expiry_delta: 0,
3530 htlc_minimum_msat: 0,
3531 htlc_maximum_msat: OptionalField::Present(20_000),
3533 fee_proportional_millionths: 0,
3534 excess_data: Vec::new()
3536 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3537 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3538 short_channel_id: 4,
3541 cltv_expiry_delta: 0,
3542 htlc_minimum_msat: 0,
3543 htlc_maximum_msat: OptionalField::Present(20_000),
3545 fee_proportional_millionths: 0,
3546 excess_data: Vec::new()
3550 // Attempt to route more than available results in a failure.
3551 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
3552 Some(InvoiceFeatures::known()), None, &Vec::new(), 150_000, 42, Arc::clone(&logger)) {
3553 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3554 } else { panic!(); }
3558 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
3559 // Our algorithm should provide us with these 3 paths.
3560 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
3561 Some(InvoiceFeatures::known()), None, &Vec::new(), 125_000, 42, Arc::clone(&logger)).unwrap();
3562 assert_eq!(route.paths.len(), 3);
3563 let mut total_amount_paid_msat = 0;
3564 for path in &route.paths {
3565 assert_eq!(path.len(), 2);
3566 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3567 total_amount_paid_msat += path.last().unwrap().fee_msat;
3569 assert_eq!(total_amount_paid_msat, 125_000);
3573 // Attempt to route without the last small cheap channel
3574 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
3575 Some(InvoiceFeatures::known()), None, &Vec::new(), 90_000, 42, Arc::clone(&logger)).unwrap();
3576 assert_eq!(route.paths.len(), 2);
3577 let mut total_amount_paid_msat = 0;
3578 for path in &route.paths {
3579 assert_eq!(path.len(), 2);
3580 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3581 total_amount_paid_msat += path.last().unwrap().fee_msat;
3583 assert_eq!(total_amount_paid_msat, 90_000);
3588 fn min_criteria_consistency() {
3589 // Test that we don't use an inconsistent metric between updating and walking nodes during
3590 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
3591 // was updated with a different criterion from the heap sorting, resulting in loops in
3592 // calculated paths. We test for that specific case here.
3594 // We construct a network that looks like this:
3596 // node2 -1(3)2- node3
3600 // node1 -1(5)2- node4 -1(1)2- node6
3606 // We create a loop on the side of our real path - our destination is node 6, with a
3607 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
3608 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
3609 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
3610 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
3611 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
3612 // "previous hop" being set to node 3, creating a loop in the path.
3613 let secp_ctx = Secp256k1::new();
3614 let logger = Arc::new(test_utils::TestLogger::new());
3615 let net_graph_msg_handler = NetGraphMsgHandler::new(genesis_block(Network::Testnet).header.block_hash(), None, Arc::clone(&logger));
3616 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3618 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
3619 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3620 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3621 short_channel_id: 6,
3624 cltv_expiry_delta: (6 << 8) | 0,
3625 htlc_minimum_msat: 0,
3626 htlc_maximum_msat: OptionalField::Absent,
3628 fee_proportional_millionths: 0,
3629 excess_data: Vec::new()
3631 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
3633 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3634 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3635 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3636 short_channel_id: 5,
3639 cltv_expiry_delta: (5 << 8) | 0,
3640 htlc_minimum_msat: 0,
3641 htlc_maximum_msat: OptionalField::Absent,
3643 fee_proportional_millionths: 0,
3644 excess_data: Vec::new()
3646 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
3648 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
3649 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3650 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3651 short_channel_id: 4,
3654 cltv_expiry_delta: (4 << 8) | 0,
3655 htlc_minimum_msat: 0,
3656 htlc_maximum_msat: OptionalField::Absent,
3658 fee_proportional_millionths: 0,
3659 excess_data: Vec::new()
3661 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
3663 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
3664 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
3665 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3666 short_channel_id: 3,
3669 cltv_expiry_delta: (3 << 8) | 0,
3670 htlc_minimum_msat: 0,
3671 htlc_maximum_msat: OptionalField::Absent,
3673 fee_proportional_millionths: 0,
3674 excess_data: Vec::new()
3676 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
3678 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
3679 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3680 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3681 short_channel_id: 2,
3684 cltv_expiry_delta: (2 << 8) | 0,
3685 htlc_minimum_msat: 0,
3686 htlc_maximum_msat: OptionalField::Absent,
3688 fee_proportional_millionths: 0,
3689 excess_data: Vec::new()
3692 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
3693 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3694 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3695 short_channel_id: 1,
3698 cltv_expiry_delta: (1 << 8) | 0,
3699 htlc_minimum_msat: 100,
3700 htlc_maximum_msat: OptionalField::Absent,
3702 fee_proportional_millionths: 0,
3703 excess_data: Vec::new()
3705 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
3708 // Now ensure the route flows simply over nodes 1 and 4 to 6.
3709 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();
3710 assert_eq!(route.paths.len(), 1);
3711 assert_eq!(route.paths[0].len(), 3);
3713 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3714 assert_eq!(route.paths[0][0].short_channel_id, 6);
3715 assert_eq!(route.paths[0][0].fee_msat, 100);
3716 assert_eq!(route.paths[0][0].cltv_expiry_delta, (5 << 8) | 0);
3717 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(1));
3718 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(6));
3720 assert_eq!(route.paths[0][1].pubkey, nodes[4]);
3721 assert_eq!(route.paths[0][1].short_channel_id, 5);
3722 assert_eq!(route.paths[0][1].fee_msat, 0);
3723 assert_eq!(route.paths[0][1].cltv_expiry_delta, (1 << 8) | 0);
3724 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(4));
3725 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(5));
3727 assert_eq!(route.paths[0][2].pubkey, nodes[6]);
3728 assert_eq!(route.paths[0][2].short_channel_id, 1);
3729 assert_eq!(route.paths[0][2].fee_msat, 10_000);
3730 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
3731 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
3732 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(1));
3738 fn exact_fee_liquidity_limit() {
3739 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
3740 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
3741 // we calculated fees on a higher value, resulting in us ignoring such paths.
3742 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3743 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
3745 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
3747 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3748 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3749 short_channel_id: 2,
3752 cltv_expiry_delta: 0,
3753 htlc_minimum_msat: 0,
3754 htlc_maximum_msat: OptionalField::Present(85_000),
3756 fee_proportional_millionths: 0,
3757 excess_data: Vec::new()
3760 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3761 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3762 short_channel_id: 12,
3765 cltv_expiry_delta: (4 << 8) | 1,
3766 htlc_minimum_msat: 0,
3767 htlc_maximum_msat: OptionalField::Present(270_000),
3769 fee_proportional_millionths: 1000000,
3770 excess_data: Vec::new()
3774 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
3775 // 200% fee charged channel 13 in the 1-to-2 direction.
3776 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();
3777 assert_eq!(route.paths.len(), 1);
3778 assert_eq!(route.paths[0].len(), 2);
3780 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
3781 assert_eq!(route.paths[0][0].short_channel_id, 12);
3782 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
3783 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
3784 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
3785 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
3787 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3788 assert_eq!(route.paths[0][1].short_channel_id, 13);
3789 assert_eq!(route.paths[0][1].fee_msat, 90_000);
3790 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3791 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3792 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
3797 fn htlc_max_reduction_below_min() {
3798 // Test that if, while walking the graph, we reduce the value being sent to meet an
3799 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
3800 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
3801 // resulting in us thinking there is no possible path, even if other paths exist.
3802 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3803 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3805 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
3806 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
3807 // then try to send 90_000.
3808 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3809 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3810 short_channel_id: 2,
3813 cltv_expiry_delta: 0,
3814 htlc_minimum_msat: 0,
3815 htlc_maximum_msat: OptionalField::Present(80_000),
3817 fee_proportional_millionths: 0,
3818 excess_data: Vec::new()
3820 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3821 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3822 short_channel_id: 4,
3825 cltv_expiry_delta: (4 << 8) | 1,
3826 htlc_minimum_msat: 90_000,
3827 htlc_maximum_msat: OptionalField::Absent,
3829 fee_proportional_millionths: 0,
3830 excess_data: Vec::new()
3834 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
3835 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
3836 // expensive) channels 12-13 path.
3837 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();
3838 assert_eq!(route.paths.len(), 1);
3839 assert_eq!(route.paths[0].len(), 2);
3841 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
3842 assert_eq!(route.paths[0][0].short_channel_id, 12);
3843 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
3844 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
3845 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
3846 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
3848 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3849 assert_eq!(route.paths[0][1].short_channel_id, 13);
3850 assert_eq!(route.paths[0][1].fee_msat, 90_000);
3851 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3852 assert_eq!(route.paths[0][1].node_features.le_flags(), InvoiceFeatures::known().le_flags());
3853 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
3857 #[cfg(not(feature = "no_std"))]
3858 pub(super) fn random_init_seed() -> u64 {
3859 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
3860 use core::hash::{BuildHasher, Hasher};
3861 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
3862 println!("Using seed of {}", seed);
3865 #[cfg(not(feature = "no_std"))]
3866 use util::ser::Readable;
3869 #[cfg(not(feature = "no_std"))]
3870 fn generate_routes() {
3871 let mut d = match super::test_utils::get_route_file() {
3878 let graph = NetworkGraph::read(&mut d).unwrap();
3880 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
3881 let mut seed = random_init_seed() as usize;
3882 'load_endpoints: for _ in 0..10 {
3884 seed = seed.overflowing_mul(0xdeadbeef).0;
3885 let src = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3886 seed = seed.overflowing_mul(0xdeadbeef).0;
3887 let dst = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3888 let amt = seed as u64 % 200_000_000;
3889 if get_route(src, &graph, dst, None, None, &[], amt, 42, &test_utils::TestLogger::new()).is_ok() {
3890 continue 'load_endpoints;
3897 #[cfg(not(feature = "no_std"))]
3898 fn generate_routes_mpp() {
3899 let mut d = match super::test_utils::get_route_file() {
3906 let graph = NetworkGraph::read(&mut d).unwrap();
3908 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
3909 let mut seed = random_init_seed() as usize;
3910 'load_endpoints: for _ in 0..10 {
3912 seed = seed.overflowing_mul(0xdeadbeef).0;
3913 let src = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3914 seed = seed.overflowing_mul(0xdeadbeef).0;
3915 let dst = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3916 let amt = seed as u64 % 200_000_000;
3917 if get_route(src, &graph, dst, Some(InvoiceFeatures::known()), None, &[], amt, 42, &test_utils::TestLogger::new()).is_ok() {
3918 continue 'load_endpoints;
3925 #[cfg(all(test, not(feature = "no_std")))]
3926 pub(crate) mod test_utils {
3928 /// Tries to open a network graph file, or panics with a URL to fetch it.
3929 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
3930 let res = File::open("net_graph-2021-05-31.bin") // By default we're run in RL/lightning
3931 .or_else(|_| File::open("lightning/net_graph-2021-05-31.bin")) // We may be run manually in RL/
3932 .or_else(|_| { // Fall back to guessing based on the binary location
3933 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
3934 let mut path = std::env::current_exe().unwrap();
3935 path.pop(); // lightning-...
3937 path.pop(); // debug
3938 path.pop(); // target
3939 path.push("lightning");
3940 path.push("net_graph-2021-05-31.bin");
3941 eprintln!("{}", path.to_str().unwrap());
3944 .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");
3945 #[cfg(require_route_graph_test)]
3946 return Ok(res.unwrap());
3947 #[cfg(not(require_route_graph_test))]
3952 #[cfg(all(test, feature = "unstable", not(feature = "no_std")))]
3955 use util::logger::{Logger, Record};
3959 struct DummyLogger {}
3960 impl Logger for DummyLogger {
3961 fn log(&self, _record: &Record) {}
3965 fn generate_routes(bench: &mut Bencher) {
3966 let mut d = test_utils::get_route_file().unwrap();
3967 let graph = NetworkGraph::read(&mut d).unwrap();
3969 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
3970 let mut path_endpoints = Vec::new();
3971 let mut seed: usize = 0xdeadbeef;
3972 'load_endpoints: for _ in 0..100 {
3975 let src = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3977 let dst = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3978 let amt = seed as u64 % 1_000_000;
3979 if get_route(src, &graph, dst, None, None, &[], amt, 42, &DummyLogger{}).is_ok() {
3980 path_endpoints.push((src, dst, amt));
3981 continue 'load_endpoints;
3986 // ...then benchmark finding paths between the nodes we learned.
3989 let (src, dst, amt) = path_endpoints[idx % path_endpoints.len()];
3990 assert!(get_route(src, &graph, dst, None, None, &[], amt, 42, &DummyLogger{}).is_ok());
3996 fn generate_mpp_routes(bench: &mut Bencher) {
3997 let mut d = test_utils::get_route_file().unwrap();
3998 let graph = NetworkGraph::read(&mut d).unwrap();
4000 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4001 let mut path_endpoints = Vec::new();
4002 let mut seed: usize = 0xdeadbeef;
4003 'load_endpoints: for _ in 0..100 {
4006 let src = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
4008 let dst = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
4009 let amt = seed as u64 % 1_000_000;
4010 if get_route(src, &graph, dst, Some(InvoiceFeatures::known()), None, &[], amt, 42, &DummyLogger{}).is_ok() {
4011 path_endpoints.push((src, dst, amt));
4012 continue 'load_endpoints;
4017 // ...then benchmark finding paths between the nodes we learned.
4020 let (src, dst, amt) = path_endpoints[idx % path_endpoints.len()];
4021 assert!(get_route(src, &graph, dst, Some(InvoiceFeatures::known()), None, &[], amt, 42, &DummyLogger{}).is_ok());