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, NodeFeatures};
19 use ln::msgs::{DecodeError, ErrorAction, LightningError, MAX_VALUE_MSAT};
20 use routing::network_graph::{NetworkGraph, RoutingFees};
21 use util::ser::{Writeable, Readable};
22 use util::logger::Logger;
25 use std::collections::{HashMap,BinaryHeap};
29 #[derive(Clone, PartialEq)]
31 /// The node_id of the node at this hop.
32 pub pubkey: PublicKey,
33 /// The node_announcement features of the node at this hop. For the last hop, these may be
34 /// amended to match the features present in the invoice this node generated.
35 pub node_features: NodeFeatures,
36 /// The channel that should be used from the previous hop to reach this node.
37 pub short_channel_id: u64,
38 /// The channel_announcement features of the channel that should be used from the previous hop
39 /// to reach this node.
40 pub channel_features: ChannelFeatures,
41 /// The fee taken on this hop. For the last hop, this should be the full value of the payment.
43 /// The CLTV delta added for this hop. For the last hop, this should be the full CLTV value
44 /// expected at the destination, in excess of the current block height.
45 pub cltv_expiry_delta: u32,
48 impl Writeable for Vec<RouteHop> {
49 fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
50 (self.len() as u8).write(writer)?;
51 for hop in self.iter() {
52 hop.pubkey.write(writer)?;
53 hop.node_features.write(writer)?;
54 hop.short_channel_id.write(writer)?;
55 hop.channel_features.write(writer)?;
56 hop.fee_msat.write(writer)?;
57 hop.cltv_expiry_delta.write(writer)?;
63 impl Readable for Vec<RouteHop> {
64 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Vec<RouteHop>, DecodeError> {
65 let hops_count: u8 = Readable::read(reader)?;
66 let mut hops = Vec::with_capacity(hops_count as usize);
67 for _ in 0..hops_count {
69 pubkey: Readable::read(reader)?,
70 node_features: Readable::read(reader)?,
71 short_channel_id: Readable::read(reader)?,
72 channel_features: Readable::read(reader)?,
73 fee_msat: Readable::read(reader)?,
74 cltv_expiry_delta: Readable::read(reader)?,
81 /// A route directs a payment from the sender (us) to the recipient. If the recipient supports MPP,
82 /// it can take multiple paths. Each path is composed of one or more hops through the network.
83 #[derive(Clone, PartialEq)]
85 /// The list of routes taken for a single (potentially-)multi-part payment. The pubkey of the
86 /// last RouteHop in each path must be the same.
87 /// Each entry represents a list of hops, NOT INCLUDING our own, where the last hop is the
88 /// destination. Thus, this must always be at least length one. While the maximum length of any
89 /// given path is variable, keeping the length of any path to less than 20 should currently
90 /// ensure it is viable.
91 pub paths: Vec<Vec<RouteHop>>,
94 impl Writeable for Route {
95 fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
96 (self.paths.len() as u64).write(writer)?;
97 for hops in self.paths.iter() {
104 impl Readable for Route {
105 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
106 let path_count: u64 = Readable::read(reader)?;
107 let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
108 for _ in 0..path_count {
109 paths.push(Readable::read(reader)?);
115 /// A channel descriptor which provides a last-hop route to get_route
116 pub struct RouteHint {
117 /// The node_id of the non-target end of the route
118 pub src_node_id: PublicKey,
119 /// The short_channel_id of this channel
120 pub short_channel_id: u64,
121 /// The fees which must be paid to use this channel
122 pub fees: RoutingFees,
123 /// The difference in CLTV values between this node and the next node.
124 pub cltv_expiry_delta: u16,
125 /// The minimum value, in msat, which must be relayed to the next hop.
126 pub htlc_minimum_msat: u64,
129 #[derive(Eq, PartialEq)]
130 struct RouteGraphNode {
132 lowest_fee_to_peer_through_node: u64,
133 lowest_fee_to_node: u64,
136 impl cmp::Ord for RouteGraphNode {
137 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
138 other.lowest_fee_to_peer_through_node.cmp(&self.lowest_fee_to_peer_through_node)
139 .then_with(|| other.pubkey.serialize().cmp(&self.pubkey.serialize()))
143 impl cmp::PartialOrd for RouteGraphNode {
144 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
145 Some(self.cmp(other))
149 struct DummyDirectionalChannelInfo {
150 cltv_expiry_delta: u32,
151 htlc_minimum_msat: u64,
156 /// Gets a route from us to the given target node.
158 /// Extra routing hops between known nodes and the target will be used if they are included in
161 /// If some channels aren't announced, it may be useful to fill in a first_hops with the
162 /// results from a local ChannelManager::list_usable_channels() call. If it is filled in, our
163 /// view of our local channels (from net_graph_msg_handler) will be ignored, and only those in first_hops
166 /// Panics if first_hops contains channels without short_channel_ids
167 /// (ChannelManager::list_usable_channels will never include such channels).
169 /// The fees on channels from us to next-hops are ignored (as they are assumed to all be
170 /// equal), however the enabled/disabled bit on such channels as well as the htlc_minimum_msat
171 /// *is* checked as they may change based on the receiving node.
172 pub fn get_route<L: Deref>(our_node_id: &PublicKey, network: &NetworkGraph, target: &PublicKey, first_hops: Option<&[&ChannelDetails]>,
173 last_hops: &[&RouteHint], final_value_msat: u64, final_cltv: u32, logger: L) -> Result<Route, LightningError> where L::Target: Logger {
174 // TODO: Obviously *only* using total fee cost sucks. We should consider weighting by
175 // uptime/success in using a node in the past.
176 if *target == *our_node_id {
177 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
180 if final_value_msat > MAX_VALUE_MSAT {
181 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
184 // We do a dest-to-source Dijkstra's sorting by each node's distance from the destination
185 // plus the minimum per-HTLC fee to get from it to another node (aka "shitty A*").
186 // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
187 // to use as the A* heuristic beyond just the cost to get one node further than the current
190 let dummy_directional_info = DummyDirectionalChannelInfo { // used for first_hops routes
191 cltv_expiry_delta: 0,
192 htlc_minimum_msat: 0,
195 proportional_millionths: 0,
199 let mut targets = BinaryHeap::new(); //TODO: Do we care about switching to eg Fibbonaci heap?
200 let mut dist = HashMap::with_capacity(network.get_nodes().len());
202 let mut first_hop_targets = HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
203 if let Some(hops) = first_hops {
205 let short_channel_id = chan.short_channel_id.expect("first_hops should be filled in with usable channels, not pending ones");
206 if chan.remote_network_id == *target {
208 paths: vec![vec![RouteHop {
209 pubkey: chan.remote_network_id,
210 node_features: chan.counterparty_features.to_context(),
212 channel_features: chan.counterparty_features.to_context(),
213 fee_msat: final_value_msat,
214 cltv_expiry_delta: final_cltv,
218 first_hop_targets.insert(chan.remote_network_id, (short_channel_id, chan.counterparty_features.clone()));
220 if first_hop_targets.is_empty() {
221 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
225 macro_rules! add_entry {
226 // Adds entry which goes from $src_node_id to $dest_node_id
227 // over the channel with id $chan_id with fees described in
228 // $directional_info.
229 ( $chan_id: expr, $src_node_id: expr, $dest_node_id: expr, $directional_info: expr, $chan_features: expr, $starting_fee_msat: expr ) => {
230 //TODO: Explore simply adding fee to hit htlc_minimum_msat
231 if $starting_fee_msat as u64 + final_value_msat >= $directional_info.htlc_minimum_msat {
232 let proportional_fee_millions = ($starting_fee_msat + final_value_msat).checked_mul($directional_info.fees.proportional_millionths as u64);
233 if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
234 ($directional_info.fees.base_msat as u64).checked_add(part / 1000000) })
236 let mut total_fee = $starting_fee_msat as u64;
237 let hm_entry = dist.entry(&$src_node_id);
238 let old_entry = hm_entry.or_insert_with(|| {
239 let mut fee_base_msat = u32::max_value();
240 let mut fee_proportional_millionths = u32::max_value();
241 if let Some(fees) = network.get_nodes().get(&$src_node_id).and_then(|node| node.lowest_inbound_channel_fees) {
242 fee_base_msat = fees.base_msat;
243 fee_proportional_millionths = fees.proportional_millionths;
247 fee_proportional_millionths,
249 pubkey: $dest_node_id.clone(),
250 node_features: NodeFeatures::empty(),
252 channel_features: $chan_features.clone(),
254 cltv_expiry_delta: 0,
258 if $src_node_id != *our_node_id {
259 // Ignore new_fee for channel-from-us as we assume all channels-from-us
260 // will have the same effective-fee
261 total_fee += new_fee;
262 if let Some(fee_inc) = final_value_msat.checked_add(total_fee).and_then(|inc| { (old_entry.2 as u64).checked_mul(inc) }) {
263 total_fee += fee_inc / 1000000 + (old_entry.1 as u64);
265 // max_value means we'll always fail the old_entry.0 > total_fee check
266 total_fee = u64::max_value();
269 let new_graph_node = RouteGraphNode {
270 pubkey: $src_node_id,
271 lowest_fee_to_peer_through_node: total_fee,
272 lowest_fee_to_node: $starting_fee_msat as u64 + new_fee,
274 if old_entry.0 > total_fee {
275 targets.push(new_graph_node);
276 old_entry.0 = total_fee;
277 old_entry.3 = RouteHop {
278 pubkey: $dest_node_id.clone(),
279 node_features: NodeFeatures::empty(),
280 short_channel_id: $chan_id.clone(),
281 channel_features: $chan_features.clone(),
282 fee_msat: new_fee, // This field is ignored on the last-hop anyway
283 cltv_expiry_delta: $directional_info.cltv_expiry_delta as u32,
291 macro_rules! add_entries_to_cheapest_to_target_node {
292 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr ) => {
293 if first_hops.is_some() {
294 if let Some(&(ref first_hop, ref features)) = first_hop_targets.get(&$node_id) {
295 add_entry!(first_hop, *our_node_id, $node_id, dummy_directional_info, features.to_context(), $fee_to_target_msat);
300 if let Some(node_info) = $node.announcement_info.as_ref() {
301 features = node_info.features.clone();
303 features = NodeFeatures::empty();
306 if !features.requires_unknown_bits() {
307 for chan_id in $node.channels.iter() {
308 let chan = network.get_channels().get(chan_id).unwrap();
309 if !chan.features.requires_unknown_bits() {
310 if chan.node_one == *$node_id {
311 // ie $node is one, ie next hop in A* is two, via the two_to_one channel
312 if first_hops.is_none() || chan.node_two != *our_node_id {
313 if let Some(two_to_one) = chan.two_to_one.as_ref() {
314 if two_to_one.enabled {
315 add_entry!(chan_id, chan.node_two, chan.node_one, two_to_one, chan.features, $fee_to_target_msat);
320 if first_hops.is_none() || chan.node_one != *our_node_id {
321 if let Some(one_to_two) = chan.one_to_two.as_ref() {
322 if one_to_two.enabled {
323 add_entry!(chan_id, chan.node_one, chan.node_two, one_to_two, chan.features, $fee_to_target_msat);
335 match network.get_nodes().get(target) {
338 add_entries_to_cheapest_to_target_node!(node, target, 0);
342 for hop in last_hops.iter() {
343 let have_hop_src_in_graph =
344 if let Some(&(ref first_hop, ref features)) = first_hop_targets.get(&hop.src_node_id) {
345 // If this hop connects to a node with which we have a direct channel, ignore the
346 // network graph and add both the hop and our direct channel to the candidate set:
348 // Currently there are no channel-context features defined, so we are a
349 // bit lazy here. In the future, we should pull them out via our
350 // ChannelManager, but there's no reason to waste the space until we
352 add_entry!(first_hop, *our_node_id , hop.src_node_id, dummy_directional_info, features.to_context(), 0);
355 // In any other case, only add the hop if the source is in the regular network
357 network.get_nodes().get(&hop.src_node_id).is_some()
359 if have_hop_src_in_graph {
360 // BOLT 11 doesn't allow inclusion of features for the last hop hints, which
361 // really sucks, cause we're gonna need that eventually.
362 add_entry!(hop.short_channel_id, hop.src_node_id, target, hop, ChannelFeatures::empty(), 0);
366 while let Some(RouteGraphNode { pubkey, lowest_fee_to_node, .. }) = targets.pop() {
367 if pubkey == *our_node_id {
368 let mut res = vec!(dist.remove(&our_node_id).unwrap().3);
370 if let Some(&(_, ref features)) = first_hop_targets.get(&res.last().unwrap().pubkey) {
371 res.last_mut().unwrap().node_features = features.to_context();
372 } else if let Some(node) = network.get_nodes().get(&res.last().unwrap().pubkey) {
373 if let Some(node_info) = node.announcement_info.as_ref() {
374 res.last_mut().unwrap().node_features = node_info.features.clone();
376 res.last_mut().unwrap().node_features = NodeFeatures::empty();
379 // We should be able to fill in features for everything except the last
380 // hop, if the last hop was provided via a BOLT 11 invoice (though we
381 // should be able to extend it further as BOLT 11 does have feature
382 // flags for the last hop node itself).
383 assert!(res.last().unwrap().pubkey == *target);
385 if res.last().unwrap().pubkey == *target {
389 let new_entry = match dist.remove(&res.last().unwrap().pubkey) {
391 None => return Err(LightningError{err: "Failed to find a non-fee-overflowing path to the given destination".to_owned(), action: ErrorAction::IgnoreError}),
393 res.last_mut().unwrap().fee_msat = new_entry.fee_msat;
394 res.last_mut().unwrap().cltv_expiry_delta = new_entry.cltv_expiry_delta;
397 res.last_mut().unwrap().fee_msat = final_value_msat;
398 res.last_mut().unwrap().cltv_expiry_delta = final_cltv;
399 let route = Route { paths: vec![res] };
400 log_trace!(logger, "Got route: {}", log_route!(route));
404 match network.get_nodes().get(&pubkey) {
407 add_entries_to_cheapest_to_target_node!(node, &pubkey, lowest_fee_to_node);
412 Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError})
417 use routing::router::{get_route, RouteHint, RoutingFees};
418 use routing::network_graph::{NetworkGraph, NetGraphMsgHandler};
419 use ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
420 use ln::msgs::{ErrorAction, LightningError, OptionalField, UnsignedChannelAnnouncement, ChannelAnnouncement, RoutingMessageHandler,
421 NodeAnnouncement, UnsignedNodeAnnouncement, ChannelUpdate, UnsignedChannelUpdate};
422 use ln::channelmanager;
423 use util::test_utils;
424 use util::ser::Writeable;
426 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
427 use bitcoin::hashes::Hash;
428 use bitcoin::network::constants::Network;
429 use bitcoin::blockdata::constants::genesis_block;
433 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
434 use bitcoin::secp256k1::{Secp256k1, All};
438 // Using the same keys for LN and BTC ids
439 fn add_channel(net_graph_msg_handler: &NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>, secp_ctx: &Secp256k1<All>, node_1_privkey: &SecretKey,
440 node_2_privkey: &SecretKey, features: ChannelFeatures, short_channel_id: u64) {
441 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
442 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
444 let unsigned_announcement = UnsignedChannelAnnouncement {
446 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
450 bitcoin_key_1: node_id_1,
451 bitcoin_key_2: node_id_2,
452 excess_data: Vec::new(),
455 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
456 let valid_announcement = ChannelAnnouncement {
457 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
458 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
459 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
460 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
461 contents: unsigned_announcement.clone(),
463 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
464 Ok(res) => assert!(res),
469 fn update_channel(net_graph_msg_handler: &NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>, secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, update: UnsignedChannelUpdate) {
470 let msghash = hash_to_message!(&Sha256dHash::hash(&update.encode()[..])[..]);
471 let valid_channel_update = ChannelUpdate {
472 signature: secp_ctx.sign(&msghash, node_privkey),
473 contents: update.clone()
476 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
477 Ok(res) => assert!(res),
478 // Err(_) => panic!()
479 Err(e) => println!("{:?}", e.err)
484 fn add_or_update_node(net_graph_msg_handler: &NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>, secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey,
485 features: NodeFeatures, timestamp: u32) {
486 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
487 let unsigned_announcement = UnsignedNodeAnnouncement {
493 addresses: Vec::new(),
494 excess_address_data: Vec::new(),
495 excess_data: Vec::new(),
497 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
498 let valid_announcement = NodeAnnouncement {
499 signature: secp_ctx.sign(&msghash, node_privkey),
500 contents: unsigned_announcement.clone()
503 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
509 fn get_nodes(secp_ctx: &Secp256k1<All>) -> (SecretKey, PublicKey, Vec<SecretKey>, Vec<PublicKey>) {
510 let privkeys: Vec<SecretKey> = (2..10).map(|i| {
511 SecretKey::from_slice(&hex::decode(format!("{:02}", i).repeat(32)).unwrap()[..]).unwrap()
514 let pubkeys = privkeys.iter().map(|secret| PublicKey::from_secret_key(&secp_ctx, secret)).collect();
516 let our_privkey = SecretKey::from_slice(&hex::decode("01".repeat(32)).unwrap()[..]).unwrap();
517 let our_id = PublicKey::from_secret_key(&secp_ctx, &our_privkey);
519 (our_privkey, our_id, privkeys, pubkeys)
522 fn id_to_feature_flags(id: u8) -> Vec<u8> {
523 // Set the feature flags to the id'th odd (ie non-required) feature bit so that we can
524 // test for it later.
525 let idx = (id - 1) * 2 + 1;
527 vec![1 << (idx - 8*3), 0, 0, 0]
528 } else if idx > 8*2 {
529 vec![1 << (idx - 8*2), 0, 0]
530 } else if idx > 8*1 {
531 vec![1 << (idx - 8*1), 0]
537 fn build_graph() -> (Secp256k1<All>, NetGraphMsgHandler<std::sync::Arc<crate::util::test_utils::TestChainSource>, std::sync::Arc<crate::util::test_utils::TestLogger>>, std::sync::Arc<test_utils::TestLogger>) {
538 let secp_ctx = Secp256k1::new();
539 let logger = Arc::new(test_utils::TestLogger::new());
540 let net_graph_msg_handler = NetGraphMsgHandler::new(None, Arc::clone(&logger));
541 // Build network from our_id to node7:
543 // -1(1)2- node0 -1(3)2-
545 // our_id -1(12)2- node7 -1(13)2--- node2
547 // -1(2)2- node1 -1(4)2-
550 // chan1 1-to-2: disabled
551 // chan1 2-to-1: enabled, 0 fee
553 // chan2 1-to-2: enabled, ignored fee
554 // chan2 2-to-1: enabled, 0 fee
556 // chan3 1-to-2: enabled, 0 fee
557 // chan3 2-to-1: enabled, 100 msat fee
559 // chan4 1-to-2: enabled, 100% fee
560 // chan4 2-to-1: enabled, 0 fee
562 // chan12 1-to-2: enabled, ignored fee
563 // chan12 2-to-1: enabled, 0 fee
565 // chan13 1-to-2: enabled, 200% fee
566 // chan13 2-to-1: enabled, 0 fee
569 // -1(5)2- node3 -1(8)2--
573 // node2--1(6)2- node4 -1(9)2--- node6 (not in global route map)
575 // -1(7)2- node5 -1(10)2-
577 // chan5 1-to-2: enabled, 100 msat fee
578 // chan5 2-to-1: enabled, 0 fee
580 // chan6 1-to-2: enabled, 0 fee
581 // chan6 2-to-1: enabled, 0 fee
583 // chan7 1-to-2: enabled, 100% fee
584 // chan7 2-to-1: enabled, 0 fee
586 // chan8 1-to-2: enabled, variable fee (0 then 1000 msat)
587 // chan8 2-to-1: enabled, 0 fee
589 // chan9 1-to-2: enabled, 1001 msat fee
590 // chan9 2-to-1: enabled, 0 fee
592 // chan10 1-to-2: enabled, 0 fee
593 // chan10 2-to-1: enabled, 0 fee
595 // chan11 1-to-2: enabled, 0 fee
596 // chan11 2-to-1: enabled, 0 fee
598 let (our_privkey, _, privkeys, _) = get_nodes(&secp_ctx);
600 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[0], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
601 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
602 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
606 cltv_expiry_delta: 0,
607 htlc_minimum_msat: 0,
608 htlc_maximum_msat: OptionalField::Absent,
610 fee_proportional_millionths: 0,
611 excess_data: Vec::new()
614 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
616 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
617 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
618 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
622 cltv_expiry_delta: u16::max_value(),
623 htlc_minimum_msat: 0,
624 htlc_maximum_msat: OptionalField::Absent,
625 fee_base_msat: u32::max_value(),
626 fee_proportional_millionths: u32::max_value(),
627 excess_data: Vec::new()
629 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
630 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
634 cltv_expiry_delta: 0,
635 htlc_minimum_msat: 0,
636 htlc_maximum_msat: OptionalField::Absent,
638 fee_proportional_millionths: 0,
639 excess_data: Vec::new()
642 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
644 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[7], ChannelFeatures::from_le_bytes(id_to_feature_flags(12)), 12);
645 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
646 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
647 short_channel_id: 12,
650 cltv_expiry_delta: u16::max_value(),
651 htlc_minimum_msat: 0,
652 htlc_maximum_msat: OptionalField::Absent,
653 fee_base_msat: u32::max_value(),
654 fee_proportional_millionths: u32::max_value(),
655 excess_data: Vec::new()
657 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
658 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
659 short_channel_id: 12,
662 cltv_expiry_delta: 0,
663 htlc_minimum_msat: 0,
664 htlc_maximum_msat: OptionalField::Absent,
666 fee_proportional_millionths: 0,
667 excess_data: Vec::new()
670 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], NodeFeatures::from_le_bytes(id_to_feature_flags(8)), 0);
672 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
673 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
674 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
678 cltv_expiry_delta: (3 << 8) | 1,
679 htlc_minimum_msat: 0,
680 htlc_maximum_msat: OptionalField::Absent,
682 fee_proportional_millionths: 0,
683 excess_data: Vec::new()
685 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
686 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
690 cltv_expiry_delta: (3 << 8) | 2,
691 htlc_minimum_msat: 0,
692 htlc_maximum_msat: OptionalField::Absent,
694 fee_proportional_millionths: 0,
695 excess_data: Vec::new()
698 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
699 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
700 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
704 cltv_expiry_delta: (4 << 8) | 1,
705 htlc_minimum_msat: 0,
706 htlc_maximum_msat: OptionalField::Absent,
708 fee_proportional_millionths: 1000000,
709 excess_data: Vec::new()
711 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
712 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
716 cltv_expiry_delta: (4 << 8) | 2,
717 htlc_minimum_msat: 0,
718 htlc_maximum_msat: OptionalField::Absent,
720 fee_proportional_millionths: 0,
721 excess_data: Vec::new()
724 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(13)), 13);
725 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
726 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
727 short_channel_id: 13,
730 cltv_expiry_delta: (13 << 8) | 1,
731 htlc_minimum_msat: 0,
732 htlc_maximum_msat: OptionalField::Absent,
734 fee_proportional_millionths: 2000000,
735 excess_data: Vec::new()
737 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
738 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
739 short_channel_id: 13,
742 cltv_expiry_delta: (13 << 8) | 2,
743 htlc_minimum_msat: 0,
744 htlc_maximum_msat: OptionalField::Absent,
746 fee_proportional_millionths: 0,
747 excess_data: Vec::new()
750 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
752 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
753 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
754 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
758 cltv_expiry_delta: (6 << 8) | 1,
759 htlc_minimum_msat: 0,
760 htlc_maximum_msat: OptionalField::Absent,
762 fee_proportional_millionths: 0,
763 excess_data: Vec::new()
765 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
766 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
770 cltv_expiry_delta: (6 << 8) | 2,
771 htlc_minimum_msat: 0,
772 htlc_maximum_msat: OptionalField::Absent,
774 fee_proportional_millionths: 0,
775 excess_data: Vec::new(),
778 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(11)), 11);
779 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
780 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
781 short_channel_id: 11,
784 cltv_expiry_delta: (11 << 8) | 1,
785 htlc_minimum_msat: 0,
786 htlc_maximum_msat: OptionalField::Absent,
788 fee_proportional_millionths: 0,
789 excess_data: Vec::new()
791 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
792 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
793 short_channel_id: 11,
796 cltv_expiry_delta: (11 << 8) | 2,
797 htlc_minimum_msat: 0,
798 htlc_maximum_msat: OptionalField::Absent,
800 fee_proportional_millionths: 0,
801 excess_data: Vec::new()
804 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(5)), 0);
806 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
808 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[5], ChannelFeatures::from_le_bytes(id_to_feature_flags(7)), 7);
809 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
810 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
814 cltv_expiry_delta: (7 << 8) | 1,
815 htlc_minimum_msat: 0,
816 htlc_maximum_msat: OptionalField::Absent,
818 fee_proportional_millionths: 1000000,
819 excess_data: Vec::new()
821 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[5], UnsignedChannelUpdate {
822 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
826 cltv_expiry_delta: (7 << 8) | 2,
827 htlc_minimum_msat: 0,
828 htlc_maximum_msat: OptionalField::Absent,
830 fee_proportional_millionths: 0,
831 excess_data: Vec::new()
834 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[5], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
836 (secp_ctx, net_graph_msg_handler, logger)
840 fn simple_route_test() {
841 let (secp_ctx, net_graph_msg_handler, logger) = build_graph();
842 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
844 // Simple route to 3 via 2
845 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, &Vec::new(), 100, 42, Arc::clone(&logger)).unwrap();
846 assert_eq!(route.paths[0].len(), 2);
848 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
849 assert_eq!(route.paths[0][0].short_channel_id, 2);
850 assert_eq!(route.paths[0][0].fee_msat, 100);
851 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
852 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
853 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
855 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
856 assert_eq!(route.paths[0][1].short_channel_id, 4);
857 assert_eq!(route.paths[0][1].fee_msat, 100);
858 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
859 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
860 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
864 fn disable_channels_test() {
865 let (secp_ctx, net_graph_msg_handler, logger) = build_graph();
866 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
868 // // Disable channels 4 and 12 by flags=2
869 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
870 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
873 flags: 2, // to disable
874 cltv_expiry_delta: 0,
875 htlc_minimum_msat: 0,
876 htlc_maximum_msat: OptionalField::Absent,
878 fee_proportional_millionths: 0,
879 excess_data: Vec::new()
881 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
882 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
883 short_channel_id: 12,
885 flags: 2, // to disable
886 cltv_expiry_delta: 0,
887 htlc_minimum_msat: 0,
888 htlc_maximum_msat: OptionalField::Absent,
890 fee_proportional_millionths: 0,
891 excess_data: Vec::new()
894 // If all the channels require some features we don't understand, route should fail
895 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, &Vec::new(), 100, 42, Arc::clone(&logger)) {
896 assert_eq!(err, "Failed to find a path to the given destination");
899 // If we specify a channel to node7, that overrides our local channel view and that gets used
900 let our_chans = vec![channelmanager::ChannelDetails {
902 short_channel_id: Some(42),
903 remote_network_id: nodes[7].clone(),
904 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
905 channel_value_satoshis: 0,
907 outbound_capacity_msat: 0,
908 inbound_capacity_msat: 0,
911 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 100, 42, Arc::clone(&logger)).unwrap();
912 assert_eq!(route.paths[0].len(), 2);
914 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
915 assert_eq!(route.paths[0][0].short_channel_id, 42);
916 assert_eq!(route.paths[0][0].fee_msat, 200);
917 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
918 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
919 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
921 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
922 assert_eq!(route.paths[0][1].short_channel_id, 13);
923 assert_eq!(route.paths[0][1].fee_msat, 100);
924 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
925 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
926 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
930 fn disable_node_test() {
931 let (secp_ctx, net_graph_msg_handler, logger) = build_graph();
932 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
934 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
935 let mut unknown_features = NodeFeatures::known();
936 unknown_features.set_required_unknown_bits();
937 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
938 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
939 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
941 // If all nodes require some features we don't understand, route should fail
942 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, &Vec::new(), 100, 42, Arc::clone(&logger)) {
943 assert_eq!(err, "Failed to find a path to the given destination");
946 // If we specify a channel to node7, that overrides our local channel view and that gets used
947 let our_chans = vec![channelmanager::ChannelDetails {
949 short_channel_id: Some(42),
950 remote_network_id: nodes[7].clone(),
951 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
952 channel_value_satoshis: 0,
954 outbound_capacity_msat: 0,
955 inbound_capacity_msat: 0,
958 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 100, 42, Arc::clone(&logger)).unwrap();
959 assert_eq!(route.paths[0].len(), 2);
961 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
962 assert_eq!(route.paths[0][0].short_channel_id, 42);
963 assert_eq!(route.paths[0][0].fee_msat, 200);
964 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
965 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
966 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
968 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
969 assert_eq!(route.paths[0][1].short_channel_id, 13);
970 assert_eq!(route.paths[0][1].fee_msat, 100);
971 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
972 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
973 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
975 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
976 // naively) assume that the user checked the feature bits on the invoice, which override
977 // the node_announcement.
981 fn our_chans_test() {
982 let (secp_ctx, net_graph_msg_handler, logger) = build_graph();
983 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
985 // Route to 1 via 2 and 3 because our channel to 1 is disabled
986 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[0], None, &Vec::new(), 100, 42, Arc::clone(&logger)).unwrap();
987 assert_eq!(route.paths[0].len(), 3);
989 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
990 assert_eq!(route.paths[0][0].short_channel_id, 2);
991 assert_eq!(route.paths[0][0].fee_msat, 200);
992 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
993 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
994 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
996 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
997 assert_eq!(route.paths[0][1].short_channel_id, 4);
998 assert_eq!(route.paths[0][1].fee_msat, 100);
999 assert_eq!(route.paths[0][1].cltv_expiry_delta, (3 << 8) | 2);
1000 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1001 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
1003 assert_eq!(route.paths[0][2].pubkey, nodes[0]);
1004 assert_eq!(route.paths[0][2].short_channel_id, 3);
1005 assert_eq!(route.paths[0][2].fee_msat, 100);
1006 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
1007 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(1));
1008 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(3));
1010 // If we specify a channel to node7, that overrides our local channel view and that gets used
1011 let our_chans = vec![channelmanager::ChannelDetails {
1012 channel_id: [0; 32],
1013 short_channel_id: Some(42),
1014 remote_network_id: nodes[7].clone(),
1015 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1016 channel_value_satoshis: 0,
1018 outbound_capacity_msat: 0,
1019 inbound_capacity_msat: 0,
1022 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 100, 42, Arc::clone(&logger)).unwrap();
1023 assert_eq!(route.paths[0].len(), 2);
1025 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
1026 assert_eq!(route.paths[0][0].short_channel_id, 42);
1027 assert_eq!(route.paths[0][0].fee_msat, 200);
1028 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
1029 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
1030 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
1032 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1033 assert_eq!(route.paths[0][1].short_channel_id, 13);
1034 assert_eq!(route.paths[0][1].fee_msat, 100);
1035 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1036 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1037 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
1040 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
1041 let zero_fees = RoutingFees {
1043 proportional_millionths: 0,
1046 src_node_id: nodes[3].clone(),
1047 short_channel_id: 8,
1049 cltv_expiry_delta: (8 << 8) | 1,
1050 htlc_minimum_msat: 0,
1052 src_node_id: nodes[4].clone(),
1053 short_channel_id: 9,
1056 proportional_millionths: 0,
1058 cltv_expiry_delta: (9 << 8) | 1,
1059 htlc_minimum_msat: 0,
1061 src_node_id: nodes[5].clone(),
1062 short_channel_id: 10,
1064 cltv_expiry_delta: (10 << 8) | 1,
1065 htlc_minimum_msat: 0,
1070 fn last_hops_test() {
1071 let (secp_ctx, net_graph_msg_handler, logger) = build_graph();
1072 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1074 // Simple test across 2, 3, 5, and 4 via a last_hop channel
1075 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[6], None, &last_hops(&nodes).iter().collect::<Vec<_>>(), 100, 42, Arc::clone(&logger)).unwrap();
1076 assert_eq!(route.paths[0].len(), 5);
1078 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
1079 assert_eq!(route.paths[0][0].short_channel_id, 2);
1080 assert_eq!(route.paths[0][0].fee_msat, 100);
1081 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
1082 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
1083 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
1085 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1086 assert_eq!(route.paths[0][1].short_channel_id, 4);
1087 assert_eq!(route.paths[0][1].fee_msat, 0);
1088 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
1089 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1090 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
1092 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
1093 assert_eq!(route.paths[0][2].short_channel_id, 6);
1094 assert_eq!(route.paths[0][2].fee_msat, 0);
1095 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
1096 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
1097 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
1099 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
1100 assert_eq!(route.paths[0][3].short_channel_id, 11);
1101 assert_eq!(route.paths[0][3].fee_msat, 0);
1102 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
1103 // If we have a peer in the node map, we'll use their features here since we don't have
1104 // a way of figuring out their features from the invoice:
1105 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
1106 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
1108 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
1109 assert_eq!(route.paths[0][4].short_channel_id, 8);
1110 assert_eq!(route.paths[0][4].fee_msat, 100);
1111 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
1112 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
1113 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
1117 fn our_chans_last_hop_connect_test() {
1118 let (secp_ctx, net_graph_msg_handler, logger) = build_graph();
1119 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1121 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
1122 let our_chans = vec![channelmanager::ChannelDetails {
1123 channel_id: [0; 32],
1124 short_channel_id: Some(42),
1125 remote_network_id: nodes[3].clone(),
1126 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1127 channel_value_satoshis: 0,
1129 outbound_capacity_msat: 0,
1130 inbound_capacity_msat: 0,
1133 let mut last_hops = last_hops(&nodes);
1134 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[6], Some(&our_chans.iter().collect::<Vec<_>>()), &last_hops.iter().collect::<Vec<_>>(), 100, 42, Arc::clone(&logger)).unwrap();
1135 assert_eq!(route.paths[0].len(), 2);
1137 assert_eq!(route.paths[0][0].pubkey, nodes[3]);
1138 assert_eq!(route.paths[0][0].short_channel_id, 42);
1139 assert_eq!(route.paths[0][0].fee_msat, 0);
1140 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
1141 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
1142 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
1144 assert_eq!(route.paths[0][1].pubkey, nodes[6]);
1145 assert_eq!(route.paths[0][1].short_channel_id, 8);
1146 assert_eq!(route.paths[0][1].fee_msat, 100);
1147 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1148 assert_eq!(route.paths[0][1].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
1149 assert_eq!(route.paths[0][1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
1151 last_hops[0].fees.base_msat = 1000;
1153 // Revert to via 6 as the fee on 8 goes up
1154 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[6], None, &last_hops.iter().collect::<Vec<_>>(), 100, 42, Arc::clone(&logger)).unwrap();
1155 assert_eq!(route.paths[0].len(), 4);
1157 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
1158 assert_eq!(route.paths[0][0].short_channel_id, 2);
1159 assert_eq!(route.paths[0][0].fee_msat, 200); // fee increased as its % of value transferred across node
1160 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
1161 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
1162 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
1164 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1165 assert_eq!(route.paths[0][1].short_channel_id, 4);
1166 assert_eq!(route.paths[0][1].fee_msat, 100);
1167 assert_eq!(route.paths[0][1].cltv_expiry_delta, (7 << 8) | 1);
1168 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1169 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
1171 assert_eq!(route.paths[0][2].pubkey, nodes[5]);
1172 assert_eq!(route.paths[0][2].short_channel_id, 7);
1173 assert_eq!(route.paths[0][2].fee_msat, 0);
1174 assert_eq!(route.paths[0][2].cltv_expiry_delta, (10 << 8) | 1);
1175 // If we have a peer in the node map, we'll use their features here since we don't have
1176 // a way of figuring out their features from the invoice:
1177 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
1178 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(7));
1180 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
1181 assert_eq!(route.paths[0][3].short_channel_id, 10);
1182 assert_eq!(route.paths[0][3].fee_msat, 100);
1183 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
1184 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
1185 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
1187 // ...but still use 8 for larger payments as 6 has a variable feerate
1188 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[6], None, &last_hops.iter().collect::<Vec<_>>(), 2000, 42, Arc::clone(&logger)).unwrap();
1189 assert_eq!(route.paths[0].len(), 5);
1191 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
1192 assert_eq!(route.paths[0][0].short_channel_id, 2);
1193 assert_eq!(route.paths[0][0].fee_msat, 3000);
1194 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
1195 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
1196 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
1198 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1199 assert_eq!(route.paths[0][1].short_channel_id, 4);
1200 assert_eq!(route.paths[0][1].fee_msat, 0);
1201 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
1202 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1203 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
1205 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
1206 assert_eq!(route.paths[0][2].short_channel_id, 6);
1207 assert_eq!(route.paths[0][2].fee_msat, 0);
1208 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
1209 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
1210 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
1212 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
1213 assert_eq!(route.paths[0][3].short_channel_id, 11);
1214 assert_eq!(route.paths[0][3].fee_msat, 1000);
1215 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
1216 // If we have a peer in the node map, we'll use their features here since we don't have
1217 // a way of figuring out their features from the invoice:
1218 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
1219 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
1221 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
1222 assert_eq!(route.paths[0][4].short_channel_id, 8);
1223 assert_eq!(route.paths[0][4].fee_msat, 2000);
1224 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
1225 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
1226 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
1230 fn unannounced_path_test() {
1231 // We should be able to send a payment to a destination without any help of a routing graph
1232 // if we have a channel with a common counterparty that appears in the first and last hop
1234 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
1235 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
1236 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
1238 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
1239 let last_hops = vec![RouteHint {
1240 src_node_id: middle_node_id,
1241 short_channel_id: 8,
1244 proportional_millionths: 0,
1246 cltv_expiry_delta: (8 << 8) | 1,
1247 htlc_minimum_msat: 0,
1249 let our_chans = vec![channelmanager::ChannelDetails {
1250 channel_id: [0; 32],
1251 short_channel_id: Some(42),
1252 remote_network_id: middle_node_id,
1253 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1254 channel_value_satoshis: 100000,
1256 outbound_capacity_msat: 100000,
1257 inbound_capacity_msat: 100000,
1260 let route = get_route(&source_node_id, &NetworkGraph::new(), &target_node_id, Some(&our_chans.iter().collect::<Vec<_>>()), &last_hops.iter().collect::<Vec<_>>(), 100, 42, Arc::new(test_utils::TestLogger::new())).unwrap();
1262 assert_eq!(route.paths[0].len(), 2);
1264 assert_eq!(route.paths[0][0].pubkey, middle_node_id);
1265 assert_eq!(route.paths[0][0].short_channel_id, 42);
1266 assert_eq!(route.paths[0][0].fee_msat, 1000);
1267 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
1268 assert_eq!(route.paths[0][0].node_features.le_flags(), &[0b11]);
1269 assert_eq!(route.paths[0][0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
1271 assert_eq!(route.paths[0][1].pubkey, target_node_id);
1272 assert_eq!(route.paths[0][1].short_channel_id, 8);
1273 assert_eq!(route.paths[0][1].fee_msat, 100);
1274 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1275 assert_eq!(route.paths[0][1].node_features.le_flags(), &[0; 0]); // We dont pass flags in from invoices yet
1276 assert_eq!(route.paths[0][1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly