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;
26 use alloc::collections::BinaryHeap;
31 #[derive(Clone, Hash, PartialEq, Eq)]
33 /// The node_id of the node at this hop.
34 pub pubkey: PublicKey,
35 /// The node_announcement features of the node at this hop. For the last hop, these may be
36 /// amended to match the features present in the invoice this node generated.
37 pub node_features: NodeFeatures,
38 /// The channel that should be used from the previous hop to reach this node.
39 pub short_channel_id: u64,
40 /// The channel_announcement features of the channel that should be used from the previous hop
41 /// to reach this node.
42 pub channel_features: ChannelFeatures,
43 /// The fee taken on this hop (for paying for the use of the *next* channel in the path).
44 /// For the last hop, this should be the full value of the payment (might be more than
45 /// requested if we had to match htlc_minimum_msat).
47 /// The CLTV delta added for this hop. For the last hop, this should be the full CLTV value
48 /// expected at the destination, in excess of the current block height.
49 pub cltv_expiry_delta: u32,
52 impl_writeable_tlv_based!(RouteHop, {
53 (0, pubkey, required),
54 (2, node_features, required),
55 (4, short_channel_id, required),
56 (6, channel_features, required),
57 (8, fee_msat, required),
58 (10, cltv_expiry_delta, required),
61 /// A route directs a payment from the sender (us) to the recipient. If the recipient supports MPP,
62 /// it can take multiple paths. Each path is composed of one or more hops through the network.
63 #[derive(Clone, Hash, PartialEq, Eq)]
65 /// The list of routes taken for a single (potentially-)multi-part payment. The pubkey of the
66 /// last RouteHop in each path must be the same.
67 /// Each entry represents a list of hops, NOT INCLUDING our own, where the last hop is the
68 /// destination. Thus, this must always be at least length one. While the maximum length of any
69 /// given path is variable, keeping the length of any path to less than 20 should currently
70 /// ensure it is viable.
71 pub paths: Vec<Vec<RouteHop>>,
74 const SERIALIZATION_VERSION: u8 = 1;
75 const MIN_SERIALIZATION_VERSION: u8 = 1;
77 impl Writeable for Route {
78 fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
79 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
80 (self.paths.len() as u64).write(writer)?;
81 for hops in self.paths.iter() {
82 (hops.len() as u8).write(writer)?;
83 for hop in hops.iter() {
87 write_tlv_fields!(writer, {});
92 impl Readable for Route {
93 fn read<R: io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
94 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
95 let path_count: u64 = Readable::read(reader)?;
96 let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
97 for _ in 0..path_count {
98 let hop_count: u8 = Readable::read(reader)?;
99 let mut hops = Vec::with_capacity(hop_count as usize);
100 for _ in 0..hop_count {
101 hops.push(Readable::read(reader)?);
105 read_tlv_fields!(reader, {});
110 /// A list of hops along a payment path terminating with a channel to the recipient.
111 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
112 pub struct RouteHint(pub Vec<RouteHintHop>);
114 /// A channel descriptor for a hop along a payment path.
115 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
116 pub struct RouteHintHop {
117 /// The node_id of the non-target end of the route
118 pub src_node_id: PublicKey,
119 /// The short_channel_id of this channel
120 pub short_channel_id: u64,
121 /// The fees which must be paid to use this channel
122 pub fees: RoutingFees,
123 /// The difference in CLTV values between this node and the next node.
124 pub cltv_expiry_delta: u16,
125 /// The minimum value, in msat, which must be relayed to the next hop.
126 pub htlc_minimum_msat: Option<u64>,
127 /// The maximum value in msat available for routing with a single HTLC.
128 pub htlc_maximum_msat: Option<u64>,
131 #[derive(Eq, PartialEq)]
132 struct RouteGraphNode {
134 lowest_fee_to_peer_through_node: u64,
135 lowest_fee_to_node: u64,
136 // The maximum value a yet-to-be-constructed payment path might flow through this node.
137 // This value is upper-bounded by us by:
138 // - how much is needed for a path being constructed
139 // - how much value can channels following this node (up to the destination) can contribute,
140 // considering their capacity and fees
141 value_contribution_msat: u64,
142 /// The effective htlc_minimum_msat at this hop. If a later hop on the path had a higher HTLC
143 /// minimum, we use it, plus the fees required at each earlier hop to meet it.
144 path_htlc_minimum_msat: u64,
147 impl cmp::Ord for RouteGraphNode {
148 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
149 let other_score = cmp::max(other.lowest_fee_to_peer_through_node, other.path_htlc_minimum_msat);
150 let self_score = cmp::max(self.lowest_fee_to_peer_through_node, self.path_htlc_minimum_msat);
151 other_score.cmp(&self_score).then_with(|| other.pubkey.serialize().cmp(&self.pubkey.serialize()))
155 impl cmp::PartialOrd for RouteGraphNode {
156 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
157 Some(self.cmp(other))
161 struct DummyDirectionalChannelInfo {
162 cltv_expiry_delta: u32,
163 htlc_minimum_msat: u64,
164 htlc_maximum_msat: Option<u64>,
168 /// It's useful to keep track of the hops associated with the fees required to use them,
169 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
170 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
171 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
172 #[derive(Clone, Debug)]
173 struct PathBuildingHop<'a> {
174 // The RouteHintHop fields which will eventually be used if this hop is used in a final Route.
175 // Note that node_features is calculated separately after our initial graph walk.
177 short_channel_id: u64,
178 channel_features: &'a ChannelFeatures,
180 cltv_expiry_delta: u32,
182 /// Minimal fees required to route to the source node of the current hop via any of its inbound channels.
183 src_lowest_inbound_fees: RoutingFees,
184 /// Fees of the channel used in this hop.
185 channel_fees: RoutingFees,
186 /// All the fees paid *after* this channel on the way to the destination
187 next_hops_fee_msat: u64,
188 /// Fee paid for the use of the current channel (see channel_fees).
189 /// The value will be actually deducted from the counterparty balance on the previous link.
190 hop_use_fee_msat: u64,
191 /// Used to compare channels when choosing the for routing.
192 /// Includes paying for the use of a hop and the following hops, as well as
193 /// an estimated cost of reaching this hop.
194 /// Might get stale when fees are recomputed. Primarily for internal use.
196 /// This is useful for update_value_and_recompute_fees to make sure
197 /// we don't fall below the minimum. Should not be updated manually and
198 /// generally should not be accessed.
199 htlc_minimum_msat: u64,
200 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
201 /// walk and may be invalid thereafter.
202 path_htlc_minimum_msat: u64,
203 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
204 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
205 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
206 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
207 /// avoid processing them again.
209 #[cfg(any(test, feature = "fuzztarget"))]
210 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
211 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
212 // value_contribution_msat, which requires tracking it here. See comments below where it is
213 // used for more info.
214 value_contribution_msat: u64,
217 // Instantiated with a list of hops with correct data in them collected during path finding,
218 // an instance of this struct should be further modified only via given methods.
220 struct PaymentPath<'a> {
221 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
224 impl<'a> PaymentPath<'a> {
225 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
226 fn get_value_msat(&self) -> u64 {
227 self.hops.last().unwrap().0.fee_msat
230 fn get_total_fee_paid_msat(&self) -> u64 {
231 if self.hops.len() < 1 {
235 // Can't use next_hops_fee_msat because it gets outdated.
236 for (i, (hop, _)) in self.hops.iter().enumerate() {
237 if i != self.hops.len() - 1 {
238 result += hop.fee_msat;
244 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
245 // to change fees may result in an inconsistency.
247 // Sometimes we call this function right after constructing a path which is inconsistent in
248 // that it the value being transferred has decreased while we were doing path finding, leading
249 // to the fees being paid not lining up with the actual limits.
251 // Note that this function is not aware of the available_liquidity limit, and thus does not
252 // support increasing the value being transferred.
253 fn update_value_and_recompute_fees(&mut self, value_msat: u64) {
254 assert!(value_msat <= self.hops.last().unwrap().0.fee_msat);
256 let mut total_fee_paid_msat = 0 as u64;
257 for i in (0..self.hops.len()).rev() {
258 let last_hop = i == self.hops.len() - 1;
260 // For non-last-hop, this value will represent the fees paid on the current hop. It
261 // will consist of the fees for the use of the next hop, and extra fees to match
262 // htlc_minimum_msat of the current channel. Last hop is handled separately.
263 let mut cur_hop_fees_msat = 0;
265 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
268 let mut cur_hop = &mut self.hops.get_mut(i).unwrap().0;
269 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
270 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
271 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
272 // set it too high just to maliciously take more fees by exploiting this
273 // match htlc_minimum_msat logic.
274 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
275 if let Some(extra_fees_msat) = cur_hop.htlc_minimum_msat.checked_sub(cur_hop_transferred_amount_msat) {
276 // Note that there is a risk that *previous hops* (those closer to us, as we go
277 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
279 // This might make us end up with a broken route, although this should be super-rare
280 // in practice, both because of how healthy channels look like, and how we pick
281 // channels in add_entry.
282 // Also, this can't be exploited more heavily than *announce a free path and fail
284 cur_hop_transferred_amount_msat += extra_fees_msat;
285 total_fee_paid_msat += extra_fees_msat;
286 cur_hop_fees_msat += extra_fees_msat;
290 // Final hop is a special case: it usually has just value_msat (by design), but also
291 // it still could overpay for the htlc_minimum_msat.
292 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
294 // Propagate updated fees for the use of the channels to one hop back, where they
295 // will be actually paid (fee_msat). The last hop is handled above separately.
296 cur_hop.fee_msat = cur_hop_fees_msat;
299 // Fee for the use of the current hop which will be deducted on the previous hop.
300 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
301 // this channel is free for us.
303 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.channel_fees) {
304 cur_hop.hop_use_fee_msat = new_fee;
305 total_fee_paid_msat += new_fee;
307 // It should not be possible because this function is called only to reduce the
308 // value. In that case, compute_fee was already called with the same fees for
309 // larger amount and there was no overflow.
317 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
318 let proportional_fee_millions =
319 amount_msat.checked_mul(channel_fees.proportional_millionths as u64);
320 if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
321 (channel_fees.base_msat as u64).checked_add(part / 1_000_000) }) {
325 // This function may be (indirectly) called without any verification,
326 // with channel_fees provided by a caller. We should handle it gracefully.
331 /// Gets a keysend route from us (payer) to the given target node (payee). This is needed because
332 /// keysend payments do not have an invoice from which to pull the payee's supported features, which
333 /// makes it tricky to otherwise supply the `payee_features` parameter of `get_route`.
334 pub fn get_keysend_route<L: Deref>(our_node_id: &PublicKey, network: &NetworkGraph, payee:
335 &PublicKey, first_hops: Option<&[&ChannelDetails]>, last_hops: &[&RouteHint],
336 final_value_msat: u64, final_cltv: u32, logger: L) -> Result<Route,
337 LightningError> where L::Target: Logger {
338 let invoice_features = InvoiceFeatures::for_keysend();
339 get_route(our_node_id, network, payee, Some(invoice_features), first_hops, last_hops,
340 final_value_msat, final_cltv, logger)
343 /// Gets a route from us (payer) to the given target node (payee).
345 /// If the payee provided features in their invoice, they should be provided via payee_features.
346 /// Without this, MPP will only be used if the payee's features are available in the network graph.
348 /// Private routing paths between a public node and the target may be included in `last_hops`.
349 /// Currently, only the last hop in each path is considered.
351 /// If some channels aren't announced, it may be useful to fill in a first_hops with the
352 /// results from a local ChannelManager::list_usable_channels() call. If it is filled in, our
353 /// view of our local channels (from net_graph_msg_handler) will be ignored, and only those
354 /// in first_hops will be used.
356 /// Panics if first_hops contains channels without short_channel_ids
357 /// (ChannelManager::list_usable_channels will never include such channels).
359 /// The fees on channels from us to next-hops are ignored (as they are assumed to all be
360 /// equal), however the enabled/disabled bit on such channels as well as the
361 /// htlc_minimum_msat/htlc_maximum_msat *are* checked as they may change based on the receiving node.
362 pub fn get_route<L: Deref>(our_node_id: &PublicKey, network: &NetworkGraph, payee: &PublicKey, payee_features: Option<InvoiceFeatures>, first_hops: Option<&[&ChannelDetails]>,
363 last_hops: &[&RouteHint], final_value_msat: u64, final_cltv: u32, logger: L) -> Result<Route, LightningError> where L::Target: Logger {
364 // TODO: Obviously *only* using total fee cost sucks. We should consider weighting by
365 // uptime/success in using a node in the past.
366 if *payee == *our_node_id {
367 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
370 if final_value_msat > MAX_VALUE_MSAT {
371 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
374 if final_value_msat == 0 {
375 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
378 for route in last_hops.iter() {
379 for hop in &route.0 {
380 if hop.src_node_id == *payee {
381 return Err(LightningError{err: "Last hop cannot have a payee as a source.".to_owned(), action: ErrorAction::IgnoreError});
386 // The general routing idea is the following:
387 // 1. Fill first/last hops communicated by the caller.
388 // 2. Attempt to construct a path from payer to payee for transferring
389 // any ~sufficient (described later) value.
390 // If succeed, remember which channels were used and how much liquidity they have available,
391 // so that future paths don't rely on the same liquidity.
392 // 3. Prooceed to the next step if:
393 // - we hit the recommended target value;
394 // - OR if we could not construct a new path. Any next attempt will fail too.
395 // Otherwise, repeat step 2.
396 // 4. See if we managed to collect paths which aggregately are able to transfer target value
397 // (not recommended value). If yes, proceed. If not, fail routing.
398 // 5. Randomly combine paths into routes having enough to fulfill the payment. (TODO: knapsack)
399 // 6. Of all the found paths, select only those with the lowest total fee.
400 // 7. The last path in every selected route is likely to be more than we need.
401 // Reduce its value-to-transfer and recompute fees.
402 // 8. Choose the best route by the lowest total fee.
404 // As for the actual search algorithm,
405 // we do a payee-to-payer pseudo-Dijkstra's sorting by each node's distance from the payee
406 // plus the minimum per-HTLC fee to get from it to another node (aka "shitty pseudo-A*").
408 // We are not a faithful Dijkstra's implementation because we can change values which impact
409 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
410 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) then
411 // the value we are currently attempting to send over a path, we simply reduce the value being
412 // sent along the path for any hops after that channel. This may imply that later fees (which
413 // we've already tabulated) are lower because a smaller value is passing through the channels
414 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
415 // channels which were selected earlier (and which may still be used for other paths without a
416 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
419 // One potentially problematic case for this algorithm would be if there are many
420 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
421 // graph walking), we may never find a path which is not liquidity-limited and has lower
422 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
423 // Because we only consider paths with at least 5% of the total value being sent, the damage
424 // from such a case should be limited, however this could be further reduced in the future by
425 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
426 // limits for the purposes of fee calculation.
428 // Alternatively, we could store more detailed path information in the heap (targets, below)
429 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
430 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
431 // and practically (as we would need to store dynamically-allocated path information in heap
432 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
433 // results of such an algorithm would likely be biased towards lower-value paths.
435 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
436 // outside of our current search value, running a path search more times to gather candidate
437 // paths at different values. While this may be acceptable, further path searches may increase
438 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
439 // graph for candidate paths, calculating the maximum value which can realistically be sent at
440 // the same time, remaining generic across different payment values.
442 // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
443 // to use as the A* heuristic beyond just the cost to get one node further than the current
446 let dummy_directional_info = DummyDirectionalChannelInfo { // used for first_hops routes
447 cltv_expiry_delta: 0,
448 htlc_minimum_msat: 0,
449 htlc_maximum_msat: None,
452 proportional_millionths: 0,
456 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
457 // it. If the payee supports it they're supposed to include it in the invoice, so that should
459 let allow_mpp = if let Some(features) = &payee_features {
460 features.supports_basic_mpp()
461 } else if let Some(node) = network.get_nodes().get(&payee) {
462 if let Some(node_info) = node.announcement_info.as_ref() {
463 node_info.features.supports_basic_mpp()
468 // Prepare the data we'll use for payee-to-payer search by
469 // inserting first hops suggested by the caller as targets.
470 // Our search will then attempt to reach them while traversing from the payee node.
471 let mut first_hop_targets: HashMap<_, (_, ChannelFeatures, _, NodeFeatures)> =
472 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
473 if let Some(hops) = first_hops {
475 let short_channel_id = chan.short_channel_id.expect("first_hops should be filled in with usable channels, not pending ones");
476 if chan.counterparty.node_id == *our_node_id {
477 return Err(LightningError{err: "First hop cannot have our_node_id as a destination.".to_owned(), action: ErrorAction::IgnoreError});
479 first_hop_targets.insert(chan.counterparty.node_id, (short_channel_id, chan.counterparty.features.to_context(), chan.outbound_capacity_msat, chan.counterparty.features.to_context()));
481 if first_hop_targets.is_empty() {
482 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
486 let empty_channel_features = ChannelFeatures::empty();
488 // The main heap containing all candidate next-hops sorted by their score (max(A* fee,
489 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
490 // adding duplicate entries when we find a better path to a given node.
491 let mut targets = BinaryHeap::new();
493 // Map from node_id to information about the best current path to that node, including feerate
495 let mut dist = HashMap::with_capacity(network.get_nodes().len());
497 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
498 // indicating that we may wish to try again with a higher value, potentially paying to meet an
499 // htlc_minimum with extra fees while still finding a cheaper path.
500 let mut hit_minimum_limit;
502 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
503 // We start with a path_value of the exact amount we want, and if that generates a route we may
504 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
505 // amount we want in total across paths, selecting the best subset at the end.
506 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
507 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
508 let mut path_value_msat = final_value_msat;
510 // We don't want multiple paths (as per MPP) share liquidity of the same channels.
511 // This map allows paths to be aware of the channel use by other paths in the same call.
512 // This would help to make a better path finding decisions and not "overbook" channels.
513 // It is unaware of the directions (except for `outbound_capacity_msat` in `first_hops`).
514 let mut bookkeeped_channels_liquidity_available_msat = HashMap::with_capacity(network.get_nodes().len());
516 // Keeping track of how much value we already collected across other paths. Helps to decide:
517 // - how much a new path should be transferring (upper bound);
518 // - whether a channel should be disregarded because
519 // it's available liquidity is too small comparing to how much more we need to collect;
520 // - when we want to stop looking for new paths.
521 let mut already_collected_value_msat = 0;
523 log_trace!(logger, "Building path from {} (payee) to {} (us/payer) for value {} msat.", payee, our_node_id, final_value_msat);
525 macro_rules! add_entry {
526 // Adds entry which goes from $src_node_id to $dest_node_id
527 // over the channel with id $chan_id with fees described in
528 // $directional_info.
529 // $next_hops_fee_msat represents the fees paid for using all the channel *after* this one,
530 // since that value has to be transferred over this channel.
531 // Returns whether this channel caused an update to `targets`.
532 ( $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,
533 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr ) => { {
534 // We "return" whether we updated the path at the end, via this:
535 let mut did_add_update_path_to_src_node = false;
536 // Channels to self should not be used. This is more of belt-and-suspenders, because in
537 // practice these cases should be caught earlier:
538 // - for regular channels at channel announcement (TODO)
539 // - for first and last hops early in get_route
540 if $src_node_id != $dest_node_id.clone() {
541 let available_liquidity_msat = bookkeeped_channels_liquidity_available_msat.entry($chan_id.clone()).or_insert_with(|| {
542 let mut initial_liquidity_available_msat = None;
543 if let Some(capacity_sats) = $capacity_sats {
544 initial_liquidity_available_msat = Some(capacity_sats * 1000);
547 if let Some(htlc_maximum_msat) = $directional_info.htlc_maximum_msat {
548 if let Some(available_msat) = initial_liquidity_available_msat {
549 initial_liquidity_available_msat = Some(cmp::min(available_msat, htlc_maximum_msat));
551 initial_liquidity_available_msat = Some(htlc_maximum_msat);
555 match initial_liquidity_available_msat {
556 Some(available_msat) => available_msat,
557 // We assume channels with unknown balance have
558 // a capacity of 0.0025 BTC (or 250_000 sats).
559 None => 250_000 * 1000
563 // It is tricky to substract $next_hops_fee_msat from available liquidity here.
564 // It may be misleading because we might later choose to reduce the value transferred
565 // over these channels, and the channel which was insufficient might become sufficient.
566 // Worst case: we drop a good channel here because it can't cover the high following
567 // fees caused by one expensive channel, but then this channel could have been used
568 // if the amount being transferred over this path is lower.
569 // We do this for now, but this is a subject for removal.
570 if let Some(available_value_contribution_msat) = available_liquidity_msat.checked_sub($next_hops_fee_msat) {
572 // Routing Fragmentation Mitigation heuristic:
574 // Routing fragmentation across many payment paths increases the overall routing
575 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
576 // Taking too many smaller paths also increases the chance of payment failure.
577 // Thus to avoid this effect, we require from our collected links to provide
578 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
580 // This requirement is currently 5% of the remaining-to-be-collected value.
581 // This means as we successfully advance in our collection,
582 // the absolute liquidity contribution is lowered,
583 // thus increasing the number of potential channels to be selected.
585 // Derive the minimal liquidity contribution with a ratio of 20 (5%, rounded up)
586 // or 100% if we're not allowed to do multipath payments.
587 let minimal_value_contribution_msat: u64 = if allow_mpp {
588 (recommended_value_msat - already_collected_value_msat + 19) / 20
592 // Verify the liquidity offered by this channel complies to the minimal contribution.
593 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
595 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
596 // Includes paying fees for the use of the following channels.
597 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
598 Some(result) => result,
599 // Can't overflow due to how the values were computed right above.
600 None => unreachable!(),
602 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
603 let over_path_minimum_msat = amount_to_transfer_over_msat >= $directional_info.htlc_minimum_msat &&
604 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
606 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
607 // bother considering this channel.
608 // Since we're choosing amount_to_transfer_over_msat as maximum possible, it can
609 // be only reduced later (not increased), so this channel should just be skipped
610 // as not sufficient.
611 if !over_path_minimum_msat {
612 hit_minimum_limit = true;
613 } else if contributes_sufficient_value {
614 // Note that low contribution here (limited by available_liquidity_msat)
615 // might violate htlc_minimum_msat on the hops which are next along the
616 // payment path (upstream to the payee). To avoid that, we recompute path
617 // path fees knowing the final path contribution after constructing it.
618 let path_htlc_minimum_msat = match compute_fees($next_hops_path_htlc_minimum_msat, $directional_info.fees)
619 .map(|fee_msat| fee_msat.checked_add($next_hops_path_htlc_minimum_msat)) {
620 Some(Some(value_msat)) => cmp::max(value_msat, $directional_info.htlc_minimum_msat),
621 _ => u64::max_value()
623 let hm_entry = dist.entry(&$src_node_id);
624 let old_entry = hm_entry.or_insert_with(|| {
625 // If there was previously no known way to access
626 // the source node (recall it goes payee-to-payer) of $chan_id, first add
627 // a semi-dummy record just to compute the fees to reach the source node.
628 // This will affect our decision on selecting $chan_id
629 // as a way to reach the $dest_node_id.
630 let mut fee_base_msat = u32::max_value();
631 let mut fee_proportional_millionths = u32::max_value();
632 if let Some(Some(fees)) = network.get_nodes().get(&$src_node_id).map(|node| node.lowest_inbound_channel_fees) {
633 fee_base_msat = fees.base_msat;
634 fee_proportional_millionths = fees.proportional_millionths;
637 pubkey: $dest_node_id.clone(),
639 channel_features: $chan_features,
641 cltv_expiry_delta: 0,
642 src_lowest_inbound_fees: RoutingFees {
643 base_msat: fee_base_msat,
644 proportional_millionths: fee_proportional_millionths,
646 channel_fees: $directional_info.fees,
647 next_hops_fee_msat: u64::max_value(),
648 hop_use_fee_msat: u64::max_value(),
649 total_fee_msat: u64::max_value(),
650 htlc_minimum_msat: $directional_info.htlc_minimum_msat,
651 path_htlc_minimum_msat,
652 was_processed: false,
653 #[cfg(any(test, feature = "fuzztarget"))]
654 value_contribution_msat,
658 #[allow(unused_mut)] // We only use the mut in cfg(test)
659 let mut should_process = !old_entry.was_processed;
660 #[cfg(any(test, feature = "fuzztarget"))]
662 // In test/fuzzing builds, we do extra checks to make sure the skipping
663 // of already-seen nodes only happens in cases we expect (see below).
664 if !should_process { should_process = true; }
668 let mut hop_use_fee_msat = 0;
669 let mut total_fee_msat = $next_hops_fee_msat;
671 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
672 // will have the same effective-fee
673 if $src_node_id != *our_node_id {
674 match compute_fees(amount_to_transfer_over_msat, $directional_info.fees) {
675 // max_value means we'll always fail
676 // the old_entry.total_fee_msat > total_fee_msat check
677 None => total_fee_msat = u64::max_value(),
679 hop_use_fee_msat = fee_msat;
680 total_fee_msat += hop_use_fee_msat;
681 // When calculating the lowest inbound fees to a node, we
682 // calculate fees here not based on the actual value we think
683 // will flow over this channel, but on the minimum value that
684 // we'll accept flowing over it. The minimum accepted value
685 // is a constant through each path collection run, ensuring
686 // consistent basis. Otherwise we may later find a
687 // different path to the source node that is more expensive,
688 // but which we consider to be cheaper because we are capacity
689 // constrained and the relative fee becomes lower.
690 match compute_fees(minimal_value_contribution_msat, old_entry.src_lowest_inbound_fees)
691 .map(|a| a.checked_add(total_fee_msat)) {
696 total_fee_msat = u64::max_value();
703 let new_graph_node = RouteGraphNode {
704 pubkey: $src_node_id,
705 lowest_fee_to_peer_through_node: total_fee_msat,
706 lowest_fee_to_node: $next_hops_fee_msat as u64 + hop_use_fee_msat,
707 value_contribution_msat: value_contribution_msat,
708 path_htlc_minimum_msat,
711 // Update the way of reaching $src_node_id with the given $chan_id (from $dest_node_id),
712 // if this way is cheaper than the already known
713 // (considering the cost to "reach" this channel from the route destination,
714 // the cost of using this channel,
715 // and the cost of routing to the source node of this channel).
716 // Also, consider that htlc_minimum_msat_difference, because we might end up
717 // paying it. Consider the following exploit:
718 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
719 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
720 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
721 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
723 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
724 // but it may require additional tracking - we don't want to double-count
725 // the fees included in $next_hops_path_htlc_minimum_msat, but also
726 // can't use something that may decrease on future hops.
727 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat);
728 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat);
730 if !old_entry.was_processed && new_cost < old_cost {
731 targets.push(new_graph_node);
732 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
733 old_entry.hop_use_fee_msat = hop_use_fee_msat;
734 old_entry.total_fee_msat = total_fee_msat;
735 old_entry.pubkey = $dest_node_id.clone();
736 old_entry.short_channel_id = $chan_id.clone();
737 old_entry.channel_features = $chan_features;
738 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
739 old_entry.cltv_expiry_delta = $directional_info.cltv_expiry_delta as u32;
740 old_entry.channel_fees = $directional_info.fees;
741 old_entry.htlc_minimum_msat = $directional_info.htlc_minimum_msat;
742 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
743 #[cfg(any(test, feature = "fuzztarget"))]
745 old_entry.value_contribution_msat = value_contribution_msat;
747 did_add_update_path_to_src_node = true;
748 } else if old_entry.was_processed && new_cost < old_cost {
749 #[cfg(any(test, feature = "fuzztarget"))]
751 // If we're skipping processing a node which was previously
752 // processed even though we found another path to it with a
753 // cheaper fee, check that it was because the second path we
754 // found (which we are processing now) has a lower value
755 // contribution due to an HTLC minimum limit.
757 // e.g. take a graph with two paths from node 1 to node 2, one
758 // through channel A, and one through channel B. Channel A and
759 // B are both in the to-process heap, with their scores set by
760 // a higher htlc_minimum than fee.
761 // Channel A is processed first, and the channels onwards from
762 // node 1 are added to the to-process heap. Thereafter, we pop
763 // Channel B off of the heap, note that it has a much more
764 // restrictive htlc_maximum_msat, and recalculate the fees for
765 // all of node 1's channels using the new, reduced, amount.
767 // This would be bogus - we'd be selecting a higher-fee path
768 // with a lower htlc_maximum_msat instead of the one we'd
769 // already decided to use.
770 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
771 debug_assert!(value_contribution_msat < old_entry.value_contribution_msat);
778 did_add_update_path_to_src_node
782 let empty_node_features = NodeFeatures::empty();
783 // Find ways (channels with destination) to reach a given node and store them
784 // in the corresponding data structures (routing graph etc).
785 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
786 // meaning how much will be paid in fees after this node (to the best of our knowledge).
787 // This data can later be helpful to optimize routing (pay lower fees).
788 macro_rules! add_entries_to_cheapest_to_target_node {
789 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr, $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr ) => {
790 let skip_node = if let Some(elem) = dist.get_mut($node_id) {
791 let was_processed = elem.was_processed;
792 elem.was_processed = true;
795 // Entries are added to dist in add_entry!() when there is a channel from a node.
796 // Because there are no channels from payee, it will not have a dist entry at this point.
797 // If we're processing any other node, it is always be the result of a channel from it.
798 assert_eq!($node_id, payee);
803 if first_hops.is_some() {
804 if let Some(&(ref first_hop, ref features, ref outbound_capacity_msat, _)) = first_hop_targets.get(&$node_id) {
805 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);
809 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
815 if !features.requires_unknown_bits() {
816 for chan_id in $node.channels.iter() {
817 let chan = network.get_channels().get(chan_id).unwrap();
818 if !chan.features.requires_unknown_bits() {
819 if chan.node_one == *$node_id {
820 // ie $node is one, ie next hop in A* is two, via the two_to_one channel
821 if first_hops.is_none() || chan.node_two != *our_node_id {
822 if let Some(two_to_one) = chan.two_to_one.as_ref() {
823 if two_to_one.enabled {
824 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);
829 if first_hops.is_none() || chan.node_one != *our_node_id {
830 if let Some(one_to_two) = chan.one_to_two.as_ref() {
831 if one_to_two.enabled {
832 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);
844 let mut payment_paths = Vec::<PaymentPath>::new();
846 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
847 'paths_collection: loop {
848 // For every new path, start from scratch, except
849 // bookkeeped_channels_liquidity_available_msat, which will improve
850 // the further iterations of path finding. Also don't erase first_hop_targets.
853 hit_minimum_limit = false;
855 // If first hop is a private channel and the only way to reach the payee, this is the only
856 // place where it could be added.
857 if first_hops.is_some() {
858 if let Some(&(ref first_hop, ref features, ref outbound_capacity_msat, _)) = first_hop_targets.get(&payee) {
859 add_entry!(first_hop, *our_node_id, payee, dummy_directional_info, Some(outbound_capacity_msat / 1000), features, 0, path_value_msat, 0);
863 // Add the payee as a target, so that the payee-to-payer
864 // search algorithm knows what to start with.
865 match network.get_nodes().get(payee) {
866 // The payee is not in our network graph, so nothing to add here.
867 // There is still a chance of reaching them via last_hops though,
868 // so don't yet fail the payment here.
869 // If not, targets.pop() will not even let us enter the loop in step 2.
872 add_entries_to_cheapest_to_target_node!(node, payee, 0, path_value_msat, 0);
877 // If a caller provided us with last hops, add them to routing targets. Since this happens
878 // earlier than general path finding, they will be somewhat prioritized, although currently
879 // it matters only if the fees are exactly the same.
880 for route in last_hops.iter().filter(|route| !route.0.is_empty()) {
881 let first_hop_in_route = &(route.0)[0];
882 let have_hop_src_in_graph =
883 // Only add the hops in this route to our candidate set if either
884 // we have a direct channel to the first hop or the first hop is
885 // in the regular network graph.
886 first_hop_targets.get(&first_hop_in_route.src_node_id).is_some() ||
887 network.get_nodes().get(&first_hop_in_route.src_node_id).is_some();
888 if have_hop_src_in_graph {
889 // We start building the path from reverse, i.e., from payee
890 // to the first RouteHintHop in the path.
891 let hop_iter = route.0.iter().rev();
892 let prev_hop_iter = core::iter::once(payee).chain(
893 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
894 let mut hop_used = true;
895 let mut aggregate_next_hops_fee_msat: u64 = 0;
896 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
898 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
899 // BOLT 11 doesn't allow inclusion of features for the last hop hints, which
900 // really sucks, cause we're gonna need that eventually.
901 let hop_htlc_minimum_msat: u64 = hop.htlc_minimum_msat.unwrap_or(0);
903 let directional_info = DummyDirectionalChannelInfo {
904 cltv_expiry_delta: hop.cltv_expiry_delta as u32,
905 htlc_minimum_msat: hop_htlc_minimum_msat,
906 htlc_maximum_msat: hop.htlc_maximum_msat,
910 let reqd_channel_cap = if let Some (val) = final_value_msat.checked_add(match idx {
912 _ => aggregate_next_hops_fee_msat.checked_add(999).unwrap_or(u64::max_value())
913 }) { Some( val / 1000 ) } else { break; }; // converting from msat or breaking if max ~ infinity
916 // We assume that the recipient only included route hints for routes which had
917 // sufficient value to route `final_value_msat`. Note that in the case of "0-value"
918 // invoices where the invoice does not specify value this may not be the case, but
919 // better to include the hints than not.
920 if !add_entry!(hop.short_channel_id, hop.src_node_id, prev_hop_id, directional_info, reqd_channel_cap, &empty_channel_features, aggregate_next_hops_fee_msat, path_value_msat, aggregate_next_hops_path_htlc_minimum_msat) {
921 // If this hop was not used then there is no use checking the preceding hops
922 // in the RouteHint. We can break by just searching for a direct channel between
923 // last checked hop and first_hop_targets
927 // Searching for a direct channel between last checked hop and first_hop_targets
928 if let Some(&(ref first_hop, ref features, ref outbound_capacity_msat, _)) = first_hop_targets.get(&prev_hop_id) {
929 add_entry!(first_hop, *our_node_id , prev_hop_id, dummy_directional_info, Some(outbound_capacity_msat / 1000), features, aggregate_next_hops_fee_msat, path_value_msat, aggregate_next_hops_path_htlc_minimum_msat);
936 // In the next values of the iterator, the aggregate fees already reflects
937 // the sum of value sent from payer (final_value_msat) and routing fees
938 // for the last node in the RouteHint. We need to just add the fees to
939 // route through the current node so that the preceeding node (next iteration)
941 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
942 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
943 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
945 let hop_htlc_minimum_msat_inc = if let Some(val) = compute_fees(aggregate_next_hops_path_htlc_minimum_msat, hop.fees) { val } else { break; };
946 let hops_path_htlc_minimum = aggregate_next_hops_path_htlc_minimum_msat
947 .checked_add(hop_htlc_minimum_msat_inc);
948 aggregate_next_hops_path_htlc_minimum_msat = if let Some(val) = hops_path_htlc_minimum { cmp::max(hop_htlc_minimum_msat, val) } else { break; };
950 if idx == route.0.len() - 1 {
951 // The last hop in this iterator is the first hop in
952 // overall RouteHint.
953 // If this hop connects to a node with which we have a direct channel,
954 // ignore the network graph and, if the last hop was added, add our
955 // direct channel to the candidate set.
957 // Note that we *must* check if the last hop was added as `add_entry`
958 // always assumes that the third argument is a node to which we have a
960 if let Some(&(ref first_hop, ref features, ref outbound_capacity_msat, _)) = first_hop_targets.get(&hop.src_node_id) {
961 add_entry!(first_hop, *our_node_id , hop.src_node_id, dummy_directional_info, Some(outbound_capacity_msat / 1000), features, aggregate_next_hops_fee_msat, path_value_msat, aggregate_next_hops_path_htlc_minimum_msat);
968 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
970 // At this point, targets are filled with the data from first and
971 // last hops communicated by the caller, and the payment receiver.
972 let mut found_new_path = false;
975 // If this loop terminates due the exhaustion of targets, two situations are possible:
976 // - not enough outgoing liquidity:
977 // 0 < already_collected_value_msat < final_value_msat
978 // - enough outgoing liquidity:
979 // final_value_msat <= already_collected_value_msat < recommended_value_msat
980 // Both these cases (and other cases except reaching recommended_value_msat) mean that
981 // paths_collection will be stopped because found_new_path==false.
982 // This is not necessarily a routing failure.
983 'path_construction: while let Some(RouteGraphNode { pubkey, lowest_fee_to_node, value_contribution_msat, path_htlc_minimum_msat, .. }) = targets.pop() {
985 // Since we're going payee-to-payer, hitting our node as a target means we should stop
986 // traversing the graph and arrange the path out of what we found.
987 if pubkey == *our_node_id {
988 let mut new_entry = dist.remove(&our_node_id).unwrap();
989 let mut ordered_hops = vec!((new_entry.clone(), NodeFeatures::empty()));
992 if let Some(&(_, _, _, ref features)) = first_hop_targets.get(&ordered_hops.last().unwrap().0.pubkey) {
993 ordered_hops.last_mut().unwrap().1 = features.clone();
994 } else if let Some(node) = network.get_nodes().get(&ordered_hops.last().unwrap().0.pubkey) {
995 if let Some(node_info) = node.announcement_info.as_ref() {
996 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
998 ordered_hops.last_mut().unwrap().1 = NodeFeatures::empty();
1001 // We should be able to fill in features for everything except the last
1002 // hop, if the last hop was provided via a BOLT 11 invoice (though we
1003 // should be able to extend it further as BOLT 11 does have feature
1004 // flags for the last hop node itself).
1005 assert!(ordered_hops.last().unwrap().0.pubkey == *payee);
1008 // Means we succesfully traversed from the payer to the payee, now
1009 // save this path for the payment route. Also, update the liquidity
1010 // remaining on the used hops, so that we take them into account
1011 // while looking for more paths.
1012 if ordered_hops.last().unwrap().0.pubkey == *payee {
1016 new_entry = match dist.remove(&ordered_hops.last().unwrap().0.pubkey) {
1017 Some(payment_hop) => payment_hop,
1018 // We can't arrive at None because, if we ever add an entry to targets,
1019 // we also fill in the entry in dist (see add_entry!).
1020 None => unreachable!(),
1022 // We "propagate" the fees one hop backward (topologically) here,
1023 // so that fees paid for a HTLC forwarding on the current channel are
1024 // associated with the previous channel (where they will be subtracted).
1025 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
1026 ordered_hops.last_mut().unwrap().0.cltv_expiry_delta = new_entry.cltv_expiry_delta;
1027 ordered_hops.push((new_entry.clone(), NodeFeatures::empty()));
1029 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
1030 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
1031 ordered_hops.last_mut().unwrap().0.cltv_expiry_delta = final_cltv;
1033 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: {:?}",
1034 ordered_hops.len(), value_contribution_msat, ordered_hops);
1036 let mut payment_path = PaymentPath {hops: ordered_hops};
1038 // We could have possibly constructed a slightly inconsistent path: since we reduce
1039 // value being transferred along the way, we could have violated htlc_minimum_msat
1040 // on some channels we already passed (assuming dest->source direction). Here, we
1041 // recompute the fees again, so that if that's the case, we match the currently
1042 // underpaid htlc_minimum_msat with fees.
1043 payment_path.update_value_and_recompute_fees(cmp::min(value_contribution_msat, final_value_msat));
1045 // Since a path allows to transfer as much value as
1046 // the smallest channel it has ("bottleneck"), we should recompute
1047 // the fees so sender HTLC don't overpay fees when traversing
1048 // larger channels than the bottleneck. This may happen because
1049 // when we were selecting those channels we were not aware how much value
1050 // this path will transfer, and the relative fee for them
1051 // might have been computed considering a larger value.
1052 // Remember that we used these channels so that we don't rely
1053 // on the same liquidity in future paths.
1054 let mut prevented_redundant_path_selection = false;
1055 for (payment_hop, _) in payment_path.hops.iter() {
1056 let channel_liquidity_available_msat = bookkeeped_channels_liquidity_available_msat.get_mut(&payment_hop.short_channel_id).unwrap();
1057 let mut spent_on_hop_msat = value_contribution_msat;
1058 let next_hops_fee_msat = payment_hop.next_hops_fee_msat;
1059 spent_on_hop_msat += next_hops_fee_msat;
1060 if spent_on_hop_msat == *channel_liquidity_available_msat {
1061 // If this path used all of this channel's available liquidity, we know
1062 // this path will not be selected again in the next loop iteration.
1063 prevented_redundant_path_selection = true;
1065 *channel_liquidity_available_msat -= spent_on_hop_msat;
1067 if !prevented_redundant_path_selection {
1068 // If we weren't capped by hitting a liquidity limit on a channel in the path,
1069 // we'll probably end up picking the same path again on the next iteration.
1070 // Decrease the available liquidity of a hop in the middle of the path.
1071 let victim_scid = payment_path.hops[(payment_path.hops.len() - 1) / 2].0.short_channel_id;
1072 log_trace!(logger, "Disabling channel {} for future path building iterations to avoid duplicates.", victim_scid);
1073 let victim_liquidity = bookkeeped_channels_liquidity_available_msat.get_mut(&victim_scid).unwrap();
1074 *victim_liquidity = 0;
1077 // Track the total amount all our collected paths allow to send so that we:
1078 // - know when to stop looking for more paths
1079 // - know which of the hops are useless considering how much more sats we need
1080 // (contributes_sufficient_value)
1081 already_collected_value_msat += value_contribution_msat;
1083 payment_paths.push(payment_path);
1084 found_new_path = true;
1085 break 'path_construction;
1088 // If we found a path back to the payee, we shouldn't try to process it again. This is
1089 // the equivalent of the `elem.was_processed` check in
1090 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
1091 if pubkey == *payee { continue 'path_construction; }
1093 // Otherwise, since the current target node is not us,
1094 // keep "unrolling" the payment graph from payee to payer by
1095 // finding a way to reach the current target from the payer side.
1096 match network.get_nodes().get(&pubkey) {
1099 add_entries_to_cheapest_to_target_node!(node, &pubkey, lowest_fee_to_node, value_contribution_msat, path_htlc_minimum_msat);
1105 // If we don't support MPP, no use trying to gather more value ever.
1106 break 'paths_collection;
1110 // Stop either when the recommended value is reached or if no new path was found in this
1112 // In the latter case, making another path finding attempt won't help,
1113 // because we deterministically terminated the search due to low liquidity.
1114 if already_collected_value_msat >= recommended_value_msat || !found_new_path {
1115 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
1116 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
1117 break 'paths_collection;
1118 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
1119 // Further, if this was our first walk of the graph, and we weren't limited by an
1120 // htlc_minimum_msat, return immediately because this path should suffice. If we were
1121 // limited by an htlc_minimum_msat value, find another path with a higher value,
1122 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
1123 // still keeping a lower total fee than this path.
1124 if !hit_minimum_limit {
1125 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
1126 break 'paths_collection;
1128 log_trace!(logger, "Collected our payment amount on the first pass, but running again to collect extra paths with a potentially higher limit.");
1129 path_value_msat = recommended_value_msat;
1134 if payment_paths.len() == 0 {
1135 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1138 if already_collected_value_msat < final_value_msat {
1139 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1142 // Sort by total fees and take the best paths.
1143 payment_paths.sort_by_key(|path| path.get_total_fee_paid_msat());
1144 if payment_paths.len() > 50 {
1145 payment_paths.truncate(50);
1148 // Draw multiple sufficient routes by randomly combining the selected paths.
1149 let mut drawn_routes = Vec::new();
1150 for i in 0..payment_paths.len() {
1151 let mut cur_route = Vec::<PaymentPath>::new();
1152 let mut aggregate_route_value_msat = 0;
1155 // TODO: real random shuffle
1156 // Currently just starts with i_th and goes up to i-1_th in a looped way.
1157 let cur_payment_paths = [&payment_paths[i..], &payment_paths[..i]].concat();
1160 for payment_path in cur_payment_paths {
1161 cur_route.push(payment_path.clone());
1162 aggregate_route_value_msat += payment_path.get_value_msat();
1163 if aggregate_route_value_msat > final_value_msat {
1164 // Last path likely overpaid. Substract it from the most expensive
1165 // (in terms of proportional fee) path in this route and recompute fees.
1166 // This might be not the most economically efficient way, but fewer paths
1167 // also makes routing more reliable.
1168 let mut overpaid_value_msat = aggregate_route_value_msat - final_value_msat;
1170 // First, drop some expensive low-value paths entirely if possible.
1171 // Sort by value so that we drop many really-low values first, since
1172 // fewer paths is better: the payment is less likely to fail.
1173 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1174 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1175 cur_route.sort_by_key(|path| path.get_value_msat());
1176 // We should make sure that at least 1 path left.
1177 let mut paths_left = cur_route.len();
1178 cur_route.retain(|path| {
1179 if paths_left == 1 {
1182 let mut keep = true;
1183 let path_value_msat = path.get_value_msat();
1184 if path_value_msat <= overpaid_value_msat {
1186 overpaid_value_msat -= path_value_msat;
1192 if overpaid_value_msat == 0 {
1196 assert!(cur_route.len() > 0);
1199 // Now, substract the overpaid value from the most-expensive path.
1200 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1201 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1202 cur_route.sort_by_key(|path| { path.hops.iter().map(|hop| hop.0.channel_fees.proportional_millionths as u64).sum::<u64>() });
1203 let expensive_payment_path = cur_route.first_mut().unwrap();
1204 // We already dropped all the small channels above, meaning all the
1205 // remaining channels are larger than remaining overpaid_value_msat.
1206 // Thus, this can't be negative.
1207 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
1208 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
1212 drawn_routes.push(cur_route);
1216 // Select the best route by lowest total fee.
1217 drawn_routes.sort_by_key(|paths| paths.iter().map(|path| path.get_total_fee_paid_msat()).sum::<u64>());
1218 let mut selected_paths = Vec::<Vec<RouteHop>>::new();
1219 for payment_path in drawn_routes.first().unwrap() {
1220 selected_paths.push(payment_path.hops.iter().map(|(payment_hop, node_features)| {
1222 pubkey: payment_hop.pubkey,
1223 node_features: node_features.clone(),
1224 short_channel_id: payment_hop.short_channel_id,
1225 channel_features: payment_hop.channel_features.clone(),
1226 fee_msat: payment_hop.fee_msat,
1227 cltv_expiry_delta: payment_hop.cltv_expiry_delta,
1232 if let Some(features) = &payee_features {
1233 for path in selected_paths.iter_mut() {
1234 path.last_mut().unwrap().node_features = features.to_context();
1238 let route = Route { paths: selected_paths };
1239 log_info!(logger, "Got route to {}: {}", payee, log_route!(route));
1245 use routing::router::{get_route, Route, RouteHint, RouteHintHop, RoutingFees};
1246 use routing::network_graph::{NetworkGraph, NetGraphMsgHandler};
1247 use chain::transaction::OutPoint;
1248 use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
1249 use ln::msgs::{ErrorAction, LightningError, OptionalField, UnsignedChannelAnnouncement, ChannelAnnouncement, RoutingMessageHandler,
1250 NodeAnnouncement, UnsignedNodeAnnouncement, ChannelUpdate, UnsignedChannelUpdate};
1251 use ln::channelmanager;
1252 use util::test_utils;
1253 use util::ser::Writeable;
1255 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
1256 use bitcoin::hashes::Hash;
1257 use bitcoin::network::constants::Network;
1258 use bitcoin::blockdata::constants::genesis_block;
1259 use bitcoin::blockdata::script::Builder;
1260 use bitcoin::blockdata::opcodes;
1261 use bitcoin::blockdata::transaction::TxOut;
1265 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
1266 use bitcoin::secp256k1::{Secp256k1, All};
1269 use sync::{self, Arc};
1271 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
1272 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
1273 channelmanager::ChannelDetails {
1274 channel_id: [0; 32],
1275 counterparty: channelmanager::ChannelCounterparty {
1278 unspendable_punishment_reserve: 0,
1279 forwarding_info: None,
1281 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
1283 channel_value_satoshis: 0,
1285 outbound_capacity_msat,
1286 inbound_capacity_msat: 42,
1287 unspendable_punishment_reserve: None,
1288 confirmations_required: None,
1289 force_close_spend_delay: None,
1290 is_outbound: true, is_funding_locked: true,
1291 is_usable: true, is_public: true,
1295 // Using the same keys for LN and BTC ids
1296 fn add_channel(net_graph_msg_handler: &NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>, secp_ctx: &Secp256k1<All>, node_1_privkey: &SecretKey,
1297 node_2_privkey: &SecretKey, features: ChannelFeatures, short_channel_id: u64) {
1298 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1299 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1301 let unsigned_announcement = UnsignedChannelAnnouncement {
1303 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1307 bitcoin_key_1: node_id_1,
1308 bitcoin_key_2: node_id_2,
1309 excess_data: Vec::new(),
1312 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1313 let valid_announcement = ChannelAnnouncement {
1314 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1315 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1316 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1317 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1318 contents: unsigned_announcement.clone(),
1320 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1321 Ok(res) => assert!(res),
1326 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) {
1327 let msghash = hash_to_message!(&Sha256dHash::hash(&update.encode()[..])[..]);
1328 let valid_channel_update = ChannelUpdate {
1329 signature: secp_ctx.sign(&msghash, node_privkey),
1330 contents: update.clone()
1333 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1334 Ok(res) => assert!(res),
1339 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,
1340 features: NodeFeatures, timestamp: u32) {
1341 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
1342 let unsigned_announcement = UnsignedNodeAnnouncement {
1348 addresses: Vec::new(),
1349 excess_address_data: Vec::new(),
1350 excess_data: Vec::new(),
1352 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1353 let valid_announcement = NodeAnnouncement {
1354 signature: secp_ctx.sign(&msghash, node_privkey),
1355 contents: unsigned_announcement.clone()
1358 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1364 fn get_nodes(secp_ctx: &Secp256k1<All>) -> (SecretKey, PublicKey, Vec<SecretKey>, Vec<PublicKey>) {
1365 let privkeys: Vec<SecretKey> = (2..10).map(|i| {
1366 SecretKey::from_slice(&hex::decode(format!("{:02}", i).repeat(32)).unwrap()[..]).unwrap()
1369 let pubkeys = privkeys.iter().map(|secret| PublicKey::from_secret_key(&secp_ctx, secret)).collect();
1371 let our_privkey = SecretKey::from_slice(&hex::decode("01".repeat(32)).unwrap()[..]).unwrap();
1372 let our_id = PublicKey::from_secret_key(&secp_ctx, &our_privkey);
1374 (our_privkey, our_id, privkeys, pubkeys)
1377 fn id_to_feature_flags(id: u8) -> Vec<u8> {
1378 // Set the feature flags to the id'th odd (ie non-required) feature bit so that we can
1379 // test for it later.
1380 let idx = (id - 1) * 2 + 1;
1382 vec![1 << (idx - 8*3), 0, 0, 0]
1383 } else if idx > 8*2 {
1384 vec![1 << (idx - 8*2), 0, 0]
1385 } else if idx > 8*1 {
1386 vec![1 << (idx - 8*1), 0]
1392 fn build_graph() -> (Secp256k1<All>, NetGraphMsgHandler<sync::Arc<test_utils::TestChainSource>, sync::Arc<crate::util::test_utils::TestLogger>>, sync::Arc<test_utils::TestChainSource>, sync::Arc<test_utils::TestLogger>) {
1393 let secp_ctx = Secp256k1::new();
1394 let logger = Arc::new(test_utils::TestLogger::new());
1395 let chain_monitor = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1396 let net_graph_msg_handler = NetGraphMsgHandler::new(genesis_block(Network::Testnet).header.block_hash(), None, Arc::clone(&logger));
1397 // Build network from our_id to node6:
1399 // -1(1)2- node0 -1(3)2-
1401 // our_id -1(12)2- node7 -1(13)2--- node2
1403 // -1(2)2- node1 -1(4)2-
1406 // chan1 1-to-2: disabled
1407 // chan1 2-to-1: enabled, 0 fee
1409 // chan2 1-to-2: enabled, ignored fee
1410 // chan2 2-to-1: enabled, 0 fee
1412 // chan3 1-to-2: enabled, 0 fee
1413 // chan3 2-to-1: enabled, 100 msat fee
1415 // chan4 1-to-2: enabled, 100% fee
1416 // chan4 2-to-1: enabled, 0 fee
1418 // chan12 1-to-2: enabled, ignored fee
1419 // chan12 2-to-1: enabled, 0 fee
1421 // chan13 1-to-2: enabled, 200% fee
1422 // chan13 2-to-1: enabled, 0 fee
1425 // -1(5)2- node3 -1(8)2--
1429 // node2--1(6)2- node4 -1(9)2--- node6 (not in global route map)
1431 // -1(7)2- node5 -1(10)2-
1433 // Channels 5, 8, 9 and 10 are private channels.
1435 // chan5 1-to-2: enabled, 100 msat fee
1436 // chan5 2-to-1: enabled, 0 fee
1438 // chan6 1-to-2: enabled, 0 fee
1439 // chan6 2-to-1: enabled, 0 fee
1441 // chan7 1-to-2: enabled, 100% fee
1442 // chan7 2-to-1: enabled, 0 fee
1444 // chan8 1-to-2: enabled, variable fee (0 then 1000 msat)
1445 // chan8 2-to-1: enabled, 0 fee
1447 // chan9 1-to-2: enabled, 1001 msat fee
1448 // chan9 2-to-1: enabled, 0 fee
1450 // chan10 1-to-2: enabled, 0 fee
1451 // chan10 2-to-1: enabled, 0 fee
1453 // chan11 1-to-2: enabled, 0 fee
1454 // chan11 2-to-1: enabled, 0 fee
1456 let (our_privkey, _, privkeys, _) = get_nodes(&secp_ctx);
1458 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[0], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
1459 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1460 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1461 short_channel_id: 1,
1464 cltv_expiry_delta: 0,
1465 htlc_minimum_msat: 0,
1466 htlc_maximum_msat: OptionalField::Absent,
1468 fee_proportional_millionths: 0,
1469 excess_data: Vec::new()
1472 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
1474 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
1475 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1476 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1477 short_channel_id: 2,
1480 cltv_expiry_delta: u16::max_value(),
1481 htlc_minimum_msat: 0,
1482 htlc_maximum_msat: OptionalField::Absent,
1483 fee_base_msat: u32::max_value(),
1484 fee_proportional_millionths: u32::max_value(),
1485 excess_data: Vec::new()
1487 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1488 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1489 short_channel_id: 2,
1492 cltv_expiry_delta: 0,
1493 htlc_minimum_msat: 0,
1494 htlc_maximum_msat: OptionalField::Absent,
1496 fee_proportional_millionths: 0,
1497 excess_data: Vec::new()
1500 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
1502 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[7], ChannelFeatures::from_le_bytes(id_to_feature_flags(12)), 12);
1503 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1504 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1505 short_channel_id: 12,
1508 cltv_expiry_delta: u16::max_value(),
1509 htlc_minimum_msat: 0,
1510 htlc_maximum_msat: OptionalField::Absent,
1511 fee_base_msat: u32::max_value(),
1512 fee_proportional_millionths: u32::max_value(),
1513 excess_data: Vec::new()
1515 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1516 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1517 short_channel_id: 12,
1520 cltv_expiry_delta: 0,
1521 htlc_minimum_msat: 0,
1522 htlc_maximum_msat: OptionalField::Absent,
1524 fee_proportional_millionths: 0,
1525 excess_data: Vec::new()
1528 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], NodeFeatures::from_le_bytes(id_to_feature_flags(8)), 0);
1530 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
1531 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1532 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1533 short_channel_id: 3,
1536 cltv_expiry_delta: (3 << 8) | 1,
1537 htlc_minimum_msat: 0,
1538 htlc_maximum_msat: OptionalField::Absent,
1540 fee_proportional_millionths: 0,
1541 excess_data: Vec::new()
1543 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1544 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1545 short_channel_id: 3,
1548 cltv_expiry_delta: (3 << 8) | 2,
1549 htlc_minimum_msat: 0,
1550 htlc_maximum_msat: OptionalField::Absent,
1552 fee_proportional_millionths: 0,
1553 excess_data: Vec::new()
1556 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
1557 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1558 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1559 short_channel_id: 4,
1562 cltv_expiry_delta: (4 << 8) | 1,
1563 htlc_minimum_msat: 0,
1564 htlc_maximum_msat: OptionalField::Absent,
1566 fee_proportional_millionths: 1000000,
1567 excess_data: Vec::new()
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: 4,
1574 cltv_expiry_delta: (4 << 8) | 2,
1575 htlc_minimum_msat: 0,
1576 htlc_maximum_msat: OptionalField::Absent,
1578 fee_proportional_millionths: 0,
1579 excess_data: Vec::new()
1582 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(13)), 13);
1583 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1584 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1585 short_channel_id: 13,
1588 cltv_expiry_delta: (13 << 8) | 1,
1589 htlc_minimum_msat: 0,
1590 htlc_maximum_msat: OptionalField::Absent,
1592 fee_proportional_millionths: 2000000,
1593 excess_data: Vec::new()
1595 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1596 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1597 short_channel_id: 13,
1600 cltv_expiry_delta: (13 << 8) | 2,
1601 htlc_minimum_msat: 0,
1602 htlc_maximum_msat: OptionalField::Absent,
1604 fee_proportional_millionths: 0,
1605 excess_data: Vec::new()
1608 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
1610 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
1611 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1612 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1613 short_channel_id: 6,
1616 cltv_expiry_delta: (6 << 8) | 1,
1617 htlc_minimum_msat: 0,
1618 htlc_maximum_msat: OptionalField::Absent,
1620 fee_proportional_millionths: 0,
1621 excess_data: Vec::new()
1623 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1624 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1625 short_channel_id: 6,
1628 cltv_expiry_delta: (6 << 8) | 2,
1629 htlc_minimum_msat: 0,
1630 htlc_maximum_msat: OptionalField::Absent,
1632 fee_proportional_millionths: 0,
1633 excess_data: Vec::new(),
1636 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(11)), 11);
1637 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1638 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1639 short_channel_id: 11,
1642 cltv_expiry_delta: (11 << 8) | 1,
1643 htlc_minimum_msat: 0,
1644 htlc_maximum_msat: OptionalField::Absent,
1646 fee_proportional_millionths: 0,
1647 excess_data: Vec::new()
1649 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
1650 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1651 short_channel_id: 11,
1654 cltv_expiry_delta: (11 << 8) | 2,
1655 htlc_minimum_msat: 0,
1656 htlc_maximum_msat: OptionalField::Absent,
1658 fee_proportional_millionths: 0,
1659 excess_data: Vec::new()
1662 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(5)), 0);
1664 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
1666 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[5], ChannelFeatures::from_le_bytes(id_to_feature_flags(7)), 7);
1667 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1668 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1669 short_channel_id: 7,
1672 cltv_expiry_delta: (7 << 8) | 1,
1673 htlc_minimum_msat: 0,
1674 htlc_maximum_msat: OptionalField::Absent,
1676 fee_proportional_millionths: 1000000,
1677 excess_data: Vec::new()
1679 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[5], UnsignedChannelUpdate {
1680 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1681 short_channel_id: 7,
1684 cltv_expiry_delta: (7 << 8) | 2,
1685 htlc_minimum_msat: 0,
1686 htlc_maximum_msat: OptionalField::Absent,
1688 fee_proportional_millionths: 0,
1689 excess_data: Vec::new()
1692 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[5], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
1694 (secp_ctx, net_graph_msg_handler, chain_monitor, logger)
1698 fn simple_route_test() {
1699 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1700 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1702 // Simple route to 2 via 1
1704 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)) {
1705 assert_eq!(err, "Cannot send a payment of 0 msat");
1706 } else { panic!(); }
1708 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();
1709 assert_eq!(route.paths[0].len(), 2);
1711 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
1712 assert_eq!(route.paths[0][0].short_channel_id, 2);
1713 assert_eq!(route.paths[0][0].fee_msat, 100);
1714 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
1715 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
1716 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
1718 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1719 assert_eq!(route.paths[0][1].short_channel_id, 4);
1720 assert_eq!(route.paths[0][1].fee_msat, 100);
1721 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1722 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1723 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
1727 fn invalid_first_hop_test() {
1728 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1729 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1731 // Simple route to 2 via 1
1733 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
1735 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)) {
1736 assert_eq!(err, "First hop cannot have our_node_id as a destination.");
1737 } else { panic!(); }
1739 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();
1740 assert_eq!(route.paths[0].len(), 2);
1744 fn htlc_minimum_test() {
1745 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1746 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1748 // Simple route to 2 via 1
1750 // Disable other paths
1751 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1752 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1753 short_channel_id: 12,
1755 flags: 2, // to disable
1756 cltv_expiry_delta: 0,
1757 htlc_minimum_msat: 0,
1758 htlc_maximum_msat: OptionalField::Absent,
1760 fee_proportional_millionths: 0,
1761 excess_data: Vec::new()
1763 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1764 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1765 short_channel_id: 3,
1767 flags: 2, // to disable
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()
1775 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1776 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1777 short_channel_id: 13,
1779 flags: 2, // to disable
1780 cltv_expiry_delta: 0,
1781 htlc_minimum_msat: 0,
1782 htlc_maximum_msat: OptionalField::Absent,
1784 fee_proportional_millionths: 0,
1785 excess_data: Vec::new()
1787 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1788 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1789 short_channel_id: 6,
1791 flags: 2, // to disable
1792 cltv_expiry_delta: 0,
1793 htlc_minimum_msat: 0,
1794 htlc_maximum_msat: OptionalField::Absent,
1796 fee_proportional_millionths: 0,
1797 excess_data: Vec::new()
1799 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1800 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1801 short_channel_id: 7,
1803 flags: 2, // to disable
1804 cltv_expiry_delta: 0,
1805 htlc_minimum_msat: 0,
1806 htlc_maximum_msat: OptionalField::Absent,
1808 fee_proportional_millionths: 0,
1809 excess_data: Vec::new()
1812 // Check against amount_to_transfer_over_msat.
1813 // Set minimal HTLC of 200_000_000 msat.
1814 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1815 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1816 short_channel_id: 2,
1819 cltv_expiry_delta: 0,
1820 htlc_minimum_msat: 200_000_000,
1821 htlc_maximum_msat: OptionalField::Absent,
1823 fee_proportional_millionths: 0,
1824 excess_data: Vec::new()
1827 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
1829 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1830 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1831 short_channel_id: 4,
1834 cltv_expiry_delta: 0,
1835 htlc_minimum_msat: 0,
1836 htlc_maximum_msat: OptionalField::Present(199_999_999),
1838 fee_proportional_millionths: 0,
1839 excess_data: Vec::new()
1842 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
1843 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)) {
1844 assert_eq!(err, "Failed to find a path to the given destination");
1845 } else { panic!(); }
1847 // Lift the restriction on the first hop.
1848 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1849 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1850 short_channel_id: 2,
1853 cltv_expiry_delta: 0,
1854 htlc_minimum_msat: 0,
1855 htlc_maximum_msat: OptionalField::Absent,
1857 fee_proportional_millionths: 0,
1858 excess_data: Vec::new()
1861 // A payment above the minimum should pass
1862 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();
1863 assert_eq!(route.paths[0].len(), 2);
1867 fn htlc_minimum_overpay_test() {
1868 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1869 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1871 // A route to node#2 via two paths.
1872 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
1873 // Thus, they can't send 60 without overpaying.
1874 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1875 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1876 short_channel_id: 2,
1879 cltv_expiry_delta: 0,
1880 htlc_minimum_msat: 35_000,
1881 htlc_maximum_msat: OptionalField::Present(40_000),
1883 fee_proportional_millionths: 0,
1884 excess_data: Vec::new()
1886 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1887 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1888 short_channel_id: 12,
1891 cltv_expiry_delta: 0,
1892 htlc_minimum_msat: 35_000,
1893 htlc_maximum_msat: OptionalField::Present(40_000),
1895 fee_proportional_millionths: 0,
1896 excess_data: Vec::new()
1900 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1901 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1902 short_channel_id: 13,
1905 cltv_expiry_delta: 0,
1906 htlc_minimum_msat: 0,
1907 htlc_maximum_msat: OptionalField::Absent,
1909 fee_proportional_millionths: 0,
1910 excess_data: Vec::new()
1912 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1913 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1914 short_channel_id: 4,
1917 cltv_expiry_delta: 0,
1918 htlc_minimum_msat: 0,
1919 htlc_maximum_msat: OptionalField::Absent,
1921 fee_proportional_millionths: 0,
1922 excess_data: Vec::new()
1925 // Disable other paths
1926 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1927 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1928 short_channel_id: 1,
1930 flags: 2, // to disable
1931 cltv_expiry_delta: 0,
1932 htlc_minimum_msat: 0,
1933 htlc_maximum_msat: OptionalField::Absent,
1935 fee_proportional_millionths: 0,
1936 excess_data: Vec::new()
1939 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
1940 Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger)).unwrap();
1941 // Overpay fees to hit htlc_minimum_msat.
1942 let overpaid_fees = route.paths[0][0].fee_msat + route.paths[1][0].fee_msat;
1943 // TODO: this could be better balanced to overpay 10k and not 15k.
1944 assert_eq!(overpaid_fees, 15_000);
1946 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
1947 // while taking even more fee to match htlc_minimum_msat.
1948 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1949 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1950 short_channel_id: 12,
1953 cltv_expiry_delta: 0,
1954 htlc_minimum_msat: 65_000,
1955 htlc_maximum_msat: OptionalField::Present(80_000),
1957 fee_proportional_millionths: 0,
1958 excess_data: Vec::new()
1960 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1961 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1962 short_channel_id: 2,
1965 cltv_expiry_delta: 0,
1966 htlc_minimum_msat: 0,
1967 htlc_maximum_msat: OptionalField::Absent,
1969 fee_proportional_millionths: 0,
1970 excess_data: Vec::new()
1972 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1973 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1974 short_channel_id: 4,
1977 cltv_expiry_delta: 0,
1978 htlc_minimum_msat: 0,
1979 htlc_maximum_msat: OptionalField::Absent,
1981 fee_proportional_millionths: 100_000,
1982 excess_data: Vec::new()
1985 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
1986 Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger)).unwrap();
1987 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
1988 assert_eq!(route.paths.len(), 1);
1989 assert_eq!(route.paths[0][0].short_channel_id, 12);
1990 let fees = route.paths[0][0].fee_msat;
1991 assert_eq!(fees, 5_000);
1993 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
1994 Some(InvoiceFeatures::known()), None, &Vec::new(), 50_000, 42, Arc::clone(&logger)).unwrap();
1995 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
1996 // the other channel.
1997 assert_eq!(route.paths.len(), 1);
1998 assert_eq!(route.paths[0][0].short_channel_id, 2);
1999 let fees = route.paths[0][0].fee_msat;
2000 assert_eq!(fees, 5_000);
2004 fn disable_channels_test() {
2005 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2006 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2008 // // Disable channels 4 and 12 by flags=2
2009 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2010 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2011 short_channel_id: 4,
2013 flags: 2, // to disable
2014 cltv_expiry_delta: 0,
2015 htlc_minimum_msat: 0,
2016 htlc_maximum_msat: OptionalField::Absent,
2018 fee_proportional_millionths: 0,
2019 excess_data: Vec::new()
2021 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2022 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2023 short_channel_id: 12,
2025 flags: 2, // to disable
2026 cltv_expiry_delta: 0,
2027 htlc_minimum_msat: 0,
2028 htlc_maximum_msat: OptionalField::Absent,
2030 fee_proportional_millionths: 0,
2031 excess_data: Vec::new()
2034 // If all the channels require some features we don't understand, route should fail
2035 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)) {
2036 assert_eq!(err, "Failed to find a path to the given destination");
2037 } else { panic!(); }
2039 // If we specify a channel to node7, that overrides our local channel view and that gets used
2040 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2041 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();
2042 assert_eq!(route.paths[0].len(), 2);
2044 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2045 assert_eq!(route.paths[0][0].short_channel_id, 42);
2046 assert_eq!(route.paths[0][0].fee_msat, 200);
2047 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
2048 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2049 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2051 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2052 assert_eq!(route.paths[0][1].short_channel_id, 13);
2053 assert_eq!(route.paths[0][1].fee_msat, 100);
2054 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2055 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2056 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2060 fn disable_node_test() {
2061 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2062 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2064 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
2065 let unknown_features = NodeFeatures::known().set_unknown_feature_required();
2066 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
2067 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
2068 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
2070 // If all nodes require some features we don't understand, route should fail
2071 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)) {
2072 assert_eq!(err, "Failed to find a path to the given destination");
2073 } else { panic!(); }
2075 // If we specify a channel to node7, that overrides our local channel view and that gets used
2076 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2077 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();
2078 assert_eq!(route.paths[0].len(), 2);
2080 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2081 assert_eq!(route.paths[0][0].short_channel_id, 42);
2082 assert_eq!(route.paths[0][0].fee_msat, 200);
2083 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
2084 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2085 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2087 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2088 assert_eq!(route.paths[0][1].short_channel_id, 13);
2089 assert_eq!(route.paths[0][1].fee_msat, 100);
2090 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2091 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2092 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2094 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
2095 // naively) assume that the user checked the feature bits on the invoice, which override
2096 // the node_announcement.
2100 fn our_chans_test() {
2101 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2102 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2104 // Route to 1 via 2 and 3 because our channel to 1 is disabled
2105 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();
2106 assert_eq!(route.paths[0].len(), 3);
2108 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2109 assert_eq!(route.paths[0][0].short_channel_id, 2);
2110 assert_eq!(route.paths[0][0].fee_msat, 200);
2111 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2112 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2113 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2115 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2116 assert_eq!(route.paths[0][1].short_channel_id, 4);
2117 assert_eq!(route.paths[0][1].fee_msat, 100);
2118 assert_eq!(route.paths[0][1].cltv_expiry_delta, (3 << 8) | 2);
2119 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2120 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2122 assert_eq!(route.paths[0][2].pubkey, nodes[0]);
2123 assert_eq!(route.paths[0][2].short_channel_id, 3);
2124 assert_eq!(route.paths[0][2].fee_msat, 100);
2125 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
2126 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(1));
2127 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(3));
2129 // If we specify a channel to node7, that overrides our local channel view and that gets used
2130 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2131 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();
2132 assert_eq!(route.paths[0].len(), 2);
2134 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2135 assert_eq!(route.paths[0][0].short_channel_id, 42);
2136 assert_eq!(route.paths[0][0].fee_msat, 200);
2137 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
2138 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2139 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2141 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2142 assert_eq!(route.paths[0][1].short_channel_id, 13);
2143 assert_eq!(route.paths[0][1].fee_msat, 100);
2144 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2145 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2146 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2149 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2150 let zero_fees = RoutingFees {
2152 proportional_millionths: 0,
2154 vec![RouteHint(vec![RouteHintHop {
2155 src_node_id: nodes[3].clone(),
2156 short_channel_id: 8,
2158 cltv_expiry_delta: (8 << 8) | 1,
2159 htlc_minimum_msat: None,
2160 htlc_maximum_msat: None,
2162 ]), RouteHint(vec![RouteHintHop {
2163 src_node_id: nodes[4].clone(),
2164 short_channel_id: 9,
2167 proportional_millionths: 0,
2169 cltv_expiry_delta: (9 << 8) | 1,
2170 htlc_minimum_msat: None,
2171 htlc_maximum_msat: None,
2172 }]), RouteHint(vec![RouteHintHop {
2173 src_node_id: nodes[5].clone(),
2174 short_channel_id: 10,
2176 cltv_expiry_delta: (10 << 8) | 1,
2177 htlc_minimum_msat: None,
2178 htlc_maximum_msat: None,
2182 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2183 let zero_fees = RoutingFees {
2185 proportional_millionths: 0,
2187 vec![RouteHint(vec![RouteHintHop {
2188 src_node_id: nodes[2].clone(),
2189 short_channel_id: 5,
2192 proportional_millionths: 0,
2194 cltv_expiry_delta: (5 << 8) | 1,
2195 htlc_minimum_msat: None,
2196 htlc_maximum_msat: None,
2198 src_node_id: nodes[3].clone(),
2199 short_channel_id: 8,
2201 cltv_expiry_delta: (8 << 8) | 1,
2202 htlc_minimum_msat: None,
2203 htlc_maximum_msat: None,
2205 ]), RouteHint(vec![RouteHintHop {
2206 src_node_id: nodes[4].clone(),
2207 short_channel_id: 9,
2210 proportional_millionths: 0,
2212 cltv_expiry_delta: (9 << 8) | 1,
2213 htlc_minimum_msat: None,
2214 htlc_maximum_msat: None,
2215 }]), RouteHint(vec![RouteHintHop {
2216 src_node_id: nodes[5].clone(),
2217 short_channel_id: 10,
2219 cltv_expiry_delta: (10 << 8) | 1,
2220 htlc_minimum_msat: None,
2221 htlc_maximum_msat: None,
2226 fn partial_route_hint_test() {
2227 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2228 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2230 // Simple test across 2, 3, 5, and 4 via a last_hop channel
2231 // Tests the behaviour when the RouteHint contains a suboptimal hop.
2232 // RouteHint may be partially used by the algo to build the best path.
2234 // First check that last hop can't have its source as the payee.
2235 let invalid_last_hop = RouteHint(vec![RouteHintHop {
2236 src_node_id: nodes[6],
2237 short_channel_id: 8,
2240 proportional_millionths: 0,
2242 cltv_expiry_delta: (8 << 8) | 1,
2243 htlc_minimum_msat: None,
2244 htlc_maximum_msat: None,
2247 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
2248 invalid_last_hops.push(invalid_last_hop);
2250 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)) {
2251 assert_eq!(err, "Last hop cannot have a payee as a source.");
2252 } else { panic!(); }
2255 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[6], None, None, &last_hops_multi_private_channels(&nodes).iter().collect::<Vec<_>>(), 100, 42, Arc::clone(&logger)).unwrap();
2256 assert_eq!(route.paths[0].len(), 5);
2258 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2259 assert_eq!(route.paths[0][0].short_channel_id, 2);
2260 assert_eq!(route.paths[0][0].fee_msat, 100);
2261 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2262 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2263 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2265 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2266 assert_eq!(route.paths[0][1].short_channel_id, 4);
2267 assert_eq!(route.paths[0][1].fee_msat, 0);
2268 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2269 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2270 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2272 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2273 assert_eq!(route.paths[0][2].short_channel_id, 6);
2274 assert_eq!(route.paths[0][2].fee_msat, 0);
2275 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2276 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2277 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2279 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2280 assert_eq!(route.paths[0][3].short_channel_id, 11);
2281 assert_eq!(route.paths[0][3].fee_msat, 0);
2282 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2283 // If we have a peer in the node map, we'll use their features here since we don't have
2284 // a way of figuring out their features from the invoice:
2285 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2286 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2288 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2289 assert_eq!(route.paths[0][4].short_channel_id, 8);
2290 assert_eq!(route.paths[0][4].fee_msat, 100);
2291 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2292 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2293 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2296 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2297 let zero_fees = RoutingFees {
2299 proportional_millionths: 0,
2301 vec![RouteHint(vec![RouteHintHop {
2302 src_node_id: nodes[3].clone(),
2303 short_channel_id: 8,
2305 cltv_expiry_delta: (8 << 8) | 1,
2306 htlc_minimum_msat: None,
2307 htlc_maximum_msat: None,
2308 }]), RouteHint(vec![
2310 ]), RouteHint(vec![RouteHintHop {
2311 src_node_id: nodes[5].clone(),
2312 short_channel_id: 10,
2314 cltv_expiry_delta: (10 << 8) | 1,
2315 htlc_minimum_msat: None,
2316 htlc_maximum_msat: None,
2321 fn ignores_empty_last_hops_test() {
2322 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2323 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2325 // Test handling of an empty RouteHint passed in Invoice.
2327 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[6], None, None, &empty_last_hop(&nodes).iter().collect::<Vec<_>>(), 100, 42, Arc::clone(&logger)).unwrap();
2328 assert_eq!(route.paths[0].len(), 5);
2330 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2331 assert_eq!(route.paths[0][0].short_channel_id, 2);
2332 assert_eq!(route.paths[0][0].fee_msat, 100);
2333 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2334 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2335 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2337 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2338 assert_eq!(route.paths[0][1].short_channel_id, 4);
2339 assert_eq!(route.paths[0][1].fee_msat, 0);
2340 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2341 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2342 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2344 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2345 assert_eq!(route.paths[0][2].short_channel_id, 6);
2346 assert_eq!(route.paths[0][2].fee_msat, 0);
2347 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2348 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2349 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2351 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2352 assert_eq!(route.paths[0][3].short_channel_id, 11);
2353 assert_eq!(route.paths[0][3].fee_msat, 0);
2354 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2355 // If we have a peer in the node map, we'll use their features here since we don't have
2356 // a way of figuring out their features from the invoice:
2357 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2358 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2360 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2361 assert_eq!(route.paths[0][4].short_channel_id, 8);
2362 assert_eq!(route.paths[0][4].fee_msat, 100);
2363 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2364 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2365 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2368 fn multi_hint_last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2369 let zero_fees = RoutingFees {
2371 proportional_millionths: 0,
2373 vec![RouteHint(vec![RouteHintHop {
2374 src_node_id: nodes[2].clone(),
2375 short_channel_id: 5,
2378 proportional_millionths: 0,
2380 cltv_expiry_delta: (5 << 8) | 1,
2381 htlc_minimum_msat: None,
2382 htlc_maximum_msat: None,
2384 src_node_id: nodes[3].clone(),
2385 short_channel_id: 8,
2387 cltv_expiry_delta: (8 << 8) | 1,
2388 htlc_minimum_msat: None,
2389 htlc_maximum_msat: None,
2390 }]), RouteHint(vec![RouteHintHop {
2391 src_node_id: nodes[5].clone(),
2392 short_channel_id: 10,
2394 cltv_expiry_delta: (10 << 8) | 1,
2395 htlc_minimum_msat: None,
2396 htlc_maximum_msat: None,
2401 fn multi_hint_last_hops_test() {
2402 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2403 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2404 // Test through channels 2, 3, 5, 8.
2405 // Test shows that multiple hop hints are considered.
2407 // Disabling channels 6 & 7 by flags=2
2408 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2409 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2410 short_channel_id: 6,
2412 flags: 2, // to disable
2413 cltv_expiry_delta: 0,
2414 htlc_minimum_msat: 0,
2415 htlc_maximum_msat: OptionalField::Absent,
2417 fee_proportional_millionths: 0,
2418 excess_data: Vec::new()
2420 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2421 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2422 short_channel_id: 7,
2424 flags: 2, // to disable
2425 cltv_expiry_delta: 0,
2426 htlc_minimum_msat: 0,
2427 htlc_maximum_msat: OptionalField::Absent,
2429 fee_proportional_millionths: 0,
2430 excess_data: Vec::new()
2433 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[6], None, None, &multi_hint_last_hops(&nodes).iter().collect::<Vec<_>>(), 100, 42, Arc::clone(&logger)).unwrap();
2434 assert_eq!(route.paths[0].len(), 4);
2436 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2437 assert_eq!(route.paths[0][0].short_channel_id, 2);
2438 assert_eq!(route.paths[0][0].fee_msat, 200);
2439 assert_eq!(route.paths[0][0].cltv_expiry_delta, 1025);
2440 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2441 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2443 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2444 assert_eq!(route.paths[0][1].short_channel_id, 4);
2445 assert_eq!(route.paths[0][1].fee_msat, 100);
2446 assert_eq!(route.paths[0][1].cltv_expiry_delta, 1281);
2447 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2448 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2450 assert_eq!(route.paths[0][2].pubkey, nodes[3]);
2451 assert_eq!(route.paths[0][2].short_channel_id, 5);
2452 assert_eq!(route.paths[0][2].fee_msat, 0);
2453 assert_eq!(route.paths[0][2].cltv_expiry_delta, 2049);
2454 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(4));
2455 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new());
2457 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2458 assert_eq!(route.paths[0][3].short_channel_id, 8);
2459 assert_eq!(route.paths[0][3].fee_msat, 100);
2460 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2461 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2462 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2465 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2466 let zero_fees = RoutingFees {
2468 proportional_millionths: 0,
2470 vec![RouteHint(vec![RouteHintHop {
2471 src_node_id: nodes[4].clone(),
2472 short_channel_id: 11,
2474 cltv_expiry_delta: (11 << 8) | 1,
2475 htlc_minimum_msat: None,
2476 htlc_maximum_msat: None,
2478 src_node_id: nodes[3].clone(),
2479 short_channel_id: 8,
2481 cltv_expiry_delta: (8 << 8) | 1,
2482 htlc_minimum_msat: None,
2483 htlc_maximum_msat: None,
2484 }]), RouteHint(vec![RouteHintHop {
2485 src_node_id: nodes[4].clone(),
2486 short_channel_id: 9,
2489 proportional_millionths: 0,
2491 cltv_expiry_delta: (9 << 8) | 1,
2492 htlc_minimum_msat: None,
2493 htlc_maximum_msat: None,
2494 }]), RouteHint(vec![RouteHintHop {
2495 src_node_id: nodes[5].clone(),
2496 short_channel_id: 10,
2498 cltv_expiry_delta: (10 << 8) | 1,
2499 htlc_minimum_msat: None,
2500 htlc_maximum_msat: None,
2505 fn last_hops_with_public_channel_test() {
2506 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2507 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2508 // This test shows that public routes can be present in the invoice
2509 // which would be handled in the same manner.
2511 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[6], None, None, &last_hops_with_public_channel(&nodes).iter().collect::<Vec<_>>(), 100, 42, Arc::clone(&logger)).unwrap();
2512 assert_eq!(route.paths[0].len(), 5);
2514 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2515 assert_eq!(route.paths[0][0].short_channel_id, 2);
2516 assert_eq!(route.paths[0][0].fee_msat, 100);
2517 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2518 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2519 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2521 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2522 assert_eq!(route.paths[0][1].short_channel_id, 4);
2523 assert_eq!(route.paths[0][1].fee_msat, 0);
2524 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2525 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2526 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2528 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2529 assert_eq!(route.paths[0][2].short_channel_id, 6);
2530 assert_eq!(route.paths[0][2].fee_msat, 0);
2531 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2532 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2533 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2535 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2536 assert_eq!(route.paths[0][3].short_channel_id, 11);
2537 assert_eq!(route.paths[0][3].fee_msat, 0);
2538 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2539 // If we have a peer in the node map, we'll use their features here since we don't have
2540 // a way of figuring out their features from the invoice:
2541 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2542 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new());
2544 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2545 assert_eq!(route.paths[0][4].short_channel_id, 8);
2546 assert_eq!(route.paths[0][4].fee_msat, 100);
2547 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2548 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2549 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2553 fn our_chans_last_hop_connect_test() {
2554 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2555 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2557 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
2558 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2559 let mut last_hops = last_hops(&nodes);
2560 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();
2561 assert_eq!(route.paths[0].len(), 2);
2563 assert_eq!(route.paths[0][0].pubkey, nodes[3]);
2564 assert_eq!(route.paths[0][0].short_channel_id, 42);
2565 assert_eq!(route.paths[0][0].fee_msat, 0);
2566 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
2567 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2568 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2570 assert_eq!(route.paths[0][1].pubkey, nodes[6]);
2571 assert_eq!(route.paths[0][1].short_channel_id, 8);
2572 assert_eq!(route.paths[0][1].fee_msat, 100);
2573 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2574 assert_eq!(route.paths[0][1].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2575 assert_eq!(route.paths[0][1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2577 last_hops[0].0[0].fees.base_msat = 1000;
2579 // Revert to via 6 as the fee on 8 goes up
2580 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();
2581 assert_eq!(route.paths[0].len(), 4);
2583 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2584 assert_eq!(route.paths[0][0].short_channel_id, 2);
2585 assert_eq!(route.paths[0][0].fee_msat, 200); // fee increased as its % of value transferred across node
2586 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2587 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2588 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2590 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2591 assert_eq!(route.paths[0][1].short_channel_id, 4);
2592 assert_eq!(route.paths[0][1].fee_msat, 100);
2593 assert_eq!(route.paths[0][1].cltv_expiry_delta, (7 << 8) | 1);
2594 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2595 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2597 assert_eq!(route.paths[0][2].pubkey, nodes[5]);
2598 assert_eq!(route.paths[0][2].short_channel_id, 7);
2599 assert_eq!(route.paths[0][2].fee_msat, 0);
2600 assert_eq!(route.paths[0][2].cltv_expiry_delta, (10 << 8) | 1);
2601 // If we have a peer in the node map, we'll use their features here since we don't have
2602 // a way of figuring out their features from the invoice:
2603 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
2604 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(7));
2606 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2607 assert_eq!(route.paths[0][3].short_channel_id, 10);
2608 assert_eq!(route.paths[0][3].fee_msat, 100);
2609 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2610 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2611 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2613 // ...but still use 8 for larger payments as 6 has a variable feerate
2614 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();
2615 assert_eq!(route.paths[0].len(), 5);
2617 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2618 assert_eq!(route.paths[0][0].short_channel_id, 2);
2619 assert_eq!(route.paths[0][0].fee_msat, 3000);
2620 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2621 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2622 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2624 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2625 assert_eq!(route.paths[0][1].short_channel_id, 4);
2626 assert_eq!(route.paths[0][1].fee_msat, 0);
2627 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2628 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2629 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2631 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2632 assert_eq!(route.paths[0][2].short_channel_id, 6);
2633 assert_eq!(route.paths[0][2].fee_msat, 0);
2634 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2635 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2636 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2638 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2639 assert_eq!(route.paths[0][3].short_channel_id, 11);
2640 assert_eq!(route.paths[0][3].fee_msat, 1000);
2641 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2642 // If we have a peer in the node map, we'll use their features here since we don't have
2643 // a way of figuring out their features from the invoice:
2644 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2645 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2647 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2648 assert_eq!(route.paths[0][4].short_channel_id, 8);
2649 assert_eq!(route.paths[0][4].fee_msat, 2000);
2650 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2651 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2652 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2655 fn do_unannounced_path_test(last_hop_htlc_max: Option<u64>, last_hop_fee_prop: u32, outbound_capacity_msat: u64, route_val: u64) -> Result<Route, LightningError> {
2656 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
2657 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
2658 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
2660 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
2661 let last_hops = RouteHint(vec![RouteHintHop {
2662 src_node_id: middle_node_id,
2663 short_channel_id: 8,
2666 proportional_millionths: last_hop_fee_prop,
2668 cltv_expiry_delta: (8 << 8) | 1,
2669 htlc_minimum_msat: None,
2670 htlc_maximum_msat: last_hop_htlc_max,
2672 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
2673 get_route(&source_node_id, &NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()), &target_node_id, None, Some(&our_chans.iter().collect::<Vec<_>>()), &vec![&last_hops], route_val, 42, Arc::new(test_utils::TestLogger::new()))
2677 fn unannounced_path_test() {
2678 // We should be able to send a payment to a destination without any help of a routing graph
2679 // if we have a channel with a common counterparty that appears in the first and last hop
2681 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
2683 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
2684 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
2685 assert_eq!(route.paths[0].len(), 2);
2687 assert_eq!(route.paths[0][0].pubkey, middle_node_id);
2688 assert_eq!(route.paths[0][0].short_channel_id, 42);
2689 assert_eq!(route.paths[0][0].fee_msat, 1001);
2690 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
2691 assert_eq!(route.paths[0][0].node_features.le_flags(), &[0b11]);
2692 assert_eq!(route.paths[0][0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
2694 assert_eq!(route.paths[0][1].pubkey, target_node_id);
2695 assert_eq!(route.paths[0][1].short_channel_id, 8);
2696 assert_eq!(route.paths[0][1].fee_msat, 1000000);
2697 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2698 assert_eq!(route.paths[0][1].node_features.le_flags(), &[0; 0]); // We dont pass flags in from invoices yet
2699 assert_eq!(route.paths[0][1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
2703 fn overflow_unannounced_path_test_liquidity_underflow() {
2704 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
2705 // the last-hop had a fee which overflowed a u64, we'd panic.
2706 // This was due to us adding the first-hop from us unconditionally, causing us to think
2707 // we'd built a path (as our node is in the "best candidate" set), when we had not.
2708 // In this test, we previously hit a subtraction underflow due to having less available
2709 // liquidity at the last hop than 0.
2710 assert!(do_unannounced_path_test(Some(21_000_000_0000_0000_000), 0, 21_000_000_0000_0000_000, 21_000_000_0000_0000_000).is_err());
2714 fn overflow_unannounced_path_test_feerate_overflow() {
2715 // This tests for the same case as above, except instead of hitting a subtraction
2716 // underflow, we hit a case where the fee charged at a hop overflowed.
2717 assert!(do_unannounced_path_test(Some(21_000_000_0000_0000_000), 50000, 21_000_000_0000_0000_000, 21_000_000_0000_0000_000).is_err());
2721 fn available_amount_while_routing_test() {
2722 // Tests whether we choose the correct available channel amount while routing.
2724 let (secp_ctx, mut net_graph_msg_handler, chain_monitor, logger) = build_graph();
2725 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2727 // We will use a simple single-path route from
2728 // our node to node2 via node0: channels {1, 3}.
2730 // First disable all other paths.
2731 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2732 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2733 short_channel_id: 2,
2736 cltv_expiry_delta: 0,
2737 htlc_minimum_msat: 0,
2738 htlc_maximum_msat: OptionalField::Present(100_000),
2740 fee_proportional_millionths: 0,
2741 excess_data: Vec::new()
2743 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2744 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2745 short_channel_id: 12,
2748 cltv_expiry_delta: 0,
2749 htlc_minimum_msat: 0,
2750 htlc_maximum_msat: OptionalField::Present(100_000),
2752 fee_proportional_millionths: 0,
2753 excess_data: Vec::new()
2756 // Make the first channel (#1) very permissive,
2757 // and we will be testing all limits on the second channel.
2758 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2759 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2760 short_channel_id: 1,
2763 cltv_expiry_delta: 0,
2764 htlc_minimum_msat: 0,
2765 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2767 fee_proportional_millionths: 0,
2768 excess_data: Vec::new()
2771 // First, let's see if routing works if we have absolutely no idea about the available amount.
2772 // In this case, it should be set to 250_000 sats.
2773 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2774 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2775 short_channel_id: 3,
2778 cltv_expiry_delta: 0,
2779 htlc_minimum_msat: 0,
2780 htlc_maximum_msat: OptionalField::Absent,
2782 fee_proportional_millionths: 0,
2783 excess_data: Vec::new()
2787 // Attempt to route more than available results in a failure.
2788 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2789 Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000_001, 42, Arc::clone(&logger)) {
2790 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2791 } else { panic!(); }
2795 // Now, attempt to route an exact amount we have should be fine.
2796 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2797 Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000_000, 42, Arc::clone(&logger)).unwrap();
2798 assert_eq!(route.paths.len(), 1);
2799 let path = route.paths.last().unwrap();
2800 assert_eq!(path.len(), 2);
2801 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2802 assert_eq!(path.last().unwrap().fee_msat, 250_000_000);
2805 // Check that setting outbound_capacity_msat in first_hops limits the channels.
2806 // Disable channel #1 and use another first hop.
2807 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2808 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2809 short_channel_id: 1,
2812 cltv_expiry_delta: 0,
2813 htlc_minimum_msat: 0,
2814 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2816 fee_proportional_millionths: 0,
2817 excess_data: Vec::new()
2820 // Now, limit the first_hop by the outbound_capacity_msat of 200_000 sats.
2821 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
2824 // Attempt to route more than available results in a failure.
2825 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2826 Some(InvoiceFeatures::known()), Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 200_000_001, 42, Arc::clone(&logger)) {
2827 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2828 } else { panic!(); }
2832 // Now, attempt to route an exact amount we have should be fine.
2833 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2834 Some(InvoiceFeatures::known()), Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 200_000_000, 42, Arc::clone(&logger)).unwrap();
2835 assert_eq!(route.paths.len(), 1);
2836 let path = route.paths.last().unwrap();
2837 assert_eq!(path.len(), 2);
2838 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2839 assert_eq!(path.last().unwrap().fee_msat, 200_000_000);
2842 // Enable channel #1 back.
2843 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2844 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2845 short_channel_id: 1,
2848 cltv_expiry_delta: 0,
2849 htlc_minimum_msat: 0,
2850 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2852 fee_proportional_millionths: 0,
2853 excess_data: Vec::new()
2857 // Now let's see if routing works if we know only htlc_maximum_msat.
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(15_000),
2867 fee_proportional_millionths: 0,
2868 excess_data: Vec::new()
2872 // Attempt to route more than available results in a failure.
2873 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2874 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_001, 42, Arc::clone(&logger)) {
2875 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2876 } else { panic!(); }
2880 // Now, attempt to route an exact amount we have should be fine.
2881 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2882 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_000, 42, Arc::clone(&logger)).unwrap();
2883 assert_eq!(route.paths.len(), 1);
2884 let path = route.paths.last().unwrap();
2885 assert_eq!(path.len(), 2);
2886 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2887 assert_eq!(path.last().unwrap().fee_msat, 15_000);
2890 // Now let's see if routing works if we know only capacity from the UTXO.
2892 // We can't change UTXO capacity on the fly, so we'll disable
2893 // the existing channel and add another one with the capacity we need.
2894 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2895 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2896 short_channel_id: 3,
2899 cltv_expiry_delta: 0,
2900 htlc_minimum_msat: 0,
2901 htlc_maximum_msat: OptionalField::Absent,
2903 fee_proportional_millionths: 0,
2904 excess_data: Vec::new()
2907 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
2908 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
2909 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
2910 .push_opcode(opcodes::all::OP_PUSHNUM_2)
2911 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
2913 *chain_monitor.utxo_ret.lock().unwrap() = Ok(TxOut { value: 15, script_pubkey: good_script.clone() });
2914 net_graph_msg_handler.add_chain_access(Some(chain_monitor));
2916 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
2917 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2918 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2919 short_channel_id: 333,
2922 cltv_expiry_delta: (3 << 8) | 1,
2923 htlc_minimum_msat: 0,
2924 htlc_maximum_msat: OptionalField::Absent,
2926 fee_proportional_millionths: 0,
2927 excess_data: Vec::new()
2929 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2930 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2931 short_channel_id: 333,
2934 cltv_expiry_delta: (3 << 8) | 2,
2935 htlc_minimum_msat: 0,
2936 htlc_maximum_msat: OptionalField::Absent,
2938 fee_proportional_millionths: 0,
2939 excess_data: Vec::new()
2943 // Attempt to route more than available results in a failure.
2944 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2945 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_001, 42, Arc::clone(&logger)) {
2946 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2947 } else { panic!(); }
2951 // Now, attempt to route an exact amount we have should be fine.
2952 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2953 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_000, 42, Arc::clone(&logger)).unwrap();
2954 assert_eq!(route.paths.len(), 1);
2955 let path = route.paths.last().unwrap();
2956 assert_eq!(path.len(), 2);
2957 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2958 assert_eq!(path.last().unwrap().fee_msat, 15_000);
2961 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
2962 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2963 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2964 short_channel_id: 333,
2967 cltv_expiry_delta: 0,
2968 htlc_minimum_msat: 0,
2969 htlc_maximum_msat: OptionalField::Present(10_000),
2971 fee_proportional_millionths: 0,
2972 excess_data: Vec::new()
2976 // Attempt to route more than available results in a failure.
2977 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2978 Some(InvoiceFeatures::known()), None, &Vec::new(), 10_001, 42, Arc::clone(&logger)) {
2979 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2980 } else { panic!(); }
2984 // Now, attempt to route an exact amount we have should be fine.
2985 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2986 Some(InvoiceFeatures::known()), None, &Vec::new(), 10_000, 42, Arc::clone(&logger)).unwrap();
2987 assert_eq!(route.paths.len(), 1);
2988 let path = route.paths.last().unwrap();
2989 assert_eq!(path.len(), 2);
2990 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2991 assert_eq!(path.last().unwrap().fee_msat, 10_000);
2996 fn available_liquidity_last_hop_test() {
2997 // Check that available liquidity properly limits the path even when only
2998 // one of the latter hops is limited.
2999 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3000 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3002 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3003 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
3004 // Total capacity: 50 sats.
3006 // Disable other potential paths.
3007 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3008 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3009 short_channel_id: 2,
3012 cltv_expiry_delta: 0,
3013 htlc_minimum_msat: 0,
3014 htlc_maximum_msat: OptionalField::Present(100_000),
3016 fee_proportional_millionths: 0,
3017 excess_data: Vec::new()
3019 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3020 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3021 short_channel_id: 7,
3024 cltv_expiry_delta: 0,
3025 htlc_minimum_msat: 0,
3026 htlc_maximum_msat: OptionalField::Present(100_000),
3028 fee_proportional_millionths: 0,
3029 excess_data: Vec::new()
3034 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3035 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3036 short_channel_id: 12,
3039 cltv_expiry_delta: 0,
3040 htlc_minimum_msat: 0,
3041 htlc_maximum_msat: OptionalField::Present(100_000),
3043 fee_proportional_millionths: 0,
3044 excess_data: Vec::new()
3046 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3047 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3048 short_channel_id: 13,
3051 cltv_expiry_delta: 0,
3052 htlc_minimum_msat: 0,
3053 htlc_maximum_msat: OptionalField::Present(100_000),
3055 fee_proportional_millionths: 0,
3056 excess_data: Vec::new()
3059 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3060 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3061 short_channel_id: 6,
3064 cltv_expiry_delta: 0,
3065 htlc_minimum_msat: 0,
3066 htlc_maximum_msat: OptionalField::Present(50_000),
3068 fee_proportional_millionths: 0,
3069 excess_data: Vec::new()
3071 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3072 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3073 short_channel_id: 11,
3076 cltv_expiry_delta: 0,
3077 htlc_minimum_msat: 0,
3078 htlc_maximum_msat: OptionalField::Present(100_000),
3080 fee_proportional_millionths: 0,
3081 excess_data: Vec::new()
3084 // Attempt to route more than available results in a failure.
3085 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3086 Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger)) {
3087 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3088 } else { panic!(); }
3092 // Now, attempt to route 49 sats (just a bit below the capacity).
3093 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3094 Some(InvoiceFeatures::known()), None, &Vec::new(), 49_000, 42, Arc::clone(&logger)).unwrap();
3095 assert_eq!(route.paths.len(), 1);
3096 let mut total_amount_paid_msat = 0;
3097 for path in &route.paths {
3098 assert_eq!(path.len(), 4);
3099 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3100 total_amount_paid_msat += path.last().unwrap().fee_msat;
3102 assert_eq!(total_amount_paid_msat, 49_000);
3106 // Attempt to route an exact amount is also fine
3107 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3108 Some(InvoiceFeatures::known()), None, &Vec::new(), 50_000, 42, Arc::clone(&logger)).unwrap();
3109 assert_eq!(route.paths.len(), 1);
3110 let mut total_amount_paid_msat = 0;
3111 for path in &route.paths {
3112 assert_eq!(path.len(), 4);
3113 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3114 total_amount_paid_msat += path.last().unwrap().fee_msat;
3116 assert_eq!(total_amount_paid_msat, 50_000);
3121 fn ignore_fee_first_hop_test() {
3122 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3123 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3125 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3126 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3127 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3128 short_channel_id: 1,
3131 cltv_expiry_delta: 0,
3132 htlc_minimum_msat: 0,
3133 htlc_maximum_msat: OptionalField::Present(100_000),
3134 fee_base_msat: 1_000_000,
3135 fee_proportional_millionths: 0,
3136 excess_data: Vec::new()
3138 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3139 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3140 short_channel_id: 3,
3143 cltv_expiry_delta: 0,
3144 htlc_minimum_msat: 0,
3145 htlc_maximum_msat: OptionalField::Present(50_000),
3147 fee_proportional_millionths: 0,
3148 excess_data: Vec::new()
3152 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();
3153 assert_eq!(route.paths.len(), 1);
3154 let mut total_amount_paid_msat = 0;
3155 for path in &route.paths {
3156 assert_eq!(path.len(), 2);
3157 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3158 total_amount_paid_msat += path.last().unwrap().fee_msat;
3160 assert_eq!(total_amount_paid_msat, 50_000);
3165 fn simple_mpp_route_test() {
3166 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3167 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3169 // We need a route consisting of 3 paths:
3170 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3171 // To achieve this, the amount being transferred should be around
3172 // the total capacity of these 3 paths.
3174 // First, we set limits on these (previously unlimited) channels.
3175 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
3177 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3178 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3179 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3180 short_channel_id: 1,
3183 cltv_expiry_delta: 0,
3184 htlc_minimum_msat: 0,
3185 htlc_maximum_msat: OptionalField::Present(100_000),
3187 fee_proportional_millionths: 0,
3188 excess_data: Vec::new()
3190 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3191 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3192 short_channel_id: 3,
3195 cltv_expiry_delta: 0,
3196 htlc_minimum_msat: 0,
3197 htlc_maximum_msat: OptionalField::Present(50_000),
3199 fee_proportional_millionths: 0,
3200 excess_data: Vec::new()
3203 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
3204 // (total limit 60).
3205 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3206 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3207 short_channel_id: 12,
3210 cltv_expiry_delta: 0,
3211 htlc_minimum_msat: 0,
3212 htlc_maximum_msat: OptionalField::Present(60_000),
3214 fee_proportional_millionths: 0,
3215 excess_data: Vec::new()
3217 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3218 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3219 short_channel_id: 13,
3222 cltv_expiry_delta: 0,
3223 htlc_minimum_msat: 0,
3224 htlc_maximum_msat: OptionalField::Present(60_000),
3226 fee_proportional_millionths: 0,
3227 excess_data: Vec::new()
3230 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
3231 // (total capacity 180 sats).
3232 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3233 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3234 short_channel_id: 2,
3237 cltv_expiry_delta: 0,
3238 htlc_minimum_msat: 0,
3239 htlc_maximum_msat: OptionalField::Present(200_000),
3241 fee_proportional_millionths: 0,
3242 excess_data: Vec::new()
3244 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3245 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3246 short_channel_id: 4,
3249 cltv_expiry_delta: 0,
3250 htlc_minimum_msat: 0,
3251 htlc_maximum_msat: OptionalField::Present(180_000),
3253 fee_proportional_millionths: 0,
3254 excess_data: Vec::new()
3258 // Attempt to route more than available results in a failure.
3259 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(),
3260 &nodes[2], Some(InvoiceFeatures::known()), None, &Vec::new(), 300_000, 42, Arc::clone(&logger)) {
3261 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3262 } else { panic!(); }
3266 // Now, attempt to route 250 sats (just a bit below the capacity).
3267 // Our algorithm should provide us with these 3 paths.
3268 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
3269 Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000, 42, Arc::clone(&logger)).unwrap();
3270 assert_eq!(route.paths.len(), 3);
3271 let mut total_amount_paid_msat = 0;
3272 for path in &route.paths {
3273 assert_eq!(path.len(), 2);
3274 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3275 total_amount_paid_msat += path.last().unwrap().fee_msat;
3277 assert_eq!(total_amount_paid_msat, 250_000);
3281 // Attempt to route an exact amount is also fine
3282 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
3283 Some(InvoiceFeatures::known()), None, &Vec::new(), 290_000, 42, Arc::clone(&logger)).unwrap();
3284 assert_eq!(route.paths.len(), 3);
3285 let mut total_amount_paid_msat = 0;
3286 for path in &route.paths {
3287 assert_eq!(path.len(), 2);
3288 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3289 total_amount_paid_msat += path.last().unwrap().fee_msat;
3291 assert_eq!(total_amount_paid_msat, 290_000);
3296 fn long_mpp_route_test() {
3297 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3298 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3300 // We need a route consisting of 3 paths:
3301 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3302 // Note that these paths overlap (channels 5, 12, 13).
3303 // We will route 300 sats.
3304 // Each path will have 100 sats capacity, those channels which
3305 // are used twice will have 200 sats capacity.
3307 // Disable other potential paths.
3308 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3309 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3310 short_channel_id: 2,
3313 cltv_expiry_delta: 0,
3314 htlc_minimum_msat: 0,
3315 htlc_maximum_msat: OptionalField::Present(100_000),
3317 fee_proportional_millionths: 0,
3318 excess_data: Vec::new()
3320 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3321 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3322 short_channel_id: 7,
3325 cltv_expiry_delta: 0,
3326 htlc_minimum_msat: 0,
3327 htlc_maximum_msat: OptionalField::Present(100_000),
3329 fee_proportional_millionths: 0,
3330 excess_data: Vec::new()
3333 // Path via {node0, node2} is channels {1, 3, 5}.
3334 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3335 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3336 short_channel_id: 1,
3339 cltv_expiry_delta: 0,
3340 htlc_minimum_msat: 0,
3341 htlc_maximum_msat: OptionalField::Present(100_000),
3343 fee_proportional_millionths: 0,
3344 excess_data: Vec::new()
3346 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3347 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3348 short_channel_id: 3,
3351 cltv_expiry_delta: 0,
3352 htlc_minimum_msat: 0,
3353 htlc_maximum_msat: OptionalField::Present(100_000),
3355 fee_proportional_millionths: 0,
3356 excess_data: Vec::new()
3359 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3360 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3361 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3362 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3363 short_channel_id: 5,
3366 cltv_expiry_delta: 0,
3367 htlc_minimum_msat: 0,
3368 htlc_maximum_msat: OptionalField::Present(200_000),
3370 fee_proportional_millionths: 0,
3371 excess_data: Vec::new()
3374 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3375 // Add 100 sats to the capacities of {12, 13}, because these channels
3376 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3377 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3378 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3379 short_channel_id: 12,
3382 cltv_expiry_delta: 0,
3383 htlc_minimum_msat: 0,
3384 htlc_maximum_msat: OptionalField::Present(200_000),
3386 fee_proportional_millionths: 0,
3387 excess_data: Vec::new()
3389 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3390 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3391 short_channel_id: 13,
3394 cltv_expiry_delta: 0,
3395 htlc_minimum_msat: 0,
3396 htlc_maximum_msat: OptionalField::Present(200_000),
3398 fee_proportional_millionths: 0,
3399 excess_data: Vec::new()
3402 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3403 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3404 short_channel_id: 6,
3407 cltv_expiry_delta: 0,
3408 htlc_minimum_msat: 0,
3409 htlc_maximum_msat: OptionalField::Present(100_000),
3411 fee_proportional_millionths: 0,
3412 excess_data: Vec::new()
3414 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3415 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3416 short_channel_id: 11,
3419 cltv_expiry_delta: 0,
3420 htlc_minimum_msat: 0,
3421 htlc_maximum_msat: OptionalField::Present(100_000),
3423 fee_proportional_millionths: 0,
3424 excess_data: Vec::new()
3427 // Path via {node7, node2} is channels {12, 13, 5}.
3428 // We already limited them to 200 sats (they are used twice for 100 sats).
3429 // Nothing to do here.
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(), 350_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 300 sats (exact amount we can route).
3441 // Our algorithm should provide us with these 3 paths, 100 sats each.
3442 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3443 Some(InvoiceFeatures::known()), None, &Vec::new(), 300_000, 42, Arc::clone(&logger)).unwrap();
3444 assert_eq!(route.paths.len(), 3);
3446 let mut total_amount_paid_msat = 0;
3447 for path in &route.paths {
3448 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3449 total_amount_paid_msat += path.last().unwrap().fee_msat;
3451 assert_eq!(total_amount_paid_msat, 300_000);
3457 fn mpp_cheaper_route_test() {
3458 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3459 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3461 // This test checks that if we have two cheaper paths and one more expensive path,
3462 // so that liquidity-wise any 2 of 3 combination is sufficient,
3463 // two cheaper paths will be taken.
3464 // These paths have equal available liquidity.
3466 // We need a combination of 3 paths:
3467 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3468 // Note that these paths overlap (channels 5, 12, 13).
3469 // Each path will have 100 sats capacity, those channels which
3470 // are used twice will have 200 sats capacity.
3472 // Disable other potential paths.
3473 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3474 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3475 short_channel_id: 2,
3478 cltv_expiry_delta: 0,
3479 htlc_minimum_msat: 0,
3480 htlc_maximum_msat: OptionalField::Present(100_000),
3482 fee_proportional_millionths: 0,
3483 excess_data: Vec::new()
3485 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3486 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3487 short_channel_id: 7,
3490 cltv_expiry_delta: 0,
3491 htlc_minimum_msat: 0,
3492 htlc_maximum_msat: OptionalField::Present(100_000),
3494 fee_proportional_millionths: 0,
3495 excess_data: Vec::new()
3498 // Path via {node0, node2} is channels {1, 3, 5}.
3499 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3500 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3501 short_channel_id: 1,
3504 cltv_expiry_delta: 0,
3505 htlc_minimum_msat: 0,
3506 htlc_maximum_msat: OptionalField::Present(100_000),
3508 fee_proportional_millionths: 0,
3509 excess_data: Vec::new()
3511 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3512 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3513 short_channel_id: 3,
3516 cltv_expiry_delta: 0,
3517 htlc_minimum_msat: 0,
3518 htlc_maximum_msat: OptionalField::Present(100_000),
3520 fee_proportional_millionths: 0,
3521 excess_data: Vec::new()
3524 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3525 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3526 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3527 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3528 short_channel_id: 5,
3531 cltv_expiry_delta: 0,
3532 htlc_minimum_msat: 0,
3533 htlc_maximum_msat: OptionalField::Present(200_000),
3535 fee_proportional_millionths: 0,
3536 excess_data: Vec::new()
3539 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3540 // Add 100 sats to the capacities of {12, 13}, because these channels
3541 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3542 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3543 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3544 short_channel_id: 12,
3547 cltv_expiry_delta: 0,
3548 htlc_minimum_msat: 0,
3549 htlc_maximum_msat: OptionalField::Present(200_000),
3551 fee_proportional_millionths: 0,
3552 excess_data: Vec::new()
3554 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3555 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3556 short_channel_id: 13,
3559 cltv_expiry_delta: 0,
3560 htlc_minimum_msat: 0,
3561 htlc_maximum_msat: OptionalField::Present(200_000),
3563 fee_proportional_millionths: 0,
3564 excess_data: Vec::new()
3567 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3568 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3569 short_channel_id: 6,
3572 cltv_expiry_delta: 0,
3573 htlc_minimum_msat: 0,
3574 htlc_maximum_msat: OptionalField::Present(100_000),
3575 fee_base_msat: 1_000,
3576 fee_proportional_millionths: 0,
3577 excess_data: Vec::new()
3579 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3580 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3581 short_channel_id: 11,
3584 cltv_expiry_delta: 0,
3585 htlc_minimum_msat: 0,
3586 htlc_maximum_msat: OptionalField::Present(100_000),
3588 fee_proportional_millionths: 0,
3589 excess_data: Vec::new()
3592 // Path via {node7, node2} is channels {12, 13, 5}.
3593 // We already limited them to 200 sats (they are used twice for 100 sats).
3594 // Nothing to do here.
3597 // Now, attempt to route 180 sats.
3598 // Our algorithm should provide us with these 2 paths.
3599 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3600 Some(InvoiceFeatures::known()), None, &Vec::new(), 180_000, 42, Arc::clone(&logger)).unwrap();
3601 assert_eq!(route.paths.len(), 2);
3603 let mut total_value_transferred_msat = 0;
3604 let mut total_paid_msat = 0;
3605 for path in &route.paths {
3606 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3607 total_value_transferred_msat += path.last().unwrap().fee_msat;
3609 total_paid_msat += hop.fee_msat;
3612 // If we paid fee, this would be higher.
3613 assert_eq!(total_value_transferred_msat, 180_000);
3614 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
3615 assert_eq!(total_fees_paid, 0);
3620 fn fees_on_mpp_route_test() {
3621 // This test makes sure that MPP algorithm properly takes into account
3622 // fees charged on the channels, by making the fees impactful:
3623 // if the fee is not properly accounted for, the behavior is different.
3624 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3625 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3627 // We need a route consisting of 2 paths:
3628 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
3629 // We will route 200 sats, Each path will have 100 sats capacity.
3631 // This test is not particularly stable: e.g.,
3632 // there's a way to route via {node0, node2, node4}.
3633 // It works while pathfinding is deterministic, but can be broken otherwise.
3634 // It's fine to ignore this concern for now.
3636 // Disable other potential paths.
3637 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3638 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3639 short_channel_id: 2,
3642 cltv_expiry_delta: 0,
3643 htlc_minimum_msat: 0,
3644 htlc_maximum_msat: OptionalField::Present(100_000),
3646 fee_proportional_millionths: 0,
3647 excess_data: Vec::new()
3650 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3651 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3652 short_channel_id: 7,
3655 cltv_expiry_delta: 0,
3656 htlc_minimum_msat: 0,
3657 htlc_maximum_msat: OptionalField::Present(100_000),
3659 fee_proportional_millionths: 0,
3660 excess_data: Vec::new()
3663 // Path via {node0, node2} is channels {1, 3, 5}.
3664 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3665 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3666 short_channel_id: 1,
3669 cltv_expiry_delta: 0,
3670 htlc_minimum_msat: 0,
3671 htlc_maximum_msat: OptionalField::Present(100_000),
3673 fee_proportional_millionths: 0,
3674 excess_data: Vec::new()
3676 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3677 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3678 short_channel_id: 3,
3681 cltv_expiry_delta: 0,
3682 htlc_minimum_msat: 0,
3683 htlc_maximum_msat: OptionalField::Present(100_000),
3685 fee_proportional_millionths: 0,
3686 excess_data: Vec::new()
3689 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3690 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3691 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3692 short_channel_id: 5,
3695 cltv_expiry_delta: 0,
3696 htlc_minimum_msat: 0,
3697 htlc_maximum_msat: OptionalField::Present(100_000),
3699 fee_proportional_millionths: 0,
3700 excess_data: Vec::new()
3703 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3704 // All channels should be 100 sats capacity. But for the fee experiment,
3705 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
3706 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
3707 // 100 sats (and pay 150 sats in fees for the use of channel 6),
3708 // so no matter how large are other channels,
3709 // the whole path will be limited by 100 sats with just these 2 conditions:
3710 // - channel 12 capacity is 250 sats
3711 // - fee for channel 6 is 150 sats
3712 // Let's test this by enforcing these 2 conditions and removing other limits.
3713 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3714 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3715 short_channel_id: 12,
3718 cltv_expiry_delta: 0,
3719 htlc_minimum_msat: 0,
3720 htlc_maximum_msat: OptionalField::Present(250_000),
3722 fee_proportional_millionths: 0,
3723 excess_data: Vec::new()
3725 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3726 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3727 short_channel_id: 13,
3730 cltv_expiry_delta: 0,
3731 htlc_minimum_msat: 0,
3732 htlc_maximum_msat: OptionalField::Absent,
3734 fee_proportional_millionths: 0,
3735 excess_data: Vec::new()
3738 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3739 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3740 short_channel_id: 6,
3743 cltv_expiry_delta: 0,
3744 htlc_minimum_msat: 0,
3745 htlc_maximum_msat: OptionalField::Absent,
3746 fee_base_msat: 150_000,
3747 fee_proportional_millionths: 0,
3748 excess_data: Vec::new()
3750 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3751 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3752 short_channel_id: 11,
3755 cltv_expiry_delta: 0,
3756 htlc_minimum_msat: 0,
3757 htlc_maximum_msat: OptionalField::Absent,
3759 fee_proportional_millionths: 0,
3760 excess_data: Vec::new()
3764 // Attempt to route more than available results in a failure.
3765 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3766 Some(InvoiceFeatures::known()), None, &Vec::new(), 210_000, 42, Arc::clone(&logger)) {
3767 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3768 } else { panic!(); }
3772 // Now, attempt to route 200 sats (exact amount we can route).
3773 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3774 Some(InvoiceFeatures::known()), None, &Vec::new(), 200_000, 42, Arc::clone(&logger)).unwrap();
3775 assert_eq!(route.paths.len(), 2);
3777 let mut total_amount_paid_msat = 0;
3778 for path in &route.paths {
3779 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3780 total_amount_paid_msat += path.last().unwrap().fee_msat;
3782 assert_eq!(total_amount_paid_msat, 200_000);
3788 fn drop_lowest_channel_mpp_route_test() {
3789 // This test checks that low-capacity channel is dropped when after
3790 // path finding we realize that we found more capacity than we need.
3791 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3792 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3794 // We need a route consisting of 3 paths:
3795 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3797 // The first and the second paths should be sufficient, but the third should be
3798 // cheaper, so that we select it but drop later.
3800 // First, we set limits on these (previously unlimited) channels.
3801 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
3803 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
3804 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3805 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3806 short_channel_id: 1,
3809 cltv_expiry_delta: 0,
3810 htlc_minimum_msat: 0,
3811 htlc_maximum_msat: OptionalField::Present(100_000),
3813 fee_proportional_millionths: 0,
3814 excess_data: Vec::new()
3816 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3817 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3818 short_channel_id: 3,
3821 cltv_expiry_delta: 0,
3822 htlc_minimum_msat: 0,
3823 htlc_maximum_msat: OptionalField::Present(50_000),
3825 fee_proportional_millionths: 0,
3826 excess_data: Vec::new()
3829 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
3830 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3831 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3832 short_channel_id: 12,
3835 cltv_expiry_delta: 0,
3836 htlc_minimum_msat: 0,
3837 htlc_maximum_msat: OptionalField::Present(60_000),
3839 fee_proportional_millionths: 0,
3840 excess_data: Vec::new()
3842 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3843 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3844 short_channel_id: 13,
3847 cltv_expiry_delta: 0,
3848 htlc_minimum_msat: 0,
3849 htlc_maximum_msat: OptionalField::Present(60_000),
3851 fee_proportional_millionths: 0,
3852 excess_data: Vec::new()
3855 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
3856 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3857 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3858 short_channel_id: 2,
3861 cltv_expiry_delta: 0,
3862 htlc_minimum_msat: 0,
3863 htlc_maximum_msat: OptionalField::Present(20_000),
3865 fee_proportional_millionths: 0,
3866 excess_data: Vec::new()
3868 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3869 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3870 short_channel_id: 4,
3873 cltv_expiry_delta: 0,
3874 htlc_minimum_msat: 0,
3875 htlc_maximum_msat: OptionalField::Present(20_000),
3877 fee_proportional_millionths: 0,
3878 excess_data: Vec::new()
3882 // Attempt to route more than available results in a failure.
3883 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
3884 Some(InvoiceFeatures::known()), None, &Vec::new(), 150_000, 42, Arc::clone(&logger)) {
3885 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3886 } else { panic!(); }
3890 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
3891 // Our algorithm should provide us with these 3 paths.
3892 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
3893 Some(InvoiceFeatures::known()), None, &Vec::new(), 125_000, 42, Arc::clone(&logger)).unwrap();
3894 assert_eq!(route.paths.len(), 3);
3895 let mut total_amount_paid_msat = 0;
3896 for path in &route.paths {
3897 assert_eq!(path.len(), 2);
3898 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3899 total_amount_paid_msat += path.last().unwrap().fee_msat;
3901 assert_eq!(total_amount_paid_msat, 125_000);
3905 // Attempt to route without the last small cheap channel
3906 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
3907 Some(InvoiceFeatures::known()), None, &Vec::new(), 90_000, 42, Arc::clone(&logger)).unwrap();
3908 assert_eq!(route.paths.len(), 2);
3909 let mut total_amount_paid_msat = 0;
3910 for path in &route.paths {
3911 assert_eq!(path.len(), 2);
3912 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3913 total_amount_paid_msat += path.last().unwrap().fee_msat;
3915 assert_eq!(total_amount_paid_msat, 90_000);
3920 fn min_criteria_consistency() {
3921 // Test that we don't use an inconsistent metric between updating and walking nodes during
3922 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
3923 // was updated with a different criterion from the heap sorting, resulting in loops in
3924 // calculated paths. We test for that specific case here.
3926 // We construct a network that looks like this:
3928 // node2 -1(3)2- node3
3932 // node1 -1(5)2- node4 -1(1)2- node6
3938 // We create a loop on the side of our real path - our destination is node 6, with a
3939 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
3940 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
3941 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
3942 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
3943 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
3944 // "previous hop" being set to node 3, creating a loop in the path.
3945 let secp_ctx = Secp256k1::new();
3946 let logger = Arc::new(test_utils::TestLogger::new());
3947 let net_graph_msg_handler = NetGraphMsgHandler::new(genesis_block(Network::Testnet).header.block_hash(), None, Arc::clone(&logger));
3948 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3950 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
3951 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3952 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3953 short_channel_id: 6,
3956 cltv_expiry_delta: (6 << 8) | 0,
3957 htlc_minimum_msat: 0,
3958 htlc_maximum_msat: OptionalField::Absent,
3960 fee_proportional_millionths: 0,
3961 excess_data: Vec::new()
3963 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
3965 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3966 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3967 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3968 short_channel_id: 5,
3971 cltv_expiry_delta: (5 << 8) | 0,
3972 htlc_minimum_msat: 0,
3973 htlc_maximum_msat: OptionalField::Absent,
3975 fee_proportional_millionths: 0,
3976 excess_data: Vec::new()
3978 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
3980 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
3981 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3982 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3983 short_channel_id: 4,
3986 cltv_expiry_delta: (4 << 8) | 0,
3987 htlc_minimum_msat: 0,
3988 htlc_maximum_msat: OptionalField::Absent,
3990 fee_proportional_millionths: 0,
3991 excess_data: Vec::new()
3993 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
3995 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
3996 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
3997 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3998 short_channel_id: 3,
4001 cltv_expiry_delta: (3 << 8) | 0,
4002 htlc_minimum_msat: 0,
4003 htlc_maximum_msat: OptionalField::Absent,
4005 fee_proportional_millionths: 0,
4006 excess_data: Vec::new()
4008 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
4010 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
4011 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4012 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4013 short_channel_id: 2,
4016 cltv_expiry_delta: (2 << 8) | 0,
4017 htlc_minimum_msat: 0,
4018 htlc_maximum_msat: OptionalField::Absent,
4020 fee_proportional_millionths: 0,
4021 excess_data: Vec::new()
4024 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
4025 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4026 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4027 short_channel_id: 1,
4030 cltv_expiry_delta: (1 << 8) | 0,
4031 htlc_minimum_msat: 100,
4032 htlc_maximum_msat: OptionalField::Absent,
4034 fee_proportional_millionths: 0,
4035 excess_data: Vec::new()
4037 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
4040 // Now ensure the route flows simply over nodes 1 and 4 to 6.
4041 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();
4042 assert_eq!(route.paths.len(), 1);
4043 assert_eq!(route.paths[0].len(), 3);
4045 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
4046 assert_eq!(route.paths[0][0].short_channel_id, 6);
4047 assert_eq!(route.paths[0][0].fee_msat, 100);
4048 assert_eq!(route.paths[0][0].cltv_expiry_delta, (5 << 8) | 0);
4049 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(1));
4050 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(6));
4052 assert_eq!(route.paths[0][1].pubkey, nodes[4]);
4053 assert_eq!(route.paths[0][1].short_channel_id, 5);
4054 assert_eq!(route.paths[0][1].fee_msat, 0);
4055 assert_eq!(route.paths[0][1].cltv_expiry_delta, (1 << 8) | 0);
4056 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(4));
4057 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(5));
4059 assert_eq!(route.paths[0][2].pubkey, nodes[6]);
4060 assert_eq!(route.paths[0][2].short_channel_id, 1);
4061 assert_eq!(route.paths[0][2].fee_msat, 10_000);
4062 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
4063 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
4064 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(1));
4070 fn exact_fee_liquidity_limit() {
4071 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
4072 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
4073 // we calculated fees on a higher value, resulting in us ignoring such paths.
4074 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
4075 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
4077 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
4079 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4080 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4081 short_channel_id: 2,
4084 cltv_expiry_delta: 0,
4085 htlc_minimum_msat: 0,
4086 htlc_maximum_msat: OptionalField::Present(85_000),
4088 fee_proportional_millionths: 0,
4089 excess_data: Vec::new()
4092 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4093 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4094 short_channel_id: 12,
4097 cltv_expiry_delta: (4 << 8) | 1,
4098 htlc_minimum_msat: 0,
4099 htlc_maximum_msat: OptionalField::Present(270_000),
4101 fee_proportional_millionths: 1000000,
4102 excess_data: Vec::new()
4106 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
4107 // 200% fee charged channel 13 in the 1-to-2 direction.
4108 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();
4109 assert_eq!(route.paths.len(), 1);
4110 assert_eq!(route.paths[0].len(), 2);
4112 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4113 assert_eq!(route.paths[0][0].short_channel_id, 12);
4114 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4115 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
4116 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4117 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4119 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4120 assert_eq!(route.paths[0][1].short_channel_id, 13);
4121 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4122 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4123 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
4124 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4129 fn htlc_max_reduction_below_min() {
4130 // Test that if, while walking the graph, we reduce the value being sent to meet an
4131 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
4132 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
4133 // resulting in us thinking there is no possible path, even if other paths exist.
4134 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
4135 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4137 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
4138 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
4139 // then try to send 90_000.
4140 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4141 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4142 short_channel_id: 2,
4145 cltv_expiry_delta: 0,
4146 htlc_minimum_msat: 0,
4147 htlc_maximum_msat: OptionalField::Present(80_000),
4149 fee_proportional_millionths: 0,
4150 excess_data: Vec::new()
4152 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4153 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4154 short_channel_id: 4,
4157 cltv_expiry_delta: (4 << 8) | 1,
4158 htlc_minimum_msat: 90_000,
4159 htlc_maximum_msat: OptionalField::Absent,
4161 fee_proportional_millionths: 0,
4162 excess_data: Vec::new()
4166 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
4167 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
4168 // expensive) channels 12-13 path.
4169 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();
4170 assert_eq!(route.paths.len(), 1);
4171 assert_eq!(route.paths[0].len(), 2);
4173 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4174 assert_eq!(route.paths[0][0].short_channel_id, 12);
4175 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4176 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
4177 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4178 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4180 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4181 assert_eq!(route.paths[0][1].short_channel_id, 13);
4182 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4183 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4184 assert_eq!(route.paths[0][1].node_features.le_flags(), InvoiceFeatures::known().le_flags());
4185 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4189 #[cfg(not(feature = "no-std"))]
4190 pub(super) fn random_init_seed() -> u64 {
4191 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
4192 use core::hash::{BuildHasher, Hasher};
4193 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
4194 println!("Using seed of {}", seed);
4197 #[cfg(not(feature = "no-std"))]
4198 use util::ser::Readable;
4201 #[cfg(not(feature = "no-std"))]
4202 fn generate_routes() {
4203 let mut d = match super::test_utils::get_route_file() {
4210 let graph = NetworkGraph::read(&mut d).unwrap();
4212 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4213 let mut seed = random_init_seed() as usize;
4214 'load_endpoints: for _ in 0..10 {
4216 seed = seed.overflowing_mul(0xdeadbeef).0;
4217 let src = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
4218 seed = seed.overflowing_mul(0xdeadbeef).0;
4219 let dst = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
4220 let amt = seed as u64 % 200_000_000;
4221 if get_route(src, &graph, dst, None, None, &[], amt, 42, &test_utils::TestLogger::new()).is_ok() {
4222 continue 'load_endpoints;
4229 #[cfg(not(feature = "no-std"))]
4230 fn generate_routes_mpp() {
4231 let mut d = match super::test_utils::get_route_file() {
4238 let graph = NetworkGraph::read(&mut d).unwrap();
4240 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4241 let mut seed = random_init_seed() as usize;
4242 'load_endpoints: for _ in 0..10 {
4244 seed = seed.overflowing_mul(0xdeadbeef).0;
4245 let src = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
4246 seed = seed.overflowing_mul(0xdeadbeef).0;
4247 let dst = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
4248 let amt = seed as u64 % 200_000_000;
4249 if get_route(src, &graph, dst, Some(InvoiceFeatures::known()), None, &[], amt, 42, &test_utils::TestLogger::new()).is_ok() {
4250 continue 'load_endpoints;
4257 #[cfg(all(test, not(feature = "no-std")))]
4258 pub(crate) mod test_utils {
4260 /// Tries to open a network graph file, or panics with a URL to fetch it.
4261 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
4262 let res = File::open("net_graph-2021-05-31.bin") // By default we're run in RL/lightning
4263 .or_else(|_| File::open("lightning/net_graph-2021-05-31.bin")) // We may be run manually in RL/
4264 .or_else(|_| { // Fall back to guessing based on the binary location
4265 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
4266 let mut path = std::env::current_exe().unwrap();
4267 path.pop(); // lightning-...
4269 path.pop(); // debug
4270 path.pop(); // target
4271 path.push("lightning");
4272 path.push("net_graph-2021-05-31.bin");
4273 eprintln!("{}", path.to_str().unwrap());
4276 .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");
4277 #[cfg(require_route_graph_test)]
4278 return Ok(res.unwrap());
4279 #[cfg(not(require_route_graph_test))]
4284 #[cfg(all(test, feature = "unstable", not(feature = "no-std")))]
4287 use util::logger::{Logger, Record};
4291 struct DummyLogger {}
4292 impl Logger for DummyLogger {
4293 fn log(&self, _record: &Record) {}
4297 fn generate_routes(bench: &mut Bencher) {
4298 let mut d = test_utils::get_route_file().unwrap();
4299 let graph = NetworkGraph::read(&mut d).unwrap();
4301 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4302 let mut path_endpoints = Vec::new();
4303 let mut seed: usize = 0xdeadbeef;
4304 'load_endpoints: for _ in 0..100 {
4307 let src = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
4309 let dst = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
4310 let amt = seed as u64 % 1_000_000;
4311 if get_route(src, &graph, dst, None, None, &[], amt, 42, &DummyLogger{}).is_ok() {
4312 path_endpoints.push((src, dst, amt));
4313 continue 'load_endpoints;
4318 // ...then benchmark finding paths between the nodes we learned.
4321 let (src, dst, amt) = path_endpoints[idx % path_endpoints.len()];
4322 assert!(get_route(src, &graph, dst, None, None, &[], amt, 42, &DummyLogger{}).is_ok());
4328 fn generate_mpp_routes(bench: &mut Bencher) {
4329 let mut d = test_utils::get_route_file().unwrap();
4330 let graph = NetworkGraph::read(&mut d).unwrap();
4332 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4333 let mut path_endpoints = Vec::new();
4334 let mut seed: usize = 0xdeadbeef;
4335 'load_endpoints: for _ in 0..100 {
4338 let src = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
4340 let dst = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
4341 let amt = seed as u64 % 1_000_000;
4342 if get_route(src, &graph, dst, Some(InvoiceFeatures::known()), None, &[], amt, 42, &DummyLogger{}).is_ok() {
4343 path_endpoints.push((src, dst, amt));
4344 continue 'load_endpoints;
4349 // ...then benchmark finding paths between the nodes we learned.
4352 let (src, dst, amt) = path_endpoints[idx % path_endpoints.len()];
4353 assert!(get_route(src, &graph, dst, Some(InvoiceFeatures::known()), None, &[], amt, 42, &DummyLogger{}).is_ok());