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::sync::atomic::{AtomicUsize, Ordering};
26 use std::collections::{HashMap,BinaryHeap,BTreeMap};
27 use std::collections::btree_map::Entry as BtreeEntry;
31 #[derive(Clone, PartialEq)]
33 /// The node_id of the node at this hop.
34 pub pubkey: PublicKey,
35 /// The node_announcement features of the node at this hop. For the last hop, these may be
36 /// amended to match the features present in the invoice this node generated.
37 pub node_features: NodeFeatures,
38 /// The channel that should be used from the previous hop to reach this node.
39 pub short_channel_id: u64,
40 /// The channel_announcement features of the channel that should be used from the previous hop
41 /// to reach this node.
42 pub channel_features: ChannelFeatures,
43 /// The fee taken on this hop. For the last hop, this should be the full value of the payment.
45 /// The CLTV delta added for this hop. For the last hop, this should be the full CLTV value
46 /// expected at the destination, in excess of the current block height.
47 pub cltv_expiry_delta: u32,
50 impl Writeable for Vec<RouteHop> {
51 fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
52 (self.len() as u8).write(writer)?;
53 for hop in self.iter() {
54 hop.pubkey.write(writer)?;
55 hop.node_features.write(writer)?;
56 hop.short_channel_id.write(writer)?;
57 hop.channel_features.write(writer)?;
58 hop.fee_msat.write(writer)?;
59 hop.cltv_expiry_delta.write(writer)?;
65 impl Readable for Vec<RouteHop> {
66 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Vec<RouteHop>, 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 node_features: Readable::read(reader)?,
73 short_channel_id: Readable::read(reader)?,
74 channel_features: Readable::read(reader)?,
75 fee_msat: Readable::read(reader)?,
76 cltv_expiry_delta: Readable::read(reader)?,
83 /// A route directs a payment from the sender (us) to the recipient. If the recipient supports MPP,
84 /// it can take multiple paths. Each path is composed of one or more hops through the network.
85 #[derive(Clone, PartialEq)]
87 /// The list of routes taken for a single (potentially-)multi-part payment. The pubkey of the
88 /// last RouteHop in each path must be the same.
89 /// Each entry represents a list of hops, NOT INCLUDING our own, where the last hop is the
90 /// destination. Thus, this must always be at least length one. While the maximum length of any
91 /// given path is variable, keeping the length of any path to less than 20 should currently
92 /// ensure it is viable.
93 pub paths: Vec<Vec<RouteHop>>,
96 impl Writeable for Route {
97 fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
98 (self.paths.len() as u64).write(writer)?;
99 for hops in self.paths.iter() {
106 impl Readable for Route {
107 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
108 let path_count: u64 = Readable::read(reader)?;
109 let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
110 for _ in 0..path_count {
111 paths.push(Readable::read(reader)?);
118 struct DirectionalChannelInfo {
119 src_node_id: PublicKey,
122 cltv_expiry_delta: u16,
123 htlc_minimum_msat: u64,
125 fee_proportional_millionths: u32,
126 last_update_message: Option<msgs::ChannelUpdate>,
129 impl std::fmt::Display for DirectionalChannelInfo {
130 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
131 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)?;
136 impl_writeable!(DirectionalChannelInfo, 0, {
143 fee_proportional_millionths,
149 features: ChannelFeatures,
150 one_to_two: DirectionalChannelInfo,
151 two_to_one: DirectionalChannelInfo,
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::ChannelAnnouncement>,
157 impl std::fmt::Display for ChannelInfo {
158 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
159 write!(f, "features: {}, one_to_two: {}, two_to_one: {}", log_bytes!(self.features.encode()), self.one_to_two, self.two_to_one)?;
164 impl_writeable!(ChannelInfo, 0, {
173 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
174 channels: Vec<(u64, Sha256dHash)>,
175 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
178 lowest_inbound_channel_fee_base_msat: u32,
179 lowest_inbound_channel_fee_proportional_millionths: u32,
181 features: NodeFeatures,
182 /// Unlike for channels, we may have a NodeInfo entry before having received a node_update.
183 /// Thus, we have to be able to capture "no update has been received", which we do with an
185 last_update: Option<u32>,
188 addresses: Vec<NetAddress>,
189 //this is cached here so we can send out it later if required by route_init_sync
190 //keep an eye on this to see if the extra memory is a problem
191 announcement_message: Option<msgs::NodeAnnouncement>,
194 impl std::fmt::Display for NodeInfo {
195 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
196 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[..])?;
201 impl Writeable for NodeInfo {
202 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
203 (self.channels.len() as u64).write(writer)?;
204 for ref chan in self.channels.iter() {
207 self.lowest_inbound_channel_fee_base_msat.write(writer)?;
208 self.lowest_inbound_channel_fee_proportional_millionths.write(writer)?;
209 self.features.write(writer)?;
210 self.last_update.write(writer)?;
211 self.rgb.write(writer)?;
212 self.alias.write(writer)?;
213 (self.addresses.len() as u64).write(writer)?;
214 for ref addr in &self.addresses {
217 self.announcement_message.write(writer)?;
222 const MAX_ALLOC_SIZE: u64 = 64*1024;
224 impl Readable for NodeInfo {
225 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NodeInfo, DecodeError> {
226 let channels_count: u64 = Readable::read(reader)?;
227 let mut channels = Vec::with_capacity(cmp::min(channels_count, MAX_ALLOC_SIZE / 8) as usize);
228 for _ in 0..channels_count {
229 channels.push(Readable::read(reader)?);
231 let lowest_inbound_channel_fee_base_msat = Readable::read(reader)?;
232 let lowest_inbound_channel_fee_proportional_millionths = Readable::read(reader)?;
233 let features = Readable::read(reader)?;
234 let last_update = Readable::read(reader)?;
235 let rgb = Readable::read(reader)?;
236 let alias = Readable::read(reader)?;
237 let addresses_count: u64 = Readable::read(reader)?;
238 let mut addresses = Vec::with_capacity(cmp::min(addresses_count, MAX_ALLOC_SIZE / 40) as usize);
239 for _ in 0..addresses_count {
240 match Readable::read(reader) {
241 Ok(Ok(addr)) => { addresses.push(addr); },
242 Ok(Err(_)) => return Err(DecodeError::InvalidValue),
243 Err(DecodeError::ShortRead) => return Err(DecodeError::BadLengthDescriptor),
247 let announcement_message = Readable::read(reader)?;
250 lowest_inbound_channel_fee_base_msat,
251 lowest_inbound_channel_fee_proportional_millionths,
264 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
265 channels: BTreeMap<(u64, Sha256dHash), ChannelInfo>,
266 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
267 channels: BTreeMap<u64, ChannelInfo>,
269 our_node_id: PublicKey,
270 nodes: BTreeMap<PublicKey, NodeInfo>,
273 impl Writeable for NetworkMap {
274 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
275 (self.channels.len() as u64).write(writer)?;
276 for (ref chan_id, ref chan_info) in self.channels.iter() {
277 (*chan_id).write(writer)?;
278 chan_info.write(writer)?;
280 self.our_node_id.write(writer)?;
281 (self.nodes.len() as u64).write(writer)?;
282 for (ref node_id, ref node_info) in self.nodes.iter() {
283 node_id.write(writer)?;
284 node_info.write(writer)?;
290 impl Readable for NetworkMap {
291 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NetworkMap, DecodeError> {
292 let channels_count: u64 = Readable::read(reader)?;
293 let mut channels = BTreeMap::new();
294 for _ in 0..channels_count {
295 let chan_id: u64 = Readable::read(reader)?;
296 let chan_info = Readable::read(reader)?;
297 channels.insert(chan_id, chan_info);
299 let our_node_id = Readable::read(reader)?;
300 let nodes_count: u64 = Readable::read(reader)?;
301 let mut nodes = BTreeMap::new();
302 for _ in 0..nodes_count {
303 let node_id = Readable::read(reader)?;
304 let node_info = Readable::read(reader)?;
305 nodes.insert(node_id, node_info);
315 impl std::fmt::Display for NetworkMap {
316 fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
317 write!(f, "Node id {} network map\n[Channels]\n", log_pubkey!(self.our_node_id))?;
318 for (key, val) in self.channels.iter() {
319 write!(f, " {}: {}\n", key, val)?;
321 write!(f, "[Nodes]\n")?;
322 for (key, val) in self.nodes.iter() {
323 write!(f, " {}: {}\n", log_pubkey!(key), val)?;
330 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
332 fn get_key(short_channel_id: u64, chain_hash: Sha256dHash) -> (u64, Sha256dHash) {
333 (short_channel_id, chain_hash)
336 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
338 fn get_key(short_channel_id: u64, _: Sha256dHash) -> u64 {
342 #[cfg(feature = "non_bitcoin_chain_hash_routing")]
344 fn get_short_id(id: &(u64, Sha256dHash)) -> &u64 {
348 #[cfg(not(feature = "non_bitcoin_chain_hash_routing"))]
350 fn get_short_id(id: &u64) -> &u64 {
355 /// A channel descriptor which provides a last-hop route to get_route
356 pub struct RouteHint {
357 /// The node_id of the non-target end of the route
358 pub src_node_id: PublicKey,
359 /// The short_channel_id of this channel
360 pub short_channel_id: u64,
361 /// The static msat-denominated fee which must be paid to use this channel
362 pub fee_base_msat: u32,
363 /// The dynamic proportional fee which must be paid to use this channel, denominated in
364 /// millionths of the value being forwarded to the next hop.
365 pub fee_proportional_millionths: u32,
366 /// The difference in CLTV values between this node and the next node.
367 pub cltv_expiry_delta: u16,
368 /// The minimum value, in msat, which must be relayed to the next hop.
369 pub htlc_minimum_msat: u64,
372 /// Tracks a view of the network, receiving updates from peers and generating Routes to
373 /// payment destinations.
375 secp_ctx: Secp256k1<secp256k1::VerifyOnly>,
376 network_map: RwLock<NetworkMap>,
377 full_syncs_requested: AtomicUsize,
378 chain_monitor: Arc<ChainWatchInterface>,
382 const SERIALIZATION_VERSION: u8 = 1;
383 const MIN_SERIALIZATION_VERSION: u8 = 1;
385 impl Writeable for Router {
386 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
387 writer.write_all(&[SERIALIZATION_VERSION; 1])?;
388 writer.write_all(&[MIN_SERIALIZATION_VERSION; 1])?;
390 let network = self.network_map.read().unwrap();
391 network.write(writer)?;
396 /// Arguments for the creation of a Router that are not deserialized.
397 /// At a high-level, the process for deserializing a Router and resuming normal operation is:
398 /// 1) Deserialize the Router by filling in this struct and calling <Router>::read(reaser, args).
399 /// 2) Register the new Router with your ChainWatchInterface
400 pub struct RouterReadArgs {
401 /// The ChainWatchInterface for use in the Router in the future.
403 /// No calls to the ChainWatchInterface will be made during deserialization.
404 pub chain_monitor: Arc<ChainWatchInterface>,
405 /// The Logger for use in the ChannelManager and which may be used to log information during
407 pub logger: Arc<Logger>,
410 impl ReadableArgs<RouterReadArgs> for Router {
411 fn read<R: ::std::io::Read>(reader: &mut R, args: RouterReadArgs) -> Result<Router, DecodeError> {
412 let _ver: u8 = Readable::read(reader)?;
413 let min_ver: u8 = Readable::read(reader)?;
414 if min_ver > SERIALIZATION_VERSION {
415 return Err(DecodeError::UnknownVersion);
417 let network_map = Readable::read(reader)?;
419 secp_ctx: Secp256k1::verification_only(),
420 network_map: RwLock::new(network_map),
421 full_syncs_requested: AtomicUsize::new(0),
422 chain_monitor: args.chain_monitor,
428 macro_rules! secp_verify_sig {
429 ( $secp_ctx: expr, $msg: expr, $sig: expr, $pubkey: expr ) => {
430 match $secp_ctx.verify($msg, $sig, $pubkey) {
432 Err(_) => return Err(LightningError{err: "Invalid signature from remote node", action: ErrorAction::IgnoreError}),
437 impl RoutingMessageHandler for Router {
439 fn handle_node_announcement(&self, msg: &msgs::NodeAnnouncement) -> Result<bool, LightningError> {
440 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
441 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.signature, &msg.contents.node_id);
443 let mut network = self.network_map.write().unwrap();
444 match network.nodes.get_mut(&msg.contents.node_id) {
445 None => Err(LightningError{err: "No existing channels for node_announcement", action: ErrorAction::IgnoreError}),
447 match node.last_update {
448 Some(last_update) => if last_update >= msg.contents.timestamp {
449 return Err(LightningError{err: "Update older than last processed update", action: ErrorAction::IgnoreError});
454 node.features = msg.contents.features.clone();
455 node.last_update = Some(msg.contents.timestamp);
456 node.rgb = msg.contents.rgb;
457 node.alias = msg.contents.alias;
458 node.addresses = msg.contents.addresses.clone();
460 let should_relay = msg.contents.excess_data.is_empty() && msg.contents.excess_address_data.is_empty();
461 node.announcement_message = if should_relay { Some(msg.clone()) } else { None };
467 fn handle_channel_announcement(&self, msg: &msgs::ChannelAnnouncement) -> Result<bool, LightningError> {
468 if msg.contents.node_id_1 == msg.contents.node_id_2 || msg.contents.bitcoin_key_1 == msg.contents.bitcoin_key_2 {
469 return Err(LightningError{err: "Channel announcement node had a channel with itself", action: ErrorAction::IgnoreError});
472 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
473 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.node_signature_1, &msg.contents.node_id_1);
474 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.node_signature_2, &msg.contents.node_id_2);
475 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.bitcoin_signature_1, &msg.contents.bitcoin_key_1);
476 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.bitcoin_signature_2, &msg.contents.bitcoin_key_2);
478 let checked_utxo = match self.chain_monitor.get_chain_utxo(msg.contents.chain_hash, msg.contents.short_channel_id) {
479 Ok((script_pubkey, _value)) => {
480 let expected_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
481 .push_slice(&msg.contents.bitcoin_key_1.serialize())
482 .push_slice(&msg.contents.bitcoin_key_2.serialize())
483 .push_opcode(opcodes::all::OP_PUSHNUM_2)
484 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
485 if script_pubkey != expected_script {
486 return Err(LightningError{err: "Channel announcement keys didn't match on-chain script", action: ErrorAction::IgnoreError});
488 //TODO: Check if value is worth storing, use it to inform routing, and compare it
489 //to the new HTLC max field in channel_update
492 Err(ChainError::NotSupported) => {
493 // Tentatively accept, potentially exposing us to DoS attacks
496 Err(ChainError::NotWatched) => {
497 return Err(LightningError{err: "Channel announced on an unknown chain", action: ErrorAction::IgnoreError});
499 Err(ChainError::UnknownTx) => {
500 return Err(LightningError{err: "Channel announced without corresponding UTXO entry", action: ErrorAction::IgnoreError});
504 let mut network_lock = self.network_map.write().unwrap();
505 let network = &mut *network_lock;
507 let should_relay = msg.contents.excess_data.is_empty();
509 let chan_info = ChannelInfo {
510 features: msg.contents.features.clone(),
511 one_to_two: DirectionalChannelInfo {
512 src_node_id: msg.contents.node_id_1.clone(),
515 cltv_expiry_delta: u16::max_value(),
516 htlc_minimum_msat: u64::max_value(),
517 fee_base_msat: u32::max_value(),
518 fee_proportional_millionths: u32::max_value(),
519 last_update_message: None,
521 two_to_one: DirectionalChannelInfo {
522 src_node_id: msg.contents.node_id_2.clone(),
525 cltv_expiry_delta: u16::max_value(),
526 htlc_minimum_msat: u64::max_value(),
527 fee_base_msat: u32::max_value(),
528 fee_proportional_millionths: u32::max_value(),
529 last_update_message: None,
531 announcement_message: if should_relay { Some(msg.clone()) } else { None },
534 match network.channels.entry(NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash)) {
535 BtreeEntry::Occupied(mut entry) => {
536 //TODO: because asking the blockchain if short_channel_id is valid is only optional
537 //in the blockchain API, we need to handle it smartly here, though it's unclear
540 // Either our UTXO provider is busted, there was a reorg, or the UTXO provider
541 // only sometimes returns results. In any case remove the previous entry. Note
542 // that the spec expects us to "blacklist" the node_ids involved, but we can't
544 // a) we don't *require* a UTXO provider that always returns results.
545 // b) we don't track UTXOs of channels we know about and remove them if they
547 // c) it's unclear how to do so without exposing ourselves to massive DoS risk.
548 Self::remove_channel_in_nodes(&mut network.nodes, &entry.get(), msg.contents.short_channel_id);
549 *entry.get_mut() = chan_info;
551 return Err(LightningError{err: "Already have knowledge of channel", action: ErrorAction::IgnoreError})
554 BtreeEntry::Vacant(entry) => {
555 entry.insert(chan_info);
559 macro_rules! add_channel_to_node {
560 ( $node_id: expr ) => {
561 match network.nodes.entry($node_id) {
562 BtreeEntry::Occupied(node_entry) => {
563 node_entry.into_mut().channels.push(NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash));
565 BtreeEntry::Vacant(node_entry) => {
566 node_entry.insert(NodeInfo {
567 channels: vec!(NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash)),
568 lowest_inbound_channel_fee_base_msat: u32::max_value(),
569 lowest_inbound_channel_fee_proportional_millionths: u32::max_value(),
570 features: NodeFeatures::empty(),
574 addresses: Vec::new(),
575 announcement_message: None,
582 add_channel_to_node!(msg.contents.node_id_1);
583 add_channel_to_node!(msg.contents.node_id_2);
585 log_trace!(self, "Added channel_announcement for {}{}", msg.contents.short_channel_id, if !should_relay { " with excess uninterpreted data!" } else { "" });
589 fn handle_htlc_fail_channel_update(&self, update: &msgs::HTLCFailChannelUpdate) {
591 &msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg } => {
592 let _ = self.handle_channel_update(msg);
594 &msgs::HTLCFailChannelUpdate::ChannelClosed { ref short_channel_id, ref is_permanent } => {
595 let mut network = self.network_map.write().unwrap();
597 if let Some(chan) = network.channels.remove(short_channel_id) {
598 Self::remove_channel_in_nodes(&mut network.nodes, &chan, *short_channel_id);
601 if let Some(chan) = network.channels.get_mut(short_channel_id) {
602 chan.one_to_two.enabled = false;
603 chan.two_to_one.enabled = false;
607 &msgs::HTLCFailChannelUpdate::NodeFailure { ref node_id, ref is_permanent } => {
609 //TODO: Wholly remove the node
611 self.mark_node_bad(node_id, false);
617 fn handle_channel_update(&self, msg: &msgs::ChannelUpdate) -> Result<bool, LightningError> {
618 let mut network = self.network_map.write().unwrap();
620 let chan_enabled = msg.contents.flags & (1 << 1) != (1 << 1);
621 let chan_was_enabled;
623 match network.channels.get_mut(&NetworkMap::get_key(msg.contents.short_channel_id, msg.contents.chain_hash)) {
624 None => return Err(LightningError{err: "Couldn't find channel for update", action: ErrorAction::IgnoreError}),
626 macro_rules! maybe_update_channel_info {
627 ( $target: expr) => {
628 if $target.last_update >= msg.contents.timestamp {
629 return Err(LightningError{err: "Update older than last processed update", action: ErrorAction::IgnoreError});
631 chan_was_enabled = $target.enabled;
632 $target.last_update = msg.contents.timestamp;
633 $target.enabled = chan_enabled;
634 $target.cltv_expiry_delta = msg.contents.cltv_expiry_delta;
635 $target.htlc_minimum_msat = msg.contents.htlc_minimum_msat;
636 $target.fee_base_msat = msg.contents.fee_base_msat;
637 $target.fee_proportional_millionths = msg.contents.fee_proportional_millionths;
638 $target.last_update_message = if msg.contents.excess_data.is_empty() {
645 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
646 if msg.contents.flags & 1 == 1 {
647 dest_node_id = channel.one_to_two.src_node_id.clone();
648 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.signature, &channel.two_to_one.src_node_id);
649 maybe_update_channel_info!(channel.two_to_one);
651 dest_node_id = channel.two_to_one.src_node_id.clone();
652 secp_verify_sig!(self.secp_ctx, &msg_hash, &msg.signature, &channel.one_to_two.src_node_id);
653 maybe_update_channel_info!(channel.one_to_two);
659 let node = network.nodes.get_mut(&dest_node_id).unwrap();
660 node.lowest_inbound_channel_fee_base_msat = cmp::min(node.lowest_inbound_channel_fee_base_msat, msg.contents.fee_base_msat);
661 node.lowest_inbound_channel_fee_proportional_millionths = cmp::min(node.lowest_inbound_channel_fee_proportional_millionths, msg.contents.fee_proportional_millionths);
662 } else if chan_was_enabled {
663 let mut lowest_inbound_channel_fee_base_msat = u32::max_value();
664 let mut lowest_inbound_channel_fee_proportional_millionths = u32::max_value();
667 let node = network.nodes.get(&dest_node_id).unwrap();
669 for chan_id in node.channels.iter() {
670 let chan = network.channels.get(chan_id).unwrap();
671 if chan.one_to_two.src_node_id == dest_node_id {
672 lowest_inbound_channel_fee_base_msat = cmp::min(lowest_inbound_channel_fee_base_msat, chan.two_to_one.fee_base_msat);
673 lowest_inbound_channel_fee_proportional_millionths = cmp::min(lowest_inbound_channel_fee_proportional_millionths, chan.two_to_one.fee_proportional_millionths);
675 lowest_inbound_channel_fee_base_msat = cmp::min(lowest_inbound_channel_fee_base_msat, chan.one_to_two.fee_base_msat);
676 lowest_inbound_channel_fee_proportional_millionths = cmp::min(lowest_inbound_channel_fee_proportional_millionths, chan.one_to_two.fee_proportional_millionths);
681 //TODO: satisfy the borrow-checker without a double-map-lookup :(
682 let mut_node = network.nodes.get_mut(&dest_node_id).unwrap();
683 mut_node.lowest_inbound_channel_fee_base_msat = lowest_inbound_channel_fee_base_msat;
684 mut_node.lowest_inbound_channel_fee_proportional_millionths = lowest_inbound_channel_fee_proportional_millionths;
687 Ok(msg.contents.excess_data.is_empty())
690 fn get_next_channel_announcements(&self, starting_point: u64, batch_amount: u8) -> Vec<(msgs::ChannelAnnouncement, Option<msgs::ChannelUpdate>, Option<msgs::ChannelUpdate>)> {
691 let mut result = Vec::with_capacity(batch_amount as usize);
692 let network = self.network_map.read().unwrap();
693 let mut iter = network.channels.range(starting_point..);
694 while result.len() < batch_amount as usize {
695 if let Some((_, ref chan)) = iter.next() {
696 if chan.announcement_message.is_some() {
697 result.push((chan.announcement_message.clone().unwrap(),
698 chan.one_to_two.last_update_message.clone(),
699 chan.two_to_one.last_update_message.clone()));
701 // TODO: We may end up sending un-announced channel_updates if we are sending
702 // initial sync data while receiving announce/updates for this channel.
711 fn get_next_node_announcements(&self, starting_point: Option<&PublicKey>, batch_amount: u8) -> Vec<msgs::NodeAnnouncement> {
712 let mut result = Vec::with_capacity(batch_amount as usize);
713 let network = self.network_map.read().unwrap();
714 let mut iter = if let Some(pubkey) = starting_point {
715 let mut iter = network.nodes.range((*pubkey)..);
719 network.nodes.range(..)
721 while result.len() < batch_amount as usize {
722 if let Some((_, ref node)) = iter.next() {
723 if node.announcement_message.is_some() {
724 result.push(node.announcement_message.clone().unwrap());
733 fn should_request_full_sync(&self, _node_id: &PublicKey) -> bool {
734 //TODO: Determine whether to request a full sync based on the network map.
735 const FULL_SYNCS_TO_REQUEST: usize = 5;
736 if self.full_syncs_requested.load(Ordering::Acquire) < FULL_SYNCS_TO_REQUEST {
737 self.full_syncs_requested.fetch_add(1, Ordering::AcqRel);
745 #[derive(Eq, PartialEq)]
746 struct RouteGraphNode {
748 lowest_fee_to_peer_through_node: u64,
749 lowest_fee_to_node: u64,
752 impl cmp::Ord for RouteGraphNode {
753 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
754 other.lowest_fee_to_peer_through_node.cmp(&self.lowest_fee_to_peer_through_node)
755 .then_with(|| other.pubkey.serialize().cmp(&self.pubkey.serialize()))
759 impl cmp::PartialOrd for RouteGraphNode {
760 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
761 Some(self.cmp(other))
765 struct DummyDirectionalChannelInfo {
766 src_node_id: PublicKey,
767 cltv_expiry_delta: u32,
768 htlc_minimum_msat: u64,
770 fee_proportional_millionths: u32,
774 /// Creates a new router with the given node_id to be used as the source for get_route()
775 pub fn new(our_pubkey: PublicKey, chain_monitor: Arc<ChainWatchInterface>, logger: Arc<Logger>) -> Router {
776 let mut nodes = BTreeMap::new();
777 nodes.insert(our_pubkey.clone(), NodeInfo {
778 channels: Vec::new(),
779 lowest_inbound_channel_fee_base_msat: u32::max_value(),
780 lowest_inbound_channel_fee_proportional_millionths: u32::max_value(),
781 features: NodeFeatures::empty(),
785 addresses: Vec::new(),
786 announcement_message: None,
789 secp_ctx: Secp256k1::verification_only(),
790 network_map: RwLock::new(NetworkMap {
791 channels: BTreeMap::new(),
792 our_node_id: our_pubkey,
795 full_syncs_requested: AtomicUsize::new(0),
801 /// Dumps the entire network view of this Router to the logger provided in the constructor at
803 pub fn trace_state(&self) {
804 log_trace!(self, "{}", self.network_map.read().unwrap());
807 /// Get network addresses by node id
808 pub fn get_addresses(&self, pubkey: &PublicKey) -> Option<Vec<NetAddress>> {
809 let network = self.network_map.read().unwrap();
810 network.nodes.get(pubkey).map(|n| n.addresses.clone())
813 /// Marks a node as having failed a route. This will avoid re-using the node in routes for now,
814 /// with an exponential decay in node "badness". Note that there is deliberately no
815 /// mark_channel_bad as a node may simply lie and suggest that an upstream channel from it is
816 /// what failed the route and not the node itself. Instead, setting the blamed_upstream_node
817 /// boolean will reduce the penalty, returning the node to usability faster. If the node is
818 /// behaving correctly, it will disable the failing channel and we will use it again next time.
819 pub fn mark_node_bad(&self, _node_id: &PublicKey, _blamed_upstream_node: bool) {
823 fn remove_channel_in_nodes(nodes: &mut BTreeMap<PublicKey, NodeInfo>, chan: &ChannelInfo, short_channel_id: u64) {
824 macro_rules! remove_from_node {
825 ($node_id: expr) => {
826 if let BtreeEntry::Occupied(mut entry) = nodes.entry($node_id) {
827 entry.get_mut().channels.retain(|chan_id| {
828 short_channel_id != *NetworkMap::get_short_id(chan_id)
830 if entry.get().channels.is_empty() {
831 entry.remove_entry();
834 panic!("Had channel that pointed to unknown node (ie inconsistent network map)!");
838 remove_from_node!(chan.one_to_two.src_node_id);
839 remove_from_node!(chan.two_to_one.src_node_id);
842 /// Gets a route from us to the given target node.
844 /// Extra routing hops between known nodes and the target will be used if they are included in
847 /// If some channels aren't announced, it may be useful to fill in a first_hops with the
848 /// results from a local ChannelManager::list_usable_channels() call. If it is filled in, our
849 /// (this Router's) view of our local channels will be ignored, and only those in first_hops
852 /// Panics if first_hops contains channels without short_channel_ids
853 /// (ChannelManager::list_usable_channels will never include such channels).
855 /// The fees on channels from us to next-hops are ignored (as they are assumed to all be
856 /// equal), however the enabled/disabled bit on such channels as well as the htlc_minimum_msat
857 /// *is* checked as they may change based on the receiving node.
858 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> {
859 // TODO: Obviously *only* using total fee cost sucks. We should consider weighting by
860 // uptime/success in using a node in the past.
861 let network = self.network_map.read().unwrap();
863 if *target == network.our_node_id {
864 return Err(LightningError{err: "Cannot generate a route to ourselves", action: ErrorAction::IgnoreError});
867 if final_value_msat > 21_000_000 * 1_0000_0000 * 1000 {
868 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis", action: ErrorAction::IgnoreError});
871 // We do a dest-to-source Dijkstra's sorting by each node's distance from the destination
872 // plus the minimum per-HTLC fee to get from it to another node (aka "shitty A*").
873 // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
874 // to use as the A* heuristic beyond just the cost to get one node further than the current
877 let dummy_directional_info = DummyDirectionalChannelInfo { // used for first_hops routes
878 src_node_id: network.our_node_id.clone(),
879 cltv_expiry_delta: 0,
880 htlc_minimum_msat: 0,
882 fee_proportional_millionths: 0,
885 let mut targets = BinaryHeap::new(); //TODO: Do we care about switching to eg Fibbonaci heap?
886 let mut dist = HashMap::with_capacity(network.nodes.len());
888 let mut first_hop_targets = HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
889 if let Some(hops) = first_hops {
891 let short_channel_id = chan.short_channel_id.expect("first_hops should be filled in with usable channels, not pending ones");
892 if chan.remote_network_id == *target {
894 paths: vec![vec![RouteHop {
895 pubkey: chan.remote_network_id,
896 node_features: NodeFeatures::with_known_relevant_init_flags(&chan.counterparty_features),
898 channel_features: ChannelFeatures::with_known_relevant_init_flags(&chan.counterparty_features),
899 fee_msat: final_value_msat,
900 cltv_expiry_delta: final_cltv,
904 first_hop_targets.insert(chan.remote_network_id, (short_channel_id, chan.counterparty_features.clone()));
906 if first_hop_targets.is_empty() {
907 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us", action: ErrorAction::IgnoreError});
911 macro_rules! add_entry {
912 // Adds entry which goes from the node pointed to by $directional_info to
913 // $dest_node_id over the channel with id $chan_id with fees described in
914 // $directional_info.
915 ( $chan_id: expr, $dest_node_id: expr, $directional_info: expr, $chan_features: expr, $starting_fee_msat: expr ) => {
916 //TODO: Explore simply adding fee to hit htlc_minimum_msat
917 if $starting_fee_msat as u64 + final_value_msat >= $directional_info.htlc_minimum_msat {
918 let proportional_fee_millions = ($starting_fee_msat + final_value_msat).checked_mul($directional_info.fee_proportional_millionths as u64);
919 if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
920 ($directional_info.fee_base_msat as u64).checked_add(part / 1000000) })
922 let mut total_fee = $starting_fee_msat as u64;
923 let hm_entry = dist.entry(&$directional_info.src_node_id);
924 let old_entry = hm_entry.or_insert_with(|| {
925 let node = network.nodes.get(&$directional_info.src_node_id).unwrap();
927 node.lowest_inbound_channel_fee_base_msat,
928 node.lowest_inbound_channel_fee_proportional_millionths,
930 pubkey: $dest_node_id.clone(),
931 node_features: NodeFeatures::empty(),
933 channel_features: $chan_features.clone(),
935 cltv_expiry_delta: 0,
938 if $directional_info.src_node_id != network.our_node_id {
939 // Ignore new_fee for channel-from-us as we assume all channels-from-us
940 // will have the same effective-fee
941 total_fee += new_fee;
942 if let Some(fee_inc) = final_value_msat.checked_add(total_fee).and_then(|inc| { (old_entry.2 as u64).checked_mul(inc) }) {
943 total_fee += fee_inc / 1000000 + (old_entry.1 as u64);
945 // max_value means we'll always fail the old_entry.0 > total_fee check
946 total_fee = u64::max_value();
949 let new_graph_node = RouteGraphNode {
950 pubkey: $directional_info.src_node_id,
951 lowest_fee_to_peer_through_node: total_fee,
952 lowest_fee_to_node: $starting_fee_msat as u64 + new_fee,
954 if old_entry.0 > total_fee {
955 targets.push(new_graph_node);
956 old_entry.0 = total_fee;
957 old_entry.3 = RouteHop {
958 pubkey: $dest_node_id.clone(),
959 node_features: NodeFeatures::empty(),
960 short_channel_id: $chan_id.clone(),
961 channel_features: $chan_features.clone(),
962 fee_msat: new_fee, // This field is ignored on the last-hop anyway
963 cltv_expiry_delta: $directional_info.cltv_expiry_delta as u32,
971 macro_rules! add_entries_to_cheapest_to_target_node {
972 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr ) => {
973 if first_hops.is_some() {
974 if let Some(&(ref first_hop, ref features)) = first_hop_targets.get(&$node_id) {
975 add_entry!(first_hop, $node_id, dummy_directional_info, ChannelFeatures::with_known_relevant_init_flags(&features), $fee_to_target_msat);
979 if !$node.features.requires_unknown_bits() {
980 for chan_id in $node.channels.iter() {
981 let chan = network.channels.get(chan_id).unwrap();
982 if !chan.features.requires_unknown_bits() {
983 if chan.one_to_two.src_node_id == *$node_id {
984 // ie $node is one, ie next hop in A* is two, via the two_to_one channel
985 if first_hops.is_none() || chan.two_to_one.src_node_id != network.our_node_id {
986 if chan.two_to_one.enabled {
987 add_entry!(chan_id, chan.one_to_two.src_node_id, chan.two_to_one, chan.features, $fee_to_target_msat);
991 if first_hops.is_none() || chan.one_to_two.src_node_id != network.our_node_id {
992 if chan.one_to_two.enabled {
993 add_entry!(chan_id, chan.two_to_one.src_node_id, chan.one_to_two, chan.features, $fee_to_target_msat);
1003 match network.nodes.get(target) {
1006 add_entries_to_cheapest_to_target_node!(node, target, 0);
1010 for hop in last_hops.iter() {
1011 if first_hops.is_none() || hop.src_node_id != network.our_node_id { // first_hop overrules last_hops
1012 if network.nodes.get(&hop.src_node_id).is_some() {
1013 if first_hops.is_some() {
1014 if let Some(&(ref first_hop, ref features)) = first_hop_targets.get(&hop.src_node_id) {
1015 // Currently there are no channel-context features defined, so we are a
1016 // bit lazy here. In the future, we should pull them out via our
1017 // ChannelManager, but there's no reason to waste the space until we
1019 add_entry!(first_hop, hop.src_node_id, dummy_directional_info, ChannelFeatures::with_known_relevant_init_flags(&features), 0);
1022 // BOLT 11 doesn't allow inclusion of features for the last hop hints, which
1023 // really sucks, cause we're gonna need that eventually.
1024 add_entry!(hop.short_channel_id, target, hop, ChannelFeatures::empty(), 0);
1029 while let Some(RouteGraphNode { pubkey, lowest_fee_to_node, .. }) = targets.pop() {
1030 if pubkey == network.our_node_id {
1031 let mut res = vec!(dist.remove(&network.our_node_id).unwrap().3);
1033 if let Some(&(_, ref features)) = first_hop_targets.get(&res.last().unwrap().pubkey) {
1034 res.last_mut().unwrap().node_features = NodeFeatures::with_known_relevant_init_flags(&features);
1035 } else if let Some(node) = network.nodes.get(&res.last().unwrap().pubkey) {
1036 res.last_mut().unwrap().node_features = node.features.clone();
1038 // We should be able to fill in features for everything except the last
1039 // hop, if the last hop was provided via a BOLT 11 invoice (though we
1040 // should be able to extend it further as BOLT 11 does have feature
1041 // flags for the last hop node itself).
1042 assert!(res.last().unwrap().pubkey == *target);
1044 if res.last().unwrap().pubkey == *target {
1048 let new_entry = match dist.remove(&res.last().unwrap().pubkey) {
1050 None => return Err(LightningError{err: "Failed to find a non-fee-overflowing path to the given destination", action: ErrorAction::IgnoreError}),
1052 res.last_mut().unwrap().fee_msat = new_entry.fee_msat;
1053 res.last_mut().unwrap().cltv_expiry_delta = new_entry.cltv_expiry_delta;
1054 res.push(new_entry);
1056 res.last_mut().unwrap().fee_msat = final_value_msat;
1057 res.last_mut().unwrap().cltv_expiry_delta = final_cltv;
1058 let route = Route { paths: vec![res] };
1059 log_trace!(self, "Got route: {}", log_route!(route));
1063 match network.nodes.get(&pubkey) {
1066 add_entries_to_cheapest_to_target_node!(node, &pubkey, lowest_fee_to_node);
1071 Err(LightningError{err: "Failed to find a path to the given destination", action: ErrorAction::IgnoreError})
1077 use chain::chaininterface;
1078 use ln::channelmanager;
1079 use ln::router::{Router,NodeInfo,NetworkMap,ChannelInfo,DirectionalChannelInfo,RouteHint};
1080 use ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
1081 use ln::msgs::{ErrorAction, LightningError, RoutingMessageHandler, UnsignedNodeAnnouncement, NodeAnnouncement,
1082 UnsignedChannelAnnouncement, ChannelAnnouncement, UnsignedChannelUpdate, ChannelUpdate, HTLCFailChannelUpdate};
1083 use util::test_utils;
1084 use util::test_utils::TestVecWriter;
1085 use util::logger::Logger;
1086 use util::ser::{Writeable, Readable};
1088 use bitcoin_hashes::sha256d::Hash as Sha256dHash;
1089 use bitcoin_hashes::Hash;
1090 use bitcoin::network::constants::Network;
1091 use bitcoin::blockdata::constants::genesis_block;
1092 use bitcoin::blockdata::script::Builder;
1093 use bitcoin::blockdata::opcodes;
1094 use bitcoin::util::hash::BitcoinHash;
1098 use secp256k1::key::{PublicKey,SecretKey};
1100 use secp256k1::Secp256k1;
1103 use std::collections::btree_map::Entry as BtreeEntry;
1105 fn create_router() -> (Secp256k1<All>, PublicKey, Router) {
1106 let secp_ctx = Secp256k1::new();
1107 let our_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap());
1108 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
1109 let chain_monitor = Arc::new(chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet, Arc::clone(&logger)));
1110 let router = Router::new(our_id, chain_monitor, Arc::clone(&logger));
1111 (secp_ctx, our_id, router)
1116 let (secp_ctx, our_id, router) = create_router();
1118 // Build network from our_id to node8:
1120 // -1(1)2- node1 -1(3)2-
1122 // our_id -1(12)2- node8 -1(13)2--- node3
1124 // -1(2)2- node2 -1(4)2-
1127 // chan1 1-to-2: disabled
1128 // chan1 2-to-1: enabled, 0 fee
1130 // chan2 1-to-2: enabled, ignored fee
1131 // chan2 2-to-1: enabled, 0 fee
1133 // chan3 1-to-2: enabled, 0 fee
1134 // chan3 2-to-1: enabled, 100 msat fee
1136 // chan4 1-to-2: enabled, 100% fee
1137 // chan4 2-to-1: enabled, 0 fee
1139 // chan12 1-to-2: enabled, ignored fee
1140 // chan12 2-to-1: enabled, 0 fee
1142 // chan13 1-to-2: enabled, 200% fee
1143 // chan13 2-to-1: enabled, 0 fee
1146 // -1(5)2- node4 -1(8)2--
1150 // node3--1(6)2- node5 -1(9)2--- node7 (not in global route map)
1152 // -1(7)2- node6 -1(10)2-
1154 // chan5 1-to-2: enabled, 100 msat fee
1155 // chan5 2-to-1: enabled, 0 fee
1157 // chan6 1-to-2: enabled, 0 fee
1158 // chan6 2-to-1: enabled, 0 fee
1160 // chan7 1-to-2: enabled, 100% fee
1161 // chan7 2-to-1: enabled, 0 fee
1163 // chan8 1-to-2: enabled, variable fee (0 then 1000 msat)
1164 // chan8 2-to-1: enabled, 0 fee
1166 // chan9 1-to-2: enabled, 1001 msat fee
1167 // chan9 2-to-1: enabled, 0 fee
1169 // chan10 1-to-2: enabled, 0 fee
1170 // chan10 2-to-1: enabled, 0 fee
1172 // chan11 1-to-2: enabled, 0 fee
1173 // chan11 2-to-1: enabled, 0 fee
1175 let node1 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap()[..]).unwrap());
1176 let node2 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0303030303030303030303030303030303030303030303030303030303030303").unwrap()[..]).unwrap());
1177 let node3 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0404040404040404040404040404040404040404040404040404040404040404").unwrap()[..]).unwrap());
1178 let node4 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0505050505050505050505050505050505050505050505050505050505050505").unwrap()[..]).unwrap());
1179 let node5 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0606060606060606060606060606060606060606060606060606060606060606").unwrap()[..]).unwrap());
1180 let node6 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0707070707070707070707070707070707070707070707070707070707070707").unwrap()[..]).unwrap());
1181 let node7 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0808080808080808080808080808080808080808080808080808080808080808").unwrap()[..]).unwrap());
1182 let node8 = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0909090909090909090909090909090909090909090909090909090909090909").unwrap()[..]).unwrap());
1184 let zero_hash = Sha256dHash::hash(&[0; 32]);
1186 macro_rules! id_to_feature_flags {
1187 // Set the feature flags to the id'th odd (ie non-required) feature bit so that we can
1188 // test for it later.
1190 let idx = ($id - 1) * 2 + 1;
1192 vec![1 << (idx - 8*3), 0, 0, 0]
1193 } else if idx > 8*2 {
1194 vec![1 << (idx - 8*2), 0, 0]
1195 } else if idx > 8*1 {
1196 vec![1 << (idx - 8*1), 0]
1204 let mut network = router.network_map.write().unwrap();
1206 network.nodes.insert(node1.clone(), NodeInfo {
1207 channels: vec!(NetworkMap::get_key(1, zero_hash.clone()), NetworkMap::get_key(3, zero_hash.clone())),
1208 lowest_inbound_channel_fee_base_msat: 100,
1209 lowest_inbound_channel_fee_proportional_millionths: 0,
1210 features: NodeFeatures::from_le_bytes(id_to_feature_flags!(1)),
1211 last_update: Some(1),
1214 addresses: Vec::new(),
1215 announcement_message: None,
1217 network.channels.insert(NetworkMap::get_key(1, zero_hash.clone()), ChannelInfo {
1218 features: ChannelFeatures::from_le_bytes(id_to_feature_flags!(1)),
1219 one_to_two: DirectionalChannelInfo {
1220 src_node_id: our_id.clone(),
1223 cltv_expiry_delta: u16::max_value(), // This value should be ignored
1224 htlc_minimum_msat: 0,
1225 fee_base_msat: u32::max_value(), // This value should be ignored
1226 fee_proportional_millionths: u32::max_value(), // This value should be ignored
1227 last_update_message: None,
1228 }, two_to_one: DirectionalChannelInfo {
1229 src_node_id: node1.clone(),
1232 cltv_expiry_delta: 0,
1233 htlc_minimum_msat: 0,
1235 fee_proportional_millionths: 0,
1236 last_update_message: None,
1238 announcement_message: None,
1240 network.nodes.insert(node2.clone(), NodeInfo {
1241 channels: vec!(NetworkMap::get_key(2, zero_hash.clone()), NetworkMap::get_key(4, zero_hash.clone())),
1242 lowest_inbound_channel_fee_base_msat: 0,
1243 lowest_inbound_channel_fee_proportional_millionths: 0,
1244 features: NodeFeatures::from_le_bytes(id_to_feature_flags!(2)),
1245 last_update: Some(1),
1248 addresses: Vec::new(),
1249 announcement_message: None,
1251 network.channels.insert(NetworkMap::get_key(2, zero_hash.clone()), ChannelInfo {
1252 features: ChannelFeatures::from_le_bytes(id_to_feature_flags!(2)),
1253 one_to_two: DirectionalChannelInfo {
1254 src_node_id: our_id.clone(),
1257 cltv_expiry_delta: u16::max_value(), // This value should be ignored
1258 htlc_minimum_msat: 0,
1259 fee_base_msat: u32::max_value(), // This value should be ignored
1260 fee_proportional_millionths: u32::max_value(), // This value should be ignored
1261 last_update_message: None,
1262 }, two_to_one: DirectionalChannelInfo {
1263 src_node_id: node2.clone(),
1266 cltv_expiry_delta: 0,
1267 htlc_minimum_msat: 0,
1269 fee_proportional_millionths: 0,
1270 last_update_message: None,
1272 announcement_message: None,
1274 network.nodes.insert(node8.clone(), NodeInfo {
1275 channels: vec!(NetworkMap::get_key(12, zero_hash.clone()), NetworkMap::get_key(13, zero_hash.clone())),
1276 lowest_inbound_channel_fee_base_msat: 0,
1277 lowest_inbound_channel_fee_proportional_millionths: 0,
1278 features: NodeFeatures::from_le_bytes(id_to_feature_flags!(8)),
1279 last_update: Some(1),
1282 addresses: Vec::new(),
1283 announcement_message: None,
1285 network.channels.insert(NetworkMap::get_key(12, zero_hash.clone()), ChannelInfo {
1286 features: ChannelFeatures::from_le_bytes(id_to_feature_flags!(12)),
1287 one_to_two: DirectionalChannelInfo {
1288 src_node_id: our_id.clone(),
1291 cltv_expiry_delta: u16::max_value(), // This value should be ignored
1292 htlc_minimum_msat: 0,
1293 fee_base_msat: u32::max_value(), // This value should be ignored
1294 fee_proportional_millionths: u32::max_value(), // This value should be ignored
1295 last_update_message: None,
1296 }, two_to_one: DirectionalChannelInfo {
1297 src_node_id: node8.clone(),
1300 cltv_expiry_delta: 0,
1301 htlc_minimum_msat: 0,
1303 fee_proportional_millionths: 0,
1304 last_update_message: None,
1306 announcement_message: None,
1308 network.nodes.insert(node3.clone(), NodeInfo {
1310 NetworkMap::get_key(3, zero_hash.clone()),
1311 NetworkMap::get_key(4, zero_hash.clone()),
1312 NetworkMap::get_key(13, zero_hash.clone()),
1313 NetworkMap::get_key(5, zero_hash.clone()),
1314 NetworkMap::get_key(6, zero_hash.clone()),
1315 NetworkMap::get_key(7, zero_hash.clone())),
1316 lowest_inbound_channel_fee_base_msat: 0,
1317 lowest_inbound_channel_fee_proportional_millionths: 0,
1318 features: NodeFeatures::from_le_bytes(id_to_feature_flags!(3)),
1319 last_update: Some(1),
1322 addresses: Vec::new(),
1323 announcement_message: None,
1325 network.channels.insert(NetworkMap::get_key(3, zero_hash.clone()), ChannelInfo {
1326 features: ChannelFeatures::from_le_bytes(id_to_feature_flags!(3)),
1327 one_to_two: DirectionalChannelInfo {
1328 src_node_id: node1.clone(),
1331 cltv_expiry_delta: (3 << 8) | 1,
1332 htlc_minimum_msat: 0,
1334 fee_proportional_millionths: 0,
1335 last_update_message: None,
1336 }, two_to_one: DirectionalChannelInfo {
1337 src_node_id: node3.clone(),
1340 cltv_expiry_delta: (3 << 8) | 2,
1341 htlc_minimum_msat: 0,
1343 fee_proportional_millionths: 0,
1344 last_update_message: None,
1346 announcement_message: None,
1348 network.channels.insert(NetworkMap::get_key(4, zero_hash.clone()), ChannelInfo {
1349 features: ChannelFeatures::from_le_bytes(id_to_feature_flags!(4)),
1350 one_to_two: DirectionalChannelInfo {
1351 src_node_id: node2.clone(),
1354 cltv_expiry_delta: (4 << 8) | 1,
1355 htlc_minimum_msat: 0,
1357 fee_proportional_millionths: 1000000,
1358 last_update_message: None,
1359 }, two_to_one: DirectionalChannelInfo {
1360 src_node_id: node3.clone(),
1363 cltv_expiry_delta: (4 << 8) | 2,
1364 htlc_minimum_msat: 0,
1366 fee_proportional_millionths: 0,
1367 last_update_message: None,
1369 announcement_message: None,
1371 network.channels.insert(NetworkMap::get_key(13, zero_hash.clone()), ChannelInfo {
1372 features: ChannelFeatures::from_le_bytes(id_to_feature_flags!(13)),
1373 one_to_two: DirectionalChannelInfo {
1374 src_node_id: node8.clone(),
1377 cltv_expiry_delta: (13 << 8) | 1,
1378 htlc_minimum_msat: 0,
1380 fee_proportional_millionths: 2000000,
1381 last_update_message: None,
1382 }, two_to_one: DirectionalChannelInfo {
1383 src_node_id: node3.clone(),
1386 cltv_expiry_delta: (13 << 8) | 2,
1387 htlc_minimum_msat: 0,
1389 fee_proportional_millionths: 0,
1390 last_update_message: None,
1392 announcement_message: None,
1394 network.nodes.insert(node4.clone(), NodeInfo {
1395 channels: vec!(NetworkMap::get_key(5, zero_hash.clone()), NetworkMap::get_key(11, zero_hash.clone())),
1396 lowest_inbound_channel_fee_base_msat: 0,
1397 lowest_inbound_channel_fee_proportional_millionths: 0,
1398 features: NodeFeatures::from_le_bytes(id_to_feature_flags!(4)),
1399 last_update: Some(1),
1402 addresses: Vec::new(),
1403 announcement_message: None,
1405 network.channels.insert(NetworkMap::get_key(5, zero_hash.clone()), ChannelInfo {
1406 features: ChannelFeatures::from_le_bytes(id_to_feature_flags!(5)),
1407 one_to_two: DirectionalChannelInfo {
1408 src_node_id: node3.clone(),
1411 cltv_expiry_delta: (5 << 8) | 1,
1412 htlc_minimum_msat: 0,
1414 fee_proportional_millionths: 0,
1415 last_update_message: None,
1416 }, two_to_one: DirectionalChannelInfo {
1417 src_node_id: node4.clone(),
1420 cltv_expiry_delta: (5 << 8) | 2,
1421 htlc_minimum_msat: 0,
1423 fee_proportional_millionths: 0,
1424 last_update_message: None,
1426 announcement_message: None,
1428 network.nodes.insert(node5.clone(), NodeInfo {
1429 channels: vec!(NetworkMap::get_key(6, zero_hash.clone()), NetworkMap::get_key(11, zero_hash.clone())),
1430 lowest_inbound_channel_fee_base_msat: 0,
1431 lowest_inbound_channel_fee_proportional_millionths: 0,
1432 features: NodeFeatures::from_le_bytes(id_to_feature_flags!(5)),
1433 last_update: Some(1),
1436 addresses: Vec::new(),
1437 announcement_message: None,
1439 network.channels.insert(NetworkMap::get_key(6, zero_hash.clone()), ChannelInfo {
1440 features: ChannelFeatures::from_le_bytes(id_to_feature_flags!(6)),
1441 one_to_two: DirectionalChannelInfo {
1442 src_node_id: node3.clone(),
1445 cltv_expiry_delta: (6 << 8) | 1,
1446 htlc_minimum_msat: 0,
1448 fee_proportional_millionths: 0,
1449 last_update_message: None,
1450 }, two_to_one: DirectionalChannelInfo {
1451 src_node_id: node5.clone(),
1454 cltv_expiry_delta: (6 << 8) | 2,
1455 htlc_minimum_msat: 0,
1457 fee_proportional_millionths: 0,
1458 last_update_message: None,
1460 announcement_message: None,
1462 network.channels.insert(NetworkMap::get_key(11, zero_hash.clone()), ChannelInfo {
1463 features: ChannelFeatures::from_le_bytes(id_to_feature_flags!(11)),
1464 one_to_two: DirectionalChannelInfo {
1465 src_node_id: node5.clone(),
1468 cltv_expiry_delta: (11 << 8) | 1,
1469 htlc_minimum_msat: 0,
1471 fee_proportional_millionths: 0,
1472 last_update_message: None,
1473 }, two_to_one: DirectionalChannelInfo {
1474 src_node_id: node4.clone(),
1477 cltv_expiry_delta: (11 << 8) | 2,
1478 htlc_minimum_msat: 0,
1480 fee_proportional_millionths: 0,
1481 last_update_message: None,
1483 announcement_message: None,
1485 network.nodes.insert(node6.clone(), NodeInfo {
1486 channels: vec!(NetworkMap::get_key(7, zero_hash.clone())),
1487 lowest_inbound_channel_fee_base_msat: 0,
1488 lowest_inbound_channel_fee_proportional_millionths: 0,
1489 features: NodeFeatures::from_le_bytes(id_to_feature_flags!(6)),
1490 last_update: Some(1),
1493 addresses: Vec::new(),
1494 announcement_message: None,
1496 network.channels.insert(NetworkMap::get_key(7, zero_hash.clone()), ChannelInfo {
1497 features: ChannelFeatures::from_le_bytes(id_to_feature_flags!(7)),
1498 one_to_two: DirectionalChannelInfo {
1499 src_node_id: node3.clone(),
1502 cltv_expiry_delta: (7 << 8) | 1,
1503 htlc_minimum_msat: 0,
1505 fee_proportional_millionths: 1000000,
1506 last_update_message: None,
1507 }, two_to_one: DirectionalChannelInfo {
1508 src_node_id: node6.clone(),
1511 cltv_expiry_delta: (7 << 8) | 2,
1512 htlc_minimum_msat: 0,
1514 fee_proportional_millionths: 0,
1515 last_update_message: None,
1517 announcement_message: None,
1521 { // Simple route to 3 via 2
1522 let route = router.get_route(&node3, None, &Vec::new(), 100, 42).unwrap();
1523 assert_eq!(route.paths[0].len(), 2);
1525 assert_eq!(route.paths[0][0].pubkey, node2);
1526 assert_eq!(route.paths[0][0].short_channel_id, 2);
1527 assert_eq!(route.paths[0][0].fee_msat, 100);
1528 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
1529 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags!(2));
1530 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags!(2));
1532 assert_eq!(route.paths[0][1].pubkey, node3);
1533 assert_eq!(route.paths[0][1].short_channel_id, 4);
1534 assert_eq!(route.paths[0][1].fee_msat, 100);
1535 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1536 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags!(3));
1537 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags!(4));
1540 { // Disable channels 4 and 12 by requiring unknown feature bits
1541 let mut network = router.network_map.write().unwrap();
1542 network.channels.get_mut(&NetworkMap::get_key(4, zero_hash.clone())).unwrap().features.set_require_unknown_bits();
1543 network.channels.get_mut(&NetworkMap::get_key(12, zero_hash.clone())).unwrap().features.set_require_unknown_bits();
1546 { // If all the channels require some features we don't understand, route should fail
1547 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = router.get_route(&node3, None, &Vec::new(), 100, 42) {
1548 assert_eq!(err, "Failed to find a path to the given destination");
1549 } else { panic!(); }
1552 { // If we specify a channel to node8, that overrides our local channel view and that gets used
1553 let our_chans = vec![channelmanager::ChannelDetails {
1554 channel_id: [0; 32],
1555 short_channel_id: Some(42),
1556 remote_network_id: node8.clone(),
1557 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1558 channel_value_satoshis: 0,
1560 outbound_capacity_msat: 0,
1561 inbound_capacity_msat: 0,
1564 let route = router.get_route(&node3, Some(&our_chans), &Vec::new(), 100, 42).unwrap();
1565 assert_eq!(route.paths[0].len(), 2);
1567 assert_eq!(route.paths[0][0].pubkey, node8);
1568 assert_eq!(route.paths[0][0].short_channel_id, 42);
1569 assert_eq!(route.paths[0][0].fee_msat, 200);
1570 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
1571 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
1572 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::new()); // No feature flags will meet the relevant-to-channel conversion
1574 assert_eq!(route.paths[0][1].pubkey, node3);
1575 assert_eq!(route.paths[0][1].short_channel_id, 13);
1576 assert_eq!(route.paths[0][1].fee_msat, 100);
1577 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1578 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags!(3));
1579 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags!(13));
1582 { // Re-enable channels 4 and 12 by wiping the unknown feature bits
1583 let mut network = router.network_map.write().unwrap();
1584 network.channels.get_mut(&NetworkMap::get_key(4, zero_hash.clone())).unwrap().features.clear_require_unknown_bits();
1585 network.channels.get_mut(&NetworkMap::get_key(12, zero_hash.clone())).unwrap().features.clear_require_unknown_bits();
1588 { // Disable nodes 1, 2, and 8 by requiring unknown feature bits
1589 let mut network = router.network_map.write().unwrap();
1590 network.nodes.get_mut(&node1).unwrap().features.set_require_unknown_bits();
1591 network.nodes.get_mut(&node2).unwrap().features.set_require_unknown_bits();
1592 network.nodes.get_mut(&node8).unwrap().features.set_require_unknown_bits();
1595 { // If all nodes require some features we don't understand, route should fail
1596 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = router.get_route(&node3, None, &Vec::new(), 100, 42) {
1597 assert_eq!(err, "Failed to find a path to the given destination");
1598 } else { panic!(); }
1601 { // If we specify a channel to node8, that overrides our local channel view and that gets used
1602 let our_chans = vec![channelmanager::ChannelDetails {
1603 channel_id: [0; 32],
1604 short_channel_id: Some(42),
1605 remote_network_id: node8.clone(),
1606 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1607 channel_value_satoshis: 0,
1609 outbound_capacity_msat: 0,
1610 inbound_capacity_msat: 0,
1613 let route = router.get_route(&node3, Some(&our_chans), &Vec::new(), 100, 42).unwrap();
1614 assert_eq!(route.paths[0].len(), 2);
1616 assert_eq!(route.paths[0][0].pubkey, node8);
1617 assert_eq!(route.paths[0][0].short_channel_id, 42);
1618 assert_eq!(route.paths[0][0].fee_msat, 200);
1619 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
1620 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
1621 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::new()); // No feature flags will meet the relevant-to-channel conversion
1623 assert_eq!(route.paths[0][1].pubkey, node3);
1624 assert_eq!(route.paths[0][1].short_channel_id, 13);
1625 assert_eq!(route.paths[0][1].fee_msat, 100);
1626 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1627 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags!(3));
1628 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags!(13));
1631 { // Re-enable nodes 1, 2, and 8
1632 let mut network = router.network_map.write().unwrap();
1633 network.nodes.get_mut(&node1).unwrap().features.clear_require_unknown_bits();
1634 network.nodes.get_mut(&node2).unwrap().features.clear_require_unknown_bits();
1635 network.nodes.get_mut(&node8).unwrap().features.clear_require_unknown_bits();
1638 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
1639 // naively) assume that the user checked the feature bits on the invoice, which override
1640 // the node_announcement.
1642 { // Route to 1 via 2 and 3 because our channel to 1 is disabled
1643 let route = router.get_route(&node1, None, &Vec::new(), 100, 42).unwrap();
1644 assert_eq!(route.paths[0].len(), 3);
1646 assert_eq!(route.paths[0][0].pubkey, node2);
1647 assert_eq!(route.paths[0][0].short_channel_id, 2);
1648 assert_eq!(route.paths[0][0].fee_msat, 200);
1649 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
1650 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags!(2));
1651 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags!(2));
1653 assert_eq!(route.paths[0][1].pubkey, node3);
1654 assert_eq!(route.paths[0][1].short_channel_id, 4);
1655 assert_eq!(route.paths[0][1].fee_msat, 100);
1656 assert_eq!(route.paths[0][1].cltv_expiry_delta, (3 << 8) | 2);
1657 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags!(3));
1658 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags!(4));
1660 assert_eq!(route.paths[0][2].pubkey, node1);
1661 assert_eq!(route.paths[0][2].short_channel_id, 3);
1662 assert_eq!(route.paths[0][2].fee_msat, 100);
1663 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
1664 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags!(1));
1665 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags!(3));
1668 { // If we specify a channel to node8, that overrides our local channel view and that gets used
1669 let our_chans = vec![channelmanager::ChannelDetails {
1670 channel_id: [0; 32],
1671 short_channel_id: Some(42),
1672 remote_network_id: node8.clone(),
1673 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1674 channel_value_satoshis: 0,
1676 outbound_capacity_msat: 0,
1677 inbound_capacity_msat: 0,
1680 let route = router.get_route(&node3, Some(&our_chans), &Vec::new(), 100, 42).unwrap();
1681 assert_eq!(route.paths[0].len(), 2);
1683 assert_eq!(route.paths[0][0].pubkey, node8);
1684 assert_eq!(route.paths[0][0].short_channel_id, 42);
1685 assert_eq!(route.paths[0][0].fee_msat, 200);
1686 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
1687 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
1688 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::new()); // No feature flags will meet the relevant-to-channel conversion
1690 assert_eq!(route.paths[0][1].pubkey, node3);
1691 assert_eq!(route.paths[0][1].short_channel_id, 13);
1692 assert_eq!(route.paths[0][1].fee_msat, 100);
1693 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1694 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags!(3));
1695 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags!(13));
1698 let mut last_hops = vec!(RouteHint {
1699 src_node_id: node4.clone(),
1700 short_channel_id: 8,
1702 fee_proportional_millionths: 0,
1703 cltv_expiry_delta: (8 << 8) | 1,
1704 htlc_minimum_msat: 0,
1706 src_node_id: node5.clone(),
1707 short_channel_id: 9,
1708 fee_base_msat: 1001,
1709 fee_proportional_millionths: 0,
1710 cltv_expiry_delta: (9 << 8) | 1,
1711 htlc_minimum_msat: 0,
1713 src_node_id: node6.clone(),
1714 short_channel_id: 10,
1716 fee_proportional_millionths: 0,
1717 cltv_expiry_delta: (10 << 8) | 1,
1718 htlc_minimum_msat: 0,
1721 { // Simple test across 2, 3, 5, and 4 via a last_hop channel
1722 let route = router.get_route(&node7, None, &last_hops, 100, 42).unwrap();
1723 assert_eq!(route.paths[0].len(), 5);
1725 assert_eq!(route.paths[0][0].pubkey, node2);
1726 assert_eq!(route.paths[0][0].short_channel_id, 2);
1727 assert_eq!(route.paths[0][0].fee_msat, 100);
1728 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
1729 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags!(2));
1730 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags!(2));
1732 assert_eq!(route.paths[0][1].pubkey, node3);
1733 assert_eq!(route.paths[0][1].short_channel_id, 4);
1734 assert_eq!(route.paths[0][1].fee_msat, 0);
1735 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
1736 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags!(3));
1737 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags!(4));
1739 assert_eq!(route.paths[0][2].pubkey, node5);
1740 assert_eq!(route.paths[0][2].short_channel_id, 6);
1741 assert_eq!(route.paths[0][2].fee_msat, 0);
1742 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
1743 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags!(5));
1744 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags!(6));
1746 assert_eq!(route.paths[0][3].pubkey, node4);
1747 assert_eq!(route.paths[0][3].short_channel_id, 11);
1748 assert_eq!(route.paths[0][3].fee_msat, 0);
1749 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
1750 // If we have a peer in the node map, we'll use their features here since we don't have
1751 // a way of figuring out their features from the invoice:
1752 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags!(4));
1753 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags!(11));
1755 assert_eq!(route.paths[0][4].pubkey, node7);
1756 assert_eq!(route.paths[0][4].short_channel_id, 8);
1757 assert_eq!(route.paths[0][4].fee_msat, 100);
1758 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
1759 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::new()); // We dont pass flags in from invoices yet
1760 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::new()); // We can't learn any flags from invoices, sadly
1763 { // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
1764 let our_chans = vec![channelmanager::ChannelDetails {
1765 channel_id: [0; 32],
1766 short_channel_id: Some(42),
1767 remote_network_id: node4.clone(),
1768 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1769 channel_value_satoshis: 0,
1771 outbound_capacity_msat: 0,
1772 inbound_capacity_msat: 0,
1775 let route = router.get_route(&node7, Some(&our_chans), &last_hops, 100, 42).unwrap();
1776 assert_eq!(route.paths[0].len(), 2);
1778 assert_eq!(route.paths[0][0].pubkey, node4);
1779 assert_eq!(route.paths[0][0].short_channel_id, 42);
1780 assert_eq!(route.paths[0][0].fee_msat, 0);
1781 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
1782 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
1783 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::new()); // No feature flags will meet the relevant-to-channel conversion
1785 assert_eq!(route.paths[0][1].pubkey, node7);
1786 assert_eq!(route.paths[0][1].short_channel_id, 8);
1787 assert_eq!(route.paths[0][1].fee_msat, 100);
1788 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1789 assert_eq!(route.paths[0][1].node_features.le_flags(), &Vec::new()); // We dont pass flags in from invoices yet
1790 assert_eq!(route.paths[0][1].channel_features.le_flags(), &Vec::new()); // We can't learn any flags from invoices, sadly
1793 last_hops[0].fee_base_msat = 1000;
1795 { // Revert to via 6 as the fee on 8 goes up
1796 let route = router.get_route(&node7, None, &last_hops, 100, 42).unwrap();
1797 assert_eq!(route.paths[0].len(), 4);
1799 assert_eq!(route.paths[0][0].pubkey, node2);
1800 assert_eq!(route.paths[0][0].short_channel_id, 2);
1801 assert_eq!(route.paths[0][0].fee_msat, 200); // fee increased as its % of value transferred across node
1802 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
1803 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags!(2));
1804 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags!(2));
1806 assert_eq!(route.paths[0][1].pubkey, node3);
1807 assert_eq!(route.paths[0][1].short_channel_id, 4);
1808 assert_eq!(route.paths[0][1].fee_msat, 100);
1809 assert_eq!(route.paths[0][1].cltv_expiry_delta, (7 << 8) | 1);
1810 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags!(3));
1811 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags!(4));
1813 assert_eq!(route.paths[0][2].pubkey, node6);
1814 assert_eq!(route.paths[0][2].short_channel_id, 7);
1815 assert_eq!(route.paths[0][2].fee_msat, 0);
1816 assert_eq!(route.paths[0][2].cltv_expiry_delta, (10 << 8) | 1);
1817 // If we have a peer in the node map, we'll use their features here since we don't have
1818 // a way of figuring out their features from the invoice:
1819 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags!(6));
1820 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags!(7));
1822 assert_eq!(route.paths[0][3].pubkey, node7);
1823 assert_eq!(route.paths[0][3].short_channel_id, 10);
1824 assert_eq!(route.paths[0][3].fee_msat, 100);
1825 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
1826 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::new()); // We dont pass flags in from invoices yet
1827 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::new()); // We can't learn any flags from invoices, sadly
1830 { // ...but still use 8 for larger payments as 6 has a variable feerate
1831 let route = router.get_route(&node7, None, &last_hops, 2000, 42).unwrap();
1832 assert_eq!(route.paths[0].len(), 5);
1834 assert_eq!(route.paths[0][0].pubkey, node2);
1835 assert_eq!(route.paths[0][0].short_channel_id, 2);
1836 assert_eq!(route.paths[0][0].fee_msat, 3000);
1837 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
1838 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags!(2));
1839 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags!(2));
1841 assert_eq!(route.paths[0][1].pubkey, node3);
1842 assert_eq!(route.paths[0][1].short_channel_id, 4);
1843 assert_eq!(route.paths[0][1].fee_msat, 0);
1844 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
1845 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags!(3));
1846 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags!(4));
1848 assert_eq!(route.paths[0][2].pubkey, node5);
1849 assert_eq!(route.paths[0][2].short_channel_id, 6);
1850 assert_eq!(route.paths[0][2].fee_msat, 0);
1851 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
1852 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags!(5));
1853 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags!(6));
1855 assert_eq!(route.paths[0][3].pubkey, node4);
1856 assert_eq!(route.paths[0][3].short_channel_id, 11);
1857 assert_eq!(route.paths[0][3].fee_msat, 1000);
1858 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
1859 // If we have a peer in the node map, we'll use their features here since we don't have
1860 // a way of figuring out their features from the invoice:
1861 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags!(4));
1862 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags!(11));
1864 assert_eq!(route.paths[0][4].pubkey, node7);
1865 assert_eq!(route.paths[0][4].short_channel_id, 8);
1866 assert_eq!(route.paths[0][4].fee_msat, 2000);
1867 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
1868 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::new()); // We dont pass flags in from invoices yet
1869 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::new()); // We can't learn any flags from invoices, sadly
1872 { // Test Router serialization/deserialization
1873 let mut w = TestVecWriter(Vec::new());
1874 let network = router.network_map.read().unwrap();
1875 assert!(!network.channels.is_empty());
1876 assert!(!network.nodes.is_empty());
1877 network.write(&mut w).unwrap();
1878 assert!(<NetworkMap>::read(&mut ::std::io::Cursor::new(&w.0)).unwrap() == *network);
1883 fn request_full_sync_finite_times() {
1884 let (secp_ctx, _, router) = create_router();
1885 let node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap()[..]).unwrap());
1887 assert!(router.should_request_full_sync(&node_id));
1888 assert!(router.should_request_full_sync(&node_id));
1889 assert!(router.should_request_full_sync(&node_id));
1890 assert!(router.should_request_full_sync(&node_id));
1891 assert!(router.should_request_full_sync(&node_id));
1892 assert!(!router.should_request_full_sync(&node_id));
1896 fn handling_node_announcements() {
1897 let (secp_ctx, _, router) = create_router();
1899 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1900 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1901 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1902 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1903 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1904 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1905 let zero_hash = Sha256dHash::hash(&[0; 32]);
1906 let first_announcement_time = 500;
1908 let mut unsigned_announcement = UnsignedNodeAnnouncement {
1909 features: NodeFeatures::supported(),
1910 timestamp: first_announcement_time,
1914 addresses: Vec::new(),
1915 excess_address_data: Vec::new(),
1916 excess_data: Vec::new(),
1918 let mut msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1919 let valid_announcement = NodeAnnouncement {
1920 signature: secp_ctx.sign(&msghash, node_1_privkey),
1921 contents: unsigned_announcement.clone()
1924 match router.handle_node_announcement(&valid_announcement) {
1926 Err(e) => assert_eq!("No existing channels for node_announcement", e.err)
1930 // Announce a channel to add a corresponding node.
1931 let unsigned_announcement = UnsignedChannelAnnouncement {
1932 features: ChannelFeatures::supported(),
1933 chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
1934 short_channel_id: 0,
1937 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1938 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1939 excess_data: Vec::new(),
1942 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1943 let valid_announcement = ChannelAnnouncement {
1944 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1945 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1946 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1947 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1948 contents: unsigned_announcement.clone(),
1950 match router.handle_channel_announcement(&valid_announcement) {
1951 Ok(res) => assert!(res),
1956 match router.handle_node_announcement(&valid_announcement) {
1957 Ok(res) => assert!(res),
1961 let fake_msghash = hash_to_message!(&zero_hash);
1962 match router.handle_node_announcement(
1964 signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
1965 contents: unsigned_announcement.clone()
1968 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1971 unsigned_announcement.timestamp += 1000;
1972 unsigned_announcement.excess_data.push(1);
1973 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1974 let announcement_with_data = NodeAnnouncement {
1975 signature: secp_ctx.sign(&msghash, node_1_privkey),
1976 contents: unsigned_announcement.clone()
1978 // Return false because contains excess data.
1979 match router.handle_node_announcement(&announcement_with_data) {
1980 Ok(res) => assert!(!res),
1983 unsigned_announcement.excess_data = Vec::new();
1985 // Even though previous announcement was not relayed further, we still accepted it,
1986 // so we now won't accept announcements before the previous one.
1987 unsigned_announcement.timestamp -= 10;
1988 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1989 let outdated_announcement = NodeAnnouncement {
1990 signature: secp_ctx.sign(&msghash, node_1_privkey),
1991 contents: unsigned_announcement.clone()
1993 match router.handle_node_announcement(&outdated_announcement) {
1995 Err(e) => assert_eq!(e.err, "Update older than last processed update")
2000 fn handling_channel_announcements() {
2001 let secp_ctx = Secp256k1::new();
2002 let our_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(
2003 &hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap());
2004 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
2005 let chain_monitor = Arc::new(test_utils::TestChainWatcher::new());
2006 let router = Router::new(our_id, chain_monitor.clone(), Arc::clone(&logger));
2008 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2009 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2010 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
2011 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
2012 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
2013 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
2015 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
2016 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_1_btckey).serialize())
2017 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_2_btckey).serialize())
2018 .push_opcode(opcodes::all::OP_PUSHNUM_2)
2019 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
2022 let mut unsigned_announcement = UnsignedChannelAnnouncement {
2023 features: ChannelFeatures::supported(),
2024 chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
2025 short_channel_id: 0,
2028 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
2029 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
2030 excess_data: Vec::new(),
2033 let channel_key = NetworkMap::get_key(unsigned_announcement.short_channel_id,
2034 unsigned_announcement.chain_hash);
2036 let mut msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
2037 let valid_announcement = ChannelAnnouncement {
2038 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
2039 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
2040 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
2041 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
2042 contents: unsigned_announcement.clone(),
2045 // Test if the UTXO lookups were not supported
2046 *chain_monitor.utxo_ret.lock().unwrap() = Err(chaininterface::ChainError::NotSupported);
2048 match router.handle_channel_announcement(&valid_announcement) {
2049 Ok(res) => assert!(res),
2053 let network = router.network_map.write().unwrap();
2054 match network.channels.get(&channel_key) {
2060 // If we receive announcement for the same channel (with UTXO lookups disabled),
2061 // drop new one on the floor, since we can't see any changes.
2062 match router.handle_channel_announcement(&valid_announcement) {
2064 Err(e) => assert_eq!(e.err, "Already have knowledge of channel")
2068 // Test if an associated transaction were not on-chain (or not confirmed).
2069 *chain_monitor.utxo_ret.lock().unwrap() = Err(chaininterface::ChainError::UnknownTx);
2070 unsigned_announcement.short_channel_id += 1;
2072 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
2073 let valid_announcement = ChannelAnnouncement {
2074 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
2075 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
2076 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
2077 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
2078 contents: unsigned_announcement.clone(),
2081 match router.handle_channel_announcement(&valid_announcement) {
2083 Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
2087 // Now test if the transaction is found in the UTXO set and the script is correct.
2088 unsigned_announcement.short_channel_id += 1;
2089 *chain_monitor.utxo_ret.lock().unwrap() = Ok((good_script.clone(), 0));
2090 let channel_key = NetworkMap::get_key(unsigned_announcement.short_channel_id,
2091 unsigned_announcement.chain_hash);
2093 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
2094 let valid_announcement = ChannelAnnouncement {
2095 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
2096 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
2097 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
2098 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
2099 contents: unsigned_announcement.clone(),
2101 match router.handle_channel_announcement(&valid_announcement) {
2102 Ok(res) => assert!(res),
2106 let network = router.network_map.write().unwrap();
2107 match network.channels.get(&channel_key) {
2113 // If we receive announcement for the same channel (but TX is not confirmed),
2114 // drop new one on the floor, since we can't see any changes.
2115 *chain_monitor.utxo_ret.lock().unwrap() = Err(chaininterface::ChainError::UnknownTx);
2116 match router.handle_channel_announcement(&valid_announcement) {
2118 Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
2121 // But if it is confirmed, replace the channel
2122 *chain_monitor.utxo_ret.lock().unwrap() = Ok((good_script, 0));
2123 unsigned_announcement.features = ChannelFeatures::empty();
2124 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
2125 let valid_announcement = ChannelAnnouncement {
2126 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
2127 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
2128 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
2129 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
2130 contents: unsigned_announcement.clone(),
2132 match router.handle_channel_announcement(&valid_announcement) {
2133 Ok(res) => assert!(res),
2137 let mut network = router.network_map.write().unwrap();
2138 match network.channels.entry(channel_key) {
2139 BtreeEntry::Occupied(channel_entry) => {
2140 assert_eq!(channel_entry.get().features, ChannelFeatures::empty());
2146 // Don't relay valid channels with excess data
2147 unsigned_announcement.short_channel_id += 1;
2148 unsigned_announcement.excess_data.push(1);
2149 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
2150 let valid_announcement = ChannelAnnouncement {
2151 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
2152 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
2153 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
2154 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
2155 contents: unsigned_announcement.clone(),
2157 match router.handle_channel_announcement(&valid_announcement) {
2158 Ok(res) => assert!(!res),
2162 unsigned_announcement.excess_data = Vec::new();
2163 let invalid_sig_announcement = ChannelAnnouncement {
2164 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
2165 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
2166 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
2167 bitcoin_signature_2: secp_ctx.sign(&msghash, node_1_btckey),
2168 contents: unsigned_announcement.clone(),
2170 match router.handle_channel_announcement(&invalid_sig_announcement) {
2172 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
2175 unsigned_announcement.node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
2176 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
2177 let channel_to_itself_announcement = ChannelAnnouncement {
2178 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
2179 node_signature_2: secp_ctx.sign(&msghash, node_1_privkey),
2180 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
2181 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
2182 contents: unsigned_announcement.clone(),
2184 match router.handle_channel_announcement(&channel_to_itself_announcement) {
2186 Err(e) => assert_eq!(e.err, "Channel announcement node had a channel with itself")
2191 fn handling_channel_update() {
2192 let (secp_ctx, _, router) = create_router();
2193 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2194 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2195 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
2196 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
2197 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
2198 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
2200 let zero_hash = Sha256dHash::hash(&[0; 32]);
2201 let short_channel_id = 0;
2202 let chain_hash = genesis_block(Network::Testnet).header.bitcoin_hash();
2203 let channel_key = NetworkMap::get_key(short_channel_id, chain_hash);
2207 // Announce a channel we will update
2208 let unsigned_announcement = UnsignedChannelAnnouncement {
2209 features: ChannelFeatures::empty(),
2214 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
2215 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
2216 excess_data: Vec::new(),
2219 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
2220 let valid_channel_announcement = ChannelAnnouncement {
2221 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
2222 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
2223 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
2224 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
2225 contents: unsigned_announcement.clone(),
2227 match router.handle_channel_announcement(&valid_channel_announcement) {
2234 let mut unsigned_channel_update = UnsignedChannelUpdate {
2239 cltv_expiry_delta: 144,
2240 htlc_minimum_msat: 1000000,
2241 fee_base_msat: 10000,
2242 fee_proportional_millionths: 20,
2243 excess_data: Vec::new()
2245 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
2246 let valid_channel_update = ChannelUpdate {
2247 signature: secp_ctx.sign(&msghash, node_1_privkey),
2248 contents: unsigned_channel_update.clone()
2251 match router.handle_channel_update(&valid_channel_update) {
2252 Ok(res) => assert!(res),
2257 let network = router.network_map.write().unwrap();
2258 match network.channels.get(&channel_key) {
2260 Some(channel_info) => {
2261 assert_eq!(channel_info.one_to_two.cltv_expiry_delta, 144);
2262 assert_eq!(channel_info.two_to_one.cltv_expiry_delta, u16::max_value());
2267 unsigned_channel_update.timestamp += 100;
2268 unsigned_channel_update.excess_data.push(1);
2269 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
2270 let valid_channel_update = ChannelUpdate {
2271 signature: secp_ctx.sign(&msghash, node_1_privkey),
2272 contents: unsigned_channel_update.clone()
2274 // Return false because contains excess data
2275 match router.handle_channel_update(&valid_channel_update) {
2276 Ok(res) => assert!(!res),
2280 unsigned_channel_update.short_channel_id += 1;
2281 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
2282 let valid_channel_update = ChannelUpdate {
2283 signature: secp_ctx.sign(&msghash, node_1_privkey),
2284 contents: unsigned_channel_update.clone()
2287 match router.handle_channel_update(&valid_channel_update) {
2289 Err(e) => assert_eq!(e.err, "Couldn't find channel for update")
2291 unsigned_channel_update.short_channel_id = short_channel_id;
2294 // Even though previous update was not relayed further, we still accepted it,
2295 // so we now won't accept update before the previous one.
2296 unsigned_channel_update.timestamp -= 10;
2297 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
2298 let valid_channel_update = ChannelUpdate {
2299 signature: secp_ctx.sign(&msghash, node_1_privkey),
2300 contents: unsigned_channel_update.clone()
2303 match router.handle_channel_update(&valid_channel_update) {
2305 Err(e) => assert_eq!(e.err, "Update older than last processed update")
2307 unsigned_channel_update.timestamp += 500;
2309 let fake_msghash = hash_to_message!(&zero_hash);
2310 let invalid_sig_channel_update = ChannelUpdate {
2311 signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
2312 contents: unsigned_channel_update.clone()
2315 match router.handle_channel_update(&invalid_sig_channel_update) {
2317 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
2323 fn handling_htlc_fail_channel_update() {
2324 let (secp_ctx, our_id, router) = create_router();
2325 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2326 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2327 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
2328 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
2329 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
2330 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
2332 let short_channel_id = 0;
2333 let chain_hash = genesis_block(Network::Testnet).header.bitcoin_hash();
2334 let channel_key = NetworkMap::get_key(short_channel_id, chain_hash);
2337 // There is only local node in the table at the beginning.
2338 let network = router.network_map.read().unwrap();
2339 assert_eq!(network.nodes.len(), 1);
2340 assert_eq!(network.nodes.contains_key(&our_id), true);
2344 // Announce a channel we will update
2345 let unsigned_announcement = UnsignedChannelAnnouncement {
2346 features: ChannelFeatures::empty(),
2351 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
2352 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
2353 excess_data: Vec::new(),
2356 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
2357 let valid_channel_announcement = ChannelAnnouncement {
2358 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
2359 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
2360 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
2361 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
2362 contents: unsigned_announcement.clone(),
2364 match router.handle_channel_announcement(&valid_channel_announcement) {
2371 let channel_close_msg = HTLCFailChannelUpdate::ChannelClosed {
2376 router.handle_htlc_fail_channel_update(&channel_close_msg);
2379 // Non-permanent closing just disables a channel
2380 let network = router.network_map.write().unwrap();
2381 match network.channels.get(&channel_key) {
2383 Some(channel_info) => {
2384 assert!(!channel_info.one_to_two.enabled);
2385 assert!(!channel_info.two_to_one.enabled);
2390 let channel_close_msg = HTLCFailChannelUpdate::ChannelClosed {
2395 router.handle_htlc_fail_channel_update(&channel_close_msg);
2398 // Permanent closing deletes a channel
2399 let network = router.network_map.read().unwrap();
2400 assert_eq!(network.channels.len(), 0);
2401 // Nodes are also deleted because there are no associated channels anymore
2402 // Only the local node remains in the table.
2403 assert_eq!(network.nodes.len(), 1);
2404 assert_eq!(network.nodes.contains_key(&our_id), true);
2407 // TODO: Test HTLCFailChannelUpdate::NodeFailure, which is not implemented yet.
2411 fn getting_next_channel_announcements() {
2412 let (secp_ctx, _, router) = create_router();
2413 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2414 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2415 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
2416 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
2417 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
2418 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
2420 let short_channel_id = 1;
2421 let chain_hash = genesis_block(Network::Testnet).header.bitcoin_hash();
2422 let channel_key = NetworkMap::get_key(short_channel_id, chain_hash);
2424 // Channels were not announced yet.
2425 let channels_with_announcements = router.get_next_channel_announcements(0, 1);
2426 assert_eq!(channels_with_announcements.len(), 0);
2429 // Announce a channel we will update
2430 let unsigned_announcement = UnsignedChannelAnnouncement {
2431 features: ChannelFeatures::empty(),
2436 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
2437 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
2438 excess_data: Vec::new(),
2441 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
2442 let valid_channel_announcement = ChannelAnnouncement {
2443 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
2444 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
2445 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
2446 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
2447 contents: unsigned_announcement.clone(),
2449 match router.handle_channel_announcement(&valid_channel_announcement) {
2455 // Contains initial channel announcement now.
2456 let channels_with_announcements = router.get_next_channel_announcements(channel_key, 1);
2457 assert_eq!(channels_with_announcements.len(), 1);
2458 if let Some(channel_announcements) = channels_with_announcements.first() {
2459 let &(_, ref update_1, ref update_2) = channel_announcements;
2460 assert_eq!(update_1, &None);
2461 assert_eq!(update_2, &None);
2468 // Valid channel update
2469 let unsigned_channel_update = UnsignedChannelUpdate {
2474 cltv_expiry_delta: 144,
2475 htlc_minimum_msat: 1000000,
2476 fee_base_msat: 10000,
2477 fee_proportional_millionths: 20,
2478 excess_data: Vec::new()
2480 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
2481 let valid_channel_update = ChannelUpdate {
2482 signature: secp_ctx.sign(&msghash, node_1_privkey),
2483 contents: unsigned_channel_update.clone()
2485 match router.handle_channel_update(&valid_channel_update) {
2491 // Now contains an initial announcement and an update.
2492 let channels_with_announcements = router.get_next_channel_announcements(channel_key, 1);
2493 assert_eq!(channels_with_announcements.len(), 1);
2494 if let Some(channel_announcements) = channels_with_announcements.first() {
2495 let &(_, ref update_1, ref update_2) = channel_announcements;
2496 assert_ne!(update_1, &None);
2497 assert_eq!(update_2, &None);
2504 // Channel update with excess data.
2505 let unsigned_channel_update = UnsignedChannelUpdate {
2510 cltv_expiry_delta: 144,
2511 htlc_minimum_msat: 1000000,
2512 fee_base_msat: 10000,
2513 fee_proportional_millionths: 20,
2514 excess_data: [1; 3].to_vec()
2516 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
2517 let valid_channel_update = ChannelUpdate {
2518 signature: secp_ctx.sign(&msghash, node_1_privkey),
2519 contents: unsigned_channel_update.clone()
2521 match router.handle_channel_update(&valid_channel_update) {
2527 // Test that announcements with excess data won't be returned
2528 let channels_with_announcements = router.get_next_channel_announcements(channel_key, 1);
2529 assert_eq!(channels_with_announcements.len(), 1);
2530 if let Some(channel_announcements) = channels_with_announcements.first() {
2531 let &(_, ref update_1, ref update_2) = channel_announcements;
2532 assert_eq!(update_1, &None);
2533 assert_eq!(update_2, &None);
2538 // Further starting point have no channels after it
2539 let channels_with_announcements = router.get_next_channel_announcements(channel_key + 1000, 1);
2540 assert_eq!(channels_with_announcements.len(), 0);
2544 fn getting_next_node_announcements() {
2545 let (secp_ctx, _, router) = create_router();
2546 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2547 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2548 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
2549 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
2550 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
2551 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
2553 let short_channel_id = 1;
2554 let chain_hash = genesis_block(Network::Testnet).header.bitcoin_hash();
2557 let next_announcements = router.get_next_node_announcements(None, 10);
2558 assert_eq!(next_announcements.len(), 0);
2561 // Announce a channel to add 2 nodes
2562 let unsigned_announcement = UnsignedChannelAnnouncement {
2563 features: ChannelFeatures::empty(),
2568 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
2569 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
2570 excess_data: Vec::new(),
2573 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
2574 let valid_channel_announcement = ChannelAnnouncement {
2575 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
2576 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
2577 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
2578 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
2579 contents: unsigned_announcement.clone(),
2581 match router.handle_channel_announcement(&valid_channel_announcement) {
2588 // Nodes were never announced
2589 let next_announcements = router.get_next_node_announcements(None, 3);
2590 assert_eq!(next_announcements.len(), 0);
2593 let mut unsigned_announcement = UnsignedNodeAnnouncement {
2594 features: NodeFeatures::supported(),
2599 addresses: Vec::new(),
2600 excess_address_data: Vec::new(),
2601 excess_data: Vec::new(),
2603 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
2604 let valid_announcement = NodeAnnouncement {
2605 signature: secp_ctx.sign(&msghash, node_1_privkey),
2606 contents: unsigned_announcement.clone()
2608 match router.handle_node_announcement(&valid_announcement) {
2613 unsigned_announcement.node_id = node_id_2;
2614 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
2615 let valid_announcement = NodeAnnouncement {
2616 signature: secp_ctx.sign(&msghash, node_2_privkey),
2617 contents: unsigned_announcement.clone()
2620 match router.handle_node_announcement(&valid_announcement) {
2626 let next_announcements = router.get_next_node_announcements(None, 3);
2627 assert_eq!(next_announcements.len(), 2);
2629 // Skip the first node.
2630 let next_announcements = router.get_next_node_announcements(Some(&node_id_1), 2);
2631 assert_eq!(next_announcements.len(), 1);
2634 // Later announcement which should not be relayed (excess data) prevent us from sharing a node
2635 let unsigned_announcement = UnsignedNodeAnnouncement {
2636 features: NodeFeatures::supported(),
2641 addresses: Vec::new(),
2642 excess_address_data: Vec::new(),
2643 excess_data: [1; 3].to_vec(),
2645 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
2646 let valid_announcement = NodeAnnouncement {
2647 signature: secp_ctx.sign(&msghash, node_2_privkey),
2648 contents: unsigned_announcement.clone()
2650 match router.handle_node_announcement(&valid_announcement) {
2651 Ok(res) => assert!(!res),
2656 let next_announcements = router.get_next_node_announcements(Some(&node_id_1), 2);
2657 assert_eq!(next_announcements.len(), 0);