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;
19 pub pubkey: PublicKey,
20 /// The channel that should be used from the previous hop to reach this node.
21 pub short_channel_id: u64,
22 /// The fee taken on this hop. For the last hop, this should be the full value of the payment.
24 /// The CLTV delta added for this hop. For the last hop, this should be the full CLTV value
25 /// expected at the destination, in excess of the current block height.
26 pub cltv_expiry_delta: u32,
29 /// A route from us through the network to a destination
32 /// The list of hops, NOT INCLUDING our own, where the last hop is the destination. Thus, this
33 /// must always be at least length one. By protocol rules, this may not currently exceed 20 in
35 pub hops: Vec<RouteHop>,
38 struct DirectionalChannelInfo {
39 src_node_id: PublicKey,
42 cltv_expiry_delta: u16,
43 htlc_minimum_msat: u64,
45 fee_proportional_millionths: u32,
49 features: GlobalFeatures,
50 one_to_two: DirectionalChannelInfo,
51 two_to_one: DirectionalChannelInfo,
55 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
56 channels: Vec<(u64, Sha256dHash)>,
57 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
60 lowest_inbound_channel_fee_base_msat: u32,
61 lowest_inbound_channel_fee_proportional_millionths: u32,
63 features: GlobalFeatures,
67 addresses: Vec<NetAddress>,
71 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
72 channels: HashMap<(u64, Sha256dHash), ChannelInfo>,
73 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
74 channels: HashMap<u64, ChannelInfo>,
76 our_node_id: PublicKey,
77 nodes: HashMap<PublicKey, NodeInfo>,
81 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
83 fn get_key(short_channel_id: u64, chain_hash: Sha256dHash) -> (u64, Sha256dHash) {
84 (short_channel_id, chain_hash)
87 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
89 fn get_key(short_channel_id: u64, _: Sha256dHash) -> u64 {
93 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
95 fn get_short_id(id: &(u64, Sha256dHash)) -> &u64 {
99 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
101 fn get_short_id(id: &u64) -> &u64 {
106 /// A channel descriptor which provides a last-hop route to get_route
107 pub struct RouteHint {
108 pub src_node_id: PublicKey,
109 pub short_channel_id: u64,
110 pub fee_base_msat: u32,
111 pub fee_proportional_millionths: u32,
112 pub cltv_expiry_delta: u16,
113 pub htlc_minimum_msat: u64,
116 /// Tracks a view of the network, receiving updates from peers and generating Routes to
117 /// payment destinations.
120 network_map: RwLock<NetworkMap>,
124 macro_rules! secp_verify_sig {
125 ( $secp_ctx: expr, $msg: expr, $sig: expr, $pubkey: expr ) => {
126 match $secp_ctx.verify($msg, $sig, $pubkey) {
128 Err(_) => return Err(HandleError{err: "Invalid signature from remote node", action: None}),
133 impl RoutingMessageHandler for Router {
134 fn handle_node_announcement(&self, msg: &msgs::NodeAnnouncement) -> Result<(), HandleError> {
135 let msg_hash = Message::from_slice(&Sha256dHash::from_data(&msg.contents.encode()[..])[..]).unwrap();
136 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.signature, &msg.contents.node_id);
138 let mut network = self.network_map.write().unwrap();
139 match network.nodes.get_mut(&msg.contents.node_id) {
140 None => Err(HandleError{err: "No existing channels for node_announcement", action: Some(ErrorAction::IgnoreError)}),
142 if node.last_update >= msg.contents.timestamp {
143 return Err(HandleError{err: "Update older than last processed update", action: Some(ErrorAction::IgnoreError)});
146 node.features = msg.contents.features.clone();
147 node.last_update = msg.contents.timestamp;
148 node.rgb = msg.contents.rgb;
149 node.alias = msg.contents.alias;
150 node.addresses = msg.contents.addresses.clone();
156 fn handle_channel_announcement(&self, msg: &msgs::ChannelAnnouncement) -> Result<bool, HandleError> {
157 let msg_hash = Message::from_slice(&Sha256dHash::from_data(&msg.contents.encode()[..])[..]).unwrap();
158 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.node_signature_1, &msg.contents.node_id_1);
159 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.node_signature_2, &msg.contents.node_id_2);
160 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.bitcoin_signature_1, &msg.contents.bitcoin_key_1);
161 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.bitcoin_signature_2, &msg.contents.bitcoin_key_2);
163 //TODO: Call blockchain thing to ask if the short_channel_id is valid
164 //TODO: Only allow bitcoin chain_hash
166 if msg.contents.features.requires_unknown_bits() {
167 return Err(HandleError{err: "Channel announcement required unknown feature flags", action: None});
170 let mut network = self.network_map.write().unwrap();
172 match network.channels.entry(NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash)) {
173 Entry::Occupied(_) => {
174 //TODO: because asking the blockchain if short_channel_id is valid is only optional
175 //in the blockchain API, we need to handle it smartly here, though its unclear
177 return Err(HandleError{err: "Already have knowledge of channel", action: Some(ErrorAction::IgnoreError)})
179 Entry::Vacant(entry) => {
180 entry.insert(ChannelInfo {
181 features: msg.contents.features.clone(),
182 one_to_two: DirectionalChannelInfo {
183 src_node_id: msg.contents.node_id_1.clone(),
186 cltv_expiry_delta: u16::max_value(),
187 htlc_minimum_msat: u64::max_value(),
188 fee_base_msat: u32::max_value(),
189 fee_proportional_millionths: u32::max_value(),
191 two_to_one: DirectionalChannelInfo {
192 src_node_id: msg.contents.node_id_2.clone(),
195 cltv_expiry_delta: u16::max_value(),
196 htlc_minimum_msat: u64::max_value(),
197 fee_base_msat: u32::max_value(),
198 fee_proportional_millionths: u32::max_value(),
204 macro_rules! add_channel_to_node {
205 ( $node_id: expr ) => {
206 match network.nodes.entry($node_id) {
207 Entry::Occupied(node_entry) => {
208 node_entry.into_mut().channels.push(NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash));
210 Entry::Vacant(node_entry) => {
211 node_entry.insert(NodeInfo {
212 channels: vec!(NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash)),
213 lowest_inbound_channel_fee_base_msat: u32::max_value(),
214 lowest_inbound_channel_fee_proportional_millionths: u32::max_value(),
215 features: GlobalFeatures::new(),
219 addresses: Vec::new(),
226 add_channel_to_node!(msg.contents.node_id_1);
227 add_channel_to_node!(msg.contents.node_id_2);
229 Ok(!msg.contents.features.supports_unknown_bits())
232 fn handle_htlc_fail_channel_update(&self, update: &msgs::HTLCFailChannelUpdate) {
234 &msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg } => {
235 let _ = self.handle_channel_update(msg);
237 &msgs::HTLCFailChannelUpdate::ChannelClosed { ref short_channel_id } => {
238 let mut network = self.network_map.write().unwrap();
239 if let Some(chan) = network.channels.remove(short_channel_id) {
240 network.nodes.get_mut(&chan.one_to_two.src_node_id).unwrap().channels.retain(|chan_id| {
241 chan_id != NetworkMap::get_short_id(chan_id)
243 network.nodes.get_mut(&chan.two_to_one.src_node_id).unwrap().channels.retain(|chan_id| {
244 chan_id != NetworkMap::get_short_id(chan_id)
251 fn handle_channel_update(&self, msg: &msgs::ChannelUpdate) -> Result<(), HandleError> {
252 let mut network = self.network_map.write().unwrap();
254 let chan_enabled = msg.contents.flags & (1 << 1) != (1 << 1);
255 let chan_was_enabled;
257 match network.channels.get_mut(&NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash)) {
258 None => return Err(HandleError{err: "Couldn't find channel for update", action: Some(ErrorAction::IgnoreError)}),
260 macro_rules! maybe_update_channel_info {
261 ( $target: expr) => {
262 if $target.last_update >= msg.contents.timestamp {
263 return Err(HandleError{err: "Update older than last processed update", action: Some(ErrorAction::IgnoreError)});
265 chan_was_enabled = $target.enabled;
266 $target.last_update = msg.contents.timestamp;
267 $target.enabled = chan_enabled;
268 $target.cltv_expiry_delta = msg.contents.cltv_expiry_delta;
269 $target.htlc_minimum_msat = msg.contents.htlc_minimum_msat;
270 $target.fee_base_msat = msg.contents.fee_base_msat;
271 $target.fee_proportional_millionths = msg.contents.fee_proportional_millionths;
275 let msg_hash = Message::from_slice(&Sha256dHash::from_data(&msg.contents.encode()[..])[..]).unwrap();
276 if msg.contents.flags & 1 == 1 {
277 dest_node_id = channel.one_to_two.src_node_id.clone();
278 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.signature, &channel.two_to_one.src_node_id);
279 maybe_update_channel_info!(channel.two_to_one);
281 dest_node_id = channel.two_to_one.src_node_id.clone();
282 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.signature, &channel.one_to_two.src_node_id);
283 maybe_update_channel_info!(channel.one_to_two);
289 let node = network.nodes.get_mut(&dest_node_id).unwrap();
290 node.lowest_inbound_channel_fee_base_msat = cmp::min(node.lowest_inbound_channel_fee_base_msat, msg.contents.fee_base_msat);
291 node.lowest_inbound_channel_fee_proportional_millionths = cmp::min(node.lowest_inbound_channel_fee_proportional_millionths, msg.contents.fee_proportional_millionths);
292 } else if chan_was_enabled {
293 let mut lowest_inbound_channel_fee_base_msat = u32::max_value();
294 let mut lowest_inbound_channel_fee_proportional_millionths = u32::max_value();
297 let node = network.nodes.get(&dest_node_id).unwrap();
299 for chan_id in node.channels.iter() {
300 let chan = network.channels.get(chan_id).unwrap();
301 if chan.one_to_two.src_node_id == dest_node_id {
302 lowest_inbound_channel_fee_base_msat = cmp::min(lowest_inbound_channel_fee_base_msat, chan.two_to_one.fee_base_msat);
303 lowest_inbound_channel_fee_proportional_millionths = cmp::min(lowest_inbound_channel_fee_proportional_millionths, chan.two_to_one.fee_proportional_millionths);
305 lowest_inbound_channel_fee_base_msat = cmp::min(lowest_inbound_channel_fee_base_msat, chan.one_to_two.fee_base_msat);
306 lowest_inbound_channel_fee_proportional_millionths = cmp::min(lowest_inbound_channel_fee_proportional_millionths, chan.one_to_two.fee_proportional_millionths);
311 //TODO: satisfy the borrow-checker without a double-map-lookup :(
312 let mut_node = network.nodes.get_mut(&dest_node_id).unwrap();
313 mut_node.lowest_inbound_channel_fee_base_msat = lowest_inbound_channel_fee_base_msat;
314 mut_node.lowest_inbound_channel_fee_proportional_millionths = lowest_inbound_channel_fee_proportional_millionths;
321 #[derive(Eq, PartialEq)]
322 struct RouteGraphNode {
324 lowest_fee_to_peer_through_node: u64,
325 lowest_fee_to_node: u64,
328 impl cmp::Ord for RouteGraphNode {
329 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
330 other.lowest_fee_to_peer_through_node.cmp(&self.lowest_fee_to_peer_through_node)
331 .then_with(|| other.pubkey.serialize().cmp(&self.pubkey.serialize()))
335 impl cmp::PartialOrd for RouteGraphNode {
336 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
337 Some(self.cmp(other))
341 struct DummyDirectionalChannelInfo {
342 src_node_id: PublicKey,
343 cltv_expiry_delta: u32,
344 htlc_minimum_msat: u64,
346 fee_proportional_millionths: u32,
350 pub fn new(our_pubkey: PublicKey, logger: Arc<Logger>) -> Router {
351 let mut nodes = HashMap::new();
352 nodes.insert(our_pubkey.clone(), NodeInfo {
353 channels: Vec::new(),
354 lowest_inbound_channel_fee_base_msat: u32::max_value(),
355 lowest_inbound_channel_fee_proportional_millionths: u32::max_value(),
356 features: GlobalFeatures::new(),
360 addresses: Vec::new(),
363 secp_ctx: Secp256k1::new(),
364 network_map: RwLock::new(NetworkMap {
365 channels: HashMap::new(),
366 our_node_id: our_pubkey,
373 /// Get network addresses by node id
374 pub fn get_addresses(&self, pubkey: &PublicKey) -> Option<Vec<NetAddress>> {
375 let network = self.network_map.read().unwrap();
376 network.nodes.get(pubkey).map(|n| n.addresses.clone())
379 /// Marks a node as having failed a route. This will avoid re-using the node in routes for now,
380 /// with an expotnential decay in node "badness". Note that there is deliberately no
381 /// mark_channel_bad as a node may simply lie and suggest that an upstream channel from it is
382 /// what failed the route and not the node itself. Instead, setting the blamed_upstream_node
383 /// boolean will reduce the penalty, returning the node to usability faster. If the node is
384 /// behaving correctly, it will disable the failing channel and we will use it again next time.
385 pub fn mark_node_bad(&self, _node_id: &PublicKey, _blamed_upstream_node: bool) {
389 /// Gets a route from us to the given target node.
390 /// Extra routing hops between known nodes and the target will be used if they are included in
392 /// If some channels aren't announced, it may be useful to fill in a first_hops with the
393 /// results from a local ChannelManager::list_usable_channels() call. If it is filled in, our
394 /// (this Router's) view of our local channels will be ignored, and only those in first_hops
395 /// will be used. Panics if first_hops contains channels without short_channel_ids
396 /// (ChannelManager::list_usable_channels will never include such channels).
397 /// The fees on channels from us to next-hops are ignored (as they are assumed to all be
398 /// equal), however the enabled/disabled bit on such channels as well as the htlc_minimum_msat
399 /// *is* checked as they may change based on the receiving node.
400 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> {
401 // TODO: Obviously *only* using total fee cost sucks. We should consider weighting by
402 // uptime/success in using a node in the past.
403 let network = self.network_map.read().unwrap();
405 if *target == network.our_node_id {
406 return Err(HandleError{err: "Cannot generate a route to ourselves", action: None});
409 if final_value_msat > 21_000_000 * 1_0000_0000 * 1000 {
410 return Err(HandleError{err: "Cannot generate a route of more value than all existing satoshis", action: None});
413 // We do a dest-to-source Dijkstra's sorting by each node's distance from the destination
414 // plus the minimum per-HTLC fee to get from it to another node (aka "shitty A*").
415 // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
416 // to use as the A* heuristic beyond just the cost to get one node further than the current
419 let dummy_directional_info = DummyDirectionalChannelInfo { // used for first_hops routes
420 src_node_id: network.our_node_id.clone(),
421 cltv_expiry_delta: 0,
422 htlc_minimum_msat: 0,
424 fee_proportional_millionths: 0,
427 let mut targets = BinaryHeap::new(); //TODO: Do we care about switching to eg Fibbonaci heap?
428 let mut dist = HashMap::with_capacity(network.nodes.len());
430 let mut first_hop_targets = HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
431 if let Some(hops) = first_hops {
433 let short_channel_id = chan.short_channel_id.expect("first_hops should be filled in with usable channels, not pending ones");
434 if chan.remote_network_id == *target {
436 hops: vec![RouteHop {
437 pubkey: chan.remote_network_id,
439 fee_msat: final_value_msat,
440 cltv_expiry_delta: final_cltv,
444 first_hop_targets.insert(chan.remote_network_id, short_channel_id);
446 if first_hop_targets.is_empty() {
447 return Err(HandleError{err: "Cannot route when there are no outbound routes away from us", action: None});
451 macro_rules! add_entry {
452 // Adds entry which goes from the node pointed to by $directional_info to
453 // $dest_node_id over the channel with id $chan_id with fees described in
454 // $directional_info.
455 ( $chan_id: expr, $dest_node_id: expr, $directional_info: expr, $starting_fee_msat: expr ) => {
456 //TODO: Explore simply adding fee to hit htlc_minimum_msat
457 if $starting_fee_msat as u64 + final_value_msat > $directional_info.htlc_minimum_msat {
458 let proportional_fee_millions = ($starting_fee_msat + final_value_msat).checked_mul($directional_info.fee_proportional_millionths as u64);
459 if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
460 ($directional_info.fee_base_msat as u64).checked_add(part / 1000000) })
462 let mut total_fee = $starting_fee_msat as u64;
463 let hm_entry = dist.entry(&$directional_info.src_node_id);
464 let old_entry = hm_entry.or_insert_with(|| {
465 let node = network.nodes.get(&$directional_info.src_node_id).unwrap();
467 node.lowest_inbound_channel_fee_base_msat,
468 node.lowest_inbound_channel_fee_proportional_millionths,
470 pubkey: $dest_node_id.clone(),
473 cltv_expiry_delta: 0,
476 if $directional_info.src_node_id != network.our_node_id {
477 // Ignore new_fee for channel-from-us as we assume all channels-from-us
478 // will have the same effective-fee
479 total_fee += new_fee;
480 if let Some(fee_inc) = final_value_msat.checked_add(total_fee).and_then(|inc| { (old_entry.2 as u64).checked_mul(inc) }) {
481 total_fee += fee_inc / 1000000 + (old_entry.1 as u64);
483 // max_value means we'll always fail the old_entry.0 > total_fee check
484 total_fee = u64::max_value();
487 let new_graph_node = RouteGraphNode {
488 pubkey: $directional_info.src_node_id,
489 lowest_fee_to_peer_through_node: total_fee,
490 lowest_fee_to_node: $starting_fee_msat as u64 + new_fee,
492 if old_entry.0 > total_fee {
493 targets.push(new_graph_node);
494 old_entry.0 = total_fee;
495 old_entry.3 = RouteHop {
496 pubkey: $dest_node_id.clone(),
497 short_channel_id: $chan_id.clone(),
498 fee_msat: new_fee, // This field is ignored on the last-hop anyway
499 cltv_expiry_delta: $directional_info.cltv_expiry_delta as u32,
507 macro_rules! add_entries_to_cheapest_to_target_node {
508 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr ) => {
509 if first_hops.is_some() {
510 if let Some(first_hop) = first_hop_targets.get(&$node_id) {
511 add_entry!(first_hop, $node_id, dummy_directional_info, $fee_to_target_msat);
515 for chan_id in $node.channels.iter() {
516 let chan = network.channels.get(chan_id).unwrap();
517 if chan.one_to_two.src_node_id == *$node_id {
518 // ie $node is one, ie next hop in A* is two, via the two_to_one channel
519 if first_hops.is_none() || chan.two_to_one.src_node_id != network.our_node_id {
520 if chan.two_to_one.enabled {
521 add_entry!(chan_id, chan.one_to_two.src_node_id, chan.two_to_one, $fee_to_target_msat);
525 if first_hops.is_none() || chan.one_to_two.src_node_id != network.our_node_id {
526 if chan.one_to_two.enabled {
527 add_entry!(chan_id, chan.two_to_one.src_node_id, chan.one_to_two, $fee_to_target_msat);
535 match network.nodes.get(target) {
538 add_entries_to_cheapest_to_target_node!(node, target, 0);
542 for hop in last_hops.iter() {
543 if first_hops.is_none() || hop.src_node_id != network.our_node_id { // first_hop overrules last_hops
544 if network.nodes.get(&hop.src_node_id).is_some() {
545 if first_hops.is_some() {
546 if let Some(first_hop) = first_hop_targets.get(&hop.src_node_id) {
547 add_entry!(first_hop, hop.src_node_id, dummy_directional_info, 0);
550 add_entry!(hop.short_channel_id, target, hop, 0);
555 while let Some(RouteGraphNode { pubkey, lowest_fee_to_node, .. }) = targets.pop() {
556 if pubkey == network.our_node_id {
557 let mut res = vec!(dist.remove(&network.our_node_id).unwrap().3);
558 while res.last().unwrap().pubkey != *target {
559 let new_entry = match dist.remove(&res.last().unwrap().pubkey) {
561 None => return Err(HandleError{err: "Failed to find a non-fee-overflowing path to the given destination", action: None}),
563 res.last_mut().unwrap().fee_msat = new_entry.fee_msat;
564 res.last_mut().unwrap().cltv_expiry_delta = new_entry.cltv_expiry_delta;
567 res.last_mut().unwrap().fee_msat = final_value_msat;
568 res.last_mut().unwrap().cltv_expiry_delta = final_cltv;
574 match network.nodes.get(&pubkey) {
577 add_entries_to_cheapest_to_target_node!(node, &pubkey, lowest_fee_to_node);
582 Err(HandleError{err: "Failed to find a path to the given destination", action: None})
588 use ln::channelmanager;
589 use ln::router::{Router,NodeInfo,NetworkMap,ChannelInfo,DirectionalChannelInfo,RouteHint};
590 use ln::msgs::GlobalFeatures;
591 use util::test_utils;
592 use util::logger::Logger;
594 use bitcoin::util::hash::Sha256dHash;
598 use secp256k1::key::{PublicKey,SecretKey};
599 use secp256k1::Secp256k1;
605 let secp_ctx = Secp256k1::new();
606 let our_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap()).unwrap();
607 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
608 let router = Router::new(our_id, Arc::clone(&logger));
610 // Build network from our_id to node8:
612 // -1(1)2- node1 -1(3)2-
614 // our_id -1(12)2- node8 -1(13)2--- node3
616 // -1(2)2- node2 -1(4)2-
619 // chan1 1-to-2: disabled
620 // chan1 2-to-1: enabled, 0 fee
622 // chan2 1-to-2: enabled, ignored fee
623 // chan2 2-to-1: enabled, 0 fee
625 // chan3 1-to-2: enabled, 0 fee
626 // chan3 2-to-1: enabled, 100 msat fee
628 // chan4 1-to-2: enabled, 100% fee
629 // chan4 2-to-1: enabled, 0 fee
631 // chan12 1-to-2: enabled, ignored fee
632 // chan12 2-to-1: enabled, 0 fee
634 // chan13 1-to-2: enabled, 200% fee
635 // chan13 2-to-1: enabled, 0 fee
638 // -1(5)2- node4 -1(8)2--
642 // node3--1(6)2- node5 -1(9)2--- node7 (not in global route map)
644 // -1(7)2- node6 -1(10)2-
646 // chan5 1-to-2: enabled, 100 msat fee
647 // chan5 2-to-1: enabled, 0 fee
649 // chan6 1-to-2: enabled, 0 fee
650 // chan6 2-to-1: enabled, 0 fee
652 // chan7 1-to-2: enabled, 100% fee
653 // chan7 2-to-1: enabled, 0 fee
655 // chan8 1-to-2: enabled, variable fee (0 then 1000 msat)
656 // chan8 2-to-1: enabled, 0 fee
658 // chan9 1-to-2: enabled, 1001 msat fee
659 // chan9 2-to-1: enabled, 0 fee
661 // chan10 1-to-2: enabled, 0 fee
662 // chan10 2-to-1: enabled, 0 fee
664 // chan11 1-to-2: enabled, 0 fee
665 // chan11 2-to-1: enabled, 0 fee
667 let node1 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap()[..]).unwrap()).unwrap();
668 let node2 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0303030303030303030303030303030303030303030303030303030303030303").unwrap()[..]).unwrap()).unwrap();
669 let node3 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0404040404040404040404040404040404040404040404040404040404040404").unwrap()[..]).unwrap()).unwrap();
670 let node4 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0505050505050505050505050505050505050505050505050505050505050505").unwrap()[..]).unwrap()).unwrap();
671 let node5 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0606060606060606060606060606060606060606060606060606060606060606").unwrap()[..]).unwrap()).unwrap();
672 let node6 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0707070707070707070707070707070707070707070707070707070707070707").unwrap()[..]).unwrap()).unwrap();
673 let node7 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0808080808080808080808080808080808080808080808080808080808080808").unwrap()[..]).unwrap()).unwrap();
674 let node8 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0909090909090909090909090909090909090909090909090909090909090909").unwrap()[..]).unwrap()).unwrap();
676 let zero_hash = Sha256dHash::from_data(&[0; 32]);
679 let mut network = router.network_map.write().unwrap();
681 network.nodes.insert(node1.clone(), NodeInfo {
682 channels: vec!(NetworkMap::get_key(1, zero_hash.clone()), NetworkMap::get_key(3, zero_hash.clone())),
683 lowest_inbound_channel_fee_base_msat: 100,
684 lowest_inbound_channel_fee_proportional_millionths: 0,
685 features: GlobalFeatures::new(),
689 addresses: Vec::new(),
691 network.channels.insert(NetworkMap::get_key(1, zero_hash.clone()), ChannelInfo {
692 features: GlobalFeatures::new(),
693 one_to_two: DirectionalChannelInfo {
694 src_node_id: our_id.clone(),
697 cltv_expiry_delta: u16::max_value(), // This value should be ignored
698 htlc_minimum_msat: 0,
699 fee_base_msat: u32::max_value(), // This value should be ignored
700 fee_proportional_millionths: u32::max_value(), // This value should be ignored
701 }, two_to_one: DirectionalChannelInfo {
702 src_node_id: node1.clone(),
705 cltv_expiry_delta: 0,
706 htlc_minimum_msat: 0,
708 fee_proportional_millionths: 0,
711 network.nodes.insert(node2.clone(), NodeInfo {
712 channels: vec!(NetworkMap::get_key(2, zero_hash.clone()), NetworkMap::get_key(4, zero_hash.clone())),
713 lowest_inbound_channel_fee_base_msat: 0,
714 lowest_inbound_channel_fee_proportional_millionths: 0,
715 features: GlobalFeatures::new(),
719 addresses: Vec::new(),
721 network.channels.insert(NetworkMap::get_key(2, zero_hash.clone()), ChannelInfo {
722 features: GlobalFeatures::new(),
723 one_to_two: DirectionalChannelInfo {
724 src_node_id: our_id.clone(),
727 cltv_expiry_delta: u16::max_value(), // This value should be ignored
728 htlc_minimum_msat: 0,
729 fee_base_msat: u32::max_value(), // This value should be ignored
730 fee_proportional_millionths: u32::max_value(), // This value should be ignored
731 }, two_to_one: DirectionalChannelInfo {
732 src_node_id: node2.clone(),
735 cltv_expiry_delta: 0,
736 htlc_minimum_msat: 0,
738 fee_proportional_millionths: 0,
741 network.nodes.insert(node8.clone(), NodeInfo {
742 channels: vec!(NetworkMap::get_key(12, zero_hash.clone()), NetworkMap::get_key(13, zero_hash.clone())),
743 lowest_inbound_channel_fee_base_msat: 0,
744 lowest_inbound_channel_fee_proportional_millionths: 0,
745 features: GlobalFeatures::new(),
749 addresses: Vec::new(),
751 network.channels.insert(NetworkMap::get_key(12, zero_hash.clone()), ChannelInfo {
752 features: GlobalFeatures::new(),
753 one_to_two: DirectionalChannelInfo {
754 src_node_id: our_id.clone(),
757 cltv_expiry_delta: u16::max_value(), // This value should be ignored
758 htlc_minimum_msat: 0,
759 fee_base_msat: u32::max_value(), // This value should be ignored
760 fee_proportional_millionths: u32::max_value(), // This value should be ignored
761 }, two_to_one: DirectionalChannelInfo {
762 src_node_id: node8.clone(),
765 cltv_expiry_delta: 0,
766 htlc_minimum_msat: 0,
768 fee_proportional_millionths: 0,
771 network.nodes.insert(node3.clone(), NodeInfo {
773 NetworkMap::get_key(3, zero_hash.clone()),
774 NetworkMap::get_key(4, zero_hash.clone()),
775 NetworkMap::get_key(13, zero_hash.clone()),
776 NetworkMap::get_key(5, zero_hash.clone()),
777 NetworkMap::get_key(6, zero_hash.clone()),
778 NetworkMap::get_key(7, zero_hash.clone())),
779 lowest_inbound_channel_fee_base_msat: 0,
780 lowest_inbound_channel_fee_proportional_millionths: 0,
781 features: GlobalFeatures::new(),
785 addresses: Vec::new(),
787 network.channels.insert(NetworkMap::get_key(3, zero_hash.clone()), ChannelInfo {
788 features: GlobalFeatures::new(),
789 one_to_two: DirectionalChannelInfo {
790 src_node_id: node1.clone(),
793 cltv_expiry_delta: (3 << 8) | 1,
794 htlc_minimum_msat: 0,
796 fee_proportional_millionths: 0,
797 }, two_to_one: DirectionalChannelInfo {
798 src_node_id: node3.clone(),
801 cltv_expiry_delta: (3 << 8) | 2,
802 htlc_minimum_msat: 0,
804 fee_proportional_millionths: 0,
807 network.channels.insert(NetworkMap::get_key(4, zero_hash.clone()), ChannelInfo {
808 features: GlobalFeatures::new(),
809 one_to_two: DirectionalChannelInfo {
810 src_node_id: node2.clone(),
813 cltv_expiry_delta: (4 << 8) | 1,
814 htlc_minimum_msat: 0,
816 fee_proportional_millionths: 1000000,
817 }, two_to_one: DirectionalChannelInfo {
818 src_node_id: node3.clone(),
821 cltv_expiry_delta: (4 << 8) | 2,
822 htlc_minimum_msat: 0,
824 fee_proportional_millionths: 0,
827 network.channels.insert(NetworkMap::get_key(13, zero_hash.clone()), ChannelInfo {
828 features: GlobalFeatures::new(),
829 one_to_two: DirectionalChannelInfo {
830 src_node_id: node8.clone(),
833 cltv_expiry_delta: (13 << 8) | 1,
834 htlc_minimum_msat: 0,
836 fee_proportional_millionths: 2000000,
837 }, two_to_one: DirectionalChannelInfo {
838 src_node_id: node3.clone(),
841 cltv_expiry_delta: (13 << 8) | 2,
842 htlc_minimum_msat: 0,
844 fee_proportional_millionths: 0,
847 network.nodes.insert(node4.clone(), NodeInfo {
848 channels: vec!(NetworkMap::get_key(5, zero_hash.clone()), NetworkMap::get_key(11, zero_hash.clone())),
849 lowest_inbound_channel_fee_base_msat: 0,
850 lowest_inbound_channel_fee_proportional_millionths: 0,
851 features: GlobalFeatures::new(),
855 addresses: Vec::new(),
857 network.channels.insert(NetworkMap::get_key(5, zero_hash.clone()), ChannelInfo {
858 features: GlobalFeatures::new(),
859 one_to_two: DirectionalChannelInfo {
860 src_node_id: node3.clone(),
863 cltv_expiry_delta: (5 << 8) | 1,
864 htlc_minimum_msat: 0,
866 fee_proportional_millionths: 0,
867 }, two_to_one: DirectionalChannelInfo {
868 src_node_id: node4.clone(),
871 cltv_expiry_delta: (5 << 8) | 2,
872 htlc_minimum_msat: 0,
874 fee_proportional_millionths: 0,
877 network.nodes.insert(node5.clone(), NodeInfo {
878 channels: vec!(NetworkMap::get_key(6, zero_hash.clone()), NetworkMap::get_key(11, zero_hash.clone())),
879 lowest_inbound_channel_fee_base_msat: 0,
880 lowest_inbound_channel_fee_proportional_millionths: 0,
881 features: GlobalFeatures::new(),
885 addresses: Vec::new(),
887 network.channels.insert(NetworkMap::get_key(6, zero_hash.clone()), ChannelInfo {
888 features: GlobalFeatures::new(),
889 one_to_two: DirectionalChannelInfo {
890 src_node_id: node3.clone(),
893 cltv_expiry_delta: (6 << 8) | 1,
894 htlc_minimum_msat: 0,
896 fee_proportional_millionths: 0,
897 }, two_to_one: DirectionalChannelInfo {
898 src_node_id: node5.clone(),
901 cltv_expiry_delta: (6 << 8) | 2,
902 htlc_minimum_msat: 0,
904 fee_proportional_millionths: 0,
907 network.channels.insert(NetworkMap::get_key(11, zero_hash.clone()), ChannelInfo {
908 features: GlobalFeatures::new(),
909 one_to_two: DirectionalChannelInfo {
910 src_node_id: node5.clone(),
913 cltv_expiry_delta: (11 << 8) | 1,
914 htlc_minimum_msat: 0,
916 fee_proportional_millionths: 0,
917 }, two_to_one: DirectionalChannelInfo {
918 src_node_id: node4.clone(),
921 cltv_expiry_delta: (11 << 8) | 2,
922 htlc_minimum_msat: 0,
924 fee_proportional_millionths: 0,
927 network.nodes.insert(node6.clone(), NodeInfo {
928 channels: vec!(NetworkMap::get_key(7, zero_hash.clone())),
929 lowest_inbound_channel_fee_base_msat: 0,
930 lowest_inbound_channel_fee_proportional_millionths: 0,
931 features: GlobalFeatures::new(),
935 addresses: Vec::new(),
937 network.channels.insert(NetworkMap::get_key(7, zero_hash.clone()), ChannelInfo {
938 features: GlobalFeatures::new(),
939 one_to_two: DirectionalChannelInfo {
940 src_node_id: node3.clone(),
943 cltv_expiry_delta: (7 << 8) | 1,
944 htlc_minimum_msat: 0,
946 fee_proportional_millionths: 1000000,
947 }, two_to_one: DirectionalChannelInfo {
948 src_node_id: node6.clone(),
951 cltv_expiry_delta: (7 << 8) | 2,
952 htlc_minimum_msat: 0,
954 fee_proportional_millionths: 0,
959 { // Simple route to 3 via 2
960 let route = router.get_route(&node3, None, &Vec::new(), 100, 42).unwrap();
961 assert_eq!(route.hops.len(), 2);
963 assert_eq!(route.hops[0].pubkey, node2);
964 assert_eq!(route.hops[0].short_channel_id, 2);
965 assert_eq!(route.hops[0].fee_msat, 100);
966 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
968 assert_eq!(route.hops[1].pubkey, node3);
969 assert_eq!(route.hops[1].short_channel_id, 4);
970 assert_eq!(route.hops[1].fee_msat, 100);
971 assert_eq!(route.hops[1].cltv_expiry_delta, 42);
974 { // Route to 1 via 2 and 3 because our channel to 1 is disabled
975 let route = router.get_route(&node1, None, &Vec::new(), 100, 42).unwrap();
976 assert_eq!(route.hops.len(), 3);
978 assert_eq!(route.hops[0].pubkey, node2);
979 assert_eq!(route.hops[0].short_channel_id, 2);
980 assert_eq!(route.hops[0].fee_msat, 200);
981 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
983 assert_eq!(route.hops[1].pubkey, node3);
984 assert_eq!(route.hops[1].short_channel_id, 4);
985 assert_eq!(route.hops[1].fee_msat, 100);
986 assert_eq!(route.hops[1].cltv_expiry_delta, (3 << 8) | 2);
988 assert_eq!(route.hops[2].pubkey, node1);
989 assert_eq!(route.hops[2].short_channel_id, 3);
990 assert_eq!(route.hops[2].fee_msat, 100);
991 assert_eq!(route.hops[2].cltv_expiry_delta, 42);
994 { // If we specify a channel to node8, that overrides our local channel view and that gets used
995 let our_chans = vec![channelmanager::ChannelDetails {
997 short_channel_id: Some(42),
998 remote_network_id: node8.clone(),
999 channel_value_satoshis: 0,
1002 let route = router.get_route(&node3, Some(&our_chans), &Vec::new(), 100, 42).unwrap();
1003 assert_eq!(route.hops.len(), 2);
1005 assert_eq!(route.hops[0].pubkey, node8);
1006 assert_eq!(route.hops[0].short_channel_id, 42);
1007 assert_eq!(route.hops[0].fee_msat, 200);
1008 assert_eq!(route.hops[0].cltv_expiry_delta, (13 << 8) | 1);
1010 assert_eq!(route.hops[1].pubkey, node3);
1011 assert_eq!(route.hops[1].short_channel_id, 13);
1012 assert_eq!(route.hops[1].fee_msat, 100);
1013 assert_eq!(route.hops[1].cltv_expiry_delta, 42);
1016 let mut last_hops = vec!(RouteHint {
1017 src_node_id: node4.clone(),
1018 short_channel_id: 8,
1020 fee_proportional_millionths: 0,
1021 cltv_expiry_delta: (8 << 8) | 1,
1022 htlc_minimum_msat: 0,
1024 src_node_id: node5.clone(),
1025 short_channel_id: 9,
1026 fee_base_msat: 1001,
1027 fee_proportional_millionths: 0,
1028 cltv_expiry_delta: (9 << 8) | 1,
1029 htlc_minimum_msat: 0,
1031 src_node_id: node6.clone(),
1032 short_channel_id: 10,
1034 fee_proportional_millionths: 0,
1035 cltv_expiry_delta: (10 << 8) | 1,
1036 htlc_minimum_msat: 0,
1039 { // Simple test across 2, 3, 5, and 4 via a last_hop channel
1040 let route = router.get_route(&node7, None, &last_hops, 100, 42).unwrap();
1041 assert_eq!(route.hops.len(), 5);
1043 assert_eq!(route.hops[0].pubkey, node2);
1044 assert_eq!(route.hops[0].short_channel_id, 2);
1045 assert_eq!(route.hops[0].fee_msat, 100);
1046 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1048 assert_eq!(route.hops[1].pubkey, node3);
1049 assert_eq!(route.hops[1].short_channel_id, 4);
1050 assert_eq!(route.hops[1].fee_msat, 0);
1051 assert_eq!(route.hops[1].cltv_expiry_delta, (6 << 8) | 1);
1053 assert_eq!(route.hops[2].pubkey, node5);
1054 assert_eq!(route.hops[2].short_channel_id, 6);
1055 assert_eq!(route.hops[2].fee_msat, 0);
1056 assert_eq!(route.hops[2].cltv_expiry_delta, (11 << 8) | 1);
1058 assert_eq!(route.hops[3].pubkey, node4);
1059 assert_eq!(route.hops[3].short_channel_id, 11);
1060 assert_eq!(route.hops[3].fee_msat, 0);
1061 assert_eq!(route.hops[3].cltv_expiry_delta, (8 << 8) | 1);
1063 assert_eq!(route.hops[4].pubkey, node7);
1064 assert_eq!(route.hops[4].short_channel_id, 8);
1065 assert_eq!(route.hops[4].fee_msat, 100);
1066 assert_eq!(route.hops[4].cltv_expiry_delta, 42);
1069 { // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
1070 let our_chans = vec![channelmanager::ChannelDetails {
1071 channel_id: [0; 32],
1072 short_channel_id: Some(42),
1073 remote_network_id: node4.clone(),
1074 channel_value_satoshis: 0,
1077 let route = router.get_route(&node7, Some(&our_chans), &last_hops, 100, 42).unwrap();
1078 assert_eq!(route.hops.len(), 2);
1080 assert_eq!(route.hops[0].pubkey, node4);
1081 assert_eq!(route.hops[0].short_channel_id, 42);
1082 assert_eq!(route.hops[0].fee_msat, 0);
1083 assert_eq!(route.hops[0].cltv_expiry_delta, (8 << 8) | 1);
1085 assert_eq!(route.hops[1].pubkey, node7);
1086 assert_eq!(route.hops[1].short_channel_id, 8);
1087 assert_eq!(route.hops[1].fee_msat, 100);
1088 assert_eq!(route.hops[1].cltv_expiry_delta, 42);
1091 last_hops[0].fee_base_msat = 1000;
1093 { // Revert to via 6 as the fee on 8 goes up
1094 let route = router.get_route(&node7, None, &last_hops, 100, 42).unwrap();
1095 assert_eq!(route.hops.len(), 4);
1097 assert_eq!(route.hops[0].pubkey, node2);
1098 assert_eq!(route.hops[0].short_channel_id, 2);
1099 assert_eq!(route.hops[0].fee_msat, 200); // fee increased as its % of value transferred across node
1100 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1102 assert_eq!(route.hops[1].pubkey, node3);
1103 assert_eq!(route.hops[1].short_channel_id, 4);
1104 assert_eq!(route.hops[1].fee_msat, 100);
1105 assert_eq!(route.hops[1].cltv_expiry_delta, (7 << 8) | 1);
1107 assert_eq!(route.hops[2].pubkey, node6);
1108 assert_eq!(route.hops[2].short_channel_id, 7);
1109 assert_eq!(route.hops[2].fee_msat, 0);
1110 assert_eq!(route.hops[2].cltv_expiry_delta, (10 << 8) | 1);
1112 assert_eq!(route.hops[3].pubkey, node7);
1113 assert_eq!(route.hops[3].short_channel_id, 10);
1114 assert_eq!(route.hops[3].fee_msat, 100);
1115 assert_eq!(route.hops[3].cltv_expiry_delta, 42);
1118 { // ...but still use 8 for larger payments as 6 has a variable feerate
1119 let route = router.get_route(&node7, None, &last_hops, 2000, 42).unwrap();
1120 assert_eq!(route.hops.len(), 5);
1122 assert_eq!(route.hops[0].pubkey, node2);
1123 assert_eq!(route.hops[0].short_channel_id, 2);
1124 assert_eq!(route.hops[0].fee_msat, 3000);
1125 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1127 assert_eq!(route.hops[1].pubkey, node3);
1128 assert_eq!(route.hops[1].short_channel_id, 4);
1129 assert_eq!(route.hops[1].fee_msat, 0);
1130 assert_eq!(route.hops[1].cltv_expiry_delta, (6 << 8) | 1);
1132 assert_eq!(route.hops[2].pubkey, node5);
1133 assert_eq!(route.hops[2].short_channel_id, 6);
1134 assert_eq!(route.hops[2].fee_msat, 0);
1135 assert_eq!(route.hops[2].cltv_expiry_delta, (11 << 8) | 1);
1137 assert_eq!(route.hops[3].pubkey, node4);
1138 assert_eq!(route.hops[3].short_channel_id, 11);
1139 assert_eq!(route.hops[3].fee_msat, 1000);
1140 assert_eq!(route.hops[3].cltv_expiry_delta, (8 << 8) | 1);
1142 assert_eq!(route.hops[4].pubkey, node7);
1143 assert_eq!(route.hops[4].short_channel_id, 8);
1144 assert_eq!(route.hops[4].fee_msat, 2000);
1145 assert_eq!(route.hops[4].cltv_expiry_delta, 42);