1 //! The top-level network map tracking logic lives here.
3 use bitcoin::secp256k1::key::PublicKey;
4 use bitcoin::secp256k1::Secp256k1;
5 use bitcoin::secp256k1;
7 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
8 use bitcoin::hashes::Hash;
9 use bitcoin::blockdata::script::Builder;
10 use bitcoin::blockdata::opcodes;
12 use chain::chaininterface::{ChainError, ChainWatchInterface};
13 use ln::features::{ChannelFeatures, NodeFeatures};
14 use ln::msgs::{DecodeError, ErrorAction, LightningError, RoutingMessageHandler, NetAddress, OptionalField, MAX_VALUE_MSAT};
16 use util::ser::{Writeable, Readable, Writer};
17 use util::logger::Logger;
20 use std::sync::RwLock;
21 use std::sync::atomic::{AtomicUsize, Ordering};
22 use std::collections::BTreeMap;
23 use std::collections::btree_map::Entry as BtreeEntry;
25 use bitcoin::hashes::hex::ToHex;
27 /// Receives and validates network updates from peers,
28 /// stores authentic and relevant data as a network graph.
29 /// This network graph is then used for routing payments.
30 /// Provides interface to help with initial routing sync by
31 /// serving historical announcements.
32 pub struct NetGraphMsgHandler<C: Deref, L: Deref> where C::Target: ChainWatchInterface, L::Target: Logger {
33 secp_ctx: Secp256k1<secp256k1::VerifyOnly>,
34 /// Representation of the payment channel network
35 pub network_graph: RwLock<NetworkGraph>,
37 full_syncs_requested: AtomicUsize,
41 impl<C: Deref, L: Deref> NetGraphMsgHandler<C, L> where C::Target: ChainWatchInterface, L::Target: Logger {
42 /// Creates a new tracker of the actual state of the network of channels and nodes,
43 /// assuming a fresh network graph.
44 /// Chain monitor is used to make sure announced channels exist on-chain,
45 /// channel data is correct, and that the announcement is signed with
46 /// channel owners' keys.
47 pub fn new(chain_monitor: C, logger: L) -> Self {
49 secp_ctx: Secp256k1::verification_only(),
50 network_graph: RwLock::new(NetworkGraph {
51 channels: BTreeMap::new(),
52 nodes: BTreeMap::new(),
54 full_syncs_requested: AtomicUsize::new(0),
60 /// Creates a new tracker of the actual state of the network of channels and nodes,
61 /// assuming an existing Network Graph.
62 pub fn from_net_graph(chain_monitor: C, logger: L, network_graph: NetworkGraph) -> Self {
64 secp_ctx: Secp256k1::verification_only(),
65 network_graph: RwLock::new(network_graph),
66 full_syncs_requested: AtomicUsize::new(0),
74 macro_rules! secp_verify_sig {
75 ( $secp_ctx: expr, $msg: expr, $sig: expr, $pubkey: expr ) => {
76 match $secp_ctx.verify($msg, $sig, $pubkey) {
78 Err(_) => return Err(LightningError{err: "Invalid signature from remote node".to_owned(), action: ErrorAction::IgnoreError}),
83 impl<C: Deref + Sync + Send, L: Deref + Sync + Send> RoutingMessageHandler for NetGraphMsgHandler<C, L> where C::Target: ChainWatchInterface, L::Target: Logger {
84 fn handle_node_announcement(&self, msg: &msgs::NodeAnnouncement) -> Result<bool, LightningError> {
85 self.network_graph.write().unwrap().update_node_from_announcement(msg, Some(&self.secp_ctx))
88 fn handle_channel_announcement(&self, msg: &msgs::ChannelAnnouncement) -> Result<bool, LightningError> {
89 if msg.contents.node_id_1 == msg.contents.node_id_2 || msg.contents.bitcoin_key_1 == msg.contents.bitcoin_key_2 {
90 return Err(LightningError{err: "Channel announcement node had a channel with itself".to_owned(), action: ErrorAction::IgnoreError});
93 let utxo_value = match self.chain_monitor.get_chain_utxo(msg.contents.chain_hash, msg.contents.short_channel_id) {
94 Ok((script_pubkey, value)) => {
95 let expected_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
96 .push_slice(&msg.contents.bitcoin_key_1.serialize())
97 .push_slice(&msg.contents.bitcoin_key_2.serialize())
98 .push_opcode(opcodes::all::OP_PUSHNUM_2)
99 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
100 if script_pubkey != expected_script {
101 return Err(LightningError{err: format!("Channel announcement key ({}) didn't match on-chain script ({})", script_pubkey.to_hex(), expected_script.to_hex()), action: ErrorAction::IgnoreError});
103 //TODO: Check if value is worth storing, use it to inform routing, and compare it
104 //to the new HTLC max field in channel_update
107 Err(ChainError::NotSupported) => {
108 // Tentatively accept, potentially exposing us to DoS attacks
111 Err(ChainError::NotWatched) => {
112 return Err(LightningError{err: format!("Channel announced on an unknown chain ({})", msg.contents.chain_hash.encode().to_hex()), action: ErrorAction::IgnoreError});
114 Err(ChainError::UnknownTx) => {
115 return Err(LightningError{err: "Channel announced without corresponding UTXO entry".to_owned(), action: ErrorAction::IgnoreError});
118 let result = self.network_graph.write().unwrap().update_channel_from_announcement(msg, utxo_value, Some(&self.secp_ctx));
119 log_trace!(self.logger, "Added channel_announcement for {}{}", msg.contents.short_channel_id, if !msg.contents.excess_data.is_empty() { " with excess uninterpreted data!" } else { "" });
123 fn handle_htlc_fail_channel_update(&self, update: &msgs::HTLCFailChannelUpdate) {
125 &msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg } => {
126 let _ = self.network_graph.write().unwrap().update_channel(msg, Some(&self.secp_ctx));
128 &msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id, is_permanent } => {
129 self.network_graph.write().unwrap().close_channel_from_update(short_channel_id, is_permanent);
131 &msgs::HTLCFailChannelUpdate::NodeFailure { ref node_id, is_permanent } => {
132 self.network_graph.write().unwrap().fail_node(node_id, is_permanent);
137 fn handle_channel_update(&self, msg: &msgs::ChannelUpdate) -> Result<bool, LightningError> {
138 self.network_graph.write().unwrap().update_channel(msg, Some(&self.secp_ctx))
141 fn get_next_channel_announcements(&self, starting_point: u64, batch_amount: u8) -> Vec<(msgs::ChannelAnnouncement, Option<msgs::ChannelUpdate>, Option<msgs::ChannelUpdate>)> {
142 let network_graph = self.network_graph.read().unwrap();
143 let mut result = Vec::with_capacity(batch_amount as usize);
144 let mut iter = network_graph.get_channels().range(starting_point..);
145 while result.len() < batch_amount as usize {
146 if let Some((_, ref chan)) = iter.next() {
147 if chan.announcement_message.is_some() {
148 let chan_announcement = chan.announcement_message.clone().unwrap();
149 let mut one_to_two_announcement: Option<msgs::ChannelUpdate> = None;
150 let mut two_to_one_announcement: Option<msgs::ChannelUpdate> = None;
151 if let Some(one_to_two) = chan.one_to_two.as_ref() {
152 one_to_two_announcement = one_to_two.last_update_message.clone();
154 if let Some(two_to_one) = chan.two_to_one.as_ref() {
155 two_to_one_announcement = two_to_one.last_update_message.clone();
157 result.push((chan_announcement, one_to_two_announcement, two_to_one_announcement));
159 // TODO: We may end up sending un-announced channel_updates if we are sending
160 // initial sync data while receiving announce/updates for this channel.
169 fn get_next_node_announcements(&self, starting_point: Option<&PublicKey>, batch_amount: u8) -> Vec<msgs::NodeAnnouncement> {
170 let network_graph = self.network_graph.read().unwrap();
171 let mut result = Vec::with_capacity(batch_amount as usize);
172 let mut iter = if let Some(pubkey) = starting_point {
173 let mut iter = network_graph.get_nodes().range((*pubkey)..);
177 network_graph.get_nodes().range(..)
179 while result.len() < batch_amount as usize {
180 if let Some((_, ref node)) = iter.next() {
181 if let Some(node_info) = node.announcement_info.as_ref() {
182 if node_info.announcement_message.is_some() {
183 result.push(node_info.announcement_message.clone().unwrap());
193 fn should_request_full_sync(&self, _node_id: &PublicKey) -> bool {
194 //TODO: Determine whether to request a full sync based on the network map.
195 const FULL_SYNCS_TO_REQUEST: usize = 5;
196 if self.full_syncs_requested.load(Ordering::Acquire) < FULL_SYNCS_TO_REQUEST {
197 self.full_syncs_requested.fetch_add(1, Ordering::AcqRel);
205 #[derive(PartialEq, Debug)]
206 /// Details about one direction of a channel. Received
207 /// within a channel update.
208 pub struct DirectionalChannelInfo {
209 /// When the last update to the channel direction was issued.
210 /// Value is opaque, as set in the announcement.
211 pub last_update: u32,
212 /// Whether the channel can be currently used for payments (in this one direction).
214 /// The difference in CLTV values that you must have when routing through this channel.
215 pub cltv_expiry_delta: u16,
216 /// The minimum value, which must be relayed to the next hop via the channel
217 pub htlc_minimum_msat: u64,
218 /// The maximum value which may be relayed to the next hop via the channel.
219 pub htlc_maximum_msat: Option<u64>,
220 /// Fees charged when the channel is used for routing
221 pub fees: RoutingFees,
222 /// Most recent update for the channel received from the network
223 /// Mostly redundant with the data we store in fields explicitly.
224 /// Everything else is useful only for sending out for initial routing sync.
225 /// Not stored if contains excess data to prevent DoS.
226 pub last_update_message: Option<msgs::ChannelUpdate>,
229 impl fmt::Display for DirectionalChannelInfo {
230 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
231 write!(f, "last_update {}, enabled {}, cltv_expiry_delta {}, htlc_minimum_msat {}, fees {:?}", self.last_update, self.enabled, self.cltv_expiry_delta, self.htlc_minimum_msat, self.fees)?;
236 impl_writeable!(DirectionalChannelInfo, 0, {
247 /// Details about a channel (both directions).
248 /// Received within a channel announcement.
249 pub struct ChannelInfo {
250 /// Protocol features of a channel communicated during its announcement
251 pub features: ChannelFeatures,
252 /// Source node of the first direction of a channel
253 pub node_one: PublicKey,
254 /// Details about the first direction of a channel
255 pub one_to_two: Option<DirectionalChannelInfo>,
256 /// Source node of the second direction of a channel
257 pub node_two: PublicKey,
258 /// Details about the second direction of a channel
259 pub two_to_one: Option<DirectionalChannelInfo>,
260 /// The channel capacity as seen on-chain, if chain lookup is available.
261 pub capacity_sats: Option<u64>,
262 /// An initial announcement of the channel
263 /// Mostly redundant with the data we store in fields explicitly.
264 /// Everything else is useful only for sending out for initial routing sync.
265 /// Not stored if contains excess data to prevent DoS.
266 pub announcement_message: Option<msgs::ChannelAnnouncement>,
269 impl fmt::Display for ChannelInfo {
270 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
271 write!(f, "features: {}, node_one: {}, one_to_two: {:?}, node_two: {}, two_to_one: {:?}",
272 log_bytes!(self.features.encode()), log_pubkey!(self.node_one), self.one_to_two, log_pubkey!(self.node_two), self.two_to_one)?;
277 impl_writeable!(ChannelInfo, 0, {
288 /// Fees for routing via a given channel or a node
289 #[derive(Eq, PartialEq, Copy, Clone, Debug)]
290 pub struct RoutingFees {
291 /// Flat routing fee in satoshis
293 /// Liquidity-based routing fee in millionths of a routed amount.
294 /// In other words, 10000 is 1%.
295 pub proportional_millionths: u32,
298 impl Readable for RoutingFees{
299 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<RoutingFees, DecodeError> {
300 let base_msat: u32 = Readable::read(reader)?;
301 let proportional_millionths: u32 = Readable::read(reader)?;
304 proportional_millionths,
309 impl Writeable for RoutingFees {
310 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
311 self.base_msat.write(writer)?;
312 self.proportional_millionths.write(writer)?;
317 #[derive(PartialEq, Debug)]
318 /// Information received in the latest node_announcement from this node.
319 pub struct NodeAnnouncementInfo {
320 /// Protocol features the node announced support for
321 pub features: NodeFeatures,
322 /// When the last known update to the node state was issued.
323 /// Value is opaque, as set in the announcement.
324 pub last_update: u32,
325 /// Color assigned to the node
327 /// Moniker assigned to the node.
328 /// May be invalid or malicious (eg control chars),
329 /// should not be exposed to the user.
331 /// Internet-level addresses via which one can connect to the node
332 pub addresses: Vec<NetAddress>,
333 /// An initial announcement of the node
334 /// Mostly redundant with the data we store in fields explicitly.
335 /// Everything else is useful only for sending out for initial routing sync.
336 /// Not stored if contains excess data to prevent DoS.
337 pub announcement_message: Option<msgs::NodeAnnouncement>
340 impl Writeable for NodeAnnouncementInfo {
341 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
342 self.features.write(writer)?;
343 self.last_update.write(writer)?;
344 self.rgb.write(writer)?;
345 self.alias.write(writer)?;
346 (self.addresses.len() as u64).write(writer)?;
347 for ref addr in &self.addresses {
350 self.announcement_message.write(writer)?;
355 impl Readable for NodeAnnouncementInfo {
356 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NodeAnnouncementInfo, DecodeError> {
357 let features = Readable::read(reader)?;
358 let last_update = Readable::read(reader)?;
359 let rgb = Readable::read(reader)?;
360 let alias = Readable::read(reader)?;
361 let addresses_count: u64 = Readable::read(reader)?;
362 let mut addresses = Vec::with_capacity(cmp::min(addresses_count, MAX_ALLOC_SIZE / 40) as usize);
363 for _ in 0..addresses_count {
364 match Readable::read(reader) {
365 Ok(Ok(addr)) => { addresses.push(addr); },
366 Ok(Err(_)) => return Err(DecodeError::InvalidValue),
367 Err(DecodeError::ShortRead) => return Err(DecodeError::BadLengthDescriptor),
371 let announcement_message = Readable::read(reader)?;
372 Ok(NodeAnnouncementInfo {
384 /// Details about a node in the network, known from the network announcement.
385 pub struct NodeInfo {
386 /// All valid channels a node has announced
387 pub channels: Vec<u64>,
388 /// Lowest fees enabling routing via any of the enabled, known channels to a node.
389 /// The two fields (flat and proportional fee) are independent,
390 /// meaning they don't have to refer to the same channel.
391 pub lowest_inbound_channel_fees: Option<RoutingFees>,
392 /// More information about a node from node_announcement.
393 /// Optional because we store a Node entry after learning about it from
394 /// a channel announcement, but before receiving a node announcement.
395 pub announcement_info: Option<NodeAnnouncementInfo>
398 impl fmt::Display for NodeInfo {
399 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
400 write!(f, "lowest_inbound_channel_fees: {:?}, channels: {:?}, announcement_info: {:?}",
401 self.lowest_inbound_channel_fees, &self.channels[..], self.announcement_info)?;
406 impl Writeable for NodeInfo {
407 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
408 (self.channels.len() as u64).write(writer)?;
409 for ref chan in self.channels.iter() {
412 self.lowest_inbound_channel_fees.write(writer)?;
413 self.announcement_info.write(writer)?;
418 const MAX_ALLOC_SIZE: u64 = 64*1024;
420 impl Readable for NodeInfo {
421 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NodeInfo, DecodeError> {
422 let channels_count: u64 = Readable::read(reader)?;
423 let mut channels = Vec::with_capacity(cmp::min(channels_count, MAX_ALLOC_SIZE / 8) as usize);
424 for _ in 0..channels_count {
425 channels.push(Readable::read(reader)?);
427 let lowest_inbound_channel_fees = Readable::read(reader)?;
428 let announcement_info = Readable::read(reader)?;
431 lowest_inbound_channel_fees,
437 /// Represents the network as nodes and channels between them
439 pub struct NetworkGraph {
440 channels: BTreeMap<u64, ChannelInfo>,
441 nodes: BTreeMap<PublicKey, NodeInfo>,
444 impl Writeable for NetworkGraph {
445 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
446 (self.channels.len() as u64).write(writer)?;
447 for (ref chan_id, ref chan_info) in self.channels.iter() {
448 (*chan_id).write(writer)?;
449 chan_info.write(writer)?;
451 (self.nodes.len() as u64).write(writer)?;
452 for (ref node_id, ref node_info) in self.nodes.iter() {
453 node_id.write(writer)?;
454 node_info.write(writer)?;
460 impl Readable for NetworkGraph {
461 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NetworkGraph, DecodeError> {
462 let channels_count: u64 = Readable::read(reader)?;
463 let mut channels = BTreeMap::new();
464 for _ in 0..channels_count {
465 let chan_id: u64 = Readable::read(reader)?;
466 let chan_info = Readable::read(reader)?;
467 channels.insert(chan_id, chan_info);
469 let nodes_count: u64 = Readable::read(reader)?;
470 let mut nodes = BTreeMap::new();
471 for _ in 0..nodes_count {
472 let node_id = Readable::read(reader)?;
473 let node_info = Readable::read(reader)?;
474 nodes.insert(node_id, node_info);
483 impl fmt::Display for NetworkGraph {
484 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
485 write!(f, "Network map\n[Channels]\n")?;
486 for (key, val) in self.channels.iter() {
487 write!(f, " {}: {}\n", key, val)?;
489 write!(f, "[Nodes]\n")?;
490 for (key, val) in self.nodes.iter() {
491 write!(f, " {}: {}\n", log_pubkey!(key), val)?;
498 /// Returns all known valid channels' short ids along with announced channel info.
499 pub fn get_channels<'a>(&'a self) -> &'a BTreeMap<u64, ChannelInfo> { &self.channels }
500 /// Returns all known nodes' public keys along with announced node info.
501 pub fn get_nodes<'a>(&'a self) -> &'a BTreeMap<PublicKey, NodeInfo> { &self.nodes }
503 /// Get network addresses by node id.
504 /// Returns None if the requested node is completely unknown,
505 /// or if node announcement for the node was never received.
506 pub fn get_addresses<'a>(&'a self, pubkey: &PublicKey) -> Option<&'a Vec<NetAddress>> {
507 if let Some(node) = self.nodes.get(pubkey) {
508 if let Some(node_info) = node.announcement_info.as_ref() {
509 return Some(&node_info.addresses)
515 /// Creates a new, empty, network graph.
516 pub fn new() -> NetworkGraph {
518 channels: BTreeMap::new(),
519 nodes: BTreeMap::new(),
523 /// For an already known node (from channel announcements), update its stored properties from a given node announcement
524 /// Announcement signatures are checked here only if Secp256k1 object is provided.
525 fn update_node_from_announcement(&mut self, msg: &msgs::NodeAnnouncement, secp_ctx: Option<&Secp256k1<secp256k1::VerifyOnly>>) -> Result<bool, LightningError> {
526 if let Some(sig_verifier) = secp_ctx {
527 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
528 secp_verify_sig!(sig_verifier, &msg_hash, &msg.signature, &msg.contents.node_id);
531 match self.nodes.get_mut(&msg.contents.node_id) {
532 None => Err(LightningError{err: "No existing channels for node_announcement".to_owned(), action: ErrorAction::IgnoreError}),
534 if let Some(node_info) = node.announcement_info.as_ref() {
535 if node_info.last_update >= msg.contents.timestamp {
536 return Err(LightningError{err: "Update older than last processed update".to_owned(), action: ErrorAction::IgnoreError});
540 let should_relay = msg.contents.excess_data.is_empty() && msg.contents.excess_address_data.is_empty();
541 node.announcement_info = Some(NodeAnnouncementInfo {
542 features: msg.contents.features.clone(),
543 last_update: msg.contents.timestamp,
544 rgb: msg.contents.rgb,
545 alias: msg.contents.alias,
546 addresses: msg.contents.addresses.clone(),
547 announcement_message: if should_relay { Some(msg.clone()) } else { None },
555 /// For a new or already known (from previous announcement) channel, store or update channel info.
556 /// Also store nodes (if not stored yet) the channel is between, and make node aware of this channel.
557 /// Checking utxo on-chain is useful if we receive an update for already known channel id,
558 /// which is probably result of a reorg. In that case, we update channel info only if the
559 /// utxo was checked, otherwise stick to the existing update, to prevent DoS risks.
560 /// Announcement signatures are checked here only if Secp256k1 object is provided.
561 fn update_channel_from_announcement(&mut self, msg: &msgs::ChannelAnnouncement, utxo_value: Option<u64>, secp_ctx: Option<&Secp256k1<secp256k1::VerifyOnly>>) -> Result<bool, LightningError> {
562 if let Some(sig_verifier) = secp_ctx {
563 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
564 secp_verify_sig!(sig_verifier, &msg_hash, &msg.node_signature_1, &msg.contents.node_id_1);
565 secp_verify_sig!(sig_verifier, &msg_hash, &msg.node_signature_2, &msg.contents.node_id_2);
566 secp_verify_sig!(sig_verifier, &msg_hash, &msg.bitcoin_signature_1, &msg.contents.bitcoin_key_1);
567 secp_verify_sig!(sig_verifier, &msg_hash, &msg.bitcoin_signature_2, &msg.contents.bitcoin_key_2);
570 let should_relay = msg.contents.excess_data.is_empty();
572 let chan_info = ChannelInfo {
573 features: msg.contents.features.clone(),
574 node_one: msg.contents.node_id_1.clone(),
576 node_two: msg.contents.node_id_2.clone(),
578 capacity_sats: utxo_value,
579 announcement_message: if should_relay { Some(msg.clone()) } else { None },
582 match self.channels.entry(msg.contents.short_channel_id) {
583 BtreeEntry::Occupied(mut entry) => {
584 //TODO: because asking the blockchain if short_channel_id is valid is only optional
585 //in the blockchain API, we need to handle it smartly here, though it's unclear
587 if utxo_value.is_some() {
588 // Either our UTXO provider is busted, there was a reorg, or the UTXO provider
589 // only sometimes returns results. In any case remove the previous entry. Note
590 // that the spec expects us to "blacklist" the node_ids involved, but we can't
592 // a) we don't *require* a UTXO provider that always returns results.
593 // b) we don't track UTXOs of channels we know about and remove them if they
595 // c) it's unclear how to do so without exposing ourselves to massive DoS risk.
596 Self::remove_channel_in_nodes(&mut self.nodes, &entry.get(), msg.contents.short_channel_id);
597 *entry.get_mut() = chan_info;
599 return Err(LightningError{err: "Already have knowledge of channel".to_owned(), action: ErrorAction::IgnoreError})
602 BtreeEntry::Vacant(entry) => {
603 entry.insert(chan_info);
607 macro_rules! add_channel_to_node {
608 ( $node_id: expr ) => {
609 match self.nodes.entry($node_id) {
610 BtreeEntry::Occupied(node_entry) => {
611 node_entry.into_mut().channels.push(msg.contents.short_channel_id);
613 BtreeEntry::Vacant(node_entry) => {
614 node_entry.insert(NodeInfo {
615 channels: vec!(msg.contents.short_channel_id),
616 lowest_inbound_channel_fees: None,
617 announcement_info: None,
624 add_channel_to_node!(msg.contents.node_id_1);
625 add_channel_to_node!(msg.contents.node_id_2);
630 /// Close a channel if a corresponding HTLC fail was sent.
631 /// If permanent, removes a channel from the local storage.
632 /// May cause the removal of nodes too, if this was their last channel.
633 /// If not permanent, makes channels unavailable for routing.
634 pub fn close_channel_from_update(&mut self, short_channel_id: u64, is_permanent: bool) {
636 if let Some(chan) = self.channels.remove(&short_channel_id) {
637 Self::remove_channel_in_nodes(&mut self.nodes, &chan, short_channel_id);
640 if let Some(chan) = self.channels.get_mut(&short_channel_id) {
641 if let Some(one_to_two) = chan.one_to_two.as_mut() {
642 one_to_two.enabled = false;
644 if let Some(two_to_one) = chan.two_to_one.as_mut() {
645 two_to_one.enabled = false;
651 fn fail_node(&mut self, _node_id: &PublicKey, is_permanent: bool) {
653 // TODO: Wholly remove the node
655 // TODO: downgrade the node
659 /// For an already known (from announcement) channel, update info about one of the directions of a channel.
660 /// Announcement signatures are checked here only if Secp256k1 object is provided.
661 fn update_channel(&mut self, msg: &msgs::ChannelUpdate, secp_ctx: Option<&Secp256k1<secp256k1::VerifyOnly>>) -> Result<bool, LightningError> {
663 let chan_enabled = msg.contents.flags & (1 << 1) != (1 << 1);
664 let chan_was_enabled;
666 match self.channels.get_mut(&msg.contents.short_channel_id) {
667 None => return Err(LightningError{err: "Couldn't find channel for update".to_owned(), action: ErrorAction::IgnoreError}),
669 if let OptionalField::Present(htlc_maximum_msat) = msg.contents.htlc_maximum_msat {
670 if htlc_maximum_msat > MAX_VALUE_MSAT {
671 return Err(LightningError{err: "htlc_maximum_msat is larger than maximum possible msats".to_owned(), action: ErrorAction::IgnoreError});
674 if let Some(capacity_sats) = channel.capacity_sats {
675 // It's possible channel capacity is available now, although it wasn't available at announcement (so the field is None).
676 // Don't query UTXO set here to reduce DoS risks.
677 if htlc_maximum_msat > capacity_sats * 1000 {
678 return Err(LightningError{err: "htlc_maximum_msat is larger than channel capacity".to_owned(), action: ErrorAction::IgnoreError});
682 macro_rules! maybe_update_channel_info {
683 ( $target: expr, $src_node: expr) => {
684 if let Some(existing_chan_info) = $target.as_ref() {
685 if existing_chan_info.last_update >= msg.contents.timestamp {
686 return Err(LightningError{err: "Update older than last processed update".to_owned(), action: ErrorAction::IgnoreError});
688 chan_was_enabled = existing_chan_info.enabled;
690 chan_was_enabled = false;
693 let last_update_message = if msg.contents.excess_data.is_empty() {
699 let updated_channel_dir_info = DirectionalChannelInfo {
700 enabled: chan_enabled,
701 last_update: msg.contents.timestamp,
702 cltv_expiry_delta: msg.contents.cltv_expiry_delta,
703 htlc_minimum_msat: msg.contents.htlc_minimum_msat,
704 htlc_maximum_msat: if let OptionalField::Present(max_value) = msg.contents.htlc_maximum_msat { Some(max_value) } else { None },
706 base_msat: msg.contents.fee_base_msat,
707 proportional_millionths: msg.contents.fee_proportional_millionths,
711 $target = Some(updated_channel_dir_info);
715 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
716 if msg.contents.flags & 1 == 1 {
717 dest_node_id = channel.node_one.clone();
718 if let Some(sig_verifier) = secp_ctx {
719 secp_verify_sig!(sig_verifier, &msg_hash, &msg.signature, &channel.node_two);
721 maybe_update_channel_info!(channel.two_to_one, channel.node_two);
723 dest_node_id = channel.node_two.clone();
724 if let Some(sig_verifier) = secp_ctx {
725 secp_verify_sig!(sig_verifier, &msg_hash, &msg.signature, &channel.node_one);
727 maybe_update_channel_info!(channel.one_to_two, channel.node_one);
733 let node = self.nodes.get_mut(&dest_node_id).unwrap();
734 let mut base_msat = msg.contents.fee_base_msat;
735 let mut proportional_millionths = msg.contents.fee_proportional_millionths;
736 if let Some(fees) = node.lowest_inbound_channel_fees {
737 base_msat = cmp::min(base_msat, fees.base_msat);
738 proportional_millionths = cmp::min(proportional_millionths, fees.proportional_millionths);
740 node.lowest_inbound_channel_fees = Some(RoutingFees {
742 proportional_millionths
744 } else if chan_was_enabled {
745 let node = self.nodes.get_mut(&dest_node_id).unwrap();
746 let mut lowest_inbound_channel_fees = None;
748 for chan_id in node.channels.iter() {
749 let chan = self.channels.get(chan_id).unwrap();
751 if chan.node_one == dest_node_id {
752 chan_info_opt = chan.two_to_one.as_ref();
754 chan_info_opt = chan.one_to_two.as_ref();
756 if let Some(chan_info) = chan_info_opt {
757 if chan_info.enabled {
758 let fees = lowest_inbound_channel_fees.get_or_insert(RoutingFees {
759 base_msat: u32::max_value(), proportional_millionths: u32::max_value() });
760 fees.base_msat = cmp::min(fees.base_msat, chan_info.fees.base_msat);
761 fees.proportional_millionths = cmp::min(fees.proportional_millionths, chan_info.fees.proportional_millionths);
766 node.lowest_inbound_channel_fees = lowest_inbound_channel_fees;
769 Ok(msg.contents.excess_data.is_empty())
772 fn remove_channel_in_nodes(nodes: &mut BTreeMap<PublicKey, NodeInfo>, chan: &ChannelInfo, short_channel_id: u64) {
773 macro_rules! remove_from_node {
774 ($node_id: expr) => {
775 if let BtreeEntry::Occupied(mut entry) = nodes.entry($node_id) {
776 entry.get_mut().channels.retain(|chan_id| {
777 short_channel_id != *chan_id
779 if entry.get().channels.is_empty() {
780 entry.remove_entry();
783 panic!("Had channel that pointed to unknown node (ie inconsistent network map)!");
788 remove_from_node!(chan.node_one);
789 remove_from_node!(chan.node_two);
795 use chain::chaininterface;
796 use ln::features::{ChannelFeatures, NodeFeatures};
797 use routing::network_graph::{NetGraphMsgHandler, NetworkGraph};
798 use ln::msgs::{OptionalField, RoutingMessageHandler, UnsignedNodeAnnouncement, NodeAnnouncement,
799 UnsignedChannelAnnouncement, ChannelAnnouncement, UnsignedChannelUpdate, ChannelUpdate, HTLCFailChannelUpdate,
801 use util::test_utils;
802 use util::logger::Logger;
803 use util::ser::{Readable, Writeable};
805 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
806 use bitcoin::hashes::Hash;
807 use bitcoin::network::constants::Network;
808 use bitcoin::blockdata::constants::genesis_block;
809 use bitcoin::blockdata::script::Builder;
810 use bitcoin::blockdata::opcodes;
811 use bitcoin::util::hash::BitcoinHash;
815 use bitcoin::secp256k1::key::{PublicKey, SecretKey};
816 use bitcoin::secp256k1::{All, Secp256k1};
820 fn create_net_graph_msg_handler() -> (Secp256k1<All>, NetGraphMsgHandler<Arc<chaininterface::ChainWatchInterfaceUtil>, Arc<test_utils::TestLogger>>) {
821 let secp_ctx = Secp256k1::new();
822 let logger = Arc::new(test_utils::TestLogger::new());
823 let chain_monitor = Arc::new(chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet));
824 let net_graph_msg_handler = NetGraphMsgHandler::new(chain_monitor, Arc::clone(&logger));
825 (secp_ctx, net_graph_msg_handler)
829 fn request_full_sync_finite_times() {
830 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
831 let node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap()[..]).unwrap());
833 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
834 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
835 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
836 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
837 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
838 assert!(!net_graph_msg_handler.should_request_full_sync(&node_id));
842 fn handling_node_announcements() {
843 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
845 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
846 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
847 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
848 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
849 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
850 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
851 let zero_hash = Sha256dHash::hash(&[0; 32]);
852 let first_announcement_time = 500;
854 let mut unsigned_announcement = UnsignedNodeAnnouncement {
855 features: NodeFeatures::known(),
856 timestamp: first_announcement_time,
860 addresses: Vec::new(),
861 excess_address_data: Vec::new(),
862 excess_data: Vec::new(),
864 let mut msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
865 let valid_announcement = NodeAnnouncement {
866 signature: secp_ctx.sign(&msghash, node_1_privkey),
867 contents: unsigned_announcement.clone()
870 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
872 Err(e) => assert_eq!("No existing channels for node_announcement", e.err)
876 // Announce a channel to add a corresponding node.
877 let unsigned_announcement = UnsignedChannelAnnouncement {
878 features: ChannelFeatures::known(),
879 chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
883 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
884 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
885 excess_data: Vec::new(),
888 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
889 let valid_announcement = ChannelAnnouncement {
890 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
891 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
892 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
893 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
894 contents: unsigned_announcement.clone(),
896 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
897 Ok(res) => assert!(res),
902 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
903 Ok(res) => assert!(res),
907 let fake_msghash = hash_to_message!(&zero_hash);
908 match net_graph_msg_handler.handle_node_announcement(
910 signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
911 contents: unsigned_announcement.clone()
914 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
917 unsigned_announcement.timestamp += 1000;
918 unsigned_announcement.excess_data.push(1);
919 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
920 let announcement_with_data = NodeAnnouncement {
921 signature: secp_ctx.sign(&msghash, node_1_privkey),
922 contents: unsigned_announcement.clone()
924 // Return false because contains excess data.
925 match net_graph_msg_handler.handle_node_announcement(&announcement_with_data) {
926 Ok(res) => assert!(!res),
929 unsigned_announcement.excess_data = Vec::new();
931 // Even though previous announcement was not relayed further, we still accepted it,
932 // so we now won't accept announcements before the previous one.
933 unsigned_announcement.timestamp -= 10;
934 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
935 let outdated_announcement = NodeAnnouncement {
936 signature: secp_ctx.sign(&msghash, node_1_privkey),
937 contents: unsigned_announcement.clone()
939 match net_graph_msg_handler.handle_node_announcement(&outdated_announcement) {
941 Err(e) => assert_eq!(e.err, "Update older than last processed update")
946 fn handling_channel_announcements() {
947 let secp_ctx = Secp256k1::new();
948 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
949 let chain_monitor = Arc::new(test_utils::TestChainWatcher::new());
950 let net_graph_msg_handler = NetGraphMsgHandler::new(chain_monitor.clone(), Arc::clone(&logger));
953 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
954 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
955 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
956 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
957 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
958 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
960 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
961 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_1_btckey).serialize())
962 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_2_btckey).serialize())
963 .push_opcode(opcodes::all::OP_PUSHNUM_2)
964 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
967 let mut unsigned_announcement = UnsignedChannelAnnouncement {
968 features: ChannelFeatures::known(),
969 chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
973 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
974 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
975 excess_data: Vec::new(),
978 let mut msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
979 let valid_announcement = ChannelAnnouncement {
980 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
981 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
982 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
983 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
984 contents: unsigned_announcement.clone(),
987 // Test if the UTXO lookups were not supported
988 *chain_monitor.utxo_ret.lock().unwrap() = Err(chaininterface::ChainError::NotSupported);
990 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
991 Ok(res) => assert!(res),
996 let network = net_graph_msg_handler.network_graph.read().unwrap();
997 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1004 // If we receive announcement for the same channel (with UTXO lookups disabled),
1005 // drop new one on the floor, since we can't see any changes.
1006 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1008 Err(e) => assert_eq!(e.err, "Already have knowledge of channel")
1012 // Test if an associated transaction were not on-chain (or not confirmed).
1013 *chain_monitor.utxo_ret.lock().unwrap() = Err(chaininterface::ChainError::UnknownTx);
1014 unsigned_announcement.short_channel_id += 1;
1016 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1017 let valid_announcement = ChannelAnnouncement {
1018 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1019 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1020 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1021 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1022 contents: unsigned_announcement.clone(),
1025 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1027 Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1031 // Now test if the transaction is found in the UTXO set and the script is correct.
1032 unsigned_announcement.short_channel_id += 1;
1033 *chain_monitor.utxo_ret.lock().unwrap() = Ok((good_script.clone(), 0));
1035 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1036 let valid_announcement = ChannelAnnouncement {
1037 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1038 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1039 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1040 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1041 contents: unsigned_announcement.clone(),
1043 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1044 Ok(res) => assert!(res),
1049 let network = net_graph_msg_handler.network_graph.read().unwrap();
1050 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1056 // If we receive announcement for the same channel (but TX is not confirmed),
1057 // drop new one on the floor, since we can't see any changes.
1058 *chain_monitor.utxo_ret.lock().unwrap() = Err(chaininterface::ChainError::UnknownTx);
1059 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1061 Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1064 // But if it is confirmed, replace the channel
1065 *chain_monitor.utxo_ret.lock().unwrap() = Ok((good_script, 0));
1066 unsigned_announcement.features = ChannelFeatures::empty();
1067 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1068 let valid_announcement = ChannelAnnouncement {
1069 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1070 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1071 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1072 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1073 contents: unsigned_announcement.clone(),
1075 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1076 Ok(res) => assert!(res),
1080 let network = net_graph_msg_handler.network_graph.read().unwrap();
1081 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1082 Some(channel_entry) => {
1083 assert_eq!(channel_entry.features, ChannelFeatures::empty());
1089 // Don't relay valid channels with excess data
1090 unsigned_announcement.short_channel_id += 1;
1091 unsigned_announcement.excess_data.push(1);
1092 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1093 let valid_announcement = ChannelAnnouncement {
1094 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1095 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1096 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1097 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1098 contents: unsigned_announcement.clone(),
1100 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1101 Ok(res) => assert!(!res),
1105 unsigned_announcement.excess_data = Vec::new();
1106 let invalid_sig_announcement = ChannelAnnouncement {
1107 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1108 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1109 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1110 bitcoin_signature_2: secp_ctx.sign(&msghash, node_1_btckey),
1111 contents: unsigned_announcement.clone(),
1113 match net_graph_msg_handler.handle_channel_announcement(&invalid_sig_announcement) {
1115 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1118 unsigned_announcement.node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1119 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1120 let channel_to_itself_announcement = ChannelAnnouncement {
1121 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1122 node_signature_2: secp_ctx.sign(&msghash, node_1_privkey),
1123 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1124 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1125 contents: unsigned_announcement.clone(),
1127 match net_graph_msg_handler.handle_channel_announcement(&channel_to_itself_announcement) {
1129 Err(e) => assert_eq!(e.err, "Channel announcement node had a channel with itself")
1134 fn handling_channel_update() {
1135 let secp_ctx = Secp256k1::new();
1136 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
1137 let chain_monitor = Arc::new(test_utils::TestChainWatcher::new());
1138 let net_graph_msg_handler = NetGraphMsgHandler::new(chain_monitor.clone(), Arc::clone(&logger));
1140 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1141 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1142 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1143 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1144 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1145 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1147 let zero_hash = Sha256dHash::hash(&[0; 32]);
1148 let short_channel_id = 0;
1149 let chain_hash = genesis_block(Network::Testnet).header.bitcoin_hash();
1150 let amount_sats = 1000_000;
1153 // Announce a channel we will update
1154 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
1155 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_1_btckey).serialize())
1156 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_2_btckey).serialize())
1157 .push_opcode(opcodes::all::OP_PUSHNUM_2)
1158 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
1159 *chain_monitor.utxo_ret.lock().unwrap() = Ok((good_script.clone(), amount_sats));
1160 let unsigned_announcement = UnsignedChannelAnnouncement {
1161 features: ChannelFeatures::empty(),
1166 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1167 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1168 excess_data: Vec::new(),
1171 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1172 let valid_channel_announcement = ChannelAnnouncement {
1173 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1174 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1175 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1176 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1177 contents: unsigned_announcement.clone(),
1179 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1186 let mut unsigned_channel_update = UnsignedChannelUpdate {
1191 cltv_expiry_delta: 144,
1192 htlc_minimum_msat: 1000000,
1193 htlc_maximum_msat: OptionalField::Absent,
1194 fee_base_msat: 10000,
1195 fee_proportional_millionths: 20,
1196 excess_data: Vec::new()
1198 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1199 let valid_channel_update = ChannelUpdate {
1200 signature: secp_ctx.sign(&msghash, node_1_privkey),
1201 contents: unsigned_channel_update.clone()
1204 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1205 Ok(res) => assert!(res),
1210 let network = net_graph_msg_handler.network_graph.read().unwrap();
1211 match network.get_channels().get(&short_channel_id) {
1213 Some(channel_info) => {
1214 assert_eq!(channel_info.one_to_two.as_ref().unwrap().cltv_expiry_delta, 144);
1215 assert!(channel_info.two_to_one.is_none());
1220 unsigned_channel_update.timestamp += 100;
1221 unsigned_channel_update.excess_data.push(1);
1222 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1223 let valid_channel_update = ChannelUpdate {
1224 signature: secp_ctx.sign(&msghash, node_1_privkey),
1225 contents: unsigned_channel_update.clone()
1227 // Return false because contains excess data
1228 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1229 Ok(res) => assert!(!res),
1232 unsigned_channel_update.timestamp += 10;
1234 unsigned_channel_update.short_channel_id += 1;
1235 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1236 let valid_channel_update = ChannelUpdate {
1237 signature: secp_ctx.sign(&msghash, node_1_privkey),
1238 contents: unsigned_channel_update.clone()
1241 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1243 Err(e) => assert_eq!(e.err, "Couldn't find channel for update")
1245 unsigned_channel_update.short_channel_id = short_channel_id;
1247 unsigned_channel_update.htlc_maximum_msat = OptionalField::Present(MAX_VALUE_MSAT + 1);
1248 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1249 let valid_channel_update = ChannelUpdate {
1250 signature: secp_ctx.sign(&msghash, node_1_privkey),
1251 contents: unsigned_channel_update.clone()
1254 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1256 Err(e) => assert_eq!(e.err, "htlc_maximum_msat is larger than maximum possible msats")
1258 unsigned_channel_update.htlc_maximum_msat = OptionalField::Absent;
1260 unsigned_channel_update.htlc_maximum_msat = OptionalField::Present(amount_sats * 1000 + 1);
1261 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1262 let valid_channel_update = ChannelUpdate {
1263 signature: secp_ctx.sign(&msghash, node_1_privkey),
1264 contents: unsigned_channel_update.clone()
1267 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1269 Err(e) => assert_eq!(e.err, "htlc_maximum_msat is larger than channel capacity")
1271 unsigned_channel_update.htlc_maximum_msat = OptionalField::Absent;
1273 // Even though previous update was not relayed further, we still accepted it,
1274 // so we now won't accept update before the previous one.
1275 unsigned_channel_update.timestamp -= 10;
1276 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1277 let valid_channel_update = ChannelUpdate {
1278 signature: secp_ctx.sign(&msghash, node_1_privkey),
1279 contents: unsigned_channel_update.clone()
1282 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1284 Err(e) => assert_eq!(e.err, "Update older than last processed update")
1286 unsigned_channel_update.timestamp += 500;
1288 let fake_msghash = hash_to_message!(&zero_hash);
1289 let invalid_sig_channel_update = ChannelUpdate {
1290 signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
1291 contents: unsigned_channel_update.clone()
1294 match net_graph_msg_handler.handle_channel_update(&invalid_sig_channel_update) {
1296 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1302 fn handling_htlc_fail_channel_update() {
1303 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1304 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1305 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1306 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1307 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1308 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1309 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1311 let short_channel_id = 0;
1312 let chain_hash = genesis_block(Network::Testnet).header.bitcoin_hash();
1315 // There is no nodes in the table at the beginning.
1316 let network = net_graph_msg_handler.network_graph.read().unwrap();
1317 assert_eq!(network.get_nodes().len(), 0);
1321 // Announce a channel we will update
1322 let unsigned_announcement = UnsignedChannelAnnouncement {
1323 features: ChannelFeatures::empty(),
1328 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1329 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1330 excess_data: Vec::new(),
1333 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1334 let valid_channel_announcement = ChannelAnnouncement {
1335 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1336 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1337 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1338 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1339 contents: unsigned_announcement.clone(),
1341 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1346 let unsigned_channel_update = UnsignedChannelUpdate {
1351 cltv_expiry_delta: 144,
1352 htlc_minimum_msat: 1000000,
1353 htlc_maximum_msat: OptionalField::Absent,
1354 fee_base_msat: 10000,
1355 fee_proportional_millionths: 20,
1356 excess_data: Vec::new()
1358 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1359 let valid_channel_update = ChannelUpdate {
1360 signature: secp_ctx.sign(&msghash, node_1_privkey),
1361 contents: unsigned_channel_update.clone()
1364 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1365 Ok(res) => assert!(res),
1370 // Non-permanent closing just disables a channel
1372 let network = net_graph_msg_handler.network_graph.read().unwrap();
1373 match network.get_channels().get(&short_channel_id) {
1375 Some(channel_info) => {
1376 assert!(channel_info.one_to_two.is_some());
1381 let channel_close_msg = HTLCFailChannelUpdate::ChannelClosed {
1386 net_graph_msg_handler.handle_htlc_fail_channel_update(&channel_close_msg);
1388 // Non-permanent closing just disables a channel
1390 let network = net_graph_msg_handler.network_graph.read().unwrap();
1391 match network.get_channels().get(&short_channel_id) {
1393 Some(channel_info) => {
1394 assert!(!channel_info.one_to_two.as_ref().unwrap().enabled);
1399 let channel_close_msg = HTLCFailChannelUpdate::ChannelClosed {
1404 net_graph_msg_handler.handle_htlc_fail_channel_update(&channel_close_msg);
1406 // Permanent closing deletes a channel
1408 let network = net_graph_msg_handler.network_graph.read().unwrap();
1409 assert_eq!(network.get_channels().len(), 0);
1410 // Nodes are also deleted because there are no associated channels anymore
1411 assert_eq!(network.get_nodes().len(), 0);
1413 // TODO: Test HTLCFailChannelUpdate::NodeFailure, which is not implemented yet.
1417 fn getting_next_channel_announcements() {
1418 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1419 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1420 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1421 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1422 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1423 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1424 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1426 let short_channel_id = 1;
1427 let chain_hash = genesis_block(Network::Testnet).header.bitcoin_hash();
1429 // Channels were not announced yet.
1430 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(0, 1);
1431 assert_eq!(channels_with_announcements.len(), 0);
1434 // Announce a channel we will update
1435 let unsigned_announcement = UnsignedChannelAnnouncement {
1436 features: ChannelFeatures::empty(),
1441 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1442 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1443 excess_data: Vec::new(),
1446 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1447 let valid_channel_announcement = ChannelAnnouncement {
1448 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1449 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1450 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1451 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1452 contents: unsigned_announcement.clone(),
1454 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1460 // Contains initial channel announcement now.
1461 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1462 assert_eq!(channels_with_announcements.len(), 1);
1463 if let Some(channel_announcements) = channels_with_announcements.first() {
1464 let &(_, ref update_1, ref update_2) = channel_announcements;
1465 assert_eq!(update_1, &None);
1466 assert_eq!(update_2, &None);
1473 // Valid channel update
1474 let unsigned_channel_update = UnsignedChannelUpdate {
1479 cltv_expiry_delta: 144,
1480 htlc_minimum_msat: 1000000,
1481 htlc_maximum_msat: OptionalField::Absent,
1482 fee_base_msat: 10000,
1483 fee_proportional_millionths: 20,
1484 excess_data: Vec::new()
1486 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1487 let valid_channel_update = ChannelUpdate {
1488 signature: secp_ctx.sign(&msghash, node_1_privkey),
1489 contents: unsigned_channel_update.clone()
1491 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1497 // Now contains an initial announcement and an update.
1498 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1499 assert_eq!(channels_with_announcements.len(), 1);
1500 if let Some(channel_announcements) = channels_with_announcements.first() {
1501 let &(_, ref update_1, ref update_2) = channel_announcements;
1502 assert_ne!(update_1, &None);
1503 assert_eq!(update_2, &None);
1510 // Channel update with excess data.
1511 let unsigned_channel_update = UnsignedChannelUpdate {
1516 cltv_expiry_delta: 144,
1517 htlc_minimum_msat: 1000000,
1518 htlc_maximum_msat: OptionalField::Absent,
1519 fee_base_msat: 10000,
1520 fee_proportional_millionths: 20,
1521 excess_data: [1; 3].to_vec()
1523 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1524 let valid_channel_update = ChannelUpdate {
1525 signature: secp_ctx.sign(&msghash, node_1_privkey),
1526 contents: unsigned_channel_update.clone()
1528 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1534 // Test that announcements with excess data won't be returned
1535 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1536 assert_eq!(channels_with_announcements.len(), 1);
1537 if let Some(channel_announcements) = channels_with_announcements.first() {
1538 let &(_, ref update_1, ref update_2) = channel_announcements;
1539 assert_eq!(update_1, &None);
1540 assert_eq!(update_2, &None);
1545 // Further starting point have no channels after it
1546 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id + 1000, 1);
1547 assert_eq!(channels_with_announcements.len(), 0);
1551 fn getting_next_node_announcements() {
1552 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1553 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1554 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1555 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1556 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1557 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1558 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1560 let short_channel_id = 1;
1561 let chain_hash = genesis_block(Network::Testnet).header.bitcoin_hash();
1564 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 10);
1565 assert_eq!(next_announcements.len(), 0);
1568 // Announce a channel to add 2 nodes
1569 let unsigned_announcement = UnsignedChannelAnnouncement {
1570 features: ChannelFeatures::empty(),
1575 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1576 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1577 excess_data: Vec::new(),
1580 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1581 let valid_channel_announcement = ChannelAnnouncement {
1582 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1583 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1584 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1585 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1586 contents: unsigned_announcement.clone(),
1588 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1595 // Nodes were never announced
1596 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
1597 assert_eq!(next_announcements.len(), 0);
1600 let mut unsigned_announcement = UnsignedNodeAnnouncement {
1601 features: NodeFeatures::known(),
1606 addresses: Vec::new(),
1607 excess_address_data: Vec::new(),
1608 excess_data: Vec::new(),
1610 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1611 let valid_announcement = NodeAnnouncement {
1612 signature: secp_ctx.sign(&msghash, node_1_privkey),
1613 contents: unsigned_announcement.clone()
1615 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1620 unsigned_announcement.node_id = node_id_2;
1621 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1622 let valid_announcement = NodeAnnouncement {
1623 signature: secp_ctx.sign(&msghash, node_2_privkey),
1624 contents: unsigned_announcement.clone()
1627 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1633 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
1634 assert_eq!(next_announcements.len(), 2);
1636 // Skip the first node.
1637 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
1638 assert_eq!(next_announcements.len(), 1);
1641 // Later announcement which should not be relayed (excess data) prevent us from sharing a node
1642 let unsigned_announcement = UnsignedNodeAnnouncement {
1643 features: NodeFeatures::known(),
1648 addresses: Vec::new(),
1649 excess_address_data: Vec::new(),
1650 excess_data: [1; 3].to_vec(),
1652 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1653 let valid_announcement = NodeAnnouncement {
1654 signature: secp_ctx.sign(&msghash, node_2_privkey),
1655 contents: unsigned_announcement.clone()
1657 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1658 Ok(res) => assert!(!res),
1663 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
1664 assert_eq!(next_announcements.len(), 0);
1668 fn network_graph_serialization() {
1669 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1671 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1672 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1673 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1674 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1676 // Announce a channel to add a corresponding node.
1677 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1678 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1679 let unsigned_announcement = UnsignedChannelAnnouncement {
1680 features: ChannelFeatures::known(),
1681 chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
1682 short_channel_id: 0,
1685 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1686 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1687 excess_data: Vec::new(),
1690 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1691 let valid_announcement = ChannelAnnouncement {
1692 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1693 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1694 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1695 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1696 contents: unsigned_announcement.clone(),
1698 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1699 Ok(res) => assert!(res),
1704 let node_id = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1705 let unsigned_announcement = UnsignedNodeAnnouncement {
1706 features: NodeFeatures::known(),
1711 addresses: Vec::new(),
1712 excess_address_data: Vec::new(),
1713 excess_data: Vec::new(),
1715 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1716 let valid_announcement = NodeAnnouncement {
1717 signature: secp_ctx.sign(&msghash, node_1_privkey),
1718 contents: unsigned_announcement.clone()
1721 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1726 let network = net_graph_msg_handler.network_graph.write().unwrap();
1727 let mut w = test_utils::TestVecWriter(Vec::new());
1728 assert!(!network.get_nodes().is_empty());
1729 assert!(!network.get_channels().is_empty());
1730 network.write(&mut w).unwrap();
1731 assert!(<NetworkGraph>::read(&mut ::std::io::Cursor::new(&w.0)).unwrap() == *network);