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 } => {
353 let mut network = self.network_map.write().unwrap();
354 if let Some(chan) = network.channels.remove(short_channel_id) {
355 Self::remove_channel_in_nodes(&mut network.nodes, &chan, *short_channel_id);
361 fn handle_channel_update(&self, msg: &msgs::ChannelUpdate) -> Result<bool, HandleError> {
362 let mut network = self.network_map.write().unwrap();
364 let chan_enabled = msg.contents.flags & (1 << 1) != (1 << 1);
365 let chan_was_enabled;
367 match network.channels.get_mut(&NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash)) {
368 None => return Err(HandleError{err: "Couldn't find channel for update", action: Some(ErrorAction::IgnoreError)}),
370 macro_rules! maybe_update_channel_info {
371 ( $target: expr) => {
372 if $target.last_update >= msg.contents.timestamp {
373 return Err(HandleError{err: "Update older than last processed update", action: Some(ErrorAction::IgnoreError)});
375 chan_was_enabled = $target.enabled;
376 $target.last_update = msg.contents.timestamp;
377 $target.enabled = chan_enabled;
378 $target.cltv_expiry_delta = msg.contents.cltv_expiry_delta;
379 $target.htlc_minimum_msat = msg.contents.htlc_minimum_msat;
380 $target.fee_base_msat = msg.contents.fee_base_msat;
381 $target.fee_proportional_millionths = msg.contents.fee_proportional_millionths;
385 let msg_hash = Message::from_slice(&Sha256dHash::from_data(&msg.contents.encode()[..])[..]).unwrap();
386 if msg.contents.flags & 1 == 1 {
387 dest_node_id = channel.one_to_two.src_node_id.clone();
388 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.signature, &channel.two_to_one.src_node_id);
389 maybe_update_channel_info!(channel.two_to_one);
391 dest_node_id = channel.two_to_one.src_node_id.clone();
392 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.signature, &channel.one_to_two.src_node_id);
393 maybe_update_channel_info!(channel.one_to_two);
399 let node = network.nodes.get_mut(&dest_node_id).unwrap();
400 node.lowest_inbound_channel_fee_base_msat = cmp::min(node.lowest_inbound_channel_fee_base_msat, msg.contents.fee_base_msat);
401 node.lowest_inbound_channel_fee_proportional_millionths = cmp::min(node.lowest_inbound_channel_fee_proportional_millionths, msg.contents.fee_proportional_millionths);
402 } else if chan_was_enabled {
403 let mut lowest_inbound_channel_fee_base_msat = u32::max_value();
404 let mut lowest_inbound_channel_fee_proportional_millionths = u32::max_value();
407 let node = network.nodes.get(&dest_node_id).unwrap();
409 for chan_id in node.channels.iter() {
410 let chan = network.channels.get(chan_id).unwrap();
411 if chan.one_to_two.src_node_id == dest_node_id {
412 lowest_inbound_channel_fee_base_msat = cmp::min(lowest_inbound_channel_fee_base_msat, chan.two_to_one.fee_base_msat);
413 lowest_inbound_channel_fee_proportional_millionths = cmp::min(lowest_inbound_channel_fee_proportional_millionths, chan.two_to_one.fee_proportional_millionths);
415 lowest_inbound_channel_fee_base_msat = cmp::min(lowest_inbound_channel_fee_base_msat, chan.one_to_two.fee_base_msat);
416 lowest_inbound_channel_fee_proportional_millionths = cmp::min(lowest_inbound_channel_fee_proportional_millionths, chan.one_to_two.fee_proportional_millionths);
421 //TODO: satisfy the borrow-checker without a double-map-lookup :(
422 let mut_node = network.nodes.get_mut(&dest_node_id).unwrap();
423 mut_node.lowest_inbound_channel_fee_base_msat = lowest_inbound_channel_fee_base_msat;
424 mut_node.lowest_inbound_channel_fee_proportional_millionths = lowest_inbound_channel_fee_proportional_millionths;
427 Ok(msg.contents.excess_data.is_empty())
431 #[derive(Eq, PartialEq)]
432 struct RouteGraphNode {
434 lowest_fee_to_peer_through_node: u64,
435 lowest_fee_to_node: u64,
438 impl cmp::Ord for RouteGraphNode {
439 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
440 other.lowest_fee_to_peer_through_node.cmp(&self.lowest_fee_to_peer_through_node)
441 .then_with(|| other.pubkey.serialize().cmp(&self.pubkey.serialize()))
445 impl cmp::PartialOrd for RouteGraphNode {
446 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
447 Some(self.cmp(other))
451 struct DummyDirectionalChannelInfo {
452 src_node_id: PublicKey,
453 cltv_expiry_delta: u32,
454 htlc_minimum_msat: u64,
456 fee_proportional_millionths: u32,
460 /// Creates a new router with the given node_id to be used as the source for get_route()
461 pub fn new(our_pubkey: PublicKey, chain_monitor: Arc<ChainWatchInterface>, logger: Arc<Logger>) -> Router {
462 let mut nodes = HashMap::new();
463 nodes.insert(our_pubkey.clone(), NodeInfo {
464 channels: Vec::new(),
465 lowest_inbound_channel_fee_base_msat: u32::max_value(),
466 lowest_inbound_channel_fee_proportional_millionths: u32::max_value(),
467 features: GlobalFeatures::new(),
471 addresses: Vec::new(),
474 secp_ctx: Secp256k1::verification_only(),
475 network_map: RwLock::new(NetworkMap {
476 channels: HashMap::new(),
477 our_node_id: our_pubkey,
485 /// Dumps the entire network view of this Router to the logger provided in the constructor at
487 pub fn trace_state(&self) {
488 log_trace!(self, "{}", self.network_map.read().unwrap());
491 /// Get network addresses by node id
492 pub fn get_addresses(&self, pubkey: &PublicKey) -> Option<Vec<NetAddress>> {
493 let network = self.network_map.read().unwrap();
494 network.nodes.get(pubkey).map(|n| n.addresses.clone())
497 /// Marks a node as having failed a route. This will avoid re-using the node in routes for now,
498 /// with an expotnential decay in node "badness". Note that there is deliberately no
499 /// mark_channel_bad as a node may simply lie and suggest that an upstream channel from it is
500 /// what failed the route and not the node itself. Instead, setting the blamed_upstream_node
501 /// boolean will reduce the penalty, returning the node to usability faster. If the node is
502 /// behaving correctly, it will disable the failing channel and we will use it again next time.
503 pub fn mark_node_bad(&self, _node_id: &PublicKey, _blamed_upstream_node: bool) {
507 fn remove_channel_in_nodes(nodes: &mut HashMap<PublicKey, NodeInfo>, chan: &ChannelInfo, short_channel_id: u64) {
508 macro_rules! remove_from_node {
509 ($node_id: expr) => {
510 if let Entry::Occupied(mut entry) = nodes.entry($node_id) {
511 entry.get_mut().channels.retain(|chan_id| {
512 short_channel_id != *NetworkMap::get_short_id(chan_id)
514 if entry.get().channels.is_empty() {
515 entry.remove_entry();
518 panic!("Had channel that pointed to unknown node (ie inconsistent network map)!");
522 remove_from_node!(chan.one_to_two.src_node_id);
523 remove_from_node!(chan.two_to_one.src_node_id);
526 /// Gets a route from us to the given target node.
528 /// Extra routing hops between known nodes and the target will be used if they are included in
531 /// If some channels aren't announced, it may be useful to fill in a first_hops with the
532 /// results from a local ChannelManager::list_usable_channels() call. If it is filled in, our
533 /// (this Router's) view of our local channels will be ignored, and only those in first_hops
536 /// Panics if first_hops contains channels without short_channel_ids
537 /// (ChannelManager::list_usable_channels will never include such channels).
539 /// The fees on channels from us to next-hops are ignored (as they are assumed to all be
540 /// equal), however the enabled/disabled bit on such channels as well as the htlc_minimum_msat
541 /// *is* checked as they may change based on the receiving node.
542 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> {
543 // TODO: Obviously *only* using total fee cost sucks. We should consider weighting by
544 // uptime/success in using a node in the past.
545 let network = self.network_map.read().unwrap();
547 if *target == network.our_node_id {
548 return Err(HandleError{err: "Cannot generate a route to ourselves", action: None});
551 if final_value_msat > 21_000_000 * 1_0000_0000 * 1000 {
552 return Err(HandleError{err: "Cannot generate a route of more value than all existing satoshis", action: None});
555 // We do a dest-to-source Dijkstra's sorting by each node's distance from the destination
556 // plus the minimum per-HTLC fee to get from it to another node (aka "shitty A*").
557 // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
558 // to use as the A* heuristic beyond just the cost to get one node further than the current
561 let dummy_directional_info = DummyDirectionalChannelInfo { // used for first_hops routes
562 src_node_id: network.our_node_id.clone(),
563 cltv_expiry_delta: 0,
564 htlc_minimum_msat: 0,
566 fee_proportional_millionths: 0,
569 let mut targets = BinaryHeap::new(); //TODO: Do we care about switching to eg Fibbonaci heap?
570 let mut dist = HashMap::with_capacity(network.nodes.len());
572 let mut first_hop_targets = HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
573 if let Some(hops) = first_hops {
575 let short_channel_id = chan.short_channel_id.expect("first_hops should be filled in with usable channels, not pending ones");
576 if chan.remote_network_id == *target {
578 hops: vec![RouteHop {
579 pubkey: chan.remote_network_id,
581 fee_msat: final_value_msat,
582 cltv_expiry_delta: final_cltv,
586 first_hop_targets.insert(chan.remote_network_id, short_channel_id);
588 if first_hop_targets.is_empty() {
589 return Err(HandleError{err: "Cannot route when there are no outbound routes away from us", action: None});
593 macro_rules! add_entry {
594 // Adds entry which goes from the node pointed to by $directional_info to
595 // $dest_node_id over the channel with id $chan_id with fees described in
596 // $directional_info.
597 ( $chan_id: expr, $dest_node_id: expr, $directional_info: expr, $starting_fee_msat: expr ) => {
598 //TODO: Explore simply adding fee to hit htlc_minimum_msat
599 if $starting_fee_msat as u64 + final_value_msat > $directional_info.htlc_minimum_msat {
600 let proportional_fee_millions = ($starting_fee_msat + final_value_msat).checked_mul($directional_info.fee_proportional_millionths as u64);
601 if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
602 ($directional_info.fee_base_msat as u64).checked_add(part / 1000000) })
604 let mut total_fee = $starting_fee_msat as u64;
605 let hm_entry = dist.entry(&$directional_info.src_node_id);
606 let old_entry = hm_entry.or_insert_with(|| {
607 let node = network.nodes.get(&$directional_info.src_node_id).unwrap();
609 node.lowest_inbound_channel_fee_base_msat,
610 node.lowest_inbound_channel_fee_proportional_millionths,
612 pubkey: $dest_node_id.clone(),
615 cltv_expiry_delta: 0,
618 if $directional_info.src_node_id != network.our_node_id {
619 // Ignore new_fee for channel-from-us as we assume all channels-from-us
620 // will have the same effective-fee
621 total_fee += new_fee;
622 if let Some(fee_inc) = final_value_msat.checked_add(total_fee).and_then(|inc| { (old_entry.2 as u64).checked_mul(inc) }) {
623 total_fee += fee_inc / 1000000 + (old_entry.1 as u64);
625 // max_value means we'll always fail the old_entry.0 > total_fee check
626 total_fee = u64::max_value();
629 let new_graph_node = RouteGraphNode {
630 pubkey: $directional_info.src_node_id,
631 lowest_fee_to_peer_through_node: total_fee,
632 lowest_fee_to_node: $starting_fee_msat as u64 + new_fee,
634 if old_entry.0 > total_fee {
635 targets.push(new_graph_node);
636 old_entry.0 = total_fee;
637 old_entry.3 = RouteHop {
638 pubkey: $dest_node_id.clone(),
639 short_channel_id: $chan_id.clone(),
640 fee_msat: new_fee, // This field is ignored on the last-hop anyway
641 cltv_expiry_delta: $directional_info.cltv_expiry_delta as u32,
649 macro_rules! add_entries_to_cheapest_to_target_node {
650 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr ) => {
651 if first_hops.is_some() {
652 if let Some(first_hop) = first_hop_targets.get(&$node_id) {
653 add_entry!(first_hop, $node_id, dummy_directional_info, $fee_to_target_msat);
657 for chan_id in $node.channels.iter() {
658 let chan = network.channels.get(chan_id).unwrap();
659 if chan.one_to_two.src_node_id == *$node_id {
660 // ie $node is one, ie next hop in A* is two, via the two_to_one channel
661 if first_hops.is_none() || chan.two_to_one.src_node_id != network.our_node_id {
662 if chan.two_to_one.enabled {
663 add_entry!(chan_id, chan.one_to_two.src_node_id, chan.two_to_one, $fee_to_target_msat);
667 if first_hops.is_none() || chan.one_to_two.src_node_id != network.our_node_id {
668 if chan.one_to_two.enabled {
669 add_entry!(chan_id, chan.two_to_one.src_node_id, chan.one_to_two, $fee_to_target_msat);
677 match network.nodes.get(target) {
680 add_entries_to_cheapest_to_target_node!(node, target, 0);
684 for hop in last_hops.iter() {
685 if first_hops.is_none() || hop.src_node_id != network.our_node_id { // first_hop overrules last_hops
686 if network.nodes.get(&hop.src_node_id).is_some() {
687 if first_hops.is_some() {
688 if let Some(first_hop) = first_hop_targets.get(&hop.src_node_id) {
689 add_entry!(first_hop, hop.src_node_id, dummy_directional_info, 0);
692 add_entry!(hop.short_channel_id, target, hop, 0);
697 while let Some(RouteGraphNode { pubkey, lowest_fee_to_node, .. }) = targets.pop() {
698 if pubkey == network.our_node_id {
699 let mut res = vec!(dist.remove(&network.our_node_id).unwrap().3);
700 while res.last().unwrap().pubkey != *target {
701 let new_entry = match dist.remove(&res.last().unwrap().pubkey) {
703 None => return Err(HandleError{err: "Failed to find a non-fee-overflowing path to the given destination", action: None}),
705 res.last_mut().unwrap().fee_msat = new_entry.fee_msat;
706 res.last_mut().unwrap().cltv_expiry_delta = new_entry.cltv_expiry_delta;
709 res.last_mut().unwrap().fee_msat = final_value_msat;
710 res.last_mut().unwrap().cltv_expiry_delta = final_cltv;
711 let route = Route { hops: res };
712 log_trace!(self, "Got route: {}", log_route!(route));
716 match network.nodes.get(&pubkey) {
719 add_entries_to_cheapest_to_target_node!(node, &pubkey, lowest_fee_to_node);
724 Err(HandleError{err: "Failed to find a path to the given destination", action: None})
730 use chain::chaininterface;
731 use ln::channelmanager;
732 use ln::router::{Router,NodeInfo,NetworkMap,ChannelInfo,DirectionalChannelInfo,RouteHint};
733 use ln::msgs::GlobalFeatures;
734 use util::test_utils;
735 use util::logger::Logger;
737 use bitcoin::util::hash::Sha256dHash;
738 use bitcoin::network::constants::Network;
742 use secp256k1::key::{PublicKey,SecretKey};
743 use secp256k1::Secp256k1;
749 let secp_ctx = Secp256k1::new();
750 let our_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap());
751 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
752 let chain_monitor = Arc::new(chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet, Arc::clone(&logger)));
753 let router = Router::new(our_id, chain_monitor, Arc::clone(&logger));
755 // Build network from our_id to node8:
757 // -1(1)2- node1 -1(3)2-
759 // our_id -1(12)2- node8 -1(13)2--- node3
761 // -1(2)2- node2 -1(4)2-
764 // chan1 1-to-2: disabled
765 // chan1 2-to-1: enabled, 0 fee
767 // chan2 1-to-2: enabled, ignored fee
768 // chan2 2-to-1: enabled, 0 fee
770 // chan3 1-to-2: enabled, 0 fee
771 // chan3 2-to-1: enabled, 100 msat fee
773 // chan4 1-to-2: enabled, 100% fee
774 // chan4 2-to-1: enabled, 0 fee
776 // chan12 1-to-2: enabled, ignored fee
777 // chan12 2-to-1: enabled, 0 fee
779 // chan13 1-to-2: enabled, 200% fee
780 // chan13 2-to-1: enabled, 0 fee
783 // -1(5)2- node4 -1(8)2--
787 // node3--1(6)2- node5 -1(9)2--- node7 (not in global route map)
789 // -1(7)2- node6 -1(10)2-
791 // chan5 1-to-2: enabled, 100 msat fee
792 // chan5 2-to-1: enabled, 0 fee
794 // chan6 1-to-2: enabled, 0 fee
795 // chan6 2-to-1: enabled, 0 fee
797 // chan7 1-to-2: enabled, 100% fee
798 // chan7 2-to-1: enabled, 0 fee
800 // chan8 1-to-2: enabled, variable fee (0 then 1000 msat)
801 // chan8 2-to-1: enabled, 0 fee
803 // chan9 1-to-2: enabled, 1001 msat fee
804 // chan9 2-to-1: enabled, 0 fee
806 // chan10 1-to-2: enabled, 0 fee
807 // chan10 2-to-1: enabled, 0 fee
809 // chan11 1-to-2: enabled, 0 fee
810 // chan11 2-to-1: enabled, 0 fee
812 let node1 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap()[..]).unwrap());
813 let node2 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0303030303030303030303030303030303030303030303030303030303030303").unwrap()[..]).unwrap());
814 let node3 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0404040404040404040404040404040404040404040404040404040404040404").unwrap()[..]).unwrap());
815 let node4 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0505050505050505050505050505050505050505050505050505050505050505").unwrap()[..]).unwrap());
816 let node5 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0606060606060606060606060606060606060606060606060606060606060606").unwrap()[..]).unwrap());
817 let node6 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0707070707070707070707070707070707070707070707070707070707070707").unwrap()[..]).unwrap());
818 let node7 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0808080808080808080808080808080808080808080808080808080808080808").unwrap()[..]).unwrap());
819 let node8 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0909090909090909090909090909090909090909090909090909090909090909").unwrap()[..]).unwrap());
821 let zero_hash = Sha256dHash::from_data(&[0; 32]);
824 let mut network = router.network_map.write().unwrap();
826 network.nodes.insert(node1.clone(), NodeInfo {
827 channels: vec!(NetworkMap::get_key(1, zero_hash.clone()), NetworkMap::get_key(3, zero_hash.clone())),
828 lowest_inbound_channel_fee_base_msat: 100,
829 lowest_inbound_channel_fee_proportional_millionths: 0,
830 features: GlobalFeatures::new(),
834 addresses: Vec::new(),
836 network.channels.insert(NetworkMap::get_key(1, zero_hash.clone()), ChannelInfo {
837 features: GlobalFeatures::new(),
838 one_to_two: DirectionalChannelInfo {
839 src_node_id: our_id.clone(),
842 cltv_expiry_delta: u16::max_value(), // This value should be ignored
843 htlc_minimum_msat: 0,
844 fee_base_msat: u32::max_value(), // This value should be ignored
845 fee_proportional_millionths: u32::max_value(), // This value should be ignored
846 }, two_to_one: DirectionalChannelInfo {
847 src_node_id: node1.clone(),
850 cltv_expiry_delta: 0,
851 htlc_minimum_msat: 0,
853 fee_proportional_millionths: 0,
856 network.nodes.insert(node2.clone(), NodeInfo {
857 channels: vec!(NetworkMap::get_key(2, zero_hash.clone()), NetworkMap::get_key(4, zero_hash.clone())),
858 lowest_inbound_channel_fee_base_msat: 0,
859 lowest_inbound_channel_fee_proportional_millionths: 0,
860 features: GlobalFeatures::new(),
864 addresses: Vec::new(),
866 network.channels.insert(NetworkMap::get_key(2, zero_hash.clone()), ChannelInfo {
867 features: GlobalFeatures::new(),
868 one_to_two: DirectionalChannelInfo {
869 src_node_id: our_id.clone(),
872 cltv_expiry_delta: u16::max_value(), // This value should be ignored
873 htlc_minimum_msat: 0,
874 fee_base_msat: u32::max_value(), // This value should be ignored
875 fee_proportional_millionths: u32::max_value(), // This value should be ignored
876 }, two_to_one: DirectionalChannelInfo {
877 src_node_id: node2.clone(),
880 cltv_expiry_delta: 0,
881 htlc_minimum_msat: 0,
883 fee_proportional_millionths: 0,
886 network.nodes.insert(node8.clone(), NodeInfo {
887 channels: vec!(NetworkMap::get_key(12, zero_hash.clone()), NetworkMap::get_key(13, zero_hash.clone())),
888 lowest_inbound_channel_fee_base_msat: 0,
889 lowest_inbound_channel_fee_proportional_millionths: 0,
890 features: GlobalFeatures::new(),
894 addresses: Vec::new(),
896 network.channels.insert(NetworkMap::get_key(12, zero_hash.clone()), ChannelInfo {
897 features: GlobalFeatures::new(),
898 one_to_two: DirectionalChannelInfo {
899 src_node_id: our_id.clone(),
902 cltv_expiry_delta: u16::max_value(), // This value should be ignored
903 htlc_minimum_msat: 0,
904 fee_base_msat: u32::max_value(), // This value should be ignored
905 fee_proportional_millionths: u32::max_value(), // This value should be ignored
906 }, two_to_one: DirectionalChannelInfo {
907 src_node_id: node8.clone(),
910 cltv_expiry_delta: 0,
911 htlc_minimum_msat: 0,
913 fee_proportional_millionths: 0,
916 network.nodes.insert(node3.clone(), NodeInfo {
918 NetworkMap::get_key(3, zero_hash.clone()),
919 NetworkMap::get_key(4, zero_hash.clone()),
920 NetworkMap::get_key(13, zero_hash.clone()),
921 NetworkMap::get_key(5, zero_hash.clone()),
922 NetworkMap::get_key(6, zero_hash.clone()),
923 NetworkMap::get_key(7, zero_hash.clone())),
924 lowest_inbound_channel_fee_base_msat: 0,
925 lowest_inbound_channel_fee_proportional_millionths: 0,
926 features: GlobalFeatures::new(),
930 addresses: Vec::new(),
932 network.channels.insert(NetworkMap::get_key(3, zero_hash.clone()), ChannelInfo {
933 features: GlobalFeatures::new(),
934 one_to_two: DirectionalChannelInfo {
935 src_node_id: node1.clone(),
938 cltv_expiry_delta: (3 << 8) | 1,
939 htlc_minimum_msat: 0,
941 fee_proportional_millionths: 0,
942 }, two_to_one: DirectionalChannelInfo {
943 src_node_id: node3.clone(),
946 cltv_expiry_delta: (3 << 8) | 2,
947 htlc_minimum_msat: 0,
949 fee_proportional_millionths: 0,
952 network.channels.insert(NetworkMap::get_key(4, zero_hash.clone()), ChannelInfo {
953 features: GlobalFeatures::new(),
954 one_to_two: DirectionalChannelInfo {
955 src_node_id: node2.clone(),
958 cltv_expiry_delta: (4 << 8) | 1,
959 htlc_minimum_msat: 0,
961 fee_proportional_millionths: 1000000,
962 }, two_to_one: DirectionalChannelInfo {
963 src_node_id: node3.clone(),
966 cltv_expiry_delta: (4 << 8) | 2,
967 htlc_minimum_msat: 0,
969 fee_proportional_millionths: 0,
972 network.channels.insert(NetworkMap::get_key(13, zero_hash.clone()), ChannelInfo {
973 features: GlobalFeatures::new(),
974 one_to_two: DirectionalChannelInfo {
975 src_node_id: node8.clone(),
978 cltv_expiry_delta: (13 << 8) | 1,
979 htlc_minimum_msat: 0,
981 fee_proportional_millionths: 2000000,
982 }, two_to_one: DirectionalChannelInfo {
983 src_node_id: node3.clone(),
986 cltv_expiry_delta: (13 << 8) | 2,
987 htlc_minimum_msat: 0,
989 fee_proportional_millionths: 0,
992 network.nodes.insert(node4.clone(), NodeInfo {
993 channels: vec!(NetworkMap::get_key(5, zero_hash.clone()), NetworkMap::get_key(11, zero_hash.clone())),
994 lowest_inbound_channel_fee_base_msat: 0,
995 lowest_inbound_channel_fee_proportional_millionths: 0,
996 features: GlobalFeatures::new(),
1000 addresses: Vec::new(),
1002 network.channels.insert(NetworkMap::get_key(5, zero_hash.clone()), ChannelInfo {
1003 features: GlobalFeatures::new(),
1004 one_to_two: DirectionalChannelInfo {
1005 src_node_id: node3.clone(),
1008 cltv_expiry_delta: (5 << 8) | 1,
1009 htlc_minimum_msat: 0,
1011 fee_proportional_millionths: 0,
1012 }, two_to_one: DirectionalChannelInfo {
1013 src_node_id: node4.clone(),
1016 cltv_expiry_delta: (5 << 8) | 2,
1017 htlc_minimum_msat: 0,
1019 fee_proportional_millionths: 0,
1022 network.nodes.insert(node5.clone(), NodeInfo {
1023 channels: vec!(NetworkMap::get_key(6, zero_hash.clone()), NetworkMap::get_key(11, zero_hash.clone())),
1024 lowest_inbound_channel_fee_base_msat: 0,
1025 lowest_inbound_channel_fee_proportional_millionths: 0,
1026 features: GlobalFeatures::new(),
1030 addresses: Vec::new(),
1032 network.channels.insert(NetworkMap::get_key(6, zero_hash.clone()), ChannelInfo {
1033 features: GlobalFeatures::new(),
1034 one_to_two: DirectionalChannelInfo {
1035 src_node_id: node3.clone(),
1038 cltv_expiry_delta: (6 << 8) | 1,
1039 htlc_minimum_msat: 0,
1041 fee_proportional_millionths: 0,
1042 }, two_to_one: DirectionalChannelInfo {
1043 src_node_id: node5.clone(),
1046 cltv_expiry_delta: (6 << 8) | 2,
1047 htlc_minimum_msat: 0,
1049 fee_proportional_millionths: 0,
1052 network.channels.insert(NetworkMap::get_key(11, zero_hash.clone()), ChannelInfo {
1053 features: GlobalFeatures::new(),
1054 one_to_two: DirectionalChannelInfo {
1055 src_node_id: node5.clone(),
1058 cltv_expiry_delta: (11 << 8) | 1,
1059 htlc_minimum_msat: 0,
1061 fee_proportional_millionths: 0,
1062 }, two_to_one: DirectionalChannelInfo {
1063 src_node_id: node4.clone(),
1066 cltv_expiry_delta: (11 << 8) | 2,
1067 htlc_minimum_msat: 0,
1069 fee_proportional_millionths: 0,
1072 network.nodes.insert(node6.clone(), NodeInfo {
1073 channels: vec!(NetworkMap::get_key(7, zero_hash.clone())),
1074 lowest_inbound_channel_fee_base_msat: 0,
1075 lowest_inbound_channel_fee_proportional_millionths: 0,
1076 features: GlobalFeatures::new(),
1080 addresses: Vec::new(),
1082 network.channels.insert(NetworkMap::get_key(7, zero_hash.clone()), ChannelInfo {
1083 features: GlobalFeatures::new(),
1084 one_to_two: DirectionalChannelInfo {
1085 src_node_id: node3.clone(),
1088 cltv_expiry_delta: (7 << 8) | 1,
1089 htlc_minimum_msat: 0,
1091 fee_proportional_millionths: 1000000,
1092 }, two_to_one: DirectionalChannelInfo {
1093 src_node_id: node6.clone(),
1096 cltv_expiry_delta: (7 << 8) | 2,
1097 htlc_minimum_msat: 0,
1099 fee_proportional_millionths: 0,
1104 { // Simple route to 3 via 2
1105 let route = router.get_route(&node3, None, &Vec::new(), 100, 42).unwrap();
1106 assert_eq!(route.hops.len(), 2);
1108 assert_eq!(route.hops[0].pubkey, node2);
1109 assert_eq!(route.hops[0].short_channel_id, 2);
1110 assert_eq!(route.hops[0].fee_msat, 100);
1111 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1113 assert_eq!(route.hops[1].pubkey, node3);
1114 assert_eq!(route.hops[1].short_channel_id, 4);
1115 assert_eq!(route.hops[1].fee_msat, 100);
1116 assert_eq!(route.hops[1].cltv_expiry_delta, 42);
1119 { // Route to 1 via 2 and 3 because our channel to 1 is disabled
1120 let route = router.get_route(&node1, None, &Vec::new(), 100, 42).unwrap();
1121 assert_eq!(route.hops.len(), 3);
1123 assert_eq!(route.hops[0].pubkey, node2);
1124 assert_eq!(route.hops[0].short_channel_id, 2);
1125 assert_eq!(route.hops[0].fee_msat, 200);
1126 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1128 assert_eq!(route.hops[1].pubkey, node3);
1129 assert_eq!(route.hops[1].short_channel_id, 4);
1130 assert_eq!(route.hops[1].fee_msat, 100);
1131 assert_eq!(route.hops[1].cltv_expiry_delta, (3 << 8) | 2);
1133 assert_eq!(route.hops[2].pubkey, node1);
1134 assert_eq!(route.hops[2].short_channel_id, 3);
1135 assert_eq!(route.hops[2].fee_msat, 100);
1136 assert_eq!(route.hops[2].cltv_expiry_delta, 42);
1139 { // If we specify a channel to node8, that overrides our local channel view and that gets used
1140 let our_chans = vec![channelmanager::ChannelDetails {
1141 channel_id: [0; 32],
1142 short_channel_id: Some(42),
1143 remote_network_id: node8.clone(),
1144 channel_value_satoshis: 0,
1147 let route = router.get_route(&node3, Some(&our_chans), &Vec::new(), 100, 42).unwrap();
1148 assert_eq!(route.hops.len(), 2);
1150 assert_eq!(route.hops[0].pubkey, node8);
1151 assert_eq!(route.hops[0].short_channel_id, 42);
1152 assert_eq!(route.hops[0].fee_msat, 200);
1153 assert_eq!(route.hops[0].cltv_expiry_delta, (13 << 8) | 1);
1155 assert_eq!(route.hops[1].pubkey, node3);
1156 assert_eq!(route.hops[1].short_channel_id, 13);
1157 assert_eq!(route.hops[1].fee_msat, 100);
1158 assert_eq!(route.hops[1].cltv_expiry_delta, 42);
1161 let mut last_hops = vec!(RouteHint {
1162 src_node_id: node4.clone(),
1163 short_channel_id: 8,
1165 fee_proportional_millionths: 0,
1166 cltv_expiry_delta: (8 << 8) | 1,
1167 htlc_minimum_msat: 0,
1169 src_node_id: node5.clone(),
1170 short_channel_id: 9,
1171 fee_base_msat: 1001,
1172 fee_proportional_millionths: 0,
1173 cltv_expiry_delta: (9 << 8) | 1,
1174 htlc_minimum_msat: 0,
1176 src_node_id: node6.clone(),
1177 short_channel_id: 10,
1179 fee_proportional_millionths: 0,
1180 cltv_expiry_delta: (10 << 8) | 1,
1181 htlc_minimum_msat: 0,
1184 { // Simple test across 2, 3, 5, and 4 via a last_hop channel
1185 let route = router.get_route(&node7, None, &last_hops, 100, 42).unwrap();
1186 assert_eq!(route.hops.len(), 5);
1188 assert_eq!(route.hops[0].pubkey, node2);
1189 assert_eq!(route.hops[0].short_channel_id, 2);
1190 assert_eq!(route.hops[0].fee_msat, 100);
1191 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1193 assert_eq!(route.hops[1].pubkey, node3);
1194 assert_eq!(route.hops[1].short_channel_id, 4);
1195 assert_eq!(route.hops[1].fee_msat, 0);
1196 assert_eq!(route.hops[1].cltv_expiry_delta, (6 << 8) | 1);
1198 assert_eq!(route.hops[2].pubkey, node5);
1199 assert_eq!(route.hops[2].short_channel_id, 6);
1200 assert_eq!(route.hops[2].fee_msat, 0);
1201 assert_eq!(route.hops[2].cltv_expiry_delta, (11 << 8) | 1);
1203 assert_eq!(route.hops[3].pubkey, node4);
1204 assert_eq!(route.hops[3].short_channel_id, 11);
1205 assert_eq!(route.hops[3].fee_msat, 0);
1206 assert_eq!(route.hops[3].cltv_expiry_delta, (8 << 8) | 1);
1208 assert_eq!(route.hops[4].pubkey, node7);
1209 assert_eq!(route.hops[4].short_channel_id, 8);
1210 assert_eq!(route.hops[4].fee_msat, 100);
1211 assert_eq!(route.hops[4].cltv_expiry_delta, 42);
1214 { // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
1215 let our_chans = vec![channelmanager::ChannelDetails {
1216 channel_id: [0; 32],
1217 short_channel_id: Some(42),
1218 remote_network_id: node4.clone(),
1219 channel_value_satoshis: 0,
1222 let route = router.get_route(&node7, Some(&our_chans), &last_hops, 100, 42).unwrap();
1223 assert_eq!(route.hops.len(), 2);
1225 assert_eq!(route.hops[0].pubkey, node4);
1226 assert_eq!(route.hops[0].short_channel_id, 42);
1227 assert_eq!(route.hops[0].fee_msat, 0);
1228 assert_eq!(route.hops[0].cltv_expiry_delta, (8 << 8) | 1);
1230 assert_eq!(route.hops[1].pubkey, node7);
1231 assert_eq!(route.hops[1].short_channel_id, 8);
1232 assert_eq!(route.hops[1].fee_msat, 100);
1233 assert_eq!(route.hops[1].cltv_expiry_delta, 42);
1236 last_hops[0].fee_base_msat = 1000;
1238 { // Revert to via 6 as the fee on 8 goes up
1239 let route = router.get_route(&node7, None, &last_hops, 100, 42).unwrap();
1240 assert_eq!(route.hops.len(), 4);
1242 assert_eq!(route.hops[0].pubkey, node2);
1243 assert_eq!(route.hops[0].short_channel_id, 2);
1244 assert_eq!(route.hops[0].fee_msat, 200); // fee increased as its % of value transferred across node
1245 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1247 assert_eq!(route.hops[1].pubkey, node3);
1248 assert_eq!(route.hops[1].short_channel_id, 4);
1249 assert_eq!(route.hops[1].fee_msat, 100);
1250 assert_eq!(route.hops[1].cltv_expiry_delta, (7 << 8) | 1);
1252 assert_eq!(route.hops[2].pubkey, node6);
1253 assert_eq!(route.hops[2].short_channel_id, 7);
1254 assert_eq!(route.hops[2].fee_msat, 0);
1255 assert_eq!(route.hops[2].cltv_expiry_delta, (10 << 8) | 1);
1257 assert_eq!(route.hops[3].pubkey, node7);
1258 assert_eq!(route.hops[3].short_channel_id, 10);
1259 assert_eq!(route.hops[3].fee_msat, 100);
1260 assert_eq!(route.hops[3].cltv_expiry_delta, 42);
1263 { // ...but still use 8 for larger payments as 6 has a variable feerate
1264 let route = router.get_route(&node7, None, &last_hops, 2000, 42).unwrap();
1265 assert_eq!(route.hops.len(), 5);
1267 assert_eq!(route.hops[0].pubkey, node2);
1268 assert_eq!(route.hops[0].short_channel_id, 2);
1269 assert_eq!(route.hops[0].fee_msat, 3000);
1270 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1272 assert_eq!(route.hops[1].pubkey, node3);
1273 assert_eq!(route.hops[1].short_channel_id, 4);
1274 assert_eq!(route.hops[1].fee_msat, 0);
1275 assert_eq!(route.hops[1].cltv_expiry_delta, (6 << 8) | 1);
1277 assert_eq!(route.hops[2].pubkey, node5);
1278 assert_eq!(route.hops[2].short_channel_id, 6);
1279 assert_eq!(route.hops[2].fee_msat, 0);
1280 assert_eq!(route.hops[2].cltv_expiry_delta, (11 << 8) | 1);
1282 assert_eq!(route.hops[3].pubkey, node4);
1283 assert_eq!(route.hops[3].short_channel_id, 11);
1284 assert_eq!(route.hops[3].fee_msat, 1000);
1285 assert_eq!(route.hops[3].cltv_expiry_delta, (8 << 8) | 1);
1287 assert_eq!(route.hops[4].pubkey, node7);
1288 assert_eq!(route.hops[4].short_channel_id, 8);
1289 assert_eq!(route.hops[4].fee_msat, 2000);
1290 assert_eq!(route.hops[4].cltv_expiry_delta, 42);