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::transaction::TxOut;
11 use bitcoin::blockdata::opcodes;
15 use ln::features::{ChannelFeatures, NodeFeatures};
16 use ln::msgs::{DecodeError, ErrorAction, LightningError, RoutingMessageHandler, NetAddress, OptionalField, MAX_VALUE_MSAT};
18 use util::ser::{Writeable, Readable, Writer};
19 use util::logger::Logger;
22 use std::sync::RwLock;
23 use std::sync::atomic::{AtomicUsize, Ordering};
24 use std::collections::BTreeMap;
25 use std::collections::btree_map::Entry as BtreeEntry;
27 use bitcoin::hashes::hex::ToHex;
29 /// Receives and validates network updates from peers,
30 /// stores authentic and relevant data as a network graph.
31 /// This network graph is then used for routing payments.
32 /// Provides interface to help with initial routing sync by
33 /// serving historical announcements.
34 pub struct NetGraphMsgHandler<C: Deref, L: Deref> where C::Target: chain::Access, L::Target: Logger {
35 secp_ctx: Secp256k1<secp256k1::VerifyOnly>,
36 /// Representation of the payment channel network
37 pub network_graph: RwLock<NetworkGraph>,
38 chain_access: Option<C>,
39 full_syncs_requested: AtomicUsize,
43 impl<C: Deref, L: Deref> NetGraphMsgHandler<C, L> where C::Target: chain::Access, L::Target: Logger {
44 /// Creates a new tracker of the actual state of the network of channels and nodes,
45 /// assuming a fresh network graph.
46 /// Chain monitor is used to make sure announced channels exist on-chain,
47 /// channel data is correct, and that the announcement is signed with
48 /// channel owners' keys.
49 pub fn new(chain_access: Option<C>, logger: L) -> Self {
51 secp_ctx: Secp256k1::verification_only(),
52 network_graph: RwLock::new(NetworkGraph {
53 channels: BTreeMap::new(),
54 nodes: BTreeMap::new(),
56 full_syncs_requested: AtomicUsize::new(0),
62 /// Creates a new tracker of the actual state of the network of channels and nodes,
63 /// assuming an existing Network Graph.
64 pub fn from_net_graph(chain_access: Option<C>, logger: L, network_graph: NetworkGraph) -> Self {
66 secp_ctx: Secp256k1::verification_only(),
67 network_graph: RwLock::new(network_graph),
68 full_syncs_requested: AtomicUsize::new(0),
76 macro_rules! secp_verify_sig {
77 ( $secp_ctx: expr, $msg: expr, $sig: expr, $pubkey: expr ) => {
78 match $secp_ctx.verify($msg, $sig, $pubkey) {
80 Err(_) => return Err(LightningError{err: "Invalid signature from remote node".to_owned(), action: ErrorAction::IgnoreError}),
85 impl<C: Deref + Sync + Send, L: Deref + Sync + Send> RoutingMessageHandler for NetGraphMsgHandler<C, L> where C::Target: chain::Access, L::Target: Logger {
86 fn handle_node_announcement(&self, msg: &msgs::NodeAnnouncement) -> Result<bool, LightningError> {
87 self.network_graph.write().unwrap().update_node_from_announcement(msg, Some(&self.secp_ctx))
90 fn handle_channel_announcement(&self, msg: &msgs::ChannelAnnouncement) -> Result<bool, LightningError> {
91 if msg.contents.node_id_1 == msg.contents.node_id_2 || msg.contents.bitcoin_key_1 == msg.contents.bitcoin_key_2 {
92 return Err(LightningError{err: "Channel announcement node had a channel with itself".to_owned(), action: ErrorAction::IgnoreError});
95 let utxo_value = match &self.chain_access {
97 // Tentatively accept, potentially exposing us to DoS attacks
100 &Some(ref chain_access) => {
101 match chain_access.get_utxo(&msg.contents.chain_hash, msg.contents.short_channel_id) {
102 Ok(TxOut { value, script_pubkey }) => {
103 let expected_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
104 .push_slice(&msg.contents.bitcoin_key_1.serialize())
105 .push_slice(&msg.contents.bitcoin_key_2.serialize())
106 .push_opcode(opcodes::all::OP_PUSHNUM_2)
107 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
108 if script_pubkey != expected_script {
109 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});
111 //TODO: Check if value is worth storing, use it to inform routing, and compare it
112 //to the new HTLC max field in channel_update
115 Err(chain::AccessError::UnknownChain) => {
116 return Err(LightningError{err: format!("Channel announced on an unknown chain ({})", msg.contents.chain_hash.encode().to_hex()), action: ErrorAction::IgnoreError});
118 Err(chain::AccessError::UnknownTx) => {
119 return Err(LightningError{err: "Channel announced without corresponding UTXO entry".to_owned(), action: ErrorAction::IgnoreError});
121 // format!("Channel announced on an unknown chain ({})", msg.contents.chain_hash.encode().to_hex())
125 let result = self.network_graph.write().unwrap().update_channel_from_announcement(msg, utxo_value, Some(&self.secp_ctx));
126 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 { "" });
130 fn handle_htlc_fail_channel_update(&self, update: &msgs::HTLCFailChannelUpdate) {
132 &msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg } => {
133 let _ = self.network_graph.write().unwrap().update_channel(msg, Some(&self.secp_ctx));
135 &msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id, is_permanent } => {
136 self.network_graph.write().unwrap().close_channel_from_update(short_channel_id, is_permanent);
138 &msgs::HTLCFailChannelUpdate::NodeFailure { ref node_id, is_permanent } => {
139 self.network_graph.write().unwrap().fail_node(node_id, is_permanent);
144 fn handle_channel_update(&self, msg: &msgs::ChannelUpdate) -> Result<bool, LightningError> {
145 self.network_graph.write().unwrap().update_channel(msg, Some(&self.secp_ctx))
148 fn get_next_channel_announcements(&self, starting_point: u64, batch_amount: u8) -> Vec<(msgs::ChannelAnnouncement, Option<msgs::ChannelUpdate>, Option<msgs::ChannelUpdate>)> {
149 let network_graph = self.network_graph.read().unwrap();
150 let mut result = Vec::with_capacity(batch_amount as usize);
151 let mut iter = network_graph.get_channels().range(starting_point..);
152 while result.len() < batch_amount as usize {
153 if let Some((_, ref chan)) = iter.next() {
154 if chan.announcement_message.is_some() {
155 let chan_announcement = chan.announcement_message.clone().unwrap();
156 let mut one_to_two_announcement: Option<msgs::ChannelUpdate> = None;
157 let mut two_to_one_announcement: Option<msgs::ChannelUpdate> = None;
158 if let Some(one_to_two) = chan.one_to_two.as_ref() {
159 one_to_two_announcement = one_to_two.last_update_message.clone();
161 if let Some(two_to_one) = chan.two_to_one.as_ref() {
162 two_to_one_announcement = two_to_one.last_update_message.clone();
164 result.push((chan_announcement, one_to_two_announcement, two_to_one_announcement));
166 // TODO: We may end up sending un-announced channel_updates if we are sending
167 // initial sync data while receiving announce/updates for this channel.
176 fn get_next_node_announcements(&self, starting_point: Option<&PublicKey>, batch_amount: u8) -> Vec<msgs::NodeAnnouncement> {
177 let network_graph = self.network_graph.read().unwrap();
178 let mut result = Vec::with_capacity(batch_amount as usize);
179 let mut iter = if let Some(pubkey) = starting_point {
180 let mut iter = network_graph.get_nodes().range((*pubkey)..);
184 network_graph.get_nodes().range(..)
186 while result.len() < batch_amount as usize {
187 if let Some((_, ref node)) = iter.next() {
188 if let Some(node_info) = node.announcement_info.as_ref() {
189 if node_info.announcement_message.is_some() {
190 result.push(node_info.announcement_message.clone().unwrap());
200 fn should_request_full_sync(&self, _node_id: &PublicKey) -> bool {
201 //TODO: Determine whether to request a full sync based on the network map.
202 const FULL_SYNCS_TO_REQUEST: usize = 5;
203 if self.full_syncs_requested.load(Ordering::Acquire) < FULL_SYNCS_TO_REQUEST {
204 self.full_syncs_requested.fetch_add(1, Ordering::AcqRel);
212 #[derive(PartialEq, Debug)]
213 /// Details about one direction of a channel. Received
214 /// within a channel update.
215 pub struct DirectionalChannelInfo {
216 /// When the last update to the channel direction was issued.
217 /// Value is opaque, as set in the announcement.
218 pub last_update: u32,
219 /// Whether the channel can be currently used for payments (in this one direction).
221 /// The difference in CLTV values that you must have when routing through this channel.
222 pub cltv_expiry_delta: u16,
223 /// The minimum value, which must be relayed to the next hop via the channel
224 pub htlc_minimum_msat: u64,
225 /// The maximum value which may be relayed to the next hop via the channel.
226 pub htlc_maximum_msat: Option<u64>,
227 /// Fees charged when the channel is used for routing
228 pub fees: RoutingFees,
229 /// Most recent update for the channel received from the network
230 /// Mostly redundant with the data we store in fields explicitly.
231 /// Everything else is useful only for sending out for initial routing sync.
232 /// Not stored if contains excess data to prevent DoS.
233 pub last_update_message: Option<msgs::ChannelUpdate>,
236 impl fmt::Display for DirectionalChannelInfo {
237 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
238 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)?;
243 impl_writeable!(DirectionalChannelInfo, 0, {
254 /// Details about a channel (both directions).
255 /// Received within a channel announcement.
256 pub struct ChannelInfo {
257 /// Protocol features of a channel communicated during its announcement
258 pub features: ChannelFeatures,
259 /// Source node of the first direction of a channel
260 pub node_one: PublicKey,
261 /// Details about the first direction of a channel
262 pub one_to_two: Option<DirectionalChannelInfo>,
263 /// Source node of the second direction of a channel
264 pub node_two: PublicKey,
265 /// Details about the second direction of a channel
266 pub two_to_one: Option<DirectionalChannelInfo>,
267 /// The channel capacity as seen on-chain, if chain lookup is available.
268 pub capacity_sats: Option<u64>,
269 /// An initial announcement of the channel
270 /// Mostly redundant with the data we store in fields explicitly.
271 /// Everything else is useful only for sending out for initial routing sync.
272 /// Not stored if contains excess data to prevent DoS.
273 pub announcement_message: Option<msgs::ChannelAnnouncement>,
276 impl fmt::Display for ChannelInfo {
277 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
278 write!(f, "features: {}, node_one: {}, one_to_two: {:?}, node_two: {}, two_to_one: {:?}",
279 log_bytes!(self.features.encode()), log_pubkey!(self.node_one), self.one_to_two, log_pubkey!(self.node_two), self.two_to_one)?;
284 impl_writeable!(ChannelInfo, 0, {
295 /// Fees for routing via a given channel or a node
296 #[derive(Eq, PartialEq, Copy, Clone, Debug)]
297 pub struct RoutingFees {
298 /// Flat routing fee in satoshis
300 /// Liquidity-based routing fee in millionths of a routed amount.
301 /// In other words, 10000 is 1%.
302 pub proportional_millionths: u32,
305 impl Readable for RoutingFees{
306 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<RoutingFees, DecodeError> {
307 let base_msat: u32 = Readable::read(reader)?;
308 let proportional_millionths: u32 = Readable::read(reader)?;
311 proportional_millionths,
316 impl Writeable for RoutingFees {
317 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
318 self.base_msat.write(writer)?;
319 self.proportional_millionths.write(writer)?;
324 #[derive(PartialEq, Debug)]
325 /// Information received in the latest node_announcement from this node.
326 pub struct NodeAnnouncementInfo {
327 /// Protocol features the node announced support for
328 pub features: NodeFeatures,
329 /// When the last known update to the node state was issued.
330 /// Value is opaque, as set in the announcement.
331 pub last_update: u32,
332 /// Color assigned to the node
334 /// Moniker assigned to the node.
335 /// May be invalid or malicious (eg control chars),
336 /// should not be exposed to the user.
338 /// Internet-level addresses via which one can connect to the node
339 pub addresses: Vec<NetAddress>,
340 /// An initial announcement of the node
341 /// Mostly redundant with the data we store in fields explicitly.
342 /// Everything else is useful only for sending out for initial routing sync.
343 /// Not stored if contains excess data to prevent DoS.
344 pub announcement_message: Option<msgs::NodeAnnouncement>
347 impl Writeable for NodeAnnouncementInfo {
348 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
349 self.features.write(writer)?;
350 self.last_update.write(writer)?;
351 self.rgb.write(writer)?;
352 self.alias.write(writer)?;
353 (self.addresses.len() as u64).write(writer)?;
354 for ref addr in &self.addresses {
357 self.announcement_message.write(writer)?;
362 impl Readable for NodeAnnouncementInfo {
363 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NodeAnnouncementInfo, DecodeError> {
364 let features = Readable::read(reader)?;
365 let last_update = Readable::read(reader)?;
366 let rgb = Readable::read(reader)?;
367 let alias = Readable::read(reader)?;
368 let addresses_count: u64 = Readable::read(reader)?;
369 let mut addresses = Vec::with_capacity(cmp::min(addresses_count, MAX_ALLOC_SIZE / 40) as usize);
370 for _ in 0..addresses_count {
371 match Readable::read(reader) {
372 Ok(Ok(addr)) => { addresses.push(addr); },
373 Ok(Err(_)) => return Err(DecodeError::InvalidValue),
374 Err(DecodeError::ShortRead) => return Err(DecodeError::BadLengthDescriptor),
378 let announcement_message = Readable::read(reader)?;
379 Ok(NodeAnnouncementInfo {
391 /// Details about a node in the network, known from the network announcement.
392 pub struct NodeInfo {
393 /// All valid channels a node has announced
394 pub channels: Vec<u64>,
395 /// Lowest fees enabling routing via any of the enabled, known channels to a node.
396 /// The two fields (flat and proportional fee) are independent,
397 /// meaning they don't have to refer to the same channel.
398 pub lowest_inbound_channel_fees: Option<RoutingFees>,
399 /// More information about a node from node_announcement.
400 /// Optional because we store a Node entry after learning about it from
401 /// a channel announcement, but before receiving a node announcement.
402 pub announcement_info: Option<NodeAnnouncementInfo>
405 impl fmt::Display for NodeInfo {
406 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
407 write!(f, "lowest_inbound_channel_fees: {:?}, channels: {:?}, announcement_info: {:?}",
408 self.lowest_inbound_channel_fees, &self.channels[..], self.announcement_info)?;
413 impl Writeable for NodeInfo {
414 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
415 (self.channels.len() as u64).write(writer)?;
416 for ref chan in self.channels.iter() {
419 self.lowest_inbound_channel_fees.write(writer)?;
420 self.announcement_info.write(writer)?;
425 const MAX_ALLOC_SIZE: u64 = 64*1024;
427 impl Readable for NodeInfo {
428 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NodeInfo, DecodeError> {
429 let channels_count: u64 = Readable::read(reader)?;
430 let mut channels = Vec::with_capacity(cmp::min(channels_count, MAX_ALLOC_SIZE / 8) as usize);
431 for _ in 0..channels_count {
432 channels.push(Readable::read(reader)?);
434 let lowest_inbound_channel_fees = Readable::read(reader)?;
435 let announcement_info = Readable::read(reader)?;
438 lowest_inbound_channel_fees,
444 /// Represents the network as nodes and channels between them
446 pub struct NetworkGraph {
447 channels: BTreeMap<u64, ChannelInfo>,
448 nodes: BTreeMap<PublicKey, NodeInfo>,
451 impl Writeable for NetworkGraph {
452 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
453 (self.channels.len() as u64).write(writer)?;
454 for (ref chan_id, ref chan_info) in self.channels.iter() {
455 (*chan_id).write(writer)?;
456 chan_info.write(writer)?;
458 (self.nodes.len() as u64).write(writer)?;
459 for (ref node_id, ref node_info) in self.nodes.iter() {
460 node_id.write(writer)?;
461 node_info.write(writer)?;
467 impl Readable for NetworkGraph {
468 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NetworkGraph, DecodeError> {
469 let channels_count: u64 = Readable::read(reader)?;
470 let mut channels = BTreeMap::new();
471 for _ in 0..channels_count {
472 let chan_id: u64 = Readable::read(reader)?;
473 let chan_info = Readable::read(reader)?;
474 channels.insert(chan_id, chan_info);
476 let nodes_count: u64 = Readable::read(reader)?;
477 let mut nodes = BTreeMap::new();
478 for _ in 0..nodes_count {
479 let node_id = Readable::read(reader)?;
480 let node_info = Readable::read(reader)?;
481 nodes.insert(node_id, node_info);
490 impl fmt::Display for NetworkGraph {
491 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
492 write!(f, "Network map\n[Channels]\n")?;
493 for (key, val) in self.channels.iter() {
494 write!(f, " {}: {}\n", key, val)?;
496 write!(f, "[Nodes]\n")?;
497 for (key, val) in self.nodes.iter() {
498 write!(f, " {}: {}\n", log_pubkey!(key), val)?;
505 /// Returns all known valid channels' short ids along with announced channel info.
506 pub fn get_channels<'a>(&'a self) -> &'a BTreeMap<u64, ChannelInfo> { &self.channels }
507 /// Returns all known nodes' public keys along with announced node info.
508 pub fn get_nodes<'a>(&'a self) -> &'a BTreeMap<PublicKey, NodeInfo> { &self.nodes }
510 /// Get network addresses by node id.
511 /// Returns None if the requested node is completely unknown,
512 /// or if node announcement for the node was never received.
513 pub fn get_addresses<'a>(&'a self, pubkey: &PublicKey) -> Option<&'a Vec<NetAddress>> {
514 if let Some(node) = self.nodes.get(pubkey) {
515 if let Some(node_info) = node.announcement_info.as_ref() {
516 return Some(&node_info.addresses)
522 /// Creates a new, empty, network graph.
523 pub fn new() -> NetworkGraph {
525 channels: BTreeMap::new(),
526 nodes: BTreeMap::new(),
530 /// For an already known node (from channel announcements), update its stored properties from a given node announcement
531 /// Announcement signatures are checked here only if Secp256k1 object is provided.
532 fn update_node_from_announcement(&mut self, msg: &msgs::NodeAnnouncement, secp_ctx: Option<&Secp256k1<secp256k1::VerifyOnly>>) -> Result<bool, LightningError> {
533 if let Some(sig_verifier) = secp_ctx {
534 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
535 secp_verify_sig!(sig_verifier, &msg_hash, &msg.signature, &msg.contents.node_id);
538 match self.nodes.get_mut(&msg.contents.node_id) {
539 None => Err(LightningError{err: "No existing channels for node_announcement".to_owned(), action: ErrorAction::IgnoreError}),
541 if let Some(node_info) = node.announcement_info.as_ref() {
542 if node_info.last_update >= msg.contents.timestamp {
543 return Err(LightningError{err: "Update older than last processed update".to_owned(), action: ErrorAction::IgnoreError});
547 let should_relay = msg.contents.excess_data.is_empty() && msg.contents.excess_address_data.is_empty();
548 node.announcement_info = Some(NodeAnnouncementInfo {
549 features: msg.contents.features.clone(),
550 last_update: msg.contents.timestamp,
551 rgb: msg.contents.rgb,
552 alias: msg.contents.alias,
553 addresses: msg.contents.addresses.clone(),
554 announcement_message: if should_relay { Some(msg.clone()) } else { None },
562 /// For a new or already known (from previous announcement) channel, store or update channel info.
563 /// Also store nodes (if not stored yet) the channel is between, and make node aware of this channel.
564 /// Checking utxo on-chain is useful if we receive an update for already known channel id,
565 /// which is probably result of a reorg. In that case, we update channel info only if the
566 /// utxo was checked, otherwise stick to the existing update, to prevent DoS risks.
567 /// Announcement signatures are checked here only if Secp256k1 object is provided.
568 fn update_channel_from_announcement(&mut self, msg: &msgs::ChannelAnnouncement, utxo_value: Option<u64>, secp_ctx: Option<&Secp256k1<secp256k1::VerifyOnly>>) -> Result<bool, LightningError> {
569 if let Some(sig_verifier) = secp_ctx {
570 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
571 secp_verify_sig!(sig_verifier, &msg_hash, &msg.node_signature_1, &msg.contents.node_id_1);
572 secp_verify_sig!(sig_verifier, &msg_hash, &msg.node_signature_2, &msg.contents.node_id_2);
573 secp_verify_sig!(sig_verifier, &msg_hash, &msg.bitcoin_signature_1, &msg.contents.bitcoin_key_1);
574 secp_verify_sig!(sig_verifier, &msg_hash, &msg.bitcoin_signature_2, &msg.contents.bitcoin_key_2);
577 let should_relay = msg.contents.excess_data.is_empty();
579 let chan_info = ChannelInfo {
580 features: msg.contents.features.clone(),
581 node_one: msg.contents.node_id_1.clone(),
583 node_two: msg.contents.node_id_2.clone(),
585 capacity_sats: utxo_value,
586 announcement_message: if should_relay { Some(msg.clone()) } else { None },
589 match self.channels.entry(msg.contents.short_channel_id) {
590 BtreeEntry::Occupied(mut entry) => {
591 //TODO: because asking the blockchain if short_channel_id is valid is only optional
592 //in the blockchain API, we need to handle it smartly here, though it's unclear
594 if utxo_value.is_some() {
595 // Either our UTXO provider is busted, there was a reorg, or the UTXO provider
596 // only sometimes returns results. In any case remove the previous entry. Note
597 // that the spec expects us to "blacklist" the node_ids involved, but we can't
599 // a) we don't *require* a UTXO provider that always returns results.
600 // b) we don't track UTXOs of channels we know about and remove them if they
602 // c) it's unclear how to do so without exposing ourselves to massive DoS risk.
603 Self::remove_channel_in_nodes(&mut self.nodes, &entry.get(), msg.contents.short_channel_id);
604 *entry.get_mut() = chan_info;
606 return Err(LightningError{err: "Already have knowledge of channel".to_owned(), action: ErrorAction::IgnoreError})
609 BtreeEntry::Vacant(entry) => {
610 entry.insert(chan_info);
614 macro_rules! add_channel_to_node {
615 ( $node_id: expr ) => {
616 match self.nodes.entry($node_id) {
617 BtreeEntry::Occupied(node_entry) => {
618 node_entry.into_mut().channels.push(msg.contents.short_channel_id);
620 BtreeEntry::Vacant(node_entry) => {
621 node_entry.insert(NodeInfo {
622 channels: vec!(msg.contents.short_channel_id),
623 lowest_inbound_channel_fees: None,
624 announcement_info: None,
631 add_channel_to_node!(msg.contents.node_id_1);
632 add_channel_to_node!(msg.contents.node_id_2);
637 /// Close a channel if a corresponding HTLC fail was sent.
638 /// If permanent, removes a channel from the local storage.
639 /// May cause the removal of nodes too, if this was their last channel.
640 /// If not permanent, makes channels unavailable for routing.
641 pub fn close_channel_from_update(&mut self, short_channel_id: u64, is_permanent: bool) {
643 if let Some(chan) = self.channels.remove(&short_channel_id) {
644 Self::remove_channel_in_nodes(&mut self.nodes, &chan, short_channel_id);
647 if let Some(chan) = self.channels.get_mut(&short_channel_id) {
648 if let Some(one_to_two) = chan.one_to_two.as_mut() {
649 one_to_two.enabled = false;
651 if let Some(two_to_one) = chan.two_to_one.as_mut() {
652 two_to_one.enabled = false;
658 fn fail_node(&mut self, _node_id: &PublicKey, is_permanent: bool) {
660 // TODO: Wholly remove the node
662 // TODO: downgrade the node
666 /// For an already known (from announcement) channel, update info about one of the directions of a channel.
667 /// Announcement signatures are checked here only if Secp256k1 object is provided.
668 fn update_channel(&mut self, msg: &msgs::ChannelUpdate, secp_ctx: Option<&Secp256k1<secp256k1::VerifyOnly>>) -> Result<bool, LightningError> {
670 let chan_enabled = msg.contents.flags & (1 << 1) != (1 << 1);
671 let chan_was_enabled;
673 match self.channels.get_mut(&msg.contents.short_channel_id) {
674 None => return Err(LightningError{err: "Couldn't find channel for update".to_owned(), action: ErrorAction::IgnoreError}),
676 if let OptionalField::Present(htlc_maximum_msat) = msg.contents.htlc_maximum_msat {
677 if htlc_maximum_msat > MAX_VALUE_MSAT {
678 return Err(LightningError{err: "htlc_maximum_msat is larger than maximum possible msats".to_owned(), action: ErrorAction::IgnoreError});
681 if let Some(capacity_sats) = channel.capacity_sats {
682 // It's possible channel capacity is available now, although it wasn't available at announcement (so the field is None).
683 // Don't query UTXO set here to reduce DoS risks.
684 if htlc_maximum_msat > capacity_sats * 1000 {
685 return Err(LightningError{err: "htlc_maximum_msat is larger than channel capacity".to_owned(), action: ErrorAction::IgnoreError});
689 macro_rules! maybe_update_channel_info {
690 ( $target: expr, $src_node: expr) => {
691 if let Some(existing_chan_info) = $target.as_ref() {
692 if existing_chan_info.last_update >= msg.contents.timestamp {
693 return Err(LightningError{err: "Update older than last processed update".to_owned(), action: ErrorAction::IgnoreError});
695 chan_was_enabled = existing_chan_info.enabled;
697 chan_was_enabled = false;
700 let last_update_message = if msg.contents.excess_data.is_empty() {
706 let updated_channel_dir_info = DirectionalChannelInfo {
707 enabled: chan_enabled,
708 last_update: msg.contents.timestamp,
709 cltv_expiry_delta: msg.contents.cltv_expiry_delta,
710 htlc_minimum_msat: msg.contents.htlc_minimum_msat,
711 htlc_maximum_msat: if let OptionalField::Present(max_value) = msg.contents.htlc_maximum_msat { Some(max_value) } else { None },
713 base_msat: msg.contents.fee_base_msat,
714 proportional_millionths: msg.contents.fee_proportional_millionths,
718 $target = Some(updated_channel_dir_info);
722 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
723 if msg.contents.flags & 1 == 1 {
724 dest_node_id = channel.node_one.clone();
725 if let Some(sig_verifier) = secp_ctx {
726 secp_verify_sig!(sig_verifier, &msg_hash, &msg.signature, &channel.node_two);
728 maybe_update_channel_info!(channel.two_to_one, channel.node_two);
730 dest_node_id = channel.node_two.clone();
731 if let Some(sig_verifier) = secp_ctx {
732 secp_verify_sig!(sig_verifier, &msg_hash, &msg.signature, &channel.node_one);
734 maybe_update_channel_info!(channel.one_to_two, channel.node_one);
740 let node = self.nodes.get_mut(&dest_node_id).unwrap();
741 let mut base_msat = msg.contents.fee_base_msat;
742 let mut proportional_millionths = msg.contents.fee_proportional_millionths;
743 if let Some(fees) = node.lowest_inbound_channel_fees {
744 base_msat = cmp::min(base_msat, fees.base_msat);
745 proportional_millionths = cmp::min(proportional_millionths, fees.proportional_millionths);
747 node.lowest_inbound_channel_fees = Some(RoutingFees {
749 proportional_millionths
751 } else if chan_was_enabled {
752 let node = self.nodes.get_mut(&dest_node_id).unwrap();
753 let mut lowest_inbound_channel_fees = None;
755 for chan_id in node.channels.iter() {
756 let chan = self.channels.get(chan_id).unwrap();
758 if chan.node_one == dest_node_id {
759 chan_info_opt = chan.two_to_one.as_ref();
761 chan_info_opt = chan.one_to_two.as_ref();
763 if let Some(chan_info) = chan_info_opt {
764 if chan_info.enabled {
765 let fees = lowest_inbound_channel_fees.get_or_insert(RoutingFees {
766 base_msat: u32::max_value(), proportional_millionths: u32::max_value() });
767 fees.base_msat = cmp::min(fees.base_msat, chan_info.fees.base_msat);
768 fees.proportional_millionths = cmp::min(fees.proportional_millionths, chan_info.fees.proportional_millionths);
773 node.lowest_inbound_channel_fees = lowest_inbound_channel_fees;
776 Ok(msg.contents.excess_data.is_empty())
779 fn remove_channel_in_nodes(nodes: &mut BTreeMap<PublicKey, NodeInfo>, chan: &ChannelInfo, short_channel_id: u64) {
780 macro_rules! remove_from_node {
781 ($node_id: expr) => {
782 if let BtreeEntry::Occupied(mut entry) = nodes.entry($node_id) {
783 entry.get_mut().channels.retain(|chan_id| {
784 short_channel_id != *chan_id
786 if entry.get().channels.is_empty() {
787 entry.remove_entry();
790 panic!("Had channel that pointed to unknown node (ie inconsistent network map)!");
795 remove_from_node!(chan.node_one);
796 remove_from_node!(chan.node_two);
803 use ln::features::{ChannelFeatures, NodeFeatures};
804 use routing::network_graph::{NetGraphMsgHandler, NetworkGraph};
805 use ln::msgs::{OptionalField, RoutingMessageHandler, UnsignedNodeAnnouncement, NodeAnnouncement,
806 UnsignedChannelAnnouncement, ChannelAnnouncement, UnsignedChannelUpdate, ChannelUpdate, HTLCFailChannelUpdate,
808 use util::test_utils;
809 use util::logger::Logger;
810 use util::ser::{Readable, Writeable};
812 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
813 use bitcoin::hashes::Hash;
814 use bitcoin::network::constants::Network;
815 use bitcoin::blockdata::constants::genesis_block;
816 use bitcoin::blockdata::script::Builder;
817 use bitcoin::blockdata::transaction::TxOut;
818 use bitcoin::blockdata::opcodes;
819 use bitcoin::util::hash::BitcoinHash;
823 use bitcoin::secp256k1::key::{PublicKey, SecretKey};
824 use bitcoin::secp256k1::{All, Secp256k1};
828 fn create_net_graph_msg_handler() -> (Secp256k1<All>, NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>) {
829 let secp_ctx = Secp256k1::new();
830 let logger = Arc::new(test_utils::TestLogger::new());
831 let net_graph_msg_handler = NetGraphMsgHandler::new(None, Arc::clone(&logger));
832 (secp_ctx, net_graph_msg_handler)
836 fn request_full_sync_finite_times() {
837 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
838 let node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap()[..]).unwrap());
840 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
841 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
842 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
843 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
844 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
845 assert!(!net_graph_msg_handler.should_request_full_sync(&node_id));
849 fn handling_node_announcements() {
850 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
852 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
853 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
854 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
855 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
856 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
857 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
858 let zero_hash = Sha256dHash::hash(&[0; 32]);
859 let first_announcement_time = 500;
861 let mut unsigned_announcement = UnsignedNodeAnnouncement {
862 features: NodeFeatures::known(),
863 timestamp: first_announcement_time,
867 addresses: Vec::new(),
868 excess_address_data: Vec::new(),
869 excess_data: Vec::new(),
871 let mut msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
872 let valid_announcement = NodeAnnouncement {
873 signature: secp_ctx.sign(&msghash, node_1_privkey),
874 contents: unsigned_announcement.clone()
877 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
879 Err(e) => assert_eq!("No existing channels for node_announcement", e.err)
883 // Announce a channel to add a corresponding node.
884 let unsigned_announcement = UnsignedChannelAnnouncement {
885 features: ChannelFeatures::known(),
886 chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
890 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
891 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
892 excess_data: Vec::new(),
895 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
896 let valid_announcement = ChannelAnnouncement {
897 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
898 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
899 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
900 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
901 contents: unsigned_announcement.clone(),
903 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
904 Ok(res) => assert!(res),
909 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
910 Ok(res) => assert!(res),
914 let fake_msghash = hash_to_message!(&zero_hash);
915 match net_graph_msg_handler.handle_node_announcement(
917 signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
918 contents: unsigned_announcement.clone()
921 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
924 unsigned_announcement.timestamp += 1000;
925 unsigned_announcement.excess_data.push(1);
926 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
927 let announcement_with_data = NodeAnnouncement {
928 signature: secp_ctx.sign(&msghash, node_1_privkey),
929 contents: unsigned_announcement.clone()
931 // Return false because contains excess data.
932 match net_graph_msg_handler.handle_node_announcement(&announcement_with_data) {
933 Ok(res) => assert!(!res),
936 unsigned_announcement.excess_data = Vec::new();
938 // Even though previous announcement was not relayed further, we still accepted it,
939 // so we now won't accept announcements before the previous one.
940 unsigned_announcement.timestamp -= 10;
941 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
942 let outdated_announcement = NodeAnnouncement {
943 signature: secp_ctx.sign(&msghash, node_1_privkey),
944 contents: unsigned_announcement.clone()
946 match net_graph_msg_handler.handle_node_announcement(&outdated_announcement) {
948 Err(e) => assert_eq!(e.err, "Update older than last processed update")
953 fn handling_channel_announcements() {
954 let secp_ctx = Secp256k1::new();
955 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
957 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
958 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
959 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
960 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
961 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
962 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
964 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
965 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_1_btckey).serialize())
966 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_2_btckey).serialize())
967 .push_opcode(opcodes::all::OP_PUSHNUM_2)
968 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
971 let mut unsigned_announcement = UnsignedChannelAnnouncement {
972 features: ChannelFeatures::known(),
973 chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
977 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
978 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
979 excess_data: Vec::new(),
982 let mut msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
983 let valid_announcement = ChannelAnnouncement {
984 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
985 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
986 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
987 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
988 contents: unsigned_announcement.clone(),
991 // Test if the UTXO lookups were not supported
992 let mut net_graph_msg_handler = NetGraphMsgHandler::new(None, Arc::clone(&logger));
993 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
994 Ok(res) => assert!(res),
999 let network = net_graph_msg_handler.network_graph.read().unwrap();
1000 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1006 // If we receive announcement for the same channel (with UTXO lookups disabled),
1007 // drop new one on the floor, since we can't see any changes.
1008 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1010 Err(e) => assert_eq!(e.err, "Already have knowledge of channel")
1013 // Test if an associated transaction were not on-chain (or not confirmed).
1014 let chain_source = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1015 *chain_source.utxo_ret.lock().unwrap() = Err(chain::AccessError::UnknownTx);
1016 net_graph_msg_handler = NetGraphMsgHandler::new(Some(chain_source.clone()), Arc::clone(&logger));
1017 unsigned_announcement.short_channel_id += 1;
1019 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1020 let valid_announcement = ChannelAnnouncement {
1021 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1022 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1023 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1024 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1025 contents: unsigned_announcement.clone(),
1028 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1030 Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1033 // Now test if the transaction is found in the UTXO set and the script is correct.
1034 unsigned_announcement.short_channel_id += 1;
1035 *chain_source.utxo_ret.lock().unwrap() = Ok(TxOut { value: 0, script_pubkey: good_script.clone() });
1037 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1038 let valid_announcement = ChannelAnnouncement {
1039 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1040 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1041 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1042 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1043 contents: unsigned_announcement.clone(),
1045 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1046 Ok(res) => assert!(res),
1051 let network = net_graph_msg_handler.network_graph.read().unwrap();
1052 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1058 // If we receive announcement for the same channel (but TX is not confirmed),
1059 // drop new one on the floor, since we can't see any changes.
1060 *chain_source.utxo_ret.lock().unwrap() = Err(chain::AccessError::UnknownTx);
1061 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1063 Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1066 // But if it is confirmed, replace the channel
1067 *chain_source.utxo_ret.lock().unwrap() = Ok(TxOut { value: 0, script_pubkey: good_script });
1068 unsigned_announcement.features = ChannelFeatures::empty();
1069 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1070 let valid_announcement = ChannelAnnouncement {
1071 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1072 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1073 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1074 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1075 contents: unsigned_announcement.clone(),
1077 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1078 Ok(res) => assert!(res),
1082 let network = net_graph_msg_handler.network_graph.read().unwrap();
1083 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1084 Some(channel_entry) => {
1085 assert_eq!(channel_entry.features, ChannelFeatures::empty());
1091 // Don't relay valid channels with excess data
1092 unsigned_announcement.short_channel_id += 1;
1093 unsigned_announcement.excess_data.push(1);
1094 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1095 let valid_announcement = ChannelAnnouncement {
1096 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1097 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1098 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1099 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1100 contents: unsigned_announcement.clone(),
1102 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1103 Ok(res) => assert!(!res),
1107 unsigned_announcement.excess_data = Vec::new();
1108 let invalid_sig_announcement = ChannelAnnouncement {
1109 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1110 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1111 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1112 bitcoin_signature_2: secp_ctx.sign(&msghash, node_1_btckey),
1113 contents: unsigned_announcement.clone(),
1115 match net_graph_msg_handler.handle_channel_announcement(&invalid_sig_announcement) {
1117 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1120 unsigned_announcement.node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1121 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1122 let channel_to_itself_announcement = ChannelAnnouncement {
1123 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1124 node_signature_2: secp_ctx.sign(&msghash, node_1_privkey),
1125 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1126 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1127 contents: unsigned_announcement.clone(),
1129 match net_graph_msg_handler.handle_channel_announcement(&channel_to_itself_announcement) {
1131 Err(e) => assert_eq!(e.err, "Channel announcement node had a channel with itself")
1136 fn handling_channel_update() {
1137 let secp_ctx = Secp256k1::new();
1138 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
1139 let chain_source = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1140 let net_graph_msg_handler = NetGraphMsgHandler::new(Some(chain_source.clone()), Arc::clone(&logger));
1142 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1143 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1144 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1145 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1146 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1147 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1149 let zero_hash = Sha256dHash::hash(&[0; 32]);
1150 let short_channel_id = 0;
1151 let chain_hash = genesis_block(Network::Testnet).header.bitcoin_hash();
1152 let amount_sats = 1000_000;
1155 // Announce a channel we will update
1156 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
1157 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_1_btckey).serialize())
1158 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_2_btckey).serialize())
1159 .push_opcode(opcodes::all::OP_PUSHNUM_2)
1160 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
1161 *chain_source.utxo_ret.lock().unwrap() = Ok(TxOut { value: amount_sats, script_pubkey: good_script.clone() });
1162 let unsigned_announcement = UnsignedChannelAnnouncement {
1163 features: ChannelFeatures::empty(),
1168 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1169 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1170 excess_data: Vec::new(),
1173 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1174 let valid_channel_announcement = ChannelAnnouncement {
1175 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1176 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1177 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1178 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1179 contents: unsigned_announcement.clone(),
1181 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1188 let mut unsigned_channel_update = UnsignedChannelUpdate {
1193 cltv_expiry_delta: 144,
1194 htlc_minimum_msat: 1000000,
1195 htlc_maximum_msat: OptionalField::Absent,
1196 fee_base_msat: 10000,
1197 fee_proportional_millionths: 20,
1198 excess_data: Vec::new()
1200 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1201 let valid_channel_update = ChannelUpdate {
1202 signature: secp_ctx.sign(&msghash, node_1_privkey),
1203 contents: unsigned_channel_update.clone()
1206 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1207 Ok(res) => assert!(res),
1212 let network = net_graph_msg_handler.network_graph.read().unwrap();
1213 match network.get_channels().get(&short_channel_id) {
1215 Some(channel_info) => {
1216 assert_eq!(channel_info.one_to_two.as_ref().unwrap().cltv_expiry_delta, 144);
1217 assert!(channel_info.two_to_one.is_none());
1222 unsigned_channel_update.timestamp += 100;
1223 unsigned_channel_update.excess_data.push(1);
1224 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1225 let valid_channel_update = ChannelUpdate {
1226 signature: secp_ctx.sign(&msghash, node_1_privkey),
1227 contents: unsigned_channel_update.clone()
1229 // Return false because contains excess data
1230 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1231 Ok(res) => assert!(!res),
1234 unsigned_channel_update.timestamp += 10;
1236 unsigned_channel_update.short_channel_id += 1;
1237 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1238 let valid_channel_update = ChannelUpdate {
1239 signature: secp_ctx.sign(&msghash, node_1_privkey),
1240 contents: unsigned_channel_update.clone()
1243 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1245 Err(e) => assert_eq!(e.err, "Couldn't find channel for update")
1247 unsigned_channel_update.short_channel_id = short_channel_id;
1249 unsigned_channel_update.htlc_maximum_msat = OptionalField::Present(MAX_VALUE_MSAT + 1);
1250 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1251 let valid_channel_update = ChannelUpdate {
1252 signature: secp_ctx.sign(&msghash, node_1_privkey),
1253 contents: unsigned_channel_update.clone()
1256 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1258 Err(e) => assert_eq!(e.err, "htlc_maximum_msat is larger than maximum possible msats")
1260 unsigned_channel_update.htlc_maximum_msat = OptionalField::Absent;
1262 unsigned_channel_update.htlc_maximum_msat = OptionalField::Present(amount_sats * 1000 + 1);
1263 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1264 let valid_channel_update = ChannelUpdate {
1265 signature: secp_ctx.sign(&msghash, node_1_privkey),
1266 contents: unsigned_channel_update.clone()
1269 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1271 Err(e) => assert_eq!(e.err, "htlc_maximum_msat is larger than channel capacity")
1273 unsigned_channel_update.htlc_maximum_msat = OptionalField::Absent;
1275 // Even though previous update was not relayed further, we still accepted it,
1276 // so we now won't accept update before the previous one.
1277 unsigned_channel_update.timestamp -= 10;
1278 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1279 let valid_channel_update = ChannelUpdate {
1280 signature: secp_ctx.sign(&msghash, node_1_privkey),
1281 contents: unsigned_channel_update.clone()
1284 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1286 Err(e) => assert_eq!(e.err, "Update older than last processed update")
1288 unsigned_channel_update.timestamp += 500;
1290 let fake_msghash = hash_to_message!(&zero_hash);
1291 let invalid_sig_channel_update = ChannelUpdate {
1292 signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
1293 contents: unsigned_channel_update.clone()
1296 match net_graph_msg_handler.handle_channel_update(&invalid_sig_channel_update) {
1298 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1304 fn handling_htlc_fail_channel_update() {
1305 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1306 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1307 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1308 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1309 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1310 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1311 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1313 let short_channel_id = 0;
1314 let chain_hash = genesis_block(Network::Testnet).header.bitcoin_hash();
1317 // There is no nodes in the table at the beginning.
1318 let network = net_graph_msg_handler.network_graph.read().unwrap();
1319 assert_eq!(network.get_nodes().len(), 0);
1323 // Announce a channel we will update
1324 let unsigned_announcement = UnsignedChannelAnnouncement {
1325 features: ChannelFeatures::empty(),
1330 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1331 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1332 excess_data: Vec::new(),
1335 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1336 let valid_channel_announcement = ChannelAnnouncement {
1337 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1338 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1339 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1340 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1341 contents: unsigned_announcement.clone(),
1343 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1348 let unsigned_channel_update = UnsignedChannelUpdate {
1353 cltv_expiry_delta: 144,
1354 htlc_minimum_msat: 1000000,
1355 htlc_maximum_msat: OptionalField::Absent,
1356 fee_base_msat: 10000,
1357 fee_proportional_millionths: 20,
1358 excess_data: Vec::new()
1360 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1361 let valid_channel_update = ChannelUpdate {
1362 signature: secp_ctx.sign(&msghash, node_1_privkey),
1363 contents: unsigned_channel_update.clone()
1366 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1367 Ok(res) => assert!(res),
1372 // Non-permanent closing just disables a channel
1374 let network = net_graph_msg_handler.network_graph.read().unwrap();
1375 match network.get_channels().get(&short_channel_id) {
1377 Some(channel_info) => {
1378 assert!(channel_info.one_to_two.is_some());
1383 let channel_close_msg = HTLCFailChannelUpdate::ChannelClosed {
1388 net_graph_msg_handler.handle_htlc_fail_channel_update(&channel_close_msg);
1390 // Non-permanent closing just disables a channel
1392 let network = net_graph_msg_handler.network_graph.read().unwrap();
1393 match network.get_channels().get(&short_channel_id) {
1395 Some(channel_info) => {
1396 assert!(!channel_info.one_to_two.as_ref().unwrap().enabled);
1401 let channel_close_msg = HTLCFailChannelUpdate::ChannelClosed {
1406 net_graph_msg_handler.handle_htlc_fail_channel_update(&channel_close_msg);
1408 // Permanent closing deletes a channel
1410 let network = net_graph_msg_handler.network_graph.read().unwrap();
1411 assert_eq!(network.get_channels().len(), 0);
1412 // Nodes are also deleted because there are no associated channels anymore
1413 assert_eq!(network.get_nodes().len(), 0);
1415 // TODO: Test HTLCFailChannelUpdate::NodeFailure, which is not implemented yet.
1419 fn getting_next_channel_announcements() {
1420 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1421 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1422 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1423 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1424 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1425 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1426 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1428 let short_channel_id = 1;
1429 let chain_hash = genesis_block(Network::Testnet).header.bitcoin_hash();
1431 // Channels were not announced yet.
1432 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(0, 1);
1433 assert_eq!(channels_with_announcements.len(), 0);
1436 // Announce a channel we will update
1437 let unsigned_announcement = UnsignedChannelAnnouncement {
1438 features: ChannelFeatures::empty(),
1443 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1444 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1445 excess_data: Vec::new(),
1448 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1449 let valid_channel_announcement = ChannelAnnouncement {
1450 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1451 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1452 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1453 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1454 contents: unsigned_announcement.clone(),
1456 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1462 // Contains initial channel announcement now.
1463 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1464 assert_eq!(channels_with_announcements.len(), 1);
1465 if let Some(channel_announcements) = channels_with_announcements.first() {
1466 let &(_, ref update_1, ref update_2) = channel_announcements;
1467 assert_eq!(update_1, &None);
1468 assert_eq!(update_2, &None);
1475 // Valid channel update
1476 let unsigned_channel_update = UnsignedChannelUpdate {
1481 cltv_expiry_delta: 144,
1482 htlc_minimum_msat: 1000000,
1483 htlc_maximum_msat: OptionalField::Absent,
1484 fee_base_msat: 10000,
1485 fee_proportional_millionths: 20,
1486 excess_data: Vec::new()
1488 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1489 let valid_channel_update = ChannelUpdate {
1490 signature: secp_ctx.sign(&msghash, node_1_privkey),
1491 contents: unsigned_channel_update.clone()
1493 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1499 // Now contains an initial announcement and an update.
1500 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1501 assert_eq!(channels_with_announcements.len(), 1);
1502 if let Some(channel_announcements) = channels_with_announcements.first() {
1503 let &(_, ref update_1, ref update_2) = channel_announcements;
1504 assert_ne!(update_1, &None);
1505 assert_eq!(update_2, &None);
1512 // Channel update with excess data.
1513 let unsigned_channel_update = UnsignedChannelUpdate {
1518 cltv_expiry_delta: 144,
1519 htlc_minimum_msat: 1000000,
1520 htlc_maximum_msat: OptionalField::Absent,
1521 fee_base_msat: 10000,
1522 fee_proportional_millionths: 20,
1523 excess_data: [1; 3].to_vec()
1525 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1526 let valid_channel_update = ChannelUpdate {
1527 signature: secp_ctx.sign(&msghash, node_1_privkey),
1528 contents: unsigned_channel_update.clone()
1530 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1536 // Test that announcements with excess data won't be returned
1537 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1538 assert_eq!(channels_with_announcements.len(), 1);
1539 if let Some(channel_announcements) = channels_with_announcements.first() {
1540 let &(_, ref update_1, ref update_2) = channel_announcements;
1541 assert_eq!(update_1, &None);
1542 assert_eq!(update_2, &None);
1547 // Further starting point have no channels after it
1548 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id + 1000, 1);
1549 assert_eq!(channels_with_announcements.len(), 0);
1553 fn getting_next_node_announcements() {
1554 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1555 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1556 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1557 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1558 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1559 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1560 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1562 let short_channel_id = 1;
1563 let chain_hash = genesis_block(Network::Testnet).header.bitcoin_hash();
1566 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 10);
1567 assert_eq!(next_announcements.len(), 0);
1570 // Announce a channel to add 2 nodes
1571 let unsigned_announcement = UnsignedChannelAnnouncement {
1572 features: ChannelFeatures::empty(),
1577 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1578 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1579 excess_data: Vec::new(),
1582 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1583 let valid_channel_announcement = ChannelAnnouncement {
1584 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1585 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1586 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1587 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1588 contents: unsigned_announcement.clone(),
1590 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1597 // Nodes were never announced
1598 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
1599 assert_eq!(next_announcements.len(), 0);
1602 let mut unsigned_announcement = UnsignedNodeAnnouncement {
1603 features: NodeFeatures::known(),
1608 addresses: Vec::new(),
1609 excess_address_data: Vec::new(),
1610 excess_data: Vec::new(),
1612 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1613 let valid_announcement = NodeAnnouncement {
1614 signature: secp_ctx.sign(&msghash, node_1_privkey),
1615 contents: unsigned_announcement.clone()
1617 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1622 unsigned_announcement.node_id = node_id_2;
1623 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1624 let valid_announcement = NodeAnnouncement {
1625 signature: secp_ctx.sign(&msghash, node_2_privkey),
1626 contents: unsigned_announcement.clone()
1629 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1635 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
1636 assert_eq!(next_announcements.len(), 2);
1638 // Skip the first node.
1639 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
1640 assert_eq!(next_announcements.len(), 1);
1643 // Later announcement which should not be relayed (excess data) prevent us from sharing a node
1644 let unsigned_announcement = UnsignedNodeAnnouncement {
1645 features: NodeFeatures::known(),
1650 addresses: Vec::new(),
1651 excess_address_data: Vec::new(),
1652 excess_data: [1; 3].to_vec(),
1654 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1655 let valid_announcement = NodeAnnouncement {
1656 signature: secp_ctx.sign(&msghash, node_2_privkey),
1657 contents: unsigned_announcement.clone()
1659 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1660 Ok(res) => assert!(!res),
1665 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
1666 assert_eq!(next_announcements.len(), 0);
1670 fn network_graph_serialization() {
1671 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1673 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1674 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1675 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1676 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1678 // Announce a channel to add a corresponding node.
1679 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1680 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1681 let unsigned_announcement = UnsignedChannelAnnouncement {
1682 features: ChannelFeatures::known(),
1683 chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
1684 short_channel_id: 0,
1687 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1688 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1689 excess_data: Vec::new(),
1692 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1693 let valid_announcement = ChannelAnnouncement {
1694 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1695 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1696 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1697 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1698 contents: unsigned_announcement.clone(),
1700 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1701 Ok(res) => assert!(res),
1706 let node_id = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1707 let unsigned_announcement = UnsignedNodeAnnouncement {
1708 features: NodeFeatures::known(),
1713 addresses: Vec::new(),
1714 excess_address_data: Vec::new(),
1715 excess_data: Vec::new(),
1717 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1718 let valid_announcement = NodeAnnouncement {
1719 signature: secp_ctx.sign(&msghash, node_1_privkey),
1720 contents: unsigned_announcement.clone()
1723 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1728 let network = net_graph_msg_handler.network_graph.write().unwrap();
1729 let mut w = test_utils::TestVecWriter(Vec::new());
1730 assert!(!network.get_nodes().is_empty());
1731 assert!(!network.get_channels().is_empty());
1732 network.write(&mut w).unwrap();
1733 assert!(<NetworkGraph>::read(&mut ::std::io::Cursor::new(&w.0)).unwrap() == *network);