1 //! The top-level routing/network map tracking logic lives here.
3 //! You probably want to create a Router and use that as your RoutingMessageHandler and then
4 //! interrogate it to get routes for your own payments.
6 use secp256k1::key::PublicKey;
7 use secp256k1::{Secp256k1,Message};
10 use bitcoin::util::hash::Sha256dHash;
11 use bitcoin::blockdata::script::Builder;
12 use bitcoin::blockdata::opcodes;
14 use chain::chaininterface::{ChainError, ChainWatchInterface};
15 use ln::channelmanager;
16 use ln::msgs::{ErrorAction,HandleError,RoutingMessageHandler,NetAddress,GlobalFeatures};
18 use util::ser::Writeable;
19 use util::logger::Logger;
22 use std::sync::{RwLock,Arc};
23 use std::collections::{HashMap,BinaryHeap};
24 use std::collections::hash_map::Entry;
30 /// The node_id of the node at this hop.
31 pub pubkey: PublicKey,
32 /// The channel that should be used from the previous hop to reach this node.
33 pub short_channel_id: u64,
34 /// The fee taken on this hop. For the last hop, this should be the full value of the payment.
36 /// The CLTV delta added for this hop. For the last hop, this should be the full CLTV value
37 /// expected at the destination, in excess of the current block height.
38 pub cltv_expiry_delta: u32,
41 /// A route from us through the network to a destination
44 /// The list of hops, NOT INCLUDING our own, where the last hop is the destination. Thus, this
45 /// must always be at least length one. By protocol rules, this may not currently exceed 20 in
47 pub hops: Vec<RouteHop>,
50 struct DirectionalChannelInfo {
51 src_node_id: PublicKey,
54 cltv_expiry_delta: u16,
55 htlc_minimum_msat: u64,
57 fee_proportional_millionths: u32,
60 impl std::fmt::Display for DirectionalChannelInfo {
61 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
62 write!(f, "src_node_id {}, last_update {}, enabled {}, cltv_expiry_delta {}, htlc_minimum_msat {}, fee_base_msat {}, fee_proportional_millionths {}", log_pubkey!(self.src_node_id), self.last_update, self.enabled, self.cltv_expiry_delta, self.htlc_minimum_msat, self.fee_base_msat, self.fee_proportional_millionths)?;
68 features: GlobalFeatures,
69 one_to_two: DirectionalChannelInfo,
70 two_to_one: DirectionalChannelInfo,
73 impl std::fmt::Display for ChannelInfo {
74 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
75 write!(f, "features: {}, one_to_two: {}, two_to_one: {}", log_bytes!(self.features.encode()), self.one_to_two, self.two_to_one)?;
81 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
82 channels: Vec<(u64, Sha256dHash)>,
83 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
86 lowest_inbound_channel_fee_base_msat: u32,
87 lowest_inbound_channel_fee_proportional_millionths: u32,
89 features: GlobalFeatures,
93 addresses: Vec<NetAddress>,
96 impl std::fmt::Display for NodeInfo {
97 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
98 write!(f, "features: {}, last_update: {}, lowest_inbound_channel_fee_base_msat: {}, lowest_inbound_channel_fee_proportional_millionths: {}, channels: {:?}", log_bytes!(self.features.encode()), self.last_update, self.lowest_inbound_channel_fee_base_msat, self.lowest_inbound_channel_fee_proportional_millionths, &self.channels[..])?;
104 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
105 channels: HashMap<(u64, Sha256dHash), ChannelInfo>,
106 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
107 channels: HashMap<u64, ChannelInfo>,
109 our_node_id: PublicKey,
110 nodes: HashMap<PublicKey, NodeInfo>,
112 struct MutNetworkMap<'a> {
113 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
114 channels: &'a mut HashMap<(u64, Sha256dHash), ChannelInfo>,
115 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
116 channels: &'a mut HashMap<u64, ChannelInfo>,
117 nodes: &'a mut HashMap<PublicKey, NodeInfo>,
120 fn borrow_parts(&mut self) -> MutNetworkMap {
122 channels: &mut self.channels,
123 nodes: &mut self.nodes,
127 impl std::fmt::Display for NetworkMap {
128 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
129 write!(f, "Node id {} network map\n[Channels]\n", log_pubkey!(self.our_node_id))?;
130 for (key, val) in self.channels.iter() {
131 write!(f, " {}: {}\n", key, val)?;
133 write!(f, "[Nodes]\n")?;
134 for (key, val) in self.nodes.iter() {
135 write!(f, " {}: {}\n", log_pubkey!(key), val)?;
142 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
144 fn get_key(short_channel_id: u64, chain_hash: Sha256dHash) -> (u64, Sha256dHash) {
145 (short_channel_id, chain_hash)
148 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
150 fn get_key(short_channel_id: u64, _: Sha256dHash) -> u64 {
154 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
156 fn get_short_id(id: &(u64, Sha256dHash)) -> &u64 {
160 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
162 fn get_short_id(id: &u64) -> &u64 {
167 /// A channel descriptor which provides a last-hop route to get_route
168 pub struct RouteHint {
169 /// The node_id of the non-target end of the route
170 pub src_node_id: PublicKey,
171 /// The short_channel_id of this channel
172 pub short_channel_id: u64,
173 /// The static msat-denominated fee which must be paid to use this channel
174 pub fee_base_msat: u32,
175 /// The dynamic proportional fee which must be paid to use this channel, denominated in
176 /// millionths of the value being forwarded to the next hop.
177 pub fee_proportional_millionths: u32,
178 /// The difference in CLTV values between this node and the next node.
179 pub cltv_expiry_delta: u16,
180 /// The minimum value, in msat, which must be relayed to the next hop.
181 pub htlc_minimum_msat: u64,
184 /// Tracks a view of the network, receiving updates from peers and generating Routes to
185 /// payment destinations.
187 secp_ctx: Secp256k1<secp256k1::VerifyOnly>,
188 network_map: RwLock<NetworkMap>,
189 chain_monitor: Arc<ChainWatchInterface>,
193 macro_rules! secp_verify_sig {
194 ( $secp_ctx: expr, $msg: expr, $sig: expr, $pubkey: expr ) => {
195 match $secp_ctx.verify($msg, $sig, $pubkey) {
197 Err(_) => return Err(HandleError{err: "Invalid signature from remote node", action: None}),
202 impl RoutingMessageHandler for Router {
203 fn handle_node_announcement(&self, msg: &msgs::NodeAnnouncement) -> Result<bool, HandleError> {
204 let msg_hash = Message::from_slice(&Sha256dHash::from_data(&msg.contents.encode()[..])[..]).unwrap();
205 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.signature, &msg.contents.node_id);
207 if msg.contents.features.requires_unknown_bits() {
208 panic!("Unknown-required-features NodeAnnouncements should never deserialize!");
211 let mut network = self.network_map.write().unwrap();
212 match network.nodes.get_mut(&msg.contents.node_id) {
213 None => Err(HandleError{err: "No existing channels for node_announcement", action: Some(ErrorAction::IgnoreError)}),
215 if node.last_update >= msg.contents.timestamp {
216 return Err(HandleError{err: "Update older than last processed update", action: Some(ErrorAction::IgnoreError)});
219 node.features = msg.contents.features.clone();
220 node.last_update = msg.contents.timestamp;
221 node.rgb = msg.contents.rgb;
222 node.alias = msg.contents.alias;
223 node.addresses = msg.contents.addresses.clone();
224 Ok(msg.contents.excess_data.is_empty() && msg.contents.excess_address_data.is_empty() && !msg.contents.features.supports_unknown_bits())
229 fn handle_channel_announcement(&self, msg: &msgs::ChannelAnnouncement) -> Result<bool, HandleError> {
230 if msg.contents.node_id_1 == msg.contents.node_id_2 || msg.contents.bitcoin_key_1 == msg.contents.bitcoin_key_2 {
231 return Err(HandleError{err: "Channel announcement node had a channel with itself", action: Some(ErrorAction::IgnoreError)});
234 let msg_hash = Message::from_slice(&Sha256dHash::from_data(&msg.contents.encode()[..])[..]).unwrap();
235 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.node_signature_1, &msg.contents.node_id_1);
236 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.node_signature_2, &msg.contents.node_id_2);
237 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.bitcoin_signature_1, &msg.contents.bitcoin_key_1);
238 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.bitcoin_signature_2, &msg.contents.bitcoin_key_2);
240 if msg.contents.features.requires_unknown_bits() {
241 panic!("Unknown-required-features ChannelAnnouncements should never deserialize!");
244 let checked_utxo = match self.chain_monitor.get_chain_utxo(msg.contents.chain_hash, msg.contents.short_channel_id) {
245 Ok((script_pubkey, _value)) => {
246 let expected_script = Builder::new().push_opcode(opcodes::All::OP_PUSHNUM_2)
247 .push_slice(&msg.contents.bitcoin_key_1.serialize())
248 .push_slice(&msg.contents.bitcoin_key_2.serialize())
249 .push_opcode(opcodes::All::OP_PUSHNUM_2).push_opcode(opcodes::All::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
250 if script_pubkey != expected_script {
251 return Err(HandleError{err: "Channel announcement keys didn't match on-chain script", action: Some(ErrorAction::IgnoreError)});
253 //TODO: Check if value is worth storing, use it to inform routing, and compare it
254 //to the new HTLC max field in channel_update
257 Err(ChainError::NotSupported) => {
258 // Tentatively accept, potentially exposing us to DoS attacks
261 Err(ChainError::NotWatched) => {
262 return Err(HandleError{err: "Channel announced on an unknown chain", action: Some(ErrorAction::IgnoreError)});
264 Err(ChainError::UnknownTx) => {
265 return Err(HandleError{err: "Channel announced without corresponding UTXO entry", action: Some(ErrorAction::IgnoreError)});
269 let mut network_lock = self.network_map.write().unwrap();
270 let network = network_lock.borrow_parts();
272 let chan_info = ChannelInfo {
273 features: msg.contents.features.clone(),
274 one_to_two: DirectionalChannelInfo {
275 src_node_id: msg.contents.node_id_1.clone(),
278 cltv_expiry_delta: u16::max_value(),
279 htlc_minimum_msat: u64::max_value(),
280 fee_base_msat: u32::max_value(),
281 fee_proportional_millionths: u32::max_value(),
283 two_to_one: DirectionalChannelInfo {
284 src_node_id: msg.contents.node_id_2.clone(),
287 cltv_expiry_delta: u16::max_value(),
288 htlc_minimum_msat: u64::max_value(),
289 fee_base_msat: u32::max_value(),
290 fee_proportional_millionths: u32::max_value(),
294 match network.channels.entry(NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash)) {
295 Entry::Occupied(mut entry) => {
296 //TODO: because asking the blockchain if short_channel_id is valid is only optional
297 //in the blockchain API, we need to handle it smartly here, though its unclear
300 // Either our UTXO provider is busted, there was a reorg, or the UTXO provider
301 // only sometimes returns results. In any case remove the previous entry. Note
302 // that the spec expects us to "blacklist" the node_ids involved, but we can't
304 // a) we don't *require* a UTXO provider that always returns results.
305 // b) we don't track UTXOs of channels we know about and remove them if they
307 // c) it's unclear how to do so without exposing ourselves to massive DoS risk.
308 Self::remove_channel_in_nodes(network.nodes, &entry.get(), msg.contents.short_channel_id);
309 *entry.get_mut() = chan_info;
311 return Err(HandleError{err: "Already have knowledge of channel", action: Some(ErrorAction::IgnoreError)})
314 Entry::Vacant(entry) => {
315 entry.insert(chan_info);
319 macro_rules! add_channel_to_node {
320 ( $node_id: expr ) => {
321 match network.nodes.entry($node_id) {
322 Entry::Occupied(node_entry) => {
323 node_entry.into_mut().channels.push(NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash));
325 Entry::Vacant(node_entry) => {
326 node_entry.insert(NodeInfo {
327 channels: vec!(NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash)),
328 lowest_inbound_channel_fee_base_msat: u32::max_value(),
329 lowest_inbound_channel_fee_proportional_millionths: u32::max_value(),
330 features: GlobalFeatures::new(),
334 addresses: Vec::new(),
341 add_channel_to_node!(msg.contents.node_id_1);
342 add_channel_to_node!(msg.contents.node_id_2);
344 Ok(msg.contents.excess_data.is_empty() && !msg.contents.features.supports_unknown_bits())
347 fn handle_htlc_fail_channel_update(&self, update: &msgs::HTLCFailChannelUpdate) {
349 &msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg } => {
350 let _ = self.handle_channel_update(msg);
352 &msgs::HTLCFailChannelUpdate::ChannelClosed { ref short_channel_id, is_permanent:_ } => {
354 let mut network = self.network_map.write().unwrap();
355 if let Some(chan) = network.channels.remove(short_channel_id) {
356 Self::remove_channel_in_nodes(&mut network.nodes, &chan, *short_channel_id);
359 &msgs::HTLCFailChannelUpdate::NodeFailure { ref node_id, is_permanent:_ } => {
361 //let mut network = self.network_map.write().unwrap();
362 //TODO: check _blamed_upstream_node
363 self.mark_node_bad(node_id, false);
368 fn handle_channel_update(&self, msg: &msgs::ChannelUpdate) -> Result<bool, HandleError> {
369 let mut network = self.network_map.write().unwrap();
371 let chan_enabled = msg.contents.flags & (1 << 1) != (1 << 1);
372 let chan_was_enabled;
374 match network.channels.get_mut(&NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash)) {
375 None => return Err(HandleError{err: "Couldn't find channel for update", action: Some(ErrorAction::IgnoreError)}),
377 macro_rules! maybe_update_channel_info {
378 ( $target: expr) => {
379 if $target.last_update >= msg.contents.timestamp {
380 return Err(HandleError{err: "Update older than last processed update", action: Some(ErrorAction::IgnoreError)});
382 chan_was_enabled = $target.enabled;
383 $target.last_update = msg.contents.timestamp;
384 $target.enabled = chan_enabled;
385 $target.cltv_expiry_delta = msg.contents.cltv_expiry_delta;
386 $target.htlc_minimum_msat = msg.contents.htlc_minimum_msat;
387 $target.fee_base_msat = msg.contents.fee_base_msat;
388 $target.fee_proportional_millionths = msg.contents.fee_proportional_millionths;
392 let msg_hash = Message::from_slice(&Sha256dHash::from_data(&msg.contents.encode()[..])[..]).unwrap();
393 if msg.contents.flags & 1 == 1 {
394 dest_node_id = channel.one_to_two.src_node_id.clone();
395 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.signature, &channel.two_to_one.src_node_id);
396 maybe_update_channel_info!(channel.two_to_one);
398 dest_node_id = channel.two_to_one.src_node_id.clone();
399 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.signature, &channel.one_to_two.src_node_id);
400 maybe_update_channel_info!(channel.one_to_two);
406 let node = network.nodes.get_mut(&dest_node_id).unwrap();
407 node.lowest_inbound_channel_fee_base_msat = cmp::min(node.lowest_inbound_channel_fee_base_msat, msg.contents.fee_base_msat);
408 node.lowest_inbound_channel_fee_proportional_millionths = cmp::min(node.lowest_inbound_channel_fee_proportional_millionths, msg.contents.fee_proportional_millionths);
409 } else if chan_was_enabled {
410 let mut lowest_inbound_channel_fee_base_msat = u32::max_value();
411 let mut lowest_inbound_channel_fee_proportional_millionths = u32::max_value();
414 let node = network.nodes.get(&dest_node_id).unwrap();
416 for chan_id in node.channels.iter() {
417 let chan = network.channels.get(chan_id).unwrap();
418 if chan.one_to_two.src_node_id == dest_node_id {
419 lowest_inbound_channel_fee_base_msat = cmp::min(lowest_inbound_channel_fee_base_msat, chan.two_to_one.fee_base_msat);
420 lowest_inbound_channel_fee_proportional_millionths = cmp::min(lowest_inbound_channel_fee_proportional_millionths, chan.two_to_one.fee_proportional_millionths);
422 lowest_inbound_channel_fee_base_msat = cmp::min(lowest_inbound_channel_fee_base_msat, chan.one_to_two.fee_base_msat);
423 lowest_inbound_channel_fee_proportional_millionths = cmp::min(lowest_inbound_channel_fee_proportional_millionths, chan.one_to_two.fee_proportional_millionths);
428 //TODO: satisfy the borrow-checker without a double-map-lookup :(
429 let mut_node = network.nodes.get_mut(&dest_node_id).unwrap();
430 mut_node.lowest_inbound_channel_fee_base_msat = lowest_inbound_channel_fee_base_msat;
431 mut_node.lowest_inbound_channel_fee_proportional_millionths = lowest_inbound_channel_fee_proportional_millionths;
434 Ok(msg.contents.excess_data.is_empty())
438 #[derive(Eq, PartialEq)]
439 struct RouteGraphNode {
441 lowest_fee_to_peer_through_node: u64,
442 lowest_fee_to_node: u64,
445 impl cmp::Ord for RouteGraphNode {
446 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
447 other.lowest_fee_to_peer_through_node.cmp(&self.lowest_fee_to_peer_through_node)
448 .then_with(|| other.pubkey.serialize().cmp(&self.pubkey.serialize()))
452 impl cmp::PartialOrd for RouteGraphNode {
453 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
454 Some(self.cmp(other))
458 struct DummyDirectionalChannelInfo {
459 src_node_id: PublicKey,
460 cltv_expiry_delta: u32,
461 htlc_minimum_msat: u64,
463 fee_proportional_millionths: u32,
467 /// Creates a new router with the given node_id to be used as the source for get_route()
468 pub fn new(our_pubkey: PublicKey, chain_monitor: Arc<ChainWatchInterface>, logger: Arc<Logger>) -> Router {
469 let mut nodes = HashMap::new();
470 nodes.insert(our_pubkey.clone(), NodeInfo {
471 channels: Vec::new(),
472 lowest_inbound_channel_fee_base_msat: u32::max_value(),
473 lowest_inbound_channel_fee_proportional_millionths: u32::max_value(),
474 features: GlobalFeatures::new(),
478 addresses: Vec::new(),
481 secp_ctx: Secp256k1::verification_only(),
482 network_map: RwLock::new(NetworkMap {
483 channels: HashMap::new(),
484 our_node_id: our_pubkey,
492 /// Dumps the entire network view of this Router to the logger provided in the constructor at
494 pub fn trace_state(&self) {
495 log_trace!(self, "{}", self.network_map.read().unwrap());
498 /// Get network addresses by node id
499 pub fn get_addresses(&self, pubkey: &PublicKey) -> Option<Vec<NetAddress>> {
500 let network = self.network_map.read().unwrap();
501 network.nodes.get(pubkey).map(|n| n.addresses.clone())
504 /// Marks a node as having failed a route. This will avoid re-using the node in routes for now,
505 /// with an expotnential decay in node "badness". Note that there is deliberately no
506 /// mark_channel_bad as a node may simply lie and suggest that an upstream channel from it is
507 /// what failed the route and not the node itself. Instead, setting the blamed_upstream_node
508 /// boolean will reduce the penalty, returning the node to usability faster. If the node is
509 /// behaving correctly, it will disable the failing channel and we will use it again next time.
510 pub fn mark_node_bad(&self, _node_id: &PublicKey, _blamed_upstream_node: bool) {
514 fn remove_channel_in_nodes(nodes: &mut HashMap<PublicKey, NodeInfo>, chan: &ChannelInfo, short_channel_id: u64) {
515 macro_rules! remove_from_node {
516 ($node_id: expr) => {
517 if let Entry::Occupied(mut entry) = nodes.entry($node_id) {
518 entry.get_mut().channels.retain(|chan_id| {
519 short_channel_id != *NetworkMap::get_short_id(chan_id)
521 if entry.get().channels.is_empty() {
522 entry.remove_entry();
525 panic!("Had channel that pointed to unknown node (ie inconsistent network map)!");
529 remove_from_node!(chan.one_to_two.src_node_id);
530 remove_from_node!(chan.two_to_one.src_node_id);
533 /// Gets a route from us to the given target node.
535 /// Extra routing hops between known nodes and the target will be used if they are included in
538 /// If some channels aren't announced, it may be useful to fill in a first_hops with the
539 /// results from a local ChannelManager::list_usable_channels() call. If it is filled in, our
540 /// (this Router's) view of our local channels will be ignored, and only those in first_hops
543 /// Panics if first_hops contains channels without short_channel_ids
544 /// (ChannelManager::list_usable_channels will never include such channels).
546 /// The fees on channels from us to next-hops are ignored (as they are assumed to all be
547 /// equal), however the enabled/disabled bit on such channels as well as the htlc_minimum_msat
548 /// *is* checked as they may change based on the receiving node.
549 pub fn get_route(&self, target: &PublicKey, first_hops: Option<&[channelmanager::ChannelDetails]>, last_hops: &[RouteHint], final_value_msat: u64, final_cltv: u32) -> Result<Route, HandleError> {
550 // TODO: Obviously *only* using total fee cost sucks. We should consider weighting by
551 // uptime/success in using a node in the past.
552 let network = self.network_map.read().unwrap();
554 if *target == network.our_node_id {
555 return Err(HandleError{err: "Cannot generate a route to ourselves", action: None});
558 if final_value_msat > 21_000_000 * 1_0000_0000 * 1000 {
559 return Err(HandleError{err: "Cannot generate a route of more value than all existing satoshis", action: None});
562 // We do a dest-to-source Dijkstra's sorting by each node's distance from the destination
563 // plus the minimum per-HTLC fee to get from it to another node (aka "shitty A*").
564 // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
565 // to use as the A* heuristic beyond just the cost to get one node further than the current
568 let dummy_directional_info = DummyDirectionalChannelInfo { // used for first_hops routes
569 src_node_id: network.our_node_id.clone(),
570 cltv_expiry_delta: 0,
571 htlc_minimum_msat: 0,
573 fee_proportional_millionths: 0,
576 let mut targets = BinaryHeap::new(); //TODO: Do we care about switching to eg Fibbonaci heap?
577 let mut dist = HashMap::with_capacity(network.nodes.len());
579 let mut first_hop_targets = HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
580 if let Some(hops) = first_hops {
582 let short_channel_id = chan.short_channel_id.expect("first_hops should be filled in with usable channels, not pending ones");
583 if chan.remote_network_id == *target {
585 hops: vec![RouteHop {
586 pubkey: chan.remote_network_id,
588 fee_msat: final_value_msat,
589 cltv_expiry_delta: final_cltv,
593 first_hop_targets.insert(chan.remote_network_id, short_channel_id);
595 if first_hop_targets.is_empty() {
596 return Err(HandleError{err: "Cannot route when there are no outbound routes away from us", action: None});
600 macro_rules! add_entry {
601 // Adds entry which goes from the node pointed to by $directional_info to
602 // $dest_node_id over the channel with id $chan_id with fees described in
603 // $directional_info.
604 ( $chan_id: expr, $dest_node_id: expr, $directional_info: expr, $starting_fee_msat: expr ) => {
605 //TODO: Explore simply adding fee to hit htlc_minimum_msat
606 if $starting_fee_msat as u64 + final_value_msat > $directional_info.htlc_minimum_msat {
607 let proportional_fee_millions = ($starting_fee_msat + final_value_msat).checked_mul($directional_info.fee_proportional_millionths as u64);
608 if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
609 ($directional_info.fee_base_msat as u64).checked_add(part / 1000000) })
611 let mut total_fee = $starting_fee_msat as u64;
612 let hm_entry = dist.entry(&$directional_info.src_node_id);
613 let old_entry = hm_entry.or_insert_with(|| {
614 let node = network.nodes.get(&$directional_info.src_node_id).unwrap();
616 node.lowest_inbound_channel_fee_base_msat,
617 node.lowest_inbound_channel_fee_proportional_millionths,
619 pubkey: $dest_node_id.clone(),
622 cltv_expiry_delta: 0,
625 if $directional_info.src_node_id != network.our_node_id {
626 // Ignore new_fee for channel-from-us as we assume all channels-from-us
627 // will have the same effective-fee
628 total_fee += new_fee;
629 if let Some(fee_inc) = final_value_msat.checked_add(total_fee).and_then(|inc| { (old_entry.2 as u64).checked_mul(inc) }) {
630 total_fee += fee_inc / 1000000 + (old_entry.1 as u64);
632 // max_value means we'll always fail the old_entry.0 > total_fee check
633 total_fee = u64::max_value();
636 let new_graph_node = RouteGraphNode {
637 pubkey: $directional_info.src_node_id,
638 lowest_fee_to_peer_through_node: total_fee,
639 lowest_fee_to_node: $starting_fee_msat as u64 + new_fee,
641 if old_entry.0 > total_fee {
642 targets.push(new_graph_node);
643 old_entry.0 = total_fee;
644 old_entry.3 = RouteHop {
645 pubkey: $dest_node_id.clone(),
646 short_channel_id: $chan_id.clone(),
647 fee_msat: new_fee, // This field is ignored on the last-hop anyway
648 cltv_expiry_delta: $directional_info.cltv_expiry_delta as u32,
656 macro_rules! add_entries_to_cheapest_to_target_node {
657 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr ) => {
658 if first_hops.is_some() {
659 if let Some(first_hop) = first_hop_targets.get(&$node_id) {
660 add_entry!(first_hop, $node_id, dummy_directional_info, $fee_to_target_msat);
664 for chan_id in $node.channels.iter() {
665 let chan = network.channels.get(chan_id).unwrap();
666 if chan.one_to_two.src_node_id == *$node_id {
667 // ie $node is one, ie next hop in A* is two, via the two_to_one channel
668 if first_hops.is_none() || chan.two_to_one.src_node_id != network.our_node_id {
669 if chan.two_to_one.enabled {
670 add_entry!(chan_id, chan.one_to_two.src_node_id, chan.two_to_one, $fee_to_target_msat);
674 if first_hops.is_none() || chan.one_to_two.src_node_id != network.our_node_id {
675 if chan.one_to_two.enabled {
676 add_entry!(chan_id, chan.two_to_one.src_node_id, chan.one_to_two, $fee_to_target_msat);
684 match network.nodes.get(target) {
687 add_entries_to_cheapest_to_target_node!(node, target, 0);
691 for hop in last_hops.iter() {
692 if first_hops.is_none() || hop.src_node_id != network.our_node_id { // first_hop overrules last_hops
693 if network.nodes.get(&hop.src_node_id).is_some() {
694 if first_hops.is_some() {
695 if let Some(first_hop) = first_hop_targets.get(&hop.src_node_id) {
696 add_entry!(first_hop, hop.src_node_id, dummy_directional_info, 0);
699 add_entry!(hop.short_channel_id, target, hop, 0);
704 while let Some(RouteGraphNode { pubkey, lowest_fee_to_node, .. }) = targets.pop() {
705 if pubkey == network.our_node_id {
706 let mut res = vec!(dist.remove(&network.our_node_id).unwrap().3);
707 while res.last().unwrap().pubkey != *target {
708 let new_entry = match dist.remove(&res.last().unwrap().pubkey) {
710 None => return Err(HandleError{err: "Failed to find a non-fee-overflowing path to the given destination", action: None}),
712 res.last_mut().unwrap().fee_msat = new_entry.fee_msat;
713 res.last_mut().unwrap().cltv_expiry_delta = new_entry.cltv_expiry_delta;
716 res.last_mut().unwrap().fee_msat = final_value_msat;
717 res.last_mut().unwrap().cltv_expiry_delta = final_cltv;
718 let route = Route { hops: res };
719 log_trace!(self, "Got route: {}", log_route!(route));
723 match network.nodes.get(&pubkey) {
726 add_entries_to_cheapest_to_target_node!(node, &pubkey, lowest_fee_to_node);
731 Err(HandleError{err: "Failed to find a path to the given destination", action: None})
737 use chain::chaininterface;
738 use ln::channelmanager;
739 use ln::router::{Router,NodeInfo,NetworkMap,ChannelInfo,DirectionalChannelInfo,RouteHint};
740 use ln::msgs::GlobalFeatures;
741 use util::test_utils;
742 use util::logger::Logger;
744 use bitcoin::util::hash::Sha256dHash;
745 use bitcoin::network::constants::Network;
749 use secp256k1::key::{PublicKey,SecretKey};
750 use secp256k1::Secp256k1;
756 let secp_ctx = Secp256k1::new();
757 let our_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap());
758 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
759 let chain_monitor = Arc::new(chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet, Arc::clone(&logger)));
760 let router = Router::new(our_id, chain_monitor, Arc::clone(&logger));
762 // Build network from our_id to node8:
764 // -1(1)2- node1 -1(3)2-
766 // our_id -1(12)2- node8 -1(13)2--- node3
768 // -1(2)2- node2 -1(4)2-
771 // chan1 1-to-2: disabled
772 // chan1 2-to-1: enabled, 0 fee
774 // chan2 1-to-2: enabled, ignored fee
775 // chan2 2-to-1: enabled, 0 fee
777 // chan3 1-to-2: enabled, 0 fee
778 // chan3 2-to-1: enabled, 100 msat fee
780 // chan4 1-to-2: enabled, 100% fee
781 // chan4 2-to-1: enabled, 0 fee
783 // chan12 1-to-2: enabled, ignored fee
784 // chan12 2-to-1: enabled, 0 fee
786 // chan13 1-to-2: enabled, 200% fee
787 // chan13 2-to-1: enabled, 0 fee
790 // -1(5)2- node4 -1(8)2--
794 // node3--1(6)2- node5 -1(9)2--- node7 (not in global route map)
796 // -1(7)2- node6 -1(10)2-
798 // chan5 1-to-2: enabled, 100 msat fee
799 // chan5 2-to-1: enabled, 0 fee
801 // chan6 1-to-2: enabled, 0 fee
802 // chan6 2-to-1: enabled, 0 fee
804 // chan7 1-to-2: enabled, 100% fee
805 // chan7 2-to-1: enabled, 0 fee
807 // chan8 1-to-2: enabled, variable fee (0 then 1000 msat)
808 // chan8 2-to-1: enabled, 0 fee
810 // chan9 1-to-2: enabled, 1001 msat fee
811 // chan9 2-to-1: enabled, 0 fee
813 // chan10 1-to-2: enabled, 0 fee
814 // chan10 2-to-1: enabled, 0 fee
816 // chan11 1-to-2: enabled, 0 fee
817 // chan11 2-to-1: enabled, 0 fee
819 let node1 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap()[..]).unwrap());
820 let node2 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0303030303030303030303030303030303030303030303030303030303030303").unwrap()[..]).unwrap());
821 let node3 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0404040404040404040404040404040404040404040404040404040404040404").unwrap()[..]).unwrap());
822 let node4 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0505050505050505050505050505050505050505050505050505050505050505").unwrap()[..]).unwrap());
823 let node5 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0606060606060606060606060606060606060606060606060606060606060606").unwrap()[..]).unwrap());
824 let node6 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0707070707070707070707070707070707070707070707070707070707070707").unwrap()[..]).unwrap());
825 let node7 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0808080808080808080808080808080808080808080808080808080808080808").unwrap()[..]).unwrap());
826 let node8 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0909090909090909090909090909090909090909090909090909090909090909").unwrap()[..]).unwrap());
828 let zero_hash = Sha256dHash::from_data(&[0; 32]);
831 let mut network = router.network_map.write().unwrap();
833 network.nodes.insert(node1.clone(), NodeInfo {
834 channels: vec!(NetworkMap::get_key(1, zero_hash.clone()), NetworkMap::get_key(3, zero_hash.clone())),
835 lowest_inbound_channel_fee_base_msat: 100,
836 lowest_inbound_channel_fee_proportional_millionths: 0,
837 features: GlobalFeatures::new(),
841 addresses: Vec::new(),
843 network.channels.insert(NetworkMap::get_key(1, zero_hash.clone()), ChannelInfo {
844 features: GlobalFeatures::new(),
845 one_to_two: DirectionalChannelInfo {
846 src_node_id: our_id.clone(),
849 cltv_expiry_delta: u16::max_value(), // This value should be ignored
850 htlc_minimum_msat: 0,
851 fee_base_msat: u32::max_value(), // This value should be ignored
852 fee_proportional_millionths: u32::max_value(), // This value should be ignored
853 }, two_to_one: DirectionalChannelInfo {
854 src_node_id: node1.clone(),
857 cltv_expiry_delta: 0,
858 htlc_minimum_msat: 0,
860 fee_proportional_millionths: 0,
863 network.nodes.insert(node2.clone(), NodeInfo {
864 channels: vec!(NetworkMap::get_key(2, zero_hash.clone()), NetworkMap::get_key(4, zero_hash.clone())),
865 lowest_inbound_channel_fee_base_msat: 0,
866 lowest_inbound_channel_fee_proportional_millionths: 0,
867 features: GlobalFeatures::new(),
871 addresses: Vec::new(),
873 network.channels.insert(NetworkMap::get_key(2, zero_hash.clone()), ChannelInfo {
874 features: GlobalFeatures::new(),
875 one_to_two: DirectionalChannelInfo {
876 src_node_id: our_id.clone(),
879 cltv_expiry_delta: u16::max_value(), // This value should be ignored
880 htlc_minimum_msat: 0,
881 fee_base_msat: u32::max_value(), // This value should be ignored
882 fee_proportional_millionths: u32::max_value(), // This value should be ignored
883 }, two_to_one: DirectionalChannelInfo {
884 src_node_id: node2.clone(),
887 cltv_expiry_delta: 0,
888 htlc_minimum_msat: 0,
890 fee_proportional_millionths: 0,
893 network.nodes.insert(node8.clone(), NodeInfo {
894 channels: vec!(NetworkMap::get_key(12, zero_hash.clone()), NetworkMap::get_key(13, zero_hash.clone())),
895 lowest_inbound_channel_fee_base_msat: 0,
896 lowest_inbound_channel_fee_proportional_millionths: 0,
897 features: GlobalFeatures::new(),
901 addresses: Vec::new(),
903 network.channels.insert(NetworkMap::get_key(12, zero_hash.clone()), ChannelInfo {
904 features: GlobalFeatures::new(),
905 one_to_two: DirectionalChannelInfo {
906 src_node_id: our_id.clone(),
909 cltv_expiry_delta: u16::max_value(), // This value should be ignored
910 htlc_minimum_msat: 0,
911 fee_base_msat: u32::max_value(), // This value should be ignored
912 fee_proportional_millionths: u32::max_value(), // This value should be ignored
913 }, two_to_one: DirectionalChannelInfo {
914 src_node_id: node8.clone(),
917 cltv_expiry_delta: 0,
918 htlc_minimum_msat: 0,
920 fee_proportional_millionths: 0,
923 network.nodes.insert(node3.clone(), NodeInfo {
925 NetworkMap::get_key(3, zero_hash.clone()),
926 NetworkMap::get_key(4, zero_hash.clone()),
927 NetworkMap::get_key(13, zero_hash.clone()),
928 NetworkMap::get_key(5, zero_hash.clone()),
929 NetworkMap::get_key(6, zero_hash.clone()),
930 NetworkMap::get_key(7, zero_hash.clone())),
931 lowest_inbound_channel_fee_base_msat: 0,
932 lowest_inbound_channel_fee_proportional_millionths: 0,
933 features: GlobalFeatures::new(),
937 addresses: Vec::new(),
939 network.channels.insert(NetworkMap::get_key(3, zero_hash.clone()), ChannelInfo {
940 features: GlobalFeatures::new(),
941 one_to_two: DirectionalChannelInfo {
942 src_node_id: node1.clone(),
945 cltv_expiry_delta: (3 << 8) | 1,
946 htlc_minimum_msat: 0,
948 fee_proportional_millionths: 0,
949 }, two_to_one: DirectionalChannelInfo {
950 src_node_id: node3.clone(),
953 cltv_expiry_delta: (3 << 8) | 2,
954 htlc_minimum_msat: 0,
956 fee_proportional_millionths: 0,
959 network.channels.insert(NetworkMap::get_key(4, zero_hash.clone()), ChannelInfo {
960 features: GlobalFeatures::new(),
961 one_to_two: DirectionalChannelInfo {
962 src_node_id: node2.clone(),
965 cltv_expiry_delta: (4 << 8) | 1,
966 htlc_minimum_msat: 0,
968 fee_proportional_millionths: 1000000,
969 }, two_to_one: DirectionalChannelInfo {
970 src_node_id: node3.clone(),
973 cltv_expiry_delta: (4 << 8) | 2,
974 htlc_minimum_msat: 0,
976 fee_proportional_millionths: 0,
979 network.channels.insert(NetworkMap::get_key(13, zero_hash.clone()), ChannelInfo {
980 features: GlobalFeatures::new(),
981 one_to_two: DirectionalChannelInfo {
982 src_node_id: node8.clone(),
985 cltv_expiry_delta: (13 << 8) | 1,
986 htlc_minimum_msat: 0,
988 fee_proportional_millionths: 2000000,
989 }, two_to_one: DirectionalChannelInfo {
990 src_node_id: node3.clone(),
993 cltv_expiry_delta: (13 << 8) | 2,
994 htlc_minimum_msat: 0,
996 fee_proportional_millionths: 0,
999 network.nodes.insert(node4.clone(), NodeInfo {
1000 channels: vec!(NetworkMap::get_key(5, zero_hash.clone()), NetworkMap::get_key(11, zero_hash.clone())),
1001 lowest_inbound_channel_fee_base_msat: 0,
1002 lowest_inbound_channel_fee_proportional_millionths: 0,
1003 features: GlobalFeatures::new(),
1007 addresses: Vec::new(),
1009 network.channels.insert(NetworkMap::get_key(5, zero_hash.clone()), ChannelInfo {
1010 features: GlobalFeatures::new(),
1011 one_to_two: DirectionalChannelInfo {
1012 src_node_id: node3.clone(),
1015 cltv_expiry_delta: (5 << 8) | 1,
1016 htlc_minimum_msat: 0,
1018 fee_proportional_millionths: 0,
1019 }, two_to_one: DirectionalChannelInfo {
1020 src_node_id: node4.clone(),
1023 cltv_expiry_delta: (5 << 8) | 2,
1024 htlc_minimum_msat: 0,
1026 fee_proportional_millionths: 0,
1029 network.nodes.insert(node5.clone(), NodeInfo {
1030 channels: vec!(NetworkMap::get_key(6, zero_hash.clone()), NetworkMap::get_key(11, zero_hash.clone())),
1031 lowest_inbound_channel_fee_base_msat: 0,
1032 lowest_inbound_channel_fee_proportional_millionths: 0,
1033 features: GlobalFeatures::new(),
1037 addresses: Vec::new(),
1039 network.channels.insert(NetworkMap::get_key(6, zero_hash.clone()), ChannelInfo {
1040 features: GlobalFeatures::new(),
1041 one_to_two: DirectionalChannelInfo {
1042 src_node_id: node3.clone(),
1045 cltv_expiry_delta: (6 << 8) | 1,
1046 htlc_minimum_msat: 0,
1048 fee_proportional_millionths: 0,
1049 }, two_to_one: DirectionalChannelInfo {
1050 src_node_id: node5.clone(),
1053 cltv_expiry_delta: (6 << 8) | 2,
1054 htlc_minimum_msat: 0,
1056 fee_proportional_millionths: 0,
1059 network.channels.insert(NetworkMap::get_key(11, zero_hash.clone()), ChannelInfo {
1060 features: GlobalFeatures::new(),
1061 one_to_two: DirectionalChannelInfo {
1062 src_node_id: node5.clone(),
1065 cltv_expiry_delta: (11 << 8) | 1,
1066 htlc_minimum_msat: 0,
1068 fee_proportional_millionths: 0,
1069 }, two_to_one: DirectionalChannelInfo {
1070 src_node_id: node4.clone(),
1073 cltv_expiry_delta: (11 << 8) | 2,
1074 htlc_minimum_msat: 0,
1076 fee_proportional_millionths: 0,
1079 network.nodes.insert(node6.clone(), NodeInfo {
1080 channels: vec!(NetworkMap::get_key(7, zero_hash.clone())),
1081 lowest_inbound_channel_fee_base_msat: 0,
1082 lowest_inbound_channel_fee_proportional_millionths: 0,
1083 features: GlobalFeatures::new(),
1087 addresses: Vec::new(),
1089 network.channels.insert(NetworkMap::get_key(7, zero_hash.clone()), ChannelInfo {
1090 features: GlobalFeatures::new(),
1091 one_to_two: DirectionalChannelInfo {
1092 src_node_id: node3.clone(),
1095 cltv_expiry_delta: (7 << 8) | 1,
1096 htlc_minimum_msat: 0,
1098 fee_proportional_millionths: 1000000,
1099 }, two_to_one: DirectionalChannelInfo {
1100 src_node_id: node6.clone(),
1103 cltv_expiry_delta: (7 << 8) | 2,
1104 htlc_minimum_msat: 0,
1106 fee_proportional_millionths: 0,
1111 { // Simple route to 3 via 2
1112 let route = router.get_route(&node3, None, &Vec::new(), 100, 42).unwrap();
1113 assert_eq!(route.hops.len(), 2);
1115 assert_eq!(route.hops[0].pubkey, node2);
1116 assert_eq!(route.hops[0].short_channel_id, 2);
1117 assert_eq!(route.hops[0].fee_msat, 100);
1118 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1120 assert_eq!(route.hops[1].pubkey, node3);
1121 assert_eq!(route.hops[1].short_channel_id, 4);
1122 assert_eq!(route.hops[1].fee_msat, 100);
1123 assert_eq!(route.hops[1].cltv_expiry_delta, 42);
1126 { // Route to 1 via 2 and 3 because our channel to 1 is disabled
1127 let route = router.get_route(&node1, None, &Vec::new(), 100, 42).unwrap();
1128 assert_eq!(route.hops.len(), 3);
1130 assert_eq!(route.hops[0].pubkey, node2);
1131 assert_eq!(route.hops[0].short_channel_id, 2);
1132 assert_eq!(route.hops[0].fee_msat, 200);
1133 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1135 assert_eq!(route.hops[1].pubkey, node3);
1136 assert_eq!(route.hops[1].short_channel_id, 4);
1137 assert_eq!(route.hops[1].fee_msat, 100);
1138 assert_eq!(route.hops[1].cltv_expiry_delta, (3 << 8) | 2);
1140 assert_eq!(route.hops[2].pubkey, node1);
1141 assert_eq!(route.hops[2].short_channel_id, 3);
1142 assert_eq!(route.hops[2].fee_msat, 100);
1143 assert_eq!(route.hops[2].cltv_expiry_delta, 42);
1146 { // If we specify a channel to node8, that overrides our local channel view and that gets used
1147 let our_chans = vec![channelmanager::ChannelDetails {
1148 channel_id: [0; 32],
1149 short_channel_id: Some(42),
1150 remote_network_id: node8.clone(),
1151 channel_value_satoshis: 0,
1154 let route = router.get_route(&node3, Some(&our_chans), &Vec::new(), 100, 42).unwrap();
1155 assert_eq!(route.hops.len(), 2);
1157 assert_eq!(route.hops[0].pubkey, node8);
1158 assert_eq!(route.hops[0].short_channel_id, 42);
1159 assert_eq!(route.hops[0].fee_msat, 200);
1160 assert_eq!(route.hops[0].cltv_expiry_delta, (13 << 8) | 1);
1162 assert_eq!(route.hops[1].pubkey, node3);
1163 assert_eq!(route.hops[1].short_channel_id, 13);
1164 assert_eq!(route.hops[1].fee_msat, 100);
1165 assert_eq!(route.hops[1].cltv_expiry_delta, 42);
1168 let mut last_hops = vec!(RouteHint {
1169 src_node_id: node4.clone(),
1170 short_channel_id: 8,
1172 fee_proportional_millionths: 0,
1173 cltv_expiry_delta: (8 << 8) | 1,
1174 htlc_minimum_msat: 0,
1176 src_node_id: node5.clone(),
1177 short_channel_id: 9,
1178 fee_base_msat: 1001,
1179 fee_proportional_millionths: 0,
1180 cltv_expiry_delta: (9 << 8) | 1,
1181 htlc_minimum_msat: 0,
1183 src_node_id: node6.clone(),
1184 short_channel_id: 10,
1186 fee_proportional_millionths: 0,
1187 cltv_expiry_delta: (10 << 8) | 1,
1188 htlc_minimum_msat: 0,
1191 { // Simple test across 2, 3, 5, and 4 via a last_hop channel
1192 let route = router.get_route(&node7, None, &last_hops, 100, 42).unwrap();
1193 assert_eq!(route.hops.len(), 5);
1195 assert_eq!(route.hops[0].pubkey, node2);
1196 assert_eq!(route.hops[0].short_channel_id, 2);
1197 assert_eq!(route.hops[0].fee_msat, 100);
1198 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1200 assert_eq!(route.hops[1].pubkey, node3);
1201 assert_eq!(route.hops[1].short_channel_id, 4);
1202 assert_eq!(route.hops[1].fee_msat, 0);
1203 assert_eq!(route.hops[1].cltv_expiry_delta, (6 << 8) | 1);
1205 assert_eq!(route.hops[2].pubkey, node5);
1206 assert_eq!(route.hops[2].short_channel_id, 6);
1207 assert_eq!(route.hops[2].fee_msat, 0);
1208 assert_eq!(route.hops[2].cltv_expiry_delta, (11 << 8) | 1);
1210 assert_eq!(route.hops[3].pubkey, node4);
1211 assert_eq!(route.hops[3].short_channel_id, 11);
1212 assert_eq!(route.hops[3].fee_msat, 0);
1213 assert_eq!(route.hops[3].cltv_expiry_delta, (8 << 8) | 1);
1215 assert_eq!(route.hops[4].pubkey, node7);
1216 assert_eq!(route.hops[4].short_channel_id, 8);
1217 assert_eq!(route.hops[4].fee_msat, 100);
1218 assert_eq!(route.hops[4].cltv_expiry_delta, 42);
1221 { // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
1222 let our_chans = vec![channelmanager::ChannelDetails {
1223 channel_id: [0; 32],
1224 short_channel_id: Some(42),
1225 remote_network_id: node4.clone(),
1226 channel_value_satoshis: 0,
1229 let route = router.get_route(&node7, Some(&our_chans), &last_hops, 100, 42).unwrap();
1230 assert_eq!(route.hops.len(), 2);
1232 assert_eq!(route.hops[0].pubkey, node4);
1233 assert_eq!(route.hops[0].short_channel_id, 42);
1234 assert_eq!(route.hops[0].fee_msat, 0);
1235 assert_eq!(route.hops[0].cltv_expiry_delta, (8 << 8) | 1);
1237 assert_eq!(route.hops[1].pubkey, node7);
1238 assert_eq!(route.hops[1].short_channel_id, 8);
1239 assert_eq!(route.hops[1].fee_msat, 100);
1240 assert_eq!(route.hops[1].cltv_expiry_delta, 42);
1243 last_hops[0].fee_base_msat = 1000;
1245 { // Revert to via 6 as the fee on 8 goes up
1246 let route = router.get_route(&node7, None, &last_hops, 100, 42).unwrap();
1247 assert_eq!(route.hops.len(), 4);
1249 assert_eq!(route.hops[0].pubkey, node2);
1250 assert_eq!(route.hops[0].short_channel_id, 2);
1251 assert_eq!(route.hops[0].fee_msat, 200); // fee increased as its % of value transferred across node
1252 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1254 assert_eq!(route.hops[1].pubkey, node3);
1255 assert_eq!(route.hops[1].short_channel_id, 4);
1256 assert_eq!(route.hops[1].fee_msat, 100);
1257 assert_eq!(route.hops[1].cltv_expiry_delta, (7 << 8) | 1);
1259 assert_eq!(route.hops[2].pubkey, node6);
1260 assert_eq!(route.hops[2].short_channel_id, 7);
1261 assert_eq!(route.hops[2].fee_msat, 0);
1262 assert_eq!(route.hops[2].cltv_expiry_delta, (10 << 8) | 1);
1264 assert_eq!(route.hops[3].pubkey, node7);
1265 assert_eq!(route.hops[3].short_channel_id, 10);
1266 assert_eq!(route.hops[3].fee_msat, 100);
1267 assert_eq!(route.hops[3].cltv_expiry_delta, 42);
1270 { // ...but still use 8 for larger payments as 6 has a variable feerate
1271 let route = router.get_route(&node7, None, &last_hops, 2000, 42).unwrap();
1272 assert_eq!(route.hops.len(), 5);
1274 assert_eq!(route.hops[0].pubkey, node2);
1275 assert_eq!(route.hops[0].short_channel_id, 2);
1276 assert_eq!(route.hops[0].fee_msat, 3000);
1277 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1279 assert_eq!(route.hops[1].pubkey, node3);
1280 assert_eq!(route.hops[1].short_channel_id, 4);
1281 assert_eq!(route.hops[1].fee_msat, 0);
1282 assert_eq!(route.hops[1].cltv_expiry_delta, (6 << 8) | 1);
1284 assert_eq!(route.hops[2].pubkey, node5);
1285 assert_eq!(route.hops[2].short_channel_id, 6);
1286 assert_eq!(route.hops[2].fee_msat, 0);
1287 assert_eq!(route.hops[2].cltv_expiry_delta, (11 << 8) | 1);
1289 assert_eq!(route.hops[3].pubkey, node4);
1290 assert_eq!(route.hops[3].short_channel_id, 11);
1291 assert_eq!(route.hops[3].fee_msat, 1000);
1292 assert_eq!(route.hops[3].cltv_expiry_delta, (8 << 8) | 1);
1294 assert_eq!(route.hops[4].pubkey, node7);
1295 assert_eq!(route.hops[4].short_channel_id, 8);
1296 assert_eq!(route.hops[4].fee_msat, 2000);
1297 assert_eq!(route.hops[4].cltv_expiry_delta, 42);