1 use secp256k1::key::PublicKey;
2 use secp256k1::{Secp256k1,Message};
5 use bitcoin::util::hash::Sha256dHash;
6 use bitcoin::blockdata::script::Builder;
7 use bitcoin::blockdata::opcodes;
9 use chain::chaininterface::{ChainError, ChainWatchInterface};
10 use ln::channelmanager;
11 use ln::msgs::{ErrorAction,HandleError,RoutingMessageHandler,MsgEncodable,NetAddress,GlobalFeatures};
13 use util::logger::Logger;
16 use std::sync::{RwLock,Arc};
17 use std::collections::{HashMap,BinaryHeap};
18 use std::collections::hash_map::Entry;
24 pub pubkey: PublicKey,
25 /// The channel that should be used from the previous hop to reach this node.
26 pub short_channel_id: u64,
27 /// The fee taken on this hop. For the last hop, this should be the full value of the payment.
29 /// The CLTV delta added for this hop. For the last hop, this should be the full CLTV value
30 /// expected at the destination, in excess of the current block height.
31 pub cltv_expiry_delta: u32,
34 /// A route from us through the network to a destination
37 /// The list of hops, NOT INCLUDING our own, where the last hop is the destination. Thus, this
38 /// must always be at least length one. By protocol rules, this may not currently exceed 20 in
40 pub hops: Vec<RouteHop>,
43 struct DirectionalChannelInfo {
44 src_node_id: PublicKey,
47 cltv_expiry_delta: u16,
48 htlc_minimum_msat: u64,
50 fee_proportional_millionths: u32,
53 impl std::fmt::Display for DirectionalChannelInfo {
54 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
55 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)?;
61 features: GlobalFeatures,
62 one_to_two: DirectionalChannelInfo,
63 two_to_one: DirectionalChannelInfo,
66 impl std::fmt::Display for ChannelInfo {
67 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
68 write!(f, "features: {}, one_to_two: {}, two_to_one: {}", log_bytes!(self.features.encode()), self.one_to_two, self.two_to_one)?;
74 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
75 channels: Vec<(u64, Sha256dHash)>,
76 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
79 lowest_inbound_channel_fee_base_msat: u32,
80 lowest_inbound_channel_fee_proportional_millionths: u32,
82 features: GlobalFeatures,
86 addresses: Vec<NetAddress>,
89 impl std::fmt::Display for NodeInfo {
90 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
91 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[..])?;
97 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
98 channels: HashMap<(u64, Sha256dHash), ChannelInfo>,
99 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
100 channels: HashMap<u64, ChannelInfo>,
102 our_node_id: PublicKey,
103 nodes: HashMap<PublicKey, NodeInfo>,
105 struct MutNetworkMap<'a> {
106 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
107 channels: &'a mut HashMap<(u64, Sha256dHash), ChannelInfo>,
108 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
109 channels: &'a mut HashMap<u64, ChannelInfo>,
110 nodes: &'a mut HashMap<PublicKey, NodeInfo>,
113 fn borrow_parts(&mut self) -> MutNetworkMap {
115 channels: &mut self.channels,
116 nodes: &mut self.nodes,
120 impl std::fmt::Display for NetworkMap {
121 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
122 write!(f, "Node id {} network map\n[Channels]\n", log_pubkey!(self.our_node_id))?;
123 for (key, val) in self.channels.iter() {
124 write!(f, " {}: {}\n", key, val)?;
126 write!(f, "[Nodes]\n")?;
127 for (key, val) in self.nodes.iter() {
128 write!(f, " {}: {}\n", log_pubkey!(key), val)?;
135 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
137 fn get_key(short_channel_id: u64, chain_hash: Sha256dHash) -> (u64, Sha256dHash) {
138 (short_channel_id, chain_hash)
141 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
143 fn get_key(short_channel_id: u64, _: Sha256dHash) -> u64 {
147 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
149 fn get_short_id(id: &(u64, Sha256dHash)) -> &u64 {
153 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
155 fn get_short_id(id: &u64) -> &u64 {
160 /// A channel descriptor which provides a last-hop route to get_route
161 pub struct RouteHint {
162 pub src_node_id: PublicKey,
163 pub short_channel_id: u64,
164 pub fee_base_msat: u32,
165 pub fee_proportional_millionths: u32,
166 pub cltv_expiry_delta: u16,
167 pub htlc_minimum_msat: u64,
170 /// Tracks a view of the network, receiving updates from peers and generating Routes to
171 /// payment destinations.
173 secp_ctx: Secp256k1<secp256k1::VerifyOnly>,
174 network_map: RwLock<NetworkMap>,
175 chain_monitor: Arc<ChainWatchInterface>,
179 macro_rules! secp_verify_sig {
180 ( $secp_ctx: expr, $msg: expr, $sig: expr, $pubkey: expr ) => {
181 match $secp_ctx.verify($msg, $sig, $pubkey) {
183 Err(_) => return Err(HandleError{err: "Invalid signature from remote node", action: None}),
188 impl RoutingMessageHandler for Router {
189 fn handle_node_announcement(&self, msg: &msgs::NodeAnnouncement) -> Result<bool, HandleError> {
190 let msg_hash = Message::from_slice(&Sha256dHash::from_data(&msg.contents.encode()[..])[..]).unwrap();
191 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.signature, &msg.contents.node_id);
193 if msg.contents.features.requires_unknown_bits() {
194 panic!("Unknown-required-features NodeAnnouncements should never deserialize!");
197 let mut network = self.network_map.write().unwrap();
198 match network.nodes.get_mut(&msg.contents.node_id) {
199 None => Err(HandleError{err: "No existing channels for node_announcement", action: Some(ErrorAction::IgnoreError)}),
201 if node.last_update >= msg.contents.timestamp {
202 return Err(HandleError{err: "Update older than last processed update", action: Some(ErrorAction::IgnoreError)});
205 node.features = msg.contents.features.clone();
206 node.last_update = msg.contents.timestamp;
207 node.rgb = msg.contents.rgb;
208 node.alias = msg.contents.alias;
209 node.addresses = msg.contents.addresses.clone();
210 Ok(msg.contents.excess_data.is_empty() && msg.contents.excess_address_data.is_empty() && !msg.contents.features.supports_unknown_bits())
215 fn handle_channel_announcement(&self, msg: &msgs::ChannelAnnouncement) -> Result<bool, HandleError> {
216 if msg.contents.node_id_1 == msg.contents.node_id_2 || msg.contents.bitcoin_key_1 == msg.contents.bitcoin_key_2 {
217 return Err(HandleError{err: "Channel announcement node had a channel with itself", action: Some(ErrorAction::IgnoreError)});
220 let msg_hash = Message::from_slice(&Sha256dHash::from_data(&msg.contents.encode()[..])[..]).unwrap();
221 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.node_signature_1, &msg.contents.node_id_1);
222 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.node_signature_2, &msg.contents.node_id_2);
223 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.bitcoin_signature_1, &msg.contents.bitcoin_key_1);
224 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.bitcoin_signature_2, &msg.contents.bitcoin_key_2);
226 if msg.contents.features.requires_unknown_bits() {
227 panic!("Unknown-required-features ChannelAnnouncements should never deserialize!");
230 let checked_utxo = match self.chain_monitor.get_chain_utxo(msg.contents.chain_hash, msg.contents.short_channel_id) {
231 Ok((script_pubkey, _value)) => {
232 let expected_script = Builder::new().push_opcode(opcodes::All::OP_PUSHNUM_2)
233 .push_slice(&msg.contents.bitcoin_key_1.serialize())
234 .push_slice(&msg.contents.bitcoin_key_2.serialize())
235 .push_opcode(opcodes::All::OP_PUSHNUM_2).push_opcode(opcodes::All::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
236 if script_pubkey != expected_script {
237 return Err(HandleError{err: "Channel announcement keys didn't match on-chain script", action: Some(ErrorAction::IgnoreError)});
239 //TODO: Check if value is worth storing, use it to inform routing, and compare it
240 //to the new HTLC max field in channel_update
243 Err(ChainError::NotSupported) => {
244 // Tentatively accept, potentially exposing us to DoS attacks
247 Err(ChainError::NotWatched) => {
248 return Err(HandleError{err: "Channel announced on an unknown chain", action: Some(ErrorAction::IgnoreError)});
250 Err(ChainError::UnknownTx) => {
251 return Err(HandleError{err: "Channel announced without corresponding UTXO entry", action: Some(ErrorAction::IgnoreError)});
255 let mut network_lock = self.network_map.write().unwrap();
256 let network = network_lock.borrow_parts();
258 let chan_info = ChannelInfo {
259 features: msg.contents.features.clone(),
260 one_to_two: DirectionalChannelInfo {
261 src_node_id: msg.contents.node_id_1.clone(),
264 cltv_expiry_delta: u16::max_value(),
265 htlc_minimum_msat: u64::max_value(),
266 fee_base_msat: u32::max_value(),
267 fee_proportional_millionths: u32::max_value(),
269 two_to_one: DirectionalChannelInfo {
270 src_node_id: msg.contents.node_id_2.clone(),
273 cltv_expiry_delta: u16::max_value(),
274 htlc_minimum_msat: u64::max_value(),
275 fee_base_msat: u32::max_value(),
276 fee_proportional_millionths: u32::max_value(),
280 match network.channels.entry(NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash)) {
281 Entry::Occupied(mut entry) => {
282 //TODO: because asking the blockchain if short_channel_id is valid is only optional
283 //in the blockchain API, we need to handle it smartly here, though its unclear
286 // Either our UTXO provider is busted, there was a reorg, or the UTXO provider
287 // only sometimes returns results. In any case remove the previous entry. Note
288 // that the spec expects us to "blacklist" the node_ids involved, but we can't
290 // a) we don't *require* a UTXO provider that always returns results.
291 // b) we don't track UTXOs of channels we know about and remove them if they
293 // c) it's unclear how to do so without exposing ourselves to massive DoS risk.
294 Self::remove_channel_in_nodes(network.nodes, &entry.get(), msg.contents.short_channel_id);
295 *entry.get_mut() = chan_info;
297 return Err(HandleError{err: "Already have knowledge of channel", action: Some(ErrorAction::IgnoreError)})
300 Entry::Vacant(entry) => {
301 entry.insert(chan_info);
305 macro_rules! add_channel_to_node {
306 ( $node_id: expr ) => {
307 match network.nodes.entry($node_id) {
308 Entry::Occupied(node_entry) => {
309 node_entry.into_mut().channels.push(NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash));
311 Entry::Vacant(node_entry) => {
312 node_entry.insert(NodeInfo {
313 channels: vec!(NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash)),
314 lowest_inbound_channel_fee_base_msat: u32::max_value(),
315 lowest_inbound_channel_fee_proportional_millionths: u32::max_value(),
316 features: GlobalFeatures::new(),
320 addresses: Vec::new(),
327 add_channel_to_node!(msg.contents.node_id_1);
328 add_channel_to_node!(msg.contents.node_id_2);
330 Ok(msg.contents.excess_data.is_empty() && !msg.contents.features.supports_unknown_bits())
333 fn handle_htlc_fail_channel_update(&self, update: &msgs::HTLCFailChannelUpdate) {
335 &msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg } => {
336 let _ = self.handle_channel_update(msg);
338 &msgs::HTLCFailChannelUpdate::ChannelClosed { ref short_channel_id } => {
339 let mut network = self.network_map.write().unwrap();
340 if let Some(chan) = network.channels.remove(short_channel_id) {
341 Self::remove_channel_in_nodes(&mut network.nodes, &chan, *short_channel_id);
347 fn handle_channel_update(&self, msg: &msgs::ChannelUpdate) -> Result<bool, HandleError> {
348 let mut network = self.network_map.write().unwrap();
350 let chan_enabled = msg.contents.flags & (1 << 1) != (1 << 1);
351 let chan_was_enabled;
353 match network.channels.get_mut(&NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash)) {
354 None => return Err(HandleError{err: "Couldn't find channel for update", action: Some(ErrorAction::IgnoreError)}),
356 macro_rules! maybe_update_channel_info {
357 ( $target: expr) => {
358 if $target.last_update >= msg.contents.timestamp {
359 return Err(HandleError{err: "Update older than last processed update", action: Some(ErrorAction::IgnoreError)});
361 chan_was_enabled = $target.enabled;
362 $target.last_update = msg.contents.timestamp;
363 $target.enabled = chan_enabled;
364 $target.cltv_expiry_delta = msg.contents.cltv_expiry_delta;
365 $target.htlc_minimum_msat = msg.contents.htlc_minimum_msat;
366 $target.fee_base_msat = msg.contents.fee_base_msat;
367 $target.fee_proportional_millionths = msg.contents.fee_proportional_millionths;
371 let msg_hash = Message::from_slice(&Sha256dHash::from_data(&msg.contents.encode()[..])[..]).unwrap();
372 if msg.contents.flags & 1 == 1 {
373 dest_node_id = channel.one_to_two.src_node_id.clone();
374 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.signature, &channel.two_to_one.src_node_id);
375 maybe_update_channel_info!(channel.two_to_one);
377 dest_node_id = channel.two_to_one.src_node_id.clone();
378 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.signature, &channel.one_to_two.src_node_id);
379 maybe_update_channel_info!(channel.one_to_two);
385 let node = network.nodes.get_mut(&dest_node_id).unwrap();
386 node.lowest_inbound_channel_fee_base_msat = cmp::min(node.lowest_inbound_channel_fee_base_msat, msg.contents.fee_base_msat);
387 node.lowest_inbound_channel_fee_proportional_millionths = cmp::min(node.lowest_inbound_channel_fee_proportional_millionths, msg.contents.fee_proportional_millionths);
388 } else if chan_was_enabled {
389 let mut lowest_inbound_channel_fee_base_msat = u32::max_value();
390 let mut lowest_inbound_channel_fee_proportional_millionths = u32::max_value();
393 let node = network.nodes.get(&dest_node_id).unwrap();
395 for chan_id in node.channels.iter() {
396 let chan = network.channels.get(chan_id).unwrap();
397 if chan.one_to_two.src_node_id == dest_node_id {
398 lowest_inbound_channel_fee_base_msat = cmp::min(lowest_inbound_channel_fee_base_msat, chan.two_to_one.fee_base_msat);
399 lowest_inbound_channel_fee_proportional_millionths = cmp::min(lowest_inbound_channel_fee_proportional_millionths, chan.two_to_one.fee_proportional_millionths);
401 lowest_inbound_channel_fee_base_msat = cmp::min(lowest_inbound_channel_fee_base_msat, chan.one_to_two.fee_base_msat);
402 lowest_inbound_channel_fee_proportional_millionths = cmp::min(lowest_inbound_channel_fee_proportional_millionths, chan.one_to_two.fee_proportional_millionths);
407 //TODO: satisfy the borrow-checker without a double-map-lookup :(
408 let mut_node = network.nodes.get_mut(&dest_node_id).unwrap();
409 mut_node.lowest_inbound_channel_fee_base_msat = lowest_inbound_channel_fee_base_msat;
410 mut_node.lowest_inbound_channel_fee_proportional_millionths = lowest_inbound_channel_fee_proportional_millionths;
413 Ok(msg.contents.excess_data.is_empty())
417 #[derive(Eq, PartialEq)]
418 struct RouteGraphNode {
420 lowest_fee_to_peer_through_node: u64,
421 lowest_fee_to_node: u64,
424 impl cmp::Ord for RouteGraphNode {
425 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
426 other.lowest_fee_to_peer_through_node.cmp(&self.lowest_fee_to_peer_through_node)
427 .then_with(|| other.pubkey.serialize().cmp(&self.pubkey.serialize()))
431 impl cmp::PartialOrd for RouteGraphNode {
432 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
433 Some(self.cmp(other))
437 struct DummyDirectionalChannelInfo {
438 src_node_id: PublicKey,
439 cltv_expiry_delta: u32,
440 htlc_minimum_msat: u64,
442 fee_proportional_millionths: u32,
446 pub fn new(our_pubkey: PublicKey, chain_monitor: Arc<ChainWatchInterface>, logger: Arc<Logger>) -> Router {
447 let mut nodes = HashMap::new();
448 nodes.insert(our_pubkey.clone(), NodeInfo {
449 channels: Vec::new(),
450 lowest_inbound_channel_fee_base_msat: u32::max_value(),
451 lowest_inbound_channel_fee_proportional_millionths: u32::max_value(),
452 features: GlobalFeatures::new(),
456 addresses: Vec::new(),
459 secp_ctx: Secp256k1::verification_only(),
460 network_map: RwLock::new(NetworkMap {
461 channels: HashMap::new(),
462 our_node_id: our_pubkey,
470 /// Dumps the entire network view of this Router to the logger provided in the constructor at
472 pub fn trace_state(&self) {
473 log_trace!(self, "{}", self.network_map.read().unwrap());
476 /// Get network addresses by node id
477 pub fn get_addresses(&self, pubkey: &PublicKey) -> Option<Vec<NetAddress>> {
478 let network = self.network_map.read().unwrap();
479 network.nodes.get(pubkey).map(|n| n.addresses.clone())
482 /// Marks a node as having failed a route. This will avoid re-using the node in routes for now,
483 /// with an expotnential decay in node "badness". Note that there is deliberately no
484 /// mark_channel_bad as a node may simply lie and suggest that an upstream channel from it is
485 /// what failed the route and not the node itself. Instead, setting the blamed_upstream_node
486 /// boolean will reduce the penalty, returning the node to usability faster. If the node is
487 /// behaving correctly, it will disable the failing channel and we will use it again next time.
488 pub fn mark_node_bad(&self, _node_id: &PublicKey, _blamed_upstream_node: bool) {
492 fn remove_channel_in_nodes(nodes: &mut HashMap<PublicKey, NodeInfo>, chan: &ChannelInfo, short_channel_id: u64) {
493 macro_rules! remove_from_node {
494 ($node_id: expr) => {
495 if let Entry::Occupied(mut entry) = nodes.entry($node_id) {
496 entry.get_mut().channels.retain(|chan_id| {
497 short_channel_id != *NetworkMap::get_short_id(chan_id)
499 if entry.get().channels.is_empty() {
500 entry.remove_entry();
503 panic!("Had channel that pointed to unknown node (ie inconsistent network map)!");
507 remove_from_node!(chan.one_to_two.src_node_id);
508 remove_from_node!(chan.two_to_one.src_node_id);
511 /// Gets a route from us to the given target node.
512 /// Extra routing hops between known nodes and the target will be used if they are included in
514 /// If some channels aren't announced, it may be useful to fill in a first_hops with the
515 /// results from a local ChannelManager::list_usable_channels() call. If it is filled in, our
516 /// (this Router's) view of our local channels will be ignored, and only those in first_hops
517 /// will be used. Panics if first_hops contains channels without short_channel_ids
518 /// (ChannelManager::list_usable_channels will never include such channels).
519 /// The fees on channels from us to next-hops are ignored (as they are assumed to all be
520 /// equal), however the enabled/disabled bit on such channels as well as the htlc_minimum_msat
521 /// *is* checked as they may change based on the receiving node.
522 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> {
523 // TODO: Obviously *only* using total fee cost sucks. We should consider weighting by
524 // uptime/success in using a node in the past.
525 let network = self.network_map.read().unwrap();
527 if *target == network.our_node_id {
528 return Err(HandleError{err: "Cannot generate a route to ourselves", action: None});
531 if final_value_msat > 21_000_000 * 1_0000_0000 * 1000 {
532 return Err(HandleError{err: "Cannot generate a route of more value than all existing satoshis", action: None});
535 // We do a dest-to-source Dijkstra's sorting by each node's distance from the destination
536 // plus the minimum per-HTLC fee to get from it to another node (aka "shitty A*").
537 // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
538 // to use as the A* heuristic beyond just the cost to get one node further than the current
541 let dummy_directional_info = DummyDirectionalChannelInfo { // used for first_hops routes
542 src_node_id: network.our_node_id.clone(),
543 cltv_expiry_delta: 0,
544 htlc_minimum_msat: 0,
546 fee_proportional_millionths: 0,
549 let mut targets = BinaryHeap::new(); //TODO: Do we care about switching to eg Fibbonaci heap?
550 let mut dist = HashMap::with_capacity(network.nodes.len());
552 let mut first_hop_targets = HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
553 if let Some(hops) = first_hops {
555 let short_channel_id = chan.short_channel_id.expect("first_hops should be filled in with usable channels, not pending ones");
556 if chan.remote_network_id == *target {
558 hops: vec![RouteHop {
559 pubkey: chan.remote_network_id,
561 fee_msat: final_value_msat,
562 cltv_expiry_delta: final_cltv,
566 first_hop_targets.insert(chan.remote_network_id, short_channel_id);
568 if first_hop_targets.is_empty() {
569 return Err(HandleError{err: "Cannot route when there are no outbound routes away from us", action: None});
573 macro_rules! add_entry {
574 // Adds entry which goes from the node pointed to by $directional_info to
575 // $dest_node_id over the channel with id $chan_id with fees described in
576 // $directional_info.
577 ( $chan_id: expr, $dest_node_id: expr, $directional_info: expr, $starting_fee_msat: expr ) => {
578 //TODO: Explore simply adding fee to hit htlc_minimum_msat
579 if $starting_fee_msat as u64 + final_value_msat > $directional_info.htlc_minimum_msat {
580 let proportional_fee_millions = ($starting_fee_msat + final_value_msat).checked_mul($directional_info.fee_proportional_millionths as u64);
581 if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
582 ($directional_info.fee_base_msat as u64).checked_add(part / 1000000) })
584 let mut total_fee = $starting_fee_msat as u64;
585 let hm_entry = dist.entry(&$directional_info.src_node_id);
586 let old_entry = hm_entry.or_insert_with(|| {
587 let node = network.nodes.get(&$directional_info.src_node_id).unwrap();
589 node.lowest_inbound_channel_fee_base_msat,
590 node.lowest_inbound_channel_fee_proportional_millionths,
592 pubkey: $dest_node_id.clone(),
595 cltv_expiry_delta: 0,
598 if $directional_info.src_node_id != network.our_node_id {
599 // Ignore new_fee for channel-from-us as we assume all channels-from-us
600 // will have the same effective-fee
601 total_fee += new_fee;
602 if let Some(fee_inc) = final_value_msat.checked_add(total_fee).and_then(|inc| { (old_entry.2 as u64).checked_mul(inc) }) {
603 total_fee += fee_inc / 1000000 + (old_entry.1 as u64);
605 // max_value means we'll always fail the old_entry.0 > total_fee check
606 total_fee = u64::max_value();
609 let new_graph_node = RouteGraphNode {
610 pubkey: $directional_info.src_node_id,
611 lowest_fee_to_peer_through_node: total_fee,
612 lowest_fee_to_node: $starting_fee_msat as u64 + new_fee,
614 if old_entry.0 > total_fee {
615 targets.push(new_graph_node);
616 old_entry.0 = total_fee;
617 old_entry.3 = RouteHop {
618 pubkey: $dest_node_id.clone(),
619 short_channel_id: $chan_id.clone(),
620 fee_msat: new_fee, // This field is ignored on the last-hop anyway
621 cltv_expiry_delta: $directional_info.cltv_expiry_delta as u32,
629 macro_rules! add_entries_to_cheapest_to_target_node {
630 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr ) => {
631 if first_hops.is_some() {
632 if let Some(first_hop) = first_hop_targets.get(&$node_id) {
633 add_entry!(first_hop, $node_id, dummy_directional_info, $fee_to_target_msat);
637 for chan_id in $node.channels.iter() {
638 let chan = network.channels.get(chan_id).unwrap();
639 if chan.one_to_two.src_node_id == *$node_id {
640 // ie $node is one, ie next hop in A* is two, via the two_to_one channel
641 if first_hops.is_none() || chan.two_to_one.src_node_id != network.our_node_id {
642 if chan.two_to_one.enabled {
643 add_entry!(chan_id, chan.one_to_two.src_node_id, chan.two_to_one, $fee_to_target_msat);
647 if first_hops.is_none() || chan.one_to_two.src_node_id != network.our_node_id {
648 if chan.one_to_two.enabled {
649 add_entry!(chan_id, chan.two_to_one.src_node_id, chan.one_to_two, $fee_to_target_msat);
657 match network.nodes.get(target) {
660 add_entries_to_cheapest_to_target_node!(node, target, 0);
664 for hop in last_hops.iter() {
665 if first_hops.is_none() || hop.src_node_id != network.our_node_id { // first_hop overrules last_hops
666 if network.nodes.get(&hop.src_node_id).is_some() {
667 if first_hops.is_some() {
668 if let Some(first_hop) = first_hop_targets.get(&hop.src_node_id) {
669 add_entry!(first_hop, hop.src_node_id, dummy_directional_info, 0);
672 add_entry!(hop.short_channel_id, target, hop, 0);
677 while let Some(RouteGraphNode { pubkey, lowest_fee_to_node, .. }) = targets.pop() {
678 if pubkey == network.our_node_id {
679 let mut res = vec!(dist.remove(&network.our_node_id).unwrap().3);
680 while res.last().unwrap().pubkey != *target {
681 let new_entry = match dist.remove(&res.last().unwrap().pubkey) {
683 None => return Err(HandleError{err: "Failed to find a non-fee-overflowing path to the given destination", action: None}),
685 res.last_mut().unwrap().fee_msat = new_entry.fee_msat;
686 res.last_mut().unwrap().cltv_expiry_delta = new_entry.cltv_expiry_delta;
689 res.last_mut().unwrap().fee_msat = final_value_msat;
690 res.last_mut().unwrap().cltv_expiry_delta = final_cltv;
691 let route = Route { hops: res };
692 log_trace!(self, "Got route: {}", log_route!(route));
696 match network.nodes.get(&pubkey) {
699 add_entries_to_cheapest_to_target_node!(node, &pubkey, lowest_fee_to_node);
704 Err(HandleError{err: "Failed to find a path to the given destination", action: None})
710 use chain::chaininterface;
711 use ln::channelmanager;
712 use ln::router::{Router,NodeInfo,NetworkMap,ChannelInfo,DirectionalChannelInfo,RouteHint};
713 use ln::msgs::GlobalFeatures;
714 use util::test_utils;
715 use util::logger::Logger;
717 use bitcoin::util::hash::Sha256dHash;
718 use bitcoin::network::constants::Network;
722 use secp256k1::key::{PublicKey,SecretKey};
723 use secp256k1::Secp256k1;
729 let secp_ctx = Secp256k1::new();
730 let our_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap());
731 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
732 let chain_monitor = Arc::new(chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet, Arc::clone(&logger)));
733 let router = Router::new(our_id, chain_monitor, Arc::clone(&logger));
735 // Build network from our_id to node8:
737 // -1(1)2- node1 -1(3)2-
739 // our_id -1(12)2- node8 -1(13)2--- node3
741 // -1(2)2- node2 -1(4)2-
744 // chan1 1-to-2: disabled
745 // chan1 2-to-1: enabled, 0 fee
747 // chan2 1-to-2: enabled, ignored fee
748 // chan2 2-to-1: enabled, 0 fee
750 // chan3 1-to-2: enabled, 0 fee
751 // chan3 2-to-1: enabled, 100 msat fee
753 // chan4 1-to-2: enabled, 100% fee
754 // chan4 2-to-1: enabled, 0 fee
756 // chan12 1-to-2: enabled, ignored fee
757 // chan12 2-to-1: enabled, 0 fee
759 // chan13 1-to-2: enabled, 200% fee
760 // chan13 2-to-1: enabled, 0 fee
763 // -1(5)2- node4 -1(8)2--
767 // node3--1(6)2- node5 -1(9)2--- node7 (not in global route map)
769 // -1(7)2- node6 -1(10)2-
771 // chan5 1-to-2: enabled, 100 msat fee
772 // chan5 2-to-1: enabled, 0 fee
774 // chan6 1-to-2: enabled, 0 fee
775 // chan6 2-to-1: enabled, 0 fee
777 // chan7 1-to-2: enabled, 100% fee
778 // chan7 2-to-1: enabled, 0 fee
780 // chan8 1-to-2: enabled, variable fee (0 then 1000 msat)
781 // chan8 2-to-1: enabled, 0 fee
783 // chan9 1-to-2: enabled, 1001 msat fee
784 // chan9 2-to-1: enabled, 0 fee
786 // chan10 1-to-2: enabled, 0 fee
787 // chan10 2-to-1: enabled, 0 fee
789 // chan11 1-to-2: enabled, 0 fee
790 // chan11 2-to-1: enabled, 0 fee
792 let node1 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap()[..]).unwrap());
793 let node2 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0303030303030303030303030303030303030303030303030303030303030303").unwrap()[..]).unwrap());
794 let node3 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0404040404040404040404040404040404040404040404040404040404040404").unwrap()[..]).unwrap());
795 let node4 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0505050505050505050505050505050505050505050505050505050505050505").unwrap()[..]).unwrap());
796 let node5 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0606060606060606060606060606060606060606060606060606060606060606").unwrap()[..]).unwrap());
797 let node6 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0707070707070707070707070707070707070707070707070707070707070707").unwrap()[..]).unwrap());
798 let node7 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0808080808080808080808080808080808080808080808080808080808080808").unwrap()[..]).unwrap());
799 let node8 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0909090909090909090909090909090909090909090909090909090909090909").unwrap()[..]).unwrap());
801 let zero_hash = Sha256dHash::from_data(&[0; 32]);
804 let mut network = router.network_map.write().unwrap();
806 network.nodes.insert(node1.clone(), NodeInfo {
807 channels: vec!(NetworkMap::get_key(1, zero_hash.clone()), NetworkMap::get_key(3, zero_hash.clone())),
808 lowest_inbound_channel_fee_base_msat: 100,
809 lowest_inbound_channel_fee_proportional_millionths: 0,
810 features: GlobalFeatures::new(),
814 addresses: Vec::new(),
816 network.channels.insert(NetworkMap::get_key(1, zero_hash.clone()), ChannelInfo {
817 features: GlobalFeatures::new(),
818 one_to_two: DirectionalChannelInfo {
819 src_node_id: our_id.clone(),
822 cltv_expiry_delta: u16::max_value(), // This value should be ignored
823 htlc_minimum_msat: 0,
824 fee_base_msat: u32::max_value(), // This value should be ignored
825 fee_proportional_millionths: u32::max_value(), // This value should be ignored
826 }, two_to_one: DirectionalChannelInfo {
827 src_node_id: node1.clone(),
830 cltv_expiry_delta: 0,
831 htlc_minimum_msat: 0,
833 fee_proportional_millionths: 0,
836 network.nodes.insert(node2.clone(), NodeInfo {
837 channels: vec!(NetworkMap::get_key(2, zero_hash.clone()), NetworkMap::get_key(4, zero_hash.clone())),
838 lowest_inbound_channel_fee_base_msat: 0,
839 lowest_inbound_channel_fee_proportional_millionths: 0,
840 features: GlobalFeatures::new(),
844 addresses: Vec::new(),
846 network.channels.insert(NetworkMap::get_key(2, zero_hash.clone()), ChannelInfo {
847 features: GlobalFeatures::new(),
848 one_to_two: DirectionalChannelInfo {
849 src_node_id: our_id.clone(),
852 cltv_expiry_delta: u16::max_value(), // This value should be ignored
853 htlc_minimum_msat: 0,
854 fee_base_msat: u32::max_value(), // This value should be ignored
855 fee_proportional_millionths: u32::max_value(), // This value should be ignored
856 }, two_to_one: DirectionalChannelInfo {
857 src_node_id: node2.clone(),
860 cltv_expiry_delta: 0,
861 htlc_minimum_msat: 0,
863 fee_proportional_millionths: 0,
866 network.nodes.insert(node8.clone(), NodeInfo {
867 channels: vec!(NetworkMap::get_key(12, zero_hash.clone()), NetworkMap::get_key(13, zero_hash.clone())),
868 lowest_inbound_channel_fee_base_msat: 0,
869 lowest_inbound_channel_fee_proportional_millionths: 0,
870 features: GlobalFeatures::new(),
874 addresses: Vec::new(),
876 network.channels.insert(NetworkMap::get_key(12, zero_hash.clone()), ChannelInfo {
877 features: GlobalFeatures::new(),
878 one_to_two: DirectionalChannelInfo {
879 src_node_id: our_id.clone(),
882 cltv_expiry_delta: u16::max_value(), // This value should be ignored
883 htlc_minimum_msat: 0,
884 fee_base_msat: u32::max_value(), // This value should be ignored
885 fee_proportional_millionths: u32::max_value(), // This value should be ignored
886 }, two_to_one: DirectionalChannelInfo {
887 src_node_id: node8.clone(),
890 cltv_expiry_delta: 0,
891 htlc_minimum_msat: 0,
893 fee_proportional_millionths: 0,
896 network.nodes.insert(node3.clone(), NodeInfo {
898 NetworkMap::get_key(3, zero_hash.clone()),
899 NetworkMap::get_key(4, zero_hash.clone()),
900 NetworkMap::get_key(13, zero_hash.clone()),
901 NetworkMap::get_key(5, zero_hash.clone()),
902 NetworkMap::get_key(6, zero_hash.clone()),
903 NetworkMap::get_key(7, zero_hash.clone())),
904 lowest_inbound_channel_fee_base_msat: 0,
905 lowest_inbound_channel_fee_proportional_millionths: 0,
906 features: GlobalFeatures::new(),
910 addresses: Vec::new(),
912 network.channels.insert(NetworkMap::get_key(3, zero_hash.clone()), ChannelInfo {
913 features: GlobalFeatures::new(),
914 one_to_two: DirectionalChannelInfo {
915 src_node_id: node1.clone(),
918 cltv_expiry_delta: (3 << 8) | 1,
919 htlc_minimum_msat: 0,
921 fee_proportional_millionths: 0,
922 }, two_to_one: DirectionalChannelInfo {
923 src_node_id: node3.clone(),
926 cltv_expiry_delta: (3 << 8) | 2,
927 htlc_minimum_msat: 0,
929 fee_proportional_millionths: 0,
932 network.channels.insert(NetworkMap::get_key(4, zero_hash.clone()), ChannelInfo {
933 features: GlobalFeatures::new(),
934 one_to_two: DirectionalChannelInfo {
935 src_node_id: node2.clone(),
938 cltv_expiry_delta: (4 << 8) | 1,
939 htlc_minimum_msat: 0,
941 fee_proportional_millionths: 1000000,
942 }, two_to_one: DirectionalChannelInfo {
943 src_node_id: node3.clone(),
946 cltv_expiry_delta: (4 << 8) | 2,
947 htlc_minimum_msat: 0,
949 fee_proportional_millionths: 0,
952 network.channels.insert(NetworkMap::get_key(13, zero_hash.clone()), ChannelInfo {
953 features: GlobalFeatures::new(),
954 one_to_two: DirectionalChannelInfo {
955 src_node_id: node8.clone(),
958 cltv_expiry_delta: (13 << 8) | 1,
959 htlc_minimum_msat: 0,
961 fee_proportional_millionths: 2000000,
962 }, two_to_one: DirectionalChannelInfo {
963 src_node_id: node3.clone(),
966 cltv_expiry_delta: (13 << 8) | 2,
967 htlc_minimum_msat: 0,
969 fee_proportional_millionths: 0,
972 network.nodes.insert(node4.clone(), NodeInfo {
973 channels: vec!(NetworkMap::get_key(5, zero_hash.clone()), NetworkMap::get_key(11, zero_hash.clone())),
974 lowest_inbound_channel_fee_base_msat: 0,
975 lowest_inbound_channel_fee_proportional_millionths: 0,
976 features: GlobalFeatures::new(),
980 addresses: Vec::new(),
982 network.channels.insert(NetworkMap::get_key(5, zero_hash.clone()), ChannelInfo {
983 features: GlobalFeatures::new(),
984 one_to_two: DirectionalChannelInfo {
985 src_node_id: node3.clone(),
988 cltv_expiry_delta: (5 << 8) | 1,
989 htlc_minimum_msat: 0,
991 fee_proportional_millionths: 0,
992 }, two_to_one: DirectionalChannelInfo {
993 src_node_id: node4.clone(),
996 cltv_expiry_delta: (5 << 8) | 2,
997 htlc_minimum_msat: 0,
999 fee_proportional_millionths: 0,
1002 network.nodes.insert(node5.clone(), NodeInfo {
1003 channels: vec!(NetworkMap::get_key(6, zero_hash.clone()), NetworkMap::get_key(11, zero_hash.clone())),
1004 lowest_inbound_channel_fee_base_msat: 0,
1005 lowest_inbound_channel_fee_proportional_millionths: 0,
1006 features: GlobalFeatures::new(),
1010 addresses: Vec::new(),
1012 network.channels.insert(NetworkMap::get_key(6, zero_hash.clone()), ChannelInfo {
1013 features: GlobalFeatures::new(),
1014 one_to_two: DirectionalChannelInfo {
1015 src_node_id: node3.clone(),
1018 cltv_expiry_delta: (6 << 8) | 1,
1019 htlc_minimum_msat: 0,
1021 fee_proportional_millionths: 0,
1022 }, two_to_one: DirectionalChannelInfo {
1023 src_node_id: node5.clone(),
1026 cltv_expiry_delta: (6 << 8) | 2,
1027 htlc_minimum_msat: 0,
1029 fee_proportional_millionths: 0,
1032 network.channels.insert(NetworkMap::get_key(11, zero_hash.clone()), ChannelInfo {
1033 features: GlobalFeatures::new(),
1034 one_to_two: DirectionalChannelInfo {
1035 src_node_id: node5.clone(),
1038 cltv_expiry_delta: (11 << 8) | 1,
1039 htlc_minimum_msat: 0,
1041 fee_proportional_millionths: 0,
1042 }, two_to_one: DirectionalChannelInfo {
1043 src_node_id: node4.clone(),
1046 cltv_expiry_delta: (11 << 8) | 2,
1047 htlc_minimum_msat: 0,
1049 fee_proportional_millionths: 0,
1052 network.nodes.insert(node6.clone(), NodeInfo {
1053 channels: vec!(NetworkMap::get_key(7, zero_hash.clone())),
1054 lowest_inbound_channel_fee_base_msat: 0,
1055 lowest_inbound_channel_fee_proportional_millionths: 0,
1056 features: GlobalFeatures::new(),
1060 addresses: Vec::new(),
1062 network.channels.insert(NetworkMap::get_key(7, zero_hash.clone()), ChannelInfo {
1063 features: GlobalFeatures::new(),
1064 one_to_two: DirectionalChannelInfo {
1065 src_node_id: node3.clone(),
1068 cltv_expiry_delta: (7 << 8) | 1,
1069 htlc_minimum_msat: 0,
1071 fee_proportional_millionths: 1000000,
1072 }, two_to_one: DirectionalChannelInfo {
1073 src_node_id: node6.clone(),
1076 cltv_expiry_delta: (7 << 8) | 2,
1077 htlc_minimum_msat: 0,
1079 fee_proportional_millionths: 0,
1084 { // Simple route to 3 via 2
1085 let route = router.get_route(&node3, None, &Vec::new(), 100, 42).unwrap();
1086 assert_eq!(route.hops.len(), 2);
1088 assert_eq!(route.hops[0].pubkey, node2);
1089 assert_eq!(route.hops[0].short_channel_id, 2);
1090 assert_eq!(route.hops[0].fee_msat, 100);
1091 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1093 assert_eq!(route.hops[1].pubkey, node3);
1094 assert_eq!(route.hops[1].short_channel_id, 4);
1095 assert_eq!(route.hops[1].fee_msat, 100);
1096 assert_eq!(route.hops[1].cltv_expiry_delta, 42);
1099 { // Route to 1 via 2 and 3 because our channel to 1 is disabled
1100 let route = router.get_route(&node1, None, &Vec::new(), 100, 42).unwrap();
1101 assert_eq!(route.hops.len(), 3);
1103 assert_eq!(route.hops[0].pubkey, node2);
1104 assert_eq!(route.hops[0].short_channel_id, 2);
1105 assert_eq!(route.hops[0].fee_msat, 200);
1106 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1108 assert_eq!(route.hops[1].pubkey, node3);
1109 assert_eq!(route.hops[1].short_channel_id, 4);
1110 assert_eq!(route.hops[1].fee_msat, 100);
1111 assert_eq!(route.hops[1].cltv_expiry_delta, (3 << 8) | 2);
1113 assert_eq!(route.hops[2].pubkey, node1);
1114 assert_eq!(route.hops[2].short_channel_id, 3);
1115 assert_eq!(route.hops[2].fee_msat, 100);
1116 assert_eq!(route.hops[2].cltv_expiry_delta, 42);
1119 { // If we specify a channel to node8, that overrides our local channel view and that gets used
1120 let our_chans = vec![channelmanager::ChannelDetails {
1121 channel_id: [0; 32],
1122 short_channel_id: Some(42),
1123 remote_network_id: node8.clone(),
1124 channel_value_satoshis: 0,
1127 let route = router.get_route(&node3, Some(&our_chans), &Vec::new(), 100, 42).unwrap();
1128 assert_eq!(route.hops.len(), 2);
1130 assert_eq!(route.hops[0].pubkey, node8);
1131 assert_eq!(route.hops[0].short_channel_id, 42);
1132 assert_eq!(route.hops[0].fee_msat, 200);
1133 assert_eq!(route.hops[0].cltv_expiry_delta, (13 << 8) | 1);
1135 assert_eq!(route.hops[1].pubkey, node3);
1136 assert_eq!(route.hops[1].short_channel_id, 13);
1137 assert_eq!(route.hops[1].fee_msat, 100);
1138 assert_eq!(route.hops[1].cltv_expiry_delta, 42);
1141 let mut last_hops = vec!(RouteHint {
1142 src_node_id: node4.clone(),
1143 short_channel_id: 8,
1145 fee_proportional_millionths: 0,
1146 cltv_expiry_delta: (8 << 8) | 1,
1147 htlc_minimum_msat: 0,
1149 src_node_id: node5.clone(),
1150 short_channel_id: 9,
1151 fee_base_msat: 1001,
1152 fee_proportional_millionths: 0,
1153 cltv_expiry_delta: (9 << 8) | 1,
1154 htlc_minimum_msat: 0,
1156 src_node_id: node6.clone(),
1157 short_channel_id: 10,
1159 fee_proportional_millionths: 0,
1160 cltv_expiry_delta: (10 << 8) | 1,
1161 htlc_minimum_msat: 0,
1164 { // Simple test across 2, 3, 5, and 4 via a last_hop channel
1165 let route = router.get_route(&node7, None, &last_hops, 100, 42).unwrap();
1166 assert_eq!(route.hops.len(), 5);
1168 assert_eq!(route.hops[0].pubkey, node2);
1169 assert_eq!(route.hops[0].short_channel_id, 2);
1170 assert_eq!(route.hops[0].fee_msat, 100);
1171 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1173 assert_eq!(route.hops[1].pubkey, node3);
1174 assert_eq!(route.hops[1].short_channel_id, 4);
1175 assert_eq!(route.hops[1].fee_msat, 0);
1176 assert_eq!(route.hops[1].cltv_expiry_delta, (6 << 8) | 1);
1178 assert_eq!(route.hops[2].pubkey, node5);
1179 assert_eq!(route.hops[2].short_channel_id, 6);
1180 assert_eq!(route.hops[2].fee_msat, 0);
1181 assert_eq!(route.hops[2].cltv_expiry_delta, (11 << 8) | 1);
1183 assert_eq!(route.hops[3].pubkey, node4);
1184 assert_eq!(route.hops[3].short_channel_id, 11);
1185 assert_eq!(route.hops[3].fee_msat, 0);
1186 assert_eq!(route.hops[3].cltv_expiry_delta, (8 << 8) | 1);
1188 assert_eq!(route.hops[4].pubkey, node7);
1189 assert_eq!(route.hops[4].short_channel_id, 8);
1190 assert_eq!(route.hops[4].fee_msat, 100);
1191 assert_eq!(route.hops[4].cltv_expiry_delta, 42);
1194 { // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
1195 let our_chans = vec![channelmanager::ChannelDetails {
1196 channel_id: [0; 32],
1197 short_channel_id: Some(42),
1198 remote_network_id: node4.clone(),
1199 channel_value_satoshis: 0,
1202 let route = router.get_route(&node7, Some(&our_chans), &last_hops, 100, 42).unwrap();
1203 assert_eq!(route.hops.len(), 2);
1205 assert_eq!(route.hops[0].pubkey, node4);
1206 assert_eq!(route.hops[0].short_channel_id, 42);
1207 assert_eq!(route.hops[0].fee_msat, 0);
1208 assert_eq!(route.hops[0].cltv_expiry_delta, (8 << 8) | 1);
1210 assert_eq!(route.hops[1].pubkey, node7);
1211 assert_eq!(route.hops[1].short_channel_id, 8);
1212 assert_eq!(route.hops[1].fee_msat, 100);
1213 assert_eq!(route.hops[1].cltv_expiry_delta, 42);
1216 last_hops[0].fee_base_msat = 1000;
1218 { // Revert to via 6 as the fee on 8 goes up
1219 let route = router.get_route(&node7, None, &last_hops, 100, 42).unwrap();
1220 assert_eq!(route.hops.len(), 4);
1222 assert_eq!(route.hops[0].pubkey, node2);
1223 assert_eq!(route.hops[0].short_channel_id, 2);
1224 assert_eq!(route.hops[0].fee_msat, 200); // fee increased as its % of value transferred across node
1225 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1227 assert_eq!(route.hops[1].pubkey, node3);
1228 assert_eq!(route.hops[1].short_channel_id, 4);
1229 assert_eq!(route.hops[1].fee_msat, 100);
1230 assert_eq!(route.hops[1].cltv_expiry_delta, (7 << 8) | 1);
1232 assert_eq!(route.hops[2].pubkey, node6);
1233 assert_eq!(route.hops[2].short_channel_id, 7);
1234 assert_eq!(route.hops[2].fee_msat, 0);
1235 assert_eq!(route.hops[2].cltv_expiry_delta, (10 << 8) | 1);
1237 assert_eq!(route.hops[3].pubkey, node7);
1238 assert_eq!(route.hops[3].short_channel_id, 10);
1239 assert_eq!(route.hops[3].fee_msat, 100);
1240 assert_eq!(route.hops[3].cltv_expiry_delta, 42);
1243 { // ...but still use 8 for larger payments as 6 has a variable feerate
1244 let route = router.get_route(&node7, None, &last_hops, 2000, 42).unwrap();
1245 assert_eq!(route.hops.len(), 5);
1247 assert_eq!(route.hops[0].pubkey, node2);
1248 assert_eq!(route.hops[0].short_channel_id, 2);
1249 assert_eq!(route.hops[0].fee_msat, 3000);
1250 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1252 assert_eq!(route.hops[1].pubkey, node3);
1253 assert_eq!(route.hops[1].short_channel_id, 4);
1254 assert_eq!(route.hops[1].fee_msat, 0);
1255 assert_eq!(route.hops[1].cltv_expiry_delta, (6 << 8) | 1);
1257 assert_eq!(route.hops[2].pubkey, node5);
1258 assert_eq!(route.hops[2].short_channel_id, 6);
1259 assert_eq!(route.hops[2].fee_msat, 0);
1260 assert_eq!(route.hops[2].cltv_expiry_delta, (11 << 8) | 1);
1262 assert_eq!(route.hops[3].pubkey, node4);
1263 assert_eq!(route.hops[3].short_channel_id, 11);
1264 assert_eq!(route.hops[3].fee_msat, 1000);
1265 assert_eq!(route.hops[3].cltv_expiry_delta, (8 << 8) | 1);
1267 assert_eq!(route.hops[4].pubkey, node7);
1268 assert_eq!(route.hops[4].short_channel_id, 8);
1269 assert_eq!(route.hops[4].fee_msat, 2000);
1270 assert_eq!(route.hops[4].cltv_expiry_delta, 42);