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,NetAddress,GlobalFeatures};
13 use util::ser::Writeable;
14 use util::logger::Logger;
17 use std::sync::{RwLock,Arc};
18 use std::collections::{HashMap,BinaryHeap};
19 use std::collections::hash_map::Entry;
25 pub pubkey: PublicKey,
26 /// The channel that should be used from the previous hop to reach this node.
27 pub short_channel_id: u64,
28 /// The fee taken on this hop. For the last hop, this should be the full value of the payment.
30 /// The CLTV delta added for this hop. For the last hop, this should be the full CLTV value
31 /// expected at the destination, in excess of the current block height.
32 pub cltv_expiry_delta: u32,
35 /// A route from us through the network to a destination
38 /// The list of hops, NOT INCLUDING our own, where the last hop is the destination. Thus, this
39 /// must always be at least length one. By protocol rules, this may not currently exceed 20 in
41 pub hops: Vec<RouteHop>,
44 struct DirectionalChannelInfo {
45 src_node_id: PublicKey,
48 cltv_expiry_delta: u16,
49 htlc_minimum_msat: u64,
51 fee_proportional_millionths: u32,
54 impl std::fmt::Display for DirectionalChannelInfo {
55 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
56 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)?;
62 features: GlobalFeatures,
63 one_to_two: DirectionalChannelInfo,
64 two_to_one: DirectionalChannelInfo,
67 impl std::fmt::Display for ChannelInfo {
68 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
69 write!(f, "features: {}, one_to_two: {}, two_to_one: {}", log_bytes!(self.features.encode()), self.one_to_two, self.two_to_one)?;
75 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
76 channels: Vec<(u64, Sha256dHash)>,
77 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
80 lowest_inbound_channel_fee_base_msat: u32,
81 lowest_inbound_channel_fee_proportional_millionths: u32,
83 features: GlobalFeatures,
87 addresses: Vec<NetAddress>,
90 impl std::fmt::Display for NodeInfo {
91 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
92 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[..])?;
98 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
99 channels: HashMap<(u64, Sha256dHash), ChannelInfo>,
100 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
101 channels: HashMap<u64, ChannelInfo>,
103 our_node_id: PublicKey,
104 nodes: HashMap<PublicKey, NodeInfo>,
106 struct MutNetworkMap<'a> {
107 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
108 channels: &'a mut HashMap<(u64, Sha256dHash), ChannelInfo>,
109 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
110 channels: &'a mut HashMap<u64, ChannelInfo>,
111 nodes: &'a mut HashMap<PublicKey, NodeInfo>,
114 fn borrow_parts(&mut self) -> MutNetworkMap {
116 channels: &mut self.channels,
117 nodes: &mut self.nodes,
121 impl std::fmt::Display for NetworkMap {
122 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
123 write!(f, "Node id {} network map\n[Channels]\n", log_pubkey!(self.our_node_id))?;
124 for (key, val) in self.channels.iter() {
125 write!(f, " {}: {}\n", key, val)?;
127 write!(f, "[Nodes]\n")?;
128 for (key, val) in self.nodes.iter() {
129 write!(f, " {}: {}\n", log_pubkey!(key), val)?;
136 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
138 fn get_key(short_channel_id: u64, chain_hash: Sha256dHash) -> (u64, Sha256dHash) {
139 (short_channel_id, chain_hash)
142 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
144 fn get_key(short_channel_id: u64, _: Sha256dHash) -> u64 {
148 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
150 fn get_short_id(id: &(u64, Sha256dHash)) -> &u64 {
154 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
156 fn get_short_id(id: &u64) -> &u64 {
161 /// A channel descriptor which provides a last-hop route to get_route
162 pub struct RouteHint {
163 pub src_node_id: PublicKey,
164 pub short_channel_id: u64,
165 pub fee_base_msat: u32,
166 pub fee_proportional_millionths: u32,
167 pub cltv_expiry_delta: u16,
168 pub htlc_minimum_msat: u64,
171 /// Tracks a view of the network, receiving updates from peers and generating Routes to
172 /// payment destinations.
174 secp_ctx: Secp256k1<secp256k1::VerifyOnly>,
175 network_map: RwLock<NetworkMap>,
176 chain_monitor: Arc<ChainWatchInterface>,
180 macro_rules! secp_verify_sig {
181 ( $secp_ctx: expr, $msg: expr, $sig: expr, $pubkey: expr ) => {
182 match $secp_ctx.verify($msg, $sig, $pubkey) {
184 Err(_) => return Err(HandleError{err: "Invalid signature from remote node", action: None}),
189 impl RoutingMessageHandler for Router {
190 fn handle_node_announcement(&self, msg: &msgs::NodeAnnouncement) -> Result<bool, HandleError> {
191 let msg_hash = Message::from_slice(&Sha256dHash::from_data(&msg.contents.encode()[..])[..]).unwrap();
192 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.signature, &msg.contents.node_id);
194 if msg.contents.features.requires_unknown_bits() {
195 panic!("Unknown-required-features NodeAnnouncements should never deserialize!");
198 let mut network = self.network_map.write().unwrap();
199 match network.nodes.get_mut(&msg.contents.node_id) {
200 None => Err(HandleError{err: "No existing channels for node_announcement", action: Some(ErrorAction::IgnoreError)}),
202 if node.last_update >= msg.contents.timestamp {
203 return Err(HandleError{err: "Update older than last processed update", action: Some(ErrorAction::IgnoreError)});
206 node.features = msg.contents.features.clone();
207 node.last_update = msg.contents.timestamp;
208 node.rgb = msg.contents.rgb;
209 node.alias = msg.contents.alias;
210 node.addresses = msg.contents.addresses.clone();
211 Ok(msg.contents.excess_data.is_empty() && msg.contents.excess_address_data.is_empty() && !msg.contents.features.supports_unknown_bits())
216 fn handle_channel_announcement(&self, msg: &msgs::ChannelAnnouncement) -> Result<bool, HandleError> {
217 if msg.contents.node_id_1 == msg.contents.node_id_2 || msg.contents.bitcoin_key_1 == msg.contents.bitcoin_key_2 {
218 return Err(HandleError{err: "Channel announcement node had a channel with itself", action: Some(ErrorAction::IgnoreError)});
221 let msg_hash = Message::from_slice(&Sha256dHash::from_data(&msg.contents.encode()[..])[..]).unwrap();
222 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.node_signature_1, &msg.contents.node_id_1);
223 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.node_signature_2, &msg.contents.node_id_2);
224 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.bitcoin_signature_1, &msg.contents.bitcoin_key_1);
225 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.bitcoin_signature_2, &msg.contents.bitcoin_key_2);
227 if msg.contents.features.requires_unknown_bits() {
228 panic!("Unknown-required-features ChannelAnnouncements should never deserialize!");
231 let checked_utxo = match self.chain_monitor.get_chain_utxo(msg.contents.chain_hash, msg.contents.short_channel_id) {
232 Ok((script_pubkey, _value)) => {
233 let expected_script = Builder::new().push_opcode(opcodes::All::OP_PUSHNUM_2)
234 .push_slice(&msg.contents.bitcoin_key_1.serialize())
235 .push_slice(&msg.contents.bitcoin_key_2.serialize())
236 .push_opcode(opcodes::All::OP_PUSHNUM_2).push_opcode(opcodes::All::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
237 if script_pubkey != expected_script {
238 return Err(HandleError{err: "Channel announcement keys didn't match on-chain script", action: Some(ErrorAction::IgnoreError)});
240 //TODO: Check if value is worth storing, use it to inform routing, and compare it
241 //to the new HTLC max field in channel_update
244 Err(ChainError::NotSupported) => {
245 // Tentatively accept, potentially exposing us to DoS attacks
248 Err(ChainError::NotWatched) => {
249 return Err(HandleError{err: "Channel announced on an unknown chain", action: Some(ErrorAction::IgnoreError)});
251 Err(ChainError::UnknownTx) => {
252 return Err(HandleError{err: "Channel announced without corresponding UTXO entry", action: Some(ErrorAction::IgnoreError)});
256 let mut network_lock = self.network_map.write().unwrap();
257 let network = network_lock.borrow_parts();
259 let chan_info = ChannelInfo {
260 features: msg.contents.features.clone(),
261 one_to_two: DirectionalChannelInfo {
262 src_node_id: msg.contents.node_id_1.clone(),
265 cltv_expiry_delta: u16::max_value(),
266 htlc_minimum_msat: u64::max_value(),
267 fee_base_msat: u32::max_value(),
268 fee_proportional_millionths: u32::max_value(),
270 two_to_one: DirectionalChannelInfo {
271 src_node_id: msg.contents.node_id_2.clone(),
274 cltv_expiry_delta: u16::max_value(),
275 htlc_minimum_msat: u64::max_value(),
276 fee_base_msat: u32::max_value(),
277 fee_proportional_millionths: u32::max_value(),
281 match network.channels.entry(NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash)) {
282 Entry::Occupied(mut entry) => {
283 //TODO: because asking the blockchain if short_channel_id is valid is only optional
284 //in the blockchain API, we need to handle it smartly here, though its unclear
287 // Either our UTXO provider is busted, there was a reorg, or the UTXO provider
288 // only sometimes returns results. In any case remove the previous entry. Note
289 // that the spec expects us to "blacklist" the node_ids involved, but we can't
291 // a) we don't *require* a UTXO provider that always returns results.
292 // b) we don't track UTXOs of channels we know about and remove them if they
294 // c) it's unclear how to do so without exposing ourselves to massive DoS risk.
295 Self::remove_channel_in_nodes(network.nodes, &entry.get(), msg.contents.short_channel_id);
296 *entry.get_mut() = chan_info;
298 return Err(HandleError{err: "Already have knowledge of channel", action: Some(ErrorAction::IgnoreError)})
301 Entry::Vacant(entry) => {
302 entry.insert(chan_info);
306 macro_rules! add_channel_to_node {
307 ( $node_id: expr ) => {
308 match network.nodes.entry($node_id) {
309 Entry::Occupied(node_entry) => {
310 node_entry.into_mut().channels.push(NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash));
312 Entry::Vacant(node_entry) => {
313 node_entry.insert(NodeInfo {
314 channels: vec!(NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash)),
315 lowest_inbound_channel_fee_base_msat: u32::max_value(),
316 lowest_inbound_channel_fee_proportional_millionths: u32::max_value(),
317 features: GlobalFeatures::new(),
321 addresses: Vec::new(),
328 add_channel_to_node!(msg.contents.node_id_1);
329 add_channel_to_node!(msg.contents.node_id_2);
331 Ok(msg.contents.excess_data.is_empty() && !msg.contents.features.supports_unknown_bits())
334 fn handle_htlc_fail_channel_update(&self, update: &msgs::HTLCFailChannelUpdate) {
336 &msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg } => {
337 let _ = self.handle_channel_update(msg);
339 &msgs::HTLCFailChannelUpdate::ChannelClosed { ref short_channel_id } => {
340 let mut network = self.network_map.write().unwrap();
341 if let Some(chan) = network.channels.remove(short_channel_id) {
342 Self::remove_channel_in_nodes(&mut network.nodes, &chan, *short_channel_id);
348 fn handle_channel_update(&self, msg: &msgs::ChannelUpdate) -> Result<bool, HandleError> {
349 let mut network = self.network_map.write().unwrap();
351 let chan_enabled = msg.contents.flags & (1 << 1) != (1 << 1);
352 let chan_was_enabled;
354 match network.channels.get_mut(&NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash)) {
355 None => return Err(HandleError{err: "Couldn't find channel for update", action: Some(ErrorAction::IgnoreError)}),
357 macro_rules! maybe_update_channel_info {
358 ( $target: expr) => {
359 if $target.last_update >= msg.contents.timestamp {
360 return Err(HandleError{err: "Update older than last processed update", action: Some(ErrorAction::IgnoreError)});
362 chan_was_enabled = $target.enabled;
363 $target.last_update = msg.contents.timestamp;
364 $target.enabled = chan_enabled;
365 $target.cltv_expiry_delta = msg.contents.cltv_expiry_delta;
366 $target.htlc_minimum_msat = msg.contents.htlc_minimum_msat;
367 $target.fee_base_msat = msg.contents.fee_base_msat;
368 $target.fee_proportional_millionths = msg.contents.fee_proportional_millionths;
372 let msg_hash = Message::from_slice(&Sha256dHash::from_data(&msg.contents.encode()[..])[..]).unwrap();
373 if msg.contents.flags & 1 == 1 {
374 dest_node_id = channel.one_to_two.src_node_id.clone();
375 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.signature, &channel.two_to_one.src_node_id);
376 maybe_update_channel_info!(channel.two_to_one);
378 dest_node_id = channel.two_to_one.src_node_id.clone();
379 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.signature, &channel.one_to_two.src_node_id);
380 maybe_update_channel_info!(channel.one_to_two);
386 let node = network.nodes.get_mut(&dest_node_id).unwrap();
387 node.lowest_inbound_channel_fee_base_msat = cmp::min(node.lowest_inbound_channel_fee_base_msat, msg.contents.fee_base_msat);
388 node.lowest_inbound_channel_fee_proportional_millionths = cmp::min(node.lowest_inbound_channel_fee_proportional_millionths, msg.contents.fee_proportional_millionths);
389 } else if chan_was_enabled {
390 let mut lowest_inbound_channel_fee_base_msat = u32::max_value();
391 let mut lowest_inbound_channel_fee_proportional_millionths = u32::max_value();
394 let node = network.nodes.get(&dest_node_id).unwrap();
396 for chan_id in node.channels.iter() {
397 let chan = network.channels.get(chan_id).unwrap();
398 if chan.one_to_two.src_node_id == dest_node_id {
399 lowest_inbound_channel_fee_base_msat = cmp::min(lowest_inbound_channel_fee_base_msat, chan.two_to_one.fee_base_msat);
400 lowest_inbound_channel_fee_proportional_millionths = cmp::min(lowest_inbound_channel_fee_proportional_millionths, chan.two_to_one.fee_proportional_millionths);
402 lowest_inbound_channel_fee_base_msat = cmp::min(lowest_inbound_channel_fee_base_msat, chan.one_to_two.fee_base_msat);
403 lowest_inbound_channel_fee_proportional_millionths = cmp::min(lowest_inbound_channel_fee_proportional_millionths, chan.one_to_two.fee_proportional_millionths);
408 //TODO: satisfy the borrow-checker without a double-map-lookup :(
409 let mut_node = network.nodes.get_mut(&dest_node_id).unwrap();
410 mut_node.lowest_inbound_channel_fee_base_msat = lowest_inbound_channel_fee_base_msat;
411 mut_node.lowest_inbound_channel_fee_proportional_millionths = lowest_inbound_channel_fee_proportional_millionths;
414 Ok(msg.contents.excess_data.is_empty())
418 #[derive(Eq, PartialEq)]
419 struct RouteGraphNode {
421 lowest_fee_to_peer_through_node: u64,
422 lowest_fee_to_node: u64,
425 impl cmp::Ord for RouteGraphNode {
426 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
427 other.lowest_fee_to_peer_through_node.cmp(&self.lowest_fee_to_peer_through_node)
428 .then_with(|| other.pubkey.serialize().cmp(&self.pubkey.serialize()))
432 impl cmp::PartialOrd for RouteGraphNode {
433 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
434 Some(self.cmp(other))
438 struct DummyDirectionalChannelInfo {
439 src_node_id: PublicKey,
440 cltv_expiry_delta: u32,
441 htlc_minimum_msat: u64,
443 fee_proportional_millionths: u32,
447 pub fn new(our_pubkey: PublicKey, chain_monitor: Arc<ChainWatchInterface>, logger: Arc<Logger>) -> Router {
448 let mut nodes = HashMap::new();
449 nodes.insert(our_pubkey.clone(), NodeInfo {
450 channels: Vec::new(),
451 lowest_inbound_channel_fee_base_msat: u32::max_value(),
452 lowest_inbound_channel_fee_proportional_millionths: u32::max_value(),
453 features: GlobalFeatures::new(),
457 addresses: Vec::new(),
460 secp_ctx: Secp256k1::verification_only(),
461 network_map: RwLock::new(NetworkMap {
462 channels: HashMap::new(),
463 our_node_id: our_pubkey,
471 /// Dumps the entire network view of this Router to the logger provided in the constructor at
473 pub fn trace_state(&self) {
474 log_trace!(self, "{}", self.network_map.read().unwrap());
477 /// Get network addresses by node id
478 pub fn get_addresses(&self, pubkey: &PublicKey) -> Option<Vec<NetAddress>> {
479 let network = self.network_map.read().unwrap();
480 network.nodes.get(pubkey).map(|n| n.addresses.clone())
483 /// Marks a node as having failed a route. This will avoid re-using the node in routes for now,
484 /// with an expotnential decay in node "badness". Note that there is deliberately no
485 /// mark_channel_bad as a node may simply lie and suggest that an upstream channel from it is
486 /// what failed the route and not the node itself. Instead, setting the blamed_upstream_node
487 /// boolean will reduce the penalty, returning the node to usability faster. If the node is
488 /// behaving correctly, it will disable the failing channel and we will use it again next time.
489 pub fn mark_node_bad(&self, _node_id: &PublicKey, _blamed_upstream_node: bool) {
493 fn remove_channel_in_nodes(nodes: &mut HashMap<PublicKey, NodeInfo>, chan: &ChannelInfo, short_channel_id: u64) {
494 macro_rules! remove_from_node {
495 ($node_id: expr) => {
496 if let Entry::Occupied(mut entry) = nodes.entry($node_id) {
497 entry.get_mut().channels.retain(|chan_id| {
498 short_channel_id != *NetworkMap::get_short_id(chan_id)
500 if entry.get().channels.is_empty() {
501 entry.remove_entry();
504 panic!("Had channel that pointed to unknown node (ie inconsistent network map)!");
508 remove_from_node!(chan.one_to_two.src_node_id);
509 remove_from_node!(chan.two_to_one.src_node_id);
512 /// Gets a route from us to the given target node.
513 /// Extra routing hops between known nodes and the target will be used if they are included in
515 /// If some channels aren't announced, it may be useful to fill in a first_hops with the
516 /// results from a local ChannelManager::list_usable_channels() call. If it is filled in, our
517 /// (this Router's) view of our local channels will be ignored, and only those in first_hops
518 /// will be used. Panics if first_hops contains channels without short_channel_ids
519 /// (ChannelManager::list_usable_channels will never include such channels).
520 /// The fees on channels from us to next-hops are ignored (as they are assumed to all be
521 /// equal), however the enabled/disabled bit on such channels as well as the htlc_minimum_msat
522 /// *is* checked as they may change based on the receiving node.
523 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> {
524 // TODO: Obviously *only* using total fee cost sucks. We should consider weighting by
525 // uptime/success in using a node in the past.
526 let network = self.network_map.read().unwrap();
528 if *target == network.our_node_id {
529 return Err(HandleError{err: "Cannot generate a route to ourselves", action: None});
532 if final_value_msat > 21_000_000 * 1_0000_0000 * 1000 {
533 return Err(HandleError{err: "Cannot generate a route of more value than all existing satoshis", action: None});
536 // We do a dest-to-source Dijkstra's sorting by each node's distance from the destination
537 // plus the minimum per-HTLC fee to get from it to another node (aka "shitty A*").
538 // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
539 // to use as the A* heuristic beyond just the cost to get one node further than the current
542 let dummy_directional_info = DummyDirectionalChannelInfo { // used for first_hops routes
543 src_node_id: network.our_node_id.clone(),
544 cltv_expiry_delta: 0,
545 htlc_minimum_msat: 0,
547 fee_proportional_millionths: 0,
550 let mut targets = BinaryHeap::new(); //TODO: Do we care about switching to eg Fibbonaci heap?
551 let mut dist = HashMap::with_capacity(network.nodes.len());
553 let mut first_hop_targets = HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
554 if let Some(hops) = first_hops {
556 let short_channel_id = chan.short_channel_id.expect("first_hops should be filled in with usable channels, not pending ones");
557 if chan.remote_network_id == *target {
559 hops: vec![RouteHop {
560 pubkey: chan.remote_network_id,
562 fee_msat: final_value_msat,
563 cltv_expiry_delta: final_cltv,
567 first_hop_targets.insert(chan.remote_network_id, short_channel_id);
569 if first_hop_targets.is_empty() {
570 return Err(HandleError{err: "Cannot route when there are no outbound routes away from us", action: None});
574 macro_rules! add_entry {
575 // Adds entry which goes from the node pointed to by $directional_info to
576 // $dest_node_id over the channel with id $chan_id with fees described in
577 // $directional_info.
578 ( $chan_id: expr, $dest_node_id: expr, $directional_info: expr, $starting_fee_msat: expr ) => {
579 //TODO: Explore simply adding fee to hit htlc_minimum_msat
580 if $starting_fee_msat as u64 + final_value_msat > $directional_info.htlc_minimum_msat {
581 let proportional_fee_millions = ($starting_fee_msat + final_value_msat).checked_mul($directional_info.fee_proportional_millionths as u64);
582 if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
583 ($directional_info.fee_base_msat as u64).checked_add(part / 1000000) })
585 let mut total_fee = $starting_fee_msat as u64;
586 let hm_entry = dist.entry(&$directional_info.src_node_id);
587 let old_entry = hm_entry.or_insert_with(|| {
588 let node = network.nodes.get(&$directional_info.src_node_id).unwrap();
590 node.lowest_inbound_channel_fee_base_msat,
591 node.lowest_inbound_channel_fee_proportional_millionths,
593 pubkey: $dest_node_id.clone(),
596 cltv_expiry_delta: 0,
599 if $directional_info.src_node_id != network.our_node_id {
600 // Ignore new_fee for channel-from-us as we assume all channels-from-us
601 // will have the same effective-fee
602 total_fee += new_fee;
603 if let Some(fee_inc) = final_value_msat.checked_add(total_fee).and_then(|inc| { (old_entry.2 as u64).checked_mul(inc) }) {
604 total_fee += fee_inc / 1000000 + (old_entry.1 as u64);
606 // max_value means we'll always fail the old_entry.0 > total_fee check
607 total_fee = u64::max_value();
610 let new_graph_node = RouteGraphNode {
611 pubkey: $directional_info.src_node_id,
612 lowest_fee_to_peer_through_node: total_fee,
613 lowest_fee_to_node: $starting_fee_msat as u64 + new_fee,
615 if old_entry.0 > total_fee {
616 targets.push(new_graph_node);
617 old_entry.0 = total_fee;
618 old_entry.3 = RouteHop {
619 pubkey: $dest_node_id.clone(),
620 short_channel_id: $chan_id.clone(),
621 fee_msat: new_fee, // This field is ignored on the last-hop anyway
622 cltv_expiry_delta: $directional_info.cltv_expiry_delta as u32,
630 macro_rules! add_entries_to_cheapest_to_target_node {
631 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr ) => {
632 if first_hops.is_some() {
633 if let Some(first_hop) = first_hop_targets.get(&$node_id) {
634 add_entry!(first_hop, $node_id, dummy_directional_info, $fee_to_target_msat);
638 for chan_id in $node.channels.iter() {
639 let chan = network.channels.get(chan_id).unwrap();
640 if chan.one_to_two.src_node_id == *$node_id {
641 // ie $node is one, ie next hop in A* is two, via the two_to_one channel
642 if first_hops.is_none() || chan.two_to_one.src_node_id != network.our_node_id {
643 if chan.two_to_one.enabled {
644 add_entry!(chan_id, chan.one_to_two.src_node_id, chan.two_to_one, $fee_to_target_msat);
648 if first_hops.is_none() || chan.one_to_two.src_node_id != network.our_node_id {
649 if chan.one_to_two.enabled {
650 add_entry!(chan_id, chan.two_to_one.src_node_id, chan.one_to_two, $fee_to_target_msat);
658 match network.nodes.get(target) {
661 add_entries_to_cheapest_to_target_node!(node, target, 0);
665 for hop in last_hops.iter() {
666 if first_hops.is_none() || hop.src_node_id != network.our_node_id { // first_hop overrules last_hops
667 if network.nodes.get(&hop.src_node_id).is_some() {
668 if first_hops.is_some() {
669 if let Some(first_hop) = first_hop_targets.get(&hop.src_node_id) {
670 add_entry!(first_hop, hop.src_node_id, dummy_directional_info, 0);
673 add_entry!(hop.short_channel_id, target, hop, 0);
678 while let Some(RouteGraphNode { pubkey, lowest_fee_to_node, .. }) = targets.pop() {
679 if pubkey == network.our_node_id {
680 let mut res = vec!(dist.remove(&network.our_node_id).unwrap().3);
681 while res.last().unwrap().pubkey != *target {
682 let new_entry = match dist.remove(&res.last().unwrap().pubkey) {
684 None => return Err(HandleError{err: "Failed to find a non-fee-overflowing path to the given destination", action: None}),
686 res.last_mut().unwrap().fee_msat = new_entry.fee_msat;
687 res.last_mut().unwrap().cltv_expiry_delta = new_entry.cltv_expiry_delta;
690 res.last_mut().unwrap().fee_msat = final_value_msat;
691 res.last_mut().unwrap().cltv_expiry_delta = final_cltv;
692 let route = Route { hops: res };
693 log_trace!(self, "Got route: {}", log_route!(route));
697 match network.nodes.get(&pubkey) {
700 add_entries_to_cheapest_to_target_node!(node, &pubkey, lowest_fee_to_node);
705 Err(HandleError{err: "Failed to find a path to the given destination", action: None})
711 use chain::chaininterface;
712 use ln::channelmanager;
713 use ln::router::{Router,NodeInfo,NetworkMap,ChannelInfo,DirectionalChannelInfo,RouteHint};
714 use ln::msgs::GlobalFeatures;
715 use util::test_utils;
716 use util::logger::Logger;
718 use bitcoin::util::hash::Sha256dHash;
719 use bitcoin::network::constants::Network;
723 use secp256k1::key::{PublicKey,SecretKey};
724 use secp256k1::Secp256k1;
730 let secp_ctx = Secp256k1::new();
731 let our_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap());
732 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
733 let chain_monitor = Arc::new(chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet, Arc::clone(&logger)));
734 let router = Router::new(our_id, chain_monitor, Arc::clone(&logger));
736 // Build network from our_id to node8:
738 // -1(1)2- node1 -1(3)2-
740 // our_id -1(12)2- node8 -1(13)2--- node3
742 // -1(2)2- node2 -1(4)2-
745 // chan1 1-to-2: disabled
746 // chan1 2-to-1: enabled, 0 fee
748 // chan2 1-to-2: enabled, ignored fee
749 // chan2 2-to-1: enabled, 0 fee
751 // chan3 1-to-2: enabled, 0 fee
752 // chan3 2-to-1: enabled, 100 msat fee
754 // chan4 1-to-2: enabled, 100% fee
755 // chan4 2-to-1: enabled, 0 fee
757 // chan12 1-to-2: enabled, ignored fee
758 // chan12 2-to-1: enabled, 0 fee
760 // chan13 1-to-2: enabled, 200% fee
761 // chan13 2-to-1: enabled, 0 fee
764 // -1(5)2- node4 -1(8)2--
768 // node3--1(6)2- node5 -1(9)2--- node7 (not in global route map)
770 // -1(7)2- node6 -1(10)2-
772 // chan5 1-to-2: enabled, 100 msat fee
773 // chan5 2-to-1: enabled, 0 fee
775 // chan6 1-to-2: enabled, 0 fee
776 // chan6 2-to-1: enabled, 0 fee
778 // chan7 1-to-2: enabled, 100% fee
779 // chan7 2-to-1: enabled, 0 fee
781 // chan8 1-to-2: enabled, variable fee (0 then 1000 msat)
782 // chan8 2-to-1: enabled, 0 fee
784 // chan9 1-to-2: enabled, 1001 msat fee
785 // chan9 2-to-1: enabled, 0 fee
787 // chan10 1-to-2: enabled, 0 fee
788 // chan10 2-to-1: enabled, 0 fee
790 // chan11 1-to-2: enabled, 0 fee
791 // chan11 2-to-1: enabled, 0 fee
793 let node1 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap()[..]).unwrap());
794 let node2 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0303030303030303030303030303030303030303030303030303030303030303").unwrap()[..]).unwrap());
795 let node3 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0404040404040404040404040404040404040404040404040404040404040404").unwrap()[..]).unwrap());
796 let node4 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0505050505050505050505050505050505050505050505050505050505050505").unwrap()[..]).unwrap());
797 let node5 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0606060606060606060606060606060606060606060606060606060606060606").unwrap()[..]).unwrap());
798 let node6 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0707070707070707070707070707070707070707070707070707070707070707").unwrap()[..]).unwrap());
799 let node7 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0808080808080808080808080808080808080808080808080808080808080808").unwrap()[..]).unwrap());
800 let node8 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0909090909090909090909090909090909090909090909090909090909090909").unwrap()[..]).unwrap());
802 let zero_hash = Sha256dHash::from_data(&[0; 32]);
805 let mut network = router.network_map.write().unwrap();
807 network.nodes.insert(node1.clone(), NodeInfo {
808 channels: vec!(NetworkMap::get_key(1, zero_hash.clone()), NetworkMap::get_key(3, zero_hash.clone())),
809 lowest_inbound_channel_fee_base_msat: 100,
810 lowest_inbound_channel_fee_proportional_millionths: 0,
811 features: GlobalFeatures::new(),
815 addresses: Vec::new(),
817 network.channels.insert(NetworkMap::get_key(1, zero_hash.clone()), ChannelInfo {
818 features: GlobalFeatures::new(),
819 one_to_two: DirectionalChannelInfo {
820 src_node_id: our_id.clone(),
823 cltv_expiry_delta: u16::max_value(), // This value should be ignored
824 htlc_minimum_msat: 0,
825 fee_base_msat: u32::max_value(), // This value should be ignored
826 fee_proportional_millionths: u32::max_value(), // This value should be ignored
827 }, two_to_one: DirectionalChannelInfo {
828 src_node_id: node1.clone(),
831 cltv_expiry_delta: 0,
832 htlc_minimum_msat: 0,
834 fee_proportional_millionths: 0,
837 network.nodes.insert(node2.clone(), NodeInfo {
838 channels: vec!(NetworkMap::get_key(2, zero_hash.clone()), NetworkMap::get_key(4, zero_hash.clone())),
839 lowest_inbound_channel_fee_base_msat: 0,
840 lowest_inbound_channel_fee_proportional_millionths: 0,
841 features: GlobalFeatures::new(),
845 addresses: Vec::new(),
847 network.channels.insert(NetworkMap::get_key(2, zero_hash.clone()), ChannelInfo {
848 features: GlobalFeatures::new(),
849 one_to_two: DirectionalChannelInfo {
850 src_node_id: our_id.clone(),
853 cltv_expiry_delta: u16::max_value(), // This value should be ignored
854 htlc_minimum_msat: 0,
855 fee_base_msat: u32::max_value(), // This value should be ignored
856 fee_proportional_millionths: u32::max_value(), // This value should be ignored
857 }, two_to_one: DirectionalChannelInfo {
858 src_node_id: node2.clone(),
861 cltv_expiry_delta: 0,
862 htlc_minimum_msat: 0,
864 fee_proportional_millionths: 0,
867 network.nodes.insert(node8.clone(), NodeInfo {
868 channels: vec!(NetworkMap::get_key(12, zero_hash.clone()), NetworkMap::get_key(13, zero_hash.clone())),
869 lowest_inbound_channel_fee_base_msat: 0,
870 lowest_inbound_channel_fee_proportional_millionths: 0,
871 features: GlobalFeatures::new(),
875 addresses: Vec::new(),
877 network.channels.insert(NetworkMap::get_key(12, zero_hash.clone()), ChannelInfo {
878 features: GlobalFeatures::new(),
879 one_to_two: DirectionalChannelInfo {
880 src_node_id: our_id.clone(),
883 cltv_expiry_delta: u16::max_value(), // This value should be ignored
884 htlc_minimum_msat: 0,
885 fee_base_msat: u32::max_value(), // This value should be ignored
886 fee_proportional_millionths: u32::max_value(), // This value should be ignored
887 }, two_to_one: DirectionalChannelInfo {
888 src_node_id: node8.clone(),
891 cltv_expiry_delta: 0,
892 htlc_minimum_msat: 0,
894 fee_proportional_millionths: 0,
897 network.nodes.insert(node3.clone(), NodeInfo {
899 NetworkMap::get_key(3, zero_hash.clone()),
900 NetworkMap::get_key(4, zero_hash.clone()),
901 NetworkMap::get_key(13, zero_hash.clone()),
902 NetworkMap::get_key(5, zero_hash.clone()),
903 NetworkMap::get_key(6, zero_hash.clone()),
904 NetworkMap::get_key(7, zero_hash.clone())),
905 lowest_inbound_channel_fee_base_msat: 0,
906 lowest_inbound_channel_fee_proportional_millionths: 0,
907 features: GlobalFeatures::new(),
911 addresses: Vec::new(),
913 network.channels.insert(NetworkMap::get_key(3, zero_hash.clone()), ChannelInfo {
914 features: GlobalFeatures::new(),
915 one_to_two: DirectionalChannelInfo {
916 src_node_id: node1.clone(),
919 cltv_expiry_delta: (3 << 8) | 1,
920 htlc_minimum_msat: 0,
922 fee_proportional_millionths: 0,
923 }, two_to_one: DirectionalChannelInfo {
924 src_node_id: node3.clone(),
927 cltv_expiry_delta: (3 << 8) | 2,
928 htlc_minimum_msat: 0,
930 fee_proportional_millionths: 0,
933 network.channels.insert(NetworkMap::get_key(4, zero_hash.clone()), ChannelInfo {
934 features: GlobalFeatures::new(),
935 one_to_two: DirectionalChannelInfo {
936 src_node_id: node2.clone(),
939 cltv_expiry_delta: (4 << 8) | 1,
940 htlc_minimum_msat: 0,
942 fee_proportional_millionths: 1000000,
943 }, two_to_one: DirectionalChannelInfo {
944 src_node_id: node3.clone(),
947 cltv_expiry_delta: (4 << 8) | 2,
948 htlc_minimum_msat: 0,
950 fee_proportional_millionths: 0,
953 network.channels.insert(NetworkMap::get_key(13, zero_hash.clone()), ChannelInfo {
954 features: GlobalFeatures::new(),
955 one_to_two: DirectionalChannelInfo {
956 src_node_id: node8.clone(),
959 cltv_expiry_delta: (13 << 8) | 1,
960 htlc_minimum_msat: 0,
962 fee_proportional_millionths: 2000000,
963 }, two_to_one: DirectionalChannelInfo {
964 src_node_id: node3.clone(),
967 cltv_expiry_delta: (13 << 8) | 2,
968 htlc_minimum_msat: 0,
970 fee_proportional_millionths: 0,
973 network.nodes.insert(node4.clone(), NodeInfo {
974 channels: vec!(NetworkMap::get_key(5, zero_hash.clone()), NetworkMap::get_key(11, zero_hash.clone())),
975 lowest_inbound_channel_fee_base_msat: 0,
976 lowest_inbound_channel_fee_proportional_millionths: 0,
977 features: GlobalFeatures::new(),
981 addresses: Vec::new(),
983 network.channels.insert(NetworkMap::get_key(5, zero_hash.clone()), ChannelInfo {
984 features: GlobalFeatures::new(),
985 one_to_two: DirectionalChannelInfo {
986 src_node_id: node3.clone(),
989 cltv_expiry_delta: (5 << 8) | 1,
990 htlc_minimum_msat: 0,
992 fee_proportional_millionths: 0,
993 }, two_to_one: DirectionalChannelInfo {
994 src_node_id: node4.clone(),
997 cltv_expiry_delta: (5 << 8) | 2,
998 htlc_minimum_msat: 0,
1000 fee_proportional_millionths: 0,
1003 network.nodes.insert(node5.clone(), NodeInfo {
1004 channels: vec!(NetworkMap::get_key(6, zero_hash.clone()), NetworkMap::get_key(11, zero_hash.clone())),
1005 lowest_inbound_channel_fee_base_msat: 0,
1006 lowest_inbound_channel_fee_proportional_millionths: 0,
1007 features: GlobalFeatures::new(),
1011 addresses: Vec::new(),
1013 network.channels.insert(NetworkMap::get_key(6, zero_hash.clone()), ChannelInfo {
1014 features: GlobalFeatures::new(),
1015 one_to_two: DirectionalChannelInfo {
1016 src_node_id: node3.clone(),
1019 cltv_expiry_delta: (6 << 8) | 1,
1020 htlc_minimum_msat: 0,
1022 fee_proportional_millionths: 0,
1023 }, two_to_one: DirectionalChannelInfo {
1024 src_node_id: node5.clone(),
1027 cltv_expiry_delta: (6 << 8) | 2,
1028 htlc_minimum_msat: 0,
1030 fee_proportional_millionths: 0,
1033 network.channels.insert(NetworkMap::get_key(11, zero_hash.clone()), ChannelInfo {
1034 features: GlobalFeatures::new(),
1035 one_to_two: DirectionalChannelInfo {
1036 src_node_id: node5.clone(),
1039 cltv_expiry_delta: (11 << 8) | 1,
1040 htlc_minimum_msat: 0,
1042 fee_proportional_millionths: 0,
1043 }, two_to_one: DirectionalChannelInfo {
1044 src_node_id: node4.clone(),
1047 cltv_expiry_delta: (11 << 8) | 2,
1048 htlc_minimum_msat: 0,
1050 fee_proportional_millionths: 0,
1053 network.nodes.insert(node6.clone(), NodeInfo {
1054 channels: vec!(NetworkMap::get_key(7, zero_hash.clone())),
1055 lowest_inbound_channel_fee_base_msat: 0,
1056 lowest_inbound_channel_fee_proportional_millionths: 0,
1057 features: GlobalFeatures::new(),
1061 addresses: Vec::new(),
1063 network.channels.insert(NetworkMap::get_key(7, zero_hash.clone()), ChannelInfo {
1064 features: GlobalFeatures::new(),
1065 one_to_two: DirectionalChannelInfo {
1066 src_node_id: node3.clone(),
1069 cltv_expiry_delta: (7 << 8) | 1,
1070 htlc_minimum_msat: 0,
1072 fee_proportional_millionths: 1000000,
1073 }, two_to_one: DirectionalChannelInfo {
1074 src_node_id: node6.clone(),
1077 cltv_expiry_delta: (7 << 8) | 2,
1078 htlc_minimum_msat: 0,
1080 fee_proportional_millionths: 0,
1085 { // Simple route to 3 via 2
1086 let route = router.get_route(&node3, None, &Vec::new(), 100, 42).unwrap();
1087 assert_eq!(route.hops.len(), 2);
1089 assert_eq!(route.hops[0].pubkey, node2);
1090 assert_eq!(route.hops[0].short_channel_id, 2);
1091 assert_eq!(route.hops[0].fee_msat, 100);
1092 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1094 assert_eq!(route.hops[1].pubkey, node3);
1095 assert_eq!(route.hops[1].short_channel_id, 4);
1096 assert_eq!(route.hops[1].fee_msat, 100);
1097 assert_eq!(route.hops[1].cltv_expiry_delta, 42);
1100 { // Route to 1 via 2 and 3 because our channel to 1 is disabled
1101 let route = router.get_route(&node1, None, &Vec::new(), 100, 42).unwrap();
1102 assert_eq!(route.hops.len(), 3);
1104 assert_eq!(route.hops[0].pubkey, node2);
1105 assert_eq!(route.hops[0].short_channel_id, 2);
1106 assert_eq!(route.hops[0].fee_msat, 200);
1107 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1109 assert_eq!(route.hops[1].pubkey, node3);
1110 assert_eq!(route.hops[1].short_channel_id, 4);
1111 assert_eq!(route.hops[1].fee_msat, 100);
1112 assert_eq!(route.hops[1].cltv_expiry_delta, (3 << 8) | 2);
1114 assert_eq!(route.hops[2].pubkey, node1);
1115 assert_eq!(route.hops[2].short_channel_id, 3);
1116 assert_eq!(route.hops[2].fee_msat, 100);
1117 assert_eq!(route.hops[2].cltv_expiry_delta, 42);
1120 { // If we specify a channel to node8, that overrides our local channel view and that gets used
1121 let our_chans = vec![channelmanager::ChannelDetails {
1122 channel_id: [0; 32],
1123 short_channel_id: Some(42),
1124 remote_network_id: node8.clone(),
1125 channel_value_satoshis: 0,
1128 let route = router.get_route(&node3, Some(&our_chans), &Vec::new(), 100, 42).unwrap();
1129 assert_eq!(route.hops.len(), 2);
1131 assert_eq!(route.hops[0].pubkey, node8);
1132 assert_eq!(route.hops[0].short_channel_id, 42);
1133 assert_eq!(route.hops[0].fee_msat, 200);
1134 assert_eq!(route.hops[0].cltv_expiry_delta, (13 << 8) | 1);
1136 assert_eq!(route.hops[1].pubkey, node3);
1137 assert_eq!(route.hops[1].short_channel_id, 13);
1138 assert_eq!(route.hops[1].fee_msat, 100);
1139 assert_eq!(route.hops[1].cltv_expiry_delta, 42);
1142 let mut last_hops = vec!(RouteHint {
1143 src_node_id: node4.clone(),
1144 short_channel_id: 8,
1146 fee_proportional_millionths: 0,
1147 cltv_expiry_delta: (8 << 8) | 1,
1148 htlc_minimum_msat: 0,
1150 src_node_id: node5.clone(),
1151 short_channel_id: 9,
1152 fee_base_msat: 1001,
1153 fee_proportional_millionths: 0,
1154 cltv_expiry_delta: (9 << 8) | 1,
1155 htlc_minimum_msat: 0,
1157 src_node_id: node6.clone(),
1158 short_channel_id: 10,
1160 fee_proportional_millionths: 0,
1161 cltv_expiry_delta: (10 << 8) | 1,
1162 htlc_minimum_msat: 0,
1165 { // Simple test across 2, 3, 5, and 4 via a last_hop channel
1166 let route = router.get_route(&node7, None, &last_hops, 100, 42).unwrap();
1167 assert_eq!(route.hops.len(), 5);
1169 assert_eq!(route.hops[0].pubkey, node2);
1170 assert_eq!(route.hops[0].short_channel_id, 2);
1171 assert_eq!(route.hops[0].fee_msat, 100);
1172 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1174 assert_eq!(route.hops[1].pubkey, node3);
1175 assert_eq!(route.hops[1].short_channel_id, 4);
1176 assert_eq!(route.hops[1].fee_msat, 0);
1177 assert_eq!(route.hops[1].cltv_expiry_delta, (6 << 8) | 1);
1179 assert_eq!(route.hops[2].pubkey, node5);
1180 assert_eq!(route.hops[2].short_channel_id, 6);
1181 assert_eq!(route.hops[2].fee_msat, 0);
1182 assert_eq!(route.hops[2].cltv_expiry_delta, (11 << 8) | 1);
1184 assert_eq!(route.hops[3].pubkey, node4);
1185 assert_eq!(route.hops[3].short_channel_id, 11);
1186 assert_eq!(route.hops[3].fee_msat, 0);
1187 assert_eq!(route.hops[3].cltv_expiry_delta, (8 << 8) | 1);
1189 assert_eq!(route.hops[4].pubkey, node7);
1190 assert_eq!(route.hops[4].short_channel_id, 8);
1191 assert_eq!(route.hops[4].fee_msat, 100);
1192 assert_eq!(route.hops[4].cltv_expiry_delta, 42);
1195 { // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
1196 let our_chans = vec![channelmanager::ChannelDetails {
1197 channel_id: [0; 32],
1198 short_channel_id: Some(42),
1199 remote_network_id: node4.clone(),
1200 channel_value_satoshis: 0,
1203 let route = router.get_route(&node7, Some(&our_chans), &last_hops, 100, 42).unwrap();
1204 assert_eq!(route.hops.len(), 2);
1206 assert_eq!(route.hops[0].pubkey, node4);
1207 assert_eq!(route.hops[0].short_channel_id, 42);
1208 assert_eq!(route.hops[0].fee_msat, 0);
1209 assert_eq!(route.hops[0].cltv_expiry_delta, (8 << 8) | 1);
1211 assert_eq!(route.hops[1].pubkey, node7);
1212 assert_eq!(route.hops[1].short_channel_id, 8);
1213 assert_eq!(route.hops[1].fee_msat, 100);
1214 assert_eq!(route.hops[1].cltv_expiry_delta, 42);
1217 last_hops[0].fee_base_msat = 1000;
1219 { // Revert to via 6 as the fee on 8 goes up
1220 let route = router.get_route(&node7, None, &last_hops, 100, 42).unwrap();
1221 assert_eq!(route.hops.len(), 4);
1223 assert_eq!(route.hops[0].pubkey, node2);
1224 assert_eq!(route.hops[0].short_channel_id, 2);
1225 assert_eq!(route.hops[0].fee_msat, 200); // fee increased as its % of value transferred across node
1226 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1228 assert_eq!(route.hops[1].pubkey, node3);
1229 assert_eq!(route.hops[1].short_channel_id, 4);
1230 assert_eq!(route.hops[1].fee_msat, 100);
1231 assert_eq!(route.hops[1].cltv_expiry_delta, (7 << 8) | 1);
1233 assert_eq!(route.hops[2].pubkey, node6);
1234 assert_eq!(route.hops[2].short_channel_id, 7);
1235 assert_eq!(route.hops[2].fee_msat, 0);
1236 assert_eq!(route.hops[2].cltv_expiry_delta, (10 << 8) | 1);
1238 assert_eq!(route.hops[3].pubkey, node7);
1239 assert_eq!(route.hops[3].short_channel_id, 10);
1240 assert_eq!(route.hops[3].fee_msat, 100);
1241 assert_eq!(route.hops[3].cltv_expiry_delta, 42);
1244 { // ...but still use 8 for larger payments as 6 has a variable feerate
1245 let route = router.get_route(&node7, None, &last_hops, 2000, 42).unwrap();
1246 assert_eq!(route.hops.len(), 5);
1248 assert_eq!(route.hops[0].pubkey, node2);
1249 assert_eq!(route.hops[0].short_channel_id, 2);
1250 assert_eq!(route.hops[0].fee_msat, 3000);
1251 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1253 assert_eq!(route.hops[1].pubkey, node3);
1254 assert_eq!(route.hops[1].short_channel_id, 4);
1255 assert_eq!(route.hops[1].fee_msat, 0);
1256 assert_eq!(route.hops[1].cltv_expiry_delta, (6 << 8) | 1);
1258 assert_eq!(route.hops[2].pubkey, node5);
1259 assert_eq!(route.hops[2].short_channel_id, 6);
1260 assert_eq!(route.hops[2].fee_msat, 0);
1261 assert_eq!(route.hops[2].cltv_expiry_delta, (11 << 8) | 1);
1263 assert_eq!(route.hops[3].pubkey, node4);
1264 assert_eq!(route.hops[3].short_channel_id, 11);
1265 assert_eq!(route.hops[3].fee_msat, 1000);
1266 assert_eq!(route.hops[3].cltv_expiry_delta, (8 << 8) | 1);
1268 assert_eq!(route.hops[4].pubkey, node7);
1269 assert_eq!(route.hops[4].short_channel_id, 8);
1270 assert_eq!(route.hops[4].fee_msat, 2000);
1271 assert_eq!(route.hops[4].cltv_expiry_delta, 42);