1 //! The top-level routing/network map tracking logic lives here.
3 //! You probably want to create a Router and use that as your RoutingMessageHandler and then
4 //! interrogate it to get routes for your own payments.
6 use secp256k1::key::PublicKey;
7 use secp256k1::{Secp256k1,Message};
10 use bitcoin::util::hash::Sha256dHash;
11 use bitcoin::blockdata::script::Builder;
12 use bitcoin::blockdata::opcodes;
14 use chain::chaininterface::{ChainError, ChainWatchInterface};
15 use ln::channelmanager;
16 use ln::msgs::{DecodeError,ErrorAction,HandleError,RoutingMessageHandler,NetAddress,GlobalFeatures};
18 use util::ser::{Writeable, Readable};
19 use util::logger::Logger;
22 use std::sync::{RwLock,Arc};
23 use std::collections::{HashMap,BinaryHeap,BTreeMap};
24 use std::collections::btree_map::Entry as BtreeEntry;
30 /// The node_id of the node at this hop.
31 pub pubkey: PublicKey,
32 /// The channel that should be used from the previous hop to reach this node.
33 pub short_channel_id: u64,
34 /// The fee taken on this hop. For the last hop, this should be the full value of the payment.
36 /// The CLTV delta added for this hop. For the last hop, this should be the full CLTV value
37 /// expected at the destination, in excess of the current block height.
38 pub cltv_expiry_delta: u32,
41 /// A route from us through the network to a destination
44 /// The list of hops, NOT INCLUDING our own, where the last hop is the destination. Thus, this
45 /// must always be at least length one. By protocol rules, this may not currently exceed 20 in
47 pub hops: Vec<RouteHop>,
50 impl Writeable for Route {
51 fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
52 (self.hops.len() as u8).write(writer)?;
53 for hop in self.hops.iter() {
54 hop.pubkey.write(writer)?;
55 hop.short_channel_id.write(writer)?;
56 hop.fee_msat.write(writer)?;
57 hop.cltv_expiry_delta.write(writer)?;
63 impl<R: ::std::io::Read> Readable<R> for Route {
64 fn read(reader: &mut R) -> Result<Route, DecodeError> {
65 let hops_count: u8 = Readable::read(reader)?;
66 let mut hops = Vec::with_capacity(hops_count as usize);
67 for _ in 0..hops_count {
69 pubkey: Readable::read(reader)?,
70 short_channel_id: Readable::read(reader)?,
71 fee_msat: Readable::read(reader)?,
72 cltv_expiry_delta: Readable::read(reader)?,
81 struct DirectionalChannelInfo {
82 src_node_id: PublicKey,
85 cltv_expiry_delta: u16,
86 htlc_minimum_msat: u64,
88 fee_proportional_millionths: u32,
89 last_update_message: Option<msgs::ChannelUpdate>,
92 impl std::fmt::Display for DirectionalChannelInfo {
93 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
94 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)?;
100 features: GlobalFeatures,
101 one_to_two: DirectionalChannelInfo,
102 two_to_one: DirectionalChannelInfo,
103 //this is cached here so we can send out it later if required by route_init_sync
104 //keep an eye on this to see if the extra memory is a problem
105 announcement_message: Option<msgs::ChannelAnnouncement>,
108 impl std::fmt::Display for ChannelInfo {
109 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
110 write!(f, "features: {}, one_to_two: {}, two_to_one: {}", log_bytes!(self.features.encode()), self.one_to_two, self.two_to_one)?;
116 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
117 channels: Vec<(u64, Sha256dHash)>,
118 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
121 lowest_inbound_channel_fee_base_msat: u32,
122 lowest_inbound_channel_fee_proportional_millionths: u32,
124 features: GlobalFeatures,
128 addresses: Vec<NetAddress>,
129 //this is cached here so we can send out it later if required by route_init_sync
130 //keep an eye on this to see if the extra memory is a problem
131 announcement_message: Option<msgs::NodeAnnouncement>,
134 impl std::fmt::Display for NodeInfo {
135 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
136 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[..])?;
142 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
143 channels: BTreeMap<(u64, Sha256dHash), ChannelInfo>,
144 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
145 channels: BTreeMap<u64, ChannelInfo>,
147 our_node_id: PublicKey,
148 nodes: BTreeMap<PublicKey, NodeInfo>,
150 struct MutNetworkMap<'a> {
151 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
152 channels: &'a mut BTreeMap<(u64, Sha256dHash), ChannelInfo>,
153 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
154 channels: &'a mut BTreeMap<u64, ChannelInfo>,
155 nodes: &'a mut BTreeMap<PublicKey, NodeInfo>,
158 fn borrow_parts(&mut self) -> MutNetworkMap {
160 channels: &mut self.channels,
161 nodes: &mut self.nodes,
165 impl std::fmt::Display for NetworkMap {
166 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
167 write!(f, "Node id {} network map\n[Channels]\n", log_pubkey!(self.our_node_id))?;
168 for (key, val) in self.channels.iter() {
169 write!(f, " {}: {}\n", key, val)?;
171 write!(f, "[Nodes]\n")?;
172 for (key, val) in self.nodes.iter() {
173 write!(f, " {}: {}\n", log_pubkey!(key), val)?;
180 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
182 fn get_key(short_channel_id: u64, chain_hash: Sha256dHash) -> (u64, Sha256dHash) {
183 (short_channel_id, chain_hash)
186 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
188 fn get_key(short_channel_id: u64, _: Sha256dHash) -> u64 {
192 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
194 fn get_short_id(id: &(u64, Sha256dHash)) -> &u64 {
198 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
200 fn get_short_id(id: &u64) -> &u64 {
205 /// A channel descriptor which provides a last-hop route to get_route
206 pub struct RouteHint {
207 /// The node_id of the non-target end of the route
208 pub src_node_id: PublicKey,
209 /// The short_channel_id of this channel
210 pub short_channel_id: u64,
211 /// The static msat-denominated fee which must be paid to use this channel
212 pub fee_base_msat: u32,
213 /// The dynamic proportional fee which must be paid to use this channel, denominated in
214 /// millionths of the value being forwarded to the next hop.
215 pub fee_proportional_millionths: u32,
216 /// The difference in CLTV values between this node and the next node.
217 pub cltv_expiry_delta: u16,
218 /// The minimum value, in msat, which must be relayed to the next hop.
219 pub htlc_minimum_msat: u64,
222 /// Tracks a view of the network, receiving updates from peers and generating Routes to
223 /// payment destinations.
225 secp_ctx: Secp256k1<secp256k1::VerifyOnly>,
226 network_map: RwLock<NetworkMap>,
227 chain_monitor: Arc<ChainWatchInterface>,
231 macro_rules! secp_verify_sig {
232 ( $secp_ctx: expr, $msg: expr, $sig: expr, $pubkey: expr ) => {
233 match $secp_ctx.verify($msg, $sig, $pubkey) {
235 Err(_) => return Err(HandleError{err: "Invalid signature from remote node", action: None}),
240 impl RoutingMessageHandler for Router {
241 fn handle_node_announcement(&self, msg: &msgs::NodeAnnouncement) -> Result<bool, HandleError> {
242 let msg_hash = Message::from_slice(&Sha256dHash::from_data(&msg.contents.encode()[..])[..]).unwrap();
243 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.signature, &msg.contents.node_id);
245 if msg.contents.features.requires_unknown_bits() {
246 panic!("Unknown-required-features NodeAnnouncements should never deserialize!");
249 let mut network = self.network_map.write().unwrap();
250 match network.nodes.get_mut(&msg.contents.node_id) {
251 None => Err(HandleError{err: "No existing channels for node_announcement", action: Some(ErrorAction::IgnoreError)}),
253 if node.last_update >= msg.contents.timestamp {
254 return Err(HandleError{err: "Update older than last processed update", action: Some(ErrorAction::IgnoreError)});
257 node.features = msg.contents.features.clone();
258 node.last_update = msg.contents.timestamp;
259 node.rgb = msg.contents.rgb;
260 node.alias = msg.contents.alias;
261 node.addresses = msg.contents.addresses.clone();
263 let should_relay = msg.contents.excess_data.is_empty() && msg.contents.excess_address_data.is_empty() && !msg.contents.features.supports_unknown_bits();
264 node.announcement_message = if should_relay { Some(msg.clone()) } else { None };
270 fn handle_channel_announcement(&self, msg: &msgs::ChannelAnnouncement) -> Result<bool, HandleError> {
271 if msg.contents.node_id_1 == msg.contents.node_id_2 || msg.contents.bitcoin_key_1 == msg.contents.bitcoin_key_2 {
272 return Err(HandleError{err: "Channel announcement node had a channel with itself", action: Some(ErrorAction::IgnoreError)});
275 let msg_hash = Message::from_slice(&Sha256dHash::from_data(&msg.contents.encode()[..])[..]).unwrap();
276 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.node_signature_1, &msg.contents.node_id_1);
277 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.node_signature_2, &msg.contents.node_id_2);
278 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.bitcoin_signature_1, &msg.contents.bitcoin_key_1);
279 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.bitcoin_signature_2, &msg.contents.bitcoin_key_2);
281 if msg.contents.features.requires_unknown_bits() {
282 panic!("Unknown-required-features ChannelAnnouncements should never deserialize!");
285 let checked_utxo = match self.chain_monitor.get_chain_utxo(msg.contents.chain_hash, msg.contents.short_channel_id) {
286 Ok((script_pubkey, _value)) => {
287 let expected_script = Builder::new().push_opcode(opcodes::All::OP_PUSHNUM_2)
288 .push_slice(&msg.contents.bitcoin_key_1.serialize())
289 .push_slice(&msg.contents.bitcoin_key_2.serialize())
290 .push_opcode(opcodes::All::OP_PUSHNUM_2).push_opcode(opcodes::All::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
291 if script_pubkey != expected_script {
292 return Err(HandleError{err: "Channel announcement keys didn't match on-chain script", action: Some(ErrorAction::IgnoreError)});
294 //TODO: Check if value is worth storing, use it to inform routing, and compare it
295 //to the new HTLC max field in channel_update
298 Err(ChainError::NotSupported) => {
299 // Tentatively accept, potentially exposing us to DoS attacks
302 Err(ChainError::NotWatched) => {
303 return Err(HandleError{err: "Channel announced on an unknown chain", action: Some(ErrorAction::IgnoreError)});
305 Err(ChainError::UnknownTx) => {
306 return Err(HandleError{err: "Channel announced without corresponding UTXO entry", action: Some(ErrorAction::IgnoreError)});
310 let mut network_lock = self.network_map.write().unwrap();
311 let network = network_lock.borrow_parts();
313 let should_relay = msg.contents.excess_data.is_empty() && !msg.contents.features.supports_unknown_bits();
315 let chan_info = ChannelInfo {
316 features: msg.contents.features.clone(),
317 one_to_two: DirectionalChannelInfo {
318 src_node_id: msg.contents.node_id_1.clone(),
321 cltv_expiry_delta: u16::max_value(),
322 htlc_minimum_msat: u64::max_value(),
323 fee_base_msat: u32::max_value(),
324 fee_proportional_millionths: u32::max_value(),
325 last_update_message: None,
327 two_to_one: DirectionalChannelInfo {
328 src_node_id: msg.contents.node_id_2.clone(),
331 cltv_expiry_delta: u16::max_value(),
332 htlc_minimum_msat: u64::max_value(),
333 fee_base_msat: u32::max_value(),
334 fee_proportional_millionths: u32::max_value(),
335 last_update_message: None,
337 announcement_message: if should_relay { Some(msg.clone()) } else { None },
340 match network.channels.entry(NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash)) {
341 BtreeEntry::Occupied(mut entry) => {
342 //TODO: because asking the blockchain if short_channel_id is valid is only optional
343 //in the blockchain API, we need to handle it smartly here, though its unclear
346 // Either our UTXO provider is busted, there was a reorg, or the UTXO provider
347 // only sometimes returns results. In any case remove the previous entry. Note
348 // that the spec expects us to "blacklist" the node_ids involved, but we can't
350 // a) we don't *require* a UTXO provider that always returns results.
351 // b) we don't track UTXOs of channels we know about and remove them if they
353 // c) it's unclear how to do so without exposing ourselves to massive DoS risk.
354 Self::remove_channel_in_nodes(network.nodes, &entry.get(), msg.contents.short_channel_id);
355 *entry.get_mut() = chan_info;
357 return Err(HandleError{err: "Already have knowledge of channel", action: Some(ErrorAction::IgnoreError)})
360 BtreeEntry::Vacant(entry) => {
361 entry.insert(chan_info);
365 macro_rules! add_channel_to_node {
366 ( $node_id: expr ) => {
367 match network.nodes.entry($node_id) {
368 BtreeEntry::Occupied(node_entry) => {
369 node_entry.into_mut().channels.push(NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash));
371 BtreeEntry::Vacant(node_entry) => {
372 node_entry.insert(NodeInfo {
373 channels: vec!(NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash)),
374 lowest_inbound_channel_fee_base_msat: u32::max_value(),
375 lowest_inbound_channel_fee_proportional_millionths: u32::max_value(),
376 features: GlobalFeatures::new(),
380 addresses: Vec::new(),
381 announcement_message: None,
388 add_channel_to_node!(msg.contents.node_id_1);
389 add_channel_to_node!(msg.contents.node_id_2);
394 fn handle_htlc_fail_channel_update(&self, update: &msgs::HTLCFailChannelUpdate) {
396 &msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg } => {
397 let _ = self.handle_channel_update(msg);
399 &msgs::HTLCFailChannelUpdate::ChannelClosed { ref short_channel_id, ref is_permanent } => {
400 let mut network = self.network_map.write().unwrap();
402 if let Some(chan) = network.channels.remove(short_channel_id) {
403 Self::remove_channel_in_nodes(&mut network.nodes, &chan, *short_channel_id);
406 if let Some(chan) = network.channels.get_mut(short_channel_id) {
407 chan.one_to_two.enabled = false;
408 chan.two_to_one.enabled = false;
412 &msgs::HTLCFailChannelUpdate::NodeFailure { ref node_id, ref is_permanent } => {
414 //TODO: Wholly remove the node
416 self.mark_node_bad(node_id, false);
422 fn handle_channel_update(&self, msg: &msgs::ChannelUpdate) -> Result<bool, HandleError> {
423 let mut network = self.network_map.write().unwrap();
425 let chan_enabled = msg.contents.flags & (1 << 1) != (1 << 1);
426 let chan_was_enabled;
428 match network.channels.get_mut(&NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash)) {
429 None => return Err(HandleError{err: "Couldn't find channel for update", action: Some(ErrorAction::IgnoreError)}),
431 macro_rules! maybe_update_channel_info {
432 ( $target: expr) => {
433 if $target.last_update >= msg.contents.timestamp {
434 return Err(HandleError{err: "Update older than last processed update", action: Some(ErrorAction::IgnoreError)});
436 chan_was_enabled = $target.enabled;
437 $target.last_update = msg.contents.timestamp;
438 $target.enabled = chan_enabled;
439 $target.cltv_expiry_delta = msg.contents.cltv_expiry_delta;
440 $target.htlc_minimum_msat = msg.contents.htlc_minimum_msat;
441 $target.fee_base_msat = msg.contents.fee_base_msat;
442 $target.fee_proportional_millionths = msg.contents.fee_proportional_millionths;
443 $target.last_update_message = if msg.contents.excess_data.is_empty() {
450 let msg_hash = Message::from_slice(&Sha256dHash::from_data(&msg.contents.encode()[..])[..]).unwrap();
451 if msg.contents.flags & 1 == 1 {
452 dest_node_id = channel.one_to_two.src_node_id.clone();
453 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.signature, &channel.two_to_one.src_node_id);
454 maybe_update_channel_info!(channel.two_to_one);
456 dest_node_id = channel.two_to_one.src_node_id.clone();
457 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.signature, &channel.one_to_two.src_node_id);
458 maybe_update_channel_info!(channel.one_to_two);
464 let node = network.nodes.get_mut(&dest_node_id).unwrap();
465 node.lowest_inbound_channel_fee_base_msat = cmp::min(node.lowest_inbound_channel_fee_base_msat, msg.contents.fee_base_msat);
466 node.lowest_inbound_channel_fee_proportional_millionths = cmp::min(node.lowest_inbound_channel_fee_proportional_millionths, msg.contents.fee_proportional_millionths);
467 } else if chan_was_enabled {
468 let mut lowest_inbound_channel_fee_base_msat = u32::max_value();
469 let mut lowest_inbound_channel_fee_proportional_millionths = u32::max_value();
472 let node = network.nodes.get(&dest_node_id).unwrap();
474 for chan_id in node.channels.iter() {
475 let chan = network.channels.get(chan_id).unwrap();
476 if chan.one_to_two.src_node_id == dest_node_id {
477 lowest_inbound_channel_fee_base_msat = cmp::min(lowest_inbound_channel_fee_base_msat, chan.two_to_one.fee_base_msat);
478 lowest_inbound_channel_fee_proportional_millionths = cmp::min(lowest_inbound_channel_fee_proportional_millionths, chan.two_to_one.fee_proportional_millionths);
480 lowest_inbound_channel_fee_base_msat = cmp::min(lowest_inbound_channel_fee_base_msat, chan.one_to_two.fee_base_msat);
481 lowest_inbound_channel_fee_proportional_millionths = cmp::min(lowest_inbound_channel_fee_proportional_millionths, chan.one_to_two.fee_proportional_millionths);
486 //TODO: satisfy the borrow-checker without a double-map-lookup :(
487 let mut_node = network.nodes.get_mut(&dest_node_id).unwrap();
488 mut_node.lowest_inbound_channel_fee_base_msat = lowest_inbound_channel_fee_base_msat;
489 mut_node.lowest_inbound_channel_fee_proportional_millionths = lowest_inbound_channel_fee_proportional_millionths;
492 Ok(msg.contents.excess_data.is_empty())
496 fn get_next_channel_announcements(&self, starting_point: u64, batch_amount: u8) -> Vec<(msgs::ChannelAnnouncement, msgs::ChannelUpdate,msgs::ChannelUpdate)> {
497 let mut result = Vec::with_capacity(batch_amount as usize);
498 let network = self.network_map.read().unwrap();
499 let mut iter = network.channels.range(starting_point..);
500 while result.len() < batch_amount as usize {
501 if let Some((_, ref chan)) = iter.next() {
502 if chan.announcement_message.is_some() &&
503 chan.one_to_two.last_update_message.is_some() &&
504 chan.two_to_one.last_update_message.is_some() {
505 result.push((chan.announcement_message.clone().unwrap(),
506 chan.one_to_two.last_update_message.clone().unwrap(),
507 chan.two_to_one.last_update_message.clone().unwrap()));
509 // TODO: We may end up sending un-announced channel_updates if we are sending
510 // initial sync data while receiving announce/updates for this channel.
519 fn get_next_node_announcements(&self, starting_point: Option<&PublicKey>, batch_amount: u8) -> Vec<msgs::NodeAnnouncement> {
520 let mut result = Vec::with_capacity(batch_amount as usize);
521 let network = self.network_map.read().unwrap();
522 let mut iter = if let Some(pubkey) = starting_point {
523 let mut iter = network.nodes.range((*pubkey)..);
527 network.nodes.range(..)
529 while result.len() < batch_amount as usize {
530 if let Some((_, ref node)) = iter.next() {
531 if node.announcement_message.is_some() {
532 result.push(node.announcement_message.clone().unwrap());
542 #[derive(Eq, PartialEq)]
543 struct RouteGraphNode {
545 lowest_fee_to_peer_through_node: u64,
546 lowest_fee_to_node: u64,
549 impl cmp::Ord for RouteGraphNode {
550 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
551 other.lowest_fee_to_peer_through_node.cmp(&self.lowest_fee_to_peer_through_node)
552 .then_with(|| other.pubkey.serialize().cmp(&self.pubkey.serialize()))
556 impl cmp::PartialOrd for RouteGraphNode {
557 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
558 Some(self.cmp(other))
562 struct DummyDirectionalChannelInfo {
563 src_node_id: PublicKey,
564 cltv_expiry_delta: u32,
565 htlc_minimum_msat: u64,
567 fee_proportional_millionths: u32,
571 /// Creates a new router with the given node_id to be used as the source for get_route()
572 pub fn new(our_pubkey: PublicKey, chain_monitor: Arc<ChainWatchInterface>, logger: Arc<Logger>) -> Router {
573 let mut nodes = BTreeMap::new();
574 nodes.insert(our_pubkey.clone(), NodeInfo {
575 channels: Vec::new(),
576 lowest_inbound_channel_fee_base_msat: u32::max_value(),
577 lowest_inbound_channel_fee_proportional_millionths: u32::max_value(),
578 features: GlobalFeatures::new(),
582 addresses: Vec::new(),
583 announcement_message: None,
586 secp_ctx: Secp256k1::verification_only(),
587 network_map: RwLock::new(NetworkMap {
588 channels: BTreeMap::new(),
589 our_node_id: our_pubkey,
597 /// Dumps the entire network view of this Router to the logger provided in the constructor at
599 pub fn trace_state(&self) {
600 log_trace!(self, "{}", self.network_map.read().unwrap());
603 /// Get network addresses by node id
604 pub fn get_addresses(&self, pubkey: &PublicKey) -> Option<Vec<NetAddress>> {
605 let network = self.network_map.read().unwrap();
606 network.nodes.get(pubkey).map(|n| n.addresses.clone())
609 /// Marks a node as having failed a route. This will avoid re-using the node in routes for now,
610 /// with an expotnential decay in node "badness". Note that there is deliberately no
611 /// mark_channel_bad as a node may simply lie and suggest that an upstream channel from it is
612 /// what failed the route and not the node itself. Instead, setting the blamed_upstream_node
613 /// boolean will reduce the penalty, returning the node to usability faster. If the node is
614 /// behaving correctly, it will disable the failing channel and we will use it again next time.
615 pub fn mark_node_bad(&self, _node_id: &PublicKey, _blamed_upstream_node: bool) {
619 fn remove_channel_in_nodes(nodes: &mut BTreeMap<PublicKey, NodeInfo>, chan: &ChannelInfo, short_channel_id: u64) {
620 macro_rules! remove_from_node {
621 ($node_id: expr) => {
622 if let BtreeEntry::Occupied(mut entry) = nodes.entry($node_id) {
623 entry.get_mut().channels.retain(|chan_id| {
624 short_channel_id != *NetworkMap::get_short_id(chan_id)
626 if entry.get().channels.is_empty() {
627 entry.remove_entry();
630 panic!("Had channel that pointed to unknown node (ie inconsistent network map)!");
634 remove_from_node!(chan.one_to_two.src_node_id);
635 remove_from_node!(chan.two_to_one.src_node_id);
638 /// Gets a route from us to the given target node.
640 /// Extra routing hops between known nodes and the target will be used if they are included in
643 /// If some channels aren't announced, it may be useful to fill in a first_hops with the
644 /// results from a local ChannelManager::list_usable_channels() call. If it is filled in, our
645 /// (this Router's) view of our local channels will be ignored, and only those in first_hops
648 /// Panics if first_hops contains channels without short_channel_ids
649 /// (ChannelManager::list_usable_channels will never include such channels).
651 /// The fees on channels from us to next-hops are ignored (as they are assumed to all be
652 /// equal), however the enabled/disabled bit on such channels as well as the htlc_minimum_msat
653 /// *is* checked as they may change based on the receiving node.
654 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> {
655 // TODO: Obviously *only* using total fee cost sucks. We should consider weighting by
656 // uptime/success in using a node in the past.
657 let network = self.network_map.read().unwrap();
659 if *target == network.our_node_id {
660 return Err(HandleError{err: "Cannot generate a route to ourselves", action: None});
663 if final_value_msat > 21_000_000 * 1_0000_0000 * 1000 {
664 return Err(HandleError{err: "Cannot generate a route of more value than all existing satoshis", action: None});
667 // We do a dest-to-source Dijkstra's sorting by each node's distance from the destination
668 // plus the minimum per-HTLC fee to get from it to another node (aka "shitty A*").
669 // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
670 // to use as the A* heuristic beyond just the cost to get one node further than the current
673 let dummy_directional_info = DummyDirectionalChannelInfo { // used for first_hops routes
674 src_node_id: network.our_node_id.clone(),
675 cltv_expiry_delta: 0,
676 htlc_minimum_msat: 0,
678 fee_proportional_millionths: 0,
681 let mut targets = BinaryHeap::new(); //TODO: Do we care about switching to eg Fibbonaci heap?
682 let mut dist = HashMap::with_capacity(network.nodes.len());
684 let mut first_hop_targets = HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
685 if let Some(hops) = first_hops {
687 let short_channel_id = chan.short_channel_id.expect("first_hops should be filled in with usable channels, not pending ones");
688 if chan.remote_network_id == *target {
690 hops: vec![RouteHop {
691 pubkey: chan.remote_network_id,
693 fee_msat: final_value_msat,
694 cltv_expiry_delta: final_cltv,
698 first_hop_targets.insert(chan.remote_network_id, short_channel_id);
700 if first_hop_targets.is_empty() {
701 return Err(HandleError{err: "Cannot route when there are no outbound routes away from us", action: None});
705 macro_rules! add_entry {
706 // Adds entry which goes from the node pointed to by $directional_info to
707 // $dest_node_id over the channel with id $chan_id with fees described in
708 // $directional_info.
709 ( $chan_id: expr, $dest_node_id: expr, $directional_info: expr, $starting_fee_msat: expr ) => {
710 //TODO: Explore simply adding fee to hit htlc_minimum_msat
711 if $starting_fee_msat as u64 + final_value_msat > $directional_info.htlc_minimum_msat {
712 let proportional_fee_millions = ($starting_fee_msat + final_value_msat).checked_mul($directional_info.fee_proportional_millionths as u64);
713 if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
714 ($directional_info.fee_base_msat as u64).checked_add(part / 1000000) })
716 let mut total_fee = $starting_fee_msat as u64;
717 let hm_entry = dist.entry(&$directional_info.src_node_id);
718 let old_entry = hm_entry.or_insert_with(|| {
719 let node = network.nodes.get(&$directional_info.src_node_id).unwrap();
721 node.lowest_inbound_channel_fee_base_msat,
722 node.lowest_inbound_channel_fee_proportional_millionths,
724 pubkey: $dest_node_id.clone(),
727 cltv_expiry_delta: 0,
730 if $directional_info.src_node_id != network.our_node_id {
731 // Ignore new_fee for channel-from-us as we assume all channels-from-us
732 // will have the same effective-fee
733 total_fee += new_fee;
734 if let Some(fee_inc) = final_value_msat.checked_add(total_fee).and_then(|inc| { (old_entry.2 as u64).checked_mul(inc) }) {
735 total_fee += fee_inc / 1000000 + (old_entry.1 as u64);
737 // max_value means we'll always fail the old_entry.0 > total_fee check
738 total_fee = u64::max_value();
741 let new_graph_node = RouteGraphNode {
742 pubkey: $directional_info.src_node_id,
743 lowest_fee_to_peer_through_node: total_fee,
744 lowest_fee_to_node: $starting_fee_msat as u64 + new_fee,
746 if old_entry.0 > total_fee {
747 targets.push(new_graph_node);
748 old_entry.0 = total_fee;
749 old_entry.3 = RouteHop {
750 pubkey: $dest_node_id.clone(),
751 short_channel_id: $chan_id.clone(),
752 fee_msat: new_fee, // This field is ignored on the last-hop anyway
753 cltv_expiry_delta: $directional_info.cltv_expiry_delta as u32,
761 macro_rules! add_entries_to_cheapest_to_target_node {
762 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr ) => {
763 if first_hops.is_some() {
764 if let Some(first_hop) = first_hop_targets.get(&$node_id) {
765 add_entry!(first_hop, $node_id, dummy_directional_info, $fee_to_target_msat);
769 for chan_id in $node.channels.iter() {
770 let chan = network.channels.get(chan_id).unwrap();
771 if chan.one_to_two.src_node_id == *$node_id {
772 // ie $node is one, ie next hop in A* is two, via the two_to_one channel
773 if first_hops.is_none() || chan.two_to_one.src_node_id != network.our_node_id {
774 if chan.two_to_one.enabled {
775 add_entry!(chan_id, chan.one_to_two.src_node_id, chan.two_to_one, $fee_to_target_msat);
779 if first_hops.is_none() || chan.one_to_two.src_node_id != network.our_node_id {
780 if chan.one_to_two.enabled {
781 add_entry!(chan_id, chan.two_to_one.src_node_id, chan.one_to_two, $fee_to_target_msat);
789 match network.nodes.get(target) {
792 add_entries_to_cheapest_to_target_node!(node, target, 0);
796 for hop in last_hops.iter() {
797 if first_hops.is_none() || hop.src_node_id != network.our_node_id { // first_hop overrules last_hops
798 if network.nodes.get(&hop.src_node_id).is_some() {
799 if first_hops.is_some() {
800 if let Some(first_hop) = first_hop_targets.get(&hop.src_node_id) {
801 add_entry!(first_hop, hop.src_node_id, dummy_directional_info, 0);
804 add_entry!(hop.short_channel_id, target, hop, 0);
809 while let Some(RouteGraphNode { pubkey, lowest_fee_to_node, .. }) = targets.pop() {
810 if pubkey == network.our_node_id {
811 let mut res = vec!(dist.remove(&network.our_node_id).unwrap().3);
812 while res.last().unwrap().pubkey != *target {
813 let new_entry = match dist.remove(&res.last().unwrap().pubkey) {
815 None => return Err(HandleError{err: "Failed to find a non-fee-overflowing path to the given destination", action: None}),
817 res.last_mut().unwrap().fee_msat = new_entry.fee_msat;
818 res.last_mut().unwrap().cltv_expiry_delta = new_entry.cltv_expiry_delta;
821 res.last_mut().unwrap().fee_msat = final_value_msat;
822 res.last_mut().unwrap().cltv_expiry_delta = final_cltv;
823 let route = Route { hops: res };
824 log_trace!(self, "Got route: {}", log_route!(route));
828 match network.nodes.get(&pubkey) {
831 add_entries_to_cheapest_to_target_node!(node, &pubkey, lowest_fee_to_node);
836 Err(HandleError{err: "Failed to find a path to the given destination", action: None})
842 use chain::chaininterface;
843 use ln::channelmanager;
844 use ln::router::{Router,NodeInfo,NetworkMap,ChannelInfo,DirectionalChannelInfo,RouteHint};
845 use ln::msgs::GlobalFeatures;
846 use util::test_utils;
847 use util::logger::Logger;
849 use bitcoin::util::hash::Sha256dHash;
850 use bitcoin::network::constants::Network;
854 use secp256k1::key::{PublicKey,SecretKey};
855 use secp256k1::Secp256k1;
861 let secp_ctx = Secp256k1::new();
862 let our_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap());
863 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
864 let chain_monitor = Arc::new(chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet, Arc::clone(&logger)));
865 let router = Router::new(our_id, chain_monitor, Arc::clone(&logger));
867 // Build network from our_id to node8:
869 // -1(1)2- node1 -1(3)2-
871 // our_id -1(12)2- node8 -1(13)2--- node3
873 // -1(2)2- node2 -1(4)2-
876 // chan1 1-to-2: disabled
877 // chan1 2-to-1: enabled, 0 fee
879 // chan2 1-to-2: enabled, ignored fee
880 // chan2 2-to-1: enabled, 0 fee
882 // chan3 1-to-2: enabled, 0 fee
883 // chan3 2-to-1: enabled, 100 msat fee
885 // chan4 1-to-2: enabled, 100% fee
886 // chan4 2-to-1: enabled, 0 fee
888 // chan12 1-to-2: enabled, ignored fee
889 // chan12 2-to-1: enabled, 0 fee
891 // chan13 1-to-2: enabled, 200% fee
892 // chan13 2-to-1: enabled, 0 fee
895 // -1(5)2- node4 -1(8)2--
899 // node3--1(6)2- node5 -1(9)2--- node7 (not in global route map)
901 // -1(7)2- node6 -1(10)2-
903 // chan5 1-to-2: enabled, 100 msat fee
904 // chan5 2-to-1: enabled, 0 fee
906 // chan6 1-to-2: enabled, 0 fee
907 // chan6 2-to-1: enabled, 0 fee
909 // chan7 1-to-2: enabled, 100% fee
910 // chan7 2-to-1: enabled, 0 fee
912 // chan8 1-to-2: enabled, variable fee (0 then 1000 msat)
913 // chan8 2-to-1: enabled, 0 fee
915 // chan9 1-to-2: enabled, 1001 msat fee
916 // chan9 2-to-1: enabled, 0 fee
918 // chan10 1-to-2: enabled, 0 fee
919 // chan10 2-to-1: enabled, 0 fee
921 // chan11 1-to-2: enabled, 0 fee
922 // chan11 2-to-1: enabled, 0 fee
924 let node1 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap()[..]).unwrap());
925 let node2 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0303030303030303030303030303030303030303030303030303030303030303").unwrap()[..]).unwrap());
926 let node3 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0404040404040404040404040404040404040404040404040404040404040404").unwrap()[..]).unwrap());
927 let node4 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0505050505050505050505050505050505050505050505050505050505050505").unwrap()[..]).unwrap());
928 let node5 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0606060606060606060606060606060606060606060606060606060606060606").unwrap()[..]).unwrap());
929 let node6 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0707070707070707070707070707070707070707070707070707070707070707").unwrap()[..]).unwrap());
930 let node7 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0808080808080808080808080808080808080808080808080808080808080808").unwrap()[..]).unwrap());
931 let node8 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0909090909090909090909090909090909090909090909090909090909090909").unwrap()[..]).unwrap());
933 let zero_hash = Sha256dHash::from_data(&[0; 32]);
936 let mut network = router.network_map.write().unwrap();
938 network.nodes.insert(node1.clone(), NodeInfo {
939 channels: vec!(NetworkMap::get_key(1, zero_hash.clone()), NetworkMap::get_key(3, zero_hash.clone())),
940 lowest_inbound_channel_fee_base_msat: 100,
941 lowest_inbound_channel_fee_proportional_millionths: 0,
942 features: GlobalFeatures::new(),
946 addresses: Vec::new(),
947 announcement_message: None,
949 network.channels.insert(NetworkMap::get_key(1, zero_hash.clone()), ChannelInfo {
950 features: GlobalFeatures::new(),
951 one_to_two: DirectionalChannelInfo {
952 src_node_id: our_id.clone(),
955 cltv_expiry_delta: u16::max_value(), // This value should be ignored
956 htlc_minimum_msat: 0,
957 fee_base_msat: u32::max_value(), // This value should be ignored
958 fee_proportional_millionths: u32::max_value(), // This value should be ignored
959 last_update_message: None,
960 }, two_to_one: DirectionalChannelInfo {
961 src_node_id: node1.clone(),
964 cltv_expiry_delta: 0,
965 htlc_minimum_msat: 0,
967 fee_proportional_millionths: 0,
968 last_update_message: None,
970 announcement_message: None,
972 network.nodes.insert(node2.clone(), NodeInfo {
973 channels: vec!(NetworkMap::get_key(2, zero_hash.clone()), NetworkMap::get_key(4, zero_hash.clone())),
974 lowest_inbound_channel_fee_base_msat: 0,
975 lowest_inbound_channel_fee_proportional_millionths: 0,
976 features: GlobalFeatures::new(),
980 addresses: Vec::new(),
981 announcement_message: None,
983 network.channels.insert(NetworkMap::get_key(2, zero_hash.clone()), ChannelInfo {
984 features: GlobalFeatures::new(),
985 one_to_two: DirectionalChannelInfo {
986 src_node_id: our_id.clone(),
989 cltv_expiry_delta: u16::max_value(), // This value should be ignored
990 htlc_minimum_msat: 0,
991 fee_base_msat: u32::max_value(), // This value should be ignored
992 fee_proportional_millionths: u32::max_value(), // This value should be ignored
993 last_update_message: None,
994 }, two_to_one: DirectionalChannelInfo {
995 src_node_id: node2.clone(),
998 cltv_expiry_delta: 0,
999 htlc_minimum_msat: 0,
1001 fee_proportional_millionths: 0,
1002 last_update_message: None,
1004 announcement_message: None,
1006 network.nodes.insert(node8.clone(), NodeInfo {
1007 channels: vec!(NetworkMap::get_key(12, zero_hash.clone()), NetworkMap::get_key(13, zero_hash.clone())),
1008 lowest_inbound_channel_fee_base_msat: 0,
1009 lowest_inbound_channel_fee_proportional_millionths: 0,
1010 features: GlobalFeatures::new(),
1014 addresses: Vec::new(),
1015 announcement_message: None,
1017 network.channels.insert(NetworkMap::get_key(12, zero_hash.clone()), ChannelInfo {
1018 features: GlobalFeatures::new(),
1019 one_to_two: DirectionalChannelInfo {
1020 src_node_id: our_id.clone(),
1023 cltv_expiry_delta: u16::max_value(), // This value should be ignored
1024 htlc_minimum_msat: 0,
1025 fee_base_msat: u32::max_value(), // This value should be ignored
1026 fee_proportional_millionths: u32::max_value(), // This value should be ignored
1027 last_update_message: None,
1028 }, two_to_one: DirectionalChannelInfo {
1029 src_node_id: node8.clone(),
1032 cltv_expiry_delta: 0,
1033 htlc_minimum_msat: 0,
1035 fee_proportional_millionths: 0,
1036 last_update_message: None,
1038 announcement_message: None,
1040 network.nodes.insert(node3.clone(), NodeInfo {
1042 NetworkMap::get_key(3, zero_hash.clone()),
1043 NetworkMap::get_key(4, zero_hash.clone()),
1044 NetworkMap::get_key(13, zero_hash.clone()),
1045 NetworkMap::get_key(5, zero_hash.clone()),
1046 NetworkMap::get_key(6, zero_hash.clone()),
1047 NetworkMap::get_key(7, zero_hash.clone())),
1048 lowest_inbound_channel_fee_base_msat: 0,
1049 lowest_inbound_channel_fee_proportional_millionths: 0,
1050 features: GlobalFeatures::new(),
1054 addresses: Vec::new(),
1055 announcement_message: None,
1057 network.channels.insert(NetworkMap::get_key(3, zero_hash.clone()), ChannelInfo {
1058 features: GlobalFeatures::new(),
1059 one_to_two: DirectionalChannelInfo {
1060 src_node_id: node1.clone(),
1063 cltv_expiry_delta: (3 << 8) | 1,
1064 htlc_minimum_msat: 0,
1066 fee_proportional_millionths: 0,
1067 last_update_message: None,
1068 }, two_to_one: DirectionalChannelInfo {
1069 src_node_id: node3.clone(),
1072 cltv_expiry_delta: (3 << 8) | 2,
1073 htlc_minimum_msat: 0,
1075 fee_proportional_millionths: 0,
1076 last_update_message: None,
1078 announcement_message: None,
1080 network.channels.insert(NetworkMap::get_key(4, zero_hash.clone()), ChannelInfo {
1081 features: GlobalFeatures::new(),
1082 one_to_two: DirectionalChannelInfo {
1083 src_node_id: node2.clone(),
1086 cltv_expiry_delta: (4 << 8) | 1,
1087 htlc_minimum_msat: 0,
1089 fee_proportional_millionths: 1000000,
1090 last_update_message: None,
1091 }, two_to_one: DirectionalChannelInfo {
1092 src_node_id: node3.clone(),
1095 cltv_expiry_delta: (4 << 8) | 2,
1096 htlc_minimum_msat: 0,
1098 fee_proportional_millionths: 0,
1099 last_update_message: None,
1101 announcement_message: None,
1103 network.channels.insert(NetworkMap::get_key(13, zero_hash.clone()), ChannelInfo {
1104 features: GlobalFeatures::new(),
1105 one_to_two: DirectionalChannelInfo {
1106 src_node_id: node8.clone(),
1109 cltv_expiry_delta: (13 << 8) | 1,
1110 htlc_minimum_msat: 0,
1112 fee_proportional_millionths: 2000000,
1113 last_update_message: None,
1114 }, two_to_one: DirectionalChannelInfo {
1115 src_node_id: node3.clone(),
1118 cltv_expiry_delta: (13 << 8) | 2,
1119 htlc_minimum_msat: 0,
1121 fee_proportional_millionths: 0,
1122 last_update_message: None,
1124 announcement_message: None,
1126 network.nodes.insert(node4.clone(), NodeInfo {
1127 channels: vec!(NetworkMap::get_key(5, zero_hash.clone()), NetworkMap::get_key(11, zero_hash.clone())),
1128 lowest_inbound_channel_fee_base_msat: 0,
1129 lowest_inbound_channel_fee_proportional_millionths: 0,
1130 features: GlobalFeatures::new(),
1134 addresses: Vec::new(),
1135 announcement_message: None,
1137 network.channels.insert(NetworkMap::get_key(5, zero_hash.clone()), ChannelInfo {
1138 features: GlobalFeatures::new(),
1139 one_to_two: DirectionalChannelInfo {
1140 src_node_id: node3.clone(),
1143 cltv_expiry_delta: (5 << 8) | 1,
1144 htlc_minimum_msat: 0,
1146 fee_proportional_millionths: 0,
1147 last_update_message: None,
1148 }, two_to_one: DirectionalChannelInfo {
1149 src_node_id: node4.clone(),
1152 cltv_expiry_delta: (5 << 8) | 2,
1153 htlc_minimum_msat: 0,
1155 fee_proportional_millionths: 0,
1156 last_update_message: None,
1158 announcement_message: None,
1160 network.nodes.insert(node5.clone(), NodeInfo {
1161 channels: vec!(NetworkMap::get_key(6, zero_hash.clone()), NetworkMap::get_key(11, zero_hash.clone())),
1162 lowest_inbound_channel_fee_base_msat: 0,
1163 lowest_inbound_channel_fee_proportional_millionths: 0,
1164 features: GlobalFeatures::new(),
1168 addresses: Vec::new(),
1169 announcement_message: None,
1171 network.channels.insert(NetworkMap::get_key(6, zero_hash.clone()), ChannelInfo {
1172 features: GlobalFeatures::new(),
1173 one_to_two: DirectionalChannelInfo {
1174 src_node_id: node3.clone(),
1177 cltv_expiry_delta: (6 << 8) | 1,
1178 htlc_minimum_msat: 0,
1180 fee_proportional_millionths: 0,
1181 last_update_message: None,
1182 }, two_to_one: DirectionalChannelInfo {
1183 src_node_id: node5.clone(),
1186 cltv_expiry_delta: (6 << 8) | 2,
1187 htlc_minimum_msat: 0,
1189 fee_proportional_millionths: 0,
1190 last_update_message: None,
1192 announcement_message: None,
1194 network.channels.insert(NetworkMap::get_key(11, zero_hash.clone()), ChannelInfo {
1195 features: GlobalFeatures::new(),
1196 one_to_two: DirectionalChannelInfo {
1197 src_node_id: node5.clone(),
1200 cltv_expiry_delta: (11 << 8) | 1,
1201 htlc_minimum_msat: 0,
1203 fee_proportional_millionths: 0,
1204 last_update_message: None,
1205 }, two_to_one: DirectionalChannelInfo {
1206 src_node_id: node4.clone(),
1209 cltv_expiry_delta: (11 << 8) | 2,
1210 htlc_minimum_msat: 0,
1212 fee_proportional_millionths: 0,
1213 last_update_message: None,
1215 announcement_message: None,
1217 network.nodes.insert(node6.clone(), NodeInfo {
1218 channels: vec!(NetworkMap::get_key(7, zero_hash.clone())),
1219 lowest_inbound_channel_fee_base_msat: 0,
1220 lowest_inbound_channel_fee_proportional_millionths: 0,
1221 features: GlobalFeatures::new(),
1225 addresses: Vec::new(),
1226 announcement_message: None,
1228 network.channels.insert(NetworkMap::get_key(7, zero_hash.clone()), ChannelInfo {
1229 features: GlobalFeatures::new(),
1230 one_to_two: DirectionalChannelInfo {
1231 src_node_id: node3.clone(),
1234 cltv_expiry_delta: (7 << 8) | 1,
1235 htlc_minimum_msat: 0,
1237 fee_proportional_millionths: 1000000,
1238 last_update_message: None,
1239 }, two_to_one: DirectionalChannelInfo {
1240 src_node_id: node6.clone(),
1243 cltv_expiry_delta: (7 << 8) | 2,
1244 htlc_minimum_msat: 0,
1246 fee_proportional_millionths: 0,
1247 last_update_message: None,
1249 announcement_message: None,
1253 { // Simple route to 3 via 2
1254 let route = router.get_route(&node3, None, &Vec::new(), 100, 42).unwrap();
1255 assert_eq!(route.hops.len(), 2);
1257 assert_eq!(route.hops[0].pubkey, node2);
1258 assert_eq!(route.hops[0].short_channel_id, 2);
1259 assert_eq!(route.hops[0].fee_msat, 100);
1260 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1262 assert_eq!(route.hops[1].pubkey, node3);
1263 assert_eq!(route.hops[1].short_channel_id, 4);
1264 assert_eq!(route.hops[1].fee_msat, 100);
1265 assert_eq!(route.hops[1].cltv_expiry_delta, 42);
1268 { // Route to 1 via 2 and 3 because our channel to 1 is disabled
1269 let route = router.get_route(&node1, None, &Vec::new(), 100, 42).unwrap();
1270 assert_eq!(route.hops.len(), 3);
1272 assert_eq!(route.hops[0].pubkey, node2);
1273 assert_eq!(route.hops[0].short_channel_id, 2);
1274 assert_eq!(route.hops[0].fee_msat, 200);
1275 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1277 assert_eq!(route.hops[1].pubkey, node3);
1278 assert_eq!(route.hops[1].short_channel_id, 4);
1279 assert_eq!(route.hops[1].fee_msat, 100);
1280 assert_eq!(route.hops[1].cltv_expiry_delta, (3 << 8) | 2);
1282 assert_eq!(route.hops[2].pubkey, node1);
1283 assert_eq!(route.hops[2].short_channel_id, 3);
1284 assert_eq!(route.hops[2].fee_msat, 100);
1285 assert_eq!(route.hops[2].cltv_expiry_delta, 42);
1288 { // If we specify a channel to node8, that overrides our local channel view and that gets used
1289 let our_chans = vec![channelmanager::ChannelDetails {
1290 channel_id: [0; 32],
1291 short_channel_id: Some(42),
1292 remote_network_id: node8.clone(),
1293 channel_value_satoshis: 0,
1296 let route = router.get_route(&node3, Some(&our_chans), &Vec::new(), 100, 42).unwrap();
1297 assert_eq!(route.hops.len(), 2);
1299 assert_eq!(route.hops[0].pubkey, node8);
1300 assert_eq!(route.hops[0].short_channel_id, 42);
1301 assert_eq!(route.hops[0].fee_msat, 200);
1302 assert_eq!(route.hops[0].cltv_expiry_delta, (13 << 8) | 1);
1304 assert_eq!(route.hops[1].pubkey, node3);
1305 assert_eq!(route.hops[1].short_channel_id, 13);
1306 assert_eq!(route.hops[1].fee_msat, 100);
1307 assert_eq!(route.hops[1].cltv_expiry_delta, 42);
1310 let mut last_hops = vec!(RouteHint {
1311 src_node_id: node4.clone(),
1312 short_channel_id: 8,
1314 fee_proportional_millionths: 0,
1315 cltv_expiry_delta: (8 << 8) | 1,
1316 htlc_minimum_msat: 0,
1318 src_node_id: node5.clone(),
1319 short_channel_id: 9,
1320 fee_base_msat: 1001,
1321 fee_proportional_millionths: 0,
1322 cltv_expiry_delta: (9 << 8) | 1,
1323 htlc_minimum_msat: 0,
1325 src_node_id: node6.clone(),
1326 short_channel_id: 10,
1328 fee_proportional_millionths: 0,
1329 cltv_expiry_delta: (10 << 8) | 1,
1330 htlc_minimum_msat: 0,
1333 { // Simple test across 2, 3, 5, and 4 via a last_hop channel
1334 let route = router.get_route(&node7, None, &last_hops, 100, 42).unwrap();
1335 assert_eq!(route.hops.len(), 5);
1337 assert_eq!(route.hops[0].pubkey, node2);
1338 assert_eq!(route.hops[0].short_channel_id, 2);
1339 assert_eq!(route.hops[0].fee_msat, 100);
1340 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1342 assert_eq!(route.hops[1].pubkey, node3);
1343 assert_eq!(route.hops[1].short_channel_id, 4);
1344 assert_eq!(route.hops[1].fee_msat, 0);
1345 assert_eq!(route.hops[1].cltv_expiry_delta, (6 << 8) | 1);
1347 assert_eq!(route.hops[2].pubkey, node5);
1348 assert_eq!(route.hops[2].short_channel_id, 6);
1349 assert_eq!(route.hops[2].fee_msat, 0);
1350 assert_eq!(route.hops[2].cltv_expiry_delta, (11 << 8) | 1);
1352 assert_eq!(route.hops[3].pubkey, node4);
1353 assert_eq!(route.hops[3].short_channel_id, 11);
1354 assert_eq!(route.hops[3].fee_msat, 0);
1355 assert_eq!(route.hops[3].cltv_expiry_delta, (8 << 8) | 1);
1357 assert_eq!(route.hops[4].pubkey, node7);
1358 assert_eq!(route.hops[4].short_channel_id, 8);
1359 assert_eq!(route.hops[4].fee_msat, 100);
1360 assert_eq!(route.hops[4].cltv_expiry_delta, 42);
1363 { // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
1364 let our_chans = vec![channelmanager::ChannelDetails {
1365 channel_id: [0; 32],
1366 short_channel_id: Some(42),
1367 remote_network_id: node4.clone(),
1368 channel_value_satoshis: 0,
1371 let route = router.get_route(&node7, Some(&our_chans), &last_hops, 100, 42).unwrap();
1372 assert_eq!(route.hops.len(), 2);
1374 assert_eq!(route.hops[0].pubkey, node4);
1375 assert_eq!(route.hops[0].short_channel_id, 42);
1376 assert_eq!(route.hops[0].fee_msat, 0);
1377 assert_eq!(route.hops[0].cltv_expiry_delta, (8 << 8) | 1);
1379 assert_eq!(route.hops[1].pubkey, node7);
1380 assert_eq!(route.hops[1].short_channel_id, 8);
1381 assert_eq!(route.hops[1].fee_msat, 100);
1382 assert_eq!(route.hops[1].cltv_expiry_delta, 42);
1385 last_hops[0].fee_base_msat = 1000;
1387 { // Revert to via 6 as the fee on 8 goes up
1388 let route = router.get_route(&node7, None, &last_hops, 100, 42).unwrap();
1389 assert_eq!(route.hops.len(), 4);
1391 assert_eq!(route.hops[0].pubkey, node2);
1392 assert_eq!(route.hops[0].short_channel_id, 2);
1393 assert_eq!(route.hops[0].fee_msat, 200); // fee increased as its % of value transferred across node
1394 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1396 assert_eq!(route.hops[1].pubkey, node3);
1397 assert_eq!(route.hops[1].short_channel_id, 4);
1398 assert_eq!(route.hops[1].fee_msat, 100);
1399 assert_eq!(route.hops[1].cltv_expiry_delta, (7 << 8) | 1);
1401 assert_eq!(route.hops[2].pubkey, node6);
1402 assert_eq!(route.hops[2].short_channel_id, 7);
1403 assert_eq!(route.hops[2].fee_msat, 0);
1404 assert_eq!(route.hops[2].cltv_expiry_delta, (10 << 8) | 1);
1406 assert_eq!(route.hops[3].pubkey, node7);
1407 assert_eq!(route.hops[3].short_channel_id, 10);
1408 assert_eq!(route.hops[3].fee_msat, 100);
1409 assert_eq!(route.hops[3].cltv_expiry_delta, 42);
1412 { // ...but still use 8 for larger payments as 6 has a variable feerate
1413 let route = router.get_route(&node7, None, &last_hops, 2000, 42).unwrap();
1414 assert_eq!(route.hops.len(), 5);
1416 assert_eq!(route.hops[0].pubkey, node2);
1417 assert_eq!(route.hops[0].short_channel_id, 2);
1418 assert_eq!(route.hops[0].fee_msat, 3000);
1419 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1421 assert_eq!(route.hops[1].pubkey, node3);
1422 assert_eq!(route.hops[1].short_channel_id, 4);
1423 assert_eq!(route.hops[1].fee_msat, 0);
1424 assert_eq!(route.hops[1].cltv_expiry_delta, (6 << 8) | 1);
1426 assert_eq!(route.hops[2].pubkey, node5);
1427 assert_eq!(route.hops[2].short_channel_id, 6);
1428 assert_eq!(route.hops[2].fee_msat, 0);
1429 assert_eq!(route.hops[2].cltv_expiry_delta, (11 << 8) | 1);
1431 assert_eq!(route.hops[3].pubkey, node4);
1432 assert_eq!(route.hops[3].short_channel_id, 11);
1433 assert_eq!(route.hops[3].fee_msat, 1000);
1434 assert_eq!(route.hops[3].cltv_expiry_delta, (8 << 8) | 1);
1436 assert_eq!(route.hops[4].pubkey, node7);
1437 assert_eq!(route.hops[4].short_channel_id, 8);
1438 assert_eq!(route.hops[4].fee_msat, 2000);
1439 assert_eq!(route.hops[4].cltv_expiry_delta, 42);