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};
21 use routing::network_graph::{NetworkGraph, NodeId, RoutingFees};
22 use util::ser::{Writeable, Readable};
23 use util::logger::{Level, Logger};
27 use alloc::collections::BinaryHeap;
32 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
34 /// The node_id of the node at this hop.
35 pub pubkey: PublicKey,
36 /// The node_announcement features of the node at this hop. For the last hop, these may be
37 /// amended to match the features present in the invoice this node generated.
38 pub node_features: NodeFeatures,
39 /// The channel that should be used from the previous hop to reach this node.
40 pub short_channel_id: u64,
41 /// The channel_announcement features of the channel that should be used from the previous hop
42 /// to reach this node.
43 pub channel_features: ChannelFeatures,
44 /// The fee taken on this hop (for paying for the use of the *next* channel in the path).
45 /// For the last hop, this should be the full value of the payment (might be more than
46 /// requested if we had to match htlc_minimum_msat).
48 /// The CLTV delta added for this hop. For the last hop, this should be the full CLTV value
49 /// expected at the destination, in excess of the current block height.
50 pub cltv_expiry_delta: u32,
53 impl_writeable_tlv_based!(RouteHop, {
54 (0, pubkey, required),
55 (2, node_features, required),
56 (4, short_channel_id, required),
57 (6, channel_features, required),
58 (8, fee_msat, required),
59 (10, cltv_expiry_delta, required),
62 /// A route directs a payment from the sender (us) to the recipient. If the recipient supports MPP,
63 /// it can take multiple paths. Each path is composed of one or more hops through the network.
64 #[derive(Clone, Hash, PartialEq, Eq)]
66 /// The list of routes taken for a single (potentially-)multi-part payment. The pubkey of the
67 /// last RouteHop in each path must be the same.
68 /// Each entry represents a list of hops, NOT INCLUDING our own, where the last hop is the
69 /// destination. Thus, this must always be at least length one. While the maximum length of any
70 /// given path is variable, keeping the length of any path to less than 20 should currently
71 /// ensure it is viable.
72 pub paths: Vec<Vec<RouteHop>>,
76 /// Returns the total amount of fees paid on this [`Route`].
78 /// This doesn't include any extra payment made to the recipient, which can happen in excess of
79 /// the amount passed to [`get_route`]'s `final_value_msat`.
80 pub fn get_total_fees(&self) -> u64 {
81 // Do not count last hop of each path since that's the full value of the payment
82 return self.paths.iter()
83 .flat_map(|path| path.split_last().map(|(_, path_prefix)| path_prefix).unwrap_or(&[]))
84 .map(|hop| &hop.fee_msat)
88 /// Returns the total amount paid on this [`Route`], excluding the fees.
89 pub fn get_total_amount(&self) -> u64 {
90 return self.paths.iter()
91 .map(|path| path.split_last().map(|(hop, _)| hop.fee_msat).unwrap_or(0))
96 const SERIALIZATION_VERSION: u8 = 1;
97 const MIN_SERIALIZATION_VERSION: u8 = 1;
99 impl Writeable for Route {
100 fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
101 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
102 (self.paths.len() as u64).write(writer)?;
103 for hops in self.paths.iter() {
104 (hops.len() as u8).write(writer)?;
105 for hop in hops.iter() {
109 write_tlv_fields!(writer, {});
114 impl Readable for Route {
115 fn read<R: io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
116 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
117 let path_count: u64 = Readable::read(reader)?;
118 let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
119 for _ in 0..path_count {
120 let hop_count: u8 = Readable::read(reader)?;
121 let mut hops = Vec::with_capacity(hop_count as usize);
122 for _ in 0..hop_count {
123 hops.push(Readable::read(reader)?);
127 read_tlv_fields!(reader, {});
132 /// A list of hops along a payment path terminating with a channel to the recipient.
133 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
134 pub struct RouteHint(pub Vec<RouteHintHop>);
136 /// A channel descriptor for a hop along a payment path.
137 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
138 pub struct RouteHintHop {
139 /// The node_id of the non-target end of the route
140 pub src_node_id: PublicKey,
141 /// The short_channel_id of this channel
142 pub short_channel_id: u64,
143 /// The fees which must be paid to use this channel
144 pub fees: RoutingFees,
145 /// The difference in CLTV values between this node and the next node.
146 pub cltv_expiry_delta: u16,
147 /// The minimum value, in msat, which must be relayed to the next hop.
148 pub htlc_minimum_msat: Option<u64>,
149 /// The maximum value in msat available for routing with a single HTLC.
150 pub htlc_maximum_msat: Option<u64>,
153 #[derive(Eq, PartialEq)]
154 struct RouteGraphNode {
156 lowest_fee_to_peer_through_node: u64,
157 lowest_fee_to_node: u64,
158 // The maximum value a yet-to-be-constructed payment path might flow through this node.
159 // This value is upper-bounded by us by:
160 // - how much is needed for a path being constructed
161 // - how much value can channels following this node (up to the destination) can contribute,
162 // considering their capacity and fees
163 value_contribution_msat: u64,
164 /// The effective htlc_minimum_msat at this hop. If a later hop on the path had a higher HTLC
165 /// minimum, we use it, plus the fees required at each earlier hop to meet it.
166 path_htlc_minimum_msat: u64,
167 /// All penalties incurred from this hop on the way to the destination, as calculated using
169 path_penalty_msat: u64,
172 impl cmp::Ord for RouteGraphNode {
173 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
174 let other_score = cmp::max(other.lowest_fee_to_peer_through_node, other.path_htlc_minimum_msat)
175 .checked_add(other.path_penalty_msat)
176 .unwrap_or_else(|| u64::max_value());
177 let self_score = cmp::max(self.lowest_fee_to_peer_through_node, self.path_htlc_minimum_msat)
178 .checked_add(self.path_penalty_msat)
179 .unwrap_or_else(|| u64::max_value());
180 other_score.cmp(&self_score).then_with(|| other.node_id.cmp(&self.node_id))
184 impl cmp::PartialOrd for RouteGraphNode {
185 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
186 Some(self.cmp(other))
190 struct DummyDirectionalChannelInfo {
191 cltv_expiry_delta: u32,
192 htlc_minimum_msat: u64,
193 htlc_maximum_msat: Option<u64>,
197 /// It's useful to keep track of the hops associated with the fees required to use them,
198 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
199 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
200 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
201 #[derive(Clone, Debug)]
202 struct PathBuildingHop<'a> {
203 // The RouteHintHop fields which will eventually be used if this hop is used in a final Route.
204 // Note that node_features is calculated separately after our initial graph walk.
206 short_channel_id: u64,
207 channel_features: &'a ChannelFeatures,
209 cltv_expiry_delta: u32,
211 /// Minimal fees required to route to the source node of the current hop via any of its inbound channels.
212 src_lowest_inbound_fees: RoutingFees,
213 /// Fees of the channel used in this hop.
214 channel_fees: RoutingFees,
215 /// All the fees paid *after* this channel on the way to the destination
216 next_hops_fee_msat: u64,
217 /// Fee paid for the use of the current channel (see channel_fees).
218 /// The value will be actually deducted from the counterparty balance on the previous link.
219 hop_use_fee_msat: u64,
220 /// Used to compare channels when choosing the for routing.
221 /// Includes paying for the use of a hop and the following hops, as well as
222 /// an estimated cost of reaching this hop.
223 /// Might get stale when fees are recomputed. Primarily for internal use.
225 /// This is useful for update_value_and_recompute_fees to make sure
226 /// we don't fall below the minimum. Should not be updated manually and
227 /// generally should not be accessed.
228 htlc_minimum_msat: u64,
229 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
230 /// walk and may be invalid thereafter.
231 path_htlc_minimum_msat: u64,
232 /// All penalties incurred from this channel on the way to the destination, as calculated using
234 path_penalty_msat: u64,
235 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
236 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
237 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
238 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
239 /// avoid processing them again.
241 #[cfg(any(test, feature = "fuzztarget"))]
242 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
243 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
244 // value_contribution_msat, which requires tracking it here. See comments below where it is
245 // used for more info.
246 value_contribution_msat: u64,
249 // Instantiated with a list of hops with correct data in them collected during path finding,
250 // an instance of this struct should be further modified only via given methods.
252 struct PaymentPath<'a> {
253 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
256 impl<'a> PaymentPath<'a> {
257 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
258 fn get_value_msat(&self) -> u64 {
259 self.hops.last().unwrap().0.fee_msat
262 fn get_total_fee_paid_msat(&self) -> u64 {
263 if self.hops.len() < 1 {
267 // Can't use next_hops_fee_msat because it gets outdated.
268 for (i, (hop, _)) in self.hops.iter().enumerate() {
269 if i != self.hops.len() - 1 {
270 result += hop.fee_msat;
276 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
277 // to change fees may result in an inconsistency.
279 // Sometimes we call this function right after constructing a path which is inconsistent in
280 // that it the value being transferred has decreased while we were doing path finding, leading
281 // to the fees being paid not lining up with the actual limits.
283 // Note that this function is not aware of the available_liquidity limit, and thus does not
284 // support increasing the value being transferred.
285 fn update_value_and_recompute_fees(&mut self, value_msat: u64) {
286 assert!(value_msat <= self.hops.last().unwrap().0.fee_msat);
288 let mut total_fee_paid_msat = 0 as u64;
289 for i in (0..self.hops.len()).rev() {
290 let last_hop = i == self.hops.len() - 1;
292 // For non-last-hop, this value will represent the fees paid on the current hop. It
293 // will consist of the fees for the use of the next hop, and extra fees to match
294 // htlc_minimum_msat of the current channel. Last hop is handled separately.
295 let mut cur_hop_fees_msat = 0;
297 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
300 let mut cur_hop = &mut self.hops.get_mut(i).unwrap().0;
301 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
302 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
303 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
304 // set it too high just to maliciously take more fees by exploiting this
305 // match htlc_minimum_msat logic.
306 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
307 if let Some(extra_fees_msat) = cur_hop.htlc_minimum_msat.checked_sub(cur_hop_transferred_amount_msat) {
308 // Note that there is a risk that *previous hops* (those closer to us, as we go
309 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
311 // This might make us end up with a broken route, although this should be super-rare
312 // in practice, both because of how healthy channels look like, and how we pick
313 // channels in add_entry.
314 // Also, this can't be exploited more heavily than *announce a free path and fail
316 cur_hop_transferred_amount_msat += extra_fees_msat;
317 total_fee_paid_msat += extra_fees_msat;
318 cur_hop_fees_msat += extra_fees_msat;
322 // Final hop is a special case: it usually has just value_msat (by design), but also
323 // it still could overpay for the htlc_minimum_msat.
324 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
326 // Propagate updated fees for the use of the channels to one hop back, where they
327 // will be actually paid (fee_msat). The last hop is handled above separately.
328 cur_hop.fee_msat = cur_hop_fees_msat;
331 // Fee for the use of the current hop which will be deducted on the previous hop.
332 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
333 // this channel is free for us.
335 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.channel_fees) {
336 cur_hop.hop_use_fee_msat = new_fee;
337 total_fee_paid_msat += new_fee;
339 // It should not be possible because this function is called only to reduce the
340 // value. In that case, compute_fee was already called with the same fees for
341 // larger amount and there was no overflow.
349 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
350 let proportional_fee_millions =
351 amount_msat.checked_mul(channel_fees.proportional_millionths as u64);
352 if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
353 (channel_fees.base_msat as u64).checked_add(part / 1_000_000) }) {
357 // This function may be (indirectly) called without any verification,
358 // with channel_fees provided by a caller. We should handle it gracefully.
363 /// Gets a keysend route from us (payer) to the given target node (payee). This is needed because
364 /// keysend payments do not have an invoice from which to pull the payee's supported features, which
365 /// makes it tricky to otherwise supply the `payee_features` parameter of `get_route`.
366 pub fn get_keysend_route<L: Deref, S: routing::Score>(
367 our_node_pubkey: &PublicKey, network: &NetworkGraph, payee: &PublicKey,
368 first_hops: Option<&[&ChannelDetails]>, last_hops: &[&RouteHint], final_value_msat: u64,
369 final_cltv: u32, logger: L, scorer: &S
370 ) -> Result<Route, LightningError>
371 where L::Target: Logger {
372 let invoice_features = InvoiceFeatures::for_keysend();
374 our_node_pubkey, network, payee, Some(invoice_features), first_hops, last_hops,
375 final_value_msat, final_cltv, logger, scorer
379 /// Gets a route from us (payer) to the given target node (payee).
381 /// If the payee provided features in their invoice, they should be provided via payee_features.
382 /// Without this, MPP will only be used if the payee's features are available in the network graph.
384 /// Private routing paths between a public node and the target may be included in `last_hops`.
385 /// Currently, only the last hop in each path is considered.
387 /// If some channels aren't announced, it may be useful to fill in a first_hops with the
388 /// results from a local ChannelManager::list_usable_channels() call. If it is filled in, our
389 /// view of our local channels (from net_graph_msg_handler) will be ignored, and only those
390 /// in first_hops will be used.
392 /// Panics if first_hops contains channels without short_channel_ids
393 /// (ChannelManager::list_usable_channels will never include such channels).
395 /// The fees on channels from us to next-hops are ignored (as they are assumed to all be
396 /// equal), however the enabled/disabled bit on such channels as well as the
397 /// htlc_minimum_msat/htlc_maximum_msat *are* checked as they may change based on the receiving node.
398 pub fn get_route<L: Deref, S: routing::Score>(
399 our_node_pubkey: &PublicKey, network: &NetworkGraph, payee: &PublicKey,
400 payee_features: Option<InvoiceFeatures>, first_hops: Option<&[&ChannelDetails]>,
401 last_hops: &[&RouteHint], final_value_msat: u64, final_cltv: u32, logger: L, scorer: &S
402 ) -> Result<Route, LightningError>
403 where L::Target: Logger {
404 let payee_node_id = NodeId::from_pubkey(&payee);
405 let our_node_id = NodeId::from_pubkey(&our_node_pubkey);
407 if payee_node_id == our_node_id {
408 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
411 if final_value_msat > MAX_VALUE_MSAT {
412 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
415 if final_value_msat == 0 {
416 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
419 for route in last_hops.iter() {
420 for hop in &route.0 {
421 if hop.src_node_id == *payee {
422 return Err(LightningError{err: "Last hop cannot have a payee as a source.".to_owned(), action: ErrorAction::IgnoreError});
427 // The general routing idea is the following:
428 // 1. Fill first/last hops communicated by the caller.
429 // 2. Attempt to construct a path from payer to payee for transferring
430 // any ~sufficient (described later) value.
431 // If succeed, remember which channels were used and how much liquidity they have available,
432 // so that future paths don't rely on the same liquidity.
433 // 3. Prooceed to the next step if:
434 // - we hit the recommended target value;
435 // - OR if we could not construct a new path. Any next attempt will fail too.
436 // Otherwise, repeat step 2.
437 // 4. See if we managed to collect paths which aggregately are able to transfer target value
438 // (not recommended value). If yes, proceed. If not, fail routing.
439 // 5. Randomly combine paths into routes having enough to fulfill the payment. (TODO: knapsack)
440 // 6. Of all the found paths, select only those with the lowest total fee.
441 // 7. The last path in every selected route is likely to be more than we need.
442 // Reduce its value-to-transfer and recompute fees.
443 // 8. Choose the best route by the lowest total fee.
445 // As for the actual search algorithm,
446 // we do a payee-to-payer pseudo-Dijkstra's sorting by each node's distance from the payee
447 // plus the minimum per-HTLC fee to get from it to another node (aka "shitty pseudo-A*").
449 // We are not a faithful Dijkstra's implementation because we can change values which impact
450 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
451 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) then
452 // the value we are currently attempting to send over a path, we simply reduce the value being
453 // sent along the path for any hops after that channel. This may imply that later fees (which
454 // we've already tabulated) are lower because a smaller value is passing through the channels
455 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
456 // channels which were selected earlier (and which may still be used for other paths without a
457 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
460 // One potentially problematic case for this algorithm would be if there are many
461 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
462 // graph walking), we may never find a path which is not liquidity-limited and has lower
463 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
464 // Because we only consider paths with at least 5% of the total value being sent, the damage
465 // from such a case should be limited, however this could be further reduced in the future by
466 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
467 // limits for the purposes of fee calculation.
469 // Alternatively, we could store more detailed path information in the heap (targets, below)
470 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
471 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
472 // and practically (as we would need to store dynamically-allocated path information in heap
473 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
474 // results of such an algorithm would likely be biased towards lower-value paths.
476 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
477 // outside of our current search value, running a path search more times to gather candidate
478 // paths at different values. While this may be acceptable, further path searches may increase
479 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
480 // graph for candidate paths, calculating the maximum value which can realistically be sent at
481 // the same time, remaining generic across different payment values.
483 // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
484 // to use as the A* heuristic beyond just the cost to get one node further than the current
487 let network_graph = network.read_only();
488 let network_channels = network_graph.channels();
489 let network_nodes = network_graph.nodes();
490 let dummy_directional_info = DummyDirectionalChannelInfo { // used for first_hops routes
491 cltv_expiry_delta: 0,
492 htlc_minimum_msat: 0,
493 htlc_maximum_msat: None,
496 proportional_millionths: 0,
500 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
501 // it. If the payee supports it they're supposed to include it in the invoice, so that should
503 let allow_mpp = if let Some(features) = &payee_features {
504 features.supports_basic_mpp()
505 } else if let Some(node) = network_nodes.get(&payee_node_id) {
506 if let Some(node_info) = node.announcement_info.as_ref() {
507 node_info.features.supports_basic_mpp()
510 log_trace!(logger, "Searching for a route from payer {} to payee {} {} MPP", our_node_pubkey, payee,
511 if allow_mpp { "with" } else { "without" });
514 // Prepare the data we'll use for payee-to-payer search by
515 // inserting first hops suggested by the caller as targets.
516 // Our search will then attempt to reach them while traversing from the payee node.
517 let mut first_hop_targets: HashMap<_, Vec<(_, ChannelFeatures, _, NodeFeatures)>> =
518 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
519 if let Some(hops) = first_hops {
521 let short_channel_id = chan.short_channel_id.expect("first_hops should be filled in with usable channels, not pending ones");
522 if chan.counterparty.node_id == *our_node_pubkey {
523 return Err(LightningError{err: "First hop cannot have our_node_pubkey as a destination.".to_owned(), action: ErrorAction::IgnoreError});
525 first_hop_targets.entry(NodeId::from_pubkey(&chan.counterparty.node_id)).or_insert(Vec::new())
526 .push((short_channel_id, chan.counterparty.features.to_context(), chan.outbound_capacity_msat, chan.counterparty.features.to_context()));
528 if first_hop_targets.is_empty() {
529 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
533 let empty_channel_features = ChannelFeatures::empty();
535 // The main heap containing all candidate next-hops sorted by their score (max(A* fee,
536 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
537 // adding duplicate entries when we find a better path to a given node.
538 let mut targets = BinaryHeap::new();
540 // Map from node_id to information about the best current path to that node, including feerate
542 let mut dist = HashMap::with_capacity(network_nodes.len());
544 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
545 // indicating that we may wish to try again with a higher value, potentially paying to meet an
546 // htlc_minimum with extra fees while still finding a cheaper path.
547 let mut hit_minimum_limit;
549 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
550 // We start with a path_value of the exact amount we want, and if that generates a route we may
551 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
552 // amount we want in total across paths, selecting the best subset at the end.
553 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
554 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
555 let mut path_value_msat = final_value_msat;
557 // We don't want multiple paths (as per MPP) share liquidity of the same channels.
558 // This map allows paths to be aware of the channel use by other paths in the same call.
559 // This would help to make a better path finding decisions and not "overbook" channels.
560 // It is unaware of the directions (except for `outbound_capacity_msat` in `first_hops`).
561 let mut bookkeeped_channels_liquidity_available_msat = HashMap::with_capacity(network_nodes.len());
563 // Keeping track of how much value we already collected across other paths. Helps to decide:
564 // - how much a new path should be transferring (upper bound);
565 // - whether a channel should be disregarded because
566 // it's available liquidity is too small comparing to how much more we need to collect;
567 // - when we want to stop looking for new paths.
568 let mut already_collected_value_msat = 0;
570 log_trace!(logger, "Building path from {} (payee) to {} (us/payer) for value {} msat.", payee, our_node_pubkey, final_value_msat);
572 macro_rules! add_entry {
573 // Adds entry which goes from $src_node_id to $dest_node_id
574 // over the channel with id $chan_id with fees described in
575 // $directional_info.
576 // $next_hops_fee_msat represents the fees paid for using all the channel *after* this one,
577 // since that value has to be transferred over this channel.
578 // Returns whether this channel caused an update to `targets`.
579 ( $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,
580 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr, $next_hops_path_penalty_msat: expr ) => { {
581 // We "return" whether we updated the path at the end, via this:
582 let mut did_add_update_path_to_src_node = false;
583 // Channels to self should not be used. This is more of belt-and-suspenders, because in
584 // practice these cases should be caught earlier:
585 // - for regular channels at channel announcement (TODO)
586 // - for first and last hops early in get_route
587 if $src_node_id != $dest_node_id.clone() {
588 let available_liquidity_msat = bookkeeped_channels_liquidity_available_msat.entry($chan_id.clone()).or_insert_with(|| {
589 let mut initial_liquidity_available_msat = None;
590 if let Some(capacity_sats) = $capacity_sats {
591 initial_liquidity_available_msat = Some(capacity_sats * 1000);
594 if let Some(htlc_maximum_msat) = $directional_info.htlc_maximum_msat {
595 if let Some(available_msat) = initial_liquidity_available_msat {
596 initial_liquidity_available_msat = Some(cmp::min(available_msat, htlc_maximum_msat));
598 initial_liquidity_available_msat = Some(htlc_maximum_msat);
602 match initial_liquidity_available_msat {
603 Some(available_msat) => available_msat,
604 // We assume channels with unknown balance have
605 // a capacity of 0.0025 BTC (or 250_000 sats).
606 None => 250_000 * 1000
610 // It is tricky to substract $next_hops_fee_msat from available liquidity here.
611 // It may be misleading because we might later choose to reduce the value transferred
612 // over these channels, and the channel which was insufficient might become sufficient.
613 // Worst case: we drop a good channel here because it can't cover the high following
614 // fees caused by one expensive channel, but then this channel could have been used
615 // if the amount being transferred over this path is lower.
616 // We do this for now, but this is a subject for removal.
617 if let Some(available_value_contribution_msat) = available_liquidity_msat.checked_sub($next_hops_fee_msat) {
619 // Routing Fragmentation Mitigation heuristic:
621 // Routing fragmentation across many payment paths increases the overall routing
622 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
623 // Taking too many smaller paths also increases the chance of payment failure.
624 // Thus to avoid this effect, we require from our collected links to provide
625 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
627 // This requirement is currently 5% of the remaining-to-be-collected value.
628 // This means as we successfully advance in our collection,
629 // the absolute liquidity contribution is lowered,
630 // thus increasing the number of potential channels to be selected.
632 // Derive the minimal liquidity contribution with a ratio of 20 (5%, rounded up)
633 // or 100% if we're not allowed to do multipath payments.
634 let minimal_value_contribution_msat: u64 = if allow_mpp {
635 (recommended_value_msat - already_collected_value_msat + 19) / 20
639 // Verify the liquidity offered by this channel complies to the minimal contribution.
640 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
642 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
643 // Includes paying fees for the use of the following channels.
644 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
645 Some(result) => result,
646 // Can't overflow due to how the values were computed right above.
647 None => unreachable!(),
649 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
650 let over_path_minimum_msat = amount_to_transfer_over_msat >= $directional_info.htlc_minimum_msat &&
651 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
653 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
654 // bother considering this channel.
655 // Since we're choosing amount_to_transfer_over_msat as maximum possible, it can
656 // be only reduced later (not increased), so this channel should just be skipped
657 // as not sufficient.
658 if !over_path_minimum_msat {
659 hit_minimum_limit = true;
660 } else if contributes_sufficient_value {
661 // Note that low contribution here (limited by available_liquidity_msat)
662 // might violate htlc_minimum_msat on the hops which are next along the
663 // payment path (upstream to the payee). To avoid that, we recompute path
664 // path fees knowing the final path contribution after constructing it.
665 let path_htlc_minimum_msat = compute_fees($next_hops_path_htlc_minimum_msat, $directional_info.fees)
666 .and_then(|fee_msat| fee_msat.checked_add($next_hops_path_htlc_minimum_msat))
667 .map(|fee_msat| cmp::max(fee_msat, $directional_info.htlc_minimum_msat))
668 .unwrap_or_else(|| u64::max_value());
669 let hm_entry = dist.entry($src_node_id);
670 let old_entry = hm_entry.or_insert_with(|| {
671 // If there was previously no known way to access
672 // the source node (recall it goes payee-to-payer) of $chan_id, first add
673 // a semi-dummy record just to compute the fees to reach the source node.
674 // This will affect our decision on selecting $chan_id
675 // as a way to reach the $dest_node_id.
676 let mut fee_base_msat = u32::max_value();
677 let mut fee_proportional_millionths = u32::max_value();
678 if let Some(Some(fees)) = network_nodes.get(&$src_node_id).map(|node| node.lowest_inbound_channel_fees) {
679 fee_base_msat = fees.base_msat;
680 fee_proportional_millionths = fees.proportional_millionths;
683 node_id: $dest_node_id.clone(),
685 channel_features: $chan_features,
687 cltv_expiry_delta: 0,
688 src_lowest_inbound_fees: RoutingFees {
689 base_msat: fee_base_msat,
690 proportional_millionths: fee_proportional_millionths,
692 channel_fees: $directional_info.fees,
693 next_hops_fee_msat: u64::max_value(),
694 hop_use_fee_msat: u64::max_value(),
695 total_fee_msat: u64::max_value(),
696 htlc_minimum_msat: $directional_info.htlc_minimum_msat,
697 path_htlc_minimum_msat,
698 path_penalty_msat: u64::max_value(),
699 was_processed: false,
700 #[cfg(any(test, feature = "fuzztarget"))]
701 value_contribution_msat,
705 #[allow(unused_mut)] // We only use the mut in cfg(test)
706 let mut should_process = !old_entry.was_processed;
707 #[cfg(any(test, feature = "fuzztarget"))]
709 // In test/fuzzing builds, we do extra checks to make sure the skipping
710 // of already-seen nodes only happens in cases we expect (see below).
711 if !should_process { should_process = true; }
715 let mut hop_use_fee_msat = 0;
716 let mut total_fee_msat = $next_hops_fee_msat;
718 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
719 // will have the same effective-fee
720 if $src_node_id != our_node_id {
721 match compute_fees(amount_to_transfer_over_msat, $directional_info.fees) {
722 // max_value means we'll always fail
723 // the old_entry.total_fee_msat > total_fee_msat check
724 None => total_fee_msat = u64::max_value(),
726 hop_use_fee_msat = fee_msat;
727 total_fee_msat += hop_use_fee_msat;
728 // When calculating the lowest inbound fees to a node, we
729 // calculate fees here not based on the actual value we think
730 // will flow over this channel, but on the minimum value that
731 // we'll accept flowing over it. The minimum accepted value
732 // is a constant through each path collection run, ensuring
733 // consistent basis. Otherwise we may later find a
734 // different path to the source node that is more expensive,
735 // but which we consider to be cheaper because we are capacity
736 // constrained and the relative fee becomes lower.
737 match compute_fees(minimal_value_contribution_msat, old_entry.src_lowest_inbound_fees)
738 .map(|a| a.checked_add(total_fee_msat)) {
743 total_fee_msat = u64::max_value();
750 let path_penalty_msat = $next_hops_path_penalty_msat
751 .checked_add(scorer.channel_penalty_msat($chan_id.clone()))
752 .unwrap_or_else(|| u64::max_value());
753 let new_graph_node = RouteGraphNode {
754 node_id: $src_node_id,
755 lowest_fee_to_peer_through_node: total_fee_msat,
756 lowest_fee_to_node: $next_hops_fee_msat as u64 + hop_use_fee_msat,
757 value_contribution_msat: value_contribution_msat,
758 path_htlc_minimum_msat,
762 // Update the way of reaching $src_node_id with the given $chan_id (from $dest_node_id),
763 // if this way is cheaper than the already known
764 // (considering the cost to "reach" this channel from the route destination,
765 // the cost of using this channel,
766 // and the cost of routing to the source node of this channel).
767 // Also, consider that htlc_minimum_msat_difference, because we might end up
768 // paying it. Consider the following exploit:
769 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
770 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
771 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
772 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
774 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
775 // but it may require additional tracking - we don't want to double-count
776 // the fees included in $next_hops_path_htlc_minimum_msat, but also
777 // can't use something that may decrease on future hops.
778 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat)
779 .checked_add(old_entry.path_penalty_msat)
780 .unwrap_or_else(|| u64::max_value());
781 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat)
782 .checked_add(path_penalty_msat)
783 .unwrap_or_else(|| u64::max_value());
785 if !old_entry.was_processed && new_cost < old_cost {
786 targets.push(new_graph_node);
787 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
788 old_entry.hop_use_fee_msat = hop_use_fee_msat;
789 old_entry.total_fee_msat = total_fee_msat;
790 old_entry.node_id = $dest_node_id.clone();
791 old_entry.short_channel_id = $chan_id.clone();
792 old_entry.channel_features = $chan_features;
793 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
794 old_entry.cltv_expiry_delta = $directional_info.cltv_expiry_delta as u32;
795 old_entry.channel_fees = $directional_info.fees;
796 old_entry.htlc_minimum_msat = $directional_info.htlc_minimum_msat;
797 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
798 old_entry.path_penalty_msat = path_penalty_msat;
799 #[cfg(any(test, feature = "fuzztarget"))]
801 old_entry.value_contribution_msat = value_contribution_msat;
803 did_add_update_path_to_src_node = true;
804 } else if old_entry.was_processed && new_cost < old_cost {
805 #[cfg(any(test, feature = "fuzztarget"))]
807 // If we're skipping processing a node which was previously
808 // processed even though we found another path to it with a
809 // cheaper fee, check that it was because the second path we
810 // found (which we are processing now) has a lower value
811 // contribution due to an HTLC minimum limit.
813 // e.g. take a graph with two paths from node 1 to node 2, one
814 // through channel A, and one through channel B. Channel A and
815 // B are both in the to-process heap, with their scores set by
816 // a higher htlc_minimum than fee.
817 // Channel A is processed first, and the channels onwards from
818 // node 1 are added to the to-process heap. Thereafter, we pop
819 // Channel B off of the heap, note that it has a much more
820 // restrictive htlc_maximum_msat, and recalculate the fees for
821 // all of node 1's channels using the new, reduced, amount.
823 // This would be bogus - we'd be selecting a higher-fee path
824 // with a lower htlc_maximum_msat instead of the one we'd
825 // already decided to use.
826 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
828 value_contribution_msat + path_penalty_msat <
829 old_entry.value_contribution_msat + old_entry.path_penalty_msat
837 did_add_update_path_to_src_node
841 let empty_node_features = NodeFeatures::empty();
842 // Find ways (channels with destination) to reach a given node and store them
843 // in the corresponding data structures (routing graph etc).
844 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
845 // meaning how much will be paid in fees after this node (to the best of our knowledge).
846 // This data can later be helpful to optimize routing (pay lower fees).
847 macro_rules! add_entries_to_cheapest_to_target_node {
848 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr, $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr, $next_hops_path_penalty_msat: expr ) => {
849 let skip_node = if let Some(elem) = dist.get_mut(&$node_id) {
850 let was_processed = elem.was_processed;
851 elem.was_processed = true;
854 // Entries are added to dist in add_entry!() when there is a channel from a node.
855 // Because there are no channels from payee, it will not have a dist entry at this point.
856 // If we're processing any other node, it is always be the result of a channel from it.
857 assert_eq!($node_id, payee_node_id);
862 if let Some(first_channels) = first_hop_targets.get(&$node_id) {
863 for (ref first_hop, ref features, ref outbound_capacity_msat, _) in first_channels {
864 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, $next_hops_path_penalty_msat);
868 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
874 if !features.requires_unknown_bits() {
875 for chan_id in $node.channels.iter() {
876 let chan = network_channels.get(chan_id).unwrap();
877 if !chan.features.requires_unknown_bits() {
878 if chan.node_one == $node_id {
879 // ie $node is one, ie next hop in A* is two, via the two_to_one channel
880 if first_hops.is_none() || chan.node_two != our_node_id {
881 if let Some(two_to_one) = chan.two_to_one.as_ref() {
882 if two_to_one.enabled {
883 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, $next_hops_path_penalty_msat);
888 if first_hops.is_none() || chan.node_one != our_node_id{
889 if let Some(one_to_two) = chan.one_to_two.as_ref() {
890 if one_to_two.enabled {
891 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, $next_hops_path_penalty_msat);
903 let mut payment_paths = Vec::<PaymentPath>::new();
905 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
906 'paths_collection: loop {
907 // For every new path, start from scratch, except
908 // bookkeeped_channels_liquidity_available_msat, which will improve
909 // the further iterations of path finding. Also don't erase first_hop_targets.
912 hit_minimum_limit = false;
914 // If first hop is a private channel and the only way to reach the payee, this is the only
915 // place where it could be added.
916 if let Some(first_channels) = first_hop_targets.get(&payee_node_id) {
917 for (ref first_hop, ref features, ref outbound_capacity_msat, _) in first_channels {
918 let added = add_entry!(first_hop, our_node_id, payee_node_id, dummy_directional_info, Some(outbound_capacity_msat / 1000), features, 0, path_value_msat, 0, 0u64);
919 log_trace!(logger, "{} direct route to payee via SCID {}", if added { "Added" } else { "Skipped" }, first_hop);
923 // Add the payee as a target, so that the payee-to-payer
924 // search algorithm knows what to start with.
925 match network_nodes.get(&payee_node_id) {
926 // The payee is not in our network graph, so nothing to add here.
927 // There is still a chance of reaching them via last_hops though,
928 // so don't yet fail the payment here.
929 // If not, targets.pop() will not even let us enter the loop in step 2.
932 add_entries_to_cheapest_to_target_node!(node, payee_node_id, 0, path_value_msat, 0, 0u64);
937 // If a caller provided us with last hops, add them to routing targets. Since this happens
938 // earlier than general path finding, they will be somewhat prioritized, although currently
939 // it matters only if the fees are exactly the same.
940 for route in last_hops.iter().filter(|route| !route.0.is_empty()) {
941 let first_hop_in_route = &(route.0)[0];
942 let have_hop_src_in_graph =
943 // Only add the hops in this route to our candidate set if either
944 // we have a direct channel to the first hop or the first hop is
945 // in the regular network graph.
946 first_hop_targets.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some() ||
947 network_nodes.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some();
948 if have_hop_src_in_graph {
949 // We start building the path from reverse, i.e., from payee
950 // to the first RouteHintHop in the path.
951 let hop_iter = route.0.iter().rev();
952 let prev_hop_iter = core::iter::once(payee).chain(
953 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
954 let mut hop_used = true;
955 let mut aggregate_next_hops_fee_msat: u64 = 0;
956 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
957 let mut aggregate_next_hops_path_penalty_msat: u64 = 0;
959 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
960 // BOLT 11 doesn't allow inclusion of features for the last hop hints, which
961 // really sucks, cause we're gonna need that eventually.
962 let hop_htlc_minimum_msat: u64 = hop.htlc_minimum_msat.unwrap_or(0);
964 let directional_info = DummyDirectionalChannelInfo {
965 cltv_expiry_delta: hop.cltv_expiry_delta as u32,
966 htlc_minimum_msat: hop_htlc_minimum_msat,
967 htlc_maximum_msat: hop.htlc_maximum_msat,
971 let reqd_channel_cap = if let Some (val) = final_value_msat.checked_add(match idx {
973 _ => aggregate_next_hops_fee_msat.checked_add(999).unwrap_or(u64::max_value())
974 }) { Some( val / 1000 ) } else { break; }; // converting from msat or breaking if max ~ infinity
976 aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
977 .checked_add(scorer.channel_penalty_msat(hop.short_channel_id))
978 .unwrap_or_else(|| u64::max_value());
980 // We assume that the recipient only included route hints for routes which had
981 // sufficient value to route `final_value_msat`. Note that in the case of "0-value"
982 // invoices where the invoice does not specify value this may not be the case, but
983 // better to include the hints than not.
984 if !add_entry!(hop.short_channel_id, NodeId::from_pubkey(&hop.src_node_id), NodeId::from_pubkey(&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, aggregate_next_hops_path_penalty_msat) {
985 // If this hop was not used then there is no use checking the preceding hops
986 // in the RouteHint. We can break by just searching for a direct channel between
987 // last checked hop and first_hop_targets
991 // Searching for a direct channel between last checked hop and first_hop_targets
992 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&prev_hop_id)) {
993 for (ref first_hop, ref features, ref outbound_capacity_msat, _) in first_channels {
994 add_entry!(first_hop, our_node_id , NodeId::from_pubkey(&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, aggregate_next_hops_path_penalty_msat);
1002 // In the next values of the iterator, the aggregate fees already reflects
1003 // the sum of value sent from payer (final_value_msat) and routing fees
1004 // for the last node in the RouteHint. We need to just add the fees to
1005 // route through the current node so that the preceeding node (next iteration)
1007 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
1008 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
1009 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
1011 let hop_htlc_minimum_msat_inc = if let Some(val) = compute_fees(aggregate_next_hops_path_htlc_minimum_msat, hop.fees) { val } else { break; };
1012 let hops_path_htlc_minimum = aggregate_next_hops_path_htlc_minimum_msat
1013 .checked_add(hop_htlc_minimum_msat_inc);
1014 aggregate_next_hops_path_htlc_minimum_msat = if let Some(val) = hops_path_htlc_minimum { cmp::max(hop_htlc_minimum_msat, val) } else { break; };
1016 if idx == route.0.len() - 1 {
1017 // The last hop in this iterator is the first hop in
1018 // overall RouteHint.
1019 // If this hop connects to a node with which we have a direct channel,
1020 // ignore the network graph and, if the last hop was added, add our
1021 // direct channel to the candidate set.
1023 // Note that we *must* check if the last hop was added as `add_entry`
1024 // always assumes that the third argument is a node to which we have a
1026 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&hop.src_node_id)) {
1027 for (ref first_hop, ref features, ref outbound_capacity_msat, _) in first_channels {
1028 add_entry!(first_hop, our_node_id , NodeId::from_pubkey(&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, aggregate_next_hops_path_penalty_msat);
1036 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
1038 // At this point, targets are filled with the data from first and
1039 // last hops communicated by the caller, and the payment receiver.
1040 let mut found_new_path = false;
1043 // If this loop terminates due the exhaustion of targets, two situations are possible:
1044 // - not enough outgoing liquidity:
1045 // 0 < already_collected_value_msat < final_value_msat
1046 // - enough outgoing liquidity:
1047 // final_value_msat <= already_collected_value_msat < recommended_value_msat
1048 // Both these cases (and other cases except reaching recommended_value_msat) mean that
1049 // paths_collection will be stopped because found_new_path==false.
1050 // This is not necessarily a routing failure.
1051 'path_construction: while let Some(RouteGraphNode { node_id, lowest_fee_to_node, value_contribution_msat, path_htlc_minimum_msat, path_penalty_msat, .. }) = targets.pop() {
1053 // Since we're going payee-to-payer, hitting our node as a target means we should stop
1054 // traversing the graph and arrange the path out of what we found.
1055 if node_id == our_node_id {
1056 let mut new_entry = dist.remove(&our_node_id).unwrap();
1057 let mut ordered_hops = vec!((new_entry.clone(), NodeFeatures::empty()));
1060 let mut features_set = false;
1061 if let Some(first_channels) = first_hop_targets.get(&ordered_hops.last().unwrap().0.node_id) {
1062 for (scid, _, _, ref features) in first_channels {
1063 if *scid == ordered_hops.last().unwrap().0.short_channel_id {
1064 ordered_hops.last_mut().unwrap().1 = features.clone();
1065 features_set = true;
1071 if let Some(node) = network_nodes.get(&ordered_hops.last().unwrap().0.node_id) {
1072 if let Some(node_info) = node.announcement_info.as_ref() {
1073 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
1075 ordered_hops.last_mut().unwrap().1 = NodeFeatures::empty();
1078 // We should be able to fill in features for everything except the last
1079 // hop, if the last hop was provided via a BOLT 11 invoice (though we
1080 // should be able to extend it further as BOLT 11 does have feature
1081 // flags for the last hop node itself).
1082 assert!(ordered_hops.last().unwrap().0.node_id == payee_node_id);
1086 // Means we succesfully traversed from the payer to the payee, now
1087 // save this path for the payment route. Also, update the liquidity
1088 // remaining on the used hops, so that we take them into account
1089 // while looking for more paths.
1090 if ordered_hops.last().unwrap().0.node_id == payee_node_id {
1094 new_entry = match dist.remove(&ordered_hops.last().unwrap().0.node_id) {
1095 Some(payment_hop) => payment_hop,
1096 // We can't arrive at None because, if we ever add an entry to targets,
1097 // we also fill in the entry in dist (see add_entry!).
1098 None => unreachable!(),
1100 // We "propagate" the fees one hop backward (topologically) here,
1101 // so that fees paid for a HTLC forwarding on the current channel are
1102 // associated with the previous channel (where they will be subtracted).
1103 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
1104 ordered_hops.last_mut().unwrap().0.cltv_expiry_delta = new_entry.cltv_expiry_delta;
1105 ordered_hops.push((new_entry.clone(), NodeFeatures::empty()));
1107 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
1108 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
1109 ordered_hops.last_mut().unwrap().0.cltv_expiry_delta = final_cltv;
1111 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: {:?}",
1112 ordered_hops.len(), value_contribution_msat, ordered_hops);
1114 let mut payment_path = PaymentPath {hops: ordered_hops};
1116 // We could have possibly constructed a slightly inconsistent path: since we reduce
1117 // value being transferred along the way, we could have violated htlc_minimum_msat
1118 // on some channels we already passed (assuming dest->source direction). Here, we
1119 // recompute the fees again, so that if that's the case, we match the currently
1120 // underpaid htlc_minimum_msat with fees.
1121 payment_path.update_value_and_recompute_fees(cmp::min(value_contribution_msat, final_value_msat));
1123 // Since a path allows to transfer as much value as
1124 // the smallest channel it has ("bottleneck"), we should recompute
1125 // the fees so sender HTLC don't overpay fees when traversing
1126 // larger channels than the bottleneck. This may happen because
1127 // when we were selecting those channels we were not aware how much value
1128 // this path will transfer, and the relative fee for them
1129 // might have been computed considering a larger value.
1130 // Remember that we used these channels so that we don't rely
1131 // on the same liquidity in future paths.
1132 let mut prevented_redundant_path_selection = false;
1133 for (payment_hop, _) in payment_path.hops.iter() {
1134 let channel_liquidity_available_msat = bookkeeped_channels_liquidity_available_msat.get_mut(&payment_hop.short_channel_id).unwrap();
1135 let mut spent_on_hop_msat = value_contribution_msat;
1136 let next_hops_fee_msat = payment_hop.next_hops_fee_msat;
1137 spent_on_hop_msat += next_hops_fee_msat;
1138 if spent_on_hop_msat == *channel_liquidity_available_msat {
1139 // If this path used all of this channel's available liquidity, we know
1140 // this path will not be selected again in the next loop iteration.
1141 prevented_redundant_path_selection = true;
1143 *channel_liquidity_available_msat -= spent_on_hop_msat;
1145 if !prevented_redundant_path_selection {
1146 // If we weren't capped by hitting a liquidity limit on a channel in the path,
1147 // we'll probably end up picking the same path again on the next iteration.
1148 // Decrease the available liquidity of a hop in the middle of the path.
1149 let victim_scid = payment_path.hops[(payment_path.hops.len() - 1) / 2].0.short_channel_id;
1150 log_trace!(logger, "Disabling channel {} for future path building iterations to avoid duplicates.", victim_scid);
1151 let victim_liquidity = bookkeeped_channels_liquidity_available_msat.get_mut(&victim_scid).unwrap();
1152 *victim_liquidity = 0;
1155 // Track the total amount all our collected paths allow to send so that we:
1156 // - know when to stop looking for more paths
1157 // - know which of the hops are useless considering how much more sats we need
1158 // (contributes_sufficient_value)
1159 already_collected_value_msat += value_contribution_msat;
1161 payment_paths.push(payment_path);
1162 found_new_path = true;
1163 break 'path_construction;
1166 // If we found a path back to the payee, we shouldn't try to process it again. This is
1167 // the equivalent of the `elem.was_processed` check in
1168 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
1169 if node_id == payee_node_id { continue 'path_construction; }
1171 // Otherwise, since the current target node is not us,
1172 // keep "unrolling" the payment graph from payee to payer by
1173 // finding a way to reach the current target from the payer side.
1174 match network_nodes.get(&node_id) {
1177 add_entries_to_cheapest_to_target_node!(node, node_id, lowest_fee_to_node, value_contribution_msat, path_htlc_minimum_msat, path_penalty_msat);
1183 // If we don't support MPP, no use trying to gather more value ever.
1184 break 'paths_collection;
1188 // Stop either when the recommended value is reached or if no new path was found in this
1190 // In the latter case, making another path finding attempt won't help,
1191 // because we deterministically terminated the search due to low liquidity.
1192 if already_collected_value_msat >= recommended_value_msat || !found_new_path {
1193 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
1194 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
1195 break 'paths_collection;
1196 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
1197 // Further, if this was our first walk of the graph, and we weren't limited by an
1198 // htlc_minimum_msat, return immediately because this path should suffice. If we were
1199 // limited by an htlc_minimum_msat value, find another path with a higher value,
1200 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
1201 // still keeping a lower total fee than this path.
1202 if !hit_minimum_limit {
1203 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
1204 break 'paths_collection;
1206 log_trace!(logger, "Collected our payment amount on the first pass, but running again to collect extra paths with a potentially higher limit.");
1207 path_value_msat = recommended_value_msat;
1212 if payment_paths.len() == 0 {
1213 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1216 if already_collected_value_msat < final_value_msat {
1217 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1220 // Sort by total fees and take the best paths.
1221 payment_paths.sort_by_key(|path| path.get_total_fee_paid_msat());
1222 if payment_paths.len() > 50 {
1223 payment_paths.truncate(50);
1226 // Draw multiple sufficient routes by randomly combining the selected paths.
1227 let mut drawn_routes = Vec::new();
1228 for i in 0..payment_paths.len() {
1229 let mut cur_route = Vec::<PaymentPath>::new();
1230 let mut aggregate_route_value_msat = 0;
1233 // TODO: real random shuffle
1234 // Currently just starts with i_th and goes up to i-1_th in a looped way.
1235 let cur_payment_paths = [&payment_paths[i..], &payment_paths[..i]].concat();
1238 for payment_path in cur_payment_paths {
1239 cur_route.push(payment_path.clone());
1240 aggregate_route_value_msat += payment_path.get_value_msat();
1241 if aggregate_route_value_msat > final_value_msat {
1242 // Last path likely overpaid. Substract it from the most expensive
1243 // (in terms of proportional fee) path in this route and recompute fees.
1244 // This might be not the most economically efficient way, but fewer paths
1245 // also makes routing more reliable.
1246 let mut overpaid_value_msat = aggregate_route_value_msat - final_value_msat;
1248 // First, drop some expensive low-value paths entirely if possible.
1249 // Sort by value so that we drop many really-low values first, since
1250 // fewer paths is better: the payment is less likely to fail.
1251 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1252 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1253 cur_route.sort_by_key(|path| path.get_value_msat());
1254 // We should make sure that at least 1 path left.
1255 let mut paths_left = cur_route.len();
1256 cur_route.retain(|path| {
1257 if paths_left == 1 {
1260 let mut keep = true;
1261 let path_value_msat = path.get_value_msat();
1262 if path_value_msat <= overpaid_value_msat {
1264 overpaid_value_msat -= path_value_msat;
1270 if overpaid_value_msat == 0 {
1274 assert!(cur_route.len() > 0);
1277 // Now, substract the overpaid value from the most-expensive path.
1278 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1279 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1280 cur_route.sort_by_key(|path| { path.hops.iter().map(|hop| hop.0.channel_fees.proportional_millionths as u64).sum::<u64>() });
1281 let expensive_payment_path = cur_route.first_mut().unwrap();
1282 // We already dropped all the small channels above, meaning all the
1283 // remaining channels are larger than remaining overpaid_value_msat.
1284 // Thus, this can't be negative.
1285 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
1286 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
1290 drawn_routes.push(cur_route);
1294 // Select the best route by lowest total fee.
1295 drawn_routes.sort_by_key(|paths| paths.iter().map(|path| path.get_total_fee_paid_msat()).sum::<u64>());
1296 let mut selected_paths = Vec::<Vec<Result<RouteHop, LightningError>>>::new();
1297 for payment_path in drawn_routes.first().unwrap() {
1298 selected_paths.push(payment_path.hops.iter().map(|(payment_hop, node_features)| {
1300 pubkey: PublicKey::from_slice(payment_hop.node_id.as_slice()).map_err(|_| LightningError{err: format!("Public key {:?} is invalid", &payment_hop.node_id), action: ErrorAction::IgnoreAndLog(Level::Trace)})?,
1301 node_features: node_features.clone(),
1302 short_channel_id: payment_hop.short_channel_id,
1303 channel_features: payment_hop.channel_features.clone(),
1304 fee_msat: payment_hop.fee_msat,
1305 cltv_expiry_delta: payment_hop.cltv_expiry_delta,
1310 if let Some(features) = &payee_features {
1311 for path in selected_paths.iter_mut() {
1312 if let Ok(route_hop) = path.last_mut().unwrap() {
1313 route_hop.node_features = features.to_context();
1318 let route = Route { paths: selected_paths.into_iter().map(|path| path.into_iter().collect()).collect::<Result<Vec<_>, _>>()? };
1319 log_info!(logger, "Got route to {}: {}", payee, log_route!(route));
1325 use routing::network_graph::{NetworkGraph, NetGraphMsgHandler};
1326 use routing::router::{get_route, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees};
1327 use routing::scorer::Scorer;
1328 use chain::transaction::OutPoint;
1329 use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
1330 use ln::msgs::{ErrorAction, LightningError, OptionalField, UnsignedChannelAnnouncement, ChannelAnnouncement, RoutingMessageHandler,
1331 NodeAnnouncement, UnsignedNodeAnnouncement, ChannelUpdate, UnsignedChannelUpdate};
1332 use ln::channelmanager;
1333 use util::test_utils;
1334 use util::ser::Writeable;
1336 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
1337 use bitcoin::hashes::Hash;
1338 use bitcoin::network::constants::Network;
1339 use bitcoin::blockdata::constants::genesis_block;
1340 use bitcoin::blockdata::script::Builder;
1341 use bitcoin::blockdata::opcodes;
1342 use bitcoin::blockdata::transaction::TxOut;
1346 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
1347 use bitcoin::secp256k1::{Secp256k1, All};
1350 use sync::{self, Arc};
1352 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
1353 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
1354 channelmanager::ChannelDetails {
1355 channel_id: [0; 32],
1356 counterparty: channelmanager::ChannelCounterparty {
1359 unspendable_punishment_reserve: 0,
1360 forwarding_info: None,
1362 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
1364 channel_value_satoshis: 0,
1366 outbound_capacity_msat,
1367 inbound_capacity_msat: 42,
1368 unspendable_punishment_reserve: None,
1369 confirmations_required: None,
1370 force_close_spend_delay: None,
1371 is_outbound: true, is_funding_locked: true,
1372 is_usable: true, is_public: true,
1376 // Using the same keys for LN and BTC ids
1378 net_graph_msg_handler: &NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1379 secp_ctx: &Secp256k1<All>, node_1_privkey: &SecretKey, node_2_privkey: &SecretKey, features: ChannelFeatures, short_channel_id: u64
1381 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1382 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1384 let unsigned_announcement = UnsignedChannelAnnouncement {
1386 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1390 bitcoin_key_1: node_id_1,
1391 bitcoin_key_2: node_id_2,
1392 excess_data: Vec::new(),
1395 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1396 let valid_announcement = ChannelAnnouncement {
1397 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1398 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1399 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1400 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1401 contents: unsigned_announcement.clone(),
1403 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1404 Ok(res) => assert!(res),
1410 net_graph_msg_handler: &NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1411 secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, update: UnsignedChannelUpdate
1413 let msghash = hash_to_message!(&Sha256dHash::hash(&update.encode()[..])[..]);
1414 let valid_channel_update = ChannelUpdate {
1415 signature: secp_ctx.sign(&msghash, node_privkey),
1416 contents: update.clone()
1419 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1420 Ok(res) => assert!(res),
1425 fn add_or_update_node(
1426 net_graph_msg_handler: &NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1427 secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, features: NodeFeatures, timestamp: u32
1429 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
1430 let unsigned_announcement = UnsignedNodeAnnouncement {
1436 addresses: Vec::new(),
1437 excess_address_data: Vec::new(),
1438 excess_data: Vec::new(),
1440 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1441 let valid_announcement = NodeAnnouncement {
1442 signature: secp_ctx.sign(&msghash, node_privkey),
1443 contents: unsigned_announcement.clone()
1446 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1452 fn get_nodes(secp_ctx: &Secp256k1<All>) -> (SecretKey, PublicKey, Vec<SecretKey>, Vec<PublicKey>) {
1453 let privkeys: Vec<SecretKey> = (2..10).map(|i| {
1454 SecretKey::from_slice(&hex::decode(format!("{:02}", i).repeat(32)).unwrap()[..]).unwrap()
1457 let pubkeys = privkeys.iter().map(|secret| PublicKey::from_secret_key(&secp_ctx, secret)).collect();
1459 let our_privkey = SecretKey::from_slice(&hex::decode("01".repeat(32)).unwrap()[..]).unwrap();
1460 let our_id = PublicKey::from_secret_key(&secp_ctx, &our_privkey);
1462 (our_privkey, our_id, privkeys, pubkeys)
1465 fn id_to_feature_flags(id: u8) -> Vec<u8> {
1466 // Set the feature flags to the id'th odd (ie non-required) feature bit so that we can
1467 // test for it later.
1468 let idx = (id - 1) * 2 + 1;
1470 vec![1 << (idx - 8*3), 0, 0, 0]
1471 } else if idx > 8*2 {
1472 vec![1 << (idx - 8*2), 0, 0]
1473 } else if idx > 8*1 {
1474 vec![1 << (idx - 8*1), 0]
1480 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>) {
1481 let secp_ctx = Secp256k1::new();
1482 let logger = Arc::new(test_utils::TestLogger::new());
1483 let chain_monitor = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1484 let network_graph = NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash());
1485 let net_graph_msg_handler = NetGraphMsgHandler::new(network_graph, None, Arc::clone(&logger));
1486 // Build network from our_id to node6:
1488 // -1(1)2- node0 -1(3)2-
1490 // our_id -1(12)2- node7 -1(13)2--- node2
1492 // -1(2)2- node1 -1(4)2-
1495 // chan1 1-to-2: disabled
1496 // chan1 2-to-1: enabled, 0 fee
1498 // chan2 1-to-2: enabled, ignored fee
1499 // chan2 2-to-1: enabled, 0 fee
1501 // chan3 1-to-2: enabled, 0 fee
1502 // chan3 2-to-1: enabled, 100 msat fee
1504 // chan4 1-to-2: enabled, 100% fee
1505 // chan4 2-to-1: enabled, 0 fee
1507 // chan12 1-to-2: enabled, ignored fee
1508 // chan12 2-to-1: enabled, 0 fee
1510 // chan13 1-to-2: enabled, 200% fee
1511 // chan13 2-to-1: enabled, 0 fee
1514 // -1(5)2- node3 -1(8)2--
1518 // node2--1(6)2- node4 -1(9)2--- node6 (not in global route map)
1520 // -1(7)2- node5 -1(10)2-
1522 // Channels 5, 8, 9 and 10 are private channels.
1524 // chan5 1-to-2: enabled, 100 msat fee
1525 // chan5 2-to-1: enabled, 0 fee
1527 // chan6 1-to-2: enabled, 0 fee
1528 // chan6 2-to-1: enabled, 0 fee
1530 // chan7 1-to-2: enabled, 100% fee
1531 // chan7 2-to-1: enabled, 0 fee
1533 // chan8 1-to-2: enabled, variable fee (0 then 1000 msat)
1534 // chan8 2-to-1: enabled, 0 fee
1536 // chan9 1-to-2: enabled, 1001 msat fee
1537 // chan9 2-to-1: enabled, 0 fee
1539 // chan10 1-to-2: enabled, 0 fee
1540 // chan10 2-to-1: enabled, 0 fee
1542 // chan11 1-to-2: enabled, 0 fee
1543 // chan11 2-to-1: enabled, 0 fee
1545 let (our_privkey, _, privkeys, _) = get_nodes(&secp_ctx);
1547 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[0], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
1548 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1549 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1550 short_channel_id: 1,
1553 cltv_expiry_delta: 0,
1554 htlc_minimum_msat: 0,
1555 htlc_maximum_msat: OptionalField::Absent,
1557 fee_proportional_millionths: 0,
1558 excess_data: Vec::new()
1561 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
1563 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
1564 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1565 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1566 short_channel_id: 2,
1569 cltv_expiry_delta: u16::max_value(),
1570 htlc_minimum_msat: 0,
1571 htlc_maximum_msat: OptionalField::Absent,
1572 fee_base_msat: u32::max_value(),
1573 fee_proportional_millionths: u32::max_value(),
1574 excess_data: Vec::new()
1576 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1577 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1578 short_channel_id: 2,
1581 cltv_expiry_delta: 0,
1582 htlc_minimum_msat: 0,
1583 htlc_maximum_msat: OptionalField::Absent,
1585 fee_proportional_millionths: 0,
1586 excess_data: Vec::new()
1589 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
1591 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[7], ChannelFeatures::from_le_bytes(id_to_feature_flags(12)), 12);
1592 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1593 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1594 short_channel_id: 12,
1597 cltv_expiry_delta: u16::max_value(),
1598 htlc_minimum_msat: 0,
1599 htlc_maximum_msat: OptionalField::Absent,
1600 fee_base_msat: u32::max_value(),
1601 fee_proportional_millionths: u32::max_value(),
1602 excess_data: Vec::new()
1604 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1605 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1606 short_channel_id: 12,
1609 cltv_expiry_delta: 0,
1610 htlc_minimum_msat: 0,
1611 htlc_maximum_msat: OptionalField::Absent,
1613 fee_proportional_millionths: 0,
1614 excess_data: Vec::new()
1617 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], NodeFeatures::from_le_bytes(id_to_feature_flags(8)), 0);
1619 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
1620 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1621 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1622 short_channel_id: 3,
1625 cltv_expiry_delta: (3 << 8) | 1,
1626 htlc_minimum_msat: 0,
1627 htlc_maximum_msat: OptionalField::Absent,
1629 fee_proportional_millionths: 0,
1630 excess_data: Vec::new()
1632 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1633 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1634 short_channel_id: 3,
1637 cltv_expiry_delta: (3 << 8) | 2,
1638 htlc_minimum_msat: 0,
1639 htlc_maximum_msat: OptionalField::Absent,
1641 fee_proportional_millionths: 0,
1642 excess_data: Vec::new()
1645 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
1646 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1647 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1648 short_channel_id: 4,
1651 cltv_expiry_delta: (4 << 8) | 1,
1652 htlc_minimum_msat: 0,
1653 htlc_maximum_msat: OptionalField::Absent,
1655 fee_proportional_millionths: 1000000,
1656 excess_data: Vec::new()
1658 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1659 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1660 short_channel_id: 4,
1663 cltv_expiry_delta: (4 << 8) | 2,
1664 htlc_minimum_msat: 0,
1665 htlc_maximum_msat: OptionalField::Absent,
1667 fee_proportional_millionths: 0,
1668 excess_data: Vec::new()
1671 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(13)), 13);
1672 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1673 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1674 short_channel_id: 13,
1677 cltv_expiry_delta: (13 << 8) | 1,
1678 htlc_minimum_msat: 0,
1679 htlc_maximum_msat: OptionalField::Absent,
1681 fee_proportional_millionths: 2000000,
1682 excess_data: Vec::new()
1684 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1685 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1686 short_channel_id: 13,
1689 cltv_expiry_delta: (13 << 8) | 2,
1690 htlc_minimum_msat: 0,
1691 htlc_maximum_msat: OptionalField::Absent,
1693 fee_proportional_millionths: 0,
1694 excess_data: Vec::new()
1697 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
1699 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
1700 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1701 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1702 short_channel_id: 6,
1705 cltv_expiry_delta: (6 << 8) | 1,
1706 htlc_minimum_msat: 0,
1707 htlc_maximum_msat: OptionalField::Absent,
1709 fee_proportional_millionths: 0,
1710 excess_data: Vec::new()
1712 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1713 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1714 short_channel_id: 6,
1717 cltv_expiry_delta: (6 << 8) | 2,
1718 htlc_minimum_msat: 0,
1719 htlc_maximum_msat: OptionalField::Absent,
1721 fee_proportional_millionths: 0,
1722 excess_data: Vec::new(),
1725 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(11)), 11);
1726 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1727 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1728 short_channel_id: 11,
1731 cltv_expiry_delta: (11 << 8) | 1,
1732 htlc_minimum_msat: 0,
1733 htlc_maximum_msat: OptionalField::Absent,
1735 fee_proportional_millionths: 0,
1736 excess_data: Vec::new()
1738 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
1739 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1740 short_channel_id: 11,
1743 cltv_expiry_delta: (11 << 8) | 2,
1744 htlc_minimum_msat: 0,
1745 htlc_maximum_msat: OptionalField::Absent,
1747 fee_proportional_millionths: 0,
1748 excess_data: Vec::new()
1751 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(5)), 0);
1753 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
1755 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[5], ChannelFeatures::from_le_bytes(id_to_feature_flags(7)), 7);
1756 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1757 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1758 short_channel_id: 7,
1761 cltv_expiry_delta: (7 << 8) | 1,
1762 htlc_minimum_msat: 0,
1763 htlc_maximum_msat: OptionalField::Absent,
1765 fee_proportional_millionths: 1000000,
1766 excess_data: Vec::new()
1768 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[5], UnsignedChannelUpdate {
1769 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1770 short_channel_id: 7,
1773 cltv_expiry_delta: (7 << 8) | 2,
1774 htlc_minimum_msat: 0,
1775 htlc_maximum_msat: OptionalField::Absent,
1777 fee_proportional_millionths: 0,
1778 excess_data: Vec::new()
1781 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[5], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
1783 (secp_ctx, net_graph_msg_handler, chain_monitor, logger)
1787 fn simple_route_test() {
1788 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1789 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1790 let scorer = Scorer::new(0);
1792 // Simple route to 2 via 1
1794 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2], None, None, &Vec::new(), 0, 42, Arc::clone(&logger), &scorer) {
1795 assert_eq!(err, "Cannot send a payment of 0 msat");
1796 } else { panic!(); }
1798 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2], None, None, &Vec::new(), 100, 42, Arc::clone(&logger), &scorer).unwrap();
1799 assert_eq!(route.paths[0].len(), 2);
1801 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
1802 assert_eq!(route.paths[0][0].short_channel_id, 2);
1803 assert_eq!(route.paths[0][0].fee_msat, 100);
1804 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
1805 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
1806 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
1808 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1809 assert_eq!(route.paths[0][1].short_channel_id, 4);
1810 assert_eq!(route.paths[0][1].fee_msat, 100);
1811 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1812 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1813 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
1817 fn invalid_first_hop_test() {
1818 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1819 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1820 let scorer = Scorer::new(0);
1822 // Simple route to 2 via 1
1824 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
1826 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2], None, Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 100, 42, Arc::clone(&logger), &scorer) {
1827 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
1828 } else { panic!(); }
1830 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2], None, None, &Vec::new(), 100, 42, Arc::clone(&logger), &scorer).unwrap();
1831 assert_eq!(route.paths[0].len(), 2);
1835 fn htlc_minimum_test() {
1836 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1837 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1838 let scorer = Scorer::new(0);
1840 // Simple route to 2 via 1
1842 // Disable other paths
1843 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1844 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1845 short_channel_id: 12,
1847 flags: 2, // to disable
1848 cltv_expiry_delta: 0,
1849 htlc_minimum_msat: 0,
1850 htlc_maximum_msat: OptionalField::Absent,
1852 fee_proportional_millionths: 0,
1853 excess_data: Vec::new()
1855 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1856 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1857 short_channel_id: 3,
1859 flags: 2, // to disable
1860 cltv_expiry_delta: 0,
1861 htlc_minimum_msat: 0,
1862 htlc_maximum_msat: OptionalField::Absent,
1864 fee_proportional_millionths: 0,
1865 excess_data: Vec::new()
1867 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1868 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1869 short_channel_id: 13,
1871 flags: 2, // to disable
1872 cltv_expiry_delta: 0,
1873 htlc_minimum_msat: 0,
1874 htlc_maximum_msat: OptionalField::Absent,
1876 fee_proportional_millionths: 0,
1877 excess_data: Vec::new()
1879 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1880 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1881 short_channel_id: 6,
1883 flags: 2, // to disable
1884 cltv_expiry_delta: 0,
1885 htlc_minimum_msat: 0,
1886 htlc_maximum_msat: OptionalField::Absent,
1888 fee_proportional_millionths: 0,
1889 excess_data: Vec::new()
1891 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1892 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1893 short_channel_id: 7,
1895 flags: 2, // to disable
1896 cltv_expiry_delta: 0,
1897 htlc_minimum_msat: 0,
1898 htlc_maximum_msat: OptionalField::Absent,
1900 fee_proportional_millionths: 0,
1901 excess_data: Vec::new()
1904 // Check against amount_to_transfer_over_msat.
1905 // Set minimal HTLC of 200_000_000 msat.
1906 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1907 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1908 short_channel_id: 2,
1911 cltv_expiry_delta: 0,
1912 htlc_minimum_msat: 200_000_000,
1913 htlc_maximum_msat: OptionalField::Absent,
1915 fee_proportional_millionths: 0,
1916 excess_data: Vec::new()
1919 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
1921 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1922 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1923 short_channel_id: 4,
1926 cltv_expiry_delta: 0,
1927 htlc_minimum_msat: 0,
1928 htlc_maximum_msat: OptionalField::Present(199_999_999),
1930 fee_proportional_millionths: 0,
1931 excess_data: Vec::new()
1934 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
1935 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2], None, None, &Vec::new(), 199_999_999, 42, Arc::clone(&logger), &scorer) {
1936 assert_eq!(err, "Failed to find a path to the given destination");
1937 } else { panic!(); }
1939 // Lift the restriction on the first hop.
1940 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1941 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1942 short_channel_id: 2,
1945 cltv_expiry_delta: 0,
1946 htlc_minimum_msat: 0,
1947 htlc_maximum_msat: OptionalField::Absent,
1949 fee_proportional_millionths: 0,
1950 excess_data: Vec::new()
1953 // A payment above the minimum should pass
1954 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2], None, None, &Vec::new(), 199_999_999, 42, Arc::clone(&logger), &scorer).unwrap();
1955 assert_eq!(route.paths[0].len(), 2);
1959 fn htlc_minimum_overpay_test() {
1960 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1961 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1962 let scorer = Scorer::new(0);
1964 // A route to node#2 via two paths.
1965 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
1966 // Thus, they can't send 60 without overpaying.
1967 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1968 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1969 short_channel_id: 2,
1972 cltv_expiry_delta: 0,
1973 htlc_minimum_msat: 35_000,
1974 htlc_maximum_msat: OptionalField::Present(40_000),
1976 fee_proportional_millionths: 0,
1977 excess_data: Vec::new()
1979 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1980 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1981 short_channel_id: 12,
1984 cltv_expiry_delta: 0,
1985 htlc_minimum_msat: 35_000,
1986 htlc_maximum_msat: OptionalField::Present(40_000),
1988 fee_proportional_millionths: 0,
1989 excess_data: Vec::new()
1993 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1994 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1995 short_channel_id: 13,
1998 cltv_expiry_delta: 0,
1999 htlc_minimum_msat: 0,
2000 htlc_maximum_msat: OptionalField::Absent,
2002 fee_proportional_millionths: 0,
2003 excess_data: Vec::new()
2005 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2006 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2007 short_channel_id: 4,
2010 cltv_expiry_delta: 0,
2011 htlc_minimum_msat: 0,
2012 htlc_maximum_msat: OptionalField::Absent,
2014 fee_proportional_millionths: 0,
2015 excess_data: Vec::new()
2018 // Disable other paths
2019 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2020 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2021 short_channel_id: 1,
2023 flags: 2, // to disable
2024 cltv_expiry_delta: 0,
2025 htlc_minimum_msat: 0,
2026 htlc_maximum_msat: OptionalField::Absent,
2028 fee_proportional_millionths: 0,
2029 excess_data: Vec::new()
2032 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
2033 Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger), &scorer).unwrap();
2034 // Overpay fees to hit htlc_minimum_msat.
2035 let overpaid_fees = route.paths[0][0].fee_msat + route.paths[1][0].fee_msat;
2036 // TODO: this could be better balanced to overpay 10k and not 15k.
2037 assert_eq!(overpaid_fees, 15_000);
2039 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
2040 // while taking even more fee to match htlc_minimum_msat.
2041 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2042 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2043 short_channel_id: 12,
2046 cltv_expiry_delta: 0,
2047 htlc_minimum_msat: 65_000,
2048 htlc_maximum_msat: OptionalField::Present(80_000),
2050 fee_proportional_millionths: 0,
2051 excess_data: Vec::new()
2053 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2054 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2055 short_channel_id: 2,
2058 cltv_expiry_delta: 0,
2059 htlc_minimum_msat: 0,
2060 htlc_maximum_msat: OptionalField::Absent,
2062 fee_proportional_millionths: 0,
2063 excess_data: Vec::new()
2065 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2066 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2067 short_channel_id: 4,
2070 cltv_expiry_delta: 0,
2071 htlc_minimum_msat: 0,
2072 htlc_maximum_msat: OptionalField::Absent,
2074 fee_proportional_millionths: 100_000,
2075 excess_data: Vec::new()
2078 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
2079 Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger), &scorer).unwrap();
2080 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
2081 assert_eq!(route.paths.len(), 1);
2082 assert_eq!(route.paths[0][0].short_channel_id, 12);
2083 let fees = route.paths[0][0].fee_msat;
2084 assert_eq!(fees, 5_000);
2086 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
2087 Some(InvoiceFeatures::known()), None, &Vec::new(), 50_000, 42, Arc::clone(&logger), &scorer).unwrap();
2088 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
2089 // the other channel.
2090 assert_eq!(route.paths.len(), 1);
2091 assert_eq!(route.paths[0][0].short_channel_id, 2);
2092 let fees = route.paths[0][0].fee_msat;
2093 assert_eq!(fees, 5_000);
2097 fn disable_channels_test() {
2098 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2099 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2100 let scorer = Scorer::new(0);
2102 // // Disable channels 4 and 12 by flags=2
2103 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2104 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2105 short_channel_id: 4,
2107 flags: 2, // to disable
2108 cltv_expiry_delta: 0,
2109 htlc_minimum_msat: 0,
2110 htlc_maximum_msat: OptionalField::Absent,
2112 fee_proportional_millionths: 0,
2113 excess_data: Vec::new()
2115 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2116 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2117 short_channel_id: 12,
2119 flags: 2, // to disable
2120 cltv_expiry_delta: 0,
2121 htlc_minimum_msat: 0,
2122 htlc_maximum_msat: OptionalField::Absent,
2124 fee_proportional_millionths: 0,
2125 excess_data: Vec::new()
2128 // If all the channels require some features we don't understand, route should fail
2129 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2], None, None, &Vec::new(), 100, 42, Arc::clone(&logger), &scorer) {
2130 assert_eq!(err, "Failed to find a path to the given destination");
2131 } else { panic!(); }
2133 // If we specify a channel to node7, that overrides our local channel view and that gets used
2134 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2135 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2], None, Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2136 assert_eq!(route.paths[0].len(), 2);
2138 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2139 assert_eq!(route.paths[0][0].short_channel_id, 42);
2140 assert_eq!(route.paths[0][0].fee_msat, 200);
2141 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
2142 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2143 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2145 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2146 assert_eq!(route.paths[0][1].short_channel_id, 13);
2147 assert_eq!(route.paths[0][1].fee_msat, 100);
2148 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2149 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2150 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2154 fn disable_node_test() {
2155 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2156 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2157 let scorer = Scorer::new(0);
2159 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
2160 let unknown_features = NodeFeatures::known().set_unknown_feature_required();
2161 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
2162 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
2163 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
2165 // If all nodes require some features we don't understand, route should fail
2166 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2], None, None, &Vec::new(), 100, 42, Arc::clone(&logger), &scorer) {
2167 assert_eq!(err, "Failed to find a path to the given destination");
2168 } else { panic!(); }
2170 // If we specify a channel to node7, that overrides our local channel view and that gets used
2171 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2172 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2], None, Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2173 assert_eq!(route.paths[0].len(), 2);
2175 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2176 assert_eq!(route.paths[0][0].short_channel_id, 42);
2177 assert_eq!(route.paths[0][0].fee_msat, 200);
2178 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
2179 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2180 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2182 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2183 assert_eq!(route.paths[0][1].short_channel_id, 13);
2184 assert_eq!(route.paths[0][1].fee_msat, 100);
2185 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2186 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2187 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2189 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
2190 // naively) assume that the user checked the feature bits on the invoice, which override
2191 // the node_announcement.
2195 fn our_chans_test() {
2196 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2197 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2198 let scorer = Scorer::new(0);
2200 // Route to 1 via 2 and 3 because our channel to 1 is disabled
2201 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[0], None, None, &Vec::new(), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2202 assert_eq!(route.paths[0].len(), 3);
2204 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2205 assert_eq!(route.paths[0][0].short_channel_id, 2);
2206 assert_eq!(route.paths[0][0].fee_msat, 200);
2207 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2208 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2209 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2211 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2212 assert_eq!(route.paths[0][1].short_channel_id, 4);
2213 assert_eq!(route.paths[0][1].fee_msat, 100);
2214 assert_eq!(route.paths[0][1].cltv_expiry_delta, (3 << 8) | 2);
2215 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2216 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2218 assert_eq!(route.paths[0][2].pubkey, nodes[0]);
2219 assert_eq!(route.paths[0][2].short_channel_id, 3);
2220 assert_eq!(route.paths[0][2].fee_msat, 100);
2221 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
2222 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(1));
2223 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(3));
2225 // If we specify a channel to node7, that overrides our local channel view and that gets used
2226 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2227 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2], None, Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2228 assert_eq!(route.paths[0].len(), 2);
2230 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2231 assert_eq!(route.paths[0][0].short_channel_id, 42);
2232 assert_eq!(route.paths[0][0].fee_msat, 200);
2233 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
2234 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2235 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2237 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2238 assert_eq!(route.paths[0][1].short_channel_id, 13);
2239 assert_eq!(route.paths[0][1].fee_msat, 100);
2240 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2241 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2242 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2245 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2246 let zero_fees = RoutingFees {
2248 proportional_millionths: 0,
2250 vec![RouteHint(vec![RouteHintHop {
2251 src_node_id: nodes[3],
2252 short_channel_id: 8,
2254 cltv_expiry_delta: (8 << 8) | 1,
2255 htlc_minimum_msat: None,
2256 htlc_maximum_msat: None,
2258 ]), RouteHint(vec![RouteHintHop {
2259 src_node_id: nodes[4],
2260 short_channel_id: 9,
2263 proportional_millionths: 0,
2265 cltv_expiry_delta: (9 << 8) | 1,
2266 htlc_minimum_msat: None,
2267 htlc_maximum_msat: None,
2268 }]), RouteHint(vec![RouteHintHop {
2269 src_node_id: nodes[5],
2270 short_channel_id: 10,
2272 cltv_expiry_delta: (10 << 8) | 1,
2273 htlc_minimum_msat: None,
2274 htlc_maximum_msat: None,
2278 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2279 let zero_fees = RoutingFees {
2281 proportional_millionths: 0,
2283 vec![RouteHint(vec![RouteHintHop {
2284 src_node_id: nodes[2],
2285 short_channel_id: 5,
2288 proportional_millionths: 0,
2290 cltv_expiry_delta: (5 << 8) | 1,
2291 htlc_minimum_msat: None,
2292 htlc_maximum_msat: None,
2294 src_node_id: nodes[3],
2295 short_channel_id: 8,
2297 cltv_expiry_delta: (8 << 8) | 1,
2298 htlc_minimum_msat: None,
2299 htlc_maximum_msat: None,
2301 ]), RouteHint(vec![RouteHintHop {
2302 src_node_id: nodes[4],
2303 short_channel_id: 9,
2306 proportional_millionths: 0,
2308 cltv_expiry_delta: (9 << 8) | 1,
2309 htlc_minimum_msat: None,
2310 htlc_maximum_msat: None,
2311 }]), RouteHint(vec![RouteHintHop {
2312 src_node_id: nodes[5],
2313 short_channel_id: 10,
2315 cltv_expiry_delta: (10 << 8) | 1,
2316 htlc_minimum_msat: None,
2317 htlc_maximum_msat: None,
2322 fn partial_route_hint_test() {
2323 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2324 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2325 let scorer = Scorer::new(0);
2327 // Simple test across 2, 3, 5, and 4 via a last_hop channel
2328 // Tests the behaviour when the RouteHint contains a suboptimal hop.
2329 // RouteHint may be partially used by the algo to build the best path.
2331 // First check that last hop can't have its source as the payee.
2332 let invalid_last_hop = RouteHint(vec![RouteHintHop {
2333 src_node_id: nodes[6],
2334 short_channel_id: 8,
2337 proportional_millionths: 0,
2339 cltv_expiry_delta: (8 << 8) | 1,
2340 htlc_minimum_msat: None,
2341 htlc_maximum_msat: None,
2344 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
2345 invalid_last_hops.push(invalid_last_hop);
2347 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[6], None, None, &invalid_last_hops.iter().collect::<Vec<_>>(), 100, 42, Arc::clone(&logger), &scorer) {
2348 assert_eq!(err, "Last hop cannot have a payee as a source.");
2349 } else { panic!(); }
2352 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[6], None, None, &last_hops_multi_private_channels(&nodes).iter().collect::<Vec<_>>(), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2353 assert_eq!(route.paths[0].len(), 5);
2355 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2356 assert_eq!(route.paths[0][0].short_channel_id, 2);
2357 assert_eq!(route.paths[0][0].fee_msat, 100);
2358 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2359 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2360 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2362 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2363 assert_eq!(route.paths[0][1].short_channel_id, 4);
2364 assert_eq!(route.paths[0][1].fee_msat, 0);
2365 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2366 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2367 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2369 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2370 assert_eq!(route.paths[0][2].short_channel_id, 6);
2371 assert_eq!(route.paths[0][2].fee_msat, 0);
2372 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2373 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2374 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2376 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2377 assert_eq!(route.paths[0][3].short_channel_id, 11);
2378 assert_eq!(route.paths[0][3].fee_msat, 0);
2379 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2380 // If we have a peer in the node map, we'll use their features here since we don't have
2381 // a way of figuring out their features from the invoice:
2382 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2383 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2385 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2386 assert_eq!(route.paths[0][4].short_channel_id, 8);
2387 assert_eq!(route.paths[0][4].fee_msat, 100);
2388 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2389 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2390 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2393 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2394 let zero_fees = RoutingFees {
2396 proportional_millionths: 0,
2398 vec![RouteHint(vec![RouteHintHop {
2399 src_node_id: nodes[3],
2400 short_channel_id: 8,
2402 cltv_expiry_delta: (8 << 8) | 1,
2403 htlc_minimum_msat: None,
2404 htlc_maximum_msat: None,
2405 }]), RouteHint(vec![
2407 ]), RouteHint(vec![RouteHintHop {
2408 src_node_id: nodes[5],
2409 short_channel_id: 10,
2411 cltv_expiry_delta: (10 << 8) | 1,
2412 htlc_minimum_msat: None,
2413 htlc_maximum_msat: None,
2418 fn ignores_empty_last_hops_test() {
2419 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2420 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2421 let scorer = Scorer::new(0);
2423 // Test handling of an empty RouteHint passed in Invoice.
2425 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[6], None, None, &empty_last_hop(&nodes).iter().collect::<Vec<_>>(), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2426 assert_eq!(route.paths[0].len(), 5);
2428 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2429 assert_eq!(route.paths[0][0].short_channel_id, 2);
2430 assert_eq!(route.paths[0][0].fee_msat, 100);
2431 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2432 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2433 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2435 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2436 assert_eq!(route.paths[0][1].short_channel_id, 4);
2437 assert_eq!(route.paths[0][1].fee_msat, 0);
2438 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2439 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2440 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2442 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2443 assert_eq!(route.paths[0][2].short_channel_id, 6);
2444 assert_eq!(route.paths[0][2].fee_msat, 0);
2445 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2446 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2447 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2449 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2450 assert_eq!(route.paths[0][3].short_channel_id, 11);
2451 assert_eq!(route.paths[0][3].fee_msat, 0);
2452 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2453 // If we have a peer in the node map, we'll use their features here since we don't have
2454 // a way of figuring out their features from the invoice:
2455 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2456 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2458 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2459 assert_eq!(route.paths[0][4].short_channel_id, 8);
2460 assert_eq!(route.paths[0][4].fee_msat, 100);
2461 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2462 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2463 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2466 fn multi_hint_last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2467 let zero_fees = RoutingFees {
2469 proportional_millionths: 0,
2471 vec![RouteHint(vec![RouteHintHop {
2472 src_node_id: nodes[2],
2473 short_channel_id: 5,
2476 proportional_millionths: 0,
2478 cltv_expiry_delta: (5 << 8) | 1,
2479 htlc_minimum_msat: None,
2480 htlc_maximum_msat: None,
2482 src_node_id: nodes[3],
2483 short_channel_id: 8,
2485 cltv_expiry_delta: (8 << 8) | 1,
2486 htlc_minimum_msat: None,
2487 htlc_maximum_msat: None,
2488 }]), RouteHint(vec![RouteHintHop {
2489 src_node_id: nodes[5],
2490 short_channel_id: 10,
2492 cltv_expiry_delta: (10 << 8) | 1,
2493 htlc_minimum_msat: None,
2494 htlc_maximum_msat: None,
2499 fn multi_hint_last_hops_test() {
2500 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2501 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2502 let scorer = Scorer::new(0);
2503 // Test through channels 2, 3, 5, 8.
2504 // Test shows that multiple hop hints are considered.
2506 // Disabling channels 6 & 7 by flags=2
2507 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2508 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2509 short_channel_id: 6,
2511 flags: 2, // to disable
2512 cltv_expiry_delta: 0,
2513 htlc_minimum_msat: 0,
2514 htlc_maximum_msat: OptionalField::Absent,
2516 fee_proportional_millionths: 0,
2517 excess_data: Vec::new()
2519 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2520 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2521 short_channel_id: 7,
2523 flags: 2, // to disable
2524 cltv_expiry_delta: 0,
2525 htlc_minimum_msat: 0,
2526 htlc_maximum_msat: OptionalField::Absent,
2528 fee_proportional_millionths: 0,
2529 excess_data: Vec::new()
2532 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[6], None, None, &multi_hint_last_hops(&nodes).iter().collect::<Vec<_>>(), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2533 assert_eq!(route.paths[0].len(), 4);
2535 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2536 assert_eq!(route.paths[0][0].short_channel_id, 2);
2537 assert_eq!(route.paths[0][0].fee_msat, 200);
2538 assert_eq!(route.paths[0][0].cltv_expiry_delta, 1025);
2539 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2540 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2542 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2543 assert_eq!(route.paths[0][1].short_channel_id, 4);
2544 assert_eq!(route.paths[0][1].fee_msat, 100);
2545 assert_eq!(route.paths[0][1].cltv_expiry_delta, 1281);
2546 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2547 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2549 assert_eq!(route.paths[0][2].pubkey, nodes[3]);
2550 assert_eq!(route.paths[0][2].short_channel_id, 5);
2551 assert_eq!(route.paths[0][2].fee_msat, 0);
2552 assert_eq!(route.paths[0][2].cltv_expiry_delta, 2049);
2553 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(4));
2554 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new());
2556 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2557 assert_eq!(route.paths[0][3].short_channel_id, 8);
2558 assert_eq!(route.paths[0][3].fee_msat, 100);
2559 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2560 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2561 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2564 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2565 let zero_fees = RoutingFees {
2567 proportional_millionths: 0,
2569 vec![RouteHint(vec![RouteHintHop {
2570 src_node_id: nodes[4],
2571 short_channel_id: 11,
2573 cltv_expiry_delta: (11 << 8) | 1,
2574 htlc_minimum_msat: None,
2575 htlc_maximum_msat: None,
2577 src_node_id: nodes[3],
2578 short_channel_id: 8,
2580 cltv_expiry_delta: (8 << 8) | 1,
2581 htlc_minimum_msat: None,
2582 htlc_maximum_msat: None,
2583 }]), RouteHint(vec![RouteHintHop {
2584 src_node_id: nodes[4],
2585 short_channel_id: 9,
2588 proportional_millionths: 0,
2590 cltv_expiry_delta: (9 << 8) | 1,
2591 htlc_minimum_msat: None,
2592 htlc_maximum_msat: None,
2593 }]), RouteHint(vec![RouteHintHop {
2594 src_node_id: nodes[5],
2595 short_channel_id: 10,
2597 cltv_expiry_delta: (10 << 8) | 1,
2598 htlc_minimum_msat: None,
2599 htlc_maximum_msat: None,
2604 fn last_hops_with_public_channel_test() {
2605 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2606 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2607 let scorer = Scorer::new(0);
2608 // This test shows that public routes can be present in the invoice
2609 // which would be handled in the same manner.
2611 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[6], None, None, &last_hops_with_public_channel(&nodes).iter().collect::<Vec<_>>(), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2612 assert_eq!(route.paths[0].len(), 5);
2614 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2615 assert_eq!(route.paths[0][0].short_channel_id, 2);
2616 assert_eq!(route.paths[0][0].fee_msat, 100);
2617 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2618 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2619 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2621 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2622 assert_eq!(route.paths[0][1].short_channel_id, 4);
2623 assert_eq!(route.paths[0][1].fee_msat, 0);
2624 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2625 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2626 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2628 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2629 assert_eq!(route.paths[0][2].short_channel_id, 6);
2630 assert_eq!(route.paths[0][2].fee_msat, 0);
2631 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2632 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2633 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2635 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2636 assert_eq!(route.paths[0][3].short_channel_id, 11);
2637 assert_eq!(route.paths[0][3].fee_msat, 0);
2638 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2639 // If we have a peer in the node map, we'll use their features here since we don't have
2640 // a way of figuring out their features from the invoice:
2641 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2642 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new());
2644 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2645 assert_eq!(route.paths[0][4].short_channel_id, 8);
2646 assert_eq!(route.paths[0][4].fee_msat, 100);
2647 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2648 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2649 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2653 fn our_chans_last_hop_connect_test() {
2654 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2655 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2656 let scorer = Scorer::new(0);
2658 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
2659 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2660 let mut last_hops = last_hops(&nodes);
2661 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[6], None, Some(&our_chans.iter().collect::<Vec<_>>()), &last_hops.iter().collect::<Vec<_>>(), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2662 assert_eq!(route.paths[0].len(), 2);
2664 assert_eq!(route.paths[0][0].pubkey, nodes[3]);
2665 assert_eq!(route.paths[0][0].short_channel_id, 42);
2666 assert_eq!(route.paths[0][0].fee_msat, 0);
2667 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
2668 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2669 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2671 assert_eq!(route.paths[0][1].pubkey, nodes[6]);
2672 assert_eq!(route.paths[0][1].short_channel_id, 8);
2673 assert_eq!(route.paths[0][1].fee_msat, 100);
2674 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2675 assert_eq!(route.paths[0][1].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2676 assert_eq!(route.paths[0][1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2678 last_hops[0].0[0].fees.base_msat = 1000;
2680 // Revert to via 6 as the fee on 8 goes up
2681 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[6], None, None, &last_hops.iter().collect::<Vec<_>>(), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2682 assert_eq!(route.paths[0].len(), 4);
2684 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2685 assert_eq!(route.paths[0][0].short_channel_id, 2);
2686 assert_eq!(route.paths[0][0].fee_msat, 200); // fee increased as its % of value transferred across node
2687 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2688 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2689 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2691 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2692 assert_eq!(route.paths[0][1].short_channel_id, 4);
2693 assert_eq!(route.paths[0][1].fee_msat, 100);
2694 assert_eq!(route.paths[0][1].cltv_expiry_delta, (7 << 8) | 1);
2695 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2696 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2698 assert_eq!(route.paths[0][2].pubkey, nodes[5]);
2699 assert_eq!(route.paths[0][2].short_channel_id, 7);
2700 assert_eq!(route.paths[0][2].fee_msat, 0);
2701 assert_eq!(route.paths[0][2].cltv_expiry_delta, (10 << 8) | 1);
2702 // If we have a peer in the node map, we'll use their features here since we don't have
2703 // a way of figuring out their features from the invoice:
2704 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
2705 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(7));
2707 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2708 assert_eq!(route.paths[0][3].short_channel_id, 10);
2709 assert_eq!(route.paths[0][3].fee_msat, 100);
2710 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2711 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2712 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2714 // ...but still use 8 for larger payments as 6 has a variable feerate
2715 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[6], None, None, &last_hops.iter().collect::<Vec<_>>(), 2000, 42, Arc::clone(&logger), &scorer).unwrap();
2716 assert_eq!(route.paths[0].len(), 5);
2718 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2719 assert_eq!(route.paths[0][0].short_channel_id, 2);
2720 assert_eq!(route.paths[0][0].fee_msat, 3000);
2721 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2722 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2723 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2725 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2726 assert_eq!(route.paths[0][1].short_channel_id, 4);
2727 assert_eq!(route.paths[0][1].fee_msat, 0);
2728 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2729 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2730 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2732 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2733 assert_eq!(route.paths[0][2].short_channel_id, 6);
2734 assert_eq!(route.paths[0][2].fee_msat, 0);
2735 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2736 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2737 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2739 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2740 assert_eq!(route.paths[0][3].short_channel_id, 11);
2741 assert_eq!(route.paths[0][3].fee_msat, 1000);
2742 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2743 // If we have a peer in the node map, we'll use their features here since we don't have
2744 // a way of figuring out their features from the invoice:
2745 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2746 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2748 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2749 assert_eq!(route.paths[0][4].short_channel_id, 8);
2750 assert_eq!(route.paths[0][4].fee_msat, 2000);
2751 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2752 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2753 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2756 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> {
2757 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
2758 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
2759 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
2761 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
2762 let last_hops = RouteHint(vec![RouteHintHop {
2763 src_node_id: middle_node_id,
2764 short_channel_id: 8,
2767 proportional_millionths: last_hop_fee_prop,
2769 cltv_expiry_delta: (8 << 8) | 1,
2770 htlc_minimum_msat: None,
2771 htlc_maximum_msat: last_hop_htlc_max,
2773 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
2774 let scorer = Scorer::new(0);
2775 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, &test_utils::TestLogger::new(), &scorer)
2779 fn unannounced_path_test() {
2780 // We should be able to send a payment to a destination without any help of a routing graph
2781 // if we have a channel with a common counterparty that appears in the first and last hop
2783 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
2785 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
2786 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
2787 assert_eq!(route.paths[0].len(), 2);
2789 assert_eq!(route.paths[0][0].pubkey, middle_node_id);
2790 assert_eq!(route.paths[0][0].short_channel_id, 42);
2791 assert_eq!(route.paths[0][0].fee_msat, 1001);
2792 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
2793 assert_eq!(route.paths[0][0].node_features.le_flags(), &[0b11]);
2794 assert_eq!(route.paths[0][0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
2796 assert_eq!(route.paths[0][1].pubkey, target_node_id);
2797 assert_eq!(route.paths[0][1].short_channel_id, 8);
2798 assert_eq!(route.paths[0][1].fee_msat, 1000000);
2799 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2800 assert_eq!(route.paths[0][1].node_features.le_flags(), &[0; 0]); // We dont pass flags in from invoices yet
2801 assert_eq!(route.paths[0][1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
2805 fn overflow_unannounced_path_test_liquidity_underflow() {
2806 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
2807 // the last-hop had a fee which overflowed a u64, we'd panic.
2808 // This was due to us adding the first-hop from us unconditionally, causing us to think
2809 // we'd built a path (as our node is in the "best candidate" set), when we had not.
2810 // In this test, we previously hit a subtraction underflow due to having less available
2811 // liquidity at the last hop than 0.
2812 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());
2816 fn overflow_unannounced_path_test_feerate_overflow() {
2817 // This tests for the same case as above, except instead of hitting a subtraction
2818 // underflow, we hit a case where the fee charged at a hop overflowed.
2819 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());
2823 fn available_amount_while_routing_test() {
2824 // Tests whether we choose the correct available channel amount while routing.
2826 let (secp_ctx, mut net_graph_msg_handler, chain_monitor, logger) = build_graph();
2827 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2828 let scorer = Scorer::new(0);
2830 // We will use a simple single-path route from
2831 // our node to node2 via node0: channels {1, 3}.
2833 // First disable all other paths.
2834 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2835 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2836 short_channel_id: 2,
2839 cltv_expiry_delta: 0,
2840 htlc_minimum_msat: 0,
2841 htlc_maximum_msat: OptionalField::Present(100_000),
2843 fee_proportional_millionths: 0,
2844 excess_data: Vec::new()
2846 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2847 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2848 short_channel_id: 12,
2851 cltv_expiry_delta: 0,
2852 htlc_minimum_msat: 0,
2853 htlc_maximum_msat: OptionalField::Present(100_000),
2855 fee_proportional_millionths: 0,
2856 excess_data: Vec::new()
2859 // Make the first channel (#1) very permissive,
2860 // and we will be testing all limits on the second channel.
2861 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2862 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2863 short_channel_id: 1,
2866 cltv_expiry_delta: 0,
2867 htlc_minimum_msat: 0,
2868 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2870 fee_proportional_millionths: 0,
2871 excess_data: Vec::new()
2874 // First, let's see if routing works if we have absolutely no idea about the available amount.
2875 // In this case, it should be set to 250_000 sats.
2876 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2877 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2878 short_channel_id: 3,
2881 cltv_expiry_delta: 0,
2882 htlc_minimum_msat: 0,
2883 htlc_maximum_msat: OptionalField::Absent,
2885 fee_proportional_millionths: 0,
2886 excess_data: Vec::new()
2890 // Attempt to route more than available results in a failure.
2891 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
2892 Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000_001, 42, Arc::clone(&logger), &scorer) {
2893 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2894 } else { panic!(); }
2898 // Now, attempt to route an exact amount we have should be fine.
2899 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
2900 Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000_000, 42, Arc::clone(&logger), &scorer).unwrap();
2901 assert_eq!(route.paths.len(), 1);
2902 let path = route.paths.last().unwrap();
2903 assert_eq!(path.len(), 2);
2904 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2905 assert_eq!(path.last().unwrap().fee_msat, 250_000_000);
2908 // Check that setting outbound_capacity_msat in first_hops limits the channels.
2909 // Disable channel #1 and use another first hop.
2910 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2911 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2912 short_channel_id: 1,
2915 cltv_expiry_delta: 0,
2916 htlc_minimum_msat: 0,
2917 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2919 fee_proportional_millionths: 0,
2920 excess_data: Vec::new()
2923 // Now, limit the first_hop by the outbound_capacity_msat of 200_000 sats.
2924 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
2927 // Attempt to route more than available results in a failure.
2928 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
2929 Some(InvoiceFeatures::known()), Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 200_000_001, 42, Arc::clone(&logger), &scorer) {
2930 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2931 } else { panic!(); }
2935 // Now, attempt to route an exact amount we have should be fine.
2936 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
2937 Some(InvoiceFeatures::known()), Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 200_000_000, 42, Arc::clone(&logger), &scorer).unwrap();
2938 assert_eq!(route.paths.len(), 1);
2939 let path = route.paths.last().unwrap();
2940 assert_eq!(path.len(), 2);
2941 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2942 assert_eq!(path.last().unwrap().fee_msat, 200_000_000);
2945 // Enable channel #1 back.
2946 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2947 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2948 short_channel_id: 1,
2951 cltv_expiry_delta: 0,
2952 htlc_minimum_msat: 0,
2953 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2955 fee_proportional_millionths: 0,
2956 excess_data: Vec::new()
2960 // Now let's see if routing works if we know only htlc_maximum_msat.
2961 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2962 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2963 short_channel_id: 3,
2966 cltv_expiry_delta: 0,
2967 htlc_minimum_msat: 0,
2968 htlc_maximum_msat: OptionalField::Present(15_000),
2970 fee_proportional_millionths: 0,
2971 excess_data: Vec::new()
2975 // Attempt to route more than available results in a failure.
2976 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
2977 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_001, 42, Arc::clone(&logger), &scorer) {
2978 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2979 } else { panic!(); }
2983 // Now, attempt to route an exact amount we have should be fine.
2984 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
2985 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_000, 42, Arc::clone(&logger), &scorer).unwrap();
2986 assert_eq!(route.paths.len(), 1);
2987 let path = route.paths.last().unwrap();
2988 assert_eq!(path.len(), 2);
2989 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2990 assert_eq!(path.last().unwrap().fee_msat, 15_000);
2993 // Now let's see if routing works if we know only capacity from the UTXO.
2995 // We can't change UTXO capacity on the fly, so we'll disable
2996 // the existing channel and add another one with the capacity we need.
2997 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2998 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2999 short_channel_id: 3,
3002 cltv_expiry_delta: 0,
3003 htlc_minimum_msat: 0,
3004 htlc_maximum_msat: OptionalField::Absent,
3006 fee_proportional_millionths: 0,
3007 excess_data: Vec::new()
3010 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
3011 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
3012 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
3013 .push_opcode(opcodes::all::OP_PUSHNUM_2)
3014 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
3016 *chain_monitor.utxo_ret.lock().unwrap() = Ok(TxOut { value: 15, script_pubkey: good_script.clone() });
3017 net_graph_msg_handler.add_chain_access(Some(chain_monitor));
3019 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
3020 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3021 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3022 short_channel_id: 333,
3025 cltv_expiry_delta: (3 << 8) | 1,
3026 htlc_minimum_msat: 0,
3027 htlc_maximum_msat: OptionalField::Absent,
3029 fee_proportional_millionths: 0,
3030 excess_data: Vec::new()
3032 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3033 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3034 short_channel_id: 333,
3037 cltv_expiry_delta: (3 << 8) | 2,
3038 htlc_minimum_msat: 0,
3039 htlc_maximum_msat: OptionalField::Absent,
3041 fee_proportional_millionths: 0,
3042 excess_data: Vec::new()
3046 // Attempt to route more than available results in a failure.
3047 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
3048 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_001, 42, Arc::clone(&logger), &scorer) {
3049 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3050 } else { panic!(); }
3054 // Now, attempt to route an exact amount we have should be fine.
3055 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
3056 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_000, 42, Arc::clone(&logger), &scorer).unwrap();
3057 assert_eq!(route.paths.len(), 1);
3058 let path = route.paths.last().unwrap();
3059 assert_eq!(path.len(), 2);
3060 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3061 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3064 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
3065 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3066 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3067 short_channel_id: 333,
3070 cltv_expiry_delta: 0,
3071 htlc_minimum_msat: 0,
3072 htlc_maximum_msat: OptionalField::Present(10_000),
3074 fee_proportional_millionths: 0,
3075 excess_data: Vec::new()
3079 // Attempt to route more than available results in a failure.
3080 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
3081 Some(InvoiceFeatures::known()), None, &Vec::new(), 10_001, 42, Arc::clone(&logger), &scorer) {
3082 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3083 } else { panic!(); }
3087 // Now, attempt to route an exact amount we have should be fine.
3088 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
3089 Some(InvoiceFeatures::known()), None, &Vec::new(), 10_000, 42, Arc::clone(&logger), &scorer).unwrap();
3090 assert_eq!(route.paths.len(), 1);
3091 let path = route.paths.last().unwrap();
3092 assert_eq!(path.len(), 2);
3093 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3094 assert_eq!(path.last().unwrap().fee_msat, 10_000);
3099 fn available_liquidity_last_hop_test() {
3100 // Check that available liquidity properly limits the path even when only
3101 // one of the latter hops is limited.
3102 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3103 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3104 let scorer = Scorer::new(0);
3106 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3107 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
3108 // Total capacity: 50 sats.
3110 // Disable other potential paths.
3111 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3112 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3113 short_channel_id: 2,
3116 cltv_expiry_delta: 0,
3117 htlc_minimum_msat: 0,
3118 htlc_maximum_msat: OptionalField::Present(100_000),
3120 fee_proportional_millionths: 0,
3121 excess_data: Vec::new()
3123 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3124 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3125 short_channel_id: 7,
3128 cltv_expiry_delta: 0,
3129 htlc_minimum_msat: 0,
3130 htlc_maximum_msat: OptionalField::Present(100_000),
3132 fee_proportional_millionths: 0,
3133 excess_data: Vec::new()
3138 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3139 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3140 short_channel_id: 12,
3143 cltv_expiry_delta: 0,
3144 htlc_minimum_msat: 0,
3145 htlc_maximum_msat: OptionalField::Present(100_000),
3147 fee_proportional_millionths: 0,
3148 excess_data: Vec::new()
3150 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3151 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3152 short_channel_id: 13,
3155 cltv_expiry_delta: 0,
3156 htlc_minimum_msat: 0,
3157 htlc_maximum_msat: OptionalField::Present(100_000),
3159 fee_proportional_millionths: 0,
3160 excess_data: Vec::new()
3163 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3164 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3165 short_channel_id: 6,
3168 cltv_expiry_delta: 0,
3169 htlc_minimum_msat: 0,
3170 htlc_maximum_msat: OptionalField::Present(50_000),
3172 fee_proportional_millionths: 0,
3173 excess_data: Vec::new()
3175 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3176 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3177 short_channel_id: 11,
3180 cltv_expiry_delta: 0,
3181 htlc_minimum_msat: 0,
3182 htlc_maximum_msat: OptionalField::Present(100_000),
3184 fee_proportional_millionths: 0,
3185 excess_data: Vec::new()
3188 // Attempt to route more than available results in a failure.
3189 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[3],
3190 Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger), &scorer) {
3191 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3192 } else { panic!(); }
3196 // Now, attempt to route 49 sats (just a bit below the capacity).
3197 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[3],
3198 Some(InvoiceFeatures::known()), None, &Vec::new(), 49_000, 42, Arc::clone(&logger), &scorer).unwrap();
3199 assert_eq!(route.paths.len(), 1);
3200 let mut total_amount_paid_msat = 0;
3201 for path in &route.paths {
3202 assert_eq!(path.len(), 4);
3203 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3204 total_amount_paid_msat += path.last().unwrap().fee_msat;
3206 assert_eq!(total_amount_paid_msat, 49_000);
3210 // Attempt to route an exact amount is also fine
3211 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[3],
3212 Some(InvoiceFeatures::known()), None, &Vec::new(), 50_000, 42, Arc::clone(&logger), &scorer).unwrap();
3213 assert_eq!(route.paths.len(), 1);
3214 let mut total_amount_paid_msat = 0;
3215 for path in &route.paths {
3216 assert_eq!(path.len(), 4);
3217 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3218 total_amount_paid_msat += path.last().unwrap().fee_msat;
3220 assert_eq!(total_amount_paid_msat, 50_000);
3225 fn ignore_fee_first_hop_test() {
3226 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3227 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3228 let scorer = Scorer::new(0);
3230 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3231 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3232 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3233 short_channel_id: 1,
3236 cltv_expiry_delta: 0,
3237 htlc_minimum_msat: 0,
3238 htlc_maximum_msat: OptionalField::Present(100_000),
3239 fee_base_msat: 1_000_000,
3240 fee_proportional_millionths: 0,
3241 excess_data: Vec::new()
3243 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3244 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3245 short_channel_id: 3,
3248 cltv_expiry_delta: 0,
3249 htlc_minimum_msat: 0,
3250 htlc_maximum_msat: OptionalField::Present(50_000),
3252 fee_proportional_millionths: 0,
3253 excess_data: Vec::new()
3257 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2], None, None, &Vec::new(), 50_000, 42, Arc::clone(&logger), &scorer).unwrap();
3258 assert_eq!(route.paths.len(), 1);
3259 let mut total_amount_paid_msat = 0;
3260 for path in &route.paths {
3261 assert_eq!(path.len(), 2);
3262 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3263 total_amount_paid_msat += path.last().unwrap().fee_msat;
3265 assert_eq!(total_amount_paid_msat, 50_000);
3270 fn simple_mpp_route_test() {
3271 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3272 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3273 let scorer = Scorer::new(0);
3275 // We need a route consisting of 3 paths:
3276 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3277 // To achieve this, the amount being transferred should be around
3278 // the total capacity of these 3 paths.
3280 // First, we set limits on these (previously unlimited) channels.
3281 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
3283 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3284 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3285 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3286 short_channel_id: 1,
3289 cltv_expiry_delta: 0,
3290 htlc_minimum_msat: 0,
3291 htlc_maximum_msat: OptionalField::Present(100_000),
3293 fee_proportional_millionths: 0,
3294 excess_data: Vec::new()
3296 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3297 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3298 short_channel_id: 3,
3301 cltv_expiry_delta: 0,
3302 htlc_minimum_msat: 0,
3303 htlc_maximum_msat: OptionalField::Present(50_000),
3305 fee_proportional_millionths: 0,
3306 excess_data: Vec::new()
3309 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
3310 // (total limit 60).
3311 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3312 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3313 short_channel_id: 12,
3316 cltv_expiry_delta: 0,
3317 htlc_minimum_msat: 0,
3318 htlc_maximum_msat: OptionalField::Present(60_000),
3320 fee_proportional_millionths: 0,
3321 excess_data: Vec::new()
3323 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3324 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3325 short_channel_id: 13,
3328 cltv_expiry_delta: 0,
3329 htlc_minimum_msat: 0,
3330 htlc_maximum_msat: OptionalField::Present(60_000),
3332 fee_proportional_millionths: 0,
3333 excess_data: Vec::new()
3336 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
3337 // (total capacity 180 sats).
3338 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3339 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3340 short_channel_id: 2,
3343 cltv_expiry_delta: 0,
3344 htlc_minimum_msat: 0,
3345 htlc_maximum_msat: OptionalField::Present(200_000),
3347 fee_proportional_millionths: 0,
3348 excess_data: Vec::new()
3350 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3351 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3352 short_channel_id: 4,
3355 cltv_expiry_delta: 0,
3356 htlc_minimum_msat: 0,
3357 htlc_maximum_msat: OptionalField::Present(180_000),
3359 fee_proportional_millionths: 0,
3360 excess_data: Vec::new()
3364 // Attempt to route more than available results in a failure.
3365 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph,
3366 &nodes[2], Some(InvoiceFeatures::known()), None, &Vec::new(), 300_000, 42, Arc::clone(&logger), &scorer) {
3367 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3368 } else { panic!(); }
3372 // Now, attempt to route 250 sats (just a bit below the capacity).
3373 // Our algorithm should provide us with these 3 paths.
3374 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
3375 Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000, 42, Arc::clone(&logger), &scorer).unwrap();
3376 assert_eq!(route.paths.len(), 3);
3377 let mut total_amount_paid_msat = 0;
3378 for path in &route.paths {
3379 assert_eq!(path.len(), 2);
3380 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3381 total_amount_paid_msat += path.last().unwrap().fee_msat;
3383 assert_eq!(total_amount_paid_msat, 250_000);
3387 // Attempt to route an exact amount is also fine
3388 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
3389 Some(InvoiceFeatures::known()), None, &Vec::new(), 290_000, 42, Arc::clone(&logger), &scorer).unwrap();
3390 assert_eq!(route.paths.len(), 3);
3391 let mut total_amount_paid_msat = 0;
3392 for path in &route.paths {
3393 assert_eq!(path.len(), 2);
3394 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3395 total_amount_paid_msat += path.last().unwrap().fee_msat;
3397 assert_eq!(total_amount_paid_msat, 290_000);
3402 fn long_mpp_route_test() {
3403 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3404 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3405 let scorer = Scorer::new(0);
3407 // We need a route consisting of 3 paths:
3408 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3409 // Note that these paths overlap (channels 5, 12, 13).
3410 // We will route 300 sats.
3411 // Each path will have 100 sats capacity, those channels which
3412 // are used twice will have 200 sats capacity.
3414 // Disable other potential paths.
3415 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3416 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3417 short_channel_id: 2,
3420 cltv_expiry_delta: 0,
3421 htlc_minimum_msat: 0,
3422 htlc_maximum_msat: OptionalField::Present(100_000),
3424 fee_proportional_millionths: 0,
3425 excess_data: Vec::new()
3427 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3428 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3429 short_channel_id: 7,
3432 cltv_expiry_delta: 0,
3433 htlc_minimum_msat: 0,
3434 htlc_maximum_msat: OptionalField::Present(100_000),
3436 fee_proportional_millionths: 0,
3437 excess_data: Vec::new()
3440 // Path via {node0, node2} is channels {1, 3, 5}.
3441 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3442 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3443 short_channel_id: 1,
3446 cltv_expiry_delta: 0,
3447 htlc_minimum_msat: 0,
3448 htlc_maximum_msat: OptionalField::Present(100_000),
3450 fee_proportional_millionths: 0,
3451 excess_data: Vec::new()
3453 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3454 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3455 short_channel_id: 3,
3458 cltv_expiry_delta: 0,
3459 htlc_minimum_msat: 0,
3460 htlc_maximum_msat: OptionalField::Present(100_000),
3462 fee_proportional_millionths: 0,
3463 excess_data: Vec::new()
3466 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3467 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3468 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3469 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3470 short_channel_id: 5,
3473 cltv_expiry_delta: 0,
3474 htlc_minimum_msat: 0,
3475 htlc_maximum_msat: OptionalField::Present(200_000),
3477 fee_proportional_millionths: 0,
3478 excess_data: Vec::new()
3481 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3482 // Add 100 sats to the capacities of {12, 13}, because these channels
3483 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3484 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3485 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3486 short_channel_id: 12,
3489 cltv_expiry_delta: 0,
3490 htlc_minimum_msat: 0,
3491 htlc_maximum_msat: OptionalField::Present(200_000),
3493 fee_proportional_millionths: 0,
3494 excess_data: Vec::new()
3496 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3497 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3498 short_channel_id: 13,
3501 cltv_expiry_delta: 0,
3502 htlc_minimum_msat: 0,
3503 htlc_maximum_msat: OptionalField::Present(200_000),
3505 fee_proportional_millionths: 0,
3506 excess_data: Vec::new()
3509 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3510 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3511 short_channel_id: 6,
3514 cltv_expiry_delta: 0,
3515 htlc_minimum_msat: 0,
3516 htlc_maximum_msat: OptionalField::Present(100_000),
3518 fee_proportional_millionths: 0,
3519 excess_data: Vec::new()
3521 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3522 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3523 short_channel_id: 11,
3526 cltv_expiry_delta: 0,
3527 htlc_minimum_msat: 0,
3528 htlc_maximum_msat: OptionalField::Present(100_000),
3530 fee_proportional_millionths: 0,
3531 excess_data: Vec::new()
3534 // Path via {node7, node2} is channels {12, 13, 5}.
3535 // We already limited them to 200 sats (they are used twice for 100 sats).
3536 // Nothing to do here.
3539 // Attempt to route more than available results in a failure.
3540 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[3],
3541 Some(InvoiceFeatures::known()), None, &Vec::new(), 350_000, 42, Arc::clone(&logger), &scorer) {
3542 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3543 } else { panic!(); }
3547 // Now, attempt to route 300 sats (exact amount we can route).
3548 // Our algorithm should provide us with these 3 paths, 100 sats each.
3549 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[3],
3550 Some(InvoiceFeatures::known()), None, &Vec::new(), 300_000, 42, Arc::clone(&logger), &scorer).unwrap();
3551 assert_eq!(route.paths.len(), 3);
3553 let mut total_amount_paid_msat = 0;
3554 for path in &route.paths {
3555 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3556 total_amount_paid_msat += path.last().unwrap().fee_msat;
3558 assert_eq!(total_amount_paid_msat, 300_000);
3564 fn mpp_cheaper_route_test() {
3565 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3566 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3567 let scorer = Scorer::new(0);
3569 // This test checks that if we have two cheaper paths and one more expensive path,
3570 // so that liquidity-wise any 2 of 3 combination is sufficient,
3571 // two cheaper paths will be taken.
3572 // These paths have equal available liquidity.
3574 // We need a combination of 3 paths:
3575 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3576 // Note that these paths overlap (channels 5, 12, 13).
3577 // Each path will have 100 sats capacity, those channels which
3578 // are used twice will have 200 sats capacity.
3580 // Disable other potential paths.
3581 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3582 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3583 short_channel_id: 2,
3586 cltv_expiry_delta: 0,
3587 htlc_minimum_msat: 0,
3588 htlc_maximum_msat: OptionalField::Present(100_000),
3590 fee_proportional_millionths: 0,
3591 excess_data: Vec::new()
3593 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3594 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3595 short_channel_id: 7,
3598 cltv_expiry_delta: 0,
3599 htlc_minimum_msat: 0,
3600 htlc_maximum_msat: OptionalField::Present(100_000),
3602 fee_proportional_millionths: 0,
3603 excess_data: Vec::new()
3606 // Path via {node0, node2} is channels {1, 3, 5}.
3607 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3608 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3609 short_channel_id: 1,
3612 cltv_expiry_delta: 0,
3613 htlc_minimum_msat: 0,
3614 htlc_maximum_msat: OptionalField::Present(100_000),
3616 fee_proportional_millionths: 0,
3617 excess_data: Vec::new()
3619 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3620 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3621 short_channel_id: 3,
3624 cltv_expiry_delta: 0,
3625 htlc_minimum_msat: 0,
3626 htlc_maximum_msat: OptionalField::Present(100_000),
3628 fee_proportional_millionths: 0,
3629 excess_data: Vec::new()
3632 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3633 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3634 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3635 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3636 short_channel_id: 5,
3639 cltv_expiry_delta: 0,
3640 htlc_minimum_msat: 0,
3641 htlc_maximum_msat: OptionalField::Present(200_000),
3643 fee_proportional_millionths: 0,
3644 excess_data: Vec::new()
3647 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3648 // Add 100 sats to the capacities of {12, 13}, because these channels
3649 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3650 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3651 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3652 short_channel_id: 12,
3655 cltv_expiry_delta: 0,
3656 htlc_minimum_msat: 0,
3657 htlc_maximum_msat: OptionalField::Present(200_000),
3659 fee_proportional_millionths: 0,
3660 excess_data: Vec::new()
3662 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3663 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3664 short_channel_id: 13,
3667 cltv_expiry_delta: 0,
3668 htlc_minimum_msat: 0,
3669 htlc_maximum_msat: OptionalField::Present(200_000),
3671 fee_proportional_millionths: 0,
3672 excess_data: Vec::new()
3675 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3676 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3677 short_channel_id: 6,
3680 cltv_expiry_delta: 0,
3681 htlc_minimum_msat: 0,
3682 htlc_maximum_msat: OptionalField::Present(100_000),
3683 fee_base_msat: 1_000,
3684 fee_proportional_millionths: 0,
3685 excess_data: Vec::new()
3687 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3688 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3689 short_channel_id: 11,
3692 cltv_expiry_delta: 0,
3693 htlc_minimum_msat: 0,
3694 htlc_maximum_msat: OptionalField::Present(100_000),
3696 fee_proportional_millionths: 0,
3697 excess_data: Vec::new()
3700 // Path via {node7, node2} is channels {12, 13, 5}.
3701 // We already limited them to 200 sats (they are used twice for 100 sats).
3702 // Nothing to do here.
3705 // Now, attempt to route 180 sats.
3706 // Our algorithm should provide us with these 2 paths.
3707 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[3],
3708 Some(InvoiceFeatures::known()), None, &Vec::new(), 180_000, 42, Arc::clone(&logger), &scorer).unwrap();
3709 assert_eq!(route.paths.len(), 2);
3711 let mut total_value_transferred_msat = 0;
3712 let mut total_paid_msat = 0;
3713 for path in &route.paths {
3714 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3715 total_value_transferred_msat += path.last().unwrap().fee_msat;
3717 total_paid_msat += hop.fee_msat;
3720 // If we paid fee, this would be higher.
3721 assert_eq!(total_value_transferred_msat, 180_000);
3722 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
3723 assert_eq!(total_fees_paid, 0);
3728 fn fees_on_mpp_route_test() {
3729 // This test makes sure that MPP algorithm properly takes into account
3730 // fees charged on the channels, by making the fees impactful:
3731 // if the fee is not properly accounted for, the behavior is different.
3732 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3733 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3734 let scorer = Scorer::new(0);
3736 // We need a route consisting of 2 paths:
3737 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
3738 // We will route 200 sats, Each path will have 100 sats capacity.
3740 // This test is not particularly stable: e.g.,
3741 // there's a way to route via {node0, node2, node4}.
3742 // It works while pathfinding is deterministic, but can be broken otherwise.
3743 // It's fine to ignore this concern for now.
3745 // Disable other potential paths.
3746 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3747 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3748 short_channel_id: 2,
3751 cltv_expiry_delta: 0,
3752 htlc_minimum_msat: 0,
3753 htlc_maximum_msat: OptionalField::Present(100_000),
3755 fee_proportional_millionths: 0,
3756 excess_data: Vec::new()
3759 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3760 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3761 short_channel_id: 7,
3764 cltv_expiry_delta: 0,
3765 htlc_minimum_msat: 0,
3766 htlc_maximum_msat: OptionalField::Present(100_000),
3768 fee_proportional_millionths: 0,
3769 excess_data: Vec::new()
3772 // Path via {node0, node2} is channels {1, 3, 5}.
3773 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3774 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3775 short_channel_id: 1,
3778 cltv_expiry_delta: 0,
3779 htlc_minimum_msat: 0,
3780 htlc_maximum_msat: OptionalField::Present(100_000),
3782 fee_proportional_millionths: 0,
3783 excess_data: Vec::new()
3785 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3786 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3787 short_channel_id: 3,
3790 cltv_expiry_delta: 0,
3791 htlc_minimum_msat: 0,
3792 htlc_maximum_msat: OptionalField::Present(100_000),
3794 fee_proportional_millionths: 0,
3795 excess_data: Vec::new()
3798 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3799 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3800 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3801 short_channel_id: 5,
3804 cltv_expiry_delta: 0,
3805 htlc_minimum_msat: 0,
3806 htlc_maximum_msat: OptionalField::Present(100_000),
3808 fee_proportional_millionths: 0,
3809 excess_data: Vec::new()
3812 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3813 // All channels should be 100 sats capacity. But for the fee experiment,
3814 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
3815 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
3816 // 100 sats (and pay 150 sats in fees for the use of channel 6),
3817 // so no matter how large are other channels,
3818 // the whole path will be limited by 100 sats with just these 2 conditions:
3819 // - channel 12 capacity is 250 sats
3820 // - fee for channel 6 is 150 sats
3821 // Let's test this by enforcing these 2 conditions and removing other limits.
3822 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3823 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3824 short_channel_id: 12,
3827 cltv_expiry_delta: 0,
3828 htlc_minimum_msat: 0,
3829 htlc_maximum_msat: OptionalField::Present(250_000),
3831 fee_proportional_millionths: 0,
3832 excess_data: Vec::new()
3834 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3835 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3836 short_channel_id: 13,
3839 cltv_expiry_delta: 0,
3840 htlc_minimum_msat: 0,
3841 htlc_maximum_msat: OptionalField::Absent,
3843 fee_proportional_millionths: 0,
3844 excess_data: Vec::new()
3847 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3848 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3849 short_channel_id: 6,
3852 cltv_expiry_delta: 0,
3853 htlc_minimum_msat: 0,
3854 htlc_maximum_msat: OptionalField::Absent,
3855 fee_base_msat: 150_000,
3856 fee_proportional_millionths: 0,
3857 excess_data: Vec::new()
3859 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3860 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3861 short_channel_id: 11,
3864 cltv_expiry_delta: 0,
3865 htlc_minimum_msat: 0,
3866 htlc_maximum_msat: OptionalField::Absent,
3868 fee_proportional_millionths: 0,
3869 excess_data: Vec::new()
3873 // Attempt to route more than available results in a failure.
3874 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[3],
3875 Some(InvoiceFeatures::known()), None, &Vec::new(), 210_000, 42, Arc::clone(&logger), &scorer) {
3876 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3877 } else { panic!(); }
3881 // Now, attempt to route 200 sats (exact amount we can route).
3882 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[3],
3883 Some(InvoiceFeatures::known()), None, &Vec::new(), 200_000, 42, Arc::clone(&logger), &scorer).unwrap();
3884 assert_eq!(route.paths.len(), 2);
3886 let mut total_amount_paid_msat = 0;
3887 for path in &route.paths {
3888 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3889 total_amount_paid_msat += path.last().unwrap().fee_msat;
3891 assert_eq!(total_amount_paid_msat, 200_000);
3892 assert_eq!(route.get_total_fees(), 150_000);
3898 fn drop_lowest_channel_mpp_route_test() {
3899 // This test checks that low-capacity channel is dropped when after
3900 // path finding we realize that we found more capacity than we need.
3901 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3902 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3903 let scorer = Scorer::new(0);
3905 // We need a route consisting of 3 paths:
3906 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3908 // The first and the second paths should be sufficient, but the third should be
3909 // cheaper, so that we select it but drop later.
3911 // First, we set limits on these (previously unlimited) channels.
3912 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
3914 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
3915 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3916 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3917 short_channel_id: 1,
3920 cltv_expiry_delta: 0,
3921 htlc_minimum_msat: 0,
3922 htlc_maximum_msat: OptionalField::Present(100_000),
3924 fee_proportional_millionths: 0,
3925 excess_data: Vec::new()
3927 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3928 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3929 short_channel_id: 3,
3932 cltv_expiry_delta: 0,
3933 htlc_minimum_msat: 0,
3934 htlc_maximum_msat: OptionalField::Present(50_000),
3936 fee_proportional_millionths: 0,
3937 excess_data: Vec::new()
3940 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
3941 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3942 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3943 short_channel_id: 12,
3946 cltv_expiry_delta: 0,
3947 htlc_minimum_msat: 0,
3948 htlc_maximum_msat: OptionalField::Present(60_000),
3950 fee_proportional_millionths: 0,
3951 excess_data: Vec::new()
3953 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3954 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3955 short_channel_id: 13,
3958 cltv_expiry_delta: 0,
3959 htlc_minimum_msat: 0,
3960 htlc_maximum_msat: OptionalField::Present(60_000),
3962 fee_proportional_millionths: 0,
3963 excess_data: Vec::new()
3966 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
3967 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3968 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3969 short_channel_id: 2,
3972 cltv_expiry_delta: 0,
3973 htlc_minimum_msat: 0,
3974 htlc_maximum_msat: OptionalField::Present(20_000),
3976 fee_proportional_millionths: 0,
3977 excess_data: Vec::new()
3979 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3980 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3981 short_channel_id: 4,
3984 cltv_expiry_delta: 0,
3985 htlc_minimum_msat: 0,
3986 htlc_maximum_msat: OptionalField::Present(20_000),
3988 fee_proportional_millionths: 0,
3989 excess_data: Vec::new()
3993 // Attempt to route more than available results in a failure.
3994 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
3995 Some(InvoiceFeatures::known()), None, &Vec::new(), 150_000, 42, Arc::clone(&logger), &scorer) {
3996 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3997 } else { panic!(); }
4001 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
4002 // Our algorithm should provide us with these 3 paths.
4003 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
4004 Some(InvoiceFeatures::known()), None, &Vec::new(), 125_000, 42, Arc::clone(&logger), &scorer).unwrap();
4005 assert_eq!(route.paths.len(), 3);
4006 let mut total_amount_paid_msat = 0;
4007 for path in &route.paths {
4008 assert_eq!(path.len(), 2);
4009 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4010 total_amount_paid_msat += path.last().unwrap().fee_msat;
4012 assert_eq!(total_amount_paid_msat, 125_000);
4016 // Attempt to route without the last small cheap channel
4017 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
4018 Some(InvoiceFeatures::known()), None, &Vec::new(), 90_000, 42, Arc::clone(&logger), &scorer).unwrap();
4019 assert_eq!(route.paths.len(), 2);
4020 let mut total_amount_paid_msat = 0;
4021 for path in &route.paths {
4022 assert_eq!(path.len(), 2);
4023 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4024 total_amount_paid_msat += path.last().unwrap().fee_msat;
4026 assert_eq!(total_amount_paid_msat, 90_000);
4031 fn min_criteria_consistency() {
4032 // Test that we don't use an inconsistent metric between updating and walking nodes during
4033 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
4034 // was updated with a different criterion from the heap sorting, resulting in loops in
4035 // calculated paths. We test for that specific case here.
4037 // We construct a network that looks like this:
4039 // node2 -1(3)2- node3
4043 // node1 -1(5)2- node4 -1(1)2- node6
4049 // We create a loop on the side of our real path - our destination is node 6, with a
4050 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
4051 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
4052 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
4053 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
4054 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
4055 // "previous hop" being set to node 3, creating a loop in the path.
4056 let secp_ctx = Secp256k1::new();
4057 let logger = Arc::new(test_utils::TestLogger::new());
4058 let network_graph = NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash());
4059 let net_graph_msg_handler = NetGraphMsgHandler::new(network_graph, None, Arc::clone(&logger));
4060 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4061 let scorer = Scorer::new(0);
4063 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
4064 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4065 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4066 short_channel_id: 6,
4069 cltv_expiry_delta: (6 << 8) | 0,
4070 htlc_minimum_msat: 0,
4071 htlc_maximum_msat: OptionalField::Absent,
4073 fee_proportional_millionths: 0,
4074 excess_data: Vec::new()
4076 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
4078 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4079 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4080 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4081 short_channel_id: 5,
4084 cltv_expiry_delta: (5 << 8) | 0,
4085 htlc_minimum_msat: 0,
4086 htlc_maximum_msat: OptionalField::Absent,
4088 fee_proportional_millionths: 0,
4089 excess_data: Vec::new()
4091 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
4093 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
4094 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4095 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4096 short_channel_id: 4,
4099 cltv_expiry_delta: (4 << 8) | 0,
4100 htlc_minimum_msat: 0,
4101 htlc_maximum_msat: OptionalField::Absent,
4103 fee_proportional_millionths: 0,
4104 excess_data: Vec::new()
4106 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
4108 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
4109 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
4110 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4111 short_channel_id: 3,
4114 cltv_expiry_delta: (3 << 8) | 0,
4115 htlc_minimum_msat: 0,
4116 htlc_maximum_msat: OptionalField::Absent,
4118 fee_proportional_millionths: 0,
4119 excess_data: Vec::new()
4121 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
4123 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
4124 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4125 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4126 short_channel_id: 2,
4129 cltv_expiry_delta: (2 << 8) | 0,
4130 htlc_minimum_msat: 0,
4131 htlc_maximum_msat: OptionalField::Absent,
4133 fee_proportional_millionths: 0,
4134 excess_data: Vec::new()
4137 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
4138 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4139 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4140 short_channel_id: 1,
4143 cltv_expiry_delta: (1 << 8) | 0,
4144 htlc_minimum_msat: 100,
4145 htlc_maximum_msat: OptionalField::Absent,
4147 fee_proportional_millionths: 0,
4148 excess_data: Vec::new()
4150 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
4153 // Now ensure the route flows simply over nodes 1 and 4 to 6.
4154 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[6], None, None, &Vec::new(), 10_000, 42, Arc::clone(&logger), &scorer).unwrap();
4155 assert_eq!(route.paths.len(), 1);
4156 assert_eq!(route.paths[0].len(), 3);
4158 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
4159 assert_eq!(route.paths[0][0].short_channel_id, 6);
4160 assert_eq!(route.paths[0][0].fee_msat, 100);
4161 assert_eq!(route.paths[0][0].cltv_expiry_delta, (5 << 8) | 0);
4162 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(1));
4163 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(6));
4165 assert_eq!(route.paths[0][1].pubkey, nodes[4]);
4166 assert_eq!(route.paths[0][1].short_channel_id, 5);
4167 assert_eq!(route.paths[0][1].fee_msat, 0);
4168 assert_eq!(route.paths[0][1].cltv_expiry_delta, (1 << 8) | 0);
4169 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(4));
4170 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(5));
4172 assert_eq!(route.paths[0][2].pubkey, nodes[6]);
4173 assert_eq!(route.paths[0][2].short_channel_id, 1);
4174 assert_eq!(route.paths[0][2].fee_msat, 10_000);
4175 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
4176 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
4177 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(1));
4183 fn exact_fee_liquidity_limit() {
4184 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
4185 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
4186 // we calculated fees on a higher value, resulting in us ignoring such paths.
4187 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
4188 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
4189 let scorer = Scorer::new(0);
4191 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
4193 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4194 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4195 short_channel_id: 2,
4198 cltv_expiry_delta: 0,
4199 htlc_minimum_msat: 0,
4200 htlc_maximum_msat: OptionalField::Present(85_000),
4202 fee_proportional_millionths: 0,
4203 excess_data: Vec::new()
4206 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4207 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4208 short_channel_id: 12,
4211 cltv_expiry_delta: (4 << 8) | 1,
4212 htlc_minimum_msat: 0,
4213 htlc_maximum_msat: OptionalField::Present(270_000),
4215 fee_proportional_millionths: 1000000,
4216 excess_data: Vec::new()
4220 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
4221 // 200% fee charged channel 13 in the 1-to-2 direction.
4222 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2], None, None, &Vec::new(), 90_000, 42, Arc::clone(&logger), &scorer).unwrap();
4223 assert_eq!(route.paths.len(), 1);
4224 assert_eq!(route.paths[0].len(), 2);
4226 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4227 assert_eq!(route.paths[0][0].short_channel_id, 12);
4228 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4229 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
4230 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4231 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4233 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4234 assert_eq!(route.paths[0][1].short_channel_id, 13);
4235 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4236 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4237 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
4238 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4243 fn htlc_max_reduction_below_min() {
4244 // Test that if, while walking the graph, we reduce the value being sent to meet an
4245 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
4246 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
4247 // resulting in us thinking there is no possible path, even if other paths exist.
4248 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
4249 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4250 let scorer = Scorer::new(0);
4252 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
4253 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
4254 // then try to send 90_000.
4255 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4256 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4257 short_channel_id: 2,
4260 cltv_expiry_delta: 0,
4261 htlc_minimum_msat: 0,
4262 htlc_maximum_msat: OptionalField::Present(80_000),
4264 fee_proportional_millionths: 0,
4265 excess_data: Vec::new()
4267 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4268 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4269 short_channel_id: 4,
4272 cltv_expiry_delta: (4 << 8) | 1,
4273 htlc_minimum_msat: 90_000,
4274 htlc_maximum_msat: OptionalField::Absent,
4276 fee_proportional_millionths: 0,
4277 excess_data: Vec::new()
4281 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
4282 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
4283 // expensive) channels 12-13 path.
4284 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2], Some(InvoiceFeatures::known()), None, &Vec::new(), 90_000, 42, Arc::clone(&logger), &scorer).unwrap();
4285 assert_eq!(route.paths.len(), 1);
4286 assert_eq!(route.paths[0].len(), 2);
4288 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4289 assert_eq!(route.paths[0][0].short_channel_id, 12);
4290 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4291 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
4292 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4293 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4295 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4296 assert_eq!(route.paths[0][1].short_channel_id, 13);
4297 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4298 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4299 assert_eq!(route.paths[0][1].node_features.le_flags(), InvoiceFeatures::known().le_flags());
4300 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4305 fn multiple_direct_first_hops() {
4306 // Previously we'd only ever considered one first hop path per counterparty.
4307 // However, as we don't restrict users to one channel per peer, we really need to support
4308 // looking at all first hop paths.
4309 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
4310 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
4311 // route over multiple channels with the same first hop.
4312 let secp_ctx = Secp256k1::new();
4313 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4314 let logger = Arc::new(test_utils::TestLogger::new());
4315 let network_graph = NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash());
4316 let scorer = Scorer::new(0);
4319 let route = get_route(&our_id, &network_graph, &nodes[0], Some(InvoiceFeatures::known()), Some(&[
4320 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 200_000),
4321 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 10_000),
4322 ]), &[], 100_000, 42, Arc::clone(&logger), &scorer).unwrap();
4323 assert_eq!(route.paths.len(), 1);
4324 assert_eq!(route.paths[0].len(), 1);
4326 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
4327 assert_eq!(route.paths[0][0].short_channel_id, 3);
4328 assert_eq!(route.paths[0][0].fee_msat, 100_000);
4331 let route = get_route(&our_id, &network_graph, &nodes[0], Some(InvoiceFeatures::known()), Some(&[
4332 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 50_000),
4333 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 50_000),
4334 ]), &[], 100_000, 42, Arc::clone(&logger), &scorer).unwrap();
4335 assert_eq!(route.paths.len(), 2);
4336 assert_eq!(route.paths[0].len(), 1);
4337 assert_eq!(route.paths[1].len(), 1);
4339 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
4340 assert_eq!(route.paths[0][0].short_channel_id, 3);
4341 assert_eq!(route.paths[0][0].fee_msat, 50_000);
4343 assert_eq!(route.paths[1][0].pubkey, nodes[0]);
4344 assert_eq!(route.paths[1][0].short_channel_id, 2);
4345 assert_eq!(route.paths[1][0].fee_msat, 50_000);
4350 fn prefers_shorter_route_with_higher_fees() {
4351 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
4352 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4354 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
4355 let scorer = Scorer::new(0);
4356 let route = get_route(
4357 &our_id, &net_graph_msg_handler.network_graph, &nodes[6], None, None,
4358 &last_hops(&nodes).iter().collect::<Vec<_>>(), 100, 42, Arc::clone(&logger), &scorer
4360 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4362 assert_eq!(route.get_total_fees(), 100);
4363 assert_eq!(route.get_total_amount(), 100);
4364 assert_eq!(path, vec![2, 4, 6, 11, 8]);
4366 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
4367 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
4368 let scorer = Scorer::new(100);
4369 let route = get_route(
4370 &our_id, &net_graph_msg_handler.network_graph, &nodes[6], None, None,
4371 &last_hops(&nodes).iter().collect::<Vec<_>>(), 100, 42, Arc::clone(&logger), &scorer
4373 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4375 assert_eq!(route.get_total_fees(), 300);
4376 assert_eq!(route.get_total_amount(), 100);
4377 assert_eq!(path, vec![2, 4, 7, 10]);
4381 fn total_fees_single_path() {
4385 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
4386 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4387 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
4390 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
4391 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4392 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
4395 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
4396 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4397 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0
4402 assert_eq!(route.get_total_fees(), 250);
4403 assert_eq!(route.get_total_amount(), 225);
4407 fn total_fees_multi_path() {
4411 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
4412 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4413 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
4416 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
4417 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4418 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
4422 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
4423 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4424 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
4427 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
4428 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4429 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
4434 assert_eq!(route.get_total_fees(), 200);
4435 assert_eq!(route.get_total_amount(), 300);
4439 fn total_empty_route_no_panic() {
4440 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
4441 // would both panic if the route was completely empty. We test to ensure they return 0
4442 // here, even though its somewhat nonsensical as a route.
4443 let route = Route { paths: Vec::new() };
4445 assert_eq!(route.get_total_fees(), 0);
4446 assert_eq!(route.get_total_amount(), 0);
4449 #[cfg(not(feature = "no-std"))]
4450 pub(super) fn random_init_seed() -> u64 {
4451 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
4452 use core::hash::{BuildHasher, Hasher};
4453 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
4454 println!("Using seed of {}", seed);
4457 #[cfg(not(feature = "no-std"))]
4458 use util::ser::Readable;
4461 #[cfg(not(feature = "no-std"))]
4462 fn generate_routes() {
4463 let mut d = match super::test_utils::get_route_file() {
4470 let graph = NetworkGraph::read(&mut d).unwrap();
4471 let scorer = Scorer::new(0);
4473 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4474 let mut seed = random_init_seed() as usize;
4475 let nodes = graph.read_only().nodes().clone();
4476 'load_endpoints: for _ in 0..10 {
4478 seed = seed.overflowing_mul(0xdeadbeef).0;
4479 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4480 seed = seed.overflowing_mul(0xdeadbeef).0;
4481 let dst = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4482 let amt = seed as u64 % 200_000_000;
4483 if get_route(src, &graph, dst, None, None, &[], amt, 42, &test_utils::TestLogger::new(), &scorer).is_ok() {
4484 continue 'load_endpoints;
4491 #[cfg(not(feature = "no-std"))]
4492 fn generate_routes_mpp() {
4493 let mut d = match super::test_utils::get_route_file() {
4500 let graph = NetworkGraph::read(&mut d).unwrap();
4501 let scorer = Scorer::new(0);
4503 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4504 let mut seed = random_init_seed() as usize;
4505 let nodes = graph.read_only().nodes().clone();
4506 'load_endpoints: for _ in 0..10 {
4508 seed = seed.overflowing_mul(0xdeadbeef).0;
4509 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4510 seed = seed.overflowing_mul(0xdeadbeef).0;
4511 let dst = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4512 let amt = seed as u64 % 200_000_000;
4513 if get_route(src, &graph, dst, Some(InvoiceFeatures::known()), None, &[], amt, 42, &test_utils::TestLogger::new(), &scorer).is_ok() {
4514 continue 'load_endpoints;
4521 #[cfg(all(test, not(feature = "no-std")))]
4522 pub(crate) mod test_utils {
4524 /// Tries to open a network graph file, or panics with a URL to fetch it.
4525 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
4526 let res = File::open("net_graph-2021-05-31.bin") // By default we're run in RL/lightning
4527 .or_else(|_| File::open("lightning/net_graph-2021-05-31.bin")) // We may be run manually in RL/
4528 .or_else(|_| { // Fall back to guessing based on the binary location
4529 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
4530 let mut path = std::env::current_exe().unwrap();
4531 path.pop(); // lightning-...
4533 path.pop(); // debug
4534 path.pop(); // target
4535 path.push("lightning");
4536 path.push("net_graph-2021-05-31.bin");
4537 eprintln!("{}", path.to_str().unwrap());
4540 .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");
4541 #[cfg(require_route_graph_test)]
4542 return Ok(res.unwrap());
4543 #[cfg(not(require_route_graph_test))]
4548 #[cfg(all(test, feature = "unstable", not(feature = "no-std")))]
4551 use routing::scorer::Scorer;
4552 use util::logger::{Logger, Record};
4556 struct DummyLogger {}
4557 impl Logger for DummyLogger {
4558 fn log(&self, _record: &Record) {}
4562 fn generate_routes(bench: &mut Bencher) {
4563 let mut d = test_utils::get_route_file().unwrap();
4564 let graph = NetworkGraph::read(&mut d).unwrap();
4565 let nodes = graph.read_only().nodes().clone();
4566 let scorer = Scorer::new(0);
4568 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4569 let mut path_endpoints = Vec::new();
4570 let mut seed: usize = 0xdeadbeef;
4571 'load_endpoints: for _ in 0..100 {
4574 let src = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4576 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4577 let amt = seed as u64 % 1_000_000;
4578 if get_route(&src, &graph, &dst, None, None, &[], amt, 42, &DummyLogger{}, &scorer).is_ok() {
4579 path_endpoints.push((src, dst, amt));
4580 continue 'load_endpoints;
4585 // ...then benchmark finding paths between the nodes we learned.
4588 let (src, dst, amt) = path_endpoints[idx % path_endpoints.len()];
4589 assert!(get_route(&src, &graph, &dst, None, None, &[], amt, 42, &DummyLogger{}, &scorer).is_ok());
4595 fn generate_mpp_routes(bench: &mut Bencher) {
4596 let mut d = test_utils::get_route_file().unwrap();
4597 let graph = NetworkGraph::read(&mut d).unwrap();
4598 let nodes = graph.read_only().nodes().clone();
4599 let scorer = Scorer::new(0);
4601 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4602 let mut path_endpoints = Vec::new();
4603 let mut seed: usize = 0xdeadbeef;
4604 'load_endpoints: for _ in 0..100 {
4607 let src = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4609 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4610 let amt = seed as u64 % 1_000_000;
4611 if get_route(&src, &graph, &dst, Some(InvoiceFeatures::known()), None, &[], amt, 42, &DummyLogger{}, &scorer).is_ok() {
4612 path_endpoints.push((src, dst, amt));
4613 continue 'load_endpoints;
4618 // ...then benchmark finding paths between the nodes we learned.
4621 let (src, dst, amt) = path_endpoints[idx % path_endpoints.len()];
4622 assert!(get_route(&src, &graph, &dst, Some(InvoiceFeatures::known()), None, &[], amt, 42, &DummyLogger{}, &scorer).is_ok());