1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! The top-level network map tracking logic lives here.
12 use bitcoin::secp256k1::key::PublicKey;
13 use bitcoin::secp256k1::Secp256k1;
14 use bitcoin::secp256k1;
16 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
17 use bitcoin::hashes::Hash;
18 use bitcoin::blockdata::script::Builder;
19 use bitcoin::blockdata::transaction::TxOut;
20 use bitcoin::blockdata::opcodes;
21 use bitcoin::hash_types::BlockHash;
25 use ln::features::{ChannelFeatures, NodeFeatures};
26 use ln::msgs::{DecodeError, ErrorAction, Init, LightningError, RoutingMessageHandler, NetAddress, MAX_VALUE_MSAT};
27 use ln::msgs::{ChannelAnnouncement, ChannelUpdate, NodeAnnouncement, OptionalField};
28 use ln::msgs::{QueryChannelRange, ReplyChannelRange, QueryShortChannelIds, ReplyShortChannelIdsEnd};
30 use util::ser::{Writeable, Readable, Writer};
31 use util::logger::Logger;
32 use util::events::{MessageSendEvent, MessageSendEventsProvider};
33 use util::scid_utils::{block_from_scid, scid_from_parts, MAX_SCID_BLOCK};
36 use std::sync::{RwLock, RwLockReadGuard};
37 use std::sync::atomic::{AtomicUsize, Ordering};
39 use std::collections::BTreeMap;
40 use std::collections::btree_map::Entry as BtreeEntry;
42 use bitcoin::hashes::hex::ToHex;
44 /// The maximum number of extra bytes which we do not understand in a gossip message before we will
45 /// refuse to relay the message.
46 const MAX_EXCESS_BYTES_FOR_RELAY: usize = 1024;
48 /// Maximum number of short_channel_ids that will be encoded in one gossip reply message.
49 /// This value ensures a reply fits within the 65k payload limit and is consistent with other implementations.
50 const MAX_SCIDS_PER_REPLY: usize = 8000;
52 /// Represents the network as nodes and channels between them
53 #[derive(Clone, PartialEq)]
54 pub struct NetworkGraph {
55 genesis_hash: BlockHash,
56 channels: BTreeMap<u64, ChannelInfo>,
57 nodes: BTreeMap<PublicKey, NodeInfo>,
60 /// A simple newtype for RwLockReadGuard<'a, NetworkGraph>.
61 /// This exists only to make accessing a RwLock<NetworkGraph> possible from
62 /// the C bindings, as it can be done directly in Rust code.
63 pub struct LockedNetworkGraph<'a>(pub RwLockReadGuard<'a, NetworkGraph>);
65 /// Receives and validates network updates from peers,
66 /// stores authentic and relevant data as a network graph.
67 /// This network graph is then used for routing payments.
68 /// Provides interface to help with initial routing sync by
69 /// serving historical announcements.
70 pub struct NetGraphMsgHandler<C: Deref, L: Deref> where C::Target: chain::Access, L::Target: Logger {
71 secp_ctx: Secp256k1<secp256k1::VerifyOnly>,
72 /// Representation of the payment channel network
73 pub network_graph: RwLock<NetworkGraph>,
74 chain_access: Option<C>,
75 full_syncs_requested: AtomicUsize,
76 pending_events: Mutex<Vec<MessageSendEvent>>,
80 impl<C: Deref, L: Deref> NetGraphMsgHandler<C, L> where C::Target: chain::Access, L::Target: Logger {
81 /// Creates a new tracker of the actual state of the network of channels and nodes,
82 /// assuming a fresh network graph.
83 /// Chain monitor is used to make sure announced channels exist on-chain,
84 /// channel data is correct, and that the announcement is signed with
85 /// channel owners' keys.
86 pub fn new(genesis_hash: BlockHash, chain_access: Option<C>, logger: L) -> Self {
88 secp_ctx: Secp256k1::verification_only(),
89 network_graph: RwLock::new(NetworkGraph::new(genesis_hash)),
90 full_syncs_requested: AtomicUsize::new(0),
92 pending_events: Mutex::new(vec![]),
97 /// Creates a new tracker of the actual state of the network of channels and nodes,
98 /// assuming an existing Network Graph.
99 pub fn from_net_graph(chain_access: Option<C>, logger: L, network_graph: NetworkGraph) -> Self {
101 secp_ctx: Secp256k1::verification_only(),
102 network_graph: RwLock::new(network_graph),
103 full_syncs_requested: AtomicUsize::new(0),
105 pending_events: Mutex::new(vec![]),
110 /// Adds a provider used to check new announcements. Does not affect
111 /// existing announcements unless they are updated.
112 /// Add, update or remove the provider would replace the current one.
113 pub fn add_chain_access(&mut self, chain_access: Option<C>) {
114 self.chain_access = chain_access;
117 /// Take a read lock on the network_graph and return it in the C-bindings
118 /// newtype helper. This is likely only useful when called via the C
119 /// bindings as you can call `self.network_graph.read().unwrap()` in Rust
121 pub fn read_locked_graph<'a>(&'a self) -> LockedNetworkGraph<'a> {
122 LockedNetworkGraph(self.network_graph.read().unwrap())
125 /// Returns true when a full routing table sync should be performed with a peer.
126 fn should_request_full_sync(&self, _node_id: &PublicKey) -> bool {
127 //TODO: Determine whether to request a full sync based on the network map.
128 const FULL_SYNCS_TO_REQUEST: usize = 5;
129 if self.full_syncs_requested.load(Ordering::Acquire) < FULL_SYNCS_TO_REQUEST {
130 self.full_syncs_requested.fetch_add(1, Ordering::AcqRel);
138 impl<'a> LockedNetworkGraph<'a> {
139 /// Get a reference to the NetworkGraph which this read-lock contains.
140 pub fn graph(&self) -> &NetworkGraph {
146 macro_rules! secp_verify_sig {
147 ( $secp_ctx: expr, $msg: expr, $sig: expr, $pubkey: expr ) => {
148 match $secp_ctx.verify($msg, $sig, $pubkey) {
150 Err(_) => return Err(LightningError{err: "Invalid signature from remote node".to_owned(), action: ErrorAction::IgnoreError}),
155 impl<C: Deref + Sync + Send, L: Deref + Sync + Send> RoutingMessageHandler for NetGraphMsgHandler<C, L> where C::Target: chain::Access, L::Target: Logger {
156 fn handle_node_announcement(&self, msg: &msgs::NodeAnnouncement) -> Result<bool, LightningError> {
157 self.network_graph.write().unwrap().update_node_from_announcement(msg, &self.secp_ctx)?;
158 Ok(msg.contents.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY &&
159 msg.contents.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY &&
160 msg.contents.excess_data.len() + msg.contents.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY)
163 fn handle_channel_announcement(&self, msg: &msgs::ChannelAnnouncement) -> Result<bool, LightningError> {
164 self.network_graph.write().unwrap().update_channel_from_announcement(msg, &self.chain_access, &self.secp_ctx)?;
165 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 { "" });
166 Ok(msg.contents.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY)
169 fn handle_htlc_fail_channel_update(&self, update: &msgs::HTLCFailChannelUpdate) {
171 &msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg } => {
172 let _ = self.network_graph.write().unwrap().update_channel(msg, &self.secp_ctx);
174 &msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id, is_permanent } => {
175 self.network_graph.write().unwrap().close_channel_from_update(short_channel_id, is_permanent);
177 &msgs::HTLCFailChannelUpdate::NodeFailure { ref node_id, is_permanent } => {
178 self.network_graph.write().unwrap().fail_node(node_id, is_permanent);
183 fn handle_channel_update(&self, msg: &msgs::ChannelUpdate) -> Result<bool, LightningError> {
184 self.network_graph.write().unwrap().update_channel(msg, &self.secp_ctx)?;
185 Ok(msg.contents.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY)
188 fn get_next_channel_announcements(&self, starting_point: u64, batch_amount: u8) -> Vec<(ChannelAnnouncement, Option<ChannelUpdate>, Option<ChannelUpdate>)> {
189 let network_graph = self.network_graph.read().unwrap();
190 let mut result = Vec::with_capacity(batch_amount as usize);
191 let mut iter = network_graph.get_channels().range(starting_point..);
192 while result.len() < batch_amount as usize {
193 if let Some((_, ref chan)) = iter.next() {
194 if chan.announcement_message.is_some() {
195 let chan_announcement = chan.announcement_message.clone().unwrap();
196 let mut one_to_two_announcement: Option<msgs::ChannelUpdate> = None;
197 let mut two_to_one_announcement: Option<msgs::ChannelUpdate> = None;
198 if let Some(one_to_two) = chan.one_to_two.as_ref() {
199 one_to_two_announcement = one_to_two.last_update_message.clone();
201 if let Some(two_to_one) = chan.two_to_one.as_ref() {
202 two_to_one_announcement = two_to_one.last_update_message.clone();
204 result.push((chan_announcement, one_to_two_announcement, two_to_one_announcement));
206 // TODO: We may end up sending un-announced channel_updates if we are sending
207 // initial sync data while receiving announce/updates for this channel.
216 fn get_next_node_announcements(&self, starting_point: Option<&PublicKey>, batch_amount: u8) -> Vec<NodeAnnouncement> {
217 let network_graph = self.network_graph.read().unwrap();
218 let mut result = Vec::with_capacity(batch_amount as usize);
219 let mut iter = if let Some(pubkey) = starting_point {
220 let mut iter = network_graph.get_nodes().range((*pubkey)..);
224 network_graph.get_nodes().range(..)
226 while result.len() < batch_amount as usize {
227 if let Some((_, ref node)) = iter.next() {
228 if let Some(node_info) = node.announcement_info.as_ref() {
229 if node_info.announcement_message.is_some() {
230 result.push(node_info.announcement_message.clone().unwrap());
240 /// Initiates a stateless sync of routing gossip information with a peer
241 /// using gossip_queries. The default strategy used by this implementation
242 /// is to sync the full block range with several peers.
244 /// We should expect one or more reply_channel_range messages in response
245 /// to our query_channel_range. Each reply will enqueue a query_scid message
246 /// to request gossip messages for each channel. The sync is considered complete
247 /// when the final reply_scids_end message is received, though we are not
248 /// tracking this directly.
249 fn sync_routing_table(&self, their_node_id: &PublicKey, init_msg: &Init) {
251 // We will only perform a sync with peers that support gossip_queries.
252 if !init_msg.features.supports_gossip_queries() {
256 // Check if we need to perform a full synchronization with this peer
257 if !self.should_request_full_sync(their_node_id) {
261 let first_blocknum = 0;
262 let number_of_blocks = 0xffffffff;
263 log_debug!(self.logger, "Sending query_channel_range peer={}, first_blocknum={}, number_of_blocks={}", log_pubkey!(their_node_id), first_blocknum, number_of_blocks);
264 let mut pending_events = self.pending_events.lock().unwrap();
265 pending_events.push(MessageSendEvent::SendChannelRangeQuery {
266 node_id: their_node_id.clone(),
267 msg: QueryChannelRange {
268 chain_hash: self.network_graph.read().unwrap().genesis_hash,
275 /// Statelessly processes a reply to a channel range query by immediately
276 /// sending an SCID query with SCIDs in the reply. To keep this handler
277 /// stateless, it does not validate the sequencing of replies for multi-
278 /// reply ranges. It does not validate whether the reply(ies) cover the
279 /// queried range. It also does not filter SCIDs to only those in the
280 /// original query range. We also do not validate that the chain_hash
281 /// matches the chain_hash of the NetworkGraph. Any chan_ann message that
282 /// does not match our chain_hash will be rejected when the announcement is
284 fn handle_reply_channel_range(&self, their_node_id: &PublicKey, msg: ReplyChannelRange) -> Result<(), LightningError> {
285 log_debug!(self.logger, "Handling reply_channel_range peer={}, first_blocknum={}, number_of_blocks={}, sync_complete={}, scids={}", log_pubkey!(their_node_id), msg.first_blocknum, msg.number_of_blocks, msg.sync_complete, msg.short_channel_ids.len(),);
287 log_debug!(self.logger, "Sending query_short_channel_ids peer={}, batch_size={}", log_pubkey!(their_node_id), msg.short_channel_ids.len());
288 let mut pending_events = self.pending_events.lock().unwrap();
289 pending_events.push(MessageSendEvent::SendShortIdsQuery {
290 node_id: their_node_id.clone(),
291 msg: QueryShortChannelIds {
292 chain_hash: msg.chain_hash,
293 short_channel_ids: msg.short_channel_ids,
300 /// When an SCID query is initiated the remote peer will begin streaming
301 /// gossip messages. In the event of a failure, we may have received
302 /// some channel information. Before trying with another peer, the
303 /// caller should update its set of SCIDs that need to be queried.
304 fn handle_reply_short_channel_ids_end(&self, their_node_id: &PublicKey, msg: ReplyShortChannelIdsEnd) -> Result<(), LightningError> {
305 log_debug!(self.logger, "Handling reply_short_channel_ids_end peer={}, full_information={}", log_pubkey!(their_node_id), msg.full_information);
307 // If the remote node does not have up-to-date information for the
308 // chain_hash they will set full_information=false. We can fail
309 // the result and try again with a different peer.
310 if !msg.full_information {
311 return Err(LightningError {
312 err: String::from("Received reply_short_channel_ids_end with no information"),
313 action: ErrorAction::IgnoreError
320 /// Processes a query from a peer by finding announced/public channels whose funding UTXOs
321 /// are in the specified block range. Due to message size limits, large range
322 /// queries may result in several reply messages. This implementation enqueues
323 /// all reply messages into pending events. Each message will allocate just under 65KiB. A full
324 /// sync of the public routing table with 128k channels will generated 16 messages and allocate ~1MB.
325 /// Logic can be changed to reduce allocation if/when a full sync of the routing table impacts
326 /// memory constrained systems.
327 fn handle_query_channel_range(&self, their_node_id: &PublicKey, msg: QueryChannelRange) -> Result<(), LightningError> {
328 log_debug!(self.logger, "Handling query_channel_range peer={}, first_blocknum={}, number_of_blocks={}", log_pubkey!(their_node_id), msg.first_blocknum, msg.number_of_blocks);
330 let network_graph = self.network_graph.read().unwrap();
332 let inclusive_start_scid = scid_from_parts(msg.first_blocknum as u64, 0, 0);
334 // We might receive valid queries with end_blocknum that would overflow SCID conversion.
335 // If so, we manually cap the ending block to avoid this overflow.
336 let exclusive_end_scid = scid_from_parts(cmp::min(msg.end_blocknum() as u64, MAX_SCID_BLOCK), 0, 0);
338 // Per spec, we must reply to a query. Send an empty message when things are invalid.
339 if msg.chain_hash != network_graph.genesis_hash || inclusive_start_scid.is_err() || exclusive_end_scid.is_err() || msg.number_of_blocks == 0 {
340 let mut pending_events = self.pending_events.lock().unwrap();
341 pending_events.push(MessageSendEvent::SendReplyChannelRange {
342 node_id: their_node_id.clone(),
343 msg: ReplyChannelRange {
344 chain_hash: msg.chain_hash.clone(),
345 first_blocknum: msg.first_blocknum,
346 number_of_blocks: msg.number_of_blocks,
348 short_channel_ids: vec![],
351 return Err(LightningError {
352 err: String::from("query_channel_range could not be processed"),
353 action: ErrorAction::IgnoreError,
357 // Creates channel batches. We are not checking if the channel is routable
358 // (has at least one update). A peer may still want to know the channel
359 // exists even if its not yet routable.
360 let mut batches: Vec<Vec<u64>> = vec![Vec::with_capacity(MAX_SCIDS_PER_REPLY)];
361 for (_, ref chan) in network_graph.get_channels().range(inclusive_start_scid.unwrap()..exclusive_end_scid.unwrap()) {
362 if let Some(chan_announcement) = &chan.announcement_message {
363 // Construct a new batch if last one is full
364 if batches.last().unwrap().len() == batches.last().unwrap().capacity() {
365 batches.push(Vec::with_capacity(MAX_SCIDS_PER_REPLY));
368 let batch = batches.last_mut().unwrap();
369 batch.push(chan_announcement.contents.short_channel_id);
374 let mut pending_events = self.pending_events.lock().unwrap();
375 let batch_count = batches.len();
376 for (batch_index, batch) in batches.into_iter().enumerate() {
377 // Per spec, the initial first_blocknum needs to be <= the query's first_blocknum.
378 // Use the query's values since we don't use pre-processed reply ranges.
379 let first_blocknum = if batch_index == 0 {
382 // Subsequent replies must be >= the last sent first_blocknum. Use the first block
383 // in the new batch. Batches beyond the first one cannot be empty.
385 block_from_scid(batch.first().unwrap())
388 // Per spec, the last end_blocknum needs to be >= the query's end_blocknum. Last
389 // reply calculates difference between the query's end_blocknum and the start of the reply.
390 // Overflow safe since end_blocknum=msg.first_block_num+msg.number_of_blocks and first_blocknum
391 // will be either msg.first_blocknum or a higher block height.
392 let number_of_blocks = if batch_index == batch_count-1 {
393 msg.end_blocknum() - first_blocknum
395 // Prior replies should use the number of blocks that fit into the reply. Overflow
396 // safe since first_blocknum is always <= last SCID's block.
398 block_from_scid(batch.last().unwrap()) - first_blocknum + 1
401 // Only true for the last message in a sequence
402 let sync_complete = batch_index == batch_count - 1;
404 pending_events.push(MessageSendEvent::SendReplyChannelRange {
405 node_id: their_node_id.clone(),
406 msg: ReplyChannelRange {
407 chain_hash: msg.chain_hash.clone(),
411 short_channel_ids: batch,
419 fn handle_query_short_channel_ids(&self, _their_node_id: &PublicKey, _msg: QueryShortChannelIds) -> Result<(), LightningError> {
422 err: String::from("Not implemented"),
423 action: ErrorAction::IgnoreError,
428 impl<C: Deref, L: Deref> MessageSendEventsProvider for NetGraphMsgHandler<C, L>
430 C::Target: chain::Access,
433 fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> {
434 let mut ret = Vec::new();
435 let mut pending_events = self.pending_events.lock().unwrap();
436 std::mem::swap(&mut ret, &mut pending_events);
441 #[derive(Clone, Debug, PartialEq)]
442 /// Details about one direction of a channel. Received
443 /// within a channel update.
444 pub struct DirectionalChannelInfo {
445 /// When the last update to the channel direction was issued.
446 /// Value is opaque, as set in the announcement.
447 pub last_update: u32,
448 /// Whether the channel can be currently used for payments (in this one direction).
450 /// The difference in CLTV values that you must have when routing through this channel.
451 pub cltv_expiry_delta: u16,
452 /// The minimum value, which must be relayed to the next hop via the channel
453 pub htlc_minimum_msat: u64,
454 /// The maximum value which may be relayed to the next hop via the channel.
455 pub htlc_maximum_msat: Option<u64>,
456 /// Fees charged when the channel is used for routing
457 pub fees: RoutingFees,
458 /// Most recent update for the channel received from the network
459 /// Mostly redundant with the data we store in fields explicitly.
460 /// Everything else is useful only for sending out for initial routing sync.
461 /// Not stored if contains excess data to prevent DoS.
462 pub last_update_message: Option<ChannelUpdate>,
465 impl fmt::Display for DirectionalChannelInfo {
466 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
467 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)?;
472 impl_writeable!(DirectionalChannelInfo, 0, {
482 #[derive(Clone, Debug, PartialEq)]
483 /// Details about a channel (both directions).
484 /// Received within a channel announcement.
485 pub struct ChannelInfo {
486 /// Protocol features of a channel communicated during its announcement
487 pub features: ChannelFeatures,
488 /// Source node of the first direction of a channel
489 pub node_one: PublicKey,
490 /// Details about the first direction of a channel
491 pub one_to_two: Option<DirectionalChannelInfo>,
492 /// Source node of the second direction of a channel
493 pub node_two: PublicKey,
494 /// Details about the second direction of a channel
495 pub two_to_one: Option<DirectionalChannelInfo>,
496 /// The channel capacity as seen on-chain, if chain lookup is available.
497 pub capacity_sats: Option<u64>,
498 /// An initial announcement of the channel
499 /// Mostly redundant with the data we store in fields explicitly.
500 /// Everything else is useful only for sending out for initial routing sync.
501 /// Not stored if contains excess data to prevent DoS.
502 pub announcement_message: Option<ChannelAnnouncement>,
505 impl fmt::Display for ChannelInfo {
506 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
507 write!(f, "features: {}, node_one: {}, one_to_two: {:?}, node_two: {}, two_to_one: {:?}",
508 log_bytes!(self.features.encode()), log_pubkey!(self.node_one), self.one_to_two, log_pubkey!(self.node_two), self.two_to_one)?;
513 impl_writeable!(ChannelInfo, 0, {
524 /// Fees for routing via a given channel or a node
525 #[derive(Eq, PartialEq, Copy, Clone, Debug)]
526 pub struct RoutingFees {
527 /// Flat routing fee in satoshis
529 /// Liquidity-based routing fee in millionths of a routed amount.
530 /// In other words, 10000 is 1%.
531 pub proportional_millionths: u32,
534 impl Readable for RoutingFees{
535 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<RoutingFees, DecodeError> {
536 let base_msat: u32 = Readable::read(reader)?;
537 let proportional_millionths: u32 = Readable::read(reader)?;
540 proportional_millionths,
545 impl Writeable for RoutingFees {
546 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
547 self.base_msat.write(writer)?;
548 self.proportional_millionths.write(writer)?;
553 #[derive(Clone, Debug, PartialEq)]
554 /// Information received in the latest node_announcement from this node.
555 pub struct NodeAnnouncementInfo {
556 /// Protocol features the node announced support for
557 pub features: NodeFeatures,
558 /// When the last known update to the node state was issued.
559 /// Value is opaque, as set in the announcement.
560 pub last_update: u32,
561 /// Color assigned to the node
563 /// Moniker assigned to the node.
564 /// May be invalid or malicious (eg control chars),
565 /// should not be exposed to the user.
567 /// Internet-level addresses via which one can connect to the node
568 pub addresses: Vec<NetAddress>,
569 /// An initial announcement of the node
570 /// Mostly redundant with the data we store in fields explicitly.
571 /// Everything else is useful only for sending out for initial routing sync.
572 /// Not stored if contains excess data to prevent DoS.
573 pub announcement_message: Option<NodeAnnouncement>
576 impl Writeable for NodeAnnouncementInfo {
577 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
578 self.features.write(writer)?;
579 self.last_update.write(writer)?;
580 self.rgb.write(writer)?;
581 self.alias.write(writer)?;
582 (self.addresses.len() as u64).write(writer)?;
583 for ref addr in &self.addresses {
586 self.announcement_message.write(writer)?;
591 impl Readable for NodeAnnouncementInfo {
592 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NodeAnnouncementInfo, DecodeError> {
593 let features = Readable::read(reader)?;
594 let last_update = Readable::read(reader)?;
595 let rgb = Readable::read(reader)?;
596 let alias = Readable::read(reader)?;
597 let addresses_count: u64 = Readable::read(reader)?;
598 let mut addresses = Vec::with_capacity(cmp::min(addresses_count, MAX_ALLOC_SIZE / 40) as usize);
599 for _ in 0..addresses_count {
600 match Readable::read(reader) {
601 Ok(Ok(addr)) => { addresses.push(addr); },
602 Ok(Err(_)) => return Err(DecodeError::InvalidValue),
603 Err(DecodeError::ShortRead) => return Err(DecodeError::BadLengthDescriptor),
607 let announcement_message = Readable::read(reader)?;
608 Ok(NodeAnnouncementInfo {
619 #[derive(Clone, Debug, PartialEq)]
620 /// Details about a node in the network, known from the network announcement.
621 pub struct NodeInfo {
622 /// All valid channels a node has announced
623 pub channels: Vec<u64>,
624 /// Lowest fees enabling routing via any of the enabled, known channels to a node.
625 /// The two fields (flat and proportional fee) are independent,
626 /// meaning they don't have to refer to the same channel.
627 pub lowest_inbound_channel_fees: Option<RoutingFees>,
628 /// More information about a node from node_announcement.
629 /// Optional because we store a Node entry after learning about it from
630 /// a channel announcement, but before receiving a node announcement.
631 pub announcement_info: Option<NodeAnnouncementInfo>
634 impl fmt::Display for NodeInfo {
635 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
636 write!(f, "lowest_inbound_channel_fees: {:?}, channels: {:?}, announcement_info: {:?}",
637 self.lowest_inbound_channel_fees, &self.channels[..], self.announcement_info)?;
642 impl Writeable for NodeInfo {
643 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
644 (self.channels.len() as u64).write(writer)?;
645 for ref chan in self.channels.iter() {
648 self.lowest_inbound_channel_fees.write(writer)?;
649 self.announcement_info.write(writer)?;
654 const MAX_ALLOC_SIZE: u64 = 64*1024;
656 impl Readable for NodeInfo {
657 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NodeInfo, DecodeError> {
658 let channels_count: u64 = Readable::read(reader)?;
659 let mut channels = Vec::with_capacity(cmp::min(channels_count, MAX_ALLOC_SIZE / 8) as usize);
660 for _ in 0..channels_count {
661 channels.push(Readable::read(reader)?);
663 let lowest_inbound_channel_fees = Readable::read(reader)?;
664 let announcement_info = Readable::read(reader)?;
667 lowest_inbound_channel_fees,
673 impl Writeable for NetworkGraph {
674 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
675 self.genesis_hash.write(writer)?;
676 (self.channels.len() as u64).write(writer)?;
677 for (ref chan_id, ref chan_info) in self.channels.iter() {
678 (*chan_id).write(writer)?;
679 chan_info.write(writer)?;
681 (self.nodes.len() as u64).write(writer)?;
682 for (ref node_id, ref node_info) in self.nodes.iter() {
683 node_id.write(writer)?;
684 node_info.write(writer)?;
690 impl Readable for NetworkGraph {
691 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NetworkGraph, DecodeError> {
692 let genesis_hash: BlockHash = Readable::read(reader)?;
693 let channels_count: u64 = Readable::read(reader)?;
694 let mut channels = BTreeMap::new();
695 for _ in 0..channels_count {
696 let chan_id: u64 = Readable::read(reader)?;
697 let chan_info = Readable::read(reader)?;
698 channels.insert(chan_id, chan_info);
700 let nodes_count: u64 = Readable::read(reader)?;
701 let mut nodes = BTreeMap::new();
702 for _ in 0..nodes_count {
703 let node_id = Readable::read(reader)?;
704 let node_info = Readable::read(reader)?;
705 nodes.insert(node_id, node_info);
715 impl fmt::Display for NetworkGraph {
716 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
717 writeln!(f, "Network map\n[Channels]")?;
718 for (key, val) in self.channels.iter() {
719 writeln!(f, " {}: {}", key, val)?;
721 writeln!(f, "[Nodes]")?;
722 for (key, val) in self.nodes.iter() {
723 writeln!(f, " {}: {}", log_pubkey!(key), val)?;
730 /// Returns all known valid channels' short ids along with announced channel info.
732 /// (C-not exported) because we have no mapping for `BTreeMap`s
733 pub fn get_channels<'a>(&'a self) -> &'a BTreeMap<u64, ChannelInfo> { &self.channels }
734 /// Returns all known nodes' public keys along with announced node info.
736 /// (C-not exported) because we have no mapping for `BTreeMap`s
737 pub fn get_nodes<'a>(&'a self) -> &'a BTreeMap<PublicKey, NodeInfo> { &self.nodes }
739 /// Get network addresses by node id.
740 /// Returns None if the requested node is completely unknown,
741 /// or if node announcement for the node was never received.
743 /// (C-not exported) as there is no practical way to track lifetimes of returned values.
744 pub fn get_addresses<'a>(&'a self, pubkey: &PublicKey) -> Option<&'a Vec<NetAddress>> {
745 if let Some(node) = self.nodes.get(pubkey) {
746 if let Some(node_info) = node.announcement_info.as_ref() {
747 return Some(&node_info.addresses)
753 /// Creates a new, empty, network graph.
754 pub fn new(genesis_hash: BlockHash) -> NetworkGraph {
757 channels: BTreeMap::new(),
758 nodes: BTreeMap::new(),
762 /// For an already known node (from channel announcements), update its stored properties from a
763 /// given node announcement.
765 /// You probably don't want to call this directly, instead relying on a NetGraphMsgHandler's
766 /// RoutingMessageHandler implementation to call it indirectly. This may be useful to accept
767 /// routing messages from a source using a protocol other than the lightning P2P protocol.
768 pub fn update_node_from_announcement<T: secp256k1::Verification>(&mut self, msg: &msgs::NodeAnnouncement, secp_ctx: &Secp256k1<T>) -> Result<(), LightningError> {
769 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
770 secp_verify_sig!(secp_ctx, &msg_hash, &msg.signature, &msg.contents.node_id);
771 self.update_node_from_announcement_intern(&msg.contents, Some(&msg))
774 /// For an already known node (from channel announcements), update its stored properties from a
775 /// given node announcement without verifying the associated signatures. Because we aren't
776 /// given the associated signatures here we cannot relay the node announcement to any of our
778 pub fn update_node_from_unsigned_announcement(&mut self, msg: &msgs::UnsignedNodeAnnouncement) -> Result<(), LightningError> {
779 self.update_node_from_announcement_intern(msg, None)
782 fn update_node_from_announcement_intern(&mut self, msg: &msgs::UnsignedNodeAnnouncement, full_msg: Option<&msgs::NodeAnnouncement>) -> Result<(), LightningError> {
783 match self.nodes.get_mut(&msg.node_id) {
784 None => Err(LightningError{err: "No existing channels for node_announcement".to_owned(), action: ErrorAction::IgnoreError}),
786 if let Some(node_info) = node.announcement_info.as_ref() {
787 if node_info.last_update >= msg.timestamp {
788 return Err(LightningError{err: "Update older than last processed update".to_owned(), action: ErrorAction::IgnoreError});
793 msg.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY &&
794 msg.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY &&
795 msg.excess_data.len() + msg.excess_address_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY;
796 node.announcement_info = Some(NodeAnnouncementInfo {
797 features: msg.features.clone(),
798 last_update: msg.timestamp,
801 addresses: msg.addresses.clone(),
802 announcement_message: if should_relay { full_msg.cloned() } else { None },
810 /// Store or update channel info from a channel announcement.
812 /// You probably don't want to call this directly, instead relying on a NetGraphMsgHandler's
813 /// RoutingMessageHandler implementation to call it indirectly. This may be useful to accept
814 /// routing messages from a source using a protocol other than the lightning P2P protocol.
816 /// If a `chain::Access` object is provided via `chain_access`, it will be called to verify
817 /// the corresponding UTXO exists on chain and is correctly-formatted.
818 pub fn update_channel_from_announcement<T: secp256k1::Verification, C: Deref>
819 (&mut self, msg: &msgs::ChannelAnnouncement, chain_access: &Option<C>, secp_ctx: &Secp256k1<T>)
820 -> Result<(), LightningError>
821 where C::Target: chain::Access {
822 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
823 secp_verify_sig!(secp_ctx, &msg_hash, &msg.node_signature_1, &msg.contents.node_id_1);
824 secp_verify_sig!(secp_ctx, &msg_hash, &msg.node_signature_2, &msg.contents.node_id_2);
825 secp_verify_sig!(secp_ctx, &msg_hash, &msg.bitcoin_signature_1, &msg.contents.bitcoin_key_1);
826 secp_verify_sig!(secp_ctx, &msg_hash, &msg.bitcoin_signature_2, &msg.contents.bitcoin_key_2);
827 self.update_channel_from_unsigned_announcement_intern(&msg.contents, Some(msg), chain_access)
830 /// Store or update channel info from a channel announcement without verifying the associated
831 /// signatures. Because we aren't given the associated signatures here we cannot relay the
832 /// channel announcement to any of our peers.
834 /// If a `chain::Access` object is provided via `chain_access`, it will be called to verify
835 /// the corresponding UTXO exists on chain and is correctly-formatted.
836 pub fn update_channel_from_unsigned_announcement<C: Deref>
837 (&mut self, msg: &msgs::UnsignedChannelAnnouncement, chain_access: &Option<C>)
838 -> Result<(), LightningError>
839 where C::Target: chain::Access {
840 self.update_channel_from_unsigned_announcement_intern(msg, None, chain_access)
843 fn update_channel_from_unsigned_announcement_intern<C: Deref>
844 (&mut self, msg: &msgs::UnsignedChannelAnnouncement, full_msg: Option<&msgs::ChannelAnnouncement>, chain_access: &Option<C>)
845 -> Result<(), LightningError>
846 where C::Target: chain::Access {
847 if msg.node_id_1 == msg.node_id_2 || msg.bitcoin_key_1 == msg.bitcoin_key_2 {
848 return Err(LightningError{err: "Channel announcement node had a channel with itself".to_owned(), action: ErrorAction::IgnoreError});
851 let utxo_value = match &chain_access {
853 // Tentatively accept, potentially exposing us to DoS attacks
856 &Some(ref chain_access) => {
857 match chain_access.get_utxo(&msg.chain_hash, msg.short_channel_id) {
858 Ok(TxOut { value, script_pubkey }) => {
859 let expected_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
860 .push_slice(&msg.bitcoin_key_1.serialize())
861 .push_slice(&msg.bitcoin_key_2.serialize())
862 .push_opcode(opcodes::all::OP_PUSHNUM_2)
863 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
864 if script_pubkey != expected_script {
865 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});
867 //TODO: Check if value is worth storing, use it to inform routing, and compare it
868 //to the new HTLC max field in channel_update
871 Err(chain::AccessError::UnknownChain) => {
872 return Err(LightningError{err: format!("Channel announced on an unknown chain ({})", msg.chain_hash.encode().to_hex()), action: ErrorAction::IgnoreError});
874 Err(chain::AccessError::UnknownTx) => {
875 return Err(LightningError{err: "Channel announced without corresponding UTXO entry".to_owned(), action: ErrorAction::IgnoreError});
881 let chan_info = ChannelInfo {
882 features: msg.features.clone(),
883 node_one: msg.node_id_1.clone(),
885 node_two: msg.node_id_2.clone(),
887 capacity_sats: utxo_value,
888 announcement_message: if msg.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY
889 { full_msg.cloned() } else { None },
892 match self.channels.entry(msg.short_channel_id) {
893 BtreeEntry::Occupied(mut entry) => {
894 //TODO: because asking the blockchain if short_channel_id is valid is only optional
895 //in the blockchain API, we need to handle it smartly here, though it's unclear
897 if utxo_value.is_some() {
898 // Either our UTXO provider is busted, there was a reorg, or the UTXO provider
899 // only sometimes returns results. In any case remove the previous entry. Note
900 // that the spec expects us to "blacklist" the node_ids involved, but we can't
902 // a) we don't *require* a UTXO provider that always returns results.
903 // b) we don't track UTXOs of channels we know about and remove them if they
905 // c) it's unclear how to do so without exposing ourselves to massive DoS risk.
906 Self::remove_channel_in_nodes(&mut self.nodes, &entry.get(), msg.short_channel_id);
907 *entry.get_mut() = chan_info;
909 return Err(LightningError{err: "Already have knowledge of channel".to_owned(), action: ErrorAction::IgnoreError})
912 BtreeEntry::Vacant(entry) => {
913 entry.insert(chan_info);
917 macro_rules! add_channel_to_node {
918 ( $node_id: expr ) => {
919 match self.nodes.entry($node_id) {
920 BtreeEntry::Occupied(node_entry) => {
921 node_entry.into_mut().channels.push(msg.short_channel_id);
923 BtreeEntry::Vacant(node_entry) => {
924 node_entry.insert(NodeInfo {
925 channels: vec!(msg.short_channel_id),
926 lowest_inbound_channel_fees: None,
927 announcement_info: None,
934 add_channel_to_node!(msg.node_id_1);
935 add_channel_to_node!(msg.node_id_2);
940 /// Close a channel if a corresponding HTLC fail was sent.
941 /// If permanent, removes a channel from the local storage.
942 /// May cause the removal of nodes too, if this was their last channel.
943 /// If not permanent, makes channels unavailable for routing.
944 pub fn close_channel_from_update(&mut self, short_channel_id: u64, is_permanent: bool) {
946 if let Some(chan) = self.channels.remove(&short_channel_id) {
947 Self::remove_channel_in_nodes(&mut self.nodes, &chan, short_channel_id);
950 if let Some(chan) = self.channels.get_mut(&short_channel_id) {
951 if let Some(one_to_two) = chan.one_to_two.as_mut() {
952 one_to_two.enabled = false;
954 if let Some(two_to_one) = chan.two_to_one.as_mut() {
955 two_to_one.enabled = false;
961 fn fail_node(&mut self, _node_id: &PublicKey, is_permanent: bool) {
963 // TODO: Wholly remove the node
965 // TODO: downgrade the node
969 /// For an already known (from announcement) channel, update info about one of the directions
972 /// You probably don't want to call this directly, instead relying on a NetGraphMsgHandler's
973 /// RoutingMessageHandler implementation to call it indirectly. This may be useful to accept
974 /// routing messages from a source using a protocol other than the lightning P2P protocol.
975 pub fn update_channel<T: secp256k1::Verification>(&mut self, msg: &msgs::ChannelUpdate, secp_ctx: &Secp256k1<T>) -> Result<(), LightningError> {
976 self.update_channel_intern(&msg.contents, Some(&msg), Some((&msg.signature, secp_ctx)))
979 /// For an already known (from announcement) channel, update info about one of the directions
980 /// of the channel without verifying the associated signatures. Because we aren't given the
981 /// associated signatures here we cannot relay the channel update to any of our peers.
982 pub fn update_channel_unsigned(&mut self, msg: &msgs::UnsignedChannelUpdate) -> Result<(), LightningError> {
983 self.update_channel_intern(msg, None, None::<(&secp256k1::Signature, &Secp256k1<secp256k1::VerifyOnly>)>)
986 fn update_channel_intern<T: secp256k1::Verification>(&mut self, msg: &msgs::UnsignedChannelUpdate, full_msg: Option<&msgs::ChannelUpdate>, sig_info: Option<(&secp256k1::Signature, &Secp256k1<T>)>) -> Result<(), LightningError> {
988 let chan_enabled = msg.flags & (1 << 1) != (1 << 1);
989 let chan_was_enabled;
991 match self.channels.get_mut(&msg.short_channel_id) {
992 None => return Err(LightningError{err: "Couldn't find channel for update".to_owned(), action: ErrorAction::IgnoreError}),
994 if let OptionalField::Present(htlc_maximum_msat) = msg.htlc_maximum_msat {
995 if htlc_maximum_msat > MAX_VALUE_MSAT {
996 return Err(LightningError{err: "htlc_maximum_msat is larger than maximum possible msats".to_owned(), action: ErrorAction::IgnoreError});
999 if let Some(capacity_sats) = channel.capacity_sats {
1000 // It's possible channel capacity is available now, although it wasn't available at announcement (so the field is None).
1001 // Don't query UTXO set here to reduce DoS risks.
1002 if capacity_sats > MAX_VALUE_MSAT / 1000 || htlc_maximum_msat > capacity_sats * 1000 {
1003 return Err(LightningError{err: "htlc_maximum_msat is larger than channel capacity or capacity is bogus".to_owned(), action: ErrorAction::IgnoreError});
1007 macro_rules! maybe_update_channel_info {
1008 ( $target: expr, $src_node: expr) => {
1009 if let Some(existing_chan_info) = $target.as_ref() {
1010 if existing_chan_info.last_update >= msg.timestamp {
1011 return Err(LightningError{err: "Update older than last processed update".to_owned(), action: ErrorAction::IgnoreError});
1013 chan_was_enabled = existing_chan_info.enabled;
1015 chan_was_enabled = false;
1018 let last_update_message = if msg.excess_data.len() <= MAX_EXCESS_BYTES_FOR_RELAY
1019 { full_msg.cloned() } else { None };
1021 let updated_channel_dir_info = DirectionalChannelInfo {
1022 enabled: chan_enabled,
1023 last_update: msg.timestamp,
1024 cltv_expiry_delta: msg.cltv_expiry_delta,
1025 htlc_minimum_msat: msg.htlc_minimum_msat,
1026 htlc_maximum_msat: if let OptionalField::Present(max_value) = msg.htlc_maximum_msat { Some(max_value) } else { None },
1028 base_msat: msg.fee_base_msat,
1029 proportional_millionths: msg.fee_proportional_millionths,
1033 $target = Some(updated_channel_dir_info);
1037 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.encode()[..])[..]);
1038 if msg.flags & 1 == 1 {
1039 dest_node_id = channel.node_one.clone();
1040 if let Some((sig, ctx)) = sig_info {
1041 secp_verify_sig!(ctx, &msg_hash, &sig, &channel.node_two);
1043 maybe_update_channel_info!(channel.two_to_one, channel.node_two);
1045 dest_node_id = channel.node_two.clone();
1046 if let Some((sig, ctx)) = sig_info {
1047 secp_verify_sig!(ctx, &msg_hash, &sig, &channel.node_one);
1049 maybe_update_channel_info!(channel.one_to_two, channel.node_one);
1055 let node = self.nodes.get_mut(&dest_node_id).unwrap();
1056 let mut base_msat = msg.fee_base_msat;
1057 let mut proportional_millionths = msg.fee_proportional_millionths;
1058 if let Some(fees) = node.lowest_inbound_channel_fees {
1059 base_msat = cmp::min(base_msat, fees.base_msat);
1060 proportional_millionths = cmp::min(proportional_millionths, fees.proportional_millionths);
1062 node.lowest_inbound_channel_fees = Some(RoutingFees {
1064 proportional_millionths
1066 } else if chan_was_enabled {
1067 let node = self.nodes.get_mut(&dest_node_id).unwrap();
1068 let mut lowest_inbound_channel_fees = None;
1070 for chan_id in node.channels.iter() {
1071 let chan = self.channels.get(chan_id).unwrap();
1073 if chan.node_one == dest_node_id {
1074 chan_info_opt = chan.two_to_one.as_ref();
1076 chan_info_opt = chan.one_to_two.as_ref();
1078 if let Some(chan_info) = chan_info_opt {
1079 if chan_info.enabled {
1080 let fees = lowest_inbound_channel_fees.get_or_insert(RoutingFees {
1081 base_msat: u32::max_value(), proportional_millionths: u32::max_value() });
1082 fees.base_msat = cmp::min(fees.base_msat, chan_info.fees.base_msat);
1083 fees.proportional_millionths = cmp::min(fees.proportional_millionths, chan_info.fees.proportional_millionths);
1088 node.lowest_inbound_channel_fees = lowest_inbound_channel_fees;
1094 fn remove_channel_in_nodes(nodes: &mut BTreeMap<PublicKey, NodeInfo>, chan: &ChannelInfo, short_channel_id: u64) {
1095 macro_rules! remove_from_node {
1096 ($node_id: expr) => {
1097 if let BtreeEntry::Occupied(mut entry) = nodes.entry($node_id) {
1098 entry.get_mut().channels.retain(|chan_id| {
1099 short_channel_id != *chan_id
1101 if entry.get().channels.is_empty() {
1102 entry.remove_entry();
1105 panic!("Had channel that pointed to unknown node (ie inconsistent network map)!");
1110 remove_from_node!(chan.node_one);
1111 remove_from_node!(chan.node_two);
1118 use ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
1119 use routing::network_graph::{NetGraphMsgHandler, NetworkGraph, MAX_EXCESS_BYTES_FOR_RELAY};
1120 use ln::msgs::{Init, OptionalField, RoutingMessageHandler, UnsignedNodeAnnouncement, NodeAnnouncement,
1121 UnsignedChannelAnnouncement, ChannelAnnouncement, UnsignedChannelUpdate, ChannelUpdate, HTLCFailChannelUpdate,
1122 ReplyChannelRange, ReplyShortChannelIdsEnd, QueryChannelRange, QueryShortChannelIds, MAX_VALUE_MSAT};
1123 use util::test_utils;
1124 use util::logger::Logger;
1125 use util::ser::{Readable, Writeable};
1126 use util::events::{MessageSendEvent, MessageSendEventsProvider};
1127 use util::scid_utils::scid_from_parts;
1129 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
1130 use bitcoin::hashes::Hash;
1131 use bitcoin::network::constants::Network;
1132 use bitcoin::blockdata::constants::genesis_block;
1133 use bitcoin::blockdata::script::Builder;
1134 use bitcoin::blockdata::transaction::TxOut;
1135 use bitcoin::blockdata::opcodes;
1139 use bitcoin::secp256k1::key::{PublicKey, SecretKey};
1140 use bitcoin::secp256k1::{All, Secp256k1};
1144 fn create_net_graph_msg_handler() -> (Secp256k1<All>, NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>) {
1145 let secp_ctx = Secp256k1::new();
1146 let logger = Arc::new(test_utils::TestLogger::new());
1147 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
1148 let net_graph_msg_handler = NetGraphMsgHandler::new(genesis_hash, None, Arc::clone(&logger));
1149 (secp_ctx, net_graph_msg_handler)
1153 fn request_full_sync_finite_times() {
1154 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1155 let node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap()[..]).unwrap());
1157 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1158 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1159 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1160 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1161 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1162 assert!(!net_graph_msg_handler.should_request_full_sync(&node_id));
1166 fn handling_node_announcements() {
1167 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1169 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1170 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1171 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1172 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1173 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1174 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1175 let zero_hash = Sha256dHash::hash(&[0; 32]);
1176 let first_announcement_time = 500;
1178 let mut unsigned_announcement = UnsignedNodeAnnouncement {
1179 features: NodeFeatures::known(),
1180 timestamp: first_announcement_time,
1184 addresses: Vec::new(),
1185 excess_address_data: Vec::new(),
1186 excess_data: Vec::new(),
1188 let mut msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1189 let valid_announcement = NodeAnnouncement {
1190 signature: secp_ctx.sign(&msghash, node_1_privkey),
1191 contents: unsigned_announcement.clone()
1194 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1196 Err(e) => assert_eq!("No existing channels for node_announcement", e.err)
1200 // Announce a channel to add a corresponding node.
1201 let unsigned_announcement = UnsignedChannelAnnouncement {
1202 features: ChannelFeatures::known(),
1203 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1204 short_channel_id: 0,
1207 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1208 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1209 excess_data: Vec::new(),
1212 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1213 let valid_announcement = ChannelAnnouncement {
1214 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1215 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1216 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1217 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1218 contents: unsigned_announcement.clone(),
1220 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1221 Ok(res) => assert!(res),
1226 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1227 Ok(res) => assert!(res),
1231 let fake_msghash = hash_to_message!(&zero_hash);
1232 match net_graph_msg_handler.handle_node_announcement(
1234 signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
1235 contents: unsigned_announcement.clone()
1238 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1241 unsigned_announcement.timestamp += 1000;
1242 unsigned_announcement.excess_data.resize(MAX_EXCESS_BYTES_FOR_RELAY + 1, 0);
1243 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1244 let announcement_with_data = NodeAnnouncement {
1245 signature: secp_ctx.sign(&msghash, node_1_privkey),
1246 contents: unsigned_announcement.clone()
1248 // Return false because contains excess data.
1249 match net_graph_msg_handler.handle_node_announcement(&announcement_with_data) {
1250 Ok(res) => assert!(!res),
1253 unsigned_announcement.excess_data = Vec::new();
1255 // Even though previous announcement was not relayed further, we still accepted it,
1256 // so we now won't accept announcements before the previous one.
1257 unsigned_announcement.timestamp -= 10;
1258 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1259 let outdated_announcement = NodeAnnouncement {
1260 signature: secp_ctx.sign(&msghash, node_1_privkey),
1261 contents: unsigned_announcement.clone()
1263 match net_graph_msg_handler.handle_node_announcement(&outdated_announcement) {
1265 Err(e) => assert_eq!(e.err, "Update older than last processed update")
1270 fn handling_channel_announcements() {
1271 let secp_ctx = Secp256k1::new();
1272 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
1274 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1275 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1276 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1277 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1278 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1279 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1281 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
1282 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_1_btckey).serialize())
1283 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_2_btckey).serialize())
1284 .push_opcode(opcodes::all::OP_PUSHNUM_2)
1285 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
1288 let mut unsigned_announcement = UnsignedChannelAnnouncement {
1289 features: ChannelFeatures::known(),
1290 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1291 short_channel_id: 0,
1294 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1295 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1296 excess_data: Vec::new(),
1299 let mut msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1300 let valid_announcement = ChannelAnnouncement {
1301 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1302 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1303 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1304 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1305 contents: unsigned_announcement.clone(),
1308 // Test if the UTXO lookups were not supported
1309 let mut net_graph_msg_handler = NetGraphMsgHandler::new(genesis_block(Network::Testnet).header.block_hash(), None, Arc::clone(&logger));
1310 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1311 Ok(res) => assert!(res),
1316 let network = net_graph_msg_handler.network_graph.read().unwrap();
1317 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1323 // If we receive announcement for the same channel (with UTXO lookups disabled),
1324 // drop new one on the floor, since we can't see any changes.
1325 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1327 Err(e) => assert_eq!(e.err, "Already have knowledge of channel")
1330 // Test if an associated transaction were not on-chain (or not confirmed).
1331 let chain_source = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1332 *chain_source.utxo_ret.lock().unwrap() = Err(chain::AccessError::UnknownTx);
1333 net_graph_msg_handler = NetGraphMsgHandler::new(chain_source.clone().genesis_hash, Some(chain_source.clone()), Arc::clone(&logger));
1334 unsigned_announcement.short_channel_id += 1;
1336 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1337 let valid_announcement = ChannelAnnouncement {
1338 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1339 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1340 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1341 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1342 contents: unsigned_announcement.clone(),
1345 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1347 Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1350 // Now test if the transaction is found in the UTXO set and the script is correct.
1351 unsigned_announcement.short_channel_id += 1;
1352 *chain_source.utxo_ret.lock().unwrap() = Ok(TxOut { value: 0, script_pubkey: good_script.clone() });
1354 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1355 let valid_announcement = ChannelAnnouncement {
1356 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1357 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1358 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1359 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1360 contents: unsigned_announcement.clone(),
1362 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1363 Ok(res) => assert!(res),
1368 let network = net_graph_msg_handler.network_graph.read().unwrap();
1369 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1375 // If we receive announcement for the same channel (but TX is not confirmed),
1376 // drop new one on the floor, since we can't see any changes.
1377 *chain_source.utxo_ret.lock().unwrap() = Err(chain::AccessError::UnknownTx);
1378 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1380 Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1383 // But if it is confirmed, replace the channel
1384 *chain_source.utxo_ret.lock().unwrap() = Ok(TxOut { value: 0, script_pubkey: good_script });
1385 unsigned_announcement.features = ChannelFeatures::empty();
1386 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1387 let valid_announcement = ChannelAnnouncement {
1388 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1389 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1390 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1391 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1392 contents: unsigned_announcement.clone(),
1394 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1395 Ok(res) => assert!(res),
1399 let network = net_graph_msg_handler.network_graph.read().unwrap();
1400 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1401 Some(channel_entry) => {
1402 assert_eq!(channel_entry.features, ChannelFeatures::empty());
1408 // Don't relay valid channels with excess data
1409 unsigned_announcement.short_channel_id += 1;
1410 unsigned_announcement.excess_data.resize(MAX_EXCESS_BYTES_FOR_RELAY + 1, 0);
1411 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1412 let valid_announcement = ChannelAnnouncement {
1413 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1414 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1415 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1416 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1417 contents: unsigned_announcement.clone(),
1419 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1420 Ok(res) => assert!(!res),
1424 unsigned_announcement.excess_data = Vec::new();
1425 let invalid_sig_announcement = ChannelAnnouncement {
1426 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1427 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1428 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1429 bitcoin_signature_2: secp_ctx.sign(&msghash, node_1_btckey),
1430 contents: unsigned_announcement.clone(),
1432 match net_graph_msg_handler.handle_channel_announcement(&invalid_sig_announcement) {
1434 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1437 unsigned_announcement.node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1438 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1439 let channel_to_itself_announcement = ChannelAnnouncement {
1440 node_signature_1: secp_ctx.sign(&msghash, node_2_privkey),
1441 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1442 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1443 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1444 contents: unsigned_announcement.clone(),
1446 match net_graph_msg_handler.handle_channel_announcement(&channel_to_itself_announcement) {
1448 Err(e) => assert_eq!(e.err, "Channel announcement node had a channel with itself")
1453 fn handling_channel_update() {
1454 let secp_ctx = Secp256k1::new();
1455 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
1456 let chain_source = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1457 let net_graph_msg_handler = NetGraphMsgHandler::new(genesis_block(Network::Testnet).header.block_hash(), Some(chain_source.clone()), Arc::clone(&logger));
1459 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1460 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1461 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1462 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1463 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1464 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1466 let zero_hash = Sha256dHash::hash(&[0; 32]);
1467 let short_channel_id = 0;
1468 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1469 let amount_sats = 1000_000;
1472 // Announce a channel we will update
1473 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
1474 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_1_btckey).serialize())
1475 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_2_btckey).serialize())
1476 .push_opcode(opcodes::all::OP_PUSHNUM_2)
1477 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
1478 *chain_source.utxo_ret.lock().unwrap() = Ok(TxOut { value: amount_sats, script_pubkey: good_script.clone() });
1479 let unsigned_announcement = UnsignedChannelAnnouncement {
1480 features: ChannelFeatures::empty(),
1485 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1486 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1487 excess_data: Vec::new(),
1490 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1491 let valid_channel_announcement = ChannelAnnouncement {
1492 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1493 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1494 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1495 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1496 contents: unsigned_announcement.clone(),
1498 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1505 let mut unsigned_channel_update = UnsignedChannelUpdate {
1510 cltv_expiry_delta: 144,
1511 htlc_minimum_msat: 1000000,
1512 htlc_maximum_msat: OptionalField::Absent,
1513 fee_base_msat: 10000,
1514 fee_proportional_millionths: 20,
1515 excess_data: Vec::new()
1517 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1518 let valid_channel_update = ChannelUpdate {
1519 signature: secp_ctx.sign(&msghash, node_1_privkey),
1520 contents: unsigned_channel_update.clone()
1523 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1524 Ok(res) => assert!(res),
1529 let network = net_graph_msg_handler.network_graph.read().unwrap();
1530 match network.get_channels().get(&short_channel_id) {
1532 Some(channel_info) => {
1533 assert_eq!(channel_info.one_to_two.as_ref().unwrap().cltv_expiry_delta, 144);
1534 assert!(channel_info.two_to_one.is_none());
1539 unsigned_channel_update.timestamp += 100;
1540 unsigned_channel_update.excess_data.resize(MAX_EXCESS_BYTES_FOR_RELAY + 1, 0);
1541 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1542 let valid_channel_update = ChannelUpdate {
1543 signature: secp_ctx.sign(&msghash, node_1_privkey),
1544 contents: unsigned_channel_update.clone()
1546 // Return false because contains excess data
1547 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1548 Ok(res) => assert!(!res),
1551 unsigned_channel_update.timestamp += 10;
1553 unsigned_channel_update.short_channel_id += 1;
1554 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1555 let valid_channel_update = ChannelUpdate {
1556 signature: secp_ctx.sign(&msghash, node_1_privkey),
1557 contents: unsigned_channel_update.clone()
1560 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1562 Err(e) => assert_eq!(e.err, "Couldn't find channel for update")
1564 unsigned_channel_update.short_channel_id = short_channel_id;
1566 unsigned_channel_update.htlc_maximum_msat = OptionalField::Present(MAX_VALUE_MSAT + 1);
1567 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1568 let valid_channel_update = ChannelUpdate {
1569 signature: secp_ctx.sign(&msghash, node_1_privkey),
1570 contents: unsigned_channel_update.clone()
1573 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1575 Err(e) => assert_eq!(e.err, "htlc_maximum_msat is larger than maximum possible msats")
1577 unsigned_channel_update.htlc_maximum_msat = OptionalField::Absent;
1579 unsigned_channel_update.htlc_maximum_msat = OptionalField::Present(amount_sats * 1000 + 1);
1580 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1581 let valid_channel_update = ChannelUpdate {
1582 signature: secp_ctx.sign(&msghash, node_1_privkey),
1583 contents: unsigned_channel_update.clone()
1586 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1588 Err(e) => assert_eq!(e.err, "htlc_maximum_msat is larger than channel capacity or capacity is bogus")
1590 unsigned_channel_update.htlc_maximum_msat = OptionalField::Absent;
1592 // Even though previous update was not relayed further, we still accepted it,
1593 // so we now won't accept update before the previous one.
1594 unsigned_channel_update.timestamp -= 10;
1595 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1596 let valid_channel_update = ChannelUpdate {
1597 signature: secp_ctx.sign(&msghash, node_1_privkey),
1598 contents: unsigned_channel_update.clone()
1601 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1603 Err(e) => assert_eq!(e.err, "Update older than last processed update")
1605 unsigned_channel_update.timestamp += 500;
1607 let fake_msghash = hash_to_message!(&zero_hash);
1608 let invalid_sig_channel_update = ChannelUpdate {
1609 signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
1610 contents: unsigned_channel_update.clone()
1613 match net_graph_msg_handler.handle_channel_update(&invalid_sig_channel_update) {
1615 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1621 fn handling_htlc_fail_channel_update() {
1622 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1623 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1624 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1625 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1626 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1627 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1628 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1630 let short_channel_id = 0;
1631 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1634 // There is no nodes in the table at the beginning.
1635 let network = net_graph_msg_handler.network_graph.read().unwrap();
1636 assert_eq!(network.get_nodes().len(), 0);
1640 // Announce a channel we will update
1641 let unsigned_announcement = UnsignedChannelAnnouncement {
1642 features: ChannelFeatures::empty(),
1647 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1648 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1649 excess_data: Vec::new(),
1652 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1653 let valid_channel_announcement = ChannelAnnouncement {
1654 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1655 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1656 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1657 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1658 contents: unsigned_announcement.clone(),
1660 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1665 let unsigned_channel_update = UnsignedChannelUpdate {
1670 cltv_expiry_delta: 144,
1671 htlc_minimum_msat: 1000000,
1672 htlc_maximum_msat: OptionalField::Absent,
1673 fee_base_msat: 10000,
1674 fee_proportional_millionths: 20,
1675 excess_data: Vec::new()
1677 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1678 let valid_channel_update = ChannelUpdate {
1679 signature: secp_ctx.sign(&msghash, node_1_privkey),
1680 contents: unsigned_channel_update.clone()
1683 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1684 Ok(res) => assert!(res),
1689 // Non-permanent closing just disables a channel
1691 let network = net_graph_msg_handler.network_graph.read().unwrap();
1692 match network.get_channels().get(&short_channel_id) {
1694 Some(channel_info) => {
1695 assert!(channel_info.one_to_two.is_some());
1700 let channel_close_msg = HTLCFailChannelUpdate::ChannelClosed {
1705 net_graph_msg_handler.handle_htlc_fail_channel_update(&channel_close_msg);
1707 // Non-permanent closing just disables a channel
1709 let network = net_graph_msg_handler.network_graph.read().unwrap();
1710 match network.get_channels().get(&short_channel_id) {
1712 Some(channel_info) => {
1713 assert!(!channel_info.one_to_two.as_ref().unwrap().enabled);
1718 let channel_close_msg = HTLCFailChannelUpdate::ChannelClosed {
1723 net_graph_msg_handler.handle_htlc_fail_channel_update(&channel_close_msg);
1725 // Permanent closing deletes a channel
1727 let network = net_graph_msg_handler.network_graph.read().unwrap();
1728 assert_eq!(network.get_channels().len(), 0);
1729 // Nodes are also deleted because there are no associated channels anymore
1730 assert_eq!(network.get_nodes().len(), 0);
1732 // TODO: Test HTLCFailChannelUpdate::NodeFailure, which is not implemented yet.
1736 fn getting_next_channel_announcements() {
1737 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1738 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1739 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1740 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1741 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1742 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1743 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1745 let short_channel_id = 1;
1746 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1748 // Channels were not announced yet.
1749 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(0, 1);
1750 assert_eq!(channels_with_announcements.len(), 0);
1753 // Announce a channel we will update
1754 let unsigned_announcement = UnsignedChannelAnnouncement {
1755 features: ChannelFeatures::empty(),
1760 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1761 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1762 excess_data: Vec::new(),
1765 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1766 let valid_channel_announcement = ChannelAnnouncement {
1767 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1768 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1769 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1770 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1771 contents: unsigned_announcement.clone(),
1773 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1779 // Contains initial channel announcement now.
1780 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1781 assert_eq!(channels_with_announcements.len(), 1);
1782 if let Some(channel_announcements) = channels_with_announcements.first() {
1783 let &(_, ref update_1, ref update_2) = channel_announcements;
1784 assert_eq!(update_1, &None);
1785 assert_eq!(update_2, &None);
1792 // Valid channel update
1793 let unsigned_channel_update = UnsignedChannelUpdate {
1798 cltv_expiry_delta: 144,
1799 htlc_minimum_msat: 1000000,
1800 htlc_maximum_msat: OptionalField::Absent,
1801 fee_base_msat: 10000,
1802 fee_proportional_millionths: 20,
1803 excess_data: Vec::new()
1805 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1806 let valid_channel_update = ChannelUpdate {
1807 signature: secp_ctx.sign(&msghash, node_1_privkey),
1808 contents: unsigned_channel_update.clone()
1810 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1816 // Now contains an initial announcement and an update.
1817 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1818 assert_eq!(channels_with_announcements.len(), 1);
1819 if let Some(channel_announcements) = channels_with_announcements.first() {
1820 let &(_, ref update_1, ref update_2) = channel_announcements;
1821 assert_ne!(update_1, &None);
1822 assert_eq!(update_2, &None);
1829 // Channel update with excess data.
1830 let unsigned_channel_update = UnsignedChannelUpdate {
1835 cltv_expiry_delta: 144,
1836 htlc_minimum_msat: 1000000,
1837 htlc_maximum_msat: OptionalField::Absent,
1838 fee_base_msat: 10000,
1839 fee_proportional_millionths: 20,
1840 excess_data: [1; MAX_EXCESS_BYTES_FOR_RELAY + 1].to_vec()
1842 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1843 let valid_channel_update = ChannelUpdate {
1844 signature: secp_ctx.sign(&msghash, node_1_privkey),
1845 contents: unsigned_channel_update.clone()
1847 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1853 // Test that announcements with excess data won't be returned
1854 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
1855 assert_eq!(channels_with_announcements.len(), 1);
1856 if let Some(channel_announcements) = channels_with_announcements.first() {
1857 let &(_, ref update_1, ref update_2) = channel_announcements;
1858 assert_eq!(update_1, &None);
1859 assert_eq!(update_2, &None);
1864 // Further starting point have no channels after it
1865 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id + 1000, 1);
1866 assert_eq!(channels_with_announcements.len(), 0);
1870 fn getting_next_node_announcements() {
1871 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1872 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1873 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1874 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1875 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1876 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1877 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1879 let short_channel_id = 1;
1880 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1883 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 10);
1884 assert_eq!(next_announcements.len(), 0);
1887 // Announce a channel to add 2 nodes
1888 let unsigned_announcement = UnsignedChannelAnnouncement {
1889 features: ChannelFeatures::empty(),
1894 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1895 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1896 excess_data: Vec::new(),
1899 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1900 let valid_channel_announcement = ChannelAnnouncement {
1901 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1902 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1903 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1904 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1905 contents: unsigned_announcement.clone(),
1907 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1914 // Nodes were never announced
1915 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
1916 assert_eq!(next_announcements.len(), 0);
1919 let mut unsigned_announcement = UnsignedNodeAnnouncement {
1920 features: NodeFeatures::known(),
1925 addresses: Vec::new(),
1926 excess_address_data: Vec::new(),
1927 excess_data: Vec::new(),
1929 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1930 let valid_announcement = NodeAnnouncement {
1931 signature: secp_ctx.sign(&msghash, node_1_privkey),
1932 contents: unsigned_announcement.clone()
1934 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1939 unsigned_announcement.node_id = node_id_2;
1940 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1941 let valid_announcement = NodeAnnouncement {
1942 signature: secp_ctx.sign(&msghash, node_2_privkey),
1943 contents: unsigned_announcement.clone()
1946 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1952 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
1953 assert_eq!(next_announcements.len(), 2);
1955 // Skip the first node.
1956 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
1957 assert_eq!(next_announcements.len(), 1);
1960 // Later announcement which should not be relayed (excess data) prevent us from sharing a node
1961 let unsigned_announcement = UnsignedNodeAnnouncement {
1962 features: NodeFeatures::known(),
1967 addresses: Vec::new(),
1968 excess_address_data: Vec::new(),
1969 excess_data: [1; MAX_EXCESS_BYTES_FOR_RELAY + 1].to_vec(),
1971 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1972 let valid_announcement = NodeAnnouncement {
1973 signature: secp_ctx.sign(&msghash, node_2_privkey),
1974 contents: unsigned_announcement.clone()
1976 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1977 Ok(res) => assert!(!res),
1982 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
1983 assert_eq!(next_announcements.len(), 0);
1987 fn network_graph_serialization() {
1988 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1990 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1991 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1992 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1993 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1995 // Announce a channel to add a corresponding node.
1996 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1997 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1998 let unsigned_announcement = UnsignedChannelAnnouncement {
1999 features: ChannelFeatures::known(),
2000 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2001 short_channel_id: 0,
2004 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
2005 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
2006 excess_data: Vec::new(),
2009 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
2010 let valid_announcement = ChannelAnnouncement {
2011 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
2012 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
2013 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
2014 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
2015 contents: unsigned_announcement.clone(),
2017 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
2018 Ok(res) => assert!(res),
2023 let node_id = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
2024 let unsigned_announcement = UnsignedNodeAnnouncement {
2025 features: NodeFeatures::known(),
2030 addresses: Vec::new(),
2031 excess_address_data: Vec::new(),
2032 excess_data: Vec::new(),
2034 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
2035 let valid_announcement = NodeAnnouncement {
2036 signature: secp_ctx.sign(&msghash, node_1_privkey),
2037 contents: unsigned_announcement.clone()
2040 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
2045 let network = net_graph_msg_handler.network_graph.write().unwrap();
2046 let mut w = test_utils::TestVecWriter(Vec::new());
2047 assert!(!network.get_nodes().is_empty());
2048 assert!(!network.get_channels().is_empty());
2049 network.write(&mut w).unwrap();
2050 assert!(<NetworkGraph>::read(&mut ::std::io::Cursor::new(&w.0)).unwrap() == *network);
2054 fn calling_sync_routing_table() {
2055 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
2056 let node_privkey_1 = &SecretKey::from_slice(&[42; 32]).unwrap();
2057 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_privkey_1);
2059 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2060 let first_blocknum = 0;
2061 let number_of_blocks = 0xffff_ffff;
2063 // It should ignore if gossip_queries feature is not enabled
2065 let init_msg = Init { features: InitFeatures::known().clear_gossip_queries() };
2066 net_graph_msg_handler.sync_routing_table(&node_id_1, &init_msg);
2067 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
2068 assert_eq!(events.len(), 0);
2071 // It should send a query_channel_message with the correct information
2073 let init_msg = Init { features: InitFeatures::known() };
2074 net_graph_msg_handler.sync_routing_table(&node_id_1, &init_msg);
2075 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
2076 assert_eq!(events.len(), 1);
2078 MessageSendEvent::SendChannelRangeQuery{ node_id, msg } => {
2079 assert_eq!(node_id, &node_id_1);
2080 assert_eq!(msg.chain_hash, chain_hash);
2081 assert_eq!(msg.first_blocknum, first_blocknum);
2082 assert_eq!(msg.number_of_blocks, number_of_blocks);
2084 _ => panic!("Expected MessageSendEvent::SendChannelRangeQuery")
2088 // It should not enqueue a query when should_request_full_sync return false.
2089 // The initial implementation allows syncing with the first 5 peers after
2090 // which should_request_full_sync will return false
2092 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
2093 let init_msg = Init { features: InitFeatures::known() };
2095 let node_privkey = &SecretKey::from_slice(&[n; 32]).unwrap();
2096 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
2097 net_graph_msg_handler.sync_routing_table(&node_id, &init_msg);
2098 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
2100 assert_eq!(events.len(), 1);
2102 assert_eq!(events.len(), 0);
2110 fn handling_reply_channel_range() {
2111 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
2112 let node_privkey_1 = &SecretKey::from_slice(&[42; 32]).unwrap();
2113 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_privkey_1);
2115 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2117 // Test receipt of a single reply that should enqueue an SCID query
2118 // matching the SCIDs in the reply
2120 let result = net_graph_msg_handler.handle_reply_channel_range(&node_id_1, ReplyChannelRange {
2122 sync_complete: true,
2124 number_of_blocks: 2000,
2125 short_channel_ids: vec![
2126 0x0003e0_000000_0000, // 992x0x0
2127 0x0003e8_000000_0000, // 1000x0x0
2128 0x0003e9_000000_0000, // 1001x0x0
2129 0x0003f0_000000_0000, // 1008x0x0
2130 0x00044c_000000_0000, // 1100x0x0
2131 0x0006e0_000000_0000, // 1760x0x0
2134 assert!(result.is_ok());
2136 // We expect to emit a query_short_channel_ids message with the received scids
2137 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
2138 assert_eq!(events.len(), 1);
2140 MessageSendEvent::SendShortIdsQuery { node_id, msg } => {
2141 assert_eq!(node_id, &node_id_1);
2142 assert_eq!(msg.chain_hash, chain_hash);
2143 assert_eq!(msg.short_channel_ids, vec![
2144 0x0003e0_000000_0000, // 992x0x0
2145 0x0003e8_000000_0000, // 1000x0x0
2146 0x0003e9_000000_0000, // 1001x0x0
2147 0x0003f0_000000_0000, // 1008x0x0
2148 0x00044c_000000_0000, // 1100x0x0
2149 0x0006e0_000000_0000, // 1760x0x0
2152 _ => panic!("expected MessageSendEvent::SendShortIdsQuery"),
2158 fn handling_reply_short_channel_ids() {
2159 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
2160 let node_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2161 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
2163 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2165 // Test receipt of a successful reply
2167 let result = net_graph_msg_handler.handle_reply_short_channel_ids_end(&node_id, ReplyShortChannelIdsEnd {
2169 full_information: true,
2171 assert!(result.is_ok());
2174 // Test receipt of a reply that indicates the peer does not maintain up-to-date information
2175 // for the chain_hash requested in the query.
2177 let result = net_graph_msg_handler.handle_reply_short_channel_ids_end(&node_id, ReplyShortChannelIdsEnd {
2179 full_information: false,
2181 assert!(result.is_err());
2182 assert_eq!(result.err().unwrap().err, "Received reply_short_channel_ids_end with no information");
2187 fn handling_query_channel_range() {
2188 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
2190 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2191 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2192 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2193 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
2194 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
2195 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
2196 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
2197 let bitcoin_key_1 = PublicKey::from_secret_key(&secp_ctx, node_1_btckey);
2198 let bitcoin_key_2 = PublicKey::from_secret_key(&secp_ctx, node_2_btckey);
2200 let mut scids: Vec<u64> = vec![
2201 scid_from_parts(0xfffffe, 0xffffff, 0xffff).unwrap(), // max
2202 scid_from_parts(0xffffff, 0xffffff, 0xffff).unwrap(), // never
2205 // used for testing multipart reply across blocks
2206 for block in 100000..=108001 {
2207 scids.push(scid_from_parts(block, 0, 0).unwrap());
2210 // used for testing resumption on same block
2211 scids.push(scid_from_parts(108001, 1, 0).unwrap());
2212 scids.push(scid_from_parts(108001, 2, 0).unwrap());
2215 let unsigned_announcement = UnsignedChannelAnnouncement {
2216 features: ChannelFeatures::known(),
2217 chain_hash: chain_hash.clone(),
2218 short_channel_id: scid,
2223 excess_data: Vec::new(),
2226 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
2227 let valid_announcement = ChannelAnnouncement {
2228 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
2229 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
2230 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
2231 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
2232 contents: unsigned_announcement.clone(),
2234 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
2240 // Error when number_of_blocks=0
2241 do_handling_query_channel_range(
2242 &net_graph_msg_handler,
2245 chain_hash: chain_hash.clone(),
2247 number_of_blocks: 0,
2250 vec![ReplyChannelRange {
2251 chain_hash: chain_hash.clone(),
2253 number_of_blocks: 0,
2254 sync_complete: true,
2255 short_channel_ids: vec![]
2259 // Error when wrong chain
2260 do_handling_query_channel_range(
2261 &net_graph_msg_handler,
2264 chain_hash: genesis_block(Network::Bitcoin).header.block_hash(),
2266 number_of_blocks: 0xffff_ffff,
2269 vec![ReplyChannelRange {
2270 chain_hash: genesis_block(Network::Bitcoin).header.block_hash(),
2272 number_of_blocks: 0xffff_ffff,
2273 sync_complete: true,
2274 short_channel_ids: vec![],
2278 // Error when first_blocknum > 0xffffff
2279 do_handling_query_channel_range(
2280 &net_graph_msg_handler,
2283 chain_hash: chain_hash.clone(),
2284 first_blocknum: 0x01000000,
2285 number_of_blocks: 0xffff_ffff,
2288 vec![ReplyChannelRange {
2289 chain_hash: chain_hash.clone(),
2290 first_blocknum: 0x01000000,
2291 number_of_blocks: 0xffff_ffff,
2292 sync_complete: true,
2293 short_channel_ids: vec![]
2297 // Empty reply when max valid SCID block num
2298 do_handling_query_channel_range(
2299 &net_graph_msg_handler,
2302 chain_hash: chain_hash.clone(),
2303 first_blocknum: 0xffffff,
2304 number_of_blocks: 1,
2309 chain_hash: chain_hash.clone(),
2310 first_blocknum: 0xffffff,
2311 number_of_blocks: 1,
2312 sync_complete: true,
2313 short_channel_ids: vec![]
2318 // No results in valid query range
2319 do_handling_query_channel_range(
2320 &net_graph_msg_handler,
2323 chain_hash: chain_hash.clone(),
2324 first_blocknum: 0x00800000,
2325 number_of_blocks: 1000,
2330 chain_hash: chain_hash.clone(),
2331 first_blocknum: 0x00800000,
2332 number_of_blocks: 1000,
2333 sync_complete: true,
2334 short_channel_ids: vec![],
2339 // Overflow first_blocknum + number_of_blocks
2340 do_handling_query_channel_range(
2341 &net_graph_msg_handler,
2344 chain_hash: chain_hash.clone(),
2345 first_blocknum: 0xfe0000,
2346 number_of_blocks: 0xffffffff,
2351 chain_hash: chain_hash.clone(),
2352 first_blocknum: 0xfe0000,
2353 number_of_blocks: 0xffffffff - 0xfe0000,
2354 sync_complete: true,
2355 short_channel_ids: vec![
2356 0xfffffe_ffffff_ffff, // max
2362 // Single block exactly full
2363 do_handling_query_channel_range(
2364 &net_graph_msg_handler,
2367 chain_hash: chain_hash.clone(),
2368 first_blocknum: 100000,
2369 number_of_blocks: 8000,
2374 chain_hash: chain_hash.clone(),
2375 first_blocknum: 100000,
2376 number_of_blocks: 8000,
2377 sync_complete: true,
2378 short_channel_ids: (100000..=107999)
2379 .map(|block| scid_from_parts(block, 0, 0).unwrap())
2385 // Multiple split on new block
2386 do_handling_query_channel_range(
2387 &net_graph_msg_handler,
2390 chain_hash: chain_hash.clone(),
2391 first_blocknum: 100000,
2392 number_of_blocks: 8001,
2397 chain_hash: chain_hash.clone(),
2398 first_blocknum: 100000,
2399 number_of_blocks: 8000,
2400 sync_complete: false,
2401 short_channel_ids: (100000..=107999)
2402 .map(|block| scid_from_parts(block, 0, 0).unwrap())
2406 chain_hash: chain_hash.clone(),
2407 first_blocknum: 108000,
2408 number_of_blocks: 1,
2409 sync_complete: true,
2410 short_channel_ids: vec![
2411 scid_from_parts(108000, 0, 0).unwrap(),
2417 // Multiple split on same block
2418 do_handling_query_channel_range(
2419 &net_graph_msg_handler,
2422 chain_hash: chain_hash.clone(),
2423 first_blocknum: 100002,
2424 number_of_blocks: 8000,
2429 chain_hash: chain_hash.clone(),
2430 first_blocknum: 100002,
2431 number_of_blocks: 8000,
2432 sync_complete: false,
2433 short_channel_ids: (100002..=108001)
2434 .map(|block| scid_from_parts(block, 0, 0).unwrap())
2438 chain_hash: chain_hash.clone(),
2439 first_blocknum: 108001,
2440 number_of_blocks: 1,
2441 sync_complete: true,
2442 short_channel_ids: vec![
2443 scid_from_parts(108001, 1, 0).unwrap(),
2444 scid_from_parts(108001, 2, 0).unwrap(),
2451 fn do_handling_query_channel_range(
2452 net_graph_msg_handler: &NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
2453 test_node_id: &PublicKey,
2454 msg: QueryChannelRange,
2456 expected_replies: Vec<ReplyChannelRange>
2458 let result = net_graph_msg_handler.handle_query_channel_range(test_node_id, msg);
2461 assert!(result.is_ok());
2463 assert!(result.is_err());
2466 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
2467 assert_eq!(events.len(), expected_replies.len());
2469 for i in 0..events.len() {
2470 let expected_reply = &expected_replies[i];
2472 MessageSendEvent::SendReplyChannelRange { node_id, msg } => {
2473 assert_eq!(node_id, test_node_id);
2474 assert_eq!(msg.chain_hash, expected_reply.chain_hash);
2475 assert_eq!(msg.first_blocknum, expected_reply.first_blocknum);
2476 assert_eq!(msg.number_of_blocks, expected_reply.number_of_blocks);
2477 assert_eq!(msg.sync_complete, expected_reply.sync_complete);
2478 assert_eq!(msg.short_channel_ids, expected_reply.short_channel_ids);
2480 _ => panic!("expected MessageSendEvent::SendReplyChannelRange"),
2486 fn handling_query_short_channel_ids() {
2487 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
2488 let node_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2489 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
2491 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2493 let result = net_graph_msg_handler.handle_query_short_channel_ids(&node_id, QueryShortChannelIds {
2495 short_channel_ids: vec![0x0003e8_000000_0000],
2497 assert!(result.is_err());