1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! The top-level routing/network map tracking logic lives here.
12 //! You probably want to create a NetGraphMsgHandler and use that as your RoutingMessageHandler and then
13 //! interrogate it to get routes for your own payments.
15 use bitcoin::secp256k1::key::PublicKey;
17 use ln::channelmanager::ChannelDetails;
18 use ln::features::{ChannelFeatures, InvoiceFeatures, NodeFeatures};
19 use ln::msgs::{DecodeError, ErrorAction, LightningError, MAX_VALUE_MSAT};
20 use routing::network_graph::{NetworkGraph, RoutingFees};
21 use util::ser::{Writeable, Readable};
22 use util::logger::Logger;
26 use alloc::collections::BinaryHeap;
31 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
33 /// The node_id of the node at this hop.
34 pub pubkey: PublicKey,
35 /// The node_announcement features of the node at this hop. For the last hop, these may be
36 /// amended to match the features present in the invoice this node generated.
37 pub node_features: NodeFeatures,
38 /// The channel that should be used from the previous hop to reach this node.
39 pub short_channel_id: u64,
40 /// The channel_announcement features of the channel that should be used from the previous hop
41 /// to reach this node.
42 pub channel_features: ChannelFeatures,
43 /// The fee taken on this hop (for paying for the use of the *next* channel in the path).
44 /// For the last hop, this should be the full value of the payment (might be more than
45 /// requested if we had to match htlc_minimum_msat).
47 /// The CLTV delta added for this hop. For the last hop, this should be the full CLTV value
48 /// expected at the destination, in excess of the current block height.
49 pub cltv_expiry_delta: u32,
52 impl_writeable_tlv_based!(RouteHop, {
53 (0, pubkey, required),
54 (2, node_features, required),
55 (4, short_channel_id, required),
56 (6, channel_features, required),
57 (8, fee_msat, required),
58 (10, cltv_expiry_delta, required),
61 /// A route directs a payment from the sender (us) to the recipient. If the recipient supports MPP,
62 /// it can take multiple paths. Each path is composed of one or more hops through the network.
63 #[derive(Clone, Hash, PartialEq, Eq)]
65 /// The list of routes taken for a single (potentially-)multi-part payment. The pubkey of the
66 /// last RouteHop in each path must be the same.
67 /// Each entry represents a list of hops, NOT INCLUDING our own, where the last hop is the
68 /// destination. Thus, this must always be at least length one. While the maximum length of any
69 /// given path is variable, keeping the length of any path to less than 20 should currently
70 /// ensure it is viable.
71 pub paths: Vec<Vec<RouteHop>>,
75 /// Returns the total amount of fees paid on this [`Route`].
77 /// This doesn't include any extra payment made to the recipient, which can happen in excess of
78 /// the amount passed to [`get_route`]'s `final_value_msat`.
79 pub fn get_total_fees(&self) -> u64 {
80 // Do not count last hop of each path since that's the full value of the payment
81 return self.paths.iter()
82 .flat_map(|path| path.split_last().map(|(_, path_prefix)| path_prefix).unwrap_or(&[]))
83 .map(|hop| &hop.fee_msat)
87 /// Returns the total amount paid on this [`Route`], excluding the fees.
88 pub fn get_total_amount(&self) -> u64 {
89 return self.paths.iter()
90 .map(|path| path.split_last().map(|(hop, _)| hop.fee_msat).unwrap_or(0))
95 const SERIALIZATION_VERSION: u8 = 1;
96 const MIN_SERIALIZATION_VERSION: u8 = 1;
98 impl Writeable for Route {
99 fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
100 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
101 (self.paths.len() as u64).write(writer)?;
102 for hops in self.paths.iter() {
103 (hops.len() as u8).write(writer)?;
104 for hop in hops.iter() {
108 write_tlv_fields!(writer, {});
113 impl Readable for Route {
114 fn read<R: io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
115 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
116 let path_count: u64 = Readable::read(reader)?;
117 let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
118 for _ in 0..path_count {
119 let hop_count: u8 = Readable::read(reader)?;
120 let mut hops = Vec::with_capacity(hop_count as usize);
121 for _ in 0..hop_count {
122 hops.push(Readable::read(reader)?);
126 read_tlv_fields!(reader, {});
131 /// A list of hops along a payment path terminating with a channel to the recipient.
132 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
133 pub struct RouteHint(pub Vec<RouteHintHop>);
135 /// A channel descriptor for a hop along a payment path.
136 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
137 pub struct RouteHintHop {
138 /// The node_id of the non-target end of the route
139 pub src_node_id: PublicKey,
140 /// The short_channel_id of this channel
141 pub short_channel_id: u64,
142 /// The fees which must be paid to use this channel
143 pub fees: RoutingFees,
144 /// The difference in CLTV values between this node and the next node.
145 pub cltv_expiry_delta: u16,
146 /// The minimum value, in msat, which must be relayed to the next hop.
147 pub htlc_minimum_msat: Option<u64>,
148 /// The maximum value in msat available for routing with a single HTLC.
149 pub htlc_maximum_msat: Option<u64>,
152 #[derive(Eq, PartialEq)]
153 struct RouteGraphNode {
155 lowest_fee_to_peer_through_node: u64,
156 lowest_fee_to_node: u64,
157 // The maximum value a yet-to-be-constructed payment path might flow through this node.
158 // This value is upper-bounded by us by:
159 // - how much is needed for a path being constructed
160 // - how much value can channels following this node (up to the destination) can contribute,
161 // considering their capacity and fees
162 value_contribution_msat: u64,
163 /// The effective htlc_minimum_msat at this hop. If a later hop on the path had a higher HTLC
164 /// minimum, we use it, plus the fees required at each earlier hop to meet it.
165 path_htlc_minimum_msat: u64,
168 impl cmp::Ord for RouteGraphNode {
169 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
170 let other_score = cmp::max(other.lowest_fee_to_peer_through_node, other.path_htlc_minimum_msat);
171 let self_score = cmp::max(self.lowest_fee_to_peer_through_node, self.path_htlc_minimum_msat);
172 other_score.cmp(&self_score).then_with(|| other.pubkey.serialize().cmp(&self.pubkey.serialize()))
176 impl cmp::PartialOrd for RouteGraphNode {
177 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
178 Some(self.cmp(other))
182 struct DummyDirectionalChannelInfo {
183 cltv_expiry_delta: u32,
184 htlc_minimum_msat: u64,
185 htlc_maximum_msat: Option<u64>,
189 /// It's useful to keep track of the hops associated with the fees required to use them,
190 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
191 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
192 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
193 #[derive(Clone, Debug)]
194 struct PathBuildingHop<'a> {
195 // The RouteHintHop fields which will eventually be used if this hop is used in a final Route.
196 // Note that node_features is calculated separately after our initial graph walk.
198 short_channel_id: u64,
199 channel_features: &'a ChannelFeatures,
201 cltv_expiry_delta: u32,
203 /// Minimal fees required to route to the source node of the current hop via any of its inbound channels.
204 src_lowest_inbound_fees: RoutingFees,
205 /// Fees of the channel used in this hop.
206 channel_fees: RoutingFees,
207 /// All the fees paid *after* this channel on the way to the destination
208 next_hops_fee_msat: u64,
209 /// Fee paid for the use of the current channel (see channel_fees).
210 /// The value will be actually deducted from the counterparty balance on the previous link.
211 hop_use_fee_msat: u64,
212 /// Used to compare channels when choosing the for routing.
213 /// Includes paying for the use of a hop and the following hops, as well as
214 /// an estimated cost of reaching this hop.
215 /// Might get stale when fees are recomputed. Primarily for internal use.
217 /// This is useful for update_value_and_recompute_fees to make sure
218 /// we don't fall below the minimum. Should not be updated manually and
219 /// generally should not be accessed.
220 htlc_minimum_msat: u64,
221 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
222 /// walk and may be invalid thereafter.
223 path_htlc_minimum_msat: u64,
224 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
225 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
226 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
227 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
228 /// avoid processing them again.
230 #[cfg(any(test, feature = "fuzztarget"))]
231 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
232 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
233 // value_contribution_msat, which requires tracking it here. See comments below where it is
234 // used for more info.
235 value_contribution_msat: u64,
238 // Instantiated with a list of hops with correct data in them collected during path finding,
239 // an instance of this struct should be further modified only via given methods.
241 struct PaymentPath<'a> {
242 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
245 impl<'a> PaymentPath<'a> {
246 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
247 fn get_value_msat(&self) -> u64 {
248 self.hops.last().unwrap().0.fee_msat
251 fn get_total_fee_paid_msat(&self) -> u64 {
252 if self.hops.len() < 1 {
256 // Can't use next_hops_fee_msat because it gets outdated.
257 for (i, (hop, _)) in self.hops.iter().enumerate() {
258 if i != self.hops.len() - 1 {
259 result += hop.fee_msat;
265 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
266 // to change fees may result in an inconsistency.
268 // Sometimes we call this function right after constructing a path which is inconsistent in
269 // that it the value being transferred has decreased while we were doing path finding, leading
270 // to the fees being paid not lining up with the actual limits.
272 // Note that this function is not aware of the available_liquidity limit, and thus does not
273 // support increasing the value being transferred.
274 fn update_value_and_recompute_fees(&mut self, value_msat: u64) {
275 assert!(value_msat <= self.hops.last().unwrap().0.fee_msat);
277 let mut total_fee_paid_msat = 0 as u64;
278 for i in (0..self.hops.len()).rev() {
279 let last_hop = i == self.hops.len() - 1;
281 // For non-last-hop, this value will represent the fees paid on the current hop. It
282 // will consist of the fees for the use of the next hop, and extra fees to match
283 // htlc_minimum_msat of the current channel. Last hop is handled separately.
284 let mut cur_hop_fees_msat = 0;
286 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
289 let mut cur_hop = &mut self.hops.get_mut(i).unwrap().0;
290 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
291 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
292 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
293 // set it too high just to maliciously take more fees by exploiting this
294 // match htlc_minimum_msat logic.
295 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
296 if let Some(extra_fees_msat) = cur_hop.htlc_minimum_msat.checked_sub(cur_hop_transferred_amount_msat) {
297 // Note that there is a risk that *previous hops* (those closer to us, as we go
298 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
300 // This might make us end up with a broken route, although this should be super-rare
301 // in practice, both because of how healthy channels look like, and how we pick
302 // channels in add_entry.
303 // Also, this can't be exploited more heavily than *announce a free path and fail
305 cur_hop_transferred_amount_msat += extra_fees_msat;
306 total_fee_paid_msat += extra_fees_msat;
307 cur_hop_fees_msat += extra_fees_msat;
311 // Final hop is a special case: it usually has just value_msat (by design), but also
312 // it still could overpay for the htlc_minimum_msat.
313 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
315 // Propagate updated fees for the use of the channels to one hop back, where they
316 // will be actually paid (fee_msat). The last hop is handled above separately.
317 cur_hop.fee_msat = cur_hop_fees_msat;
320 // Fee for the use of the current hop which will be deducted on the previous hop.
321 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
322 // this channel is free for us.
324 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.channel_fees) {
325 cur_hop.hop_use_fee_msat = new_fee;
326 total_fee_paid_msat += new_fee;
328 // It should not be possible because this function is called only to reduce the
329 // value. In that case, compute_fee was already called with the same fees for
330 // larger amount and there was no overflow.
338 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
339 let proportional_fee_millions =
340 amount_msat.checked_mul(channel_fees.proportional_millionths as u64);
341 if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
342 (channel_fees.base_msat as u64).checked_add(part / 1_000_000) }) {
346 // This function may be (indirectly) called without any verification,
347 // with channel_fees provided by a caller. We should handle it gracefully.
352 /// Gets a keysend route from us (payer) to the given target node (payee). This is needed because
353 /// keysend payments do not have an invoice from which to pull the payee's supported features, which
354 /// makes it tricky to otherwise supply the `payee_features` parameter of `get_route`.
355 pub fn get_keysend_route<L: Deref>(our_node_id: &PublicKey, network: &NetworkGraph, payee:
356 &PublicKey, first_hops: Option<&[&ChannelDetails]>, last_hops: &[&RouteHint],
357 final_value_msat: u64, final_cltv: u32, logger: L) -> Result<Route,
358 LightningError> where L::Target: Logger {
359 let invoice_features = InvoiceFeatures::for_keysend();
360 get_route(our_node_id, network, payee, Some(invoice_features), first_hops, last_hops,
361 final_value_msat, final_cltv, logger)
364 /// Gets a route from us (payer) to the given target node (payee).
366 /// If the payee provided features in their invoice, they should be provided via payee_features.
367 /// Without this, MPP will only be used if the payee's features are available in the network graph.
369 /// Private routing paths between a public node and the target may be included in `last_hops`.
370 /// Currently, only the last hop in each path is considered.
372 /// If some channels aren't announced, it may be useful to fill in a first_hops with the
373 /// results from a local ChannelManager::list_usable_channels() call. If it is filled in, our
374 /// view of our local channels (from net_graph_msg_handler) will be ignored, and only those
375 /// in first_hops will be used.
377 /// Panics if first_hops contains channels without short_channel_ids
378 /// (ChannelManager::list_usable_channels will never include such channels).
380 /// The fees on channels from us to next-hops are ignored (as they are assumed to all be
381 /// equal), however the enabled/disabled bit on such channels as well as the
382 /// htlc_minimum_msat/htlc_maximum_msat *are* checked as they may change based on the receiving node.
383 pub fn get_route<L: Deref>(our_node_id: &PublicKey, network: &NetworkGraph, payee: &PublicKey, payee_features: Option<InvoiceFeatures>, first_hops: Option<&[&ChannelDetails]>,
384 last_hops: &[&RouteHint], final_value_msat: u64, final_cltv: u32, logger: L) -> Result<Route, LightningError> where L::Target: Logger {
385 // TODO: Obviously *only* using total fee cost sucks. We should consider weighting by
386 // uptime/success in using a node in the past.
387 if *payee == *our_node_id {
388 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
391 if final_value_msat > MAX_VALUE_MSAT {
392 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
395 if final_value_msat == 0 {
396 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
399 for route in last_hops.iter() {
400 for hop in &route.0 {
401 if hop.src_node_id == *payee {
402 return Err(LightningError{err: "Last hop cannot have a payee as a source.".to_owned(), action: ErrorAction::IgnoreError});
407 // The general routing idea is the following:
408 // 1. Fill first/last hops communicated by the caller.
409 // 2. Attempt to construct a path from payer to payee for transferring
410 // any ~sufficient (described later) value.
411 // If succeed, remember which channels were used and how much liquidity they have available,
412 // so that future paths don't rely on the same liquidity.
413 // 3. Prooceed to the next step if:
414 // - we hit the recommended target value;
415 // - OR if we could not construct a new path. Any next attempt will fail too.
416 // Otherwise, repeat step 2.
417 // 4. See if we managed to collect paths which aggregately are able to transfer target value
418 // (not recommended value). If yes, proceed. If not, fail routing.
419 // 5. Randomly combine paths into routes having enough to fulfill the payment. (TODO: knapsack)
420 // 6. Of all the found paths, select only those with the lowest total fee.
421 // 7. The last path in every selected route is likely to be more than we need.
422 // Reduce its value-to-transfer and recompute fees.
423 // 8. Choose the best route by the lowest total fee.
425 // As for the actual search algorithm,
426 // we do a payee-to-payer pseudo-Dijkstra's sorting by each node's distance from the payee
427 // plus the minimum per-HTLC fee to get from it to another node (aka "shitty pseudo-A*").
429 // We are not a faithful Dijkstra's implementation because we can change values which impact
430 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
431 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) then
432 // the value we are currently attempting to send over a path, we simply reduce the value being
433 // sent along the path for any hops after that channel. This may imply that later fees (which
434 // we've already tabulated) are lower because a smaller value is passing through the channels
435 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
436 // channels which were selected earlier (and which may still be used for other paths without a
437 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
440 // One potentially problematic case for this algorithm would be if there are many
441 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
442 // graph walking), we may never find a path which is not liquidity-limited and has lower
443 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
444 // Because we only consider paths with at least 5% of the total value being sent, the damage
445 // from such a case should be limited, however this could be further reduced in the future by
446 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
447 // limits for the purposes of fee calculation.
449 // Alternatively, we could store more detailed path information in the heap (targets, below)
450 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
451 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
452 // and practically (as we would need to store dynamically-allocated path information in heap
453 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
454 // results of such an algorithm would likely be biased towards lower-value paths.
456 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
457 // outside of our current search value, running a path search more times to gather candidate
458 // paths at different values. While this may be acceptable, further path searches may increase
459 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
460 // graph for candidate paths, calculating the maximum value which can realistically be sent at
461 // the same time, remaining generic across different payment values.
463 // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
464 // to use as the A* heuristic beyond just the cost to get one node further than the current
467 let network_graph = network.read_only();
468 let network_channels = network_graph.channels();
469 let network_nodes = network_graph.nodes();
470 let dummy_directional_info = DummyDirectionalChannelInfo { // used for first_hops routes
471 cltv_expiry_delta: 0,
472 htlc_minimum_msat: 0,
473 htlc_maximum_msat: None,
476 proportional_millionths: 0,
480 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
481 // it. If the payee supports it they're supposed to include it in the invoice, so that should
483 let allow_mpp = if let Some(features) = &payee_features {
484 features.supports_basic_mpp()
485 } else if let Some(node) = network_nodes.get(&payee) {
486 if let Some(node_info) = node.announcement_info.as_ref() {
487 node_info.features.supports_basic_mpp()
492 // Prepare the data we'll use for payee-to-payer search by
493 // inserting first hops suggested by the caller as targets.
494 // Our search will then attempt to reach them while traversing from the payee node.
495 let mut first_hop_targets: HashMap<_, (_, ChannelFeatures, _, NodeFeatures)> =
496 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
497 if let Some(hops) = first_hops {
499 let short_channel_id = chan.short_channel_id.expect("first_hops should be filled in with usable channels, not pending ones");
500 if chan.counterparty.node_id == *our_node_id {
501 return Err(LightningError{err: "First hop cannot have our_node_id as a destination.".to_owned(), action: ErrorAction::IgnoreError});
503 first_hop_targets.insert(chan.counterparty.node_id, (short_channel_id, chan.counterparty.features.to_context(), chan.outbound_capacity_msat, chan.counterparty.features.to_context()));
505 if first_hop_targets.is_empty() {
506 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
510 let empty_channel_features = ChannelFeatures::empty();
512 // The main heap containing all candidate next-hops sorted by their score (max(A* fee,
513 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
514 // adding duplicate entries when we find a better path to a given node.
515 let mut targets = BinaryHeap::new();
517 // Map from node_id to information about the best current path to that node, including feerate
519 let mut dist = HashMap::with_capacity(network_nodes.len());
521 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
522 // indicating that we may wish to try again with a higher value, potentially paying to meet an
523 // htlc_minimum with extra fees while still finding a cheaper path.
524 let mut hit_minimum_limit;
526 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
527 // We start with a path_value of the exact amount we want, and if that generates a route we may
528 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
529 // amount we want in total across paths, selecting the best subset at the end.
530 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
531 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
532 let mut path_value_msat = final_value_msat;
534 // We don't want multiple paths (as per MPP) share liquidity of the same channels.
535 // This map allows paths to be aware of the channel use by other paths in the same call.
536 // This would help to make a better path finding decisions and not "overbook" channels.
537 // It is unaware of the directions (except for `outbound_capacity_msat` in `first_hops`).
538 let mut bookkeeped_channels_liquidity_available_msat = HashMap::with_capacity(network_nodes.len());
540 // Keeping track of how much value we already collected across other paths. Helps to decide:
541 // - how much a new path should be transferring (upper bound);
542 // - whether a channel should be disregarded because
543 // it's available liquidity is too small comparing to how much more we need to collect;
544 // - when we want to stop looking for new paths.
545 let mut already_collected_value_msat = 0;
547 log_trace!(logger, "Building path from {} (payee) to {} (us/payer) for value {} msat.", payee, our_node_id, final_value_msat);
549 macro_rules! add_entry {
550 // Adds entry which goes from $src_node_id to $dest_node_id
551 // over the channel with id $chan_id with fees described in
552 // $directional_info.
553 // $next_hops_fee_msat represents the fees paid for using all the channel *after* this one,
554 // since that value has to be transferred over this channel.
555 // Returns whether this channel caused an update to `targets`.
556 ( $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,
557 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr ) => { {
558 // We "return" whether we updated the path at the end, via this:
559 let mut did_add_update_path_to_src_node = false;
560 // Channels to self should not be used. This is more of belt-and-suspenders, because in
561 // practice these cases should be caught earlier:
562 // - for regular channels at channel announcement (TODO)
563 // - for first and last hops early in get_route
564 if $src_node_id != $dest_node_id.clone() {
565 let available_liquidity_msat = bookkeeped_channels_liquidity_available_msat.entry($chan_id.clone()).or_insert_with(|| {
566 let mut initial_liquidity_available_msat = None;
567 if let Some(capacity_sats) = $capacity_sats {
568 initial_liquidity_available_msat = Some(capacity_sats * 1000);
571 if let Some(htlc_maximum_msat) = $directional_info.htlc_maximum_msat {
572 if let Some(available_msat) = initial_liquidity_available_msat {
573 initial_liquidity_available_msat = Some(cmp::min(available_msat, htlc_maximum_msat));
575 initial_liquidity_available_msat = Some(htlc_maximum_msat);
579 match initial_liquidity_available_msat {
580 Some(available_msat) => available_msat,
581 // We assume channels with unknown balance have
582 // a capacity of 0.0025 BTC (or 250_000 sats).
583 None => 250_000 * 1000
587 // It is tricky to substract $next_hops_fee_msat from available liquidity here.
588 // It may be misleading because we might later choose to reduce the value transferred
589 // over these channels, and the channel which was insufficient might become sufficient.
590 // Worst case: we drop a good channel here because it can't cover the high following
591 // fees caused by one expensive channel, but then this channel could have been used
592 // if the amount being transferred over this path is lower.
593 // We do this for now, but this is a subject for removal.
594 if let Some(available_value_contribution_msat) = available_liquidity_msat.checked_sub($next_hops_fee_msat) {
596 // Routing Fragmentation Mitigation heuristic:
598 // Routing fragmentation across many payment paths increases the overall routing
599 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
600 // Taking too many smaller paths also increases the chance of payment failure.
601 // Thus to avoid this effect, we require from our collected links to provide
602 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
604 // This requirement is currently 5% of the remaining-to-be-collected value.
605 // This means as we successfully advance in our collection,
606 // the absolute liquidity contribution is lowered,
607 // thus increasing the number of potential channels to be selected.
609 // Derive the minimal liquidity contribution with a ratio of 20 (5%, rounded up)
610 // or 100% if we're not allowed to do multipath payments.
611 let minimal_value_contribution_msat: u64 = if allow_mpp {
612 (recommended_value_msat - already_collected_value_msat + 19) / 20
616 // Verify the liquidity offered by this channel complies to the minimal contribution.
617 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
619 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
620 // Includes paying fees for the use of the following channels.
621 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
622 Some(result) => result,
623 // Can't overflow due to how the values were computed right above.
624 None => unreachable!(),
626 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
627 let over_path_minimum_msat = amount_to_transfer_over_msat >= $directional_info.htlc_minimum_msat &&
628 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
630 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
631 // bother considering this channel.
632 // Since we're choosing amount_to_transfer_over_msat as maximum possible, it can
633 // be only reduced later (not increased), so this channel should just be skipped
634 // as not sufficient.
635 if !over_path_minimum_msat {
636 hit_minimum_limit = true;
637 } else if contributes_sufficient_value {
638 // Note that low contribution here (limited by available_liquidity_msat)
639 // might violate htlc_minimum_msat on the hops which are next along the
640 // payment path (upstream to the payee). To avoid that, we recompute path
641 // path fees knowing the final path contribution after constructing it.
642 let path_htlc_minimum_msat = match compute_fees($next_hops_path_htlc_minimum_msat, $directional_info.fees)
643 .map(|fee_msat| fee_msat.checked_add($next_hops_path_htlc_minimum_msat)) {
644 Some(Some(value_msat)) => cmp::max(value_msat, $directional_info.htlc_minimum_msat),
645 _ => u64::max_value()
647 let hm_entry = dist.entry(&$src_node_id);
648 let old_entry = hm_entry.or_insert_with(|| {
649 // If there was previously no known way to access
650 // the source node (recall it goes payee-to-payer) of $chan_id, first add
651 // a semi-dummy record just to compute the fees to reach the source node.
652 // This will affect our decision on selecting $chan_id
653 // as a way to reach the $dest_node_id.
654 let mut fee_base_msat = u32::max_value();
655 let mut fee_proportional_millionths = u32::max_value();
656 if let Some(Some(fees)) = network_nodes.get(&$src_node_id).map(|node| node.lowest_inbound_channel_fees) {
657 fee_base_msat = fees.base_msat;
658 fee_proportional_millionths = fees.proportional_millionths;
661 pubkey: $dest_node_id.clone(),
663 channel_features: $chan_features,
665 cltv_expiry_delta: 0,
666 src_lowest_inbound_fees: RoutingFees {
667 base_msat: fee_base_msat,
668 proportional_millionths: fee_proportional_millionths,
670 channel_fees: $directional_info.fees,
671 next_hops_fee_msat: u64::max_value(),
672 hop_use_fee_msat: u64::max_value(),
673 total_fee_msat: u64::max_value(),
674 htlc_minimum_msat: $directional_info.htlc_minimum_msat,
675 path_htlc_minimum_msat,
676 was_processed: false,
677 #[cfg(any(test, feature = "fuzztarget"))]
678 value_contribution_msat,
682 #[allow(unused_mut)] // We only use the mut in cfg(test)
683 let mut should_process = !old_entry.was_processed;
684 #[cfg(any(test, feature = "fuzztarget"))]
686 // In test/fuzzing builds, we do extra checks to make sure the skipping
687 // of already-seen nodes only happens in cases we expect (see below).
688 if !should_process { should_process = true; }
692 let mut hop_use_fee_msat = 0;
693 let mut total_fee_msat = $next_hops_fee_msat;
695 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
696 // will have the same effective-fee
697 if $src_node_id != *our_node_id {
698 match compute_fees(amount_to_transfer_over_msat, $directional_info.fees) {
699 // max_value means we'll always fail
700 // the old_entry.total_fee_msat > total_fee_msat check
701 None => total_fee_msat = u64::max_value(),
703 hop_use_fee_msat = fee_msat;
704 total_fee_msat += hop_use_fee_msat;
705 // When calculating the lowest inbound fees to a node, we
706 // calculate fees here not based on the actual value we think
707 // will flow over this channel, but on the minimum value that
708 // we'll accept flowing over it. The minimum accepted value
709 // is a constant through each path collection run, ensuring
710 // consistent basis. Otherwise we may later find a
711 // different path to the source node that is more expensive,
712 // but which we consider to be cheaper because we are capacity
713 // constrained and the relative fee becomes lower.
714 match compute_fees(minimal_value_contribution_msat, old_entry.src_lowest_inbound_fees)
715 .map(|a| a.checked_add(total_fee_msat)) {
720 total_fee_msat = u64::max_value();
727 let new_graph_node = RouteGraphNode {
728 pubkey: $src_node_id,
729 lowest_fee_to_peer_through_node: total_fee_msat,
730 lowest_fee_to_node: $next_hops_fee_msat as u64 + hop_use_fee_msat,
731 value_contribution_msat: value_contribution_msat,
732 path_htlc_minimum_msat,
735 // Update the way of reaching $src_node_id with the given $chan_id (from $dest_node_id),
736 // if this way is cheaper than the already known
737 // (considering the cost to "reach" this channel from the route destination,
738 // the cost of using this channel,
739 // and the cost of routing to the source node of this channel).
740 // Also, consider that htlc_minimum_msat_difference, because we might end up
741 // paying it. Consider the following exploit:
742 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
743 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
744 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
745 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
747 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
748 // but it may require additional tracking - we don't want to double-count
749 // the fees included in $next_hops_path_htlc_minimum_msat, but also
750 // can't use something that may decrease on future hops.
751 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat);
752 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat);
754 if !old_entry.was_processed && new_cost < old_cost {
755 targets.push(new_graph_node);
756 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
757 old_entry.hop_use_fee_msat = hop_use_fee_msat;
758 old_entry.total_fee_msat = total_fee_msat;
759 old_entry.pubkey = $dest_node_id.clone();
760 old_entry.short_channel_id = $chan_id.clone();
761 old_entry.channel_features = $chan_features;
762 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
763 old_entry.cltv_expiry_delta = $directional_info.cltv_expiry_delta as u32;
764 old_entry.channel_fees = $directional_info.fees;
765 old_entry.htlc_minimum_msat = $directional_info.htlc_minimum_msat;
766 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
767 #[cfg(any(test, feature = "fuzztarget"))]
769 old_entry.value_contribution_msat = value_contribution_msat;
771 did_add_update_path_to_src_node = true;
772 } else if old_entry.was_processed && new_cost < old_cost {
773 #[cfg(any(test, feature = "fuzztarget"))]
775 // If we're skipping processing a node which was previously
776 // processed even though we found another path to it with a
777 // cheaper fee, check that it was because the second path we
778 // found (which we are processing now) has a lower value
779 // contribution due to an HTLC minimum limit.
781 // e.g. take a graph with two paths from node 1 to node 2, one
782 // through channel A, and one through channel B. Channel A and
783 // B are both in the to-process heap, with their scores set by
784 // a higher htlc_minimum than fee.
785 // Channel A is processed first, and the channels onwards from
786 // node 1 are added to the to-process heap. Thereafter, we pop
787 // Channel B off of the heap, note that it has a much more
788 // restrictive htlc_maximum_msat, and recalculate the fees for
789 // all of node 1's channels using the new, reduced, amount.
791 // This would be bogus - we'd be selecting a higher-fee path
792 // with a lower htlc_maximum_msat instead of the one we'd
793 // already decided to use.
794 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
795 debug_assert!(value_contribution_msat < old_entry.value_contribution_msat);
802 did_add_update_path_to_src_node
806 let empty_node_features = NodeFeatures::empty();
807 // Find ways (channels with destination) to reach a given node and store them
808 // in the corresponding data structures (routing graph etc).
809 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
810 // meaning how much will be paid in fees after this node (to the best of our knowledge).
811 // This data can later be helpful to optimize routing (pay lower fees).
812 macro_rules! add_entries_to_cheapest_to_target_node {
813 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr, $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr ) => {
814 let skip_node = if let Some(elem) = dist.get_mut($node_id) {
815 let was_processed = elem.was_processed;
816 elem.was_processed = true;
819 // Entries are added to dist in add_entry!() when there is a channel from a node.
820 // Because there are no channels from payee, it will not have a dist entry at this point.
821 // If we're processing any other node, it is always be the result of a channel from it.
822 assert_eq!($node_id, payee);
827 if first_hops.is_some() {
828 if let Some(&(ref first_hop, ref features, ref outbound_capacity_msat, _)) = first_hop_targets.get(&$node_id) {
829 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);
833 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
839 if !features.requires_unknown_bits() {
840 for chan_id in $node.channels.iter() {
841 let chan = network_channels.get(chan_id).unwrap();
842 if !chan.features.requires_unknown_bits() {
843 if chan.node_one == *$node_id {
844 // ie $node is one, ie next hop in A* is two, via the two_to_one channel
845 if first_hops.is_none() || chan.node_two != *our_node_id {
846 if let Some(two_to_one) = chan.two_to_one.as_ref() {
847 if two_to_one.enabled {
848 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);
853 if first_hops.is_none() || chan.node_one != *our_node_id {
854 if let Some(one_to_two) = chan.one_to_two.as_ref() {
855 if one_to_two.enabled {
856 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);
868 let mut payment_paths = Vec::<PaymentPath>::new();
870 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
871 'paths_collection: loop {
872 // For every new path, start from scratch, except
873 // bookkeeped_channels_liquidity_available_msat, which will improve
874 // the further iterations of path finding. Also don't erase first_hop_targets.
877 hit_minimum_limit = false;
879 // If first hop is a private channel and the only way to reach the payee, this is the only
880 // place where it could be added.
881 if first_hops.is_some() {
882 if let Some(&(ref first_hop, ref features, ref outbound_capacity_msat, _)) = first_hop_targets.get(&payee) {
883 add_entry!(first_hop, *our_node_id, payee, dummy_directional_info, Some(outbound_capacity_msat / 1000), features, 0, path_value_msat, 0);
887 // Add the payee as a target, so that the payee-to-payer
888 // search algorithm knows what to start with.
889 match network_nodes.get(payee) {
890 // The payee is not in our network graph, so nothing to add here.
891 // There is still a chance of reaching them via last_hops though,
892 // so don't yet fail the payment here.
893 // If not, targets.pop() will not even let us enter the loop in step 2.
896 add_entries_to_cheapest_to_target_node!(node, payee, 0, path_value_msat, 0);
901 // If a caller provided us with last hops, add them to routing targets. Since this happens
902 // earlier than general path finding, they will be somewhat prioritized, although currently
903 // it matters only if the fees are exactly the same.
904 for route in last_hops.iter().filter(|route| !route.0.is_empty()) {
905 let first_hop_in_route = &(route.0)[0];
906 let have_hop_src_in_graph =
907 // Only add the hops in this route to our candidate set if either
908 // we have a direct channel to the first hop or the first hop is
909 // in the regular network graph.
910 first_hop_targets.get(&first_hop_in_route.src_node_id).is_some() ||
911 network_nodes.get(&first_hop_in_route.src_node_id).is_some();
912 if have_hop_src_in_graph {
913 // We start building the path from reverse, i.e., from payee
914 // to the first RouteHintHop in the path.
915 let hop_iter = route.0.iter().rev();
916 let prev_hop_iter = core::iter::once(payee).chain(
917 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
918 let mut hop_used = true;
919 let mut aggregate_next_hops_fee_msat: u64 = 0;
920 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
922 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
923 // BOLT 11 doesn't allow inclusion of features for the last hop hints, which
924 // really sucks, cause we're gonna need that eventually.
925 let hop_htlc_minimum_msat: u64 = hop.htlc_minimum_msat.unwrap_or(0);
927 let directional_info = DummyDirectionalChannelInfo {
928 cltv_expiry_delta: hop.cltv_expiry_delta as u32,
929 htlc_minimum_msat: hop_htlc_minimum_msat,
930 htlc_maximum_msat: hop.htlc_maximum_msat,
934 let reqd_channel_cap = if let Some (val) = final_value_msat.checked_add(match idx {
936 _ => aggregate_next_hops_fee_msat.checked_add(999).unwrap_or(u64::max_value())
937 }) { Some( val / 1000 ) } else { break; }; // converting from msat or breaking if max ~ infinity
940 // We assume that the recipient only included route hints for routes which had
941 // sufficient value to route `final_value_msat`. Note that in the case of "0-value"
942 // invoices where the invoice does not specify value this may not be the case, but
943 // better to include the hints than not.
944 if !add_entry!(hop.short_channel_id, hop.src_node_id, prev_hop_id, directional_info, reqd_channel_cap, &empty_channel_features, aggregate_next_hops_fee_msat, path_value_msat, aggregate_next_hops_path_htlc_minimum_msat) {
945 // If this hop was not used then there is no use checking the preceding hops
946 // in the RouteHint. We can break by just searching for a direct channel between
947 // last checked hop and first_hop_targets
951 // Searching for a direct channel between last checked hop and first_hop_targets
952 if let Some(&(ref first_hop, ref features, ref outbound_capacity_msat, _)) = first_hop_targets.get(&prev_hop_id) {
953 add_entry!(first_hop, *our_node_id , prev_hop_id, dummy_directional_info, Some(outbound_capacity_msat / 1000), features, aggregate_next_hops_fee_msat, path_value_msat, aggregate_next_hops_path_htlc_minimum_msat);
960 // In the next values of the iterator, the aggregate fees already reflects
961 // the sum of value sent from payer (final_value_msat) and routing fees
962 // for the last node in the RouteHint. We need to just add the fees to
963 // route through the current node so that the preceeding node (next iteration)
965 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
966 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
967 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
969 let hop_htlc_minimum_msat_inc = if let Some(val) = compute_fees(aggregate_next_hops_path_htlc_minimum_msat, hop.fees) { val } else { break; };
970 let hops_path_htlc_minimum = aggregate_next_hops_path_htlc_minimum_msat
971 .checked_add(hop_htlc_minimum_msat_inc);
972 aggregate_next_hops_path_htlc_minimum_msat = if let Some(val) = hops_path_htlc_minimum { cmp::max(hop_htlc_minimum_msat, val) } else { break; };
974 if idx == route.0.len() - 1 {
975 // The last hop in this iterator is the first hop in
976 // overall RouteHint.
977 // If this hop connects to a node with which we have a direct channel,
978 // ignore the network graph and, if the last hop was added, add our
979 // direct channel to the candidate set.
981 // Note that we *must* check if the last hop was added as `add_entry`
982 // always assumes that the third argument is a node to which we have a
984 if let Some(&(ref first_hop, ref features, ref outbound_capacity_msat, _)) = first_hop_targets.get(&hop.src_node_id) {
985 add_entry!(first_hop, *our_node_id , hop.src_node_id, dummy_directional_info, Some(outbound_capacity_msat / 1000), features, aggregate_next_hops_fee_msat, path_value_msat, aggregate_next_hops_path_htlc_minimum_msat);
992 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
994 // At this point, targets are filled with the data from first and
995 // last hops communicated by the caller, and the payment receiver.
996 let mut found_new_path = false;
999 // If this loop terminates due the exhaustion of targets, two situations are possible:
1000 // - not enough outgoing liquidity:
1001 // 0 < already_collected_value_msat < final_value_msat
1002 // - enough outgoing liquidity:
1003 // final_value_msat <= already_collected_value_msat < recommended_value_msat
1004 // Both these cases (and other cases except reaching recommended_value_msat) mean that
1005 // paths_collection will be stopped because found_new_path==false.
1006 // This is not necessarily a routing failure.
1007 'path_construction: while let Some(RouteGraphNode { pubkey, lowest_fee_to_node, value_contribution_msat, path_htlc_minimum_msat, .. }) = targets.pop() {
1009 // Since we're going payee-to-payer, hitting our node as a target means we should stop
1010 // traversing the graph and arrange the path out of what we found.
1011 if pubkey == *our_node_id {
1012 let mut new_entry = dist.remove(&our_node_id).unwrap();
1013 let mut ordered_hops = vec!((new_entry.clone(), NodeFeatures::empty()));
1016 if let Some(&(_, _, _, ref features)) = first_hop_targets.get(&ordered_hops.last().unwrap().0.pubkey) {
1017 ordered_hops.last_mut().unwrap().1 = features.clone();
1018 } else if let Some(node) = network_nodes.get(&ordered_hops.last().unwrap().0.pubkey) {
1019 if let Some(node_info) = node.announcement_info.as_ref() {
1020 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
1022 ordered_hops.last_mut().unwrap().1 = NodeFeatures::empty();
1025 // We should be able to fill in features for everything except the last
1026 // hop, if the last hop was provided via a BOLT 11 invoice (though we
1027 // should be able to extend it further as BOLT 11 does have feature
1028 // flags for the last hop node itself).
1029 assert!(ordered_hops.last().unwrap().0.pubkey == *payee);
1032 // Means we succesfully traversed from the payer to the payee, now
1033 // save this path for the payment route. Also, update the liquidity
1034 // remaining on the used hops, so that we take them into account
1035 // while looking for more paths.
1036 if ordered_hops.last().unwrap().0.pubkey == *payee {
1040 new_entry = match dist.remove(&ordered_hops.last().unwrap().0.pubkey) {
1041 Some(payment_hop) => payment_hop,
1042 // We can't arrive at None because, if we ever add an entry to targets,
1043 // we also fill in the entry in dist (see add_entry!).
1044 None => unreachable!(),
1046 // We "propagate" the fees one hop backward (topologically) here,
1047 // so that fees paid for a HTLC forwarding on the current channel are
1048 // associated with the previous channel (where they will be subtracted).
1049 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
1050 ordered_hops.last_mut().unwrap().0.cltv_expiry_delta = new_entry.cltv_expiry_delta;
1051 ordered_hops.push((new_entry.clone(), NodeFeatures::empty()));
1053 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
1054 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
1055 ordered_hops.last_mut().unwrap().0.cltv_expiry_delta = final_cltv;
1057 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: {:?}",
1058 ordered_hops.len(), value_contribution_msat, ordered_hops);
1060 let mut payment_path = PaymentPath {hops: ordered_hops};
1062 // We could have possibly constructed a slightly inconsistent path: since we reduce
1063 // value being transferred along the way, we could have violated htlc_minimum_msat
1064 // on some channels we already passed (assuming dest->source direction). Here, we
1065 // recompute the fees again, so that if that's the case, we match the currently
1066 // underpaid htlc_minimum_msat with fees.
1067 payment_path.update_value_and_recompute_fees(cmp::min(value_contribution_msat, final_value_msat));
1069 // Since a path allows to transfer as much value as
1070 // the smallest channel it has ("bottleneck"), we should recompute
1071 // the fees so sender HTLC don't overpay fees when traversing
1072 // larger channels than the bottleneck. This may happen because
1073 // when we were selecting those channels we were not aware how much value
1074 // this path will transfer, and the relative fee for them
1075 // might have been computed considering a larger value.
1076 // Remember that we used these channels so that we don't rely
1077 // on the same liquidity in future paths.
1078 let mut prevented_redundant_path_selection = false;
1079 for (payment_hop, _) in payment_path.hops.iter() {
1080 let channel_liquidity_available_msat = bookkeeped_channels_liquidity_available_msat.get_mut(&payment_hop.short_channel_id).unwrap();
1081 let mut spent_on_hop_msat = value_contribution_msat;
1082 let next_hops_fee_msat = payment_hop.next_hops_fee_msat;
1083 spent_on_hop_msat += next_hops_fee_msat;
1084 if spent_on_hop_msat == *channel_liquidity_available_msat {
1085 // If this path used all of this channel's available liquidity, we know
1086 // this path will not be selected again in the next loop iteration.
1087 prevented_redundant_path_selection = true;
1089 *channel_liquidity_available_msat -= spent_on_hop_msat;
1091 if !prevented_redundant_path_selection {
1092 // If we weren't capped by hitting a liquidity limit on a channel in the path,
1093 // we'll probably end up picking the same path again on the next iteration.
1094 // Decrease the available liquidity of a hop in the middle of the path.
1095 let victim_scid = payment_path.hops[(payment_path.hops.len() - 1) / 2].0.short_channel_id;
1096 log_trace!(logger, "Disabling channel {} for future path building iterations to avoid duplicates.", victim_scid);
1097 let victim_liquidity = bookkeeped_channels_liquidity_available_msat.get_mut(&victim_scid).unwrap();
1098 *victim_liquidity = 0;
1101 // Track the total amount all our collected paths allow to send so that we:
1102 // - know when to stop looking for more paths
1103 // - know which of the hops are useless considering how much more sats we need
1104 // (contributes_sufficient_value)
1105 already_collected_value_msat += value_contribution_msat;
1107 payment_paths.push(payment_path);
1108 found_new_path = true;
1109 break 'path_construction;
1112 // If we found a path back to the payee, we shouldn't try to process it again. This is
1113 // the equivalent of the `elem.was_processed` check in
1114 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
1115 if pubkey == *payee { continue 'path_construction; }
1117 // Otherwise, since the current target node is not us,
1118 // keep "unrolling" the payment graph from payee to payer by
1119 // finding a way to reach the current target from the payer side.
1120 match network_nodes.get(&pubkey) {
1123 add_entries_to_cheapest_to_target_node!(node, &pubkey, lowest_fee_to_node, value_contribution_msat, path_htlc_minimum_msat);
1129 // If we don't support MPP, no use trying to gather more value ever.
1130 break 'paths_collection;
1134 // Stop either when the recommended value is reached or if no new path was found in this
1136 // In the latter case, making another path finding attempt won't help,
1137 // because we deterministically terminated the search due to low liquidity.
1138 if already_collected_value_msat >= recommended_value_msat || !found_new_path {
1139 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
1140 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
1141 break 'paths_collection;
1142 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
1143 // Further, if this was our first walk of the graph, and we weren't limited by an
1144 // htlc_minimum_msat, return immediately because this path should suffice. If we were
1145 // limited by an htlc_minimum_msat value, find another path with a higher value,
1146 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
1147 // still keeping a lower total fee than this path.
1148 if !hit_minimum_limit {
1149 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
1150 break 'paths_collection;
1152 log_trace!(logger, "Collected our payment amount on the first pass, but running again to collect extra paths with a potentially higher limit.");
1153 path_value_msat = recommended_value_msat;
1158 if payment_paths.len() == 0 {
1159 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1162 if already_collected_value_msat < final_value_msat {
1163 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1166 // Sort by total fees and take the best paths.
1167 payment_paths.sort_by_key(|path| path.get_total_fee_paid_msat());
1168 if payment_paths.len() > 50 {
1169 payment_paths.truncate(50);
1172 // Draw multiple sufficient routes by randomly combining the selected paths.
1173 let mut drawn_routes = Vec::new();
1174 for i in 0..payment_paths.len() {
1175 let mut cur_route = Vec::<PaymentPath>::new();
1176 let mut aggregate_route_value_msat = 0;
1179 // TODO: real random shuffle
1180 // Currently just starts with i_th and goes up to i-1_th in a looped way.
1181 let cur_payment_paths = [&payment_paths[i..], &payment_paths[..i]].concat();
1184 for payment_path in cur_payment_paths {
1185 cur_route.push(payment_path.clone());
1186 aggregate_route_value_msat += payment_path.get_value_msat();
1187 if aggregate_route_value_msat > final_value_msat {
1188 // Last path likely overpaid. Substract it from the most expensive
1189 // (in terms of proportional fee) path in this route and recompute fees.
1190 // This might be not the most economically efficient way, but fewer paths
1191 // also makes routing more reliable.
1192 let mut overpaid_value_msat = aggregate_route_value_msat - final_value_msat;
1194 // First, drop some expensive low-value paths entirely if possible.
1195 // Sort by value so that we drop many really-low values first, since
1196 // fewer paths is better: the payment is less likely to fail.
1197 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1198 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1199 cur_route.sort_by_key(|path| path.get_value_msat());
1200 // We should make sure that at least 1 path left.
1201 let mut paths_left = cur_route.len();
1202 cur_route.retain(|path| {
1203 if paths_left == 1 {
1206 let mut keep = true;
1207 let path_value_msat = path.get_value_msat();
1208 if path_value_msat <= overpaid_value_msat {
1210 overpaid_value_msat -= path_value_msat;
1216 if overpaid_value_msat == 0 {
1220 assert!(cur_route.len() > 0);
1223 // Now, substract the overpaid value from the most-expensive path.
1224 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1225 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1226 cur_route.sort_by_key(|path| { path.hops.iter().map(|hop| hop.0.channel_fees.proportional_millionths as u64).sum::<u64>() });
1227 let expensive_payment_path = cur_route.first_mut().unwrap();
1228 // We already dropped all the small channels above, meaning all the
1229 // remaining channels are larger than remaining overpaid_value_msat.
1230 // Thus, this can't be negative.
1231 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
1232 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
1236 drawn_routes.push(cur_route);
1240 // Select the best route by lowest total fee.
1241 drawn_routes.sort_by_key(|paths| paths.iter().map(|path| path.get_total_fee_paid_msat()).sum::<u64>());
1242 let mut selected_paths = Vec::<Vec<RouteHop>>::new();
1243 for payment_path in drawn_routes.first().unwrap() {
1244 selected_paths.push(payment_path.hops.iter().map(|(payment_hop, node_features)| {
1246 pubkey: payment_hop.pubkey,
1247 node_features: node_features.clone(),
1248 short_channel_id: payment_hop.short_channel_id,
1249 channel_features: payment_hop.channel_features.clone(),
1250 fee_msat: payment_hop.fee_msat,
1251 cltv_expiry_delta: payment_hop.cltv_expiry_delta,
1256 if let Some(features) = &payee_features {
1257 for path in selected_paths.iter_mut() {
1258 path.last_mut().unwrap().node_features = features.to_context();
1262 let route = Route { paths: selected_paths };
1263 log_info!(logger, "Got route to {}: {}", payee, log_route!(route));
1269 use routing::router::{get_route, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees};
1270 use routing::network_graph::{NetworkGraph, NetGraphMsgHandler};
1271 use chain::transaction::OutPoint;
1272 use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
1273 use ln::msgs::{ErrorAction, LightningError, OptionalField, UnsignedChannelAnnouncement, ChannelAnnouncement, RoutingMessageHandler,
1274 NodeAnnouncement, UnsignedNodeAnnouncement, ChannelUpdate, UnsignedChannelUpdate};
1275 use ln::channelmanager;
1276 use util::test_utils;
1277 use util::ser::Writeable;
1279 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
1280 use bitcoin::hashes::Hash;
1281 use bitcoin::network::constants::Network;
1282 use bitcoin::blockdata::constants::genesis_block;
1283 use bitcoin::blockdata::script::Builder;
1284 use bitcoin::blockdata::opcodes;
1285 use bitcoin::blockdata::transaction::TxOut;
1289 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
1290 use bitcoin::secp256k1::{Secp256k1, All};
1293 use sync::{self, Arc};
1295 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
1296 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
1297 channelmanager::ChannelDetails {
1298 channel_id: [0; 32],
1299 counterparty: channelmanager::ChannelCounterparty {
1302 unspendable_punishment_reserve: 0,
1303 forwarding_info: None,
1305 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
1307 channel_value_satoshis: 0,
1309 outbound_capacity_msat,
1310 inbound_capacity_msat: 42,
1311 unspendable_punishment_reserve: None,
1312 confirmations_required: None,
1313 force_close_spend_delay: None,
1314 is_outbound: true, is_funding_locked: true,
1315 is_usable: true, is_public: true,
1319 // Using the same keys for LN and BTC ids
1321 net_graph_msg_handler: &NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1322 secp_ctx: &Secp256k1<All>, node_1_privkey: &SecretKey, node_2_privkey: &SecretKey, features: ChannelFeatures, short_channel_id: u64
1324 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1325 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1327 let unsigned_announcement = UnsignedChannelAnnouncement {
1329 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1333 bitcoin_key_1: node_id_1,
1334 bitcoin_key_2: node_id_2,
1335 excess_data: Vec::new(),
1338 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1339 let valid_announcement = ChannelAnnouncement {
1340 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1341 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1342 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1343 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1344 contents: unsigned_announcement.clone(),
1346 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1347 Ok(res) => assert!(res),
1353 net_graph_msg_handler: &NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1354 secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, update: UnsignedChannelUpdate
1356 let msghash = hash_to_message!(&Sha256dHash::hash(&update.encode()[..])[..]);
1357 let valid_channel_update = ChannelUpdate {
1358 signature: secp_ctx.sign(&msghash, node_privkey),
1359 contents: update.clone()
1362 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1363 Ok(res) => assert!(res),
1368 fn add_or_update_node(
1369 net_graph_msg_handler: &NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1370 secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, features: NodeFeatures, timestamp: u32
1372 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
1373 let unsigned_announcement = UnsignedNodeAnnouncement {
1379 addresses: Vec::new(),
1380 excess_address_data: Vec::new(),
1381 excess_data: Vec::new(),
1383 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1384 let valid_announcement = NodeAnnouncement {
1385 signature: secp_ctx.sign(&msghash, node_privkey),
1386 contents: unsigned_announcement.clone()
1389 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1395 fn get_nodes(secp_ctx: &Secp256k1<All>) -> (SecretKey, PublicKey, Vec<SecretKey>, Vec<PublicKey>) {
1396 let privkeys: Vec<SecretKey> = (2..10).map(|i| {
1397 SecretKey::from_slice(&hex::decode(format!("{:02}", i).repeat(32)).unwrap()[..]).unwrap()
1400 let pubkeys = privkeys.iter().map(|secret| PublicKey::from_secret_key(&secp_ctx, secret)).collect();
1402 let our_privkey = SecretKey::from_slice(&hex::decode("01".repeat(32)).unwrap()[..]).unwrap();
1403 let our_id = PublicKey::from_secret_key(&secp_ctx, &our_privkey);
1405 (our_privkey, our_id, privkeys, pubkeys)
1408 fn id_to_feature_flags(id: u8) -> Vec<u8> {
1409 // Set the feature flags to the id'th odd (ie non-required) feature bit so that we can
1410 // test for it later.
1411 let idx = (id - 1) * 2 + 1;
1413 vec![1 << (idx - 8*3), 0, 0, 0]
1414 } else if idx > 8*2 {
1415 vec![1 << (idx - 8*2), 0, 0]
1416 } else if idx > 8*1 {
1417 vec![1 << (idx - 8*1), 0]
1423 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>) {
1424 let secp_ctx = Secp256k1::new();
1425 let logger = Arc::new(test_utils::TestLogger::new());
1426 let chain_monitor = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1427 let network_graph = NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash());
1428 let net_graph_msg_handler = NetGraphMsgHandler::new(network_graph, None, Arc::clone(&logger));
1429 // Build network from our_id to node6:
1431 // -1(1)2- node0 -1(3)2-
1433 // our_id -1(12)2- node7 -1(13)2--- node2
1435 // -1(2)2- node1 -1(4)2-
1438 // chan1 1-to-2: disabled
1439 // chan1 2-to-1: enabled, 0 fee
1441 // chan2 1-to-2: enabled, ignored fee
1442 // chan2 2-to-1: enabled, 0 fee
1444 // chan3 1-to-2: enabled, 0 fee
1445 // chan3 2-to-1: enabled, 100 msat fee
1447 // chan4 1-to-2: enabled, 100% fee
1448 // chan4 2-to-1: enabled, 0 fee
1450 // chan12 1-to-2: enabled, ignored fee
1451 // chan12 2-to-1: enabled, 0 fee
1453 // chan13 1-to-2: enabled, 200% fee
1454 // chan13 2-to-1: enabled, 0 fee
1457 // -1(5)2- node3 -1(8)2--
1461 // node2--1(6)2- node4 -1(9)2--- node6 (not in global route map)
1463 // -1(7)2- node5 -1(10)2-
1465 // Channels 5, 8, 9 and 10 are private channels.
1467 // chan5 1-to-2: enabled, 100 msat fee
1468 // chan5 2-to-1: enabled, 0 fee
1470 // chan6 1-to-2: enabled, 0 fee
1471 // chan6 2-to-1: enabled, 0 fee
1473 // chan7 1-to-2: enabled, 100% fee
1474 // chan7 2-to-1: enabled, 0 fee
1476 // chan8 1-to-2: enabled, variable fee (0 then 1000 msat)
1477 // chan8 2-to-1: enabled, 0 fee
1479 // chan9 1-to-2: enabled, 1001 msat fee
1480 // chan9 2-to-1: enabled, 0 fee
1482 // chan10 1-to-2: enabled, 0 fee
1483 // chan10 2-to-1: enabled, 0 fee
1485 // chan11 1-to-2: enabled, 0 fee
1486 // chan11 2-to-1: enabled, 0 fee
1488 let (our_privkey, _, privkeys, _) = get_nodes(&secp_ctx);
1490 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[0], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
1491 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1492 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1493 short_channel_id: 1,
1496 cltv_expiry_delta: 0,
1497 htlc_minimum_msat: 0,
1498 htlc_maximum_msat: OptionalField::Absent,
1500 fee_proportional_millionths: 0,
1501 excess_data: Vec::new()
1504 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
1506 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
1507 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1508 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1509 short_channel_id: 2,
1512 cltv_expiry_delta: u16::max_value(),
1513 htlc_minimum_msat: 0,
1514 htlc_maximum_msat: OptionalField::Absent,
1515 fee_base_msat: u32::max_value(),
1516 fee_proportional_millionths: u32::max_value(),
1517 excess_data: Vec::new()
1519 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1520 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1521 short_channel_id: 2,
1524 cltv_expiry_delta: 0,
1525 htlc_minimum_msat: 0,
1526 htlc_maximum_msat: OptionalField::Absent,
1528 fee_proportional_millionths: 0,
1529 excess_data: Vec::new()
1532 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
1534 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[7], ChannelFeatures::from_le_bytes(id_to_feature_flags(12)), 12);
1535 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1536 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1537 short_channel_id: 12,
1540 cltv_expiry_delta: u16::max_value(),
1541 htlc_minimum_msat: 0,
1542 htlc_maximum_msat: OptionalField::Absent,
1543 fee_base_msat: u32::max_value(),
1544 fee_proportional_millionths: u32::max_value(),
1545 excess_data: Vec::new()
1547 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1548 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1549 short_channel_id: 12,
1552 cltv_expiry_delta: 0,
1553 htlc_minimum_msat: 0,
1554 htlc_maximum_msat: OptionalField::Absent,
1556 fee_proportional_millionths: 0,
1557 excess_data: Vec::new()
1560 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], NodeFeatures::from_le_bytes(id_to_feature_flags(8)), 0);
1562 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
1563 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1564 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1565 short_channel_id: 3,
1568 cltv_expiry_delta: (3 << 8) | 1,
1569 htlc_minimum_msat: 0,
1570 htlc_maximum_msat: OptionalField::Absent,
1572 fee_proportional_millionths: 0,
1573 excess_data: Vec::new()
1575 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1576 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1577 short_channel_id: 3,
1580 cltv_expiry_delta: (3 << 8) | 2,
1581 htlc_minimum_msat: 0,
1582 htlc_maximum_msat: OptionalField::Absent,
1584 fee_proportional_millionths: 0,
1585 excess_data: Vec::new()
1588 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
1589 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1590 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1591 short_channel_id: 4,
1594 cltv_expiry_delta: (4 << 8) | 1,
1595 htlc_minimum_msat: 0,
1596 htlc_maximum_msat: OptionalField::Absent,
1598 fee_proportional_millionths: 1000000,
1599 excess_data: Vec::new()
1601 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1602 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1603 short_channel_id: 4,
1606 cltv_expiry_delta: (4 << 8) | 2,
1607 htlc_minimum_msat: 0,
1608 htlc_maximum_msat: OptionalField::Absent,
1610 fee_proportional_millionths: 0,
1611 excess_data: Vec::new()
1614 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(13)), 13);
1615 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1616 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1617 short_channel_id: 13,
1620 cltv_expiry_delta: (13 << 8) | 1,
1621 htlc_minimum_msat: 0,
1622 htlc_maximum_msat: OptionalField::Absent,
1624 fee_proportional_millionths: 2000000,
1625 excess_data: Vec::new()
1627 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1628 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1629 short_channel_id: 13,
1632 cltv_expiry_delta: (13 << 8) | 2,
1633 htlc_minimum_msat: 0,
1634 htlc_maximum_msat: OptionalField::Absent,
1636 fee_proportional_millionths: 0,
1637 excess_data: Vec::new()
1640 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
1642 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
1643 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1644 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1645 short_channel_id: 6,
1648 cltv_expiry_delta: (6 << 8) | 1,
1649 htlc_minimum_msat: 0,
1650 htlc_maximum_msat: OptionalField::Absent,
1652 fee_proportional_millionths: 0,
1653 excess_data: Vec::new()
1655 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1656 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1657 short_channel_id: 6,
1660 cltv_expiry_delta: (6 << 8) | 2,
1661 htlc_minimum_msat: 0,
1662 htlc_maximum_msat: OptionalField::Absent,
1664 fee_proportional_millionths: 0,
1665 excess_data: Vec::new(),
1668 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(11)), 11);
1669 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1670 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1671 short_channel_id: 11,
1674 cltv_expiry_delta: (11 << 8) | 1,
1675 htlc_minimum_msat: 0,
1676 htlc_maximum_msat: OptionalField::Absent,
1678 fee_proportional_millionths: 0,
1679 excess_data: Vec::new()
1681 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
1682 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1683 short_channel_id: 11,
1686 cltv_expiry_delta: (11 << 8) | 2,
1687 htlc_minimum_msat: 0,
1688 htlc_maximum_msat: OptionalField::Absent,
1690 fee_proportional_millionths: 0,
1691 excess_data: Vec::new()
1694 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(5)), 0);
1696 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
1698 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[5], ChannelFeatures::from_le_bytes(id_to_feature_flags(7)), 7);
1699 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1700 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1701 short_channel_id: 7,
1704 cltv_expiry_delta: (7 << 8) | 1,
1705 htlc_minimum_msat: 0,
1706 htlc_maximum_msat: OptionalField::Absent,
1708 fee_proportional_millionths: 1000000,
1709 excess_data: Vec::new()
1711 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[5], UnsignedChannelUpdate {
1712 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1713 short_channel_id: 7,
1716 cltv_expiry_delta: (7 << 8) | 2,
1717 htlc_minimum_msat: 0,
1718 htlc_maximum_msat: OptionalField::Absent,
1720 fee_proportional_millionths: 0,
1721 excess_data: Vec::new()
1724 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[5], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
1726 (secp_ctx, net_graph_msg_handler, chain_monitor, logger)
1730 fn simple_route_test() {
1731 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1732 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1734 // Simple route to 2 via 1
1736 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)) {
1737 assert_eq!(err, "Cannot send a payment of 0 msat");
1738 } else { panic!(); }
1740 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2], None, None, &Vec::new(), 100, 42, Arc::clone(&logger)).unwrap();
1741 assert_eq!(route.paths[0].len(), 2);
1743 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
1744 assert_eq!(route.paths[0][0].short_channel_id, 2);
1745 assert_eq!(route.paths[0][0].fee_msat, 100);
1746 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
1747 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
1748 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
1750 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1751 assert_eq!(route.paths[0][1].short_channel_id, 4);
1752 assert_eq!(route.paths[0][1].fee_msat, 100);
1753 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1754 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1755 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
1759 fn invalid_first_hop_test() {
1760 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1761 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1763 // Simple route to 2 via 1
1765 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
1767 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)) {
1768 assert_eq!(err, "First hop cannot have our_node_id as a destination.");
1769 } else { panic!(); }
1771 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2], None, None, &Vec::new(), 100, 42, Arc::clone(&logger)).unwrap();
1772 assert_eq!(route.paths[0].len(), 2);
1776 fn htlc_minimum_test() {
1777 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1778 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1780 // Simple route to 2 via 1
1782 // Disable other paths
1783 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1784 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1785 short_channel_id: 12,
1787 flags: 2, // to disable
1788 cltv_expiry_delta: 0,
1789 htlc_minimum_msat: 0,
1790 htlc_maximum_msat: OptionalField::Absent,
1792 fee_proportional_millionths: 0,
1793 excess_data: Vec::new()
1795 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1796 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1797 short_channel_id: 3,
1799 flags: 2, // to disable
1800 cltv_expiry_delta: 0,
1801 htlc_minimum_msat: 0,
1802 htlc_maximum_msat: OptionalField::Absent,
1804 fee_proportional_millionths: 0,
1805 excess_data: Vec::new()
1807 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1808 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1809 short_channel_id: 13,
1811 flags: 2, // to disable
1812 cltv_expiry_delta: 0,
1813 htlc_minimum_msat: 0,
1814 htlc_maximum_msat: OptionalField::Absent,
1816 fee_proportional_millionths: 0,
1817 excess_data: Vec::new()
1819 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1820 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1821 short_channel_id: 6,
1823 flags: 2, // to disable
1824 cltv_expiry_delta: 0,
1825 htlc_minimum_msat: 0,
1826 htlc_maximum_msat: OptionalField::Absent,
1828 fee_proportional_millionths: 0,
1829 excess_data: Vec::new()
1831 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1832 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1833 short_channel_id: 7,
1835 flags: 2, // to disable
1836 cltv_expiry_delta: 0,
1837 htlc_minimum_msat: 0,
1838 htlc_maximum_msat: OptionalField::Absent,
1840 fee_proportional_millionths: 0,
1841 excess_data: Vec::new()
1844 // Check against amount_to_transfer_over_msat.
1845 // Set minimal HTLC of 200_000_000 msat.
1846 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1847 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1848 short_channel_id: 2,
1851 cltv_expiry_delta: 0,
1852 htlc_minimum_msat: 200_000_000,
1853 htlc_maximum_msat: OptionalField::Absent,
1855 fee_proportional_millionths: 0,
1856 excess_data: Vec::new()
1859 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
1861 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1862 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1863 short_channel_id: 4,
1866 cltv_expiry_delta: 0,
1867 htlc_minimum_msat: 0,
1868 htlc_maximum_msat: OptionalField::Present(199_999_999),
1870 fee_proportional_millionths: 0,
1871 excess_data: Vec::new()
1874 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
1875 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)) {
1876 assert_eq!(err, "Failed to find a path to the given destination");
1877 } else { panic!(); }
1879 // Lift the restriction on the first hop.
1880 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1881 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1882 short_channel_id: 2,
1885 cltv_expiry_delta: 0,
1886 htlc_minimum_msat: 0,
1887 htlc_maximum_msat: OptionalField::Absent,
1889 fee_proportional_millionths: 0,
1890 excess_data: Vec::new()
1893 // A payment above the minimum should pass
1894 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)).unwrap();
1895 assert_eq!(route.paths[0].len(), 2);
1899 fn htlc_minimum_overpay_test() {
1900 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1901 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1903 // A route to node#2 via two paths.
1904 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
1905 // Thus, they can't send 60 without overpaying.
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: 35_000,
1913 htlc_maximum_msat: OptionalField::Present(40_000),
1915 fee_proportional_millionths: 0,
1916 excess_data: Vec::new()
1918 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1919 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1920 short_channel_id: 12,
1923 cltv_expiry_delta: 0,
1924 htlc_minimum_msat: 35_000,
1925 htlc_maximum_msat: OptionalField::Present(40_000),
1927 fee_proportional_millionths: 0,
1928 excess_data: Vec::new()
1932 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1933 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1934 short_channel_id: 13,
1937 cltv_expiry_delta: 0,
1938 htlc_minimum_msat: 0,
1939 htlc_maximum_msat: OptionalField::Absent,
1941 fee_proportional_millionths: 0,
1942 excess_data: Vec::new()
1944 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1945 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1946 short_channel_id: 4,
1949 cltv_expiry_delta: 0,
1950 htlc_minimum_msat: 0,
1951 htlc_maximum_msat: OptionalField::Absent,
1953 fee_proportional_millionths: 0,
1954 excess_data: Vec::new()
1957 // Disable other paths
1958 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1959 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1960 short_channel_id: 1,
1962 flags: 2, // to disable
1963 cltv_expiry_delta: 0,
1964 htlc_minimum_msat: 0,
1965 htlc_maximum_msat: OptionalField::Absent,
1967 fee_proportional_millionths: 0,
1968 excess_data: Vec::new()
1971 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
1972 Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger)).unwrap();
1973 // Overpay fees to hit htlc_minimum_msat.
1974 let overpaid_fees = route.paths[0][0].fee_msat + route.paths[1][0].fee_msat;
1975 // TODO: this could be better balanced to overpay 10k and not 15k.
1976 assert_eq!(overpaid_fees, 15_000);
1978 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
1979 // while taking even more fee to match htlc_minimum_msat.
1980 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1981 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1982 short_channel_id: 12,
1985 cltv_expiry_delta: 0,
1986 htlc_minimum_msat: 65_000,
1987 htlc_maximum_msat: OptionalField::Present(80_000),
1989 fee_proportional_millionths: 0,
1990 excess_data: Vec::new()
1992 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1993 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1994 short_channel_id: 2,
1997 cltv_expiry_delta: 0,
1998 htlc_minimum_msat: 0,
1999 htlc_maximum_msat: OptionalField::Absent,
2001 fee_proportional_millionths: 0,
2002 excess_data: Vec::new()
2004 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2005 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2006 short_channel_id: 4,
2009 cltv_expiry_delta: 0,
2010 htlc_minimum_msat: 0,
2011 htlc_maximum_msat: OptionalField::Absent,
2013 fee_proportional_millionths: 100_000,
2014 excess_data: Vec::new()
2017 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
2018 Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger)).unwrap();
2019 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
2020 assert_eq!(route.paths.len(), 1);
2021 assert_eq!(route.paths[0][0].short_channel_id, 12);
2022 let fees = route.paths[0][0].fee_msat;
2023 assert_eq!(fees, 5_000);
2025 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
2026 Some(InvoiceFeatures::known()), None, &Vec::new(), 50_000, 42, Arc::clone(&logger)).unwrap();
2027 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
2028 // the other channel.
2029 assert_eq!(route.paths.len(), 1);
2030 assert_eq!(route.paths[0][0].short_channel_id, 2);
2031 let fees = route.paths[0][0].fee_msat;
2032 assert_eq!(fees, 5_000);
2036 fn disable_channels_test() {
2037 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2038 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2040 // // Disable channels 4 and 12 by flags=2
2041 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2042 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2043 short_channel_id: 4,
2045 flags: 2, // to disable
2046 cltv_expiry_delta: 0,
2047 htlc_minimum_msat: 0,
2048 htlc_maximum_msat: OptionalField::Absent,
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: 12,
2057 flags: 2, // to disable
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()
2066 // If all the channels require some features we don't understand, route should fail
2067 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)) {
2068 assert_eq!(err, "Failed to find a path to the given destination");
2069 } else { panic!(); }
2071 // If we specify a channel to node7, that overrides our local channel view and that gets used
2072 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2073 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)).unwrap();
2074 assert_eq!(route.paths[0].len(), 2);
2076 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2077 assert_eq!(route.paths[0][0].short_channel_id, 42);
2078 assert_eq!(route.paths[0][0].fee_msat, 200);
2079 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
2080 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2081 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2083 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2084 assert_eq!(route.paths[0][1].short_channel_id, 13);
2085 assert_eq!(route.paths[0][1].fee_msat, 100);
2086 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2087 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2088 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2092 fn disable_node_test() {
2093 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2094 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2096 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
2097 let unknown_features = NodeFeatures::known().set_unknown_feature_required();
2098 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
2099 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
2100 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
2102 // If all nodes require some features we don't understand, route should fail
2103 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)) {
2104 assert_eq!(err, "Failed to find a path to the given destination");
2105 } else { panic!(); }
2107 // If we specify a channel to node7, that overrides our local channel view and that gets used
2108 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2109 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)).unwrap();
2110 assert_eq!(route.paths[0].len(), 2);
2112 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2113 assert_eq!(route.paths[0][0].short_channel_id, 42);
2114 assert_eq!(route.paths[0][0].fee_msat, 200);
2115 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
2116 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2117 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2119 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2120 assert_eq!(route.paths[0][1].short_channel_id, 13);
2121 assert_eq!(route.paths[0][1].fee_msat, 100);
2122 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2123 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2124 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2126 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
2127 // naively) assume that the user checked the feature bits on the invoice, which override
2128 // the node_announcement.
2132 fn our_chans_test() {
2133 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2134 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2136 // Route to 1 via 2 and 3 because our channel to 1 is disabled
2137 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[0], None, None, &Vec::new(), 100, 42, Arc::clone(&logger)).unwrap();
2138 assert_eq!(route.paths[0].len(), 3);
2140 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2141 assert_eq!(route.paths[0][0].short_channel_id, 2);
2142 assert_eq!(route.paths[0][0].fee_msat, 200);
2143 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2144 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2145 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2147 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2148 assert_eq!(route.paths[0][1].short_channel_id, 4);
2149 assert_eq!(route.paths[0][1].fee_msat, 100);
2150 assert_eq!(route.paths[0][1].cltv_expiry_delta, (3 << 8) | 2);
2151 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2152 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2154 assert_eq!(route.paths[0][2].pubkey, nodes[0]);
2155 assert_eq!(route.paths[0][2].short_channel_id, 3);
2156 assert_eq!(route.paths[0][2].fee_msat, 100);
2157 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
2158 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(1));
2159 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(3));
2161 // If we specify a channel to node7, that overrides our local channel view and that gets used
2162 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2163 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)).unwrap();
2164 assert_eq!(route.paths[0].len(), 2);
2166 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2167 assert_eq!(route.paths[0][0].short_channel_id, 42);
2168 assert_eq!(route.paths[0][0].fee_msat, 200);
2169 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
2170 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2171 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2173 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2174 assert_eq!(route.paths[0][1].short_channel_id, 13);
2175 assert_eq!(route.paths[0][1].fee_msat, 100);
2176 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2177 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2178 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2181 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2182 let zero_fees = RoutingFees {
2184 proportional_millionths: 0,
2186 vec![RouteHint(vec![RouteHintHop {
2187 src_node_id: nodes[3].clone(),
2188 short_channel_id: 8,
2190 cltv_expiry_delta: (8 << 8) | 1,
2191 htlc_minimum_msat: None,
2192 htlc_maximum_msat: None,
2194 ]), RouteHint(vec![RouteHintHop {
2195 src_node_id: nodes[4].clone(),
2196 short_channel_id: 9,
2199 proportional_millionths: 0,
2201 cltv_expiry_delta: (9 << 8) | 1,
2202 htlc_minimum_msat: None,
2203 htlc_maximum_msat: None,
2204 }]), RouteHint(vec![RouteHintHop {
2205 src_node_id: nodes[5].clone(),
2206 short_channel_id: 10,
2208 cltv_expiry_delta: (10 << 8) | 1,
2209 htlc_minimum_msat: None,
2210 htlc_maximum_msat: None,
2214 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2215 let zero_fees = RoutingFees {
2217 proportional_millionths: 0,
2219 vec![RouteHint(vec![RouteHintHop {
2220 src_node_id: nodes[2].clone(),
2221 short_channel_id: 5,
2224 proportional_millionths: 0,
2226 cltv_expiry_delta: (5 << 8) | 1,
2227 htlc_minimum_msat: None,
2228 htlc_maximum_msat: None,
2230 src_node_id: nodes[3].clone(),
2231 short_channel_id: 8,
2233 cltv_expiry_delta: (8 << 8) | 1,
2234 htlc_minimum_msat: None,
2235 htlc_maximum_msat: None,
2237 ]), RouteHint(vec![RouteHintHop {
2238 src_node_id: nodes[4].clone(),
2239 short_channel_id: 9,
2242 proportional_millionths: 0,
2244 cltv_expiry_delta: (9 << 8) | 1,
2245 htlc_minimum_msat: None,
2246 htlc_maximum_msat: None,
2247 }]), RouteHint(vec![RouteHintHop {
2248 src_node_id: nodes[5].clone(),
2249 short_channel_id: 10,
2251 cltv_expiry_delta: (10 << 8) | 1,
2252 htlc_minimum_msat: None,
2253 htlc_maximum_msat: None,
2258 fn partial_route_hint_test() {
2259 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2260 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2262 // Simple test across 2, 3, 5, and 4 via a last_hop channel
2263 // Tests the behaviour when the RouteHint contains a suboptimal hop.
2264 // RouteHint may be partially used by the algo to build the best path.
2266 // First check that last hop can't have its source as the payee.
2267 let invalid_last_hop = RouteHint(vec![RouteHintHop {
2268 src_node_id: nodes[6],
2269 short_channel_id: 8,
2272 proportional_millionths: 0,
2274 cltv_expiry_delta: (8 << 8) | 1,
2275 htlc_minimum_msat: None,
2276 htlc_maximum_msat: None,
2279 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
2280 invalid_last_hops.push(invalid_last_hop);
2282 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)) {
2283 assert_eq!(err, "Last hop cannot have a payee as a source.");
2284 } else { panic!(); }
2287 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)).unwrap();
2288 assert_eq!(route.paths[0].len(), 5);
2290 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2291 assert_eq!(route.paths[0][0].short_channel_id, 2);
2292 assert_eq!(route.paths[0][0].fee_msat, 100);
2293 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2294 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2295 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2297 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2298 assert_eq!(route.paths[0][1].short_channel_id, 4);
2299 assert_eq!(route.paths[0][1].fee_msat, 0);
2300 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2301 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2302 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2304 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2305 assert_eq!(route.paths[0][2].short_channel_id, 6);
2306 assert_eq!(route.paths[0][2].fee_msat, 0);
2307 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2308 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2309 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2311 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2312 assert_eq!(route.paths[0][3].short_channel_id, 11);
2313 assert_eq!(route.paths[0][3].fee_msat, 0);
2314 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2315 // If we have a peer in the node map, we'll use their features here since we don't have
2316 // a way of figuring out their features from the invoice:
2317 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2318 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2320 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2321 assert_eq!(route.paths[0][4].short_channel_id, 8);
2322 assert_eq!(route.paths[0][4].fee_msat, 100);
2323 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2324 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2325 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2328 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2329 let zero_fees = RoutingFees {
2331 proportional_millionths: 0,
2333 vec![RouteHint(vec![RouteHintHop {
2334 src_node_id: nodes[3].clone(),
2335 short_channel_id: 8,
2337 cltv_expiry_delta: (8 << 8) | 1,
2338 htlc_minimum_msat: None,
2339 htlc_maximum_msat: None,
2340 }]), RouteHint(vec![
2342 ]), RouteHint(vec![RouteHintHop {
2343 src_node_id: nodes[5].clone(),
2344 short_channel_id: 10,
2346 cltv_expiry_delta: (10 << 8) | 1,
2347 htlc_minimum_msat: None,
2348 htlc_maximum_msat: None,
2353 fn ignores_empty_last_hops_test() {
2354 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2355 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2357 // Test handling of an empty RouteHint passed in Invoice.
2359 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)).unwrap();
2360 assert_eq!(route.paths[0].len(), 5);
2362 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2363 assert_eq!(route.paths[0][0].short_channel_id, 2);
2364 assert_eq!(route.paths[0][0].fee_msat, 100);
2365 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2366 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2367 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2369 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2370 assert_eq!(route.paths[0][1].short_channel_id, 4);
2371 assert_eq!(route.paths[0][1].fee_msat, 0);
2372 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2373 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2374 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2376 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2377 assert_eq!(route.paths[0][2].short_channel_id, 6);
2378 assert_eq!(route.paths[0][2].fee_msat, 0);
2379 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2380 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2381 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2383 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2384 assert_eq!(route.paths[0][3].short_channel_id, 11);
2385 assert_eq!(route.paths[0][3].fee_msat, 0);
2386 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2387 // If we have a peer in the node map, we'll use their features here since we don't have
2388 // a way of figuring out their features from the invoice:
2389 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2390 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2392 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2393 assert_eq!(route.paths[0][4].short_channel_id, 8);
2394 assert_eq!(route.paths[0][4].fee_msat, 100);
2395 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2396 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2397 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2400 fn multi_hint_last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2401 let zero_fees = RoutingFees {
2403 proportional_millionths: 0,
2405 vec![RouteHint(vec![RouteHintHop {
2406 src_node_id: nodes[2].clone(),
2407 short_channel_id: 5,
2410 proportional_millionths: 0,
2412 cltv_expiry_delta: (5 << 8) | 1,
2413 htlc_minimum_msat: None,
2414 htlc_maximum_msat: None,
2416 src_node_id: nodes[3].clone(),
2417 short_channel_id: 8,
2419 cltv_expiry_delta: (8 << 8) | 1,
2420 htlc_minimum_msat: None,
2421 htlc_maximum_msat: None,
2422 }]), RouteHint(vec![RouteHintHop {
2423 src_node_id: nodes[5].clone(),
2424 short_channel_id: 10,
2426 cltv_expiry_delta: (10 << 8) | 1,
2427 htlc_minimum_msat: None,
2428 htlc_maximum_msat: None,
2433 fn multi_hint_last_hops_test() {
2434 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2435 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2436 // Test through channels 2, 3, 5, 8.
2437 // Test shows that multiple hop hints are considered.
2439 // Disabling channels 6 & 7 by flags=2
2440 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2441 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2442 short_channel_id: 6,
2444 flags: 2, // to disable
2445 cltv_expiry_delta: 0,
2446 htlc_minimum_msat: 0,
2447 htlc_maximum_msat: OptionalField::Absent,
2449 fee_proportional_millionths: 0,
2450 excess_data: Vec::new()
2452 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2453 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2454 short_channel_id: 7,
2456 flags: 2, // to disable
2457 cltv_expiry_delta: 0,
2458 htlc_minimum_msat: 0,
2459 htlc_maximum_msat: OptionalField::Absent,
2461 fee_proportional_millionths: 0,
2462 excess_data: Vec::new()
2465 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)).unwrap();
2466 assert_eq!(route.paths[0].len(), 4);
2468 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2469 assert_eq!(route.paths[0][0].short_channel_id, 2);
2470 assert_eq!(route.paths[0][0].fee_msat, 200);
2471 assert_eq!(route.paths[0][0].cltv_expiry_delta, 1025);
2472 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2473 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2475 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2476 assert_eq!(route.paths[0][1].short_channel_id, 4);
2477 assert_eq!(route.paths[0][1].fee_msat, 100);
2478 assert_eq!(route.paths[0][1].cltv_expiry_delta, 1281);
2479 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2480 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2482 assert_eq!(route.paths[0][2].pubkey, nodes[3]);
2483 assert_eq!(route.paths[0][2].short_channel_id, 5);
2484 assert_eq!(route.paths[0][2].fee_msat, 0);
2485 assert_eq!(route.paths[0][2].cltv_expiry_delta, 2049);
2486 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(4));
2487 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new());
2489 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2490 assert_eq!(route.paths[0][3].short_channel_id, 8);
2491 assert_eq!(route.paths[0][3].fee_msat, 100);
2492 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2493 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2494 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2497 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2498 let zero_fees = RoutingFees {
2500 proportional_millionths: 0,
2502 vec![RouteHint(vec![RouteHintHop {
2503 src_node_id: nodes[4].clone(),
2504 short_channel_id: 11,
2506 cltv_expiry_delta: (11 << 8) | 1,
2507 htlc_minimum_msat: None,
2508 htlc_maximum_msat: None,
2510 src_node_id: nodes[3].clone(),
2511 short_channel_id: 8,
2513 cltv_expiry_delta: (8 << 8) | 1,
2514 htlc_minimum_msat: None,
2515 htlc_maximum_msat: None,
2516 }]), RouteHint(vec![RouteHintHop {
2517 src_node_id: nodes[4].clone(),
2518 short_channel_id: 9,
2521 proportional_millionths: 0,
2523 cltv_expiry_delta: (9 << 8) | 1,
2524 htlc_minimum_msat: None,
2525 htlc_maximum_msat: None,
2526 }]), RouteHint(vec![RouteHintHop {
2527 src_node_id: nodes[5].clone(),
2528 short_channel_id: 10,
2530 cltv_expiry_delta: (10 << 8) | 1,
2531 htlc_minimum_msat: None,
2532 htlc_maximum_msat: None,
2537 fn last_hops_with_public_channel_test() {
2538 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2539 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2540 // This test shows that public routes can be present in the invoice
2541 // which would be handled in the same manner.
2543 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)).unwrap();
2544 assert_eq!(route.paths[0].len(), 5);
2546 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2547 assert_eq!(route.paths[0][0].short_channel_id, 2);
2548 assert_eq!(route.paths[0][0].fee_msat, 100);
2549 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2550 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2551 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2553 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2554 assert_eq!(route.paths[0][1].short_channel_id, 4);
2555 assert_eq!(route.paths[0][1].fee_msat, 0);
2556 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2557 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2558 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2560 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2561 assert_eq!(route.paths[0][2].short_channel_id, 6);
2562 assert_eq!(route.paths[0][2].fee_msat, 0);
2563 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2564 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2565 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2567 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2568 assert_eq!(route.paths[0][3].short_channel_id, 11);
2569 assert_eq!(route.paths[0][3].fee_msat, 0);
2570 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2571 // If we have a peer in the node map, we'll use their features here since we don't have
2572 // a way of figuring out their features from the invoice:
2573 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2574 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new());
2576 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2577 assert_eq!(route.paths[0][4].short_channel_id, 8);
2578 assert_eq!(route.paths[0][4].fee_msat, 100);
2579 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2580 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2581 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2585 fn our_chans_last_hop_connect_test() {
2586 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2587 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2589 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
2590 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2591 let mut last_hops = last_hops(&nodes);
2592 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)).unwrap();
2593 assert_eq!(route.paths[0].len(), 2);
2595 assert_eq!(route.paths[0][0].pubkey, nodes[3]);
2596 assert_eq!(route.paths[0][0].short_channel_id, 42);
2597 assert_eq!(route.paths[0][0].fee_msat, 0);
2598 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
2599 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2600 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2602 assert_eq!(route.paths[0][1].pubkey, nodes[6]);
2603 assert_eq!(route.paths[0][1].short_channel_id, 8);
2604 assert_eq!(route.paths[0][1].fee_msat, 100);
2605 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2606 assert_eq!(route.paths[0][1].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2607 assert_eq!(route.paths[0][1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2609 last_hops[0].0[0].fees.base_msat = 1000;
2611 // Revert to via 6 as the fee on 8 goes up
2612 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)).unwrap();
2613 assert_eq!(route.paths[0].len(), 4);
2615 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2616 assert_eq!(route.paths[0][0].short_channel_id, 2);
2617 assert_eq!(route.paths[0][0].fee_msat, 200); // fee increased as its % of value transferred across node
2618 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2619 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2620 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2622 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2623 assert_eq!(route.paths[0][1].short_channel_id, 4);
2624 assert_eq!(route.paths[0][1].fee_msat, 100);
2625 assert_eq!(route.paths[0][1].cltv_expiry_delta, (7 << 8) | 1);
2626 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2627 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2629 assert_eq!(route.paths[0][2].pubkey, nodes[5]);
2630 assert_eq!(route.paths[0][2].short_channel_id, 7);
2631 assert_eq!(route.paths[0][2].fee_msat, 0);
2632 assert_eq!(route.paths[0][2].cltv_expiry_delta, (10 << 8) | 1);
2633 // If we have a peer in the node map, we'll use their features here since we don't have
2634 // a way of figuring out their features from the invoice:
2635 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
2636 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(7));
2638 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2639 assert_eq!(route.paths[0][3].short_channel_id, 10);
2640 assert_eq!(route.paths[0][3].fee_msat, 100);
2641 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2642 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2643 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2645 // ...but still use 8 for larger payments as 6 has a variable feerate
2646 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)).unwrap();
2647 assert_eq!(route.paths[0].len(), 5);
2649 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2650 assert_eq!(route.paths[0][0].short_channel_id, 2);
2651 assert_eq!(route.paths[0][0].fee_msat, 3000);
2652 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2653 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2654 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2656 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2657 assert_eq!(route.paths[0][1].short_channel_id, 4);
2658 assert_eq!(route.paths[0][1].fee_msat, 0);
2659 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2660 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2661 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2663 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2664 assert_eq!(route.paths[0][2].short_channel_id, 6);
2665 assert_eq!(route.paths[0][2].fee_msat, 0);
2666 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2667 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2668 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2670 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2671 assert_eq!(route.paths[0][3].short_channel_id, 11);
2672 assert_eq!(route.paths[0][3].fee_msat, 1000);
2673 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2674 // If we have a peer in the node map, we'll use their features here since we don't have
2675 // a way of figuring out their features from the invoice:
2676 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2677 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2679 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2680 assert_eq!(route.paths[0][4].short_channel_id, 8);
2681 assert_eq!(route.paths[0][4].fee_msat, 2000);
2682 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2683 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2684 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2687 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> {
2688 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
2689 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
2690 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
2692 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
2693 let last_hops = RouteHint(vec![RouteHintHop {
2694 src_node_id: middle_node_id,
2695 short_channel_id: 8,
2698 proportional_millionths: last_hop_fee_prop,
2700 cltv_expiry_delta: (8 << 8) | 1,
2701 htlc_minimum_msat: None,
2702 htlc_maximum_msat: last_hop_htlc_max,
2704 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
2705 get_route(&source_node_id, &NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()), &target_node_id, None, Some(&our_chans.iter().collect::<Vec<_>>()), &vec![&last_hops], route_val, 42, Arc::new(test_utils::TestLogger::new()))
2709 fn unannounced_path_test() {
2710 // We should be able to send a payment to a destination without any help of a routing graph
2711 // if we have a channel with a common counterparty that appears in the first and last hop
2713 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
2715 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
2716 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
2717 assert_eq!(route.paths[0].len(), 2);
2719 assert_eq!(route.paths[0][0].pubkey, middle_node_id);
2720 assert_eq!(route.paths[0][0].short_channel_id, 42);
2721 assert_eq!(route.paths[0][0].fee_msat, 1001);
2722 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
2723 assert_eq!(route.paths[0][0].node_features.le_flags(), &[0b11]);
2724 assert_eq!(route.paths[0][0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
2726 assert_eq!(route.paths[0][1].pubkey, target_node_id);
2727 assert_eq!(route.paths[0][1].short_channel_id, 8);
2728 assert_eq!(route.paths[0][1].fee_msat, 1000000);
2729 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2730 assert_eq!(route.paths[0][1].node_features.le_flags(), &[0; 0]); // We dont pass flags in from invoices yet
2731 assert_eq!(route.paths[0][1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
2735 fn overflow_unannounced_path_test_liquidity_underflow() {
2736 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
2737 // the last-hop had a fee which overflowed a u64, we'd panic.
2738 // This was due to us adding the first-hop from us unconditionally, causing us to think
2739 // we'd built a path (as our node is in the "best candidate" set), when we had not.
2740 // In this test, we previously hit a subtraction underflow due to having less available
2741 // liquidity at the last hop than 0.
2742 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());
2746 fn overflow_unannounced_path_test_feerate_overflow() {
2747 // This tests for the same case as above, except instead of hitting a subtraction
2748 // underflow, we hit a case where the fee charged at a hop overflowed.
2749 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());
2753 fn available_amount_while_routing_test() {
2754 // Tests whether we choose the correct available channel amount while routing.
2756 let (secp_ctx, mut net_graph_msg_handler, chain_monitor, logger) = build_graph();
2757 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2759 // We will use a simple single-path route from
2760 // our node to node2 via node0: channels {1, 3}.
2762 // First disable all other paths.
2763 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2764 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2765 short_channel_id: 2,
2768 cltv_expiry_delta: 0,
2769 htlc_minimum_msat: 0,
2770 htlc_maximum_msat: OptionalField::Present(100_000),
2772 fee_proportional_millionths: 0,
2773 excess_data: Vec::new()
2775 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2776 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2777 short_channel_id: 12,
2780 cltv_expiry_delta: 0,
2781 htlc_minimum_msat: 0,
2782 htlc_maximum_msat: OptionalField::Present(100_000),
2784 fee_proportional_millionths: 0,
2785 excess_data: Vec::new()
2788 // Make the first channel (#1) very permissive,
2789 // and we will be testing all limits on the second channel.
2790 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2791 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2792 short_channel_id: 1,
2795 cltv_expiry_delta: 0,
2796 htlc_minimum_msat: 0,
2797 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2799 fee_proportional_millionths: 0,
2800 excess_data: Vec::new()
2803 // First, let's see if routing works if we have absolutely no idea about the available amount.
2804 // In this case, it should be set to 250_000 sats.
2805 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2806 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2807 short_channel_id: 3,
2810 cltv_expiry_delta: 0,
2811 htlc_minimum_msat: 0,
2812 htlc_maximum_msat: OptionalField::Absent,
2814 fee_proportional_millionths: 0,
2815 excess_data: Vec::new()
2819 // Attempt to route more than available results in a failure.
2820 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
2821 Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000_001, 42, Arc::clone(&logger)) {
2822 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2823 } else { panic!(); }
2827 // Now, attempt to route an exact amount we have should be fine.
2828 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
2829 Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000_000, 42, Arc::clone(&logger)).unwrap();
2830 assert_eq!(route.paths.len(), 1);
2831 let path = route.paths.last().unwrap();
2832 assert_eq!(path.len(), 2);
2833 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2834 assert_eq!(path.last().unwrap().fee_msat, 250_000_000);
2837 // Check that setting outbound_capacity_msat in first_hops limits the channels.
2838 // Disable channel #1 and use another first hop.
2839 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2840 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2841 short_channel_id: 1,
2844 cltv_expiry_delta: 0,
2845 htlc_minimum_msat: 0,
2846 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2848 fee_proportional_millionths: 0,
2849 excess_data: Vec::new()
2852 // Now, limit the first_hop by the outbound_capacity_msat of 200_000 sats.
2853 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
2856 // Attempt to route more than available results in a failure.
2857 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
2858 Some(InvoiceFeatures::known()), Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 200_000_001, 42, Arc::clone(&logger)) {
2859 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2860 } else { panic!(); }
2864 // Now, attempt to route an exact amount we have should be fine.
2865 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
2866 Some(InvoiceFeatures::known()), Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 200_000_000, 42, Arc::clone(&logger)).unwrap();
2867 assert_eq!(route.paths.len(), 1);
2868 let path = route.paths.last().unwrap();
2869 assert_eq!(path.len(), 2);
2870 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2871 assert_eq!(path.last().unwrap().fee_msat, 200_000_000);
2874 // Enable channel #1 back.
2875 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2876 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2877 short_channel_id: 1,
2880 cltv_expiry_delta: 0,
2881 htlc_minimum_msat: 0,
2882 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2884 fee_proportional_millionths: 0,
2885 excess_data: Vec::new()
2889 // Now let's see if routing works if we know only htlc_maximum_msat.
2890 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2891 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2892 short_channel_id: 3,
2895 cltv_expiry_delta: 0,
2896 htlc_minimum_msat: 0,
2897 htlc_maximum_msat: OptionalField::Present(15_000),
2899 fee_proportional_millionths: 0,
2900 excess_data: Vec::new()
2904 // Attempt to route more than available results in a failure.
2905 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
2906 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_001, 42, Arc::clone(&logger)) {
2907 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2908 } else { panic!(); }
2912 // Now, attempt to route an exact amount we have should be fine.
2913 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
2914 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_000, 42, Arc::clone(&logger)).unwrap();
2915 assert_eq!(route.paths.len(), 1);
2916 let path = route.paths.last().unwrap();
2917 assert_eq!(path.len(), 2);
2918 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2919 assert_eq!(path.last().unwrap().fee_msat, 15_000);
2922 // Now let's see if routing works if we know only capacity from the UTXO.
2924 // We can't change UTXO capacity on the fly, so we'll disable
2925 // the existing channel and add another one with the capacity we need.
2926 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2927 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2928 short_channel_id: 3,
2931 cltv_expiry_delta: 0,
2932 htlc_minimum_msat: 0,
2933 htlc_maximum_msat: OptionalField::Absent,
2935 fee_proportional_millionths: 0,
2936 excess_data: Vec::new()
2939 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
2940 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
2941 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
2942 .push_opcode(opcodes::all::OP_PUSHNUM_2)
2943 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
2945 *chain_monitor.utxo_ret.lock().unwrap() = Ok(TxOut { value: 15, script_pubkey: good_script.clone() });
2946 net_graph_msg_handler.add_chain_access(Some(chain_monitor));
2948 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
2949 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2950 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2951 short_channel_id: 333,
2954 cltv_expiry_delta: (3 << 8) | 1,
2955 htlc_minimum_msat: 0,
2956 htlc_maximum_msat: OptionalField::Absent,
2958 fee_proportional_millionths: 0,
2959 excess_data: Vec::new()
2961 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2962 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2963 short_channel_id: 333,
2966 cltv_expiry_delta: (3 << 8) | 2,
2967 htlc_minimum_msat: 0,
2968 htlc_maximum_msat: OptionalField::Absent,
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)) {
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)).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 chooses htlc_maximum_msat over UTXO capacity.
2994 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2995 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2996 short_channel_id: 333,
2999 cltv_expiry_delta: 0,
3000 htlc_minimum_msat: 0,
3001 htlc_maximum_msat: OptionalField::Present(10_000),
3003 fee_proportional_millionths: 0,
3004 excess_data: Vec::new()
3008 // Attempt to route more than available results in a failure.
3009 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
3010 Some(InvoiceFeatures::known()), None, &Vec::new(), 10_001, 42, Arc::clone(&logger)) {
3011 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3012 } else { panic!(); }
3016 // Now, attempt to route an exact amount we have should be fine.
3017 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
3018 Some(InvoiceFeatures::known()), None, &Vec::new(), 10_000, 42, Arc::clone(&logger)).unwrap();
3019 assert_eq!(route.paths.len(), 1);
3020 let path = route.paths.last().unwrap();
3021 assert_eq!(path.len(), 2);
3022 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3023 assert_eq!(path.last().unwrap().fee_msat, 10_000);
3028 fn available_liquidity_last_hop_test() {
3029 // Check that available liquidity properly limits the path even when only
3030 // one of the latter hops is limited.
3031 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3032 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3034 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3035 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
3036 // Total capacity: 50 sats.
3038 // Disable other potential paths.
3039 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3040 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3041 short_channel_id: 2,
3044 cltv_expiry_delta: 0,
3045 htlc_minimum_msat: 0,
3046 htlc_maximum_msat: OptionalField::Present(100_000),
3048 fee_proportional_millionths: 0,
3049 excess_data: Vec::new()
3051 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3052 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3053 short_channel_id: 7,
3056 cltv_expiry_delta: 0,
3057 htlc_minimum_msat: 0,
3058 htlc_maximum_msat: OptionalField::Present(100_000),
3060 fee_proportional_millionths: 0,
3061 excess_data: Vec::new()
3066 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3067 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3068 short_channel_id: 12,
3071 cltv_expiry_delta: 0,
3072 htlc_minimum_msat: 0,
3073 htlc_maximum_msat: OptionalField::Present(100_000),
3075 fee_proportional_millionths: 0,
3076 excess_data: Vec::new()
3078 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3079 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3080 short_channel_id: 13,
3083 cltv_expiry_delta: 0,
3084 htlc_minimum_msat: 0,
3085 htlc_maximum_msat: OptionalField::Present(100_000),
3087 fee_proportional_millionths: 0,
3088 excess_data: Vec::new()
3091 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3092 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3093 short_channel_id: 6,
3096 cltv_expiry_delta: 0,
3097 htlc_minimum_msat: 0,
3098 htlc_maximum_msat: OptionalField::Present(50_000),
3100 fee_proportional_millionths: 0,
3101 excess_data: Vec::new()
3103 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3104 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3105 short_channel_id: 11,
3108 cltv_expiry_delta: 0,
3109 htlc_minimum_msat: 0,
3110 htlc_maximum_msat: OptionalField::Present(100_000),
3112 fee_proportional_millionths: 0,
3113 excess_data: Vec::new()
3116 // Attempt to route more than available results in a failure.
3117 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[3],
3118 Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger)) {
3119 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3120 } else { panic!(); }
3124 // Now, attempt to route 49 sats (just a bit below the capacity).
3125 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[3],
3126 Some(InvoiceFeatures::known()), None, &Vec::new(), 49_000, 42, Arc::clone(&logger)).unwrap();
3127 assert_eq!(route.paths.len(), 1);
3128 let mut total_amount_paid_msat = 0;
3129 for path in &route.paths {
3130 assert_eq!(path.len(), 4);
3131 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3132 total_amount_paid_msat += path.last().unwrap().fee_msat;
3134 assert_eq!(total_amount_paid_msat, 49_000);
3138 // Attempt to route an exact amount is also fine
3139 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[3],
3140 Some(InvoiceFeatures::known()), None, &Vec::new(), 50_000, 42, Arc::clone(&logger)).unwrap();
3141 assert_eq!(route.paths.len(), 1);
3142 let mut total_amount_paid_msat = 0;
3143 for path in &route.paths {
3144 assert_eq!(path.len(), 4);
3145 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3146 total_amount_paid_msat += path.last().unwrap().fee_msat;
3148 assert_eq!(total_amount_paid_msat, 50_000);
3153 fn ignore_fee_first_hop_test() {
3154 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3155 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3157 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3158 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3159 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3160 short_channel_id: 1,
3163 cltv_expiry_delta: 0,
3164 htlc_minimum_msat: 0,
3165 htlc_maximum_msat: OptionalField::Present(100_000),
3166 fee_base_msat: 1_000_000,
3167 fee_proportional_millionths: 0,
3168 excess_data: Vec::new()
3170 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3171 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3172 short_channel_id: 3,
3175 cltv_expiry_delta: 0,
3176 htlc_minimum_msat: 0,
3177 htlc_maximum_msat: OptionalField::Present(50_000),
3179 fee_proportional_millionths: 0,
3180 excess_data: Vec::new()
3184 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2], None, None, &Vec::new(), 50_000, 42, Arc::clone(&logger)).unwrap();
3185 assert_eq!(route.paths.len(), 1);
3186 let mut total_amount_paid_msat = 0;
3187 for path in &route.paths {
3188 assert_eq!(path.len(), 2);
3189 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3190 total_amount_paid_msat += path.last().unwrap().fee_msat;
3192 assert_eq!(total_amount_paid_msat, 50_000);
3197 fn simple_mpp_route_test() {
3198 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3199 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3201 // We need a route consisting of 3 paths:
3202 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3203 // To achieve this, the amount being transferred should be around
3204 // the total capacity of these 3 paths.
3206 // First, we set limits on these (previously unlimited) channels.
3207 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
3209 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3210 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3211 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3212 short_channel_id: 1,
3215 cltv_expiry_delta: 0,
3216 htlc_minimum_msat: 0,
3217 htlc_maximum_msat: OptionalField::Present(100_000),
3219 fee_proportional_millionths: 0,
3220 excess_data: Vec::new()
3222 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3223 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3224 short_channel_id: 3,
3227 cltv_expiry_delta: 0,
3228 htlc_minimum_msat: 0,
3229 htlc_maximum_msat: OptionalField::Present(50_000),
3231 fee_proportional_millionths: 0,
3232 excess_data: Vec::new()
3235 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
3236 // (total limit 60).
3237 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3238 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3239 short_channel_id: 12,
3242 cltv_expiry_delta: 0,
3243 htlc_minimum_msat: 0,
3244 htlc_maximum_msat: OptionalField::Present(60_000),
3246 fee_proportional_millionths: 0,
3247 excess_data: Vec::new()
3249 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3250 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3251 short_channel_id: 13,
3254 cltv_expiry_delta: 0,
3255 htlc_minimum_msat: 0,
3256 htlc_maximum_msat: OptionalField::Present(60_000),
3258 fee_proportional_millionths: 0,
3259 excess_data: Vec::new()
3262 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
3263 // (total capacity 180 sats).
3264 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3265 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3266 short_channel_id: 2,
3269 cltv_expiry_delta: 0,
3270 htlc_minimum_msat: 0,
3271 htlc_maximum_msat: OptionalField::Present(200_000),
3273 fee_proportional_millionths: 0,
3274 excess_data: Vec::new()
3276 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3277 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3278 short_channel_id: 4,
3281 cltv_expiry_delta: 0,
3282 htlc_minimum_msat: 0,
3283 htlc_maximum_msat: OptionalField::Present(180_000),
3285 fee_proportional_millionths: 0,
3286 excess_data: Vec::new()
3290 // Attempt to route more than available results in a failure.
3291 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph,
3292 &nodes[2], Some(InvoiceFeatures::known()), None, &Vec::new(), 300_000, 42, Arc::clone(&logger)) {
3293 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3294 } else { panic!(); }
3298 // Now, attempt to route 250 sats (just a bit below the capacity).
3299 // Our algorithm should provide us with these 3 paths.
3300 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
3301 Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000, 42, Arc::clone(&logger)).unwrap();
3302 assert_eq!(route.paths.len(), 3);
3303 let mut total_amount_paid_msat = 0;
3304 for path in &route.paths {
3305 assert_eq!(path.len(), 2);
3306 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3307 total_amount_paid_msat += path.last().unwrap().fee_msat;
3309 assert_eq!(total_amount_paid_msat, 250_000);
3313 // Attempt to route an exact amount is also fine
3314 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
3315 Some(InvoiceFeatures::known()), None, &Vec::new(), 290_000, 42, Arc::clone(&logger)).unwrap();
3316 assert_eq!(route.paths.len(), 3);
3317 let mut total_amount_paid_msat = 0;
3318 for path in &route.paths {
3319 assert_eq!(path.len(), 2);
3320 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3321 total_amount_paid_msat += path.last().unwrap().fee_msat;
3323 assert_eq!(total_amount_paid_msat, 290_000);
3328 fn long_mpp_route_test() {
3329 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3330 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3332 // We need a route consisting of 3 paths:
3333 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3334 // Note that these paths overlap (channels 5, 12, 13).
3335 // We will route 300 sats.
3336 // Each path will have 100 sats capacity, those channels which
3337 // are used twice will have 200 sats capacity.
3339 // Disable other potential paths.
3340 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3341 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3342 short_channel_id: 2,
3345 cltv_expiry_delta: 0,
3346 htlc_minimum_msat: 0,
3347 htlc_maximum_msat: OptionalField::Present(100_000),
3349 fee_proportional_millionths: 0,
3350 excess_data: Vec::new()
3352 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3353 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3354 short_channel_id: 7,
3357 cltv_expiry_delta: 0,
3358 htlc_minimum_msat: 0,
3359 htlc_maximum_msat: OptionalField::Present(100_000),
3361 fee_proportional_millionths: 0,
3362 excess_data: Vec::new()
3365 // Path via {node0, node2} is channels {1, 3, 5}.
3366 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3367 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3368 short_channel_id: 1,
3371 cltv_expiry_delta: 0,
3372 htlc_minimum_msat: 0,
3373 htlc_maximum_msat: OptionalField::Present(100_000),
3375 fee_proportional_millionths: 0,
3376 excess_data: Vec::new()
3378 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3379 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3380 short_channel_id: 3,
3383 cltv_expiry_delta: 0,
3384 htlc_minimum_msat: 0,
3385 htlc_maximum_msat: OptionalField::Present(100_000),
3387 fee_proportional_millionths: 0,
3388 excess_data: Vec::new()
3391 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3392 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3393 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3394 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3395 short_channel_id: 5,
3398 cltv_expiry_delta: 0,
3399 htlc_minimum_msat: 0,
3400 htlc_maximum_msat: OptionalField::Present(200_000),
3402 fee_proportional_millionths: 0,
3403 excess_data: Vec::new()
3406 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3407 // Add 100 sats to the capacities of {12, 13}, because these channels
3408 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3409 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3410 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3411 short_channel_id: 12,
3414 cltv_expiry_delta: 0,
3415 htlc_minimum_msat: 0,
3416 htlc_maximum_msat: OptionalField::Present(200_000),
3418 fee_proportional_millionths: 0,
3419 excess_data: Vec::new()
3421 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3422 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3423 short_channel_id: 13,
3426 cltv_expiry_delta: 0,
3427 htlc_minimum_msat: 0,
3428 htlc_maximum_msat: OptionalField::Present(200_000),
3430 fee_proportional_millionths: 0,
3431 excess_data: Vec::new()
3434 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3435 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3436 short_channel_id: 6,
3439 cltv_expiry_delta: 0,
3440 htlc_minimum_msat: 0,
3441 htlc_maximum_msat: OptionalField::Present(100_000),
3443 fee_proportional_millionths: 0,
3444 excess_data: Vec::new()
3446 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3447 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3448 short_channel_id: 11,
3451 cltv_expiry_delta: 0,
3452 htlc_minimum_msat: 0,
3453 htlc_maximum_msat: OptionalField::Present(100_000),
3455 fee_proportional_millionths: 0,
3456 excess_data: Vec::new()
3459 // Path via {node7, node2} is channels {12, 13, 5}.
3460 // We already limited them to 200 sats (they are used twice for 100 sats).
3461 // Nothing to do here.
3464 // Attempt to route more than available results in a failure.
3465 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[3],
3466 Some(InvoiceFeatures::known()), None, &Vec::new(), 350_000, 42, Arc::clone(&logger)) {
3467 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3468 } else { panic!(); }
3472 // Now, attempt to route 300 sats (exact amount we can route).
3473 // Our algorithm should provide us with these 3 paths, 100 sats each.
3474 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[3],
3475 Some(InvoiceFeatures::known()), None, &Vec::new(), 300_000, 42, Arc::clone(&logger)).unwrap();
3476 assert_eq!(route.paths.len(), 3);
3478 let mut total_amount_paid_msat = 0;
3479 for path in &route.paths {
3480 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3481 total_amount_paid_msat += path.last().unwrap().fee_msat;
3483 assert_eq!(total_amount_paid_msat, 300_000);
3489 fn mpp_cheaper_route_test() {
3490 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3491 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3493 // This test checks that if we have two cheaper paths and one more expensive path,
3494 // so that liquidity-wise any 2 of 3 combination is sufficient,
3495 // two cheaper paths will be taken.
3496 // These paths have equal available liquidity.
3498 // We need a combination of 3 paths:
3499 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3500 // Note that these paths overlap (channels 5, 12, 13).
3501 // Each path will have 100 sats capacity, those channels which
3502 // are used twice will have 200 sats capacity.
3504 // Disable other potential paths.
3505 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3506 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3507 short_channel_id: 2,
3510 cltv_expiry_delta: 0,
3511 htlc_minimum_msat: 0,
3512 htlc_maximum_msat: OptionalField::Present(100_000),
3514 fee_proportional_millionths: 0,
3515 excess_data: Vec::new()
3517 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3518 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3519 short_channel_id: 7,
3522 cltv_expiry_delta: 0,
3523 htlc_minimum_msat: 0,
3524 htlc_maximum_msat: OptionalField::Present(100_000),
3526 fee_proportional_millionths: 0,
3527 excess_data: Vec::new()
3530 // Path via {node0, node2} is channels {1, 3, 5}.
3531 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3532 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3533 short_channel_id: 1,
3536 cltv_expiry_delta: 0,
3537 htlc_minimum_msat: 0,
3538 htlc_maximum_msat: OptionalField::Present(100_000),
3540 fee_proportional_millionths: 0,
3541 excess_data: Vec::new()
3543 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3544 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3545 short_channel_id: 3,
3548 cltv_expiry_delta: 0,
3549 htlc_minimum_msat: 0,
3550 htlc_maximum_msat: OptionalField::Present(100_000),
3552 fee_proportional_millionths: 0,
3553 excess_data: Vec::new()
3556 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3557 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3558 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3559 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3560 short_channel_id: 5,
3563 cltv_expiry_delta: 0,
3564 htlc_minimum_msat: 0,
3565 htlc_maximum_msat: OptionalField::Present(200_000),
3567 fee_proportional_millionths: 0,
3568 excess_data: Vec::new()
3571 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3572 // Add 100 sats to the capacities of {12, 13}, because these channels
3573 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3574 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3575 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3576 short_channel_id: 12,
3579 cltv_expiry_delta: 0,
3580 htlc_minimum_msat: 0,
3581 htlc_maximum_msat: OptionalField::Present(200_000),
3583 fee_proportional_millionths: 0,
3584 excess_data: Vec::new()
3586 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3587 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3588 short_channel_id: 13,
3591 cltv_expiry_delta: 0,
3592 htlc_minimum_msat: 0,
3593 htlc_maximum_msat: OptionalField::Present(200_000),
3595 fee_proportional_millionths: 0,
3596 excess_data: Vec::new()
3599 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3600 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3601 short_channel_id: 6,
3604 cltv_expiry_delta: 0,
3605 htlc_minimum_msat: 0,
3606 htlc_maximum_msat: OptionalField::Present(100_000),
3607 fee_base_msat: 1_000,
3608 fee_proportional_millionths: 0,
3609 excess_data: Vec::new()
3611 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3612 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3613 short_channel_id: 11,
3616 cltv_expiry_delta: 0,
3617 htlc_minimum_msat: 0,
3618 htlc_maximum_msat: OptionalField::Present(100_000),
3620 fee_proportional_millionths: 0,
3621 excess_data: Vec::new()
3624 // Path via {node7, node2} is channels {12, 13, 5}.
3625 // We already limited them to 200 sats (they are used twice for 100 sats).
3626 // Nothing to do here.
3629 // Now, attempt to route 180 sats.
3630 // Our algorithm should provide us with these 2 paths.
3631 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[3],
3632 Some(InvoiceFeatures::known()), None, &Vec::new(), 180_000, 42, Arc::clone(&logger)).unwrap();
3633 assert_eq!(route.paths.len(), 2);
3635 let mut total_value_transferred_msat = 0;
3636 let mut total_paid_msat = 0;
3637 for path in &route.paths {
3638 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3639 total_value_transferred_msat += path.last().unwrap().fee_msat;
3641 total_paid_msat += hop.fee_msat;
3644 // If we paid fee, this would be higher.
3645 assert_eq!(total_value_transferred_msat, 180_000);
3646 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
3647 assert_eq!(total_fees_paid, 0);
3652 fn fees_on_mpp_route_test() {
3653 // This test makes sure that MPP algorithm properly takes into account
3654 // fees charged on the channels, by making the fees impactful:
3655 // if the fee is not properly accounted for, the behavior is different.
3656 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3657 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3659 // We need a route consisting of 2 paths:
3660 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
3661 // We will route 200 sats, Each path will have 100 sats capacity.
3663 // This test is not particularly stable: e.g.,
3664 // there's a way to route via {node0, node2, node4}.
3665 // It works while pathfinding is deterministic, but can be broken otherwise.
3666 // It's fine to ignore this concern for now.
3668 // Disable other potential paths.
3669 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3670 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3671 short_channel_id: 2,
3674 cltv_expiry_delta: 0,
3675 htlc_minimum_msat: 0,
3676 htlc_maximum_msat: OptionalField::Present(100_000),
3678 fee_proportional_millionths: 0,
3679 excess_data: Vec::new()
3682 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3683 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3684 short_channel_id: 7,
3687 cltv_expiry_delta: 0,
3688 htlc_minimum_msat: 0,
3689 htlc_maximum_msat: OptionalField::Present(100_000),
3691 fee_proportional_millionths: 0,
3692 excess_data: Vec::new()
3695 // Path via {node0, node2} is channels {1, 3, 5}.
3696 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3697 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3698 short_channel_id: 1,
3701 cltv_expiry_delta: 0,
3702 htlc_minimum_msat: 0,
3703 htlc_maximum_msat: OptionalField::Present(100_000),
3705 fee_proportional_millionths: 0,
3706 excess_data: Vec::new()
3708 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3709 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3710 short_channel_id: 3,
3713 cltv_expiry_delta: 0,
3714 htlc_minimum_msat: 0,
3715 htlc_maximum_msat: OptionalField::Present(100_000),
3717 fee_proportional_millionths: 0,
3718 excess_data: Vec::new()
3721 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3722 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3723 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3724 short_channel_id: 5,
3727 cltv_expiry_delta: 0,
3728 htlc_minimum_msat: 0,
3729 htlc_maximum_msat: OptionalField::Present(100_000),
3731 fee_proportional_millionths: 0,
3732 excess_data: Vec::new()
3735 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3736 // All channels should be 100 sats capacity. But for the fee experiment,
3737 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
3738 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
3739 // 100 sats (and pay 150 sats in fees for the use of channel 6),
3740 // so no matter how large are other channels,
3741 // the whole path will be limited by 100 sats with just these 2 conditions:
3742 // - channel 12 capacity is 250 sats
3743 // - fee for channel 6 is 150 sats
3744 // Let's test this by enforcing these 2 conditions and removing other limits.
3745 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3746 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3747 short_channel_id: 12,
3750 cltv_expiry_delta: 0,
3751 htlc_minimum_msat: 0,
3752 htlc_maximum_msat: OptionalField::Present(250_000),
3754 fee_proportional_millionths: 0,
3755 excess_data: Vec::new()
3757 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3758 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3759 short_channel_id: 13,
3762 cltv_expiry_delta: 0,
3763 htlc_minimum_msat: 0,
3764 htlc_maximum_msat: OptionalField::Absent,
3766 fee_proportional_millionths: 0,
3767 excess_data: Vec::new()
3770 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3771 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3772 short_channel_id: 6,
3775 cltv_expiry_delta: 0,
3776 htlc_minimum_msat: 0,
3777 htlc_maximum_msat: OptionalField::Absent,
3778 fee_base_msat: 150_000,
3779 fee_proportional_millionths: 0,
3780 excess_data: Vec::new()
3782 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3783 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3784 short_channel_id: 11,
3787 cltv_expiry_delta: 0,
3788 htlc_minimum_msat: 0,
3789 htlc_maximum_msat: OptionalField::Absent,
3791 fee_proportional_millionths: 0,
3792 excess_data: Vec::new()
3796 // Attempt to route more than available results in a failure.
3797 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[3],
3798 Some(InvoiceFeatures::known()), None, &Vec::new(), 210_000, 42, Arc::clone(&logger)) {
3799 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3800 } else { panic!(); }
3804 // Now, attempt to route 200 sats (exact amount we can route).
3805 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[3],
3806 Some(InvoiceFeatures::known()), None, &Vec::new(), 200_000, 42, Arc::clone(&logger)).unwrap();
3807 assert_eq!(route.paths.len(), 2);
3809 let mut total_amount_paid_msat = 0;
3810 for path in &route.paths {
3811 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3812 total_amount_paid_msat += path.last().unwrap().fee_msat;
3814 assert_eq!(total_amount_paid_msat, 200_000);
3815 assert_eq!(route.get_total_fees(), 150_000);
3821 fn drop_lowest_channel_mpp_route_test() {
3822 // This test checks that low-capacity channel is dropped when after
3823 // path finding we realize that we found more capacity than we need.
3824 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3825 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3827 // We need a route consisting of 3 paths:
3828 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3830 // The first and the second paths should be sufficient, but the third should be
3831 // cheaper, so that we select it but drop later.
3833 // First, we set limits on these (previously unlimited) channels.
3834 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
3836 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
3837 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3838 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3839 short_channel_id: 1,
3842 cltv_expiry_delta: 0,
3843 htlc_minimum_msat: 0,
3844 htlc_maximum_msat: OptionalField::Present(100_000),
3846 fee_proportional_millionths: 0,
3847 excess_data: Vec::new()
3849 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3850 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3851 short_channel_id: 3,
3854 cltv_expiry_delta: 0,
3855 htlc_minimum_msat: 0,
3856 htlc_maximum_msat: OptionalField::Present(50_000),
3858 fee_proportional_millionths: 0,
3859 excess_data: Vec::new()
3862 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
3863 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3864 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3865 short_channel_id: 12,
3868 cltv_expiry_delta: 0,
3869 htlc_minimum_msat: 0,
3870 htlc_maximum_msat: OptionalField::Present(60_000),
3872 fee_proportional_millionths: 0,
3873 excess_data: Vec::new()
3875 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3876 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3877 short_channel_id: 13,
3880 cltv_expiry_delta: 0,
3881 htlc_minimum_msat: 0,
3882 htlc_maximum_msat: OptionalField::Present(60_000),
3884 fee_proportional_millionths: 0,
3885 excess_data: Vec::new()
3888 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
3889 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3890 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3891 short_channel_id: 2,
3894 cltv_expiry_delta: 0,
3895 htlc_minimum_msat: 0,
3896 htlc_maximum_msat: OptionalField::Present(20_000),
3898 fee_proportional_millionths: 0,
3899 excess_data: Vec::new()
3901 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3902 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3903 short_channel_id: 4,
3906 cltv_expiry_delta: 0,
3907 htlc_minimum_msat: 0,
3908 htlc_maximum_msat: OptionalField::Present(20_000),
3910 fee_proportional_millionths: 0,
3911 excess_data: Vec::new()
3915 // Attempt to route more than available results in a failure.
3916 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
3917 Some(InvoiceFeatures::known()), None, &Vec::new(), 150_000, 42, Arc::clone(&logger)) {
3918 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3919 } else { panic!(); }
3923 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
3924 // Our algorithm should provide us with these 3 paths.
3925 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
3926 Some(InvoiceFeatures::known()), None, &Vec::new(), 125_000, 42, Arc::clone(&logger)).unwrap();
3927 assert_eq!(route.paths.len(), 3);
3928 let mut total_amount_paid_msat = 0;
3929 for path in &route.paths {
3930 assert_eq!(path.len(), 2);
3931 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3932 total_amount_paid_msat += path.last().unwrap().fee_msat;
3934 assert_eq!(total_amount_paid_msat, 125_000);
3938 // Attempt to route without the last small cheap channel
3939 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
3940 Some(InvoiceFeatures::known()), None, &Vec::new(), 90_000, 42, Arc::clone(&logger)).unwrap();
3941 assert_eq!(route.paths.len(), 2);
3942 let mut total_amount_paid_msat = 0;
3943 for path in &route.paths {
3944 assert_eq!(path.len(), 2);
3945 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3946 total_amount_paid_msat += path.last().unwrap().fee_msat;
3948 assert_eq!(total_amount_paid_msat, 90_000);
3953 fn min_criteria_consistency() {
3954 // Test that we don't use an inconsistent metric between updating and walking nodes during
3955 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
3956 // was updated with a different criterion from the heap sorting, resulting in loops in
3957 // calculated paths. We test for that specific case here.
3959 // We construct a network that looks like this:
3961 // node2 -1(3)2- node3
3965 // node1 -1(5)2- node4 -1(1)2- node6
3971 // We create a loop on the side of our real path - our destination is node 6, with a
3972 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
3973 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
3974 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
3975 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
3976 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
3977 // "previous hop" being set to node 3, creating a loop in the path.
3978 let secp_ctx = Secp256k1::new();
3979 let logger = Arc::new(test_utils::TestLogger::new());
3980 let network_graph = NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash());
3981 let net_graph_msg_handler = NetGraphMsgHandler::new(network_graph, None, Arc::clone(&logger));
3982 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3984 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
3985 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3986 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3987 short_channel_id: 6,
3990 cltv_expiry_delta: (6 << 8) | 0,
3991 htlc_minimum_msat: 0,
3992 htlc_maximum_msat: OptionalField::Absent,
3994 fee_proportional_millionths: 0,
3995 excess_data: Vec::new()
3997 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
3999 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4000 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4001 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4002 short_channel_id: 5,
4005 cltv_expiry_delta: (5 << 8) | 0,
4006 htlc_minimum_msat: 0,
4007 htlc_maximum_msat: OptionalField::Absent,
4009 fee_proportional_millionths: 0,
4010 excess_data: Vec::new()
4012 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
4014 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
4015 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4016 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4017 short_channel_id: 4,
4020 cltv_expiry_delta: (4 << 8) | 0,
4021 htlc_minimum_msat: 0,
4022 htlc_maximum_msat: OptionalField::Absent,
4024 fee_proportional_millionths: 0,
4025 excess_data: Vec::new()
4027 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
4029 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
4030 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
4031 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4032 short_channel_id: 3,
4035 cltv_expiry_delta: (3 << 8) | 0,
4036 htlc_minimum_msat: 0,
4037 htlc_maximum_msat: OptionalField::Absent,
4039 fee_proportional_millionths: 0,
4040 excess_data: Vec::new()
4042 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
4044 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
4045 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4046 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4047 short_channel_id: 2,
4050 cltv_expiry_delta: (2 << 8) | 0,
4051 htlc_minimum_msat: 0,
4052 htlc_maximum_msat: OptionalField::Absent,
4054 fee_proportional_millionths: 0,
4055 excess_data: Vec::new()
4058 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
4059 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4060 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4061 short_channel_id: 1,
4064 cltv_expiry_delta: (1 << 8) | 0,
4065 htlc_minimum_msat: 100,
4066 htlc_maximum_msat: OptionalField::Absent,
4068 fee_proportional_millionths: 0,
4069 excess_data: Vec::new()
4071 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
4074 // Now ensure the route flows simply over nodes 1 and 4 to 6.
4075 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[6], None, None, &Vec::new(), 10_000, 42, Arc::clone(&logger)).unwrap();
4076 assert_eq!(route.paths.len(), 1);
4077 assert_eq!(route.paths[0].len(), 3);
4079 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
4080 assert_eq!(route.paths[0][0].short_channel_id, 6);
4081 assert_eq!(route.paths[0][0].fee_msat, 100);
4082 assert_eq!(route.paths[0][0].cltv_expiry_delta, (5 << 8) | 0);
4083 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(1));
4084 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(6));
4086 assert_eq!(route.paths[0][1].pubkey, nodes[4]);
4087 assert_eq!(route.paths[0][1].short_channel_id, 5);
4088 assert_eq!(route.paths[0][1].fee_msat, 0);
4089 assert_eq!(route.paths[0][1].cltv_expiry_delta, (1 << 8) | 0);
4090 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(4));
4091 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(5));
4093 assert_eq!(route.paths[0][2].pubkey, nodes[6]);
4094 assert_eq!(route.paths[0][2].short_channel_id, 1);
4095 assert_eq!(route.paths[0][2].fee_msat, 10_000);
4096 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
4097 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
4098 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(1));
4104 fn exact_fee_liquidity_limit() {
4105 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
4106 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
4107 // we calculated fees on a higher value, resulting in us ignoring such paths.
4108 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
4109 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
4111 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
4113 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4114 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4115 short_channel_id: 2,
4118 cltv_expiry_delta: 0,
4119 htlc_minimum_msat: 0,
4120 htlc_maximum_msat: OptionalField::Present(85_000),
4122 fee_proportional_millionths: 0,
4123 excess_data: Vec::new()
4126 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4127 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4128 short_channel_id: 12,
4131 cltv_expiry_delta: (4 << 8) | 1,
4132 htlc_minimum_msat: 0,
4133 htlc_maximum_msat: OptionalField::Present(270_000),
4135 fee_proportional_millionths: 1000000,
4136 excess_data: Vec::new()
4140 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
4141 // 200% fee charged channel 13 in the 1-to-2 direction.
4142 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2], None, None, &Vec::new(), 90_000, 42, Arc::clone(&logger)).unwrap();
4143 assert_eq!(route.paths.len(), 1);
4144 assert_eq!(route.paths[0].len(), 2);
4146 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4147 assert_eq!(route.paths[0][0].short_channel_id, 12);
4148 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4149 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
4150 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4151 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4153 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4154 assert_eq!(route.paths[0][1].short_channel_id, 13);
4155 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4156 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4157 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
4158 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4163 fn htlc_max_reduction_below_min() {
4164 // Test that if, while walking the graph, we reduce the value being sent to meet an
4165 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
4166 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
4167 // resulting in us thinking there is no possible path, even if other paths exist.
4168 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
4169 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4171 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
4172 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
4173 // then try to send 90_000.
4174 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4175 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4176 short_channel_id: 2,
4179 cltv_expiry_delta: 0,
4180 htlc_minimum_msat: 0,
4181 htlc_maximum_msat: OptionalField::Present(80_000),
4183 fee_proportional_millionths: 0,
4184 excess_data: Vec::new()
4186 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4187 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4188 short_channel_id: 4,
4191 cltv_expiry_delta: (4 << 8) | 1,
4192 htlc_minimum_msat: 90_000,
4193 htlc_maximum_msat: OptionalField::Absent,
4195 fee_proportional_millionths: 0,
4196 excess_data: Vec::new()
4200 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
4201 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
4202 // expensive) channels 12-13 path.
4203 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)).unwrap();
4204 assert_eq!(route.paths.len(), 1);
4205 assert_eq!(route.paths[0].len(), 2);
4207 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4208 assert_eq!(route.paths[0][0].short_channel_id, 12);
4209 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4210 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
4211 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4212 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4214 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4215 assert_eq!(route.paths[0][1].short_channel_id, 13);
4216 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4217 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4218 assert_eq!(route.paths[0][1].node_features.le_flags(), InvoiceFeatures::known().le_flags());
4219 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4224 fn total_fees_single_path() {
4228 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
4229 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4230 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
4233 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
4234 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4235 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
4238 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
4239 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4240 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0
4245 assert_eq!(route.get_total_fees(), 250);
4246 assert_eq!(route.get_total_amount(), 225);
4250 fn total_fees_multi_path() {
4254 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
4255 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4256 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
4259 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
4260 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4261 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
4265 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
4266 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4267 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
4270 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
4271 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4272 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
4277 assert_eq!(route.get_total_fees(), 200);
4278 assert_eq!(route.get_total_amount(), 300);
4282 fn total_empty_route_no_panic() {
4283 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
4284 // would both panic if the route was completely empty. We test to ensure they return 0
4285 // here, even though its somewhat nonsensical as a route.
4286 let route = Route { paths: Vec::new() };
4288 assert_eq!(route.get_total_fees(), 0);
4289 assert_eq!(route.get_total_amount(), 0);
4292 #[cfg(not(feature = "no-std"))]
4293 pub(super) fn random_init_seed() -> u64 {
4294 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
4295 use core::hash::{BuildHasher, Hasher};
4296 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
4297 println!("Using seed of {}", seed);
4300 #[cfg(not(feature = "no-std"))]
4301 use util::ser::Readable;
4304 #[cfg(not(feature = "no-std"))]
4305 fn generate_routes() {
4306 let mut d = match super::test_utils::get_route_file() {
4313 let graph = NetworkGraph::read(&mut d).unwrap();
4315 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4316 let mut seed = random_init_seed() as usize;
4317 let nodes = graph.read_only().nodes().clone();
4318 'load_endpoints: for _ in 0..10 {
4320 seed = seed.overflowing_mul(0xdeadbeef).0;
4321 let src = nodes.keys().skip(seed % nodes.len()).next().unwrap();
4322 seed = seed.overflowing_mul(0xdeadbeef).0;
4323 let dst = nodes.keys().skip(seed % nodes.len()).next().unwrap();
4324 let amt = seed as u64 % 200_000_000;
4325 if get_route(src, &graph, dst, None, None, &[], amt, 42, &test_utils::TestLogger::new()).is_ok() {
4326 continue 'load_endpoints;
4333 #[cfg(not(feature = "no-std"))]
4334 fn generate_routes_mpp() {
4335 let mut d = match super::test_utils::get_route_file() {
4342 let graph = NetworkGraph::read(&mut d).unwrap();
4344 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4345 let mut seed = random_init_seed() as usize;
4346 let nodes = graph.read_only().nodes().clone();
4347 'load_endpoints: for _ in 0..10 {
4349 seed = seed.overflowing_mul(0xdeadbeef).0;
4350 let src = nodes.keys().skip(seed % nodes.len()).next().unwrap();
4351 seed = seed.overflowing_mul(0xdeadbeef).0;
4352 let dst = nodes.keys().skip(seed % nodes.len()).next().unwrap();
4353 let amt = seed as u64 % 200_000_000;
4354 if get_route(src, &graph, dst, Some(InvoiceFeatures::known()), None, &[], amt, 42, &test_utils::TestLogger::new()).is_ok() {
4355 continue 'load_endpoints;
4362 #[cfg(all(test, not(feature = "no-std")))]
4363 pub(crate) mod test_utils {
4365 /// Tries to open a network graph file, or panics with a URL to fetch it.
4366 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
4367 let res = File::open("net_graph-2021-05-31.bin") // By default we're run in RL/lightning
4368 .or_else(|_| File::open("lightning/net_graph-2021-05-31.bin")) // We may be run manually in RL/
4369 .or_else(|_| { // Fall back to guessing based on the binary location
4370 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
4371 let mut path = std::env::current_exe().unwrap();
4372 path.pop(); // lightning-...
4374 path.pop(); // debug
4375 path.pop(); // target
4376 path.push("lightning");
4377 path.push("net_graph-2021-05-31.bin");
4378 eprintln!("{}", path.to_str().unwrap());
4381 .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");
4382 #[cfg(require_route_graph_test)]
4383 return Ok(res.unwrap());
4384 #[cfg(not(require_route_graph_test))]
4389 #[cfg(all(test, feature = "unstable", not(feature = "no-std")))]
4392 use util::logger::{Logger, Record};
4396 struct DummyLogger {}
4397 impl Logger for DummyLogger {
4398 fn log(&self, _record: &Record) {}
4402 fn generate_routes(bench: &mut Bencher) {
4403 let mut d = test_utils::get_route_file().unwrap();
4404 let graph = NetworkGraph::read(&mut d).unwrap();
4405 let nodes = graph.read_only().nodes().clone();
4407 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4408 let mut path_endpoints = Vec::new();
4409 let mut seed: usize = 0xdeadbeef;
4410 'load_endpoints: for _ in 0..100 {
4413 let src = nodes.keys().skip(seed % nodes.len()).next().unwrap();
4415 let dst = nodes.keys().skip(seed % nodes.len()).next().unwrap();
4416 let amt = seed as u64 % 1_000_000;
4417 if get_route(src, &graph, dst, None, None, &[], amt, 42, &DummyLogger{}).is_ok() {
4418 path_endpoints.push((src, dst, amt));
4419 continue 'load_endpoints;
4424 // ...then benchmark finding paths between the nodes we learned.
4427 let (src, dst, amt) = path_endpoints[idx % path_endpoints.len()];
4428 assert!(get_route(src, &graph, dst, None, None, &[], amt, 42, &DummyLogger{}).is_ok());
4434 fn generate_mpp_routes(bench: &mut Bencher) {
4435 let mut d = test_utils::get_route_file().unwrap();
4436 let graph = NetworkGraph::read(&mut d).unwrap();
4437 let nodes = graph.read_only().nodes().clone();
4439 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4440 let mut path_endpoints = Vec::new();
4441 let mut seed: usize = 0xdeadbeef;
4442 'load_endpoints: for _ in 0..100 {
4445 let src = nodes.keys().skip(seed % nodes.len()).next().unwrap();
4447 let dst = nodes.keys().skip(seed % nodes.len()).next().unwrap();
4448 let amt = seed as u64 % 1_000_000;
4449 if get_route(src, &graph, dst, Some(InvoiceFeatures::known()), None, &[], amt, 42, &DummyLogger{}).is_ok() {
4450 path_endpoints.push((src, dst, amt));
4451 continue 'load_endpoints;
4456 // ...then benchmark finding paths between the nodes we learned.
4459 let (src, dst, amt) = path_endpoints[idx % path_endpoints.len()];
4460 assert!(get_route(src, &graph, dst, Some(InvoiceFeatures::known()), None, &[], amt, 42, &DummyLogger{}).is_ok());