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;
10 use bitcoin_hashes::sha256d::Hash as Sha256dHash;
11 use bitcoin_hashes::Hash;
12 use bitcoin::blockdata::script::Builder;
13 use bitcoin::blockdata::opcodes;
15 use chain::chaininterface::{ChainError, ChainWatchInterface};
16 use ln::channelmanager;
17 use ln::features::{ChannelFeatures, NodeFeatures};
18 use ln::msgs::{DecodeError,ErrorAction,LightningError,RoutingMessageHandler,NetAddress};
20 use util::ser::{Writeable, Readable, Writer, ReadableArgs};
21 use util::logger::Logger;
24 use std::sync::{RwLock,Arc};
25 use std::collections::{HashMap,BinaryHeap,BTreeMap};
26 use std::collections::btree_map::Entry as BtreeEntry;
30 #[derive(Clone, PartialEq)]
32 /// The node_id of the node at this hop.
33 pub pubkey: PublicKey,
34 /// The channel that should be used from the previous hop to reach this node.
35 pub short_channel_id: u64,
36 /// The fee taken on this hop. For the last hop, this should be the full value of the payment.
38 /// The CLTV delta added for this hop. For the last hop, this should be the full CLTV value
39 /// expected at the destination, in excess of the current block height.
40 pub cltv_expiry_delta: u32,
43 /// A route from us through the network to a destination
44 #[derive(Clone, PartialEq)]
46 /// The list of hops, NOT INCLUDING our own, where the last hop is the destination. Thus, this
47 /// must always be at least length one. By protocol rules, this may not currently exceed 20 in
49 pub hops: Vec<RouteHop>,
52 impl Writeable for Route {
53 fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
54 (self.hops.len() as u8).write(writer)?;
55 for hop in self.hops.iter() {
56 hop.pubkey.write(writer)?;
57 hop.short_channel_id.write(writer)?;
58 hop.fee_msat.write(writer)?;
59 hop.cltv_expiry_delta.write(writer)?;
65 impl<R: ::std::io::Read> Readable<R> for Route {
66 fn read(reader: &mut R) -> Result<Route, DecodeError> {
67 let hops_count: u8 = Readable::read(reader)?;
68 let mut hops = Vec::with_capacity(hops_count as usize);
69 for _ in 0..hops_count {
71 pubkey: Readable::read(reader)?,
72 short_channel_id: Readable::read(reader)?,
73 fee_msat: Readable::read(reader)?,
74 cltv_expiry_delta: Readable::read(reader)?,
84 struct DirectionalChannelInfo {
85 src_node_id: PublicKey,
88 cltv_expiry_delta: u16,
89 htlc_minimum_msat: u64,
91 fee_proportional_millionths: u32,
92 last_update_message: Option<msgs::ChannelUpdate>,
95 impl std::fmt::Display for DirectionalChannelInfo {
96 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
97 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)?;
102 impl_writeable!(DirectionalChannelInfo, 0, {
109 fee_proportional_millionths,
115 features: ChannelFeatures,
116 one_to_two: DirectionalChannelInfo,
117 two_to_one: DirectionalChannelInfo,
118 //this is cached here so we can send out it later if required by route_init_sync
119 //keep an eye on this to see if the extra memory is a problem
120 announcement_message: Option<msgs::ChannelAnnouncement>,
123 impl std::fmt::Display for ChannelInfo {
124 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
125 write!(f, "features: {}, one_to_two: {}, two_to_one: {}", log_bytes!(self.features.encode()), self.one_to_two, self.two_to_one)?;
130 impl_writeable!(ChannelInfo, 0, {
139 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
140 channels: Vec<(u64, Sha256dHash)>,
141 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
144 lowest_inbound_channel_fee_base_msat: u32,
145 lowest_inbound_channel_fee_proportional_millionths: u32,
147 features: NodeFeatures,
151 addresses: Vec<NetAddress>,
152 //this is cached here so we can send out it later if required by route_init_sync
153 //keep an eye on this to see if the extra memory is a problem
154 announcement_message: Option<msgs::NodeAnnouncement>,
157 impl std::fmt::Display for NodeInfo {
158 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
159 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[..])?;
164 impl Writeable for NodeInfo {
165 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
166 (self.channels.len() as u64).write(writer)?;
167 for ref chan in self.channels.iter() {
170 self.lowest_inbound_channel_fee_base_msat.write(writer)?;
171 self.lowest_inbound_channel_fee_proportional_millionths.write(writer)?;
172 self.features.write(writer)?;
173 self.last_update.write(writer)?;
174 self.rgb.write(writer)?;
175 self.alias.write(writer)?;
176 (self.addresses.len() as u64).write(writer)?;
177 for ref addr in &self.addresses {
180 self.announcement_message.write(writer)?;
185 const MAX_ALLOC_SIZE: u64 = 64*1024;
187 impl<R: ::std::io::Read> Readable<R> for NodeInfo {
188 fn read(reader: &mut R) -> Result<NodeInfo, DecodeError> {
189 let channels_count: u64 = Readable::read(reader)?;
190 let mut channels = Vec::with_capacity(cmp::min(channels_count, MAX_ALLOC_SIZE / 8) as usize);
191 for _ in 0..channels_count {
192 channels.push(Readable::read(reader)?);
194 let lowest_inbound_channel_fee_base_msat = Readable::read(reader)?;
195 let lowest_inbound_channel_fee_proportional_millionths = Readable::read(reader)?;
196 let features = Readable::read(reader)?;
197 let last_update = Readable::read(reader)?;
198 let rgb = Readable::read(reader)?;
199 let alias = Readable::read(reader)?;
200 let addresses_count: u64 = Readable::read(reader)?;
201 let mut addresses = Vec::with_capacity(cmp::min(addresses_count, MAX_ALLOC_SIZE / 40) as usize);
202 for _ in 0..addresses_count {
203 match Readable::read(reader) {
204 Ok(Ok(addr)) => { addresses.push(addr); },
205 Ok(Err(_)) => return Err(DecodeError::InvalidValue),
206 Err(DecodeError::ShortRead) => return Err(DecodeError::BadLengthDescriptor),
210 let announcement_message = Readable::read(reader)?;
213 lowest_inbound_channel_fee_base_msat,
214 lowest_inbound_channel_fee_proportional_millionths,
227 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
228 channels: BTreeMap<(u64, Sha256dHash), ChannelInfo>,
229 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
230 channels: BTreeMap<u64, ChannelInfo>,
232 our_node_id: PublicKey,
233 nodes: BTreeMap<PublicKey, NodeInfo>,
236 impl Writeable for NetworkMap {
237 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
238 (self.channels.len() as u64).write(writer)?;
239 for (ref chan_id, ref chan_info) in self.channels.iter() {
240 (*chan_id).write(writer)?;
241 chan_info.write(writer)?;
243 self.our_node_id.write(writer)?;
244 (self.nodes.len() as u64).write(writer)?;
245 for (ref node_id, ref node_info) in self.nodes.iter() {
246 node_id.write(writer)?;
247 node_info.write(writer)?;
253 impl<R: ::std::io::Read> Readable<R> for NetworkMap {
254 fn read(reader: &mut R) -> Result<NetworkMap, DecodeError> {
255 let channels_count: u64 = Readable::read(reader)?;
256 let mut channels = BTreeMap::new();
257 for _ in 0..channels_count {
258 let chan_id: u64 = Readable::read(reader)?;
259 let chan_info = Readable::read(reader)?;
260 channels.insert(chan_id, chan_info);
262 let our_node_id = Readable::read(reader)?;
263 let nodes_count: u64 = Readable::read(reader)?;
264 let mut nodes = BTreeMap::new();
265 for _ in 0..nodes_count {
266 let node_id = Readable::read(reader)?;
267 let node_info = Readable::read(reader)?;
268 nodes.insert(node_id, node_info);
278 impl std::fmt::Display for NetworkMap {
279 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
280 write!(f, "Node id {} network map\n[Channels]\n", log_pubkey!(self.our_node_id))?;
281 for (key, val) in self.channels.iter() {
282 write!(f, " {}: {}\n", key, val)?;
284 write!(f, "[Nodes]\n")?;
285 for (key, val) in self.nodes.iter() {
286 write!(f, " {}: {}\n", log_pubkey!(key), val)?;
293 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
295 fn get_key(short_channel_id: u64, chain_hash: Sha256dHash) -> (u64, Sha256dHash) {
296 (short_channel_id, chain_hash)
299 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
301 fn get_key(short_channel_id: u64, _: Sha256dHash) -> u64 {
305 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
307 fn get_short_id(id: &(u64, Sha256dHash)) -> &u64 {
311 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
313 fn get_short_id(id: &u64) -> &u64 {
318 /// A channel descriptor which provides a last-hop route to get_route
319 pub struct RouteHint {
320 /// The node_id of the non-target end of the route
321 pub src_node_id: PublicKey,
322 /// The short_channel_id of this channel
323 pub short_channel_id: u64,
324 /// The static msat-denominated fee which must be paid to use this channel
325 pub fee_base_msat: u32,
326 /// The dynamic proportional fee which must be paid to use this channel, denominated in
327 /// millionths of the value being forwarded to the next hop.
328 pub fee_proportional_millionths: u32,
329 /// The difference in CLTV values between this node and the next node.
330 pub cltv_expiry_delta: u16,
331 /// The minimum value, in msat, which must be relayed to the next hop.
332 pub htlc_minimum_msat: u64,
335 /// Tracks a view of the network, receiving updates from peers and generating Routes to
336 /// payment destinations.
338 secp_ctx: Secp256k1<secp256k1::VerifyOnly>,
339 network_map: RwLock<NetworkMap>,
340 chain_monitor: Arc<ChainWatchInterface>,
344 const SERIALIZATION_VERSION: u8 = 1;
345 const MIN_SERIALIZATION_VERSION: u8 = 1;
347 impl Writeable for Router {
348 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
349 writer.write_all(&[SERIALIZATION_VERSION; 1])?;
350 writer.write_all(&[MIN_SERIALIZATION_VERSION; 1])?;
352 let network = self.network_map.read().unwrap();
353 network.write(writer)?;
358 /// Arguments for the creation of a Router that are not deserialized.
359 /// At a high-level, the process for deserializing a Router and resuming normal operation is:
360 /// 1) Deserialize the Router by filling in this struct and calling <Router>::read(reaser, args).
361 /// 2) Register the new Router with your ChainWatchInterface
362 pub struct RouterReadArgs {
363 /// The ChainWatchInterface for use in the Router in the future.
365 /// No calls to the ChainWatchInterface will be made during deserialization.
366 pub chain_monitor: Arc<ChainWatchInterface>,
367 /// The Logger for use in the ChannelManager and which may be used to log information during
369 pub logger: Arc<Logger>,
372 impl<R: ::std::io::Read> ReadableArgs<R, RouterReadArgs> for Router {
373 fn read(reader: &mut R, args: RouterReadArgs) -> Result<Router, DecodeError> {
374 let _ver: u8 = Readable::read(reader)?;
375 let min_ver: u8 = Readable::read(reader)?;
376 if min_ver > SERIALIZATION_VERSION {
377 return Err(DecodeError::UnknownVersion);
379 let network_map = Readable::read(reader)?;
381 secp_ctx: Secp256k1::verification_only(),
382 network_map: RwLock::new(network_map),
383 chain_monitor: args.chain_monitor,
389 macro_rules! secp_verify_sig {
390 ( $secp_ctx: expr, $msg: expr, $sig: expr, $pubkey: expr ) => {
391 match $secp_ctx.verify($msg, $sig, $pubkey) {
393 Err(_) => return Err(LightningError{err: "Invalid signature from remote node", action: ErrorAction::IgnoreError}),
398 impl RoutingMessageHandler for Router {
399 fn handle_node_announcement(&self, msg: &msgs::NodeAnnouncement) -> Result<bool, LightningError> {
400 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
401 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.signature, &msg.contents.node_id);
403 let mut network = self.network_map.write().unwrap();
404 match network.nodes.get_mut(&msg.contents.node_id) {
405 None => Err(LightningError{err: "No existing channels for node_announcement", action: ErrorAction::IgnoreError}),
407 if node.last_update >= msg.contents.timestamp {
408 return Err(LightningError{err: "Update older than last processed update", action: ErrorAction::IgnoreError});
411 node.features = msg.contents.features.clone();
412 node.last_update = msg.contents.timestamp;
413 node.rgb = msg.contents.rgb;
414 node.alias = msg.contents.alias;
415 node.addresses = msg.contents.addresses.clone();
417 let should_relay = msg.contents.excess_data.is_empty() && msg.contents.excess_address_data.is_empty();
418 node.announcement_message = if should_relay { Some(msg.clone()) } else { None };
424 fn handle_channel_announcement(&self, msg: &msgs::ChannelAnnouncement) -> Result<bool, LightningError> {
425 if msg.contents.node_id_1 == msg.contents.node_id_2 || msg.contents.bitcoin_key_1 == msg.contents.bitcoin_key_2 {
426 return Err(LightningError{err: "Channel announcement node had a channel with itself", action: ErrorAction::IgnoreError});
429 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
430 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.node_signature_1, &msg.contents.node_id_1);
431 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.node_signature_2, &msg.contents.node_id_2);
432 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.bitcoin_signature_1, &msg.contents.bitcoin_key_1);
433 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.bitcoin_signature_2, &msg.contents.bitcoin_key_2);
435 let checked_utxo = match self.chain_monitor.get_chain_utxo(msg.contents.chain_hash, msg.contents.short_channel_id) {
436 Ok((script_pubkey, _value)) => {
437 let expected_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
438 .push_slice(&msg.contents.bitcoin_key_1.serialize())
439 .push_slice(&msg.contents.bitcoin_key_2.serialize())
440 .push_opcode(opcodes::all::OP_PUSHNUM_2)
441 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
442 if script_pubkey != expected_script {
443 return Err(LightningError{err: "Channel announcement keys didn't match on-chain script", action: ErrorAction::IgnoreError});
445 //TODO: Check if value is worth storing, use it to inform routing, and compare it
446 //to the new HTLC max field in channel_update
449 Err(ChainError::NotSupported) => {
450 // Tentatively accept, potentially exposing us to DoS attacks
453 Err(ChainError::NotWatched) => {
454 return Err(LightningError{err: "Channel announced on an unknown chain", action: ErrorAction::IgnoreError});
456 Err(ChainError::UnknownTx) => {
457 return Err(LightningError{err: "Channel announced without corresponding UTXO entry", action: ErrorAction::IgnoreError});
461 let mut network_lock = self.network_map.write().unwrap();
462 let network = &mut *network_lock;
464 let should_relay = msg.contents.excess_data.is_empty();
466 let chan_info = ChannelInfo {
467 features: msg.contents.features.clone(),
468 one_to_two: DirectionalChannelInfo {
469 src_node_id: msg.contents.node_id_1.clone(),
472 cltv_expiry_delta: u16::max_value(),
473 htlc_minimum_msat: u64::max_value(),
474 fee_base_msat: u32::max_value(),
475 fee_proportional_millionths: u32::max_value(),
476 last_update_message: None,
478 two_to_one: DirectionalChannelInfo {
479 src_node_id: msg.contents.node_id_2.clone(),
482 cltv_expiry_delta: u16::max_value(),
483 htlc_minimum_msat: u64::max_value(),
484 fee_base_msat: u32::max_value(),
485 fee_proportional_millionths: u32::max_value(),
486 last_update_message: None,
488 announcement_message: if should_relay { Some(msg.clone()) } else { None },
491 match network.channels.entry(NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash)) {
492 BtreeEntry::Occupied(mut entry) => {
493 //TODO: because asking the blockchain if short_channel_id is valid is only optional
494 //in the blockchain API, we need to handle it smartly here, though it's unclear
497 // Either our UTXO provider is busted, there was a reorg, or the UTXO provider
498 // only sometimes returns results. In any case remove the previous entry. Note
499 // that the spec expects us to "blacklist" the node_ids involved, but we can't
501 // a) we don't *require* a UTXO provider that always returns results.
502 // b) we don't track UTXOs of channels we know about and remove them if they
504 // c) it's unclear how to do so without exposing ourselves to massive DoS risk.
505 Self::remove_channel_in_nodes(&mut network.nodes, &entry.get(), msg.contents.short_channel_id);
506 *entry.get_mut() = chan_info;
508 return Err(LightningError{err: "Already have knowledge of channel", action: ErrorAction::IgnoreError})
511 BtreeEntry::Vacant(entry) => {
512 entry.insert(chan_info);
516 macro_rules! add_channel_to_node {
517 ( $node_id: expr ) => {
518 match network.nodes.entry($node_id) {
519 BtreeEntry::Occupied(node_entry) => {
520 node_entry.into_mut().channels.push(NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash));
522 BtreeEntry::Vacant(node_entry) => {
523 node_entry.insert(NodeInfo {
524 channels: vec!(NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash)),
525 lowest_inbound_channel_fee_base_msat: u32::max_value(),
526 lowest_inbound_channel_fee_proportional_millionths: u32::max_value(),
527 features: NodeFeatures::empty(),
531 addresses: Vec::new(),
532 announcement_message: None,
539 add_channel_to_node!(msg.contents.node_id_1);
540 add_channel_to_node!(msg.contents.node_id_2);
545 fn handle_htlc_fail_channel_update(&self, update: &msgs::HTLCFailChannelUpdate) {
547 &msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg } => {
548 let _ = self.handle_channel_update(msg);
550 &msgs::HTLCFailChannelUpdate::ChannelClosed { ref short_channel_id, ref is_permanent } => {
551 let mut network = self.network_map.write().unwrap();
553 if let Some(chan) = network.channels.remove(short_channel_id) {
554 Self::remove_channel_in_nodes(&mut network.nodes, &chan, *short_channel_id);
557 if let Some(chan) = network.channels.get_mut(short_channel_id) {
558 chan.one_to_two.enabled = false;
559 chan.two_to_one.enabled = false;
563 &msgs::HTLCFailChannelUpdate::NodeFailure { ref node_id, ref is_permanent } => {
565 //TODO: Wholly remove the node
567 self.mark_node_bad(node_id, false);
573 fn handle_channel_update(&self, msg: &msgs::ChannelUpdate) -> Result<bool, LightningError> {
574 let mut network = self.network_map.write().unwrap();
576 let chan_enabled = msg.contents.flags & (1 << 1) != (1 << 1);
577 let chan_was_enabled;
579 match network.channels.get_mut(&NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash)) {
580 None => return Err(LightningError{err: "Couldn't find channel for update", action: ErrorAction::IgnoreError}),
582 macro_rules! maybe_update_channel_info {
583 ( $target: expr) => {
584 if $target.last_update >= msg.contents.timestamp {
585 return Err(LightningError{err: "Update older than last processed update", action: ErrorAction::IgnoreError});
587 chan_was_enabled = $target.enabled;
588 $target.last_update = msg.contents.timestamp;
589 $target.enabled = chan_enabled;
590 $target.cltv_expiry_delta = msg.contents.cltv_expiry_delta;
591 $target.htlc_minimum_msat = msg.contents.htlc_minimum_msat;
592 $target.fee_base_msat = msg.contents.fee_base_msat;
593 $target.fee_proportional_millionths = msg.contents.fee_proportional_millionths;
594 $target.last_update_message = if msg.contents.excess_data.is_empty() {
601 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
602 if msg.contents.flags & 1 == 1 {
603 dest_node_id = channel.one_to_two.src_node_id.clone();
604 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.signature, &channel.two_to_one.src_node_id);
605 maybe_update_channel_info!(channel.two_to_one);
607 dest_node_id = channel.two_to_one.src_node_id.clone();
608 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.signature, &channel.one_to_two.src_node_id);
609 maybe_update_channel_info!(channel.one_to_two);
615 let node = network.nodes.get_mut(&dest_node_id).unwrap();
616 node.lowest_inbound_channel_fee_base_msat = cmp::min(node.lowest_inbound_channel_fee_base_msat, msg.contents.fee_base_msat);
617 node.lowest_inbound_channel_fee_proportional_millionths = cmp::min(node.lowest_inbound_channel_fee_proportional_millionths, msg.contents.fee_proportional_millionths);
618 } else if chan_was_enabled {
619 let mut lowest_inbound_channel_fee_base_msat = u32::max_value();
620 let mut lowest_inbound_channel_fee_proportional_millionths = u32::max_value();
623 let node = network.nodes.get(&dest_node_id).unwrap();
625 for chan_id in node.channels.iter() {
626 let chan = network.channels.get(chan_id).unwrap();
627 if chan.one_to_two.src_node_id == dest_node_id {
628 lowest_inbound_channel_fee_base_msat = cmp::min(lowest_inbound_channel_fee_base_msat, chan.two_to_one.fee_base_msat);
629 lowest_inbound_channel_fee_proportional_millionths = cmp::min(lowest_inbound_channel_fee_proportional_millionths, chan.two_to_one.fee_proportional_millionths);
631 lowest_inbound_channel_fee_base_msat = cmp::min(lowest_inbound_channel_fee_base_msat, chan.one_to_two.fee_base_msat);
632 lowest_inbound_channel_fee_proportional_millionths = cmp::min(lowest_inbound_channel_fee_proportional_millionths, chan.one_to_two.fee_proportional_millionths);
637 //TODO: satisfy the borrow-checker without a double-map-lookup :(
638 let mut_node = network.nodes.get_mut(&dest_node_id).unwrap();
639 mut_node.lowest_inbound_channel_fee_base_msat = lowest_inbound_channel_fee_base_msat;
640 mut_node.lowest_inbound_channel_fee_proportional_millionths = lowest_inbound_channel_fee_proportional_millionths;
643 Ok(msg.contents.excess_data.is_empty())
647 fn get_next_channel_announcements(&self, starting_point: u64, batch_amount: u8) -> Vec<(msgs::ChannelAnnouncement, msgs::ChannelUpdate,msgs::ChannelUpdate)> {
648 let mut result = Vec::with_capacity(batch_amount as usize);
649 let network = self.network_map.read().unwrap();
650 let mut iter = network.channels.range(starting_point..);
651 while result.len() < batch_amount as usize {
652 if let Some((_, ref chan)) = iter.next() {
653 if chan.announcement_message.is_some() &&
654 chan.one_to_two.last_update_message.is_some() &&
655 chan.two_to_one.last_update_message.is_some() {
656 result.push((chan.announcement_message.clone().unwrap(),
657 chan.one_to_two.last_update_message.clone().unwrap(),
658 chan.two_to_one.last_update_message.clone().unwrap()));
660 // TODO: We may end up sending un-announced channel_updates if we are sending
661 // initial sync data while receiving announce/updates for this channel.
670 fn get_next_node_announcements(&self, starting_point: Option<&PublicKey>, batch_amount: u8) -> Vec<msgs::NodeAnnouncement> {
671 let mut result = Vec::with_capacity(batch_amount as usize);
672 let network = self.network_map.read().unwrap();
673 let mut iter = if let Some(pubkey) = starting_point {
674 let mut iter = network.nodes.range((*pubkey)..);
678 network.nodes.range(..)
680 while result.len() < batch_amount as usize {
681 if let Some((_, ref node)) = iter.next() {
682 if node.announcement_message.is_some() {
683 result.push(node.announcement_message.clone().unwrap());
693 #[derive(Eq, PartialEq)]
694 struct RouteGraphNode {
696 lowest_fee_to_peer_through_node: u64,
697 lowest_fee_to_node: u64,
700 impl cmp::Ord for RouteGraphNode {
701 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
702 other.lowest_fee_to_peer_through_node.cmp(&self.lowest_fee_to_peer_through_node)
703 .then_with(|| other.pubkey.serialize().cmp(&self.pubkey.serialize()))
707 impl cmp::PartialOrd for RouteGraphNode {
708 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
709 Some(self.cmp(other))
713 struct DummyDirectionalChannelInfo {
714 src_node_id: PublicKey,
715 cltv_expiry_delta: u32,
716 htlc_minimum_msat: u64,
718 fee_proportional_millionths: u32,
722 /// Creates a new router with the given node_id to be used as the source for get_route()
723 pub fn new(our_pubkey: PublicKey, chain_monitor: Arc<ChainWatchInterface>, logger: Arc<Logger>) -> Router {
724 let mut nodes = BTreeMap::new();
725 nodes.insert(our_pubkey.clone(), NodeInfo {
726 channels: Vec::new(),
727 lowest_inbound_channel_fee_base_msat: u32::max_value(),
728 lowest_inbound_channel_fee_proportional_millionths: u32::max_value(),
729 features: NodeFeatures::empty(),
733 addresses: Vec::new(),
734 announcement_message: None,
737 secp_ctx: Secp256k1::verification_only(),
738 network_map: RwLock::new(NetworkMap {
739 channels: BTreeMap::new(),
740 our_node_id: our_pubkey,
748 /// Dumps the entire network view of this Router to the logger provided in the constructor at
750 pub fn trace_state(&self) {
751 log_trace!(self, "{}", self.network_map.read().unwrap());
754 /// Get network addresses by node id
755 pub fn get_addresses(&self, pubkey: &PublicKey) -> Option<Vec<NetAddress>> {
756 let network = self.network_map.read().unwrap();
757 network.nodes.get(pubkey).map(|n| n.addresses.clone())
760 /// Marks a node as having failed a route. This will avoid re-using the node in routes for now,
761 /// with an exponential decay in node "badness". Note that there is deliberately no
762 /// mark_channel_bad as a node may simply lie and suggest that an upstream channel from it is
763 /// what failed the route and not the node itself. Instead, setting the blamed_upstream_node
764 /// boolean will reduce the penalty, returning the node to usability faster. If the node is
765 /// behaving correctly, it will disable the failing channel and we will use it again next time.
766 pub fn mark_node_bad(&self, _node_id: &PublicKey, _blamed_upstream_node: bool) {
770 fn remove_channel_in_nodes(nodes: &mut BTreeMap<PublicKey, NodeInfo>, chan: &ChannelInfo, short_channel_id: u64) {
771 macro_rules! remove_from_node {
772 ($node_id: expr) => {
773 if let BtreeEntry::Occupied(mut entry) = nodes.entry($node_id) {
774 entry.get_mut().channels.retain(|chan_id| {
775 short_channel_id != *NetworkMap::get_short_id(chan_id)
777 if entry.get().channels.is_empty() {
778 entry.remove_entry();
781 panic!("Had channel that pointed to unknown node (ie inconsistent network map)!");
785 remove_from_node!(chan.one_to_two.src_node_id);
786 remove_from_node!(chan.two_to_one.src_node_id);
789 /// Gets a route from us to the given target node.
791 /// Extra routing hops between known nodes and the target will be used if they are included in
794 /// If some channels aren't announced, it may be useful to fill in a first_hops with the
795 /// results from a local ChannelManager::list_usable_channels() call. If it is filled in, our
796 /// (this Router's) view of our local channels will be ignored, and only those in first_hops
799 /// Panics if first_hops contains channels without short_channel_ids
800 /// (ChannelManager::list_usable_channels will never include such channels).
802 /// The fees on channels from us to next-hops are ignored (as they are assumed to all be
803 /// equal), however the enabled/disabled bit on such channels as well as the htlc_minimum_msat
804 /// *is* checked as they may change based on the receiving node.
805 pub fn get_route(&self, target: &PublicKey, first_hops: Option<&[channelmanager::ChannelDetails]>, last_hops: &[RouteHint], final_value_msat: u64, final_cltv: u32) -> Result<Route, LightningError> {
806 // TODO: Obviously *only* using total fee cost sucks. We should consider weighting by
807 // uptime/success in using a node in the past.
808 let network = self.network_map.read().unwrap();
810 if *target == network.our_node_id {
811 return Err(LightningError{err: "Cannot generate a route to ourselves", action: ErrorAction::IgnoreError});
814 if final_value_msat > 21_000_000 * 1_0000_0000 * 1000 {
815 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis", action: ErrorAction::IgnoreError});
818 // We do a dest-to-source Dijkstra's sorting by each node's distance from the destination
819 // plus the minimum per-HTLC fee to get from it to another node (aka "shitty A*").
820 // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
821 // to use as the A* heuristic beyond just the cost to get one node further than the current
824 let dummy_directional_info = DummyDirectionalChannelInfo { // used for first_hops routes
825 src_node_id: network.our_node_id.clone(),
826 cltv_expiry_delta: 0,
827 htlc_minimum_msat: 0,
829 fee_proportional_millionths: 0,
832 let mut targets = BinaryHeap::new(); //TODO: Do we care about switching to eg Fibbonaci heap?
833 let mut dist = HashMap::with_capacity(network.nodes.len());
835 let mut first_hop_targets = HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
836 if let Some(hops) = first_hops {
838 let short_channel_id = chan.short_channel_id.expect("first_hops should be filled in with usable channels, not pending ones");
839 if chan.remote_network_id == *target {
841 hops: vec![RouteHop {
842 pubkey: chan.remote_network_id,
844 fee_msat: final_value_msat,
845 cltv_expiry_delta: final_cltv,
849 first_hop_targets.insert(chan.remote_network_id, short_channel_id);
851 if first_hop_targets.is_empty() {
852 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us", action: ErrorAction::IgnoreError});
856 macro_rules! add_entry {
857 // Adds entry which goes from the node pointed to by $directional_info to
858 // $dest_node_id over the channel with id $chan_id with fees described in
859 // $directional_info.
860 ( $chan_id: expr, $dest_node_id: expr, $directional_info: expr, $starting_fee_msat: expr ) => {
861 //TODO: Explore simply adding fee to hit htlc_minimum_msat
862 if $starting_fee_msat as u64 + final_value_msat >= $directional_info.htlc_minimum_msat {
863 let proportional_fee_millions = ($starting_fee_msat + final_value_msat).checked_mul($directional_info.fee_proportional_millionths as u64);
864 if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
865 ($directional_info.fee_base_msat as u64).checked_add(part / 1000000) })
867 let mut total_fee = $starting_fee_msat as u64;
868 let hm_entry = dist.entry(&$directional_info.src_node_id);
869 let old_entry = hm_entry.or_insert_with(|| {
870 let node = network.nodes.get(&$directional_info.src_node_id).unwrap();
872 node.lowest_inbound_channel_fee_base_msat,
873 node.lowest_inbound_channel_fee_proportional_millionths,
875 pubkey: $dest_node_id.clone(),
878 cltv_expiry_delta: 0,
881 if $directional_info.src_node_id != network.our_node_id {
882 // Ignore new_fee for channel-from-us as we assume all channels-from-us
883 // will have the same effective-fee
884 total_fee += new_fee;
885 if let Some(fee_inc) = final_value_msat.checked_add(total_fee).and_then(|inc| { (old_entry.2 as u64).checked_mul(inc) }) {
886 total_fee += fee_inc / 1000000 + (old_entry.1 as u64);
888 // max_value means we'll always fail the old_entry.0 > total_fee check
889 total_fee = u64::max_value();
892 let new_graph_node = RouteGraphNode {
893 pubkey: $directional_info.src_node_id,
894 lowest_fee_to_peer_through_node: total_fee,
895 lowest_fee_to_node: $starting_fee_msat as u64 + new_fee,
897 if old_entry.0 > total_fee {
898 targets.push(new_graph_node);
899 old_entry.0 = total_fee;
900 old_entry.3 = RouteHop {
901 pubkey: $dest_node_id.clone(),
902 short_channel_id: $chan_id.clone(),
903 fee_msat: new_fee, // This field is ignored on the last-hop anyway
904 cltv_expiry_delta: $directional_info.cltv_expiry_delta as u32,
912 macro_rules! add_entries_to_cheapest_to_target_node {
913 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr ) => {
914 if first_hops.is_some() {
915 if let Some(first_hop) = first_hop_targets.get(&$node_id) {
916 add_entry!(first_hop, $node_id, dummy_directional_info, $fee_to_target_msat);
920 if !$node.features.requires_unknown_bits() {
921 for chan_id in $node.channels.iter() {
922 let chan = network.channels.get(chan_id).unwrap();
923 if !chan.features.requires_unknown_bits() {
924 if chan.one_to_two.src_node_id == *$node_id {
925 // ie $node is one, ie next hop in A* is two, via the two_to_one channel
926 if first_hops.is_none() || chan.two_to_one.src_node_id != network.our_node_id {
927 if chan.two_to_one.enabled {
928 add_entry!(chan_id, chan.one_to_two.src_node_id, chan.two_to_one, $fee_to_target_msat);
932 if first_hops.is_none() || chan.one_to_two.src_node_id != network.our_node_id {
933 if chan.one_to_two.enabled {
934 add_entry!(chan_id, chan.two_to_one.src_node_id, chan.one_to_two, $fee_to_target_msat);
944 match network.nodes.get(target) {
947 add_entries_to_cheapest_to_target_node!(node, target, 0);
951 for hop in last_hops.iter() {
952 if first_hops.is_none() || hop.src_node_id != network.our_node_id { // first_hop overrules last_hops
953 if network.nodes.get(&hop.src_node_id).is_some() {
954 if first_hops.is_some() {
955 if let Some(first_hop) = first_hop_targets.get(&hop.src_node_id) {
956 add_entry!(first_hop, hop.src_node_id, dummy_directional_info, 0);
959 add_entry!(hop.short_channel_id, target, hop, 0);
964 while let Some(RouteGraphNode { pubkey, lowest_fee_to_node, .. }) = targets.pop() {
965 if pubkey == network.our_node_id {
966 let mut res = vec!(dist.remove(&network.our_node_id).unwrap().3);
967 while res.last().unwrap().pubkey != *target {
968 let new_entry = match dist.remove(&res.last().unwrap().pubkey) {
970 None => return Err(LightningError{err: "Failed to find a non-fee-overflowing path to the given destination", action: ErrorAction::IgnoreError}),
972 res.last_mut().unwrap().fee_msat = new_entry.fee_msat;
973 res.last_mut().unwrap().cltv_expiry_delta = new_entry.cltv_expiry_delta;
976 res.last_mut().unwrap().fee_msat = final_value_msat;
977 res.last_mut().unwrap().cltv_expiry_delta = final_cltv;
978 let route = Route { hops: res };
979 log_trace!(self, "Got route: {}", log_route!(route));
983 match network.nodes.get(&pubkey) {
986 add_entries_to_cheapest_to_target_node!(node, &pubkey, lowest_fee_to_node);
991 Err(LightningError{err: "Failed to find a path to the given destination", action: ErrorAction::IgnoreError})
997 use chain::chaininterface;
998 use ln::channelmanager;
999 use ln::router::{Router,NodeInfo,NetworkMap,ChannelInfo,DirectionalChannelInfo,RouteHint};
1000 use ln::features::{ChannelFeatures, NodeFeatures};
1001 use ln::msgs::{LightningError, ErrorAction};
1002 use util::test_utils;
1003 use util::test_utils::TestVecWriter;
1004 use util::logger::Logger;
1005 use util::ser::{Writeable, Readable};
1007 use bitcoin_hashes::sha256d::Hash as Sha256dHash;
1008 use bitcoin_hashes::Hash;
1009 use bitcoin::network::constants::Network;
1013 use secp256k1::key::{PublicKey,SecretKey};
1014 use secp256k1::Secp256k1;
1020 let secp_ctx = Secp256k1::new();
1021 let our_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap());
1022 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
1023 let chain_monitor = Arc::new(chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet, Arc::clone(&logger)));
1024 let router = Router::new(our_id, chain_monitor, Arc::clone(&logger));
1026 // Build network from our_id to node8:
1028 // -1(1)2- node1 -1(3)2-
1030 // our_id -1(12)2- node8 -1(13)2--- node3
1032 // -1(2)2- node2 -1(4)2-
1035 // chan1 1-to-2: disabled
1036 // chan1 2-to-1: enabled, 0 fee
1038 // chan2 1-to-2: enabled, ignored fee
1039 // chan2 2-to-1: enabled, 0 fee
1041 // chan3 1-to-2: enabled, 0 fee
1042 // chan3 2-to-1: enabled, 100 msat fee
1044 // chan4 1-to-2: enabled, 100% fee
1045 // chan4 2-to-1: enabled, 0 fee
1047 // chan12 1-to-2: enabled, ignored fee
1048 // chan12 2-to-1: enabled, 0 fee
1050 // chan13 1-to-2: enabled, 200% fee
1051 // chan13 2-to-1: enabled, 0 fee
1054 // -1(5)2- node4 -1(8)2--
1058 // node3--1(6)2- node5 -1(9)2--- node7 (not in global route map)
1060 // -1(7)2- node6 -1(10)2-
1062 // chan5 1-to-2: enabled, 100 msat fee
1063 // chan5 2-to-1: enabled, 0 fee
1065 // chan6 1-to-2: enabled, 0 fee
1066 // chan6 2-to-1: enabled, 0 fee
1068 // chan7 1-to-2: enabled, 100% fee
1069 // chan7 2-to-1: enabled, 0 fee
1071 // chan8 1-to-2: enabled, variable fee (0 then 1000 msat)
1072 // chan8 2-to-1: enabled, 0 fee
1074 // chan9 1-to-2: enabled, 1001 msat fee
1075 // chan9 2-to-1: enabled, 0 fee
1077 // chan10 1-to-2: enabled, 0 fee
1078 // chan10 2-to-1: enabled, 0 fee
1080 // chan11 1-to-2: enabled, 0 fee
1081 // chan11 2-to-1: enabled, 0 fee
1083 let node1 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap()[..]).unwrap());
1084 let node2 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0303030303030303030303030303030303030303030303030303030303030303").unwrap()[..]).unwrap());
1085 let node3 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0404040404040404040404040404040404040404040404040404040404040404").unwrap()[..]).unwrap());
1086 let node4 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0505050505050505050505050505050505050505050505050505050505050505").unwrap()[..]).unwrap());
1087 let node5 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0606060606060606060606060606060606060606060606060606060606060606").unwrap()[..]).unwrap());
1088 let node6 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0707070707070707070707070707070707070707070707070707070707070707").unwrap()[..]).unwrap());
1089 let node7 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0808080808080808080808080808080808080808080808080808080808080808").unwrap()[..]).unwrap());
1090 let node8 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0909090909090909090909090909090909090909090909090909090909090909").unwrap()[..]).unwrap());
1092 let zero_hash = Sha256dHash::hash(&[0; 32]);
1095 let mut network = router.network_map.write().unwrap();
1097 network.nodes.insert(node1.clone(), NodeInfo {
1098 channels: vec!(NetworkMap::get_key(1, zero_hash.clone()), NetworkMap::get_key(3, zero_hash.clone())),
1099 lowest_inbound_channel_fee_base_msat: 100,
1100 lowest_inbound_channel_fee_proportional_millionths: 0,
1101 features: NodeFeatures::empty(),
1105 addresses: Vec::new(),
1106 announcement_message: None,
1108 network.channels.insert(NetworkMap::get_key(1, zero_hash.clone()), ChannelInfo {
1109 features: ChannelFeatures::empty(),
1110 one_to_two: DirectionalChannelInfo {
1111 src_node_id: our_id.clone(),
1114 cltv_expiry_delta: u16::max_value(), // This value should be ignored
1115 htlc_minimum_msat: 0,
1116 fee_base_msat: u32::max_value(), // This value should be ignored
1117 fee_proportional_millionths: u32::max_value(), // This value should be ignored
1118 last_update_message: None,
1119 }, two_to_one: DirectionalChannelInfo {
1120 src_node_id: node1.clone(),
1123 cltv_expiry_delta: 0,
1124 htlc_minimum_msat: 0,
1126 fee_proportional_millionths: 0,
1127 last_update_message: None,
1129 announcement_message: None,
1131 network.nodes.insert(node2.clone(), NodeInfo {
1132 channels: vec!(NetworkMap::get_key(2, zero_hash.clone()), NetworkMap::get_key(4, zero_hash.clone())),
1133 lowest_inbound_channel_fee_base_msat: 0,
1134 lowest_inbound_channel_fee_proportional_millionths: 0,
1135 features: NodeFeatures::empty(),
1139 addresses: Vec::new(),
1140 announcement_message: None,
1142 network.channels.insert(NetworkMap::get_key(2, zero_hash.clone()), ChannelInfo {
1143 features: ChannelFeatures::empty(),
1144 one_to_two: DirectionalChannelInfo {
1145 src_node_id: our_id.clone(),
1148 cltv_expiry_delta: u16::max_value(), // This value should be ignored
1149 htlc_minimum_msat: 0,
1150 fee_base_msat: u32::max_value(), // This value should be ignored
1151 fee_proportional_millionths: u32::max_value(), // This value should be ignored
1152 last_update_message: None,
1153 }, two_to_one: DirectionalChannelInfo {
1154 src_node_id: node2.clone(),
1157 cltv_expiry_delta: 0,
1158 htlc_minimum_msat: 0,
1160 fee_proportional_millionths: 0,
1161 last_update_message: None,
1163 announcement_message: None,
1165 network.nodes.insert(node8.clone(), NodeInfo {
1166 channels: vec!(NetworkMap::get_key(12, zero_hash.clone()), NetworkMap::get_key(13, zero_hash.clone())),
1167 lowest_inbound_channel_fee_base_msat: 0,
1168 lowest_inbound_channel_fee_proportional_millionths: 0,
1169 features: NodeFeatures::empty(),
1173 addresses: Vec::new(),
1174 announcement_message: None,
1176 network.channels.insert(NetworkMap::get_key(12, zero_hash.clone()), ChannelInfo {
1177 features: ChannelFeatures::empty(),
1178 one_to_two: DirectionalChannelInfo {
1179 src_node_id: our_id.clone(),
1182 cltv_expiry_delta: u16::max_value(), // This value should be ignored
1183 htlc_minimum_msat: 0,
1184 fee_base_msat: u32::max_value(), // This value should be ignored
1185 fee_proportional_millionths: u32::max_value(), // This value should be ignored
1186 last_update_message: None,
1187 }, two_to_one: DirectionalChannelInfo {
1188 src_node_id: node8.clone(),
1191 cltv_expiry_delta: 0,
1192 htlc_minimum_msat: 0,
1194 fee_proportional_millionths: 0,
1195 last_update_message: None,
1197 announcement_message: None,
1199 network.nodes.insert(node3.clone(), NodeInfo {
1201 NetworkMap::get_key(3, zero_hash.clone()),
1202 NetworkMap::get_key(4, zero_hash.clone()),
1203 NetworkMap::get_key(13, zero_hash.clone()),
1204 NetworkMap::get_key(5, zero_hash.clone()),
1205 NetworkMap::get_key(6, zero_hash.clone()),
1206 NetworkMap::get_key(7, zero_hash.clone())),
1207 lowest_inbound_channel_fee_base_msat: 0,
1208 lowest_inbound_channel_fee_proportional_millionths: 0,
1209 features: NodeFeatures::empty(),
1213 addresses: Vec::new(),
1214 announcement_message: None,
1216 network.channels.insert(NetworkMap::get_key(3, zero_hash.clone()), ChannelInfo {
1217 features: ChannelFeatures::empty(),
1218 one_to_two: DirectionalChannelInfo {
1219 src_node_id: node1.clone(),
1222 cltv_expiry_delta: (3 << 8) | 1,
1223 htlc_minimum_msat: 0,
1225 fee_proportional_millionths: 0,
1226 last_update_message: None,
1227 }, two_to_one: DirectionalChannelInfo {
1228 src_node_id: node3.clone(),
1231 cltv_expiry_delta: (3 << 8) | 2,
1232 htlc_minimum_msat: 0,
1234 fee_proportional_millionths: 0,
1235 last_update_message: None,
1237 announcement_message: None,
1239 network.channels.insert(NetworkMap::get_key(4, zero_hash.clone()), ChannelInfo {
1240 features: ChannelFeatures::empty(),
1241 one_to_two: DirectionalChannelInfo {
1242 src_node_id: node2.clone(),
1245 cltv_expiry_delta: (4 << 8) | 1,
1246 htlc_minimum_msat: 0,
1248 fee_proportional_millionths: 1000000,
1249 last_update_message: None,
1250 }, two_to_one: DirectionalChannelInfo {
1251 src_node_id: node3.clone(),
1254 cltv_expiry_delta: (4 << 8) | 2,
1255 htlc_minimum_msat: 0,
1257 fee_proportional_millionths: 0,
1258 last_update_message: None,
1260 announcement_message: None,
1262 network.channels.insert(NetworkMap::get_key(13, zero_hash.clone()), ChannelInfo {
1263 features: ChannelFeatures::empty(),
1264 one_to_two: DirectionalChannelInfo {
1265 src_node_id: node8.clone(),
1268 cltv_expiry_delta: (13 << 8) | 1,
1269 htlc_minimum_msat: 0,
1271 fee_proportional_millionths: 2000000,
1272 last_update_message: None,
1273 }, two_to_one: DirectionalChannelInfo {
1274 src_node_id: node3.clone(),
1277 cltv_expiry_delta: (13 << 8) | 2,
1278 htlc_minimum_msat: 0,
1280 fee_proportional_millionths: 0,
1281 last_update_message: None,
1283 announcement_message: None,
1285 network.nodes.insert(node4.clone(), NodeInfo {
1286 channels: vec!(NetworkMap::get_key(5, zero_hash.clone()), NetworkMap::get_key(11, zero_hash.clone())),
1287 lowest_inbound_channel_fee_base_msat: 0,
1288 lowest_inbound_channel_fee_proportional_millionths: 0,
1289 features: NodeFeatures::empty(),
1293 addresses: Vec::new(),
1294 announcement_message: None,
1296 network.channels.insert(NetworkMap::get_key(5, zero_hash.clone()), ChannelInfo {
1297 features: ChannelFeatures::empty(),
1298 one_to_two: DirectionalChannelInfo {
1299 src_node_id: node3.clone(),
1302 cltv_expiry_delta: (5 << 8) | 1,
1303 htlc_minimum_msat: 0,
1305 fee_proportional_millionths: 0,
1306 last_update_message: None,
1307 }, two_to_one: DirectionalChannelInfo {
1308 src_node_id: node4.clone(),
1311 cltv_expiry_delta: (5 << 8) | 2,
1312 htlc_minimum_msat: 0,
1314 fee_proportional_millionths: 0,
1315 last_update_message: None,
1317 announcement_message: None,
1319 network.nodes.insert(node5.clone(), NodeInfo {
1320 channels: vec!(NetworkMap::get_key(6, zero_hash.clone()), NetworkMap::get_key(11, zero_hash.clone())),
1321 lowest_inbound_channel_fee_base_msat: 0,
1322 lowest_inbound_channel_fee_proportional_millionths: 0,
1323 features: NodeFeatures::empty(),
1327 addresses: Vec::new(),
1328 announcement_message: None,
1330 network.channels.insert(NetworkMap::get_key(6, zero_hash.clone()), ChannelInfo {
1331 features: ChannelFeatures::empty(),
1332 one_to_two: DirectionalChannelInfo {
1333 src_node_id: node3.clone(),
1336 cltv_expiry_delta: (6 << 8) | 1,
1337 htlc_minimum_msat: 0,
1339 fee_proportional_millionths: 0,
1340 last_update_message: None,
1341 }, two_to_one: DirectionalChannelInfo {
1342 src_node_id: node5.clone(),
1345 cltv_expiry_delta: (6 << 8) | 2,
1346 htlc_minimum_msat: 0,
1348 fee_proportional_millionths: 0,
1349 last_update_message: None,
1351 announcement_message: None,
1353 network.channels.insert(NetworkMap::get_key(11, zero_hash.clone()), ChannelInfo {
1354 features: ChannelFeatures::empty(),
1355 one_to_two: DirectionalChannelInfo {
1356 src_node_id: node5.clone(),
1359 cltv_expiry_delta: (11 << 8) | 1,
1360 htlc_minimum_msat: 0,
1362 fee_proportional_millionths: 0,
1363 last_update_message: None,
1364 }, two_to_one: DirectionalChannelInfo {
1365 src_node_id: node4.clone(),
1368 cltv_expiry_delta: (11 << 8) | 2,
1369 htlc_minimum_msat: 0,
1371 fee_proportional_millionths: 0,
1372 last_update_message: None,
1374 announcement_message: None,
1376 network.nodes.insert(node6.clone(), NodeInfo {
1377 channels: vec!(NetworkMap::get_key(7, zero_hash.clone())),
1378 lowest_inbound_channel_fee_base_msat: 0,
1379 lowest_inbound_channel_fee_proportional_millionths: 0,
1380 features: NodeFeatures::empty(),
1384 addresses: Vec::new(),
1385 announcement_message: None,
1387 network.channels.insert(NetworkMap::get_key(7, zero_hash.clone()), ChannelInfo {
1388 features: ChannelFeatures::empty(),
1389 one_to_two: DirectionalChannelInfo {
1390 src_node_id: node3.clone(),
1393 cltv_expiry_delta: (7 << 8) | 1,
1394 htlc_minimum_msat: 0,
1396 fee_proportional_millionths: 1000000,
1397 last_update_message: None,
1398 }, two_to_one: DirectionalChannelInfo {
1399 src_node_id: node6.clone(),
1402 cltv_expiry_delta: (7 << 8) | 2,
1403 htlc_minimum_msat: 0,
1405 fee_proportional_millionths: 0,
1406 last_update_message: None,
1408 announcement_message: None,
1412 { // Simple route to 3 via 2
1413 let route = router.get_route(&node3, None, &Vec::new(), 100, 42).unwrap();
1414 assert_eq!(route.hops.len(), 2);
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, 100);
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, 100);
1424 assert_eq!(route.hops[1].cltv_expiry_delta, 42);
1427 { // Disable channels 4 and 12 by requiring unknown feature bits
1428 let mut network = router.network_map.write().unwrap();
1429 network.channels.get_mut(&NetworkMap::get_key(4, zero_hash.clone())).unwrap().features.set_require_unknown_bits();
1430 network.channels.get_mut(&NetworkMap::get_key(12, zero_hash.clone())).unwrap().features.set_require_unknown_bits();
1433 { // If all the channels require some features we don't understand, route should fail
1434 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = router.get_route(&node3, None, &Vec::new(), 100, 42) {
1435 assert_eq!(err, "Failed to find a path to the given destination");
1436 } else { panic!(); }
1439 { // If we specify a channel to node8, that overrides our local channel view and that gets used
1440 let our_chans = vec![channelmanager::ChannelDetails {
1441 channel_id: [0; 32],
1442 short_channel_id: Some(42),
1443 remote_network_id: node8.clone(),
1444 channel_value_satoshis: 0,
1446 outbound_capacity_msat: 0,
1447 inbound_capacity_msat: 0,
1450 let route = router.get_route(&node3, Some(&our_chans), &Vec::new(), 100, 42).unwrap();
1451 assert_eq!(route.hops.len(), 2);
1453 assert_eq!(route.hops[0].pubkey, node8);
1454 assert_eq!(route.hops[0].short_channel_id, 42);
1455 assert_eq!(route.hops[0].fee_msat, 200);
1456 assert_eq!(route.hops[0].cltv_expiry_delta, (13 << 8) | 1);
1458 assert_eq!(route.hops[1].pubkey, node3);
1459 assert_eq!(route.hops[1].short_channel_id, 13);
1460 assert_eq!(route.hops[1].fee_msat, 100);
1461 assert_eq!(route.hops[1].cltv_expiry_delta, 42);
1464 { // Re-enable channels 4 and 12 by wiping the unknown feature bits
1465 let mut network = router.network_map.write().unwrap();
1466 network.channels.get_mut(&NetworkMap::get_key(4, zero_hash.clone())).unwrap().features.clear_require_unknown_bits();
1467 network.channels.get_mut(&NetworkMap::get_key(12, zero_hash.clone())).unwrap().features.clear_require_unknown_bits();
1470 { // Disable nodes 1, 2, and 8 by requiring unknown feature bits
1471 let mut network = router.network_map.write().unwrap();
1472 network.nodes.get_mut(&node1).unwrap().features.set_require_unknown_bits();
1473 network.nodes.get_mut(&node2).unwrap().features.set_require_unknown_bits();
1474 network.nodes.get_mut(&node8).unwrap().features.set_require_unknown_bits();
1477 { // If all nodes require some features we don't understand, route should fail
1478 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = router.get_route(&node3, None, &Vec::new(), 100, 42) {
1479 assert_eq!(err, "Failed to find a path to the given destination");
1480 } else { panic!(); }
1483 { // If we specify a channel to node8, that overrides our local channel view and that gets used
1484 let our_chans = vec![channelmanager::ChannelDetails {
1485 channel_id: [0; 32],
1486 short_channel_id: Some(42),
1487 remote_network_id: node8.clone(),
1488 channel_value_satoshis: 0,
1490 outbound_capacity_msat: 0,
1491 inbound_capacity_msat: 0,
1494 let route = router.get_route(&node3, Some(&our_chans), &Vec::new(), 100, 42).unwrap();
1495 assert_eq!(route.hops.len(), 2);
1497 assert_eq!(route.hops[0].pubkey, node8);
1498 assert_eq!(route.hops[0].short_channel_id, 42);
1499 assert_eq!(route.hops[0].fee_msat, 200);
1500 assert_eq!(route.hops[0].cltv_expiry_delta, (13 << 8) | 1);
1502 assert_eq!(route.hops[1].pubkey, node3);
1503 assert_eq!(route.hops[1].short_channel_id, 13);
1504 assert_eq!(route.hops[1].fee_msat, 100);
1505 assert_eq!(route.hops[1].cltv_expiry_delta, 42);
1508 { // Re-enable nodes 1, 2, and 8
1509 let mut network = router.network_map.write().unwrap();
1510 network.nodes.get_mut(&node1).unwrap().features.clear_require_unknown_bits();
1511 network.nodes.get_mut(&node2).unwrap().features.clear_require_unknown_bits();
1512 network.nodes.get_mut(&node8).unwrap().features.clear_require_unknown_bits();
1515 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
1516 // naively) assume that the user checked the feature bits on the invoice, which override
1517 // the node_announcement.
1519 { // Route to 1 via 2 and 3 because our channel to 1 is disabled
1520 let route = router.get_route(&node1, None, &Vec::new(), 100, 42).unwrap();
1521 assert_eq!(route.hops.len(), 3);
1523 assert_eq!(route.hops[0].pubkey, node2);
1524 assert_eq!(route.hops[0].short_channel_id, 2);
1525 assert_eq!(route.hops[0].fee_msat, 200);
1526 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1528 assert_eq!(route.hops[1].pubkey, node3);
1529 assert_eq!(route.hops[1].short_channel_id, 4);
1530 assert_eq!(route.hops[1].fee_msat, 100);
1531 assert_eq!(route.hops[1].cltv_expiry_delta, (3 << 8) | 2);
1533 assert_eq!(route.hops[2].pubkey, node1);
1534 assert_eq!(route.hops[2].short_channel_id, 3);
1535 assert_eq!(route.hops[2].fee_msat, 100);
1536 assert_eq!(route.hops[2].cltv_expiry_delta, 42);
1539 { // If we specify a channel to node8, that overrides our local channel view and that gets used
1540 let our_chans = vec![channelmanager::ChannelDetails {
1541 channel_id: [0; 32],
1542 short_channel_id: Some(42),
1543 remote_network_id: node8.clone(),
1544 channel_value_satoshis: 0,
1546 outbound_capacity_msat: 0,
1547 inbound_capacity_msat: 0,
1550 let route = router.get_route(&node3, Some(&our_chans), &Vec::new(), 100, 42).unwrap();
1551 assert_eq!(route.hops.len(), 2);
1553 assert_eq!(route.hops[0].pubkey, node8);
1554 assert_eq!(route.hops[0].short_channel_id, 42);
1555 assert_eq!(route.hops[0].fee_msat, 200);
1556 assert_eq!(route.hops[0].cltv_expiry_delta, (13 << 8) | 1);
1558 assert_eq!(route.hops[1].pubkey, node3);
1559 assert_eq!(route.hops[1].short_channel_id, 13);
1560 assert_eq!(route.hops[1].fee_msat, 100);
1561 assert_eq!(route.hops[1].cltv_expiry_delta, 42);
1564 let mut last_hops = vec!(RouteHint {
1565 src_node_id: node4.clone(),
1566 short_channel_id: 8,
1568 fee_proportional_millionths: 0,
1569 cltv_expiry_delta: (8 << 8) | 1,
1570 htlc_minimum_msat: 0,
1572 src_node_id: node5.clone(),
1573 short_channel_id: 9,
1574 fee_base_msat: 1001,
1575 fee_proportional_millionths: 0,
1576 cltv_expiry_delta: (9 << 8) | 1,
1577 htlc_minimum_msat: 0,
1579 src_node_id: node6.clone(),
1580 short_channel_id: 10,
1582 fee_proportional_millionths: 0,
1583 cltv_expiry_delta: (10 << 8) | 1,
1584 htlc_minimum_msat: 0,
1587 { // Simple test across 2, 3, 5, and 4 via a last_hop channel
1588 let route = router.get_route(&node7, None, &last_hops, 100, 42).unwrap();
1589 assert_eq!(route.hops.len(), 5);
1591 assert_eq!(route.hops[0].pubkey, node2);
1592 assert_eq!(route.hops[0].short_channel_id, 2);
1593 assert_eq!(route.hops[0].fee_msat, 100);
1594 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1596 assert_eq!(route.hops[1].pubkey, node3);
1597 assert_eq!(route.hops[1].short_channel_id, 4);
1598 assert_eq!(route.hops[1].fee_msat, 0);
1599 assert_eq!(route.hops[1].cltv_expiry_delta, (6 << 8) | 1);
1601 assert_eq!(route.hops[2].pubkey, node5);
1602 assert_eq!(route.hops[2].short_channel_id, 6);
1603 assert_eq!(route.hops[2].fee_msat, 0);
1604 assert_eq!(route.hops[2].cltv_expiry_delta, (11 << 8) | 1);
1606 assert_eq!(route.hops[3].pubkey, node4);
1607 assert_eq!(route.hops[3].short_channel_id, 11);
1608 assert_eq!(route.hops[3].fee_msat, 0);
1609 assert_eq!(route.hops[3].cltv_expiry_delta, (8 << 8) | 1);
1611 assert_eq!(route.hops[4].pubkey, node7);
1612 assert_eq!(route.hops[4].short_channel_id, 8);
1613 assert_eq!(route.hops[4].fee_msat, 100);
1614 assert_eq!(route.hops[4].cltv_expiry_delta, 42);
1617 { // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
1618 let our_chans = vec![channelmanager::ChannelDetails {
1619 channel_id: [0; 32],
1620 short_channel_id: Some(42),
1621 remote_network_id: node4.clone(),
1622 channel_value_satoshis: 0,
1624 outbound_capacity_msat: 0,
1625 inbound_capacity_msat: 0,
1628 let route = router.get_route(&node7, Some(&our_chans), &last_hops, 100, 42).unwrap();
1629 assert_eq!(route.hops.len(), 2);
1631 assert_eq!(route.hops[0].pubkey, node4);
1632 assert_eq!(route.hops[0].short_channel_id, 42);
1633 assert_eq!(route.hops[0].fee_msat, 0);
1634 assert_eq!(route.hops[0].cltv_expiry_delta, (8 << 8) | 1);
1636 assert_eq!(route.hops[1].pubkey, node7);
1637 assert_eq!(route.hops[1].short_channel_id, 8);
1638 assert_eq!(route.hops[1].fee_msat, 100);
1639 assert_eq!(route.hops[1].cltv_expiry_delta, 42);
1642 last_hops[0].fee_base_msat = 1000;
1644 { // Revert to via 6 as the fee on 8 goes up
1645 let route = router.get_route(&node7, None, &last_hops, 100, 42).unwrap();
1646 assert_eq!(route.hops.len(), 4);
1648 assert_eq!(route.hops[0].pubkey, node2);
1649 assert_eq!(route.hops[0].short_channel_id, 2);
1650 assert_eq!(route.hops[0].fee_msat, 200); // fee increased as its % of value transferred across node
1651 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1653 assert_eq!(route.hops[1].pubkey, node3);
1654 assert_eq!(route.hops[1].short_channel_id, 4);
1655 assert_eq!(route.hops[1].fee_msat, 100);
1656 assert_eq!(route.hops[1].cltv_expiry_delta, (7 << 8) | 1);
1658 assert_eq!(route.hops[2].pubkey, node6);
1659 assert_eq!(route.hops[2].short_channel_id, 7);
1660 assert_eq!(route.hops[2].fee_msat, 0);
1661 assert_eq!(route.hops[2].cltv_expiry_delta, (10 << 8) | 1);
1663 assert_eq!(route.hops[3].pubkey, node7);
1664 assert_eq!(route.hops[3].short_channel_id, 10);
1665 assert_eq!(route.hops[3].fee_msat, 100);
1666 assert_eq!(route.hops[3].cltv_expiry_delta, 42);
1669 { // ...but still use 8 for larger payments as 6 has a variable feerate
1670 let route = router.get_route(&node7, None, &last_hops, 2000, 42).unwrap();
1671 assert_eq!(route.hops.len(), 5);
1673 assert_eq!(route.hops[0].pubkey, node2);
1674 assert_eq!(route.hops[0].short_channel_id, 2);
1675 assert_eq!(route.hops[0].fee_msat, 3000);
1676 assert_eq!(route.hops[0].cltv_expiry_delta, (4 << 8) | 1);
1678 assert_eq!(route.hops[1].pubkey, node3);
1679 assert_eq!(route.hops[1].short_channel_id, 4);
1680 assert_eq!(route.hops[1].fee_msat, 0);
1681 assert_eq!(route.hops[1].cltv_expiry_delta, (6 << 8) | 1);
1683 assert_eq!(route.hops[2].pubkey, node5);
1684 assert_eq!(route.hops[2].short_channel_id, 6);
1685 assert_eq!(route.hops[2].fee_msat, 0);
1686 assert_eq!(route.hops[2].cltv_expiry_delta, (11 << 8) | 1);
1688 assert_eq!(route.hops[3].pubkey, node4);
1689 assert_eq!(route.hops[3].short_channel_id, 11);
1690 assert_eq!(route.hops[3].fee_msat, 1000);
1691 assert_eq!(route.hops[3].cltv_expiry_delta, (8 << 8) | 1);
1693 assert_eq!(route.hops[4].pubkey, node7);
1694 assert_eq!(route.hops[4].short_channel_id, 8);
1695 assert_eq!(route.hops[4].fee_msat, 2000);
1696 assert_eq!(route.hops[4].cltv_expiry_delta, 42);
1699 { // Test Router serialization/deserialization
1700 let mut w = TestVecWriter(Vec::new());
1701 let network = router.network_map.read().unwrap();
1702 assert!(!network.channels.is_empty());
1703 assert!(!network.nodes.is_empty());
1704 network.write(&mut w).unwrap();
1705 assert!(<NetworkMap>::read(&mut ::std::io::Cursor::new(&w.0)).unwrap() == *network);