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, Writer, ReadableArgs};
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;
28 #[derive(Clone, PartialEq)]
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
42 #[derive(Clone, PartialEq)]
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)?,
82 struct DirectionalChannelInfo {
83 src_node_id: PublicKey,
86 cltv_expiry_delta: u16,
87 htlc_minimum_msat: u64,
89 fee_proportional_millionths: u32,
90 last_update_message: Option<msgs::ChannelUpdate>,
93 impl std::fmt::Display for DirectionalChannelInfo {
94 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
95 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 impl_writeable!(DirectionalChannelInfo, 0, {
107 fee_proportional_millionths,
113 features: GlobalFeatures,
114 one_to_two: DirectionalChannelInfo,
115 two_to_one: DirectionalChannelInfo,
116 //this is cached here so we can send out it later if required by route_init_sync
117 //keep an eye on this to see if the extra memory is a problem
118 announcement_message: Option<msgs::ChannelAnnouncement>,
121 impl std::fmt::Display for ChannelInfo {
122 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
123 write!(f, "features: {}, one_to_two: {}, two_to_one: {}", log_bytes!(self.features.encode()), self.one_to_two, self.two_to_one)?;
128 impl_writeable!(ChannelInfo, 0, {
137 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
138 channels: Vec<(u64, Sha256dHash)>,
139 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
142 lowest_inbound_channel_fee_base_msat: u32,
143 lowest_inbound_channel_fee_proportional_millionths: u32,
145 features: GlobalFeatures,
149 addresses: Vec<NetAddress>,
150 //this is cached here so we can send out it later if required by route_init_sync
151 //keep an eye on this to see if the extra memory is a problem
152 announcement_message: Option<msgs::NodeAnnouncement>,
155 impl std::fmt::Display for NodeInfo {
156 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
157 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[..])?;
162 impl Writeable for NodeInfo {
163 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
164 (self.channels.len() as u64).write(writer)?;
165 for ref chan in self.channels.iter() {
168 self.lowest_inbound_channel_fee_base_msat.write(writer)?;
169 self.lowest_inbound_channel_fee_proportional_millionths.write(writer)?;
170 self.features.write(writer)?;
171 self.last_update.write(writer)?;
172 self.rgb.write(writer)?;
173 self.alias.write(writer)?;
174 (self.addresses.len() as u64).write(writer)?;
175 for ref addr in &self.addresses {
178 self.announcement_message.write(writer)?;
183 const MAX_ALLOC_SIZE: u64 = 64*1024;
185 impl<R: ::std::io::Read> Readable<R> for NodeInfo {
186 fn read(reader: &mut R) -> Result<NodeInfo, DecodeError> {
187 let channels_count: u64 = Readable::read(reader)?;
188 let mut channels = Vec::with_capacity(cmp::min(channels_count, MAX_ALLOC_SIZE / 8) as usize);
189 for _ in 0..channels_count {
190 channels.push(Readable::read(reader)?);
192 let lowest_inbound_channel_fee_base_msat = Readable::read(reader)?;
193 let lowest_inbound_channel_fee_proportional_millionths = Readable::read(reader)?;
194 let features = Readable::read(reader)?;
195 let last_update = Readable::read(reader)?;
196 let rgb = Readable::read(reader)?;
197 let alias = Readable::read(reader)?;
198 let addresses_count: u64 = Readable::read(reader)?;
199 let mut addresses = Vec::with_capacity(cmp::min(addresses_count, MAX_ALLOC_SIZE / 40) as usize);
200 for _ in 0..addresses_count {
201 match Readable::read(reader) {
202 Ok(Ok(addr)) => { addresses.push(addr); },
203 Ok(Err(_)) => return Err(DecodeError::InvalidValue),
204 Err(DecodeError::ShortRead) => return Err(DecodeError::BadLengthDescriptor),
208 let announcement_message = Readable::read(reader)?;
211 lowest_inbound_channel_fee_base_msat,
212 lowest_inbound_channel_fee_proportional_millionths,
225 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
226 channels: BTreeMap<(u64, Sha256dHash), ChannelInfo>,
227 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
228 channels: BTreeMap<u64, ChannelInfo>,
230 our_node_id: PublicKey,
231 nodes: BTreeMap<PublicKey, NodeInfo>,
234 impl Writeable for NetworkMap {
235 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
236 (self.channels.len() as u64).write(writer)?;
237 for (ref chan_id, ref chan_info) in self.channels.iter() {
238 (*chan_id).write(writer)?;
239 chan_info.write(writer)?;
241 self.our_node_id.write(writer)?;
242 (self.nodes.len() as u64).write(writer)?;
243 for (ref node_id, ref node_info) in self.nodes.iter() {
244 node_id.write(writer)?;
245 node_info.write(writer)?;
251 impl<R: ::std::io::Read> Readable<R> for NetworkMap {
252 fn read(reader: &mut R) -> Result<NetworkMap, DecodeError> {
253 let channels_count: u64 = Readable::read(reader)?;
254 let mut channels = BTreeMap::new();
255 for _ in 0..channels_count {
256 let chan_id: u64 = Readable::read(reader)?;
257 let chan_info = Readable::read(reader)?;
258 channels.insert(chan_id, chan_info);
260 let our_node_id = Readable::read(reader)?;
261 let nodes_count: u64 = Readable::read(reader)?;
262 let mut nodes = BTreeMap::new();
263 for _ in 0..nodes_count {
264 let node_id = Readable::read(reader)?;
265 let node_info = Readable::read(reader)?;
266 nodes.insert(node_id, node_info);
276 struct MutNetworkMap<'a> {
277 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
278 channels: &'a mut BTreeMap<(u64, Sha256dHash), ChannelInfo>,
279 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
280 channels: &'a mut BTreeMap<u64, ChannelInfo>,
281 nodes: &'a mut BTreeMap<PublicKey, NodeInfo>,
284 fn borrow_parts(&mut self) -> MutNetworkMap {
286 channels: &mut self.channels,
287 nodes: &mut self.nodes,
291 impl std::fmt::Display for NetworkMap {
292 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
293 write!(f, "Node id {} network map\n[Channels]\n", log_pubkey!(self.our_node_id))?;
294 for (key, val) in self.channels.iter() {
295 write!(f, " {}: {}\n", key, val)?;
297 write!(f, "[Nodes]\n")?;
298 for (key, val) in self.nodes.iter() {
299 write!(f, " {}: {}\n", log_pubkey!(key), val)?;
306 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
308 fn get_key(short_channel_id: u64, chain_hash: Sha256dHash) -> (u64, Sha256dHash) {
309 (short_channel_id, chain_hash)
312 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
314 fn get_key(short_channel_id: u64, _: Sha256dHash) -> u64 {
318 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
320 fn get_short_id(id: &(u64, Sha256dHash)) -> &u64 {
324 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
326 fn get_short_id(id: &u64) -> &u64 {
331 /// A channel descriptor which provides a last-hop route to get_route
332 pub struct RouteHint {
333 /// The node_id of the non-target end of the route
334 pub src_node_id: PublicKey,
335 /// The short_channel_id of this channel
336 pub short_channel_id: u64,
337 /// The static msat-denominated fee which must be paid to use this channel
338 pub fee_base_msat: u32,
339 /// The dynamic proportional fee which must be paid to use this channel, denominated in
340 /// millionths of the value being forwarded to the next hop.
341 pub fee_proportional_millionths: u32,
342 /// The difference in CLTV values between this node and the next node.
343 pub cltv_expiry_delta: u16,
344 /// The minimum value, in msat, which must be relayed to the next hop.
345 pub htlc_minimum_msat: u64,
348 /// Tracks a view of the network, receiving updates from peers and generating Routes to
349 /// payment destinations.
351 secp_ctx: Secp256k1<secp256k1::VerifyOnly>,
352 network_map: RwLock<NetworkMap>,
353 chain_monitor: Arc<ChainWatchInterface>,
357 const SERIALIZATION_VERSION: u8 = 1;
358 const MIN_SERIALIZATION_VERSION: u8 = 1;
360 impl Writeable for Router {
361 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
362 writer.write_all(&[SERIALIZATION_VERSION; 1])?;
363 writer.write_all(&[MIN_SERIALIZATION_VERSION; 1])?;
365 let network = self.network_map.read().unwrap();
366 network.write(writer)?;
371 /// Arguments for the creation of a Router that are not deserialized.
372 /// At a high-level, the process for deserializing a Router and resuming normal operation is:
373 /// 1) Deserialize the Router by filling in this struct and calling <Router>::read(reaser, args).
374 /// 2) Register the new Router with your ChainWatchInterface
375 pub struct RouterReadArgs {
376 /// The ChainWatchInterface for use in the Router in the future.
378 /// No calls to the ChainWatchInterface will be made during deserialization.
379 pub chain_monitor: Arc<ChainWatchInterface>,
380 /// The Logger for use in the ChannelManager and which may be used to log information during
382 pub logger: Arc<Logger>,
385 impl<R: ::std::io::Read> ReadableArgs<R, RouterReadArgs> for Router {
386 fn read(reader: &mut R, args: RouterReadArgs) -> Result<Router, DecodeError> {
387 let _ver: u8 = Readable::read(reader)?;
388 let min_ver: u8 = Readable::read(reader)?;
389 if min_ver > SERIALIZATION_VERSION {
390 return Err(DecodeError::UnknownVersion);
392 let network_map = Readable::read(reader)?;
394 secp_ctx: Secp256k1::verification_only(),
395 network_map: RwLock::new(network_map),
396 chain_monitor: args.chain_monitor,
402 macro_rules! secp_verify_sig {
403 ( $secp_ctx: expr, $msg: expr, $sig: expr, $pubkey: expr ) => {
404 match $secp_ctx.verify($msg, $sig, $pubkey) {
406 Err(_) => return Err(HandleError{err: "Invalid signature from remote node", action: None}),
411 impl RoutingMessageHandler for Router {
412 fn handle_node_announcement(&self, msg: &msgs::NodeAnnouncement) -> Result<bool, HandleError> {
413 let msg_hash = Message::from_slice(&Sha256dHash::from_data(&msg.contents.encode()[..])[..]).unwrap();
414 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.signature, &msg.contents.node_id);
416 if msg.contents.features.requires_unknown_bits() {
417 panic!("Unknown-required-features NodeAnnouncements should never deserialize!");
420 let mut network = self.network_map.write().unwrap();
421 match network.nodes.get_mut(&msg.contents.node_id) {
422 None => Err(HandleError{err: "No existing channels for node_announcement", action: Some(ErrorAction::IgnoreError)}),
424 if node.last_update >= msg.contents.timestamp {
425 return Err(HandleError{err: "Update older than last processed update", action: Some(ErrorAction::IgnoreError)});
428 node.features = msg.contents.features.clone();
429 node.last_update = msg.contents.timestamp;
430 node.rgb = msg.contents.rgb;
431 node.alias = msg.contents.alias;
432 node.addresses = msg.contents.addresses.clone();
434 let should_relay = msg.contents.excess_data.is_empty() && msg.contents.excess_address_data.is_empty() && !msg.contents.features.supports_unknown_bits();
435 node.announcement_message = if should_relay { Some(msg.clone()) } else { None };
441 fn handle_channel_announcement(&self, msg: &msgs::ChannelAnnouncement) -> Result<bool, HandleError> {
442 if msg.contents.node_id_1 == msg.contents.node_id_2 || msg.contents.bitcoin_key_1 == msg.contents.bitcoin_key_2 {
443 return Err(HandleError{err: "Channel announcement node had a channel with itself", action: Some(ErrorAction::IgnoreError)});
446 let msg_hash = Message::from_slice(&Sha256dHash::from_data(&msg.contents.encode()[..])[..]).unwrap();
447 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.node_signature_1, &msg.contents.node_id_1);
448 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.node_signature_2, &msg.contents.node_id_2);
449 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.bitcoin_signature_1, &msg.contents.bitcoin_key_1);
450 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.bitcoin_signature_2, &msg.contents.bitcoin_key_2);
452 if msg.contents.features.requires_unknown_bits() {
453 panic!("Unknown-required-features ChannelAnnouncements should never deserialize!");
456 let checked_utxo = match self.chain_monitor.get_chain_utxo(msg.contents.chain_hash, msg.contents.short_channel_id) {
457 Ok((script_pubkey, _value)) => {
458 let expected_script = Builder::new().push_opcode(opcodes::All::OP_PUSHNUM_2)
459 .push_slice(&msg.contents.bitcoin_key_1.serialize())
460 .push_slice(&msg.contents.bitcoin_key_2.serialize())
461 .push_opcode(opcodes::All::OP_PUSHNUM_2).push_opcode(opcodes::All::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
462 if script_pubkey != expected_script {
463 return Err(HandleError{err: "Channel announcement keys didn't match on-chain script", action: Some(ErrorAction::IgnoreError)});
465 //TODO: Check if value is worth storing, use it to inform routing, and compare it
466 //to the new HTLC max field in channel_update
469 Err(ChainError::NotSupported) => {
470 // Tentatively accept, potentially exposing us to DoS attacks
473 Err(ChainError::NotWatched) => {
474 return Err(HandleError{err: "Channel announced on an unknown chain", action: Some(ErrorAction::IgnoreError)});
476 Err(ChainError::UnknownTx) => {
477 return Err(HandleError{err: "Channel announced without corresponding UTXO entry", action: Some(ErrorAction::IgnoreError)});
481 let mut network_lock = self.network_map.write().unwrap();
482 let network = network_lock.borrow_parts();
484 let should_relay = msg.contents.excess_data.is_empty() && !msg.contents.features.supports_unknown_bits();
486 let chan_info = ChannelInfo {
487 features: msg.contents.features.clone(),
488 one_to_two: DirectionalChannelInfo {
489 src_node_id: msg.contents.node_id_1.clone(),
492 cltv_expiry_delta: u16::max_value(),
493 htlc_minimum_msat: u64::max_value(),
494 fee_base_msat: u32::max_value(),
495 fee_proportional_millionths: u32::max_value(),
496 last_update_message: None,
498 two_to_one: DirectionalChannelInfo {
499 src_node_id: msg.contents.node_id_2.clone(),
502 cltv_expiry_delta: u16::max_value(),
503 htlc_minimum_msat: u64::max_value(),
504 fee_base_msat: u32::max_value(),
505 fee_proportional_millionths: u32::max_value(),
506 last_update_message: None,
508 announcement_message: if should_relay { Some(msg.clone()) } else { None },
511 match network.channels.entry(NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash)) {
512 BtreeEntry::Occupied(mut entry) => {
513 //TODO: because asking the blockchain if short_channel_id is valid is only optional
514 //in the blockchain API, we need to handle it smartly here, though its unclear
517 // Either our UTXO provider is busted, there was a reorg, or the UTXO provider
518 // only sometimes returns results. In any case remove the previous entry. Note
519 // that the spec expects us to "blacklist" the node_ids involved, but we can't
521 // a) we don't *require* a UTXO provider that always returns results.
522 // b) we don't track UTXOs of channels we know about and remove them if they
524 // c) it's unclear how to do so without exposing ourselves to massive DoS risk.
525 Self::remove_channel_in_nodes(network.nodes, &entry.get(), msg.contents.short_channel_id);
526 *entry.get_mut() = chan_info;
528 return Err(HandleError{err: "Already have knowledge of channel", action: Some(ErrorAction::IgnoreError)})
531 BtreeEntry::Vacant(entry) => {
532 entry.insert(chan_info);
536 macro_rules! add_channel_to_node {
537 ( $node_id: expr ) => {
538 match network.nodes.entry($node_id) {
539 BtreeEntry::Occupied(node_entry) => {
540 node_entry.into_mut().channels.push(NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash));
542 BtreeEntry::Vacant(node_entry) => {
543 node_entry.insert(NodeInfo {
544 channels: vec!(NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash)),
545 lowest_inbound_channel_fee_base_msat: u32::max_value(),
546 lowest_inbound_channel_fee_proportional_millionths: u32::max_value(),
547 features: GlobalFeatures::new(),
551 addresses: Vec::new(),
552 announcement_message: None,
559 add_channel_to_node!(msg.contents.node_id_1);
560 add_channel_to_node!(msg.contents.node_id_2);
565 fn handle_htlc_fail_channel_update(&self, update: &msgs::HTLCFailChannelUpdate) {
567 &msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg } => {
568 let _ = self.handle_channel_update(msg);
570 &msgs::HTLCFailChannelUpdate::ChannelClosed { ref short_channel_id, ref is_permanent } => {
571 let mut network = self.network_map.write().unwrap();
573 if let Some(chan) = network.channels.remove(short_channel_id) {
574 Self::remove_channel_in_nodes(&mut network.nodes, &chan, *short_channel_id);
577 if let Some(chan) = network.channels.get_mut(short_channel_id) {
578 chan.one_to_two.enabled = false;
579 chan.two_to_one.enabled = false;
583 &msgs::HTLCFailChannelUpdate::NodeFailure { ref node_id, ref is_permanent } => {
585 //TODO: Wholly remove the node
587 self.mark_node_bad(node_id, false);
593 fn handle_channel_update(&self, msg: &msgs::ChannelUpdate) -> Result<bool, HandleError> {
594 let mut network = self.network_map.write().unwrap();
596 let chan_enabled = msg.contents.flags & (1 << 1) != (1 << 1);
597 let chan_was_enabled;
599 match network.channels.get_mut(&NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash)) {
600 None => return Err(HandleError{err: "Couldn't find channel for update", action: Some(ErrorAction::IgnoreError)}),
602 macro_rules! maybe_update_channel_info {
603 ( $target: expr) => {
604 if $target.last_update >= msg.contents.timestamp {
605 return Err(HandleError{err: "Update older than last processed update", action: Some(ErrorAction::IgnoreError)});
607 chan_was_enabled = $target.enabled;
608 $target.last_update = msg.contents.timestamp;
609 $target.enabled = chan_enabled;
610 $target.cltv_expiry_delta = msg.contents.cltv_expiry_delta;
611 $target.htlc_minimum_msat = msg.contents.htlc_minimum_msat;
612 $target.fee_base_msat = msg.contents.fee_base_msat;
613 $target.fee_proportional_millionths = msg.contents.fee_proportional_millionths;
614 $target.last_update_message = if msg.contents.excess_data.is_empty() {
621 let msg_hash = Message::from_slice(&Sha256dHash::from_data(&msg.contents.encode()[..])[..]).unwrap();
622 if msg.contents.flags & 1 == 1 {
623 dest_node_id = channel.one_to_two.src_node_id.clone();
624 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.signature, &channel.two_to_one.src_node_id);
625 maybe_update_channel_info!(channel.two_to_one);
627 dest_node_id = channel.two_to_one.src_node_id.clone();
628 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.signature, &channel.one_to_two.src_node_id);
629 maybe_update_channel_info!(channel.one_to_two);
635 let node = network.nodes.get_mut(&dest_node_id).unwrap();
636 node.lowest_inbound_channel_fee_base_msat = cmp::min(node.lowest_inbound_channel_fee_base_msat, msg.contents.fee_base_msat);
637 node.lowest_inbound_channel_fee_proportional_millionths = cmp::min(node.lowest_inbound_channel_fee_proportional_millionths, msg.contents.fee_proportional_millionths);
638 } else if chan_was_enabled {
639 let mut lowest_inbound_channel_fee_base_msat = u32::max_value();
640 let mut lowest_inbound_channel_fee_proportional_millionths = u32::max_value();
643 let node = network.nodes.get(&dest_node_id).unwrap();
645 for chan_id in node.channels.iter() {
646 let chan = network.channels.get(chan_id).unwrap();
647 if chan.one_to_two.src_node_id == dest_node_id {
648 lowest_inbound_channel_fee_base_msat = cmp::min(lowest_inbound_channel_fee_base_msat, chan.two_to_one.fee_base_msat);
649 lowest_inbound_channel_fee_proportional_millionths = cmp::min(lowest_inbound_channel_fee_proportional_millionths, chan.two_to_one.fee_proportional_millionths);
651 lowest_inbound_channel_fee_base_msat = cmp::min(lowest_inbound_channel_fee_base_msat, chan.one_to_two.fee_base_msat);
652 lowest_inbound_channel_fee_proportional_millionths = cmp::min(lowest_inbound_channel_fee_proportional_millionths, chan.one_to_two.fee_proportional_millionths);
657 //TODO: satisfy the borrow-checker without a double-map-lookup :(
658 let mut_node = network.nodes.get_mut(&dest_node_id).unwrap();
659 mut_node.lowest_inbound_channel_fee_base_msat = lowest_inbound_channel_fee_base_msat;
660 mut_node.lowest_inbound_channel_fee_proportional_millionths = lowest_inbound_channel_fee_proportional_millionths;
663 Ok(msg.contents.excess_data.is_empty())
667 fn get_next_channel_announcements(&self, starting_point: u64, batch_amount: u8) -> Vec<(msgs::ChannelAnnouncement, msgs::ChannelUpdate,msgs::ChannelUpdate)> {
668 let mut result = Vec::with_capacity(batch_amount as usize);
669 let network = self.network_map.read().unwrap();
670 let mut iter = network.channels.range(starting_point..);
671 while result.len() < batch_amount as usize {
672 if let Some((_, ref chan)) = iter.next() {
673 if chan.announcement_message.is_some() &&
674 chan.one_to_two.last_update_message.is_some() &&
675 chan.two_to_one.last_update_message.is_some() {
676 result.push((chan.announcement_message.clone().unwrap(),
677 chan.one_to_two.last_update_message.clone().unwrap(),
678 chan.two_to_one.last_update_message.clone().unwrap()));
680 // TODO: We may end up sending un-announced channel_updates if we are sending
681 // initial sync data while receiving announce/updates for this channel.
690 fn get_next_node_announcements(&self, starting_point: Option<&PublicKey>, batch_amount: u8) -> Vec<msgs::NodeAnnouncement> {
691 let mut result = Vec::with_capacity(batch_amount as usize);
692 let network = self.network_map.read().unwrap();
693 let mut iter = if let Some(pubkey) = starting_point {
694 let mut iter = network.nodes.range((*pubkey)..);
698 network.nodes.range(..)
700 while result.len() < batch_amount as usize {
701 if let Some((_, ref node)) = iter.next() {
702 if node.announcement_message.is_some() {
703 result.push(node.announcement_message.clone().unwrap());
713 #[derive(Eq, PartialEq)]
714 struct RouteGraphNode {
716 lowest_fee_to_peer_through_node: u64,
717 lowest_fee_to_node: u64,
720 impl cmp::Ord for RouteGraphNode {
721 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
722 other.lowest_fee_to_peer_through_node.cmp(&self.lowest_fee_to_peer_through_node)
723 .then_with(|| other.pubkey.serialize().cmp(&self.pubkey.serialize()))
727 impl cmp::PartialOrd for RouteGraphNode {
728 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
729 Some(self.cmp(other))
733 struct DummyDirectionalChannelInfo {
734 src_node_id: PublicKey,
735 cltv_expiry_delta: u32,
736 htlc_minimum_msat: u64,
738 fee_proportional_millionths: u32,
742 /// Creates a new router with the given node_id to be used as the source for get_route()
743 pub fn new(our_pubkey: PublicKey, chain_monitor: Arc<ChainWatchInterface>, logger: Arc<Logger>) -> Router {
744 let mut nodes = BTreeMap::new();
745 nodes.insert(our_pubkey.clone(), NodeInfo {
746 channels: Vec::new(),
747 lowest_inbound_channel_fee_base_msat: u32::max_value(),
748 lowest_inbound_channel_fee_proportional_millionths: u32::max_value(),
749 features: GlobalFeatures::new(),
753 addresses: Vec::new(),
754 announcement_message: None,
757 secp_ctx: Secp256k1::verification_only(),
758 network_map: RwLock::new(NetworkMap {
759 channels: BTreeMap::new(),
760 our_node_id: our_pubkey,
768 /// Dumps the entire network view of this Router to the logger provided in the constructor at
770 pub fn trace_state(&self) {
771 log_trace!(self, "{}", self.network_map.read().unwrap());
774 /// Get network addresses by node id
775 pub fn get_addresses(&self, pubkey: &PublicKey) -> Option<Vec<NetAddress>> {
776 let network = self.network_map.read().unwrap();
777 network.nodes.get(pubkey).map(|n| n.addresses.clone())
780 /// Marks a node as having failed a route. This will avoid re-using the node in routes for now,
781 /// with an expotnential decay in node "badness". Note that there is deliberately no
782 /// mark_channel_bad as a node may simply lie and suggest that an upstream channel from it is
783 /// what failed the route and not the node itself. Instead, setting the blamed_upstream_node
784 /// boolean will reduce the penalty, returning the node to usability faster. If the node is
785 /// behaving correctly, it will disable the failing channel and we will use it again next time.
786 pub fn mark_node_bad(&self, _node_id: &PublicKey, _blamed_upstream_node: bool) {
790 fn remove_channel_in_nodes(nodes: &mut BTreeMap<PublicKey, NodeInfo>, chan: &ChannelInfo, short_channel_id: u64) {
791 macro_rules! remove_from_node {
792 ($node_id: expr) => {
793 if let BtreeEntry::Occupied(mut entry) = nodes.entry($node_id) {
794 entry.get_mut().channels.retain(|chan_id| {
795 short_channel_id != *NetworkMap::get_short_id(chan_id)
797 if entry.get().channels.is_empty() {
798 entry.remove_entry();
801 panic!("Had channel that pointed to unknown node (ie inconsistent network map)!");
805 remove_from_node!(chan.one_to_two.src_node_id);
806 remove_from_node!(chan.two_to_one.src_node_id);
809 /// Gets a route from us to the given target node.
811 /// Extra routing hops between known nodes and the target will be used if they are included in
814 /// If some channels aren't announced, it may be useful to fill in a first_hops with the
815 /// results from a local ChannelManager::list_usable_channels() call. If it is filled in, our
816 /// (this Router's) view of our local channels will be ignored, and only those in first_hops
819 /// Panics if first_hops contains channels without short_channel_ids
820 /// (ChannelManager::list_usable_channels will never include such channels).
822 /// The fees on channels from us to next-hops are ignored (as they are assumed to all be
823 /// equal), however the enabled/disabled bit on such channels as well as the htlc_minimum_msat
824 /// *is* checked as they may change based on the receiving node.
825 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> {
826 // TODO: Obviously *only* using total fee cost sucks. We should consider weighting by
827 // uptime/success in using a node in the past.
828 let network = self.network_map.read().unwrap();
830 if *target == network.our_node_id {
831 return Err(HandleError{err: "Cannot generate a route to ourselves", action: None});
834 if final_value_msat > 21_000_000 * 1_0000_0000 * 1000 {
835 return Err(HandleError{err: "Cannot generate a route of more value than all existing satoshis", action: None});
838 // We do a dest-to-source Dijkstra's sorting by each node's distance from the destination
839 // plus the minimum per-HTLC fee to get from it to another node (aka "shitty A*").
840 // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
841 // to use as the A* heuristic beyond just the cost to get one node further than the current
844 let dummy_directional_info = DummyDirectionalChannelInfo { // used for first_hops routes
845 src_node_id: network.our_node_id.clone(),
846 cltv_expiry_delta: 0,
847 htlc_minimum_msat: 0,
849 fee_proportional_millionths: 0,
852 let mut targets = BinaryHeap::new(); //TODO: Do we care about switching to eg Fibbonaci heap?
853 let mut dist = HashMap::with_capacity(network.nodes.len());
855 let mut first_hop_targets = HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
856 if let Some(hops) = first_hops {
858 let short_channel_id = chan.short_channel_id.expect("first_hops should be filled in with usable channels, not pending ones");
859 if chan.remote_network_id == *target {
861 hops: vec![RouteHop {
862 pubkey: chan.remote_network_id,
864 fee_msat: final_value_msat,
865 cltv_expiry_delta: final_cltv,
869 first_hop_targets.insert(chan.remote_network_id, short_channel_id);
871 if first_hop_targets.is_empty() {
872 return Err(HandleError{err: "Cannot route when there are no outbound routes away from us", action: None});
876 macro_rules! add_entry {
877 // Adds entry which goes from the node pointed to by $directional_info to
878 // $dest_node_id over the channel with id $chan_id with fees described in
879 // $directional_info.
880 ( $chan_id: expr, $dest_node_id: expr, $directional_info: expr, $starting_fee_msat: expr ) => {
881 //TODO: Explore simply adding fee to hit htlc_minimum_msat
882 if $starting_fee_msat as u64 + final_value_msat > $directional_info.htlc_minimum_msat {
883 let proportional_fee_millions = ($starting_fee_msat + final_value_msat).checked_mul($directional_info.fee_proportional_millionths as u64);
884 if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
885 ($directional_info.fee_base_msat as u64).checked_add(part / 1000000) })
887 let mut total_fee = $starting_fee_msat as u64;
888 let hm_entry = dist.entry(&$directional_info.src_node_id);
889 let old_entry = hm_entry.or_insert_with(|| {
890 let node = network.nodes.get(&$directional_info.src_node_id).unwrap();
892 node.lowest_inbound_channel_fee_base_msat,
893 node.lowest_inbound_channel_fee_proportional_millionths,
895 pubkey: $dest_node_id.clone(),
898 cltv_expiry_delta: 0,
901 if $directional_info.src_node_id != network.our_node_id {
902 // Ignore new_fee for channel-from-us as we assume all channels-from-us
903 // will have the same effective-fee
904 total_fee += new_fee;
905 if let Some(fee_inc) = final_value_msat.checked_add(total_fee).and_then(|inc| { (old_entry.2 as u64).checked_mul(inc) }) {
906 total_fee += fee_inc / 1000000 + (old_entry.1 as u64);
908 // max_value means we'll always fail the old_entry.0 > total_fee check
909 total_fee = u64::max_value();
912 let new_graph_node = RouteGraphNode {
913 pubkey: $directional_info.src_node_id,
914 lowest_fee_to_peer_through_node: total_fee,
915 lowest_fee_to_node: $starting_fee_msat as u64 + new_fee,
917 if old_entry.0 > total_fee {
918 targets.push(new_graph_node);
919 old_entry.0 = total_fee;
920 old_entry.3 = RouteHop {
921 pubkey: $dest_node_id.clone(),
922 short_channel_id: $chan_id.clone(),
923 fee_msat: new_fee, // This field is ignored on the last-hop anyway
924 cltv_expiry_delta: $directional_info.cltv_expiry_delta as u32,
932 macro_rules! add_entries_to_cheapest_to_target_node {
933 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr ) => {
934 if first_hops.is_some() {
935 if let Some(first_hop) = first_hop_targets.get(&$node_id) {
936 add_entry!(first_hop, $node_id, dummy_directional_info, $fee_to_target_msat);
940 for chan_id in $node.channels.iter() {
941 let chan = network.channels.get(chan_id).unwrap();
942 if chan.one_to_two.src_node_id == *$node_id {
943 // ie $node is one, ie next hop in A* is two, via the two_to_one channel
944 if first_hops.is_none() || chan.two_to_one.src_node_id != network.our_node_id {
945 if chan.two_to_one.enabled {
946 add_entry!(chan_id, chan.one_to_two.src_node_id, chan.two_to_one, $fee_to_target_msat);
950 if first_hops.is_none() || chan.one_to_two.src_node_id != network.our_node_id {
951 if chan.one_to_two.enabled {
952 add_entry!(chan_id, chan.two_to_one.src_node_id, chan.one_to_two, $fee_to_target_msat);
960 match network.nodes.get(target) {
963 add_entries_to_cheapest_to_target_node!(node, target, 0);
967 for hop in last_hops.iter() {
968 if first_hops.is_none() || hop.src_node_id != network.our_node_id { // first_hop overrules last_hops
969 if network.nodes.get(&hop.src_node_id).is_some() {
970 if first_hops.is_some() {
971 if let Some(first_hop) = first_hop_targets.get(&hop.src_node_id) {
972 add_entry!(first_hop, hop.src_node_id, dummy_directional_info, 0);
975 add_entry!(hop.short_channel_id, target, hop, 0);
980 while let Some(RouteGraphNode { pubkey, lowest_fee_to_node, .. }) = targets.pop() {
981 if pubkey == network.our_node_id {
982 let mut res = vec!(dist.remove(&network.our_node_id).unwrap().3);
983 while res.last().unwrap().pubkey != *target {
984 let new_entry = match dist.remove(&res.last().unwrap().pubkey) {
986 None => return Err(HandleError{err: "Failed to find a non-fee-overflowing path to the given destination", action: None}),
988 res.last_mut().unwrap().fee_msat = new_entry.fee_msat;
989 res.last_mut().unwrap().cltv_expiry_delta = new_entry.cltv_expiry_delta;
992 res.last_mut().unwrap().fee_msat = final_value_msat;
993 res.last_mut().unwrap().cltv_expiry_delta = final_cltv;
994 let route = Route { hops: res };
995 log_trace!(self, "Got route: {}", log_route!(route));
999 match network.nodes.get(&pubkey) {
1002 add_entries_to_cheapest_to_target_node!(node, &pubkey, lowest_fee_to_node);
1007 Err(HandleError{err: "Failed to find a path to the given destination", action: None})
1013 use chain::chaininterface;
1014 use ln::channelmanager;
1015 use ln::router::{Router,NodeInfo,NetworkMap,ChannelInfo,DirectionalChannelInfo,RouteHint};
1016 use ln::msgs::GlobalFeatures;
1017 use util::test_utils;
1018 use util::test_utils::TestVecWriter;
1019 use util::logger::Logger;
1020 use util::ser::{Writeable, Readable};
1022 use bitcoin::util::hash::Sha256dHash;
1023 use bitcoin::network::constants::Network;
1027 use secp256k1::key::{PublicKey,SecretKey};
1028 use secp256k1::Secp256k1;
1034 let secp_ctx = Secp256k1::new();
1035 let our_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap());
1036 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
1037 let chain_monitor = Arc::new(chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet, Arc::clone(&logger)));
1038 let router = Router::new(our_id, chain_monitor, Arc::clone(&logger));
1040 // Build network from our_id to node8:
1042 // -1(1)2- node1 -1(3)2-
1044 // our_id -1(12)2- node8 -1(13)2--- node3
1046 // -1(2)2- node2 -1(4)2-
1049 // chan1 1-to-2: disabled
1050 // chan1 2-to-1: enabled, 0 fee
1052 // chan2 1-to-2: enabled, ignored fee
1053 // chan2 2-to-1: enabled, 0 fee
1055 // chan3 1-to-2: enabled, 0 fee
1056 // chan3 2-to-1: enabled, 100 msat fee
1058 // chan4 1-to-2: enabled, 100% fee
1059 // chan4 2-to-1: enabled, 0 fee
1061 // chan12 1-to-2: enabled, ignored fee
1062 // chan12 2-to-1: enabled, 0 fee
1064 // chan13 1-to-2: enabled, 200% fee
1065 // chan13 2-to-1: enabled, 0 fee
1068 // -1(5)2- node4 -1(8)2--
1072 // node3--1(6)2- node5 -1(9)2--- node7 (not in global route map)
1074 // -1(7)2- node6 -1(10)2-
1076 // chan5 1-to-2: enabled, 100 msat fee
1077 // chan5 2-to-1: enabled, 0 fee
1079 // chan6 1-to-2: enabled, 0 fee
1080 // chan6 2-to-1: enabled, 0 fee
1082 // chan7 1-to-2: enabled, 100% fee
1083 // chan7 2-to-1: enabled, 0 fee
1085 // chan8 1-to-2: enabled, variable fee (0 then 1000 msat)
1086 // chan8 2-to-1: enabled, 0 fee
1088 // chan9 1-to-2: enabled, 1001 msat fee
1089 // chan9 2-to-1: enabled, 0 fee
1091 // chan10 1-to-2: enabled, 0 fee
1092 // chan10 2-to-1: enabled, 0 fee
1094 // chan11 1-to-2: enabled, 0 fee
1095 // chan11 2-to-1: enabled, 0 fee
1097 let node1 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap()[..]).unwrap());
1098 let node2 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0303030303030303030303030303030303030303030303030303030303030303").unwrap()[..]).unwrap());
1099 let node3 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0404040404040404040404040404040404040404040404040404040404040404").unwrap()[..]).unwrap());
1100 let node4 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0505050505050505050505050505050505050505050505050505050505050505").unwrap()[..]).unwrap());
1101 let node5 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0606060606060606060606060606060606060606060606060606060606060606").unwrap()[..]).unwrap());
1102 let node6 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0707070707070707070707070707070707070707070707070707070707070707").unwrap()[..]).unwrap());
1103 let node7 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0808080808080808080808080808080808080808080808080808080808080808").unwrap()[..]).unwrap());
1104 let node8 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&secp_ctx, &hex::decode("0909090909090909090909090909090909090909090909090909090909090909").unwrap()[..]).unwrap());
1106 let zero_hash = Sha256dHash::from_data(&[0; 32]);
1109 let mut network = router.network_map.write().unwrap();
1111 network.nodes.insert(node1.clone(), NodeInfo {
1112 channels: vec!(NetworkMap::get_key(1, zero_hash.clone()), NetworkMap::get_key(3, zero_hash.clone())),
1113 lowest_inbound_channel_fee_base_msat: 100,
1114 lowest_inbound_channel_fee_proportional_millionths: 0,
1115 features: GlobalFeatures::new(),
1119 addresses: Vec::new(),
1120 announcement_message: None,
1122 network.channels.insert(NetworkMap::get_key(1, zero_hash.clone()), ChannelInfo {
1123 features: GlobalFeatures::new(),
1124 one_to_two: DirectionalChannelInfo {
1125 src_node_id: our_id.clone(),
1128 cltv_expiry_delta: u16::max_value(), // This value should be ignored
1129 htlc_minimum_msat: 0,
1130 fee_base_msat: u32::max_value(), // This value should be ignored
1131 fee_proportional_millionths: u32::max_value(), // This value should be ignored
1132 last_update_message: None,
1133 }, two_to_one: DirectionalChannelInfo {
1134 src_node_id: node1.clone(),
1137 cltv_expiry_delta: 0,
1138 htlc_minimum_msat: 0,
1140 fee_proportional_millionths: 0,
1141 last_update_message: None,
1143 announcement_message: None,
1145 network.nodes.insert(node2.clone(), NodeInfo {
1146 channels: vec!(NetworkMap::get_key(2, zero_hash.clone()), NetworkMap::get_key(4, zero_hash.clone())),
1147 lowest_inbound_channel_fee_base_msat: 0,
1148 lowest_inbound_channel_fee_proportional_millionths: 0,
1149 features: GlobalFeatures::new(),
1153 addresses: Vec::new(),
1154 announcement_message: None,
1156 network.channels.insert(NetworkMap::get_key(2, zero_hash.clone()), ChannelInfo {
1157 features: GlobalFeatures::new(),
1158 one_to_two: DirectionalChannelInfo {
1159 src_node_id: our_id.clone(),
1162 cltv_expiry_delta: u16::max_value(), // This value should be ignored
1163 htlc_minimum_msat: 0,
1164 fee_base_msat: u32::max_value(), // This value should be ignored
1165 fee_proportional_millionths: u32::max_value(), // This value should be ignored
1166 last_update_message: None,
1167 }, two_to_one: DirectionalChannelInfo {
1168 src_node_id: node2.clone(),
1171 cltv_expiry_delta: 0,
1172 htlc_minimum_msat: 0,
1174 fee_proportional_millionths: 0,
1175 last_update_message: None,
1177 announcement_message: None,
1179 network.nodes.insert(node8.clone(), NodeInfo {
1180 channels: vec!(NetworkMap::get_key(12, zero_hash.clone()), NetworkMap::get_key(13, zero_hash.clone())),
1181 lowest_inbound_channel_fee_base_msat: 0,
1182 lowest_inbound_channel_fee_proportional_millionths: 0,
1183 features: GlobalFeatures::new(),
1187 addresses: Vec::new(),
1188 announcement_message: None,
1190 network.channels.insert(NetworkMap::get_key(12, zero_hash.clone()), ChannelInfo {
1191 features: GlobalFeatures::new(),
1192 one_to_two: DirectionalChannelInfo {
1193 src_node_id: our_id.clone(),
1196 cltv_expiry_delta: u16::max_value(), // This value should be ignored
1197 htlc_minimum_msat: 0,
1198 fee_base_msat: u32::max_value(), // This value should be ignored
1199 fee_proportional_millionths: u32::max_value(), // This value should be ignored
1200 last_update_message: None,
1201 }, two_to_one: DirectionalChannelInfo {
1202 src_node_id: node8.clone(),
1205 cltv_expiry_delta: 0,
1206 htlc_minimum_msat: 0,
1208 fee_proportional_millionths: 0,
1209 last_update_message: None,
1211 announcement_message: None,
1213 network.nodes.insert(node3.clone(), NodeInfo {
1215 NetworkMap::get_key(3, zero_hash.clone()),
1216 NetworkMap::get_key(4, zero_hash.clone()),
1217 NetworkMap::get_key(13, zero_hash.clone()),
1218 NetworkMap::get_key(5, zero_hash.clone()),
1219 NetworkMap::get_key(6, zero_hash.clone()),
1220 NetworkMap::get_key(7, zero_hash.clone())),
1221 lowest_inbound_channel_fee_base_msat: 0,
1222 lowest_inbound_channel_fee_proportional_millionths: 0,
1223 features: GlobalFeatures::new(),
1227 addresses: Vec::new(),
1228 announcement_message: None,
1230 network.channels.insert(NetworkMap::get_key(3, zero_hash.clone()), ChannelInfo {
1231 features: GlobalFeatures::new(),
1232 one_to_two: DirectionalChannelInfo {
1233 src_node_id: node1.clone(),
1236 cltv_expiry_delta: (3 << 8) | 1,
1237 htlc_minimum_msat: 0,
1239 fee_proportional_millionths: 0,
1240 last_update_message: None,
1241 }, two_to_one: DirectionalChannelInfo {
1242 src_node_id: node3.clone(),
1245 cltv_expiry_delta: (3 << 8) | 2,
1246 htlc_minimum_msat: 0,
1248 fee_proportional_millionths: 0,
1249 last_update_message: None,
1251 announcement_message: None,
1253 network.channels.insert(NetworkMap::get_key(4, zero_hash.clone()), ChannelInfo {
1254 features: GlobalFeatures::new(),
1255 one_to_two: DirectionalChannelInfo {
1256 src_node_id: node2.clone(),
1259 cltv_expiry_delta: (4 << 8) | 1,
1260 htlc_minimum_msat: 0,
1262 fee_proportional_millionths: 1000000,
1263 last_update_message: None,
1264 }, two_to_one: DirectionalChannelInfo {
1265 src_node_id: node3.clone(),
1268 cltv_expiry_delta: (4 << 8) | 2,
1269 htlc_minimum_msat: 0,
1271 fee_proportional_millionths: 0,
1272 last_update_message: None,
1274 announcement_message: None,
1276 network.channels.insert(NetworkMap::get_key(13, zero_hash.clone()), ChannelInfo {
1277 features: GlobalFeatures::new(),
1278 one_to_two: DirectionalChannelInfo {
1279 src_node_id: node8.clone(),
1282 cltv_expiry_delta: (13 << 8) | 1,
1283 htlc_minimum_msat: 0,
1285 fee_proportional_millionths: 2000000,
1286 last_update_message: None,
1287 }, two_to_one: DirectionalChannelInfo {
1288 src_node_id: node3.clone(),
1291 cltv_expiry_delta: (13 << 8) | 2,
1292 htlc_minimum_msat: 0,
1294 fee_proportional_millionths: 0,
1295 last_update_message: None,
1297 announcement_message: None,
1299 network.nodes.insert(node4.clone(), NodeInfo {
1300 channels: vec!(NetworkMap::get_key(5, zero_hash.clone()), NetworkMap::get_key(11, zero_hash.clone())),
1301 lowest_inbound_channel_fee_base_msat: 0,
1302 lowest_inbound_channel_fee_proportional_millionths: 0,
1303 features: GlobalFeatures::new(),
1307 addresses: Vec::new(),
1308 announcement_message: None,
1310 network.channels.insert(NetworkMap::get_key(5, zero_hash.clone()), ChannelInfo {
1311 features: GlobalFeatures::new(),
1312 one_to_two: DirectionalChannelInfo {
1313 src_node_id: node3.clone(),
1316 cltv_expiry_delta: (5 << 8) | 1,
1317 htlc_minimum_msat: 0,
1319 fee_proportional_millionths: 0,
1320 last_update_message: None,
1321 }, two_to_one: DirectionalChannelInfo {
1322 src_node_id: node4.clone(),
1325 cltv_expiry_delta: (5 << 8) | 2,
1326 htlc_minimum_msat: 0,
1328 fee_proportional_millionths: 0,
1329 last_update_message: None,
1331 announcement_message: None,
1333 network.nodes.insert(node5.clone(), NodeInfo {
1334 channels: vec!(NetworkMap::get_key(6, zero_hash.clone()), NetworkMap::get_key(11, zero_hash.clone())),
1335 lowest_inbound_channel_fee_base_msat: 0,
1336 lowest_inbound_channel_fee_proportional_millionths: 0,
1337 features: GlobalFeatures::new(),
1341 addresses: Vec::new(),
1342 announcement_message: None,
1344 network.channels.insert(NetworkMap::get_key(6, zero_hash.clone()), ChannelInfo {
1345 features: GlobalFeatures::new(),
1346 one_to_two: DirectionalChannelInfo {
1347 src_node_id: node3.clone(),
1350 cltv_expiry_delta: (6 << 8) | 1,
1351 htlc_minimum_msat: 0,
1353 fee_proportional_millionths: 0,
1354 last_update_message: None,
1355 }, two_to_one: DirectionalChannelInfo {
1356 src_node_id: node5.clone(),
1359 cltv_expiry_delta: (6 << 8) | 2,
1360 htlc_minimum_msat: 0,
1362 fee_proportional_millionths: 0,
1363 last_update_message: None,
1365 announcement_message: None,
1367 network.channels.insert(NetworkMap::get_key(11, zero_hash.clone()), ChannelInfo {
1368 features: GlobalFeatures::new(),
1369 one_to_two: DirectionalChannelInfo {
1370 src_node_id: node5.clone(),
1373 cltv_expiry_delta: (11 << 8) | 1,
1374 htlc_minimum_msat: 0,
1376 fee_proportional_millionths: 0,
1377 last_update_message: None,
1378 }, two_to_one: DirectionalChannelInfo {
1379 src_node_id: node4.clone(),
1382 cltv_expiry_delta: (11 << 8) | 2,
1383 htlc_minimum_msat: 0,
1385 fee_proportional_millionths: 0,
1386 last_update_message: None,
1388 announcement_message: None,
1390 network.nodes.insert(node6.clone(), NodeInfo {
1391 channels: vec!(NetworkMap::get_key(7, zero_hash.clone())),
1392 lowest_inbound_channel_fee_base_msat: 0,
1393 lowest_inbound_channel_fee_proportional_millionths: 0,
1394 features: GlobalFeatures::new(),
1398 addresses: Vec::new(),
1399 announcement_message: None,
1401 network.channels.insert(NetworkMap::get_key(7, zero_hash.clone()), ChannelInfo {
1402 features: GlobalFeatures::new(),
1403 one_to_two: DirectionalChannelInfo {
1404 src_node_id: node3.clone(),
1407 cltv_expiry_delta: (7 << 8) | 1,
1408 htlc_minimum_msat: 0,
1410 fee_proportional_millionths: 1000000,
1411 last_update_message: None,
1412 }, two_to_one: DirectionalChannelInfo {
1413 src_node_id: node6.clone(),
1416 cltv_expiry_delta: (7 << 8) | 2,
1417 htlc_minimum_msat: 0,
1419 fee_proportional_millionths: 0,
1420 last_update_message: None,
1422 announcement_message: None,
1426 { // Simple route to 3 via 2
1427 let route = router.get_route(&node3, None, &Vec::new(), 100, 42).unwrap();
1428 assert_eq!(route.hops.len(), 2);
1430 assert_eq!(route.hops[0].pubkey, node2);
1431 assert_eq!(route.hops[0].short_channel_id, 2);
1432 assert_eq!(route.hops[0].fee_msat, 100);
1433 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1435 assert_eq!(route.hops[1].pubkey, node3);
1436 assert_eq!(route.hops[1].short_channel_id, 4);
1437 assert_eq!(route.hops[1].fee_msat, 100);
1438 assert_eq!(route.hops[1].cltv_expiry_delta, 42);
1441 { // Route to 1 via 2 and 3 because our channel to 1 is disabled
1442 let route = router.get_route(&node1, None, &Vec::new(), 100, 42).unwrap();
1443 assert_eq!(route.hops.len(), 3);
1445 assert_eq!(route.hops[0].pubkey, node2);
1446 assert_eq!(route.hops[0].short_channel_id, 2);
1447 assert_eq!(route.hops[0].fee_msat, 200);
1448 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1450 assert_eq!(route.hops[1].pubkey, node3);
1451 assert_eq!(route.hops[1].short_channel_id, 4);
1452 assert_eq!(route.hops[1].fee_msat, 100);
1453 assert_eq!(route.hops[1].cltv_expiry_delta, (3 << 8) | 2);
1455 assert_eq!(route.hops[2].pubkey, node1);
1456 assert_eq!(route.hops[2].short_channel_id, 3);
1457 assert_eq!(route.hops[2].fee_msat, 100);
1458 assert_eq!(route.hops[2].cltv_expiry_delta, 42);
1461 { // If we specify a channel to node8, that overrides our local channel view and that gets used
1462 let our_chans = vec![channelmanager::ChannelDetails {
1463 channel_id: [0; 32],
1464 short_channel_id: Some(42),
1465 remote_network_id: node8.clone(),
1466 channel_value_satoshis: 0,
1469 let route = router.get_route(&node3, Some(&our_chans), &Vec::new(), 100, 42).unwrap();
1470 assert_eq!(route.hops.len(), 2);
1472 assert_eq!(route.hops[0].pubkey, node8);
1473 assert_eq!(route.hops[0].short_channel_id, 42);
1474 assert_eq!(route.hops[0].fee_msat, 200);
1475 assert_eq!(route.hops[0].cltv_expiry_delta, (13 << 8) | 1);
1477 assert_eq!(route.hops[1].pubkey, node3);
1478 assert_eq!(route.hops[1].short_channel_id, 13);
1479 assert_eq!(route.hops[1].fee_msat, 100);
1480 assert_eq!(route.hops[1].cltv_expiry_delta, 42);
1483 let mut last_hops = vec!(RouteHint {
1484 src_node_id: node4.clone(),
1485 short_channel_id: 8,
1487 fee_proportional_millionths: 0,
1488 cltv_expiry_delta: (8 << 8) | 1,
1489 htlc_minimum_msat: 0,
1491 src_node_id: node5.clone(),
1492 short_channel_id: 9,
1493 fee_base_msat: 1001,
1494 fee_proportional_millionths: 0,
1495 cltv_expiry_delta: (9 << 8) | 1,
1496 htlc_minimum_msat: 0,
1498 src_node_id: node6.clone(),
1499 short_channel_id: 10,
1501 fee_proportional_millionths: 0,
1502 cltv_expiry_delta: (10 << 8) | 1,
1503 htlc_minimum_msat: 0,
1506 { // Simple test across 2, 3, 5, and 4 via a last_hop channel
1507 let route = router.get_route(&node7, None, &last_hops, 100, 42).unwrap();
1508 assert_eq!(route.hops.len(), 5);
1510 assert_eq!(route.hops[0].pubkey, node2);
1511 assert_eq!(route.hops[0].short_channel_id, 2);
1512 assert_eq!(route.hops[0].fee_msat, 100);
1513 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1515 assert_eq!(route.hops[1].pubkey, node3);
1516 assert_eq!(route.hops[1].short_channel_id, 4);
1517 assert_eq!(route.hops[1].fee_msat, 0);
1518 assert_eq!(route.hops[1].cltv_expiry_delta, (6 << 8) | 1);
1520 assert_eq!(route.hops[2].pubkey, node5);
1521 assert_eq!(route.hops[2].short_channel_id, 6);
1522 assert_eq!(route.hops[2].fee_msat, 0);
1523 assert_eq!(route.hops[2].cltv_expiry_delta, (11 << 8) | 1);
1525 assert_eq!(route.hops[3].pubkey, node4);
1526 assert_eq!(route.hops[3].short_channel_id, 11);
1527 assert_eq!(route.hops[3].fee_msat, 0);
1528 assert_eq!(route.hops[3].cltv_expiry_delta, (8 << 8) | 1);
1530 assert_eq!(route.hops[4].pubkey, node7);
1531 assert_eq!(route.hops[4].short_channel_id, 8);
1532 assert_eq!(route.hops[4].fee_msat, 100);
1533 assert_eq!(route.hops[4].cltv_expiry_delta, 42);
1536 { // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
1537 let our_chans = vec![channelmanager::ChannelDetails {
1538 channel_id: [0; 32],
1539 short_channel_id: Some(42),
1540 remote_network_id: node4.clone(),
1541 channel_value_satoshis: 0,
1544 let route = router.get_route(&node7, Some(&our_chans), &last_hops, 100, 42).unwrap();
1545 assert_eq!(route.hops.len(), 2);
1547 assert_eq!(route.hops[0].pubkey, node4);
1548 assert_eq!(route.hops[0].short_channel_id, 42);
1549 assert_eq!(route.hops[0].fee_msat, 0);
1550 assert_eq!(route.hops[0].cltv_expiry_delta, (8 << 8) | 1);
1552 assert_eq!(route.hops[1].pubkey, node7);
1553 assert_eq!(route.hops[1].short_channel_id, 8);
1554 assert_eq!(route.hops[1].fee_msat, 100);
1555 assert_eq!(route.hops[1].cltv_expiry_delta, 42);
1558 last_hops[0].fee_base_msat = 1000;
1560 { // Revert to via 6 as the fee on 8 goes up
1561 let route = router.get_route(&node7, None, &last_hops, 100, 42).unwrap();
1562 assert_eq!(route.hops.len(), 4);
1564 assert_eq!(route.hops[0].pubkey, node2);
1565 assert_eq!(route.hops[0].short_channel_id, 2);
1566 assert_eq!(route.hops[0].fee_msat, 200); // fee increased as its % of value transferred across node
1567 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1569 assert_eq!(route.hops[1].pubkey, node3);
1570 assert_eq!(route.hops[1].short_channel_id, 4);
1571 assert_eq!(route.hops[1].fee_msat, 100);
1572 assert_eq!(route.hops[1].cltv_expiry_delta, (7 << 8) | 1);
1574 assert_eq!(route.hops[2].pubkey, node6);
1575 assert_eq!(route.hops[2].short_channel_id, 7);
1576 assert_eq!(route.hops[2].fee_msat, 0);
1577 assert_eq!(route.hops[2].cltv_expiry_delta, (10 << 8) | 1);
1579 assert_eq!(route.hops[3].pubkey, node7);
1580 assert_eq!(route.hops[3].short_channel_id, 10);
1581 assert_eq!(route.hops[3].fee_msat, 100);
1582 assert_eq!(route.hops[3].cltv_expiry_delta, 42);
1585 { // ...but still use 8 for larger payments as 6 has a variable feerate
1586 let route = router.get_route(&node7, None, &last_hops, 2000, 42).unwrap();
1587 assert_eq!(route.hops.len(), 5);
1589 assert_eq!(route.hops[0].pubkey, node2);
1590 assert_eq!(route.hops[0].short_channel_id, 2);
1591 assert_eq!(route.hops[0].fee_msat, 3000);
1592 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1594 assert_eq!(route.hops[1].pubkey, node3);
1595 assert_eq!(route.hops[1].short_channel_id, 4);
1596 assert_eq!(route.hops[1].fee_msat, 0);
1597 assert_eq!(route.hops[1].cltv_expiry_delta, (6 << 8) | 1);
1599 assert_eq!(route.hops[2].pubkey, node5);
1600 assert_eq!(route.hops[2].short_channel_id, 6);
1601 assert_eq!(route.hops[2].fee_msat, 0);
1602 assert_eq!(route.hops[2].cltv_expiry_delta, (11 << 8) | 1);
1604 assert_eq!(route.hops[3].pubkey, node4);
1605 assert_eq!(route.hops[3].short_channel_id, 11);
1606 assert_eq!(route.hops[3].fee_msat, 1000);
1607 assert_eq!(route.hops[3].cltv_expiry_delta, (8 << 8) | 1);
1609 assert_eq!(route.hops[4].pubkey, node7);
1610 assert_eq!(route.hops[4].short_channel_id, 8);
1611 assert_eq!(route.hops[4].fee_msat, 2000);
1612 assert_eq!(route.hops[4].cltv_expiry_delta, 42);
1615 { // Test Router serialization/deserialization
1616 let mut w = TestVecWriter(Vec::new());
1617 let network = router.network_map.read().unwrap();
1618 assert!(!network.channels.is_empty());
1619 assert!(!network.nodes.is_empty());
1620 network.write(&mut w).unwrap();
1621 assert!(<NetworkMap>::read(&mut ::std::io::Cursor::new(&w.0)).unwrap() == *network);