1 use secp256k1::key::PublicKey;
2 use secp256k1::{Secp256k1,Message};
4 use bitcoin::util::hash::Sha256dHash;
6 use ln::channelmanager;
7 use ln::msgs::{ErrorAction,HandleError,RoutingMessageHandler,MsgEncodable,NetAddress,GlobalFeatures};
9 use util::logger::Logger;
12 use std::sync::{RwLock,Arc};
13 use std::collections::{HashMap,BinaryHeap};
14 use std::collections::hash_map::Entry;
20 pub pubkey: PublicKey,
21 /// The channel that should be used from the previous hop to reach this node.
22 pub short_channel_id: u64,
23 /// The fee taken on this hop. For the last hop, this should be the full value of the payment.
25 /// The CLTV delta added for this hop. For the last hop, this should be the full CLTV value
26 /// expected at the destination, in excess of the current block height.
27 pub cltv_expiry_delta: u32,
30 /// A route from us through the network to a destination
33 /// The list of hops, NOT INCLUDING our own, where the last hop is the destination. Thus, this
34 /// must always be at least length one. By protocol rules, this may not currently exceed 20 in
36 pub hops: Vec<RouteHop>,
39 struct DirectionalChannelInfo {
40 src_node_id: PublicKey,
43 cltv_expiry_delta: u16,
44 htlc_minimum_msat: u64,
46 fee_proportional_millionths: u32,
49 impl std::fmt::Display for DirectionalChannelInfo {
50 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
51 write!(f, " node id {} last_update {} enabled {} cltv_expiry_delta {} htlc_minimum_msat {} fee_base_msat {} fee_proportional_millionths {}\n", 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)?;
57 features: GlobalFeatures,
58 one_to_two: DirectionalChannelInfo,
59 two_to_one: DirectionalChannelInfo,
62 impl std::fmt::Display for ChannelInfo {
63 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
64 //TODO: GlobalFeatures
65 write!(f, " one_to_two {}", self.one_to_two)?;
66 write!(f, " two_to_one {}", 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, " Channels\n")?;
90 for c in self.channels.iter() {
91 write!(f, " {}\n", c)?;
93 write!(f, " lowest_inbound_channel_fee_base_msat {}\n", self.lowest_inbound_channel_fee_base_msat)?;
94 write!(f, " lowest_inbound_channel_fee_proportional_millionths {}\n", self.lowest_inbound_channel_fee_proportional_millionths)?;
95 //TODO: GlobalFeatures, last_update, rgb, alias, addresses
101 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
102 channels: HashMap<(u64, Sha256dHash), ChannelInfo>,
103 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
104 channels: HashMap<u64, ChannelInfo>,
106 our_node_id: PublicKey,
107 nodes: HashMap<PublicKey, NodeInfo>,
110 impl std::fmt::Display for NetworkMap {
111 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
112 write!(f, "Node id {} network map\n[Channels]\n", log_pubkey!(self.our_node_id))?;
113 for (key, val) in self.channels.iter() {
114 write!(f, " {} :\n {}\n", key, val)?;
116 write!(f, "[Nodes]\n")?;
117 for (key, val) in self.nodes.iter() {
118 write!(f, " {} :\n {}\n", log_pubkey!(key), val)?;
125 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
127 fn get_key(short_channel_id: u64, chain_hash: Sha256dHash) -> (u64, Sha256dHash) {
128 (short_channel_id, chain_hash)
131 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
133 fn get_key(short_channel_id: u64, _: Sha256dHash) -> u64 {
137 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
139 fn get_short_id(id: &(u64, Sha256dHash)) -> &u64 {
143 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
145 fn get_short_id(id: &u64) -> &u64 {
150 /// A channel descriptor which provides a last-hop route to get_route
151 pub struct RouteHint {
152 pub src_node_id: PublicKey,
153 pub short_channel_id: u64,
154 pub fee_base_msat: u32,
155 pub fee_proportional_millionths: u32,
156 pub cltv_expiry_delta: u16,
157 pub htlc_minimum_msat: u64,
160 /// Tracks a view of the network, receiving updates from peers and generating Routes to
161 /// payment destinations.
164 network_map: RwLock<NetworkMap>,
168 macro_rules! secp_verify_sig {
169 ( $secp_ctx: expr, $msg: expr, $sig: expr, $pubkey: expr ) => {
170 match $secp_ctx.verify($msg, $sig, $pubkey) {
172 Err(_) => return Err(HandleError{err: "Invalid signature from remote node", action: None}),
177 impl RoutingMessageHandler for Router {
178 fn handle_node_announcement(&self, msg: &msgs::NodeAnnouncement) -> Result<(), HandleError> {
179 let msg_hash = Message::from_slice(&Sha256dHash::from_data(&msg.contents.encode()[..])[..]).unwrap();
180 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.signature, &msg.contents.node_id);
182 let mut network = self.network_map.write().unwrap();
183 match network.nodes.get_mut(&msg.contents.node_id) {
184 None => Err(HandleError{err: "No existing channels for node_announcement", action: Some(ErrorAction::IgnoreError)}),
186 if node.last_update >= msg.contents.timestamp {
187 return Err(HandleError{err: "Update older than last processed update", action: Some(ErrorAction::IgnoreError)});
190 node.features = msg.contents.features.clone();
191 node.last_update = msg.contents.timestamp;
192 node.rgb = msg.contents.rgb;
193 node.alias = msg.contents.alias;
194 node.addresses = msg.contents.addresses.clone();
200 fn handle_channel_announcement(&self, msg: &msgs::ChannelAnnouncement) -> Result<bool, HandleError> {
201 let msg_hash = Message::from_slice(&Sha256dHash::from_data(&msg.contents.encode()[..])[..]).unwrap();
202 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.node_signature_1, &msg.contents.node_id_1);
203 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.node_signature_2, &msg.contents.node_id_2);
204 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.bitcoin_signature_1, &msg.contents.bitcoin_key_1);
205 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.bitcoin_signature_2, &msg.contents.bitcoin_key_2);
207 //TODO: Call blockchain thing to ask if the short_channel_id is valid
208 //TODO: Only allow bitcoin chain_hash
210 if msg.contents.features.requires_unknown_bits() {
211 return Err(HandleError{err: "Channel announcement required unknown feature flags", action: None});
214 let mut network = self.network_map.write().unwrap();
216 match network.channels.entry(NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash)) {
217 Entry::Occupied(_) => {
218 //TODO: because asking the blockchain if short_channel_id is valid is only optional
219 //in the blockchain API, we need to handle it smartly here, though its unclear
221 return Err(HandleError{err: "Already have knowledge of channel", action: Some(ErrorAction::IgnoreError)})
223 Entry::Vacant(entry) => {
224 entry.insert(ChannelInfo {
225 features: msg.contents.features.clone(),
226 one_to_two: DirectionalChannelInfo {
227 src_node_id: msg.contents.node_id_1.clone(),
230 cltv_expiry_delta: u16::max_value(),
231 htlc_minimum_msat: u64::max_value(),
232 fee_base_msat: u32::max_value(),
233 fee_proportional_millionths: u32::max_value(),
235 two_to_one: DirectionalChannelInfo {
236 src_node_id: msg.contents.node_id_2.clone(),
239 cltv_expiry_delta: u16::max_value(),
240 htlc_minimum_msat: u64::max_value(),
241 fee_base_msat: u32::max_value(),
242 fee_proportional_millionths: u32::max_value(),
248 macro_rules! add_channel_to_node {
249 ( $node_id: expr ) => {
250 match network.nodes.entry($node_id) {
251 Entry::Occupied(node_entry) => {
252 node_entry.into_mut().channels.push(NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash));
254 Entry::Vacant(node_entry) => {
255 node_entry.insert(NodeInfo {
256 channels: vec!(NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash)),
257 lowest_inbound_channel_fee_base_msat: u32::max_value(),
258 lowest_inbound_channel_fee_proportional_millionths: u32::max_value(),
259 features: GlobalFeatures::new(),
263 addresses: Vec::new(),
270 add_channel_to_node!(msg.contents.node_id_1);
271 add_channel_to_node!(msg.contents.node_id_2);
273 Ok(!msg.contents.features.supports_unknown_bits())
276 fn handle_htlc_fail_channel_update(&self, update: &msgs::HTLCFailChannelUpdate) {
278 &msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg } => {
279 let _ = self.handle_channel_update(msg);
281 &msgs::HTLCFailChannelUpdate::ChannelClosed { ref short_channel_id } => {
282 let mut network = self.network_map.write().unwrap();
283 if let Some(chan) = network.channels.remove(short_channel_id) {
284 network.nodes.get_mut(&chan.one_to_two.src_node_id).unwrap().channels.retain(|chan_id| {
285 chan_id != NetworkMap::get_short_id(chan_id)
287 network.nodes.get_mut(&chan.two_to_one.src_node_id).unwrap().channels.retain(|chan_id| {
288 chan_id != NetworkMap::get_short_id(chan_id)
295 fn handle_channel_update(&self, msg: &msgs::ChannelUpdate) -> Result<(), HandleError> {
296 let mut network = self.network_map.write().unwrap();
298 let chan_enabled = msg.contents.flags & (1 << 1) != (1 << 1);
299 let chan_was_enabled;
301 match network.channels.get_mut(&NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash)) {
302 None => return Err(HandleError{err: "Couldn't find channel for update", action: Some(ErrorAction::IgnoreError)}),
304 macro_rules! maybe_update_channel_info {
305 ( $target: expr) => {
306 if $target.last_update >= msg.contents.timestamp {
307 return Err(HandleError{err: "Update older than last processed update", action: Some(ErrorAction::IgnoreError)});
309 chan_was_enabled = $target.enabled;
310 $target.last_update = msg.contents.timestamp;
311 $target.enabled = chan_enabled;
312 $target.cltv_expiry_delta = msg.contents.cltv_expiry_delta;
313 $target.htlc_minimum_msat = msg.contents.htlc_minimum_msat;
314 $target.fee_base_msat = msg.contents.fee_base_msat;
315 $target.fee_proportional_millionths = msg.contents.fee_proportional_millionths;
319 let msg_hash = Message::from_slice(&Sha256dHash::from_data(&msg.contents.encode()[..])[..]).unwrap();
320 if msg.contents.flags & 1 == 1 {
321 dest_node_id = channel.one_to_two.src_node_id.clone();
322 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.signature, &channel.two_to_one.src_node_id);
323 maybe_update_channel_info!(channel.two_to_one);
325 dest_node_id = channel.two_to_one.src_node_id.clone();
326 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.signature, &channel.one_to_two.src_node_id);
327 maybe_update_channel_info!(channel.one_to_two);
333 let node = network.nodes.get_mut(&dest_node_id).unwrap();
334 node.lowest_inbound_channel_fee_base_msat = cmp::min(node.lowest_inbound_channel_fee_base_msat, msg.contents.fee_base_msat);
335 node.lowest_inbound_channel_fee_proportional_millionths = cmp::min(node.lowest_inbound_channel_fee_proportional_millionths, msg.contents.fee_proportional_millionths);
336 } else if chan_was_enabled {
337 let mut lowest_inbound_channel_fee_base_msat = u32::max_value();
338 let mut lowest_inbound_channel_fee_proportional_millionths = u32::max_value();
341 let node = network.nodes.get(&dest_node_id).unwrap();
343 for chan_id in node.channels.iter() {
344 let chan = network.channels.get(chan_id).unwrap();
345 if chan.one_to_two.src_node_id == dest_node_id {
346 lowest_inbound_channel_fee_base_msat = cmp::min(lowest_inbound_channel_fee_base_msat, chan.two_to_one.fee_base_msat);
347 lowest_inbound_channel_fee_proportional_millionths = cmp::min(lowest_inbound_channel_fee_proportional_millionths, chan.two_to_one.fee_proportional_millionths);
349 lowest_inbound_channel_fee_base_msat = cmp::min(lowest_inbound_channel_fee_base_msat, chan.one_to_two.fee_base_msat);
350 lowest_inbound_channel_fee_proportional_millionths = cmp::min(lowest_inbound_channel_fee_proportional_millionths, chan.one_to_two.fee_proportional_millionths);
355 //TODO: satisfy the borrow-checker without a double-map-lookup :(
356 let mut_node = network.nodes.get_mut(&dest_node_id).unwrap();
357 mut_node.lowest_inbound_channel_fee_base_msat = lowest_inbound_channel_fee_base_msat;
358 mut_node.lowest_inbound_channel_fee_proportional_millionths = lowest_inbound_channel_fee_proportional_millionths;
365 #[derive(Eq, PartialEq)]
366 struct RouteGraphNode {
368 lowest_fee_to_peer_through_node: u64,
369 lowest_fee_to_node: u64,
372 impl cmp::Ord for RouteGraphNode {
373 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
374 other.lowest_fee_to_peer_through_node.cmp(&self.lowest_fee_to_peer_through_node)
375 .then_with(|| other.pubkey.serialize().cmp(&self.pubkey.serialize()))
379 impl cmp::PartialOrd for RouteGraphNode {
380 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
381 Some(self.cmp(other))
385 struct DummyDirectionalChannelInfo {
386 src_node_id: PublicKey,
387 cltv_expiry_delta: u32,
388 htlc_minimum_msat: u64,
390 fee_proportional_millionths: u32,
394 pub fn new(our_pubkey: PublicKey, logger: Arc<Logger>) -> Router {
395 let mut nodes = HashMap::new();
396 nodes.insert(our_pubkey.clone(), NodeInfo {
397 channels: Vec::new(),
398 lowest_inbound_channel_fee_base_msat: u32::max_value(),
399 lowest_inbound_channel_fee_proportional_millionths: u32::max_value(),
400 features: GlobalFeatures::new(),
404 addresses: Vec::new(),
407 secp_ctx: Secp256k1::new(),
408 network_map: RwLock::new(NetworkMap {
409 channels: HashMap::new(),
410 our_node_id: our_pubkey,
417 /// Get network addresses by node id
418 pub fn get_addresses(&self, pubkey: &PublicKey) -> Option<Vec<NetAddress>> {
419 let network = self.network_map.read().unwrap();
420 network.nodes.get(pubkey).map(|n| n.addresses.clone())
423 /// Marks a node as having failed a route. This will avoid re-using the node in routes for now,
424 /// with an expotnential decay in node "badness". Note that there is deliberately no
425 /// mark_channel_bad as a node may simply lie and suggest that an upstream channel from it is
426 /// what failed the route and not the node itself. Instead, setting the blamed_upstream_node
427 /// boolean will reduce the penalty, returning the node to usability faster. If the node is
428 /// behaving correctly, it will disable the failing channel and we will use it again next time.
429 pub fn mark_node_bad(&self, _node_id: &PublicKey, _blamed_upstream_node: bool) {
433 /// Gets a route from us to the given target node.
434 /// Extra routing hops between known nodes and the target will be used if they are included in
436 /// If some channels aren't announced, it may be useful to fill in a first_hops with the
437 /// results from a local ChannelManager::list_usable_channels() call. If it is filled in, our
438 /// (this Router's) view of our local channels will be ignored, and only those in first_hops
439 /// will be used. Panics if first_hops contains channels without short_channel_ids
440 /// (ChannelManager::list_usable_channels will never include such channels).
441 /// The fees on channels from us to next-hops are ignored (as they are assumed to all be
442 /// equal), however the enabled/disabled bit on such channels as well as the htlc_minimum_msat
443 /// *is* checked as they may change based on the receiving node.
444 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> {
445 // TODO: Obviously *only* using total fee cost sucks. We should consider weighting by
446 // uptime/success in using a node in the past.
447 let network = self.network_map.read().unwrap();
449 if *target == network.our_node_id {
450 return Err(HandleError{err: "Cannot generate a route to ourselves", action: None});
453 if final_value_msat > 21_000_000 * 1_0000_0000 * 1000 {
454 return Err(HandleError{err: "Cannot generate a route of more value than all existing satoshis", action: None});
457 // We do a dest-to-source Dijkstra's sorting by each node's distance from the destination
458 // plus the minimum per-HTLC fee to get from it to another node (aka "shitty A*").
459 // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
460 // to use as the A* heuristic beyond just the cost to get one node further than the current
463 let dummy_directional_info = DummyDirectionalChannelInfo { // used for first_hops routes
464 src_node_id: network.our_node_id.clone(),
465 cltv_expiry_delta: 0,
466 htlc_minimum_msat: 0,
468 fee_proportional_millionths: 0,
471 let mut targets = BinaryHeap::new(); //TODO: Do we care about switching to eg Fibbonaci heap?
472 let mut dist = HashMap::with_capacity(network.nodes.len());
474 let mut first_hop_targets = HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
475 if let Some(hops) = first_hops {
477 let short_channel_id = chan.short_channel_id.expect("first_hops should be filled in with usable channels, not pending ones");
478 if chan.remote_network_id == *target {
480 hops: vec![RouteHop {
481 pubkey: chan.remote_network_id,
483 fee_msat: final_value_msat,
484 cltv_expiry_delta: final_cltv,
488 first_hop_targets.insert(chan.remote_network_id, short_channel_id);
490 if first_hop_targets.is_empty() {
491 return Err(HandleError{err: "Cannot route when there are no outbound routes away from us", action: None});
495 macro_rules! add_entry {
496 // Adds entry which goes from the node pointed to by $directional_info to
497 // $dest_node_id over the channel with id $chan_id with fees described in
498 // $directional_info.
499 ( $chan_id: expr, $dest_node_id: expr, $directional_info: expr, $starting_fee_msat: expr ) => {
500 //TODO: Explore simply adding fee to hit htlc_minimum_msat
501 if $starting_fee_msat as u64 + final_value_msat > $directional_info.htlc_minimum_msat {
502 let proportional_fee_millions = ($starting_fee_msat + final_value_msat).checked_mul($directional_info.fee_proportional_millionths as u64);
503 if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
504 ($directional_info.fee_base_msat as u64).checked_add(part / 1000000) })
506 let mut total_fee = $starting_fee_msat as u64;
507 let hm_entry = dist.entry(&$directional_info.src_node_id);
508 let old_entry = hm_entry.or_insert_with(|| {
509 let node = network.nodes.get(&$directional_info.src_node_id).unwrap();
511 node.lowest_inbound_channel_fee_base_msat,
512 node.lowest_inbound_channel_fee_proportional_millionths,
514 pubkey: $dest_node_id.clone(),
517 cltv_expiry_delta: 0,
520 if $directional_info.src_node_id != network.our_node_id {
521 // Ignore new_fee for channel-from-us as we assume all channels-from-us
522 // will have the same effective-fee
523 total_fee += new_fee;
524 if let Some(fee_inc) = final_value_msat.checked_add(total_fee).and_then(|inc| { (old_entry.2 as u64).checked_mul(inc) }) {
525 total_fee += fee_inc / 1000000 + (old_entry.1 as u64);
527 // max_value means we'll always fail the old_entry.0 > total_fee check
528 total_fee = u64::max_value();
531 let new_graph_node = RouteGraphNode {
532 pubkey: $directional_info.src_node_id,
533 lowest_fee_to_peer_through_node: total_fee,
534 lowest_fee_to_node: $starting_fee_msat as u64 + new_fee,
536 if old_entry.0 > total_fee {
537 targets.push(new_graph_node);
538 old_entry.0 = total_fee;
539 old_entry.3 = RouteHop {
540 pubkey: $dest_node_id.clone(),
541 short_channel_id: $chan_id.clone(),
542 fee_msat: new_fee, // This field is ignored on the last-hop anyway
543 cltv_expiry_delta: $directional_info.cltv_expiry_delta as u32,
551 macro_rules! add_entries_to_cheapest_to_target_node {
552 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr ) => {
553 if first_hops.is_some() {
554 if let Some(first_hop) = first_hop_targets.get(&$node_id) {
555 add_entry!(first_hop, $node_id, dummy_directional_info, $fee_to_target_msat);
559 for chan_id in $node.channels.iter() {
560 let chan = network.channels.get(chan_id).unwrap();
561 if chan.one_to_two.src_node_id == *$node_id {
562 // ie $node is one, ie next hop in A* is two, via the two_to_one channel
563 if first_hops.is_none() || chan.two_to_one.src_node_id != network.our_node_id {
564 if chan.two_to_one.enabled {
565 add_entry!(chan_id, chan.one_to_two.src_node_id, chan.two_to_one, $fee_to_target_msat);
569 if first_hops.is_none() || chan.one_to_two.src_node_id != network.our_node_id {
570 if chan.one_to_two.enabled {
571 add_entry!(chan_id, chan.two_to_one.src_node_id, chan.one_to_two, $fee_to_target_msat);
579 match network.nodes.get(target) {
582 add_entries_to_cheapest_to_target_node!(node, target, 0);
586 for hop in last_hops.iter() {
587 if first_hops.is_none() || hop.src_node_id != network.our_node_id { // first_hop overrules last_hops
588 if network.nodes.get(&hop.src_node_id).is_some() {
589 if first_hops.is_some() {
590 if let Some(first_hop) = first_hop_targets.get(&hop.src_node_id) {
591 add_entry!(first_hop, hop.src_node_id, dummy_directional_info, 0);
594 add_entry!(hop.short_channel_id, target, hop, 0);
599 while let Some(RouteGraphNode { pubkey, lowest_fee_to_node, .. }) = targets.pop() {
600 if pubkey == network.our_node_id {
601 let mut res = vec!(dist.remove(&network.our_node_id).unwrap().3);
602 while res.last().unwrap().pubkey != *target {
603 let new_entry = match dist.remove(&res.last().unwrap().pubkey) {
605 None => return Err(HandleError{err: "Failed to find a non-fee-overflowing path to the given destination", action: None}),
607 res.last_mut().unwrap().fee_msat = new_entry.fee_msat;
608 res.last_mut().unwrap().cltv_expiry_delta = new_entry.cltv_expiry_delta;
611 res.last_mut().unwrap().fee_msat = final_value_msat;
612 res.last_mut().unwrap().cltv_expiry_delta = final_cltv;
618 match network.nodes.get(&pubkey) {
621 add_entries_to_cheapest_to_target_node!(node, &pubkey, lowest_fee_to_node);
626 Err(HandleError{err: "Failed to find a path to the given destination", action: None})
632 use ln::channelmanager;
633 use ln::router::{Router,NodeInfo,NetworkMap,ChannelInfo,DirectionalChannelInfo,RouteHint};
634 use ln::msgs::GlobalFeatures;
635 use util::test_utils;
636 use util::logger::Logger;
638 use bitcoin::util::hash::Sha256dHash;
642 use secp256k1::key::{PublicKey,SecretKey};
643 use secp256k1::Secp256k1;
649 let secp_ctx = Secp256k1::new();
650 let our_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap()).unwrap();
651 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
652 let router = Router::new(our_id, Arc::clone(&logger));
654 // Build network from our_id to node8:
656 // -1(1)2- node1 -1(3)2-
658 // our_id -1(12)2- node8 -1(13)2--- node3
660 // -1(2)2- node2 -1(4)2-
663 // chan1 1-to-2: disabled
664 // chan1 2-to-1: enabled, 0 fee
666 // chan2 1-to-2: enabled, ignored fee
667 // chan2 2-to-1: enabled, 0 fee
669 // chan3 1-to-2: enabled, 0 fee
670 // chan3 2-to-1: enabled, 100 msat fee
672 // chan4 1-to-2: enabled, 100% fee
673 // chan4 2-to-1: enabled, 0 fee
675 // chan12 1-to-2: enabled, ignored fee
676 // chan12 2-to-1: enabled, 0 fee
678 // chan13 1-to-2: enabled, 200% fee
679 // chan13 2-to-1: enabled, 0 fee
682 // -1(5)2- node4 -1(8)2--
686 // node3--1(6)2- node5 -1(9)2--- node7 (not in global route map)
688 // -1(7)2- node6 -1(10)2-
690 // chan5 1-to-2: enabled, 100 msat fee
691 // chan5 2-to-1: enabled, 0 fee
693 // chan6 1-to-2: enabled, 0 fee
694 // chan6 2-to-1: enabled, 0 fee
696 // chan7 1-to-2: enabled, 100% fee
697 // chan7 2-to-1: enabled, 0 fee
699 // chan8 1-to-2: enabled, variable fee (0 then 1000 msat)
700 // chan8 2-to-1: enabled, 0 fee
702 // chan9 1-to-2: enabled, 1001 msat fee
703 // chan9 2-to-1: enabled, 0 fee
705 // chan10 1-to-2: enabled, 0 fee
706 // chan10 2-to-1: enabled, 0 fee
708 // chan11 1-to-2: enabled, 0 fee
709 // chan11 2-to-1: enabled, 0 fee
711 let node1 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap()[..]).unwrap()).unwrap();
712 let node2 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0303030303030303030303030303030303030303030303030303030303030303").unwrap()[..]).unwrap()).unwrap();
713 let node3 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0404040404040404040404040404040404040404040404040404040404040404").unwrap()[..]).unwrap()).unwrap();
714 let node4 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0505050505050505050505050505050505050505050505050505050505050505").unwrap()[..]).unwrap()).unwrap();
715 let node5 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0606060606060606060606060606060606060606060606060606060606060606").unwrap()[..]).unwrap()).unwrap();
716 let node6 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0707070707070707070707070707070707070707070707070707070707070707").unwrap()[..]).unwrap()).unwrap();
717 let node7 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0808080808080808080808080808080808080808080808080808080808080808").unwrap()[..]).unwrap()).unwrap();
718 let node8 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0909090909090909090909090909090909090909090909090909090909090909").unwrap()[..]).unwrap()).unwrap();
720 let zero_hash = Sha256dHash::from_data(&[0; 32]);
723 let mut network = router.network_map.write().unwrap();
725 network.nodes.insert(node1.clone(), NodeInfo {
726 channels: vec!(NetworkMap::get_key(1, zero_hash.clone()), NetworkMap::get_key(3, zero_hash.clone())),
727 lowest_inbound_channel_fee_base_msat: 100,
728 lowest_inbound_channel_fee_proportional_millionths: 0,
729 features: GlobalFeatures::new(),
733 addresses: Vec::new(),
735 network.channels.insert(NetworkMap::get_key(1, zero_hash.clone()), ChannelInfo {
736 features: GlobalFeatures::new(),
737 one_to_two: DirectionalChannelInfo {
738 src_node_id: our_id.clone(),
741 cltv_expiry_delta: u16::max_value(), // This value should be ignored
742 htlc_minimum_msat: 0,
743 fee_base_msat: u32::max_value(), // This value should be ignored
744 fee_proportional_millionths: u32::max_value(), // This value should be ignored
745 }, two_to_one: DirectionalChannelInfo {
746 src_node_id: node1.clone(),
749 cltv_expiry_delta: 0,
750 htlc_minimum_msat: 0,
752 fee_proportional_millionths: 0,
755 network.nodes.insert(node2.clone(), NodeInfo {
756 channels: vec!(NetworkMap::get_key(2, zero_hash.clone()), NetworkMap::get_key(4, zero_hash.clone())),
757 lowest_inbound_channel_fee_base_msat: 0,
758 lowest_inbound_channel_fee_proportional_millionths: 0,
759 features: GlobalFeatures::new(),
763 addresses: Vec::new(),
765 network.channels.insert(NetworkMap::get_key(2, zero_hash.clone()), ChannelInfo {
766 features: GlobalFeatures::new(),
767 one_to_two: DirectionalChannelInfo {
768 src_node_id: our_id.clone(),
771 cltv_expiry_delta: u16::max_value(), // This value should be ignored
772 htlc_minimum_msat: 0,
773 fee_base_msat: u32::max_value(), // This value should be ignored
774 fee_proportional_millionths: u32::max_value(), // This value should be ignored
775 }, two_to_one: DirectionalChannelInfo {
776 src_node_id: node2.clone(),
779 cltv_expiry_delta: 0,
780 htlc_minimum_msat: 0,
782 fee_proportional_millionths: 0,
785 network.nodes.insert(node8.clone(), NodeInfo {
786 channels: vec!(NetworkMap::get_key(12, zero_hash.clone()), NetworkMap::get_key(13, zero_hash.clone())),
787 lowest_inbound_channel_fee_base_msat: 0,
788 lowest_inbound_channel_fee_proportional_millionths: 0,
789 features: GlobalFeatures::new(),
793 addresses: Vec::new(),
795 network.channels.insert(NetworkMap::get_key(12, zero_hash.clone()), ChannelInfo {
796 features: GlobalFeatures::new(),
797 one_to_two: DirectionalChannelInfo {
798 src_node_id: our_id.clone(),
801 cltv_expiry_delta: u16::max_value(), // This value should be ignored
802 htlc_minimum_msat: 0,
803 fee_base_msat: u32::max_value(), // This value should be ignored
804 fee_proportional_millionths: u32::max_value(), // This value should be ignored
805 }, two_to_one: DirectionalChannelInfo {
806 src_node_id: node8.clone(),
809 cltv_expiry_delta: 0,
810 htlc_minimum_msat: 0,
812 fee_proportional_millionths: 0,
815 network.nodes.insert(node3.clone(), NodeInfo {
817 NetworkMap::get_key(3, zero_hash.clone()),
818 NetworkMap::get_key(4, zero_hash.clone()),
819 NetworkMap::get_key(13, zero_hash.clone()),
820 NetworkMap::get_key(5, zero_hash.clone()),
821 NetworkMap::get_key(6, zero_hash.clone()),
822 NetworkMap::get_key(7, zero_hash.clone())),
823 lowest_inbound_channel_fee_base_msat: 0,
824 lowest_inbound_channel_fee_proportional_millionths: 0,
825 features: GlobalFeatures::new(),
829 addresses: Vec::new(),
831 network.channels.insert(NetworkMap::get_key(3, zero_hash.clone()), ChannelInfo {
832 features: GlobalFeatures::new(),
833 one_to_two: DirectionalChannelInfo {
834 src_node_id: node1.clone(),
837 cltv_expiry_delta: (3 << 8) | 1,
838 htlc_minimum_msat: 0,
840 fee_proportional_millionths: 0,
841 }, two_to_one: DirectionalChannelInfo {
842 src_node_id: node3.clone(),
845 cltv_expiry_delta: (3 << 8) | 2,
846 htlc_minimum_msat: 0,
848 fee_proportional_millionths: 0,
851 network.channels.insert(NetworkMap::get_key(4, zero_hash.clone()), ChannelInfo {
852 features: GlobalFeatures::new(),
853 one_to_two: DirectionalChannelInfo {
854 src_node_id: node2.clone(),
857 cltv_expiry_delta: (4 << 8) | 1,
858 htlc_minimum_msat: 0,
860 fee_proportional_millionths: 1000000,
861 }, two_to_one: DirectionalChannelInfo {
862 src_node_id: node3.clone(),
865 cltv_expiry_delta: (4 << 8) | 2,
866 htlc_minimum_msat: 0,
868 fee_proportional_millionths: 0,
871 network.channels.insert(NetworkMap::get_key(13, zero_hash.clone()), ChannelInfo {
872 features: GlobalFeatures::new(),
873 one_to_two: DirectionalChannelInfo {
874 src_node_id: node8.clone(),
877 cltv_expiry_delta: (13 << 8) | 1,
878 htlc_minimum_msat: 0,
880 fee_proportional_millionths: 2000000,
881 }, two_to_one: DirectionalChannelInfo {
882 src_node_id: node3.clone(),
885 cltv_expiry_delta: (13 << 8) | 2,
886 htlc_minimum_msat: 0,
888 fee_proportional_millionths: 0,
891 network.nodes.insert(node4.clone(), NodeInfo {
892 channels: vec!(NetworkMap::get_key(5, zero_hash.clone()), NetworkMap::get_key(11, zero_hash.clone())),
893 lowest_inbound_channel_fee_base_msat: 0,
894 lowest_inbound_channel_fee_proportional_millionths: 0,
895 features: GlobalFeatures::new(),
899 addresses: Vec::new(),
901 network.channels.insert(NetworkMap::get_key(5, zero_hash.clone()), ChannelInfo {
902 features: GlobalFeatures::new(),
903 one_to_two: DirectionalChannelInfo {
904 src_node_id: node3.clone(),
907 cltv_expiry_delta: (5 << 8) | 1,
908 htlc_minimum_msat: 0,
910 fee_proportional_millionths: 0,
911 }, two_to_one: DirectionalChannelInfo {
912 src_node_id: node4.clone(),
915 cltv_expiry_delta: (5 << 8) | 2,
916 htlc_minimum_msat: 0,
918 fee_proportional_millionths: 0,
921 network.nodes.insert(node5.clone(), NodeInfo {
922 channels: vec!(NetworkMap::get_key(6, zero_hash.clone()), NetworkMap::get_key(11, zero_hash.clone())),
923 lowest_inbound_channel_fee_base_msat: 0,
924 lowest_inbound_channel_fee_proportional_millionths: 0,
925 features: GlobalFeatures::new(),
929 addresses: Vec::new(),
931 network.channels.insert(NetworkMap::get_key(6, zero_hash.clone()), ChannelInfo {
932 features: GlobalFeatures::new(),
933 one_to_two: DirectionalChannelInfo {
934 src_node_id: node3.clone(),
937 cltv_expiry_delta: (6 << 8) | 1,
938 htlc_minimum_msat: 0,
940 fee_proportional_millionths: 0,
941 }, two_to_one: DirectionalChannelInfo {
942 src_node_id: node5.clone(),
945 cltv_expiry_delta: (6 << 8) | 2,
946 htlc_minimum_msat: 0,
948 fee_proportional_millionths: 0,
951 network.channels.insert(NetworkMap::get_key(11, zero_hash.clone()), ChannelInfo {
952 features: GlobalFeatures::new(),
953 one_to_two: DirectionalChannelInfo {
954 src_node_id: node5.clone(),
957 cltv_expiry_delta: (11 << 8) | 1,
958 htlc_minimum_msat: 0,
960 fee_proportional_millionths: 0,
961 }, two_to_one: DirectionalChannelInfo {
962 src_node_id: node4.clone(),
965 cltv_expiry_delta: (11 << 8) | 2,
966 htlc_minimum_msat: 0,
968 fee_proportional_millionths: 0,
971 network.nodes.insert(node6.clone(), NodeInfo {
972 channels: vec!(NetworkMap::get_key(7, zero_hash.clone())),
973 lowest_inbound_channel_fee_base_msat: 0,
974 lowest_inbound_channel_fee_proportional_millionths: 0,
975 features: GlobalFeatures::new(),
979 addresses: Vec::new(),
981 network.channels.insert(NetworkMap::get_key(7, zero_hash.clone()), ChannelInfo {
982 features: GlobalFeatures::new(),
983 one_to_two: DirectionalChannelInfo {
984 src_node_id: node3.clone(),
987 cltv_expiry_delta: (7 << 8) | 1,
988 htlc_minimum_msat: 0,
990 fee_proportional_millionths: 1000000,
991 }, two_to_one: DirectionalChannelInfo {
992 src_node_id: node6.clone(),
995 cltv_expiry_delta: (7 << 8) | 2,
996 htlc_minimum_msat: 0,
998 fee_proportional_millionths: 0,
1003 { // Simple route to 3 via 2
1004 let route = router.get_route(&node3, None, &Vec::new(), 100, 42).unwrap();
1005 assert_eq!(route.hops.len(), 2);
1007 assert_eq!(route.hops[0].pubkey, node2);
1008 assert_eq!(route.hops[0].short_channel_id, 2);
1009 assert_eq!(route.hops[0].fee_msat, 100);
1010 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1012 assert_eq!(route.hops[1].pubkey, node3);
1013 assert_eq!(route.hops[1].short_channel_id, 4);
1014 assert_eq!(route.hops[1].fee_msat, 100);
1015 assert_eq!(route.hops[1].cltv_expiry_delta, 42);
1018 { // Route to 1 via 2 and 3 because our channel to 1 is disabled
1019 let route = router.get_route(&node1, None, &Vec::new(), 100, 42).unwrap();
1020 assert_eq!(route.hops.len(), 3);
1022 assert_eq!(route.hops[0].pubkey, node2);
1023 assert_eq!(route.hops[0].short_channel_id, 2);
1024 assert_eq!(route.hops[0].fee_msat, 200);
1025 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1027 assert_eq!(route.hops[1].pubkey, node3);
1028 assert_eq!(route.hops[1].short_channel_id, 4);
1029 assert_eq!(route.hops[1].fee_msat, 100);
1030 assert_eq!(route.hops[1].cltv_expiry_delta, (3 << 8) | 2);
1032 assert_eq!(route.hops[2].pubkey, node1);
1033 assert_eq!(route.hops[2].short_channel_id, 3);
1034 assert_eq!(route.hops[2].fee_msat, 100);
1035 assert_eq!(route.hops[2].cltv_expiry_delta, 42);
1038 { // If we specify a channel to node8, that overrides our local channel view and that gets used
1039 let our_chans = vec![channelmanager::ChannelDetails {
1040 channel_id: [0; 32],
1041 short_channel_id: Some(42),
1042 remote_network_id: node8.clone(),
1043 channel_value_satoshis: 0,
1046 let route = router.get_route(&node3, Some(&our_chans), &Vec::new(), 100, 42).unwrap();
1047 assert_eq!(route.hops.len(), 2);
1049 assert_eq!(route.hops[0].pubkey, node8);
1050 assert_eq!(route.hops[0].short_channel_id, 42);
1051 assert_eq!(route.hops[0].fee_msat, 200);
1052 assert_eq!(route.hops[0].cltv_expiry_delta, (13 << 8) | 1);
1054 assert_eq!(route.hops[1].pubkey, node3);
1055 assert_eq!(route.hops[1].short_channel_id, 13);
1056 assert_eq!(route.hops[1].fee_msat, 100);
1057 assert_eq!(route.hops[1].cltv_expiry_delta, 42);
1060 let mut last_hops = vec!(RouteHint {
1061 src_node_id: node4.clone(),
1062 short_channel_id: 8,
1064 fee_proportional_millionths: 0,
1065 cltv_expiry_delta: (8 << 8) | 1,
1066 htlc_minimum_msat: 0,
1068 src_node_id: node5.clone(),
1069 short_channel_id: 9,
1070 fee_base_msat: 1001,
1071 fee_proportional_millionths: 0,
1072 cltv_expiry_delta: (9 << 8) | 1,
1073 htlc_minimum_msat: 0,
1075 src_node_id: node6.clone(),
1076 short_channel_id: 10,
1078 fee_proportional_millionths: 0,
1079 cltv_expiry_delta: (10 << 8) | 1,
1080 htlc_minimum_msat: 0,
1083 { // Simple test across 2, 3, 5, and 4 via a last_hop channel
1084 let route = router.get_route(&node7, None, &last_hops, 100, 42).unwrap();
1085 assert_eq!(route.hops.len(), 5);
1087 assert_eq!(route.hops[0].pubkey, node2);
1088 assert_eq!(route.hops[0].short_channel_id, 2);
1089 assert_eq!(route.hops[0].fee_msat, 100);
1090 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1092 assert_eq!(route.hops[1].pubkey, node3);
1093 assert_eq!(route.hops[1].short_channel_id, 4);
1094 assert_eq!(route.hops[1].fee_msat, 0);
1095 assert_eq!(route.hops[1].cltv_expiry_delta, (6 << 8) | 1);
1097 assert_eq!(route.hops[2].pubkey, node5);
1098 assert_eq!(route.hops[2].short_channel_id, 6);
1099 assert_eq!(route.hops[2].fee_msat, 0);
1100 assert_eq!(route.hops[2].cltv_expiry_delta, (11 << 8) | 1);
1102 assert_eq!(route.hops[3].pubkey, node4);
1103 assert_eq!(route.hops[3].short_channel_id, 11);
1104 assert_eq!(route.hops[3].fee_msat, 0);
1105 assert_eq!(route.hops[3].cltv_expiry_delta, (8 << 8) | 1);
1107 assert_eq!(route.hops[4].pubkey, node7);
1108 assert_eq!(route.hops[4].short_channel_id, 8);
1109 assert_eq!(route.hops[4].fee_msat, 100);
1110 assert_eq!(route.hops[4].cltv_expiry_delta, 42);
1113 { // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
1114 let our_chans = vec![channelmanager::ChannelDetails {
1115 channel_id: [0; 32],
1116 short_channel_id: Some(42),
1117 remote_network_id: node4.clone(),
1118 channel_value_satoshis: 0,
1121 let route = router.get_route(&node7, Some(&our_chans), &last_hops, 100, 42).unwrap();
1122 assert_eq!(route.hops.len(), 2);
1124 assert_eq!(route.hops[0].pubkey, node4);
1125 assert_eq!(route.hops[0].short_channel_id, 42);
1126 assert_eq!(route.hops[0].fee_msat, 0);
1127 assert_eq!(route.hops[0].cltv_expiry_delta, (8 << 8) | 1);
1129 assert_eq!(route.hops[1].pubkey, node7);
1130 assert_eq!(route.hops[1].short_channel_id, 8);
1131 assert_eq!(route.hops[1].fee_msat, 100);
1132 assert_eq!(route.hops[1].cltv_expiry_delta, 42);
1135 last_hops[0].fee_base_msat = 1000;
1137 { // Revert to via 6 as the fee on 8 goes up
1138 let route = router.get_route(&node7, None, &last_hops, 100, 42).unwrap();
1139 assert_eq!(route.hops.len(), 4);
1141 assert_eq!(route.hops[0].pubkey, node2);
1142 assert_eq!(route.hops[0].short_channel_id, 2);
1143 assert_eq!(route.hops[0].fee_msat, 200); // fee increased as its % of value transferred across node
1144 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1146 assert_eq!(route.hops[1].pubkey, node3);
1147 assert_eq!(route.hops[1].short_channel_id, 4);
1148 assert_eq!(route.hops[1].fee_msat, 100);
1149 assert_eq!(route.hops[1].cltv_expiry_delta, (7 << 8) | 1);
1151 assert_eq!(route.hops[2].pubkey, node6);
1152 assert_eq!(route.hops[2].short_channel_id, 7);
1153 assert_eq!(route.hops[2].fee_msat, 0);
1154 assert_eq!(route.hops[2].cltv_expiry_delta, (10 << 8) | 1);
1156 assert_eq!(route.hops[3].pubkey, node7);
1157 assert_eq!(route.hops[3].short_channel_id, 10);
1158 assert_eq!(route.hops[3].fee_msat, 100);
1159 assert_eq!(route.hops[3].cltv_expiry_delta, 42);
1162 { // ...but still use 8 for larger payments as 6 has a variable feerate
1163 let route = router.get_route(&node7, None, &last_hops, 2000, 42).unwrap();
1164 assert_eq!(route.hops.len(), 5);
1166 assert_eq!(route.hops[0].pubkey, node2);
1167 assert_eq!(route.hops[0].short_channel_id, 2);
1168 assert_eq!(route.hops[0].fee_msat, 3000);
1169 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1171 assert_eq!(route.hops[1].pubkey, node3);
1172 assert_eq!(route.hops[1].short_channel_id, 4);
1173 assert_eq!(route.hops[1].fee_msat, 0);
1174 assert_eq!(route.hops[1].cltv_expiry_delta, (6 << 8) | 1);
1176 assert_eq!(route.hops[2].pubkey, node5);
1177 assert_eq!(route.hops[2].short_channel_id, 6);
1178 assert_eq!(route.hops[2].fee_msat, 0);
1179 assert_eq!(route.hops[2].cltv_expiry_delta, (11 << 8) | 1);
1181 assert_eq!(route.hops[3].pubkey, node4);
1182 assert_eq!(route.hops[3].short_channel_id, 11);
1183 assert_eq!(route.hops[3].fee_msat, 1000);
1184 assert_eq!(route.hops[3].cltv_expiry_delta, (8 << 8) | 1);
1186 assert_eq!(route.hops[4].pubkey, node7);
1187 assert_eq!(route.hops[4].short_channel_id, 8);
1188 assert_eq!(route.hops[4].fee_msat, 2000);
1189 assert_eq!(route.hops[4].cltv_expiry_delta, 42);