1 use secp256k1::key::PublicKey;
2 use secp256k1::{Secp256k1,Message};
5 use bitcoin::util::hash::Sha256dHash;
7 use chain::chaininterface::ChainWatchInterface;
8 use ln::channelmanager;
9 use ln::msgs::{ErrorAction,HandleError,RoutingMessageHandler,MsgEncodable,NetAddress,GlobalFeatures};
11 use util::logger::Logger;
14 use std::sync::{RwLock,Arc};
15 use std::collections::{HashMap,BinaryHeap};
16 use std::collections::hash_map::Entry;
22 pub pubkey: PublicKey,
23 /// The channel that should be used from the previous hop to reach this node.
24 pub short_channel_id: u64,
25 /// The fee taken on this hop. For the last hop, this should be the full value of the payment.
27 /// The CLTV delta added for this hop. For the last hop, this should be the full CLTV value
28 /// expected at the destination, in excess of the current block height.
29 pub cltv_expiry_delta: u32,
32 /// A route from us through the network to a destination
35 /// The list of hops, NOT INCLUDING our own, where the last hop is the destination. Thus, this
36 /// must always be at least length one. By protocol rules, this may not currently exceed 20 in
38 pub hops: Vec<RouteHop>,
41 struct DirectionalChannelInfo {
42 src_node_id: PublicKey,
45 cltv_expiry_delta: u16,
46 htlc_minimum_msat: u64,
48 fee_proportional_millionths: u32,
51 impl std::fmt::Display for DirectionalChannelInfo {
52 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
53 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)?;
59 features: GlobalFeatures,
60 one_to_two: DirectionalChannelInfo,
61 two_to_one: DirectionalChannelInfo,
64 impl std::fmt::Display for ChannelInfo {
65 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
66 write!(f, "features: {}, one_to_two: {}, two_to_one: {}", log_bytes!(self.features.encode()), self.one_to_two, self.two_to_one)?;
72 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
73 channels: Vec<(u64, Sha256dHash)>,
74 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
77 lowest_inbound_channel_fee_base_msat: u32,
78 lowest_inbound_channel_fee_proportional_millionths: u32,
80 features: GlobalFeatures,
84 addresses: Vec<NetAddress>,
87 impl std::fmt::Display for NodeInfo {
88 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
89 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[..])?;
95 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
96 channels: HashMap<(u64, Sha256dHash), ChannelInfo>,
97 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
98 channels: HashMap<u64, ChannelInfo>,
100 our_node_id: PublicKey,
101 nodes: HashMap<PublicKey, NodeInfo>,
104 impl std::fmt::Display for NetworkMap {
105 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
106 write!(f, "Node id {} network map\n[Channels]\n", log_pubkey!(self.our_node_id))?;
107 for (key, val) in self.channels.iter() {
108 write!(f, " {}: {}\n", key, val)?;
110 write!(f, "[Nodes]\n")?;
111 for (key, val) in self.nodes.iter() {
112 write!(f, " {}: {}\n", log_pubkey!(key), val)?;
119 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
121 fn get_key(short_channel_id: u64, chain_hash: Sha256dHash) -> (u64, Sha256dHash) {
122 (short_channel_id, chain_hash)
125 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
127 fn get_key(short_channel_id: u64, _: Sha256dHash) -> u64 {
131 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
133 fn get_short_id(id: &(u64, Sha256dHash)) -> &u64 {
137 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
139 fn get_short_id(id: &u64) -> &u64 {
144 /// A channel descriptor which provides a last-hop route to get_route
145 pub struct RouteHint {
146 pub src_node_id: PublicKey,
147 pub short_channel_id: u64,
148 pub fee_base_msat: u32,
149 pub fee_proportional_millionths: u32,
150 pub cltv_expiry_delta: u16,
151 pub htlc_minimum_msat: u64,
154 /// Tracks a view of the network, receiving updates from peers and generating Routes to
155 /// payment destinations.
157 secp_ctx: Secp256k1<secp256k1::VerifyOnly>,
158 network_map: RwLock<NetworkMap>,
159 chain_monitor: Arc<ChainWatchInterface>,
163 macro_rules! secp_verify_sig {
164 ( $secp_ctx: expr, $msg: expr, $sig: expr, $pubkey: expr ) => {
165 match $secp_ctx.verify($msg, $sig, $pubkey) {
167 Err(_) => return Err(HandleError{err: "Invalid signature from remote node", action: None}),
172 impl RoutingMessageHandler for Router {
173 fn handle_node_announcement(&self, msg: &msgs::NodeAnnouncement) -> Result<bool, HandleError> {
174 let msg_hash = Message::from_slice(&Sha256dHash::from_data(&msg.contents.encode()[..])[..]).unwrap();
175 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.signature, &msg.contents.node_id);
177 if msg.contents.features.requires_unknown_bits() {
178 panic!("Unknown-required-features NodeAnnouncements should never deserialize!");
181 let mut network = self.network_map.write().unwrap();
182 match network.nodes.get_mut(&msg.contents.node_id) {
183 None => Err(HandleError{err: "No existing channels for node_announcement", action: Some(ErrorAction::IgnoreError)}),
185 if node.last_update >= msg.contents.timestamp {
186 return Err(HandleError{err: "Update older than last processed update", action: Some(ErrorAction::IgnoreError)});
189 node.features = msg.contents.features.clone();
190 node.last_update = msg.contents.timestamp;
191 node.rgb = msg.contents.rgb;
192 node.alias = msg.contents.alias;
193 node.addresses = msg.contents.addresses.clone();
194 Ok(msg.contents.excess_data.is_empty() && msg.contents.excess_address_data.is_empty() && !msg.contents.features.supports_unknown_bits())
199 fn handle_channel_announcement(&self, msg: &msgs::ChannelAnnouncement) -> Result<bool, HandleError> {
200 let msg_hash = Message::from_slice(&Sha256dHash::from_data(&msg.contents.encode()[..])[..]).unwrap();
201 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.node_signature_1, &msg.contents.node_id_1);
202 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.node_signature_2, &msg.contents.node_id_2);
203 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.bitcoin_signature_1, &msg.contents.bitcoin_key_1);
204 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.bitcoin_signature_2, &msg.contents.bitcoin_key_2);
206 //TODO: Call blockchain thing to ask if the short_channel_id is valid
207 //TODO: Only allow bitcoin chain_hash
209 if msg.contents.features.requires_unknown_bits() {
210 panic!("Unknown-required-features ChannelAnnouncements should never deserialize!");
213 let mut network = self.network_map.write().unwrap();
215 match network.channels.entry(NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash)) {
216 Entry::Occupied(_) => {
217 //TODO: because asking the blockchain if short_channel_id is valid is only optional
218 //in the blockchain API, we need to handle it smartly here, though its unclear
220 return Err(HandleError{err: "Already have knowledge of channel", action: Some(ErrorAction::IgnoreError)})
222 Entry::Vacant(entry) => {
223 entry.insert(ChannelInfo {
224 features: msg.contents.features.clone(),
225 one_to_two: DirectionalChannelInfo {
226 src_node_id: msg.contents.node_id_1.clone(),
229 cltv_expiry_delta: u16::max_value(),
230 htlc_minimum_msat: u64::max_value(),
231 fee_base_msat: u32::max_value(),
232 fee_proportional_millionths: u32::max_value(),
234 two_to_one: DirectionalChannelInfo {
235 src_node_id: msg.contents.node_id_2.clone(),
238 cltv_expiry_delta: u16::max_value(),
239 htlc_minimum_msat: u64::max_value(),
240 fee_base_msat: u32::max_value(),
241 fee_proportional_millionths: u32::max_value(),
247 macro_rules! add_channel_to_node {
248 ( $node_id: expr ) => {
249 match network.nodes.entry($node_id) {
250 Entry::Occupied(node_entry) => {
251 node_entry.into_mut().channels.push(NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash));
253 Entry::Vacant(node_entry) => {
254 node_entry.insert(NodeInfo {
255 channels: vec!(NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash)),
256 lowest_inbound_channel_fee_base_msat: u32::max_value(),
257 lowest_inbound_channel_fee_proportional_millionths: u32::max_value(),
258 features: GlobalFeatures::new(),
262 addresses: Vec::new(),
269 add_channel_to_node!(msg.contents.node_id_1);
270 add_channel_to_node!(msg.contents.node_id_2);
272 Ok(msg.contents.excess_data.is_empty() && !msg.contents.features.supports_unknown_bits())
275 fn handle_htlc_fail_channel_update(&self, update: &msgs::HTLCFailChannelUpdate) {
277 &msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg } => {
278 let _ = self.handle_channel_update(msg);
280 &msgs::HTLCFailChannelUpdate::ChannelClosed { ref short_channel_id } => {
281 let mut network = self.network_map.write().unwrap();
282 if let Some(chan) = network.channels.remove(short_channel_id) {
283 network.nodes.get_mut(&chan.one_to_two.src_node_id).unwrap().channels.retain(|chan_id| {
284 chan_id != NetworkMap::get_short_id(chan_id)
286 network.nodes.get_mut(&chan.two_to_one.src_node_id).unwrap().channels.retain(|chan_id| {
287 chan_id != NetworkMap::get_short_id(chan_id)
294 fn handle_channel_update(&self, msg: &msgs::ChannelUpdate) -> Result<bool, HandleError> {
295 let mut network = self.network_map.write().unwrap();
297 let chan_enabled = msg.contents.flags & (1 << 1) != (1 << 1);
298 let chan_was_enabled;
300 match network.channels.get_mut(&NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash)) {
301 None => return Err(HandleError{err: "Couldn't find channel for update", action: Some(ErrorAction::IgnoreError)}),
303 macro_rules! maybe_update_channel_info {
304 ( $target: expr) => {
305 if $target.last_update >= msg.contents.timestamp {
306 return Err(HandleError{err: "Update older than last processed update", action: Some(ErrorAction::IgnoreError)});
308 chan_was_enabled = $target.enabled;
309 $target.last_update = msg.contents.timestamp;
310 $target.enabled = chan_enabled;
311 $target.cltv_expiry_delta = msg.contents.cltv_expiry_delta;
312 $target.htlc_minimum_msat = msg.contents.htlc_minimum_msat;
313 $target.fee_base_msat = msg.contents.fee_base_msat;
314 $target.fee_proportional_millionths = msg.contents.fee_proportional_millionths;
318 let msg_hash = Message::from_slice(&Sha256dHash::from_data(&msg.contents.encode()[..])[..]).unwrap();
319 if msg.contents.flags & 1 == 1 {
320 dest_node_id = channel.one_to_two.src_node_id.clone();
321 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.signature, &channel.two_to_one.src_node_id);
322 maybe_update_channel_info!(channel.two_to_one);
324 dest_node_id = channel.two_to_one.src_node_id.clone();
325 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.signature, &channel.one_to_two.src_node_id);
326 maybe_update_channel_info!(channel.one_to_two);
332 let node = network.nodes.get_mut(&dest_node_id).unwrap();
333 node.lowest_inbound_channel_fee_base_msat = cmp::min(node.lowest_inbound_channel_fee_base_msat, msg.contents.fee_base_msat);
334 node.lowest_inbound_channel_fee_proportional_millionths = cmp::min(node.lowest_inbound_channel_fee_proportional_millionths, msg.contents.fee_proportional_millionths);
335 } else if chan_was_enabled {
336 let mut lowest_inbound_channel_fee_base_msat = u32::max_value();
337 let mut lowest_inbound_channel_fee_proportional_millionths = u32::max_value();
340 let node = network.nodes.get(&dest_node_id).unwrap();
342 for chan_id in node.channels.iter() {
343 let chan = network.channels.get(chan_id).unwrap();
344 if chan.one_to_two.src_node_id == dest_node_id {
345 lowest_inbound_channel_fee_base_msat = cmp::min(lowest_inbound_channel_fee_base_msat, chan.two_to_one.fee_base_msat);
346 lowest_inbound_channel_fee_proportional_millionths = cmp::min(lowest_inbound_channel_fee_proportional_millionths, chan.two_to_one.fee_proportional_millionths);
348 lowest_inbound_channel_fee_base_msat = cmp::min(lowest_inbound_channel_fee_base_msat, chan.one_to_two.fee_base_msat);
349 lowest_inbound_channel_fee_proportional_millionths = cmp::min(lowest_inbound_channel_fee_proportional_millionths, chan.one_to_two.fee_proportional_millionths);
354 //TODO: satisfy the borrow-checker without a double-map-lookup :(
355 let mut_node = network.nodes.get_mut(&dest_node_id).unwrap();
356 mut_node.lowest_inbound_channel_fee_base_msat = lowest_inbound_channel_fee_base_msat;
357 mut_node.lowest_inbound_channel_fee_proportional_millionths = lowest_inbound_channel_fee_proportional_millionths;
360 Ok(msg.contents.excess_data.is_empty())
364 #[derive(Eq, PartialEq)]
365 struct RouteGraphNode {
367 lowest_fee_to_peer_through_node: u64,
368 lowest_fee_to_node: u64,
371 impl cmp::Ord for RouteGraphNode {
372 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
373 other.lowest_fee_to_peer_through_node.cmp(&self.lowest_fee_to_peer_through_node)
374 .then_with(|| other.pubkey.serialize().cmp(&self.pubkey.serialize()))
378 impl cmp::PartialOrd for RouteGraphNode {
379 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
380 Some(self.cmp(other))
384 struct DummyDirectionalChannelInfo {
385 src_node_id: PublicKey,
386 cltv_expiry_delta: u32,
387 htlc_minimum_msat: u64,
389 fee_proportional_millionths: u32,
393 pub fn new(our_pubkey: PublicKey, chain_monitor: Arc<ChainWatchInterface>, logger: Arc<Logger>) -> Router {
394 let mut nodes = HashMap::new();
395 nodes.insert(our_pubkey.clone(), NodeInfo {
396 channels: Vec::new(),
397 lowest_inbound_channel_fee_base_msat: u32::max_value(),
398 lowest_inbound_channel_fee_proportional_millionths: u32::max_value(),
399 features: GlobalFeatures::new(),
403 addresses: Vec::new(),
406 secp_ctx: Secp256k1::verification_only(),
407 network_map: RwLock::new(NetworkMap {
408 channels: HashMap::new(),
409 our_node_id: our_pubkey,
417 /// Dumps the entire network view of this Router to the logger provided in the constructor at
419 pub fn trace_state(&self) {
420 log_trace!(self, "{}", self.network_map.read().unwrap());
423 /// Get network addresses by node id
424 pub fn get_addresses(&self, pubkey: &PublicKey) -> Option<Vec<NetAddress>> {
425 let network = self.network_map.read().unwrap();
426 network.nodes.get(pubkey).map(|n| n.addresses.clone())
429 /// Marks a node as having failed a route. This will avoid re-using the node in routes for now,
430 /// with an expotnential decay in node "badness". Note that there is deliberately no
431 /// mark_channel_bad as a node may simply lie and suggest that an upstream channel from it is
432 /// what failed the route and not the node itself. Instead, setting the blamed_upstream_node
433 /// boolean will reduce the penalty, returning the node to usability faster. If the node is
434 /// behaving correctly, it will disable the failing channel and we will use it again next time.
435 pub fn mark_node_bad(&self, _node_id: &PublicKey, _blamed_upstream_node: bool) {
439 /// Gets a route from us to the given target node.
440 /// Extra routing hops between known nodes and the target will be used if they are included in
442 /// If some channels aren't announced, it may be useful to fill in a first_hops with the
443 /// results from a local ChannelManager::list_usable_channels() call. If it is filled in, our
444 /// (this Router's) view of our local channels will be ignored, and only those in first_hops
445 /// will be used. Panics if first_hops contains channels without short_channel_ids
446 /// (ChannelManager::list_usable_channels will never include such channels).
447 /// The fees on channels from us to next-hops are ignored (as they are assumed to all be
448 /// equal), however the enabled/disabled bit on such channels as well as the htlc_minimum_msat
449 /// *is* checked as they may change based on the receiving node.
450 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> {
451 // TODO: Obviously *only* using total fee cost sucks. We should consider weighting by
452 // uptime/success in using a node in the past.
453 let network = self.network_map.read().unwrap();
455 if *target == network.our_node_id {
456 return Err(HandleError{err: "Cannot generate a route to ourselves", action: None});
459 if final_value_msat > 21_000_000 * 1_0000_0000 * 1000 {
460 return Err(HandleError{err: "Cannot generate a route of more value than all existing satoshis", action: None});
463 // We do a dest-to-source Dijkstra's sorting by each node's distance from the destination
464 // plus the minimum per-HTLC fee to get from it to another node (aka "shitty A*").
465 // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
466 // to use as the A* heuristic beyond just the cost to get one node further than the current
469 let dummy_directional_info = DummyDirectionalChannelInfo { // used for first_hops routes
470 src_node_id: network.our_node_id.clone(),
471 cltv_expiry_delta: 0,
472 htlc_minimum_msat: 0,
474 fee_proportional_millionths: 0,
477 let mut targets = BinaryHeap::new(); //TODO: Do we care about switching to eg Fibbonaci heap?
478 let mut dist = HashMap::with_capacity(network.nodes.len());
480 let mut first_hop_targets = HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
481 if let Some(hops) = first_hops {
483 let short_channel_id = chan.short_channel_id.expect("first_hops should be filled in with usable channels, not pending ones");
484 if chan.remote_network_id == *target {
486 hops: vec![RouteHop {
487 pubkey: chan.remote_network_id,
489 fee_msat: final_value_msat,
490 cltv_expiry_delta: final_cltv,
494 first_hop_targets.insert(chan.remote_network_id, short_channel_id);
496 if first_hop_targets.is_empty() {
497 return Err(HandleError{err: "Cannot route when there are no outbound routes away from us", action: None});
501 macro_rules! add_entry {
502 // Adds entry which goes from the node pointed to by $directional_info to
503 // $dest_node_id over the channel with id $chan_id with fees described in
504 // $directional_info.
505 ( $chan_id: expr, $dest_node_id: expr, $directional_info: expr, $starting_fee_msat: expr ) => {
506 //TODO: Explore simply adding fee to hit htlc_minimum_msat
507 if $starting_fee_msat as u64 + final_value_msat > $directional_info.htlc_minimum_msat {
508 let proportional_fee_millions = ($starting_fee_msat + final_value_msat).checked_mul($directional_info.fee_proportional_millionths as u64);
509 if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
510 ($directional_info.fee_base_msat as u64).checked_add(part / 1000000) })
512 let mut total_fee = $starting_fee_msat as u64;
513 let hm_entry = dist.entry(&$directional_info.src_node_id);
514 let old_entry = hm_entry.or_insert_with(|| {
515 let node = network.nodes.get(&$directional_info.src_node_id).unwrap();
517 node.lowest_inbound_channel_fee_base_msat,
518 node.lowest_inbound_channel_fee_proportional_millionths,
520 pubkey: $dest_node_id.clone(),
523 cltv_expiry_delta: 0,
526 if $directional_info.src_node_id != network.our_node_id {
527 // Ignore new_fee for channel-from-us as we assume all channels-from-us
528 // will have the same effective-fee
529 total_fee += new_fee;
530 if let Some(fee_inc) = final_value_msat.checked_add(total_fee).and_then(|inc| { (old_entry.2 as u64).checked_mul(inc) }) {
531 total_fee += fee_inc / 1000000 + (old_entry.1 as u64);
533 // max_value means we'll always fail the old_entry.0 > total_fee check
534 total_fee = u64::max_value();
537 let new_graph_node = RouteGraphNode {
538 pubkey: $directional_info.src_node_id,
539 lowest_fee_to_peer_through_node: total_fee,
540 lowest_fee_to_node: $starting_fee_msat as u64 + new_fee,
542 if old_entry.0 > total_fee {
543 targets.push(new_graph_node);
544 old_entry.0 = total_fee;
545 old_entry.3 = RouteHop {
546 pubkey: $dest_node_id.clone(),
547 short_channel_id: $chan_id.clone(),
548 fee_msat: new_fee, // This field is ignored on the last-hop anyway
549 cltv_expiry_delta: $directional_info.cltv_expiry_delta as u32,
557 macro_rules! add_entries_to_cheapest_to_target_node {
558 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr ) => {
559 if first_hops.is_some() {
560 if let Some(first_hop) = first_hop_targets.get(&$node_id) {
561 add_entry!(first_hop, $node_id, dummy_directional_info, $fee_to_target_msat);
565 for chan_id in $node.channels.iter() {
566 let chan = network.channels.get(chan_id).unwrap();
567 if chan.one_to_two.src_node_id == *$node_id {
568 // ie $node is one, ie next hop in A* is two, via the two_to_one channel
569 if first_hops.is_none() || chan.two_to_one.src_node_id != network.our_node_id {
570 if chan.two_to_one.enabled {
571 add_entry!(chan_id, chan.one_to_two.src_node_id, chan.two_to_one, $fee_to_target_msat);
575 if first_hops.is_none() || chan.one_to_two.src_node_id != network.our_node_id {
576 if chan.one_to_two.enabled {
577 add_entry!(chan_id, chan.two_to_one.src_node_id, chan.one_to_two, $fee_to_target_msat);
585 match network.nodes.get(target) {
588 add_entries_to_cheapest_to_target_node!(node, target, 0);
592 for hop in last_hops.iter() {
593 if first_hops.is_none() || hop.src_node_id != network.our_node_id { // first_hop overrules last_hops
594 if network.nodes.get(&hop.src_node_id).is_some() {
595 if first_hops.is_some() {
596 if let Some(first_hop) = first_hop_targets.get(&hop.src_node_id) {
597 add_entry!(first_hop, hop.src_node_id, dummy_directional_info, 0);
600 add_entry!(hop.short_channel_id, target, hop, 0);
605 while let Some(RouteGraphNode { pubkey, lowest_fee_to_node, .. }) = targets.pop() {
606 if pubkey == network.our_node_id {
607 let mut res = vec!(dist.remove(&network.our_node_id).unwrap().3);
608 while res.last().unwrap().pubkey != *target {
609 let new_entry = match dist.remove(&res.last().unwrap().pubkey) {
611 None => return Err(HandleError{err: "Failed to find a non-fee-overflowing path to the given destination", action: None}),
613 res.last_mut().unwrap().fee_msat = new_entry.fee_msat;
614 res.last_mut().unwrap().cltv_expiry_delta = new_entry.cltv_expiry_delta;
617 res.last_mut().unwrap().fee_msat = final_value_msat;
618 res.last_mut().unwrap().cltv_expiry_delta = final_cltv;
619 let route = Route { hops: res };
620 log_trace!(self, "Got route: {}", log_route!(route));
624 match network.nodes.get(&pubkey) {
627 add_entries_to_cheapest_to_target_node!(node, &pubkey, lowest_fee_to_node);
632 Err(HandleError{err: "Failed to find a path to the given destination", action: None})
638 use chain::chaininterface;
639 use ln::channelmanager;
640 use ln::router::{Router,NodeInfo,NetworkMap,ChannelInfo,DirectionalChannelInfo,RouteHint};
641 use ln::msgs::GlobalFeatures;
642 use util::test_utils;
643 use util::logger::Logger;
645 use bitcoin::util::hash::Sha256dHash;
649 use secp256k1::key::{PublicKey,SecretKey};
650 use secp256k1::Secp256k1;
656 let secp_ctx = Secp256k1::new();
657 let our_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap());
658 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
659 let chain_monitor = Arc::new(chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet, Arc::clone(&logger)));
660 let router = Router::new(our_id, chain_monitor, Arc::clone(&logger));
662 // Build network from our_id to node8:
664 // -1(1)2- node1 -1(3)2-
666 // our_id -1(12)2- node8 -1(13)2--- node3
668 // -1(2)2- node2 -1(4)2-
671 // chan1 1-to-2: disabled
672 // chan1 2-to-1: enabled, 0 fee
674 // chan2 1-to-2: enabled, ignored fee
675 // chan2 2-to-1: enabled, 0 fee
677 // chan3 1-to-2: enabled, 0 fee
678 // chan3 2-to-1: enabled, 100 msat fee
680 // chan4 1-to-2: enabled, 100% fee
681 // chan4 2-to-1: enabled, 0 fee
683 // chan12 1-to-2: enabled, ignored fee
684 // chan12 2-to-1: enabled, 0 fee
686 // chan13 1-to-2: enabled, 200% fee
687 // chan13 2-to-1: enabled, 0 fee
690 // -1(5)2- node4 -1(8)2--
694 // node3--1(6)2- node5 -1(9)2--- node7 (not in global route map)
696 // -1(7)2- node6 -1(10)2-
698 // chan5 1-to-2: enabled, 100 msat fee
699 // chan5 2-to-1: enabled, 0 fee
701 // chan6 1-to-2: enabled, 0 fee
702 // chan6 2-to-1: enabled, 0 fee
704 // chan7 1-to-2: enabled, 100% fee
705 // chan7 2-to-1: enabled, 0 fee
707 // chan8 1-to-2: enabled, variable fee (0 then 1000 msat)
708 // chan8 2-to-1: enabled, 0 fee
710 // chan9 1-to-2: enabled, 1001 msat fee
711 // chan9 2-to-1: enabled, 0 fee
713 // chan10 1-to-2: enabled, 0 fee
714 // chan10 2-to-1: enabled, 0 fee
716 // chan11 1-to-2: enabled, 0 fee
717 // chan11 2-to-1: enabled, 0 fee
719 let node1 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap()[..]).unwrap());
720 let node2 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0303030303030303030303030303030303030303030303030303030303030303").unwrap()[..]).unwrap());
721 let node3 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0404040404040404040404040404040404040404040404040404040404040404").unwrap()[..]).unwrap());
722 let node4 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0505050505050505050505050505050505050505050505050505050505050505").unwrap()[..]).unwrap());
723 let node5 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0606060606060606060606060606060606060606060606060606060606060606").unwrap()[..]).unwrap());
724 let node6 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0707070707070707070707070707070707070707070707070707070707070707").unwrap()[..]).unwrap());
725 let node7 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0808080808080808080808080808080808080808080808080808080808080808").unwrap()[..]).unwrap());
726 let node8 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0909090909090909090909090909090909090909090909090909090909090909").unwrap()[..]).unwrap());
728 let zero_hash = Sha256dHash::from_data(&[0; 32]);
731 let mut network = router.network_map.write().unwrap();
733 network.nodes.insert(node1.clone(), NodeInfo {
734 channels: vec!(NetworkMap::get_key(1, zero_hash.clone()), NetworkMap::get_key(3, zero_hash.clone())),
735 lowest_inbound_channel_fee_base_msat: 100,
736 lowest_inbound_channel_fee_proportional_millionths: 0,
737 features: GlobalFeatures::new(),
741 addresses: Vec::new(),
743 network.channels.insert(NetworkMap::get_key(1, zero_hash.clone()), ChannelInfo {
744 features: GlobalFeatures::new(),
745 one_to_two: DirectionalChannelInfo {
746 src_node_id: our_id.clone(),
749 cltv_expiry_delta: u16::max_value(), // This value should be ignored
750 htlc_minimum_msat: 0,
751 fee_base_msat: u32::max_value(), // This value should be ignored
752 fee_proportional_millionths: u32::max_value(), // This value should be ignored
753 }, two_to_one: DirectionalChannelInfo {
754 src_node_id: node1.clone(),
757 cltv_expiry_delta: 0,
758 htlc_minimum_msat: 0,
760 fee_proportional_millionths: 0,
763 network.nodes.insert(node2.clone(), NodeInfo {
764 channels: vec!(NetworkMap::get_key(2, zero_hash.clone()), NetworkMap::get_key(4, zero_hash.clone())),
765 lowest_inbound_channel_fee_base_msat: 0,
766 lowest_inbound_channel_fee_proportional_millionths: 0,
767 features: GlobalFeatures::new(),
771 addresses: Vec::new(),
773 network.channels.insert(NetworkMap::get_key(2, zero_hash.clone()), ChannelInfo {
774 features: GlobalFeatures::new(),
775 one_to_two: DirectionalChannelInfo {
776 src_node_id: our_id.clone(),
779 cltv_expiry_delta: u16::max_value(), // This value should be ignored
780 htlc_minimum_msat: 0,
781 fee_base_msat: u32::max_value(), // This value should be ignored
782 fee_proportional_millionths: u32::max_value(), // This value should be ignored
783 }, two_to_one: DirectionalChannelInfo {
784 src_node_id: node2.clone(),
787 cltv_expiry_delta: 0,
788 htlc_minimum_msat: 0,
790 fee_proportional_millionths: 0,
793 network.nodes.insert(node8.clone(), NodeInfo {
794 channels: vec!(NetworkMap::get_key(12, zero_hash.clone()), NetworkMap::get_key(13, zero_hash.clone())),
795 lowest_inbound_channel_fee_base_msat: 0,
796 lowest_inbound_channel_fee_proportional_millionths: 0,
797 features: GlobalFeatures::new(),
801 addresses: Vec::new(),
803 network.channels.insert(NetworkMap::get_key(12, zero_hash.clone()), ChannelInfo {
804 features: GlobalFeatures::new(),
805 one_to_two: DirectionalChannelInfo {
806 src_node_id: our_id.clone(),
809 cltv_expiry_delta: u16::max_value(), // This value should be ignored
810 htlc_minimum_msat: 0,
811 fee_base_msat: u32::max_value(), // This value should be ignored
812 fee_proportional_millionths: u32::max_value(), // This value should be ignored
813 }, two_to_one: DirectionalChannelInfo {
814 src_node_id: node8.clone(),
817 cltv_expiry_delta: 0,
818 htlc_minimum_msat: 0,
820 fee_proportional_millionths: 0,
823 network.nodes.insert(node3.clone(), NodeInfo {
825 NetworkMap::get_key(3, zero_hash.clone()),
826 NetworkMap::get_key(4, zero_hash.clone()),
827 NetworkMap::get_key(13, zero_hash.clone()),
828 NetworkMap::get_key(5, zero_hash.clone()),
829 NetworkMap::get_key(6, zero_hash.clone()),
830 NetworkMap::get_key(7, zero_hash.clone())),
831 lowest_inbound_channel_fee_base_msat: 0,
832 lowest_inbound_channel_fee_proportional_millionths: 0,
833 features: GlobalFeatures::new(),
837 addresses: Vec::new(),
839 network.channels.insert(NetworkMap::get_key(3, zero_hash.clone()), ChannelInfo {
840 features: GlobalFeatures::new(),
841 one_to_two: DirectionalChannelInfo {
842 src_node_id: node1.clone(),
845 cltv_expiry_delta: (3 << 8) | 1,
846 htlc_minimum_msat: 0,
848 fee_proportional_millionths: 0,
849 }, two_to_one: DirectionalChannelInfo {
850 src_node_id: node3.clone(),
853 cltv_expiry_delta: (3 << 8) | 2,
854 htlc_minimum_msat: 0,
856 fee_proportional_millionths: 0,
859 network.channels.insert(NetworkMap::get_key(4, zero_hash.clone()), ChannelInfo {
860 features: GlobalFeatures::new(),
861 one_to_two: DirectionalChannelInfo {
862 src_node_id: node2.clone(),
865 cltv_expiry_delta: (4 << 8) | 1,
866 htlc_minimum_msat: 0,
868 fee_proportional_millionths: 1000000,
869 }, two_to_one: DirectionalChannelInfo {
870 src_node_id: node3.clone(),
873 cltv_expiry_delta: (4 << 8) | 2,
874 htlc_minimum_msat: 0,
876 fee_proportional_millionths: 0,
879 network.channels.insert(NetworkMap::get_key(13, zero_hash.clone()), ChannelInfo {
880 features: GlobalFeatures::new(),
881 one_to_two: DirectionalChannelInfo {
882 src_node_id: node8.clone(),
885 cltv_expiry_delta: (13 << 8) | 1,
886 htlc_minimum_msat: 0,
888 fee_proportional_millionths: 2000000,
889 }, two_to_one: DirectionalChannelInfo {
890 src_node_id: node3.clone(),
893 cltv_expiry_delta: (13 << 8) | 2,
894 htlc_minimum_msat: 0,
896 fee_proportional_millionths: 0,
899 network.nodes.insert(node4.clone(), NodeInfo {
900 channels: vec!(NetworkMap::get_key(5, zero_hash.clone()), NetworkMap::get_key(11, zero_hash.clone())),
901 lowest_inbound_channel_fee_base_msat: 0,
902 lowest_inbound_channel_fee_proportional_millionths: 0,
903 features: GlobalFeatures::new(),
907 addresses: Vec::new(),
909 network.channels.insert(NetworkMap::get_key(5, zero_hash.clone()), ChannelInfo {
910 features: GlobalFeatures::new(),
911 one_to_two: DirectionalChannelInfo {
912 src_node_id: node3.clone(),
915 cltv_expiry_delta: (5 << 8) | 1,
916 htlc_minimum_msat: 0,
918 fee_proportional_millionths: 0,
919 }, two_to_one: DirectionalChannelInfo {
920 src_node_id: node4.clone(),
923 cltv_expiry_delta: (5 << 8) | 2,
924 htlc_minimum_msat: 0,
926 fee_proportional_millionths: 0,
929 network.nodes.insert(node5.clone(), NodeInfo {
930 channels: vec!(NetworkMap::get_key(6, zero_hash.clone()), NetworkMap::get_key(11, zero_hash.clone())),
931 lowest_inbound_channel_fee_base_msat: 0,
932 lowest_inbound_channel_fee_proportional_millionths: 0,
933 features: GlobalFeatures::new(),
937 addresses: Vec::new(),
939 network.channels.insert(NetworkMap::get_key(6, zero_hash.clone()), ChannelInfo {
940 features: GlobalFeatures::new(),
941 one_to_two: DirectionalChannelInfo {
942 src_node_id: node3.clone(),
945 cltv_expiry_delta: (6 << 8) | 1,
946 htlc_minimum_msat: 0,
948 fee_proportional_millionths: 0,
949 }, two_to_one: DirectionalChannelInfo {
950 src_node_id: node5.clone(),
953 cltv_expiry_delta: (6 << 8) | 2,
954 htlc_minimum_msat: 0,
956 fee_proportional_millionths: 0,
959 network.channels.insert(NetworkMap::get_key(11, zero_hash.clone()), ChannelInfo {
960 features: GlobalFeatures::new(),
961 one_to_two: DirectionalChannelInfo {
962 src_node_id: node5.clone(),
965 cltv_expiry_delta: (11 << 8) | 1,
966 htlc_minimum_msat: 0,
968 fee_proportional_millionths: 0,
969 }, two_to_one: DirectionalChannelInfo {
970 src_node_id: node4.clone(),
973 cltv_expiry_delta: (11 << 8) | 2,
974 htlc_minimum_msat: 0,
976 fee_proportional_millionths: 0,
979 network.nodes.insert(node6.clone(), NodeInfo {
980 channels: vec!(NetworkMap::get_key(7, zero_hash.clone())),
981 lowest_inbound_channel_fee_base_msat: 0,
982 lowest_inbound_channel_fee_proportional_millionths: 0,
983 features: GlobalFeatures::new(),
987 addresses: Vec::new(),
989 network.channels.insert(NetworkMap::get_key(7, zero_hash.clone()), ChannelInfo {
990 features: GlobalFeatures::new(),
991 one_to_two: DirectionalChannelInfo {
992 src_node_id: node3.clone(),
995 cltv_expiry_delta: (7 << 8) | 1,
996 htlc_minimum_msat: 0,
998 fee_proportional_millionths: 1000000,
999 }, two_to_one: DirectionalChannelInfo {
1000 src_node_id: node6.clone(),
1003 cltv_expiry_delta: (7 << 8) | 2,
1004 htlc_minimum_msat: 0,
1006 fee_proportional_millionths: 0,
1011 { // Simple route to 3 via 2
1012 let route = router.get_route(&node3, None, &Vec::new(), 100, 42).unwrap();
1013 assert_eq!(route.hops.len(), 2);
1015 assert_eq!(route.hops[0].pubkey, node2);
1016 assert_eq!(route.hops[0].short_channel_id, 2);
1017 assert_eq!(route.hops[0].fee_msat, 100);
1018 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1020 assert_eq!(route.hops[1].pubkey, node3);
1021 assert_eq!(route.hops[1].short_channel_id, 4);
1022 assert_eq!(route.hops[1].fee_msat, 100);
1023 assert_eq!(route.hops[1].cltv_expiry_delta, 42);
1026 { // Route to 1 via 2 and 3 because our channel to 1 is disabled
1027 let route = router.get_route(&node1, None, &Vec::new(), 100, 42).unwrap();
1028 assert_eq!(route.hops.len(), 3);
1030 assert_eq!(route.hops[0].pubkey, node2);
1031 assert_eq!(route.hops[0].short_channel_id, 2);
1032 assert_eq!(route.hops[0].fee_msat, 200);
1033 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1035 assert_eq!(route.hops[1].pubkey, node3);
1036 assert_eq!(route.hops[1].short_channel_id, 4);
1037 assert_eq!(route.hops[1].fee_msat, 100);
1038 assert_eq!(route.hops[1].cltv_expiry_delta, (3 << 8) | 2);
1040 assert_eq!(route.hops[2].pubkey, node1);
1041 assert_eq!(route.hops[2].short_channel_id, 3);
1042 assert_eq!(route.hops[2].fee_msat, 100);
1043 assert_eq!(route.hops[2].cltv_expiry_delta, 42);
1046 { // If we specify a channel to node8, that overrides our local channel view and that gets used
1047 let our_chans = vec![channelmanager::ChannelDetails {
1048 channel_id: [0; 32],
1049 short_channel_id: Some(42),
1050 remote_network_id: node8.clone(),
1051 channel_value_satoshis: 0,
1054 let route = router.get_route(&node3, Some(&our_chans), &Vec::new(), 100, 42).unwrap();
1055 assert_eq!(route.hops.len(), 2);
1057 assert_eq!(route.hops[0].pubkey, node8);
1058 assert_eq!(route.hops[0].short_channel_id, 42);
1059 assert_eq!(route.hops[0].fee_msat, 200);
1060 assert_eq!(route.hops[0].cltv_expiry_delta, (13 << 8) | 1);
1062 assert_eq!(route.hops[1].pubkey, node3);
1063 assert_eq!(route.hops[1].short_channel_id, 13);
1064 assert_eq!(route.hops[1].fee_msat, 100);
1065 assert_eq!(route.hops[1].cltv_expiry_delta, 42);
1068 let mut last_hops = vec!(RouteHint {
1069 src_node_id: node4.clone(),
1070 short_channel_id: 8,
1072 fee_proportional_millionths: 0,
1073 cltv_expiry_delta: (8 << 8) | 1,
1074 htlc_minimum_msat: 0,
1076 src_node_id: node5.clone(),
1077 short_channel_id: 9,
1078 fee_base_msat: 1001,
1079 fee_proportional_millionths: 0,
1080 cltv_expiry_delta: (9 << 8) | 1,
1081 htlc_minimum_msat: 0,
1083 src_node_id: node6.clone(),
1084 short_channel_id: 10,
1086 fee_proportional_millionths: 0,
1087 cltv_expiry_delta: (10 << 8) | 1,
1088 htlc_minimum_msat: 0,
1091 { // Simple test across 2, 3, 5, and 4 via a last_hop channel
1092 let route = router.get_route(&node7, None, &last_hops, 100, 42).unwrap();
1093 assert_eq!(route.hops.len(), 5);
1095 assert_eq!(route.hops[0].pubkey, node2);
1096 assert_eq!(route.hops[0].short_channel_id, 2);
1097 assert_eq!(route.hops[0].fee_msat, 100);
1098 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1100 assert_eq!(route.hops[1].pubkey, node3);
1101 assert_eq!(route.hops[1].short_channel_id, 4);
1102 assert_eq!(route.hops[1].fee_msat, 0);
1103 assert_eq!(route.hops[1].cltv_expiry_delta, (6 << 8) | 1);
1105 assert_eq!(route.hops[2].pubkey, node5);
1106 assert_eq!(route.hops[2].short_channel_id, 6);
1107 assert_eq!(route.hops[2].fee_msat, 0);
1108 assert_eq!(route.hops[2].cltv_expiry_delta, (11 << 8) | 1);
1110 assert_eq!(route.hops[3].pubkey, node4);
1111 assert_eq!(route.hops[3].short_channel_id, 11);
1112 assert_eq!(route.hops[3].fee_msat, 0);
1113 assert_eq!(route.hops[3].cltv_expiry_delta, (8 << 8) | 1);
1115 assert_eq!(route.hops[4].pubkey, node7);
1116 assert_eq!(route.hops[4].short_channel_id, 8);
1117 assert_eq!(route.hops[4].fee_msat, 100);
1118 assert_eq!(route.hops[4].cltv_expiry_delta, 42);
1121 { // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
1122 let our_chans = vec![channelmanager::ChannelDetails {
1123 channel_id: [0; 32],
1124 short_channel_id: Some(42),
1125 remote_network_id: node4.clone(),
1126 channel_value_satoshis: 0,
1129 let route = router.get_route(&node7, Some(&our_chans), &last_hops, 100, 42).unwrap();
1130 assert_eq!(route.hops.len(), 2);
1132 assert_eq!(route.hops[0].pubkey, node4);
1133 assert_eq!(route.hops[0].short_channel_id, 42);
1134 assert_eq!(route.hops[0].fee_msat, 0);
1135 assert_eq!(route.hops[0].cltv_expiry_delta, (8 << 8) | 1);
1137 assert_eq!(route.hops[1].pubkey, node7);
1138 assert_eq!(route.hops[1].short_channel_id, 8);
1139 assert_eq!(route.hops[1].fee_msat, 100);
1140 assert_eq!(route.hops[1].cltv_expiry_delta, 42);
1143 last_hops[0].fee_base_msat = 1000;
1145 { // Revert to via 6 as the fee on 8 goes up
1146 let route = router.get_route(&node7, None, &last_hops, 100, 42).unwrap();
1147 assert_eq!(route.hops.len(), 4);
1149 assert_eq!(route.hops[0].pubkey, node2);
1150 assert_eq!(route.hops[0].short_channel_id, 2);
1151 assert_eq!(route.hops[0].fee_msat, 200); // fee increased as its % of value transferred across node
1152 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1154 assert_eq!(route.hops[1].pubkey, node3);
1155 assert_eq!(route.hops[1].short_channel_id, 4);
1156 assert_eq!(route.hops[1].fee_msat, 100);
1157 assert_eq!(route.hops[1].cltv_expiry_delta, (7 << 8) | 1);
1159 assert_eq!(route.hops[2].pubkey, node6);
1160 assert_eq!(route.hops[2].short_channel_id, 7);
1161 assert_eq!(route.hops[2].fee_msat, 0);
1162 assert_eq!(route.hops[2].cltv_expiry_delta, (10 << 8) | 1);
1164 assert_eq!(route.hops[3].pubkey, node7);
1165 assert_eq!(route.hops[3].short_channel_id, 10);
1166 assert_eq!(route.hops[3].fee_msat, 100);
1167 assert_eq!(route.hops[3].cltv_expiry_delta, 42);
1170 { // ...but still use 8 for larger payments as 6 has a variable feerate
1171 let route = router.get_route(&node7, None, &last_hops, 2000, 42).unwrap();
1172 assert_eq!(route.hops.len(), 5);
1174 assert_eq!(route.hops[0].pubkey, node2);
1175 assert_eq!(route.hops[0].short_channel_id, 2);
1176 assert_eq!(route.hops[0].fee_msat, 3000);
1177 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1179 assert_eq!(route.hops[1].pubkey, node3);
1180 assert_eq!(route.hops[1].short_channel_id, 4);
1181 assert_eq!(route.hops[1].fee_msat, 0);
1182 assert_eq!(route.hops[1].cltv_expiry_delta, (6 << 8) | 1);
1184 assert_eq!(route.hops[2].pubkey, node5);
1185 assert_eq!(route.hops[2].short_channel_id, 6);
1186 assert_eq!(route.hops[2].fee_msat, 0);
1187 assert_eq!(route.hops[2].cltv_expiry_delta, (11 << 8) | 1);
1189 assert_eq!(route.hops[3].pubkey, node4);
1190 assert_eq!(route.hops[3].short_channel_id, 11);
1191 assert_eq!(route.hops[3].fee_msat, 1000);
1192 assert_eq!(route.hops[3].cltv_expiry_delta, (8 << 8) | 1);
1194 assert_eq!(route.hops[4].pubkey, node7);
1195 assert_eq!(route.hops[4].short_channel_id, 8);
1196 assert_eq!(route.hops[4].fee_msat, 2000);
1197 assert_eq!(route.hops[4].cltv_expiry_delta, 42);