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, 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;
35 use std::sync::{RwLock, RwLockReadGuard};
36 use std::sync::atomic::{AtomicUsize, Ordering};
38 use std::collections::BTreeMap;
39 use std::collections::btree_map::Entry as BtreeEntry;
40 use std::collections::HashMap;
42 use bitcoin::hashes::hex::ToHex;
44 /// Maximum number of short_channel_id values that can be encoded in a
45 /// single reply_channel_range or query_short_channel_ids messages when
46 /// using raw encoding. The maximum value ensures that the 8-byte SCIDs
47 /// fit inside the maximum size of the Lightning message, 65535-bytes.
48 const MAX_SHORT_CHANNEL_ID_BATCH_SIZE: usize = 8000;
50 /// Maximum number of reply_channel_range messages we will allow in
51 /// reply to a query_channel_range. This value creates an upper-limit
52 /// on the number of SCIDs we process in reply to a single query.
53 const MAX_REPLY_CHANNEL_RANGE_PER_QUERY: usize = 250;
55 /// Represents the network as nodes and channels between them
57 pub struct NetworkGraph {
58 genesis_hash: BlockHash,
59 channels: BTreeMap<u64, ChannelInfo>,
60 nodes: BTreeMap<PublicKey, NodeInfo>,
63 /// A simple newtype for RwLockReadGuard<'a, NetworkGraph>.
64 /// This exists only to make accessing a RwLock<NetworkGraph> possible from
65 /// the C bindings, as it can be done directly in Rust code.
66 pub struct LockedNetworkGraph<'a>(pub RwLockReadGuard<'a, NetworkGraph>);
68 /// Receives and validates network updates from peers,
69 /// stores authentic and relevant data as a network graph.
70 /// This network graph is then used for routing payments.
71 /// Provides interface to help with initial routing sync by
72 /// serving historical announcements.
73 pub struct NetGraphMsgHandler<C: Deref, L: Deref> where C::Target: chain::Access, L::Target: Logger {
74 secp_ctx: Secp256k1<secp256k1::VerifyOnly>,
75 /// Representation of the payment channel network
76 pub network_graph: RwLock<NetworkGraph>,
77 chain_access: Option<C>,
78 full_syncs_requested: AtomicUsize,
79 pending_events: Mutex<Vec<events::MessageSendEvent>>,
80 chan_range_query_tasks: Mutex<HashMap<PublicKey, ChanRangeQueryTask>>,
81 scid_query_tasks: Mutex<HashMap<PublicKey, ScidQueryTask>>,
85 impl<C: Deref, L: Deref> NetGraphMsgHandler<C, L> where C::Target: chain::Access, L::Target: Logger {
86 /// Creates a new tracker of the actual state of the network of channels and nodes,
87 /// assuming a fresh network graph.
88 /// Chain monitor is used to make sure announced channels exist on-chain,
89 /// channel data is correct, and that the announcement is signed with
90 /// channel owners' keys.
91 pub fn new(genesis_hash: BlockHash, chain_access: Option<C>, logger: L) -> Self {
93 secp_ctx: Secp256k1::verification_only(),
94 network_graph: RwLock::new(NetworkGraph::new(genesis_hash)),
95 full_syncs_requested: AtomicUsize::new(0),
97 pending_events: Mutex::new(vec![]),
98 chan_range_query_tasks: Mutex::new(HashMap::new()),
99 scid_query_tasks: Mutex::new(HashMap::new()),
104 /// Creates a new tracker of the actual state of the network of channels and nodes,
105 /// assuming an existing Network Graph.
106 pub fn from_net_graph(chain_access: Option<C>, logger: L, network_graph: NetworkGraph) -> Self {
108 secp_ctx: Secp256k1::verification_only(),
109 network_graph: RwLock::new(network_graph),
110 full_syncs_requested: AtomicUsize::new(0),
112 pending_events: Mutex::new(vec![]),
113 chan_range_query_tasks: Mutex::new(HashMap::new()),
114 scid_query_tasks: Mutex::new(HashMap::new()),
119 /// Take a read lock on the network_graph and return it in the C-bindings
120 /// newtype helper. This is likely only useful when called via the C
121 /// bindings as you can call `self.network_graph.read().unwrap()` in Rust
123 pub fn read_locked_graph<'a>(&'a self) -> LockedNetworkGraph<'a> {
124 LockedNetworkGraph(self.network_graph.read().unwrap())
127 /// Enqueues a message send event for a batch of short_channel_ids
129 fn finalize_query_short_ids(&self, task: &mut ScidQueryTask) {
130 let scid_size = std::cmp::min(task.short_channel_ids.len(), MAX_SHORT_CHANNEL_ID_BATCH_SIZE);
131 let mut short_channel_ids: Vec<u64> = Vec::with_capacity(scid_size);
132 for scid in task.short_channel_ids.drain(..scid_size) {
133 short_channel_ids.push(scid);
136 log_debug!(self.logger, "Sending query_short_channel_ids peer={}, batch_size={}", log_pubkey!(task.node_id), scid_size);
138 // enqueue the message to the peer
139 let mut pending_events = self.pending_events.lock().unwrap();
140 pending_events.push(events::MessageSendEvent::SendShortIdsQuery {
141 node_id: task.node_id.clone(),
142 msg: QueryShortChannelIds {
143 chain_hash: task.chain_hash.clone(),
150 impl<'a> LockedNetworkGraph<'a> {
151 /// Get a reference to the NetworkGraph which this read-lock contains.
152 pub fn graph(&self) -> &NetworkGraph {
158 macro_rules! secp_verify_sig {
159 ( $secp_ctx: expr, $msg: expr, $sig: expr, $pubkey: expr ) => {
160 match $secp_ctx.verify($msg, $sig, $pubkey) {
162 Err(_) => return Err(LightningError{err: "Invalid signature from remote node".to_owned(), action: ErrorAction::IgnoreError}),
167 impl<C: Deref + Sync + Send, L: Deref + Sync + Send> RoutingMessageHandler for NetGraphMsgHandler<C, L> where C::Target: chain::Access, L::Target: Logger {
168 fn handle_node_announcement(&self, msg: &msgs::NodeAnnouncement) -> Result<bool, LightningError> {
169 self.network_graph.write().unwrap().update_node_from_announcement(msg, &self.secp_ctx)?;
170 Ok(msg.contents.excess_data.is_empty() && msg.contents.excess_address_data.is_empty())
173 fn handle_channel_announcement(&self, msg: &msgs::ChannelAnnouncement) -> Result<bool, LightningError> {
174 self.network_graph.write().unwrap().update_channel_from_announcement(msg, &self.chain_access, &self.secp_ctx)?;
175 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 { "" });
176 Ok(msg.contents.excess_data.is_empty())
179 fn handle_htlc_fail_channel_update(&self, update: &msgs::HTLCFailChannelUpdate) {
181 &msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg } => {
182 let _ = self.network_graph.write().unwrap().update_channel(msg, &self.secp_ctx);
184 &msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id, is_permanent } => {
185 self.network_graph.write().unwrap().close_channel_from_update(short_channel_id, is_permanent);
187 &msgs::HTLCFailChannelUpdate::NodeFailure { ref node_id, is_permanent } => {
188 self.network_graph.write().unwrap().fail_node(node_id, is_permanent);
193 fn handle_channel_update(&self, msg: &msgs::ChannelUpdate) -> Result<bool, LightningError> {
194 self.network_graph.write().unwrap().update_channel(msg, &self.secp_ctx)?;
195 Ok(msg.contents.excess_data.is_empty())
198 fn get_next_channel_announcements(&self, starting_point: u64, batch_amount: u8) -> Vec<(ChannelAnnouncement, Option<ChannelUpdate>, Option<ChannelUpdate>)> {
199 let network_graph = self.network_graph.read().unwrap();
200 let mut result = Vec::with_capacity(batch_amount as usize);
201 let mut iter = network_graph.get_channels().range(starting_point..);
202 while result.len() < batch_amount as usize {
203 if let Some((_, ref chan)) = iter.next() {
204 if chan.announcement_message.is_some() {
205 let chan_announcement = chan.announcement_message.clone().unwrap();
206 let mut one_to_two_announcement: Option<msgs::ChannelUpdate> = None;
207 let mut two_to_one_announcement: Option<msgs::ChannelUpdate> = None;
208 if let Some(one_to_two) = chan.one_to_two.as_ref() {
209 one_to_two_announcement = one_to_two.last_update_message.clone();
211 if let Some(two_to_one) = chan.two_to_one.as_ref() {
212 two_to_one_announcement = two_to_one.last_update_message.clone();
214 result.push((chan_announcement, one_to_two_announcement, two_to_one_announcement));
216 // TODO: We may end up sending un-announced channel_updates if we are sending
217 // initial sync data while receiving announce/updates for this channel.
226 fn get_next_node_announcements(&self, starting_point: Option<&PublicKey>, batch_amount: u8) -> Vec<NodeAnnouncement> {
227 let network_graph = self.network_graph.read().unwrap();
228 let mut result = Vec::with_capacity(batch_amount as usize);
229 let mut iter = if let Some(pubkey) = starting_point {
230 let mut iter = network_graph.get_nodes().range((*pubkey)..);
234 network_graph.get_nodes().range(..)
236 while result.len() < batch_amount as usize {
237 if let Some((_, ref node)) = iter.next() {
238 if let Some(node_info) = node.announcement_info.as_ref() {
239 if node_info.announcement_message.is_some() {
240 result.push(node_info.announcement_message.clone().unwrap());
250 fn should_request_full_sync(&self, _node_id: &PublicKey) -> bool {
251 //TODO: Determine whether to request a full sync based on the network map.
252 const FULL_SYNCS_TO_REQUEST: usize = 5;
253 if self.full_syncs_requested.load(Ordering::Acquire) < FULL_SYNCS_TO_REQUEST {
254 self.full_syncs_requested.fetch_add(1, Ordering::AcqRel);
261 fn query_channel_range(&self, their_node_id: &PublicKey, chain_hash: BlockHash, first_blocknum: u32, number_of_blocks: u32) -> Result<(), LightningError> {
262 // We must ensure that we only have a single in-flight query
263 // to the remote peer. If we already have a query, then we fail
264 let mut query_range_tasks_lock = self.chan_range_query_tasks.lock().unwrap();
265 let query_range_tasks = &mut *query_range_tasks_lock;
266 if query_range_tasks.contains_key(their_node_id) {
267 return Err(LightningError {
268 err: String::from("query_channel_range already in-flight"),
269 action: ErrorAction::IgnoreError,
273 // Construct a new task to keep track of the query until the full
274 // range query has been completed
275 let task = ChanRangeQueryTask::new(their_node_id, chain_hash, first_blocknum, number_of_blocks);
276 query_range_tasks.insert(their_node_id.clone(), task);
278 // Enqueue the message send event
279 log_debug!(self.logger, "Sending query_channel_range peer={}, first_blocknum={}, number_of_blocks={}", log_pubkey!(their_node_id), first_blocknum, number_of_blocks);
280 let mut pending_events = self.pending_events.lock().unwrap();
281 pending_events.push(events::MessageSendEvent::SendChannelRangeQuery {
282 node_id: their_node_id.clone(),
283 msg: QueryChannelRange {
292 /// A query should only request channels referring to unspent outputs.
293 /// This method does not validate this requirement and expects the
294 /// caller to ensure SCIDs are unspent.
295 fn query_short_channel_ids(&self, their_node_id: &PublicKey, chain_hash: BlockHash, short_channel_ids: Vec<u64>) -> Result<(), LightningError> {
296 // Create a new task or add to the existing task
297 let mut query_scids_tasks_lock = self.scid_query_tasks.lock().unwrap();
298 let query_scids_tasks = &mut *query_scids_tasks_lock;
300 // For an existing task we append the short_channel_ids which will be sent when the
301 // current in-flight batch completes.
302 if let Some(task) = query_scids_tasks.get_mut(their_node_id) {
303 task.add(short_channel_ids);
307 // For a new task we create the task with short_channel_ids and send the first
308 // batch immediately.
309 query_scids_tasks.insert(their_node_id.clone(), ScidQueryTask::new(
314 let task = query_scids_tasks.get_mut(their_node_id).unwrap();
315 self.finalize_query_short_ids(task);
319 fn handle_reply_channel_range(&self, their_node_id: &PublicKey, msg: &ReplyChannelRange) -> Result<(), LightningError> {
320 log_debug!(self.logger, "Handling reply_channel_range peer={}, first_blocknum={}, number_of_blocks={}, full_information={}, scids={}", log_pubkey!(their_node_id), msg.first_blocknum, msg.number_of_blocks, msg.full_information, msg.short_channel_ids.len(),);
322 // First we obtain a lock on the task hashmap. In order to avoid borrowing issues
323 // we will access the task as needed.
324 let mut query_range_tasks = self.chan_range_query_tasks.lock().unwrap();
326 // If there is no currently executing task then we have received
327 // an invalid message and will return an error
328 if query_range_tasks.get(their_node_id).is_none() {
329 return Err(LightningError {
330 err: String::from("Received unknown reply_channel_range message"),
331 action: ErrorAction::IgnoreError,
335 // Now that we know we have a task, we can extract a few values for use
336 // in validations without having to access the task repeatedly
337 let (task_chain_hash, task_first_blocknum, task_number_of_blocks, task_received_first_block, task_received_last_block, task_number_of_replies) = {
338 let task = query_range_tasks.get(their_node_id).unwrap();
339 (task.chain_hash, task.first_blocknum, task.number_of_blocks, task.received_first_block, task.received_last_block, task.number_of_replies)
342 // Validate the chain_hash matches the chain_hash we used in the query.
343 // If it does not, then the message is malformed and we return an error
344 if msg.chain_hash != task_chain_hash {
345 query_range_tasks.remove(their_node_id);
346 return Err(LightningError {
347 err: String::from("Received reply_channel_range with invalid chain_hash"),
348 action: ErrorAction::IgnoreError,
352 // Validate that the remote node maintains up-to-date channel
353 // information for chain_hash. Some nodes use the full_information
354 // flag to indicate multi-part messages so we must check whether
355 // we received information as well.
356 if !msg.full_information && msg.short_channel_ids.len() == 0 {
357 query_range_tasks.remove(their_node_id);
358 return Err(LightningError {
359 err: String::from("Received reply_channel_range with no information available"),
360 action: ErrorAction::IgnoreError,
364 // Calculate the last block for the message and the task
365 let msg_last_block = last_blocknum(msg.first_blocknum, msg.number_of_blocks);
366 let task_last_block = last_blocknum(task_first_blocknum, task_number_of_blocks);
368 // On the first message...
369 if task_received_first_block.is_none() {
370 // The replies can be a superset of the queried block range, but the
371 // replies must include our requested query range. We check if the
372 // start of the replies is greater than the start of our query. If
373 // so, the start of our query is excluded and the message is malformed.
374 if msg.first_blocknum > task_first_blocknum {
375 query_range_tasks.remove(their_node_id);
376 return Err(LightningError {
377 err: String::from("Failing reply_channel_range with invalid first_blocknum"),
378 action: ErrorAction::IgnoreError,
382 // Next, we ensure the reply has at least some information matching
383 // our query. If the received last_blocknum is less than our query's
384 // first_blocknum then the reply does not encompass the query range
385 // and the message is malformed.
386 if msg_last_block < task_first_blocknum {
387 query_range_tasks.remove(their_node_id);
388 return Err(LightningError {
389 err: String::from("Failing reply_channel_range with non-overlapping first reply"),
390 action: ErrorAction::IgnoreError,
394 // Capture the first block and last block so that subsequent messages
396 let task = query_range_tasks.get_mut(their_node_id).unwrap();
397 task.received_first_block = Some(msg.first_blocknum);
398 task.received_last_block = Some(msg_last_block);
400 // On subsequent message(s)...
402 // We need to validate the sequence of the reply message is expected.
403 // Subsequent messages must set the first_blocknum to the previous
404 // message's first_blocknum plus number_of_blocks. There is discrepancy
405 // in implementation where some resume on the last sent block. We will
406 // loosen the restriction and accept either, and otherwise consider the
407 // message malformed and return an error.
408 let task_received_last_block = task_received_last_block.unwrap();
409 if msg.first_blocknum != task_received_last_block && msg.first_blocknum != task_received_last_block + 1 {
410 query_range_tasks.remove(their_node_id);
411 return Err(LightningError {
412 err: String::from("Failing reply_channel_range with invalid sequence"),
413 action: ErrorAction::IgnoreError,
417 // Next we check to see that we have received a realistic number of
418 // reply messages for a query. This caps the allocation exposure
419 // for short_channel_ids that will be batched and sent in query channels.
420 if task_number_of_replies + 1 > MAX_REPLY_CHANNEL_RANGE_PER_QUERY {
421 query_range_tasks.remove(their_node_id);
422 return Err(LightningError {
423 err: String::from("Failing reply_channel_range due to excessive messages"),
424 action: ErrorAction::IgnoreError,
428 // Capture the last_block in our task so that subsequent messages
430 let task = query_range_tasks.get_mut(their_node_id).unwrap();
431 task.number_of_replies += 1;
432 task.received_last_block = Some(msg_last_block);
435 // We filter the short_channel_ids to those inside the query range.
436 // The most significant 3-bytes of the short_channel_id are the block.
438 let mut filtered_short_channel_ids: Vec<u64> = msg.short_channel_ids.clone().into_iter().filter(|short_channel_id| {
439 let block = short_channel_id >> 40;
440 return block >= query_range_tasks.get(their_node_id).unwrap().first_blocknum as u64 && block <= task_last_block as u64;
442 let task = query_range_tasks.get_mut(their_node_id).unwrap();
443 task.short_channel_ids.append(&mut filtered_short_channel_ids);
446 // The final message is indicated by a last_blocknum that is equal to
447 // or greater than the query's last_blocknum.
448 if msg_last_block >= task_last_block {
449 log_debug!(self.logger, "Completed query_channel_range: peer={}, first_blocknum={}, number_of_blocks={}", log_pubkey!(their_node_id), task_first_blocknum, task_number_of_blocks);
451 // We can now fire off a query to obtain routing messages for the
452 // accumulated short_channel_ids.
454 let task = query_range_tasks.get_mut(their_node_id).unwrap();
455 let mut short_channel_ids = Vec::new();
456 std::mem::swap(&mut short_channel_ids, &mut task.short_channel_ids);
457 self.query_short_channel_ids(their_node_id, task.chain_hash, short_channel_ids)?;
460 // We can remove the query range task now that the query is complete.
461 query_range_tasks.remove(their_node_id);
466 /// When a query is initiated the remote peer will begin streaming
467 /// gossip messages. In the event of a failure, we may have received
468 /// some channel information. Before trying with another peer, the
469 /// caller should update its set of SCIDs that need to be queried.
470 fn handle_reply_short_channel_ids_end(&self, their_node_id: &PublicKey, msg: &ReplyShortChannelIdsEnd) -> Result<(), LightningError> {
471 log_debug!(self.logger, "Handling reply_short_channel_ids_end peer={}, full_information={}", log_pubkey!(their_node_id), msg.full_information);
473 // First we obtain a lock on the task hashmap. In order to avoid borrowing issues
474 // we will access the task as needed.
475 let mut query_short_channel_ids_tasks = self.scid_query_tasks.lock().unwrap();
477 // If there is no existing task then we have received an unknown
478 // message and should return an error.
479 if query_short_channel_ids_tasks.get(their_node_id).is_none() {
480 return Err(LightningError {
481 err: String::from("Unknown reply_short_channel_ids_end message"),
482 action: ErrorAction::IgnoreError,
486 // If the reply's chain_hash does not match the task's chain_hash then
487 // the reply is malformed and we should return an error.
488 if msg.chain_hash != query_short_channel_ids_tasks.get(their_node_id).unwrap().chain_hash {
489 query_short_channel_ids_tasks.remove(their_node_id);
490 return Err(LightningError {
491 err: String::from("Received reply_short_channel_ids_end with incorrect chain_hash"),
492 action: ErrorAction::IgnoreError
496 // If the remote node does not have up-to-date information for the
497 // chain_hash they will set full_information=false. We can fail
498 // the result and try again with a different peer.
499 if !msg.full_information {
500 query_short_channel_ids_tasks.remove(their_node_id);
501 return Err(LightningError {
502 err: String::from("Received reply_short_channel_ids_end with no information"),
503 action: ErrorAction::IgnoreError
507 // If we have more scids to process we send the next batch in the task
509 let task = query_short_channel_ids_tasks.get_mut(their_node_id).unwrap();
510 if task.short_channel_ids.len() > 0 {
511 self.finalize_query_short_ids(task);
516 // Otherwise the task is complete and we can remove it
517 log_debug!(self.logger, "Completed query_short_channel_ids peer={}", log_pubkey!(their_node_id));
518 query_short_channel_ids_tasks.remove(their_node_id);
522 /// There are potential DoS vectors when handling inbound queries.
523 /// Handling requests with first_blocknum very far away may trigger repeated
524 /// disk I/O if the NetworkGraph is not fully in-memory.
525 fn handle_query_channel_range(&self, _their_node_id: &PublicKey, _msg: &QueryChannelRange) -> Result<(), LightningError> {
528 err: String::from("Not implemented"),
529 action: ErrorAction::IgnoreError,
533 /// There are potential DoS vectors when handling inbound queries.
534 /// Handling requests with first_blocknum very far away may trigger repeated
535 /// disk I/O if the NetworkGraph is not fully in-memory.
536 fn handle_query_short_channel_ids(&self, _their_node_id: &PublicKey, _msg: &QueryShortChannelIds) -> Result<(), LightningError> {
539 err: String::from("Not implemented"),
540 action: ErrorAction::IgnoreError,
545 impl<C: Deref, L: Deref> events::MessageSendEventsProvider for NetGraphMsgHandler<C, L>
547 C::Target: chain::Access,
550 fn get_and_clear_pending_msg_events(&self) -> Vec<events::MessageSendEvent> {
551 let mut ret = Vec::new();
552 let mut pending_events = self.pending_events.lock().unwrap();
553 std::mem::swap(&mut ret, &mut pending_events);
558 /// Safely calculates the last_blocknum given a first_blocknum and
559 /// number_of_blocks by returning the u32::MAX-1 if there is an overflow
560 fn last_blocknum(first_blocknum: u32, number_of_blocks: u32) -> u32 {
561 match first_blocknum.checked_add(number_of_blocks) {
562 Some(val) => val - 1,
563 None => 0xffff_ffff - 1,
567 /// Maintains state for a channel range query that we initiated.
568 /// The query may result in one or more reply_channel_range messages
569 /// being received. This struct helps determine the status of the query
570 /// when there are multiple replies. It also collects results for initiating
573 /// The task is complete and can be cleaned up when a reply meets or
574 /// exceeds the last block in the query. The collected SCIDs in the task
575 /// can be used to generate an ScidQueryTask.
577 /// A query may fail if the recipient does not maintain up-to-date
578 /// information for the chain or if the recipient fails to reply within
579 /// a reasonable amount of time. In either event, the query can be
580 /// re-initiated with a different peer.
581 pub struct ChanRangeQueryTask {
582 /// The public key of the node we will be sending queries to
583 pub node_id: PublicKey,
584 /// The genesis hash of the blockchain being queried
585 pub chain_hash: BlockHash,
586 /// The height of the first block for the channel UTXOs being queried
587 pub first_blocknum: u32,
588 /// The number of blocks to include in the query results
589 pub number_of_blocks: u32,
590 /// Tracks the number of reply messages we have received
591 pub number_of_replies: usize,
592 /// The height of the first block received in a reply. This value
593 /// should be less than or equal to the first_blocknum requested in
594 /// the query_channel_range. This allows the range of the replies to
595 /// contain, but not necessarily strictly, the queried range.
596 pub received_first_block: Option<u32>,
597 /// The height of the last block received in a reply. This value
598 /// will get incrementally closer to the target of
599 /// first_blocknum plus number_of_blocks from the query_channel_range.
600 pub received_last_block: Option<u32>,
601 /// Contains short_channel_ids received in one or more reply messages.
602 /// These will be sent in one ore more query_short_channel_ids messages
603 /// when the task is complete.
604 pub short_channel_ids: Vec<u64>,
607 impl ChanRangeQueryTask {
608 /// Constructs a new GossipQueryRangeTask
609 pub fn new(their_node_id: &PublicKey, chain_hash: BlockHash, first_blocknum: u32, number_of_blocks: u32) -> Self {
611 node_id: their_node_id.clone(),
615 number_of_replies: 0,
616 received_first_block: None,
617 received_last_block: None,
618 short_channel_ids: vec![],
623 /// Maintains state when sending one or more short_channel_ids messages
624 /// to a peer. Only a single SCID query can be in-flight with a peer. The
625 /// number of SCIDs per query is limited by the size of a Lightning message
626 /// payload. When querying a large number of SCIDs (results of a large
627 /// channel range query for instance), multiple query_short_channel_ids
628 /// messages need to be sent. This task maintains the list of awaiting
629 /// SCIDs to be queried.
631 /// When a successful reply_short_channel_ids_end message is received, the
632 /// next batch of SCIDs can be sent. When no remaining SCIDs exist in the
633 /// task, the task is complete and can be cleaned up.
635 /// The recipient may reply indicating that up-to-date information for the
636 /// chain is not maintained. A query may also fail to complete within a
637 /// reasonable amount of time. In either event, the short_channel_ids
638 /// can be queried from a different peer after validating the set of
639 /// SCIDs that still need to be queried.
640 pub struct ScidQueryTask {
641 /// The public key of the node we will be sending queries to
642 pub node_id: PublicKey,
643 /// The genesis hash of the blockchain being queried
644 pub chain_hash: BlockHash,
645 /// A vector of short_channel_ids that we would like routing gossip
646 /// information for. This list will be chunked and sent to the peer
647 /// in one or more query_short_channel_ids messages.
648 pub short_channel_ids: Vec<u64>,
652 /// Constructs a new GossipQueryShortChannelIdsTask
653 pub fn new(their_node_id: &PublicKey, chain_hash: BlockHash, short_channel_ids: Vec<u64>) -> Self {
655 node_id: their_node_id.clone(),
661 /// Adds short_channel_ids to the pending list of short_channel_ids
662 /// to be sent in the next request. You can add additional values
663 /// while a query is in-flight. These new values will be sent once
664 /// the active query has completed.
665 pub fn add(&mut self, mut short_channel_ids: Vec<u64>) {
666 self.short_channel_ids.append(&mut short_channel_ids);
670 #[derive(PartialEq, Debug)]
671 /// Details about one direction of a channel. Received
672 /// within a channel update.
673 pub struct DirectionalChannelInfo {
674 /// When the last update to the channel direction was issued.
675 /// Value is opaque, as set in the announcement.
676 pub last_update: u32,
677 /// Whether the channel can be currently used for payments (in this one direction).
679 /// The difference in CLTV values that you must have when routing through this channel.
680 pub cltv_expiry_delta: u16,
681 /// The minimum value, which must be relayed to the next hop via the channel
682 pub htlc_minimum_msat: u64,
683 /// The maximum value which may be relayed to the next hop via the channel.
684 pub htlc_maximum_msat: Option<u64>,
685 /// Fees charged when the channel is used for routing
686 pub fees: RoutingFees,
687 /// Most recent update for the channel received from the network
688 /// Mostly redundant with the data we store in fields explicitly.
689 /// Everything else is useful only for sending out for initial routing sync.
690 /// Not stored if contains excess data to prevent DoS.
691 pub last_update_message: Option<ChannelUpdate>,
694 impl fmt::Display for DirectionalChannelInfo {
695 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
696 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)?;
701 impl_writeable!(DirectionalChannelInfo, 0, {
712 /// Details about a channel (both directions).
713 /// Received within a channel announcement.
714 pub struct ChannelInfo {
715 /// Protocol features of a channel communicated during its announcement
716 pub features: ChannelFeatures,
717 /// Source node of the first direction of a channel
718 pub node_one: PublicKey,
719 /// Details about the first direction of a channel
720 pub one_to_two: Option<DirectionalChannelInfo>,
721 /// Source node of the second direction of a channel
722 pub node_two: PublicKey,
723 /// Details about the second direction of a channel
724 pub two_to_one: Option<DirectionalChannelInfo>,
725 /// The channel capacity as seen on-chain, if chain lookup is available.
726 pub capacity_sats: Option<u64>,
727 /// An initial announcement of the channel
728 /// Mostly redundant with the data we store in fields explicitly.
729 /// Everything else is useful only for sending out for initial routing sync.
730 /// Not stored if contains excess data to prevent DoS.
731 pub announcement_message: Option<ChannelAnnouncement>,
734 impl fmt::Display for ChannelInfo {
735 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
736 write!(f, "features: {}, node_one: {}, one_to_two: {:?}, node_two: {}, two_to_one: {:?}",
737 log_bytes!(self.features.encode()), log_pubkey!(self.node_one), self.one_to_two, log_pubkey!(self.node_two), self.two_to_one)?;
742 impl_writeable!(ChannelInfo, 0, {
753 /// Fees for routing via a given channel or a node
754 #[derive(Eq, PartialEq, Copy, Clone, Debug)]
755 pub struct RoutingFees {
756 /// Flat routing fee in satoshis
758 /// Liquidity-based routing fee in millionths of a routed amount.
759 /// In other words, 10000 is 1%.
760 pub proportional_millionths: u32,
763 impl Readable for RoutingFees{
764 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<RoutingFees, DecodeError> {
765 let base_msat: u32 = Readable::read(reader)?;
766 let proportional_millionths: u32 = Readable::read(reader)?;
769 proportional_millionths,
774 impl Writeable for RoutingFees {
775 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
776 self.base_msat.write(writer)?;
777 self.proportional_millionths.write(writer)?;
782 #[derive(PartialEq, Debug)]
783 /// Information received in the latest node_announcement from this node.
784 pub struct NodeAnnouncementInfo {
785 /// Protocol features the node announced support for
786 pub features: NodeFeatures,
787 /// When the last known update to the node state was issued.
788 /// Value is opaque, as set in the announcement.
789 pub last_update: u32,
790 /// Color assigned to the node
792 /// Moniker assigned to the node.
793 /// May be invalid or malicious (eg control chars),
794 /// should not be exposed to the user.
796 /// Internet-level addresses via which one can connect to the node
797 pub addresses: Vec<NetAddress>,
798 /// An initial announcement of the node
799 /// Mostly redundant with the data we store in fields explicitly.
800 /// Everything else is useful only for sending out for initial routing sync.
801 /// Not stored if contains excess data to prevent DoS.
802 pub announcement_message: Option<NodeAnnouncement>
805 impl Writeable for NodeAnnouncementInfo {
806 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
807 self.features.write(writer)?;
808 self.last_update.write(writer)?;
809 self.rgb.write(writer)?;
810 self.alias.write(writer)?;
811 (self.addresses.len() as u64).write(writer)?;
812 for ref addr in &self.addresses {
815 self.announcement_message.write(writer)?;
820 impl Readable for NodeAnnouncementInfo {
821 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NodeAnnouncementInfo, DecodeError> {
822 let features = Readable::read(reader)?;
823 let last_update = Readable::read(reader)?;
824 let rgb = Readable::read(reader)?;
825 let alias = Readable::read(reader)?;
826 let addresses_count: u64 = Readable::read(reader)?;
827 let mut addresses = Vec::with_capacity(cmp::min(addresses_count, MAX_ALLOC_SIZE / 40) as usize);
828 for _ in 0..addresses_count {
829 match Readable::read(reader) {
830 Ok(Ok(addr)) => { addresses.push(addr); },
831 Ok(Err(_)) => return Err(DecodeError::InvalidValue),
832 Err(DecodeError::ShortRead) => return Err(DecodeError::BadLengthDescriptor),
836 let announcement_message = Readable::read(reader)?;
837 Ok(NodeAnnouncementInfo {
849 /// Details about a node in the network, known from the network announcement.
850 pub struct NodeInfo {
851 /// All valid channels a node has announced
852 pub channels: Vec<u64>,
853 /// Lowest fees enabling routing via any of the enabled, known channels to a node.
854 /// The two fields (flat and proportional fee) are independent,
855 /// meaning they don't have to refer to the same channel.
856 pub lowest_inbound_channel_fees: Option<RoutingFees>,
857 /// More information about a node from node_announcement.
858 /// Optional because we store a Node entry after learning about it from
859 /// a channel announcement, but before receiving a node announcement.
860 pub announcement_info: Option<NodeAnnouncementInfo>
863 impl fmt::Display for NodeInfo {
864 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
865 write!(f, "lowest_inbound_channel_fees: {:?}, channels: {:?}, announcement_info: {:?}",
866 self.lowest_inbound_channel_fees, &self.channels[..], self.announcement_info)?;
871 impl Writeable for NodeInfo {
872 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
873 (self.channels.len() as u64).write(writer)?;
874 for ref chan in self.channels.iter() {
877 self.lowest_inbound_channel_fees.write(writer)?;
878 self.announcement_info.write(writer)?;
883 const MAX_ALLOC_SIZE: u64 = 64*1024;
885 impl Readable for NodeInfo {
886 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NodeInfo, DecodeError> {
887 let channels_count: u64 = Readable::read(reader)?;
888 let mut channels = Vec::with_capacity(cmp::min(channels_count, MAX_ALLOC_SIZE / 8) as usize);
889 for _ in 0..channels_count {
890 channels.push(Readable::read(reader)?);
892 let lowest_inbound_channel_fees = Readable::read(reader)?;
893 let announcement_info = Readable::read(reader)?;
896 lowest_inbound_channel_fees,
902 impl Writeable for NetworkGraph {
903 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
904 self.genesis_hash.write(writer)?;
905 (self.channels.len() as u64).write(writer)?;
906 for (ref chan_id, ref chan_info) in self.channels.iter() {
907 (*chan_id).write(writer)?;
908 chan_info.write(writer)?;
910 (self.nodes.len() as u64).write(writer)?;
911 for (ref node_id, ref node_info) in self.nodes.iter() {
912 node_id.write(writer)?;
913 node_info.write(writer)?;
919 impl Readable for NetworkGraph {
920 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<NetworkGraph, DecodeError> {
921 let genesis_hash: BlockHash = Readable::read(reader)?;
922 let channels_count: u64 = Readable::read(reader)?;
923 let mut channels = BTreeMap::new();
924 for _ in 0..channels_count {
925 let chan_id: u64 = Readable::read(reader)?;
926 let chan_info = Readable::read(reader)?;
927 channels.insert(chan_id, chan_info);
929 let nodes_count: u64 = Readable::read(reader)?;
930 let mut nodes = BTreeMap::new();
931 for _ in 0..nodes_count {
932 let node_id = Readable::read(reader)?;
933 let node_info = Readable::read(reader)?;
934 nodes.insert(node_id, node_info);
944 impl fmt::Display for NetworkGraph {
945 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
946 writeln!(f, "Network map\n[Channels]")?;
947 for (key, val) in self.channels.iter() {
948 writeln!(f, " {}: {}", key, val)?;
950 writeln!(f, "[Nodes]")?;
951 for (key, val) in self.nodes.iter() {
952 writeln!(f, " {}: {}", log_pubkey!(key), val)?;
959 /// Returns all known valid channels' short ids along with announced channel info.
961 /// (C-not exported) because we have no mapping for `BTreeMap`s
962 pub fn get_channels<'a>(&'a self) -> &'a BTreeMap<u64, ChannelInfo> { &self.channels }
963 /// Returns all known nodes' public keys along with announced node info.
965 /// (C-not exported) because we have no mapping for `BTreeMap`s
966 pub fn get_nodes<'a>(&'a self) -> &'a BTreeMap<PublicKey, NodeInfo> { &self.nodes }
968 /// Get network addresses by node id.
969 /// Returns None if the requested node is completely unknown,
970 /// or if node announcement for the node was never received.
972 /// (C-not exported) as there is no practical way to track lifetimes of returned values.
973 pub fn get_addresses<'a>(&'a self, pubkey: &PublicKey) -> Option<&'a Vec<NetAddress>> {
974 if let Some(node) = self.nodes.get(pubkey) {
975 if let Some(node_info) = node.announcement_info.as_ref() {
976 return Some(&node_info.addresses)
982 /// Creates a new, empty, network graph.
983 pub fn new(genesis_hash: BlockHash) -> NetworkGraph {
986 channels: BTreeMap::new(),
987 nodes: BTreeMap::new(),
991 /// For an already known node (from channel announcements), update its stored properties from a
992 /// given node announcement.
994 /// You probably don't want to call this directly, instead relying on a NetGraphMsgHandler's
995 /// RoutingMessageHandler implementation to call it indirectly. This may be useful to accept
996 /// routing messages from a source using a protocol other than the lightning P2P protocol.
997 pub fn update_node_from_announcement<T: secp256k1::Verification>(&mut self, msg: &msgs::NodeAnnouncement, secp_ctx: &Secp256k1<T>) -> Result<(), LightningError> {
998 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
999 secp_verify_sig!(secp_ctx, &msg_hash, &msg.signature, &msg.contents.node_id);
1000 self.update_node_from_announcement_intern(&msg.contents, Some(&msg))
1003 /// For an already known node (from channel announcements), update its stored properties from a
1004 /// given node announcement without verifying the associated signatures. Because we aren't
1005 /// given the associated signatures here we cannot relay the node announcement to any of our
1007 pub fn update_node_from_unsigned_announcement(&mut self, msg: &msgs::UnsignedNodeAnnouncement) -> Result<(), LightningError> {
1008 self.update_node_from_announcement_intern(msg, None)
1011 fn update_node_from_announcement_intern(&mut self, msg: &msgs::UnsignedNodeAnnouncement, full_msg: Option<&msgs::NodeAnnouncement>) -> Result<(), LightningError> {
1012 match self.nodes.get_mut(&msg.node_id) {
1013 None => Err(LightningError{err: "No existing channels for node_announcement".to_owned(), action: ErrorAction::IgnoreError}),
1015 if let Some(node_info) = node.announcement_info.as_ref() {
1016 if node_info.last_update >= msg.timestamp {
1017 return Err(LightningError{err: "Update older than last processed update".to_owned(), action: ErrorAction::IgnoreError});
1021 let should_relay = msg.excess_data.is_empty() && msg.excess_address_data.is_empty();
1022 node.announcement_info = Some(NodeAnnouncementInfo {
1023 features: msg.features.clone(),
1024 last_update: msg.timestamp,
1027 addresses: msg.addresses.clone(),
1028 announcement_message: if should_relay { full_msg.cloned() } else { None },
1036 /// Store or update channel info from a channel announcement.
1038 /// You probably don't want to call this directly, instead relying on a NetGraphMsgHandler's
1039 /// RoutingMessageHandler implementation to call it indirectly. This may be useful to accept
1040 /// routing messages from a source using a protocol other than the lightning P2P protocol.
1042 /// If a `chain::Access` object is provided via `chain_access`, it will be called to verify
1043 /// the corresponding UTXO exists on chain and is correctly-formatted.
1044 pub fn update_channel_from_announcement<T: secp256k1::Verification, C: Deref>
1045 (&mut self, msg: &msgs::ChannelAnnouncement, chain_access: &Option<C>, secp_ctx: &Secp256k1<T>)
1046 -> Result<(), LightningError>
1047 where C::Target: chain::Access {
1048 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.contents.encode()[..])[..]);
1049 secp_verify_sig!(secp_ctx, &msg_hash, &msg.node_signature_1, &msg.contents.node_id_1);
1050 secp_verify_sig!(secp_ctx, &msg_hash, &msg.node_signature_2, &msg.contents.node_id_2);
1051 secp_verify_sig!(secp_ctx, &msg_hash, &msg.bitcoin_signature_1, &msg.contents.bitcoin_key_1);
1052 secp_verify_sig!(secp_ctx, &msg_hash, &msg.bitcoin_signature_2, &msg.contents.bitcoin_key_2);
1053 self.update_channel_from_unsigned_announcement_intern(&msg.contents, Some(msg), chain_access)
1056 /// Store or update channel info from a channel announcement without verifying the associated
1057 /// signatures. Because we aren't given the associated signatures here we cannot relay the
1058 /// channel announcement to any of our peers.
1060 /// If a `chain::Access` object is provided via `chain_access`, it will be called to verify
1061 /// the corresponding UTXO exists on chain and is correctly-formatted.
1062 pub fn update_channel_from_unsigned_announcement<C: Deref>
1063 (&mut self, msg: &msgs::UnsignedChannelAnnouncement, chain_access: &Option<C>)
1064 -> Result<(), LightningError>
1065 where C::Target: chain::Access {
1066 self.update_channel_from_unsigned_announcement_intern(msg, None, chain_access)
1069 fn update_channel_from_unsigned_announcement_intern<C: Deref>
1070 (&mut self, msg: &msgs::UnsignedChannelAnnouncement, full_msg: Option<&msgs::ChannelAnnouncement>, chain_access: &Option<C>)
1071 -> Result<(), LightningError>
1072 where C::Target: chain::Access {
1073 if msg.node_id_1 == msg.node_id_2 || msg.bitcoin_key_1 == msg.bitcoin_key_2 {
1074 return Err(LightningError{err: "Channel announcement node had a channel with itself".to_owned(), action: ErrorAction::IgnoreError});
1077 let utxo_value = match &chain_access {
1079 // Tentatively accept, potentially exposing us to DoS attacks
1082 &Some(ref chain_access) => {
1083 match chain_access.get_utxo(&msg.chain_hash, msg.short_channel_id) {
1084 Ok(TxOut { value, script_pubkey }) => {
1085 let expected_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
1086 .push_slice(&msg.bitcoin_key_1.serialize())
1087 .push_slice(&msg.bitcoin_key_2.serialize())
1088 .push_opcode(opcodes::all::OP_PUSHNUM_2)
1089 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
1090 if script_pubkey != expected_script {
1091 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});
1093 //TODO: Check if value is worth storing, use it to inform routing, and compare it
1094 //to the new HTLC max field in channel_update
1097 Err(chain::AccessError::UnknownChain) => {
1098 return Err(LightningError{err: format!("Channel announced on an unknown chain ({})", msg.chain_hash.encode().to_hex()), action: ErrorAction::IgnoreError});
1100 Err(chain::AccessError::UnknownTx) => {
1101 return Err(LightningError{err: "Channel announced without corresponding UTXO entry".to_owned(), action: ErrorAction::IgnoreError});
1107 let chan_info = ChannelInfo {
1108 features: msg.features.clone(),
1109 node_one: msg.node_id_1.clone(),
1111 node_two: msg.node_id_2.clone(),
1113 capacity_sats: utxo_value,
1114 announcement_message: if msg.excess_data.is_empty() { full_msg.cloned() } else { None },
1117 match self.channels.entry(msg.short_channel_id) {
1118 BtreeEntry::Occupied(mut entry) => {
1119 //TODO: because asking the blockchain if short_channel_id is valid is only optional
1120 //in the blockchain API, we need to handle it smartly here, though it's unclear
1122 if utxo_value.is_some() {
1123 // Either our UTXO provider is busted, there was a reorg, or the UTXO provider
1124 // only sometimes returns results. In any case remove the previous entry. Note
1125 // that the spec expects us to "blacklist" the node_ids involved, but we can't
1127 // a) we don't *require* a UTXO provider that always returns results.
1128 // b) we don't track UTXOs of channels we know about and remove them if they
1130 // c) it's unclear how to do so without exposing ourselves to massive DoS risk.
1131 Self::remove_channel_in_nodes(&mut self.nodes, &entry.get(), msg.short_channel_id);
1132 *entry.get_mut() = chan_info;
1134 return Err(LightningError{err: "Already have knowledge of channel".to_owned(), action: ErrorAction::IgnoreError})
1137 BtreeEntry::Vacant(entry) => {
1138 entry.insert(chan_info);
1142 macro_rules! add_channel_to_node {
1143 ( $node_id: expr ) => {
1144 match self.nodes.entry($node_id) {
1145 BtreeEntry::Occupied(node_entry) => {
1146 node_entry.into_mut().channels.push(msg.short_channel_id);
1148 BtreeEntry::Vacant(node_entry) => {
1149 node_entry.insert(NodeInfo {
1150 channels: vec!(msg.short_channel_id),
1151 lowest_inbound_channel_fees: None,
1152 announcement_info: None,
1159 add_channel_to_node!(msg.node_id_1);
1160 add_channel_to_node!(msg.node_id_2);
1165 /// Close a channel if a corresponding HTLC fail was sent.
1166 /// If permanent, removes a channel from the local storage.
1167 /// May cause the removal of nodes too, if this was their last channel.
1168 /// If not permanent, makes channels unavailable for routing.
1169 pub fn close_channel_from_update(&mut self, short_channel_id: u64, is_permanent: bool) {
1171 if let Some(chan) = self.channels.remove(&short_channel_id) {
1172 Self::remove_channel_in_nodes(&mut self.nodes, &chan, short_channel_id);
1175 if let Some(chan) = self.channels.get_mut(&short_channel_id) {
1176 if let Some(one_to_two) = chan.one_to_two.as_mut() {
1177 one_to_two.enabled = false;
1179 if let Some(two_to_one) = chan.two_to_one.as_mut() {
1180 two_to_one.enabled = false;
1186 fn fail_node(&mut self, _node_id: &PublicKey, is_permanent: bool) {
1188 // TODO: Wholly remove the node
1190 // TODO: downgrade the node
1194 /// For an already known (from announcement) channel, update info about one of the directions
1197 /// You probably don't want to call this directly, instead relying on a NetGraphMsgHandler's
1198 /// RoutingMessageHandler implementation to call it indirectly. This may be useful to accept
1199 /// routing messages from a source using a protocol other than the lightning P2P protocol.
1200 pub fn update_channel<T: secp256k1::Verification>(&mut self, msg: &msgs::ChannelUpdate, secp_ctx: &Secp256k1<T>) -> Result<(), LightningError> {
1201 self.update_channel_intern(&msg.contents, Some(&msg), Some((&msg.signature, secp_ctx)))
1204 /// For an already known (from announcement) channel, update info about one of the directions
1205 /// of the channel without verifying the associated signatures. Because we aren't given the
1206 /// associated signatures here we cannot relay the channel update to any of our peers.
1207 pub fn update_channel_unsigned(&mut self, msg: &msgs::UnsignedChannelUpdate) -> Result<(), LightningError> {
1208 self.update_channel_intern(msg, None, None::<(&secp256k1::Signature, &Secp256k1<secp256k1::VerifyOnly>)>)
1211 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> {
1213 let chan_enabled = msg.flags & (1 << 1) != (1 << 1);
1214 let chan_was_enabled;
1216 match self.channels.get_mut(&msg.short_channel_id) {
1217 None => return Err(LightningError{err: "Couldn't find channel for update".to_owned(), action: ErrorAction::IgnoreError}),
1219 if let OptionalField::Present(htlc_maximum_msat) = msg.htlc_maximum_msat {
1220 if htlc_maximum_msat > MAX_VALUE_MSAT {
1221 return Err(LightningError{err: "htlc_maximum_msat is larger than maximum possible msats".to_owned(), action: ErrorAction::IgnoreError});
1224 if let Some(capacity_sats) = channel.capacity_sats {
1225 // It's possible channel capacity is available now, although it wasn't available at announcement (so the field is None).
1226 // Don't query UTXO set here to reduce DoS risks.
1227 if capacity_sats > MAX_VALUE_MSAT / 1000 || htlc_maximum_msat > capacity_sats * 1000 {
1228 return Err(LightningError{err: "htlc_maximum_msat is larger than channel capacity or capacity is bogus".to_owned(), action: ErrorAction::IgnoreError});
1232 macro_rules! maybe_update_channel_info {
1233 ( $target: expr, $src_node: expr) => {
1234 if let Some(existing_chan_info) = $target.as_ref() {
1235 if existing_chan_info.last_update >= msg.timestamp {
1236 return Err(LightningError{err: "Update older than last processed update".to_owned(), action: ErrorAction::IgnoreError});
1238 chan_was_enabled = existing_chan_info.enabled;
1240 chan_was_enabled = false;
1243 let last_update_message = if msg.excess_data.is_empty() { full_msg.cloned() } else { None };
1245 let updated_channel_dir_info = DirectionalChannelInfo {
1246 enabled: chan_enabled,
1247 last_update: msg.timestamp,
1248 cltv_expiry_delta: msg.cltv_expiry_delta,
1249 htlc_minimum_msat: msg.htlc_minimum_msat,
1250 htlc_maximum_msat: if let OptionalField::Present(max_value) = msg.htlc_maximum_msat { Some(max_value) } else { None },
1252 base_msat: msg.fee_base_msat,
1253 proportional_millionths: msg.fee_proportional_millionths,
1257 $target = Some(updated_channel_dir_info);
1261 let msg_hash = hash_to_message!(&Sha256dHash::hash(&msg.encode()[..])[..]);
1262 if msg.flags & 1 == 1 {
1263 dest_node_id = channel.node_one.clone();
1264 if let Some((sig, ctx)) = sig_info {
1265 secp_verify_sig!(ctx, &msg_hash, &sig, &channel.node_two);
1267 maybe_update_channel_info!(channel.two_to_one, channel.node_two);
1269 dest_node_id = channel.node_two.clone();
1270 if let Some((sig, ctx)) = sig_info {
1271 secp_verify_sig!(ctx, &msg_hash, &sig, &channel.node_one);
1273 maybe_update_channel_info!(channel.one_to_two, channel.node_one);
1279 let node = self.nodes.get_mut(&dest_node_id).unwrap();
1280 let mut base_msat = msg.fee_base_msat;
1281 let mut proportional_millionths = msg.fee_proportional_millionths;
1282 if let Some(fees) = node.lowest_inbound_channel_fees {
1283 base_msat = cmp::min(base_msat, fees.base_msat);
1284 proportional_millionths = cmp::min(proportional_millionths, fees.proportional_millionths);
1286 node.lowest_inbound_channel_fees = Some(RoutingFees {
1288 proportional_millionths
1290 } else if chan_was_enabled {
1291 let node = self.nodes.get_mut(&dest_node_id).unwrap();
1292 let mut lowest_inbound_channel_fees = None;
1294 for chan_id in node.channels.iter() {
1295 let chan = self.channels.get(chan_id).unwrap();
1297 if chan.node_one == dest_node_id {
1298 chan_info_opt = chan.two_to_one.as_ref();
1300 chan_info_opt = chan.one_to_two.as_ref();
1302 if let Some(chan_info) = chan_info_opt {
1303 if chan_info.enabled {
1304 let fees = lowest_inbound_channel_fees.get_or_insert(RoutingFees {
1305 base_msat: u32::max_value(), proportional_millionths: u32::max_value() });
1306 fees.base_msat = cmp::min(fees.base_msat, chan_info.fees.base_msat);
1307 fees.proportional_millionths = cmp::min(fees.proportional_millionths, chan_info.fees.proportional_millionths);
1312 node.lowest_inbound_channel_fees = lowest_inbound_channel_fees;
1318 fn remove_channel_in_nodes(nodes: &mut BTreeMap<PublicKey, NodeInfo>, chan: &ChannelInfo, short_channel_id: u64) {
1319 macro_rules! remove_from_node {
1320 ($node_id: expr) => {
1321 if let BtreeEntry::Occupied(mut entry) = nodes.entry($node_id) {
1322 entry.get_mut().channels.retain(|chan_id| {
1323 short_channel_id != *chan_id
1325 if entry.get().channels.is_empty() {
1326 entry.remove_entry();
1329 panic!("Had channel that pointed to unknown node (ie inconsistent network map)!");
1334 remove_from_node!(chan.node_one);
1335 remove_from_node!(chan.node_two);
1342 use ln::features::{ChannelFeatures, NodeFeatures};
1343 use routing::network_graph::{NetGraphMsgHandler, NetworkGraph};
1344 use ln::msgs::{OptionalField, RoutingMessageHandler, UnsignedNodeAnnouncement, NodeAnnouncement,
1345 UnsignedChannelAnnouncement, ChannelAnnouncement, UnsignedChannelUpdate, ChannelUpdate, HTLCFailChannelUpdate,
1346 ReplyChannelRange, ReplyShortChannelIdsEnd, QueryChannelRange, QueryShortChannelIds, MAX_VALUE_MSAT};
1347 use util::test_utils;
1348 use util::logger::Logger;
1349 use util::ser::{Readable, Writeable};
1350 use util::events::{MessageSendEvent, MessageSendEventsProvider};
1352 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
1353 use bitcoin::hashes::Hash;
1354 use bitcoin::network::constants::Network;
1355 use bitcoin::blockdata::constants::genesis_block;
1356 use bitcoin::blockdata::script::Builder;
1357 use bitcoin::blockdata::transaction::TxOut;
1358 use bitcoin::blockdata::opcodes;
1362 use bitcoin::secp256k1::key::{PublicKey, SecretKey};
1363 use bitcoin::secp256k1::{All, Secp256k1};
1367 fn create_net_graph_msg_handler() -> (Secp256k1<All>, NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>) {
1368 let secp_ctx = Secp256k1::new();
1369 let logger = Arc::new(test_utils::TestLogger::new());
1370 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
1371 let net_graph_msg_handler = NetGraphMsgHandler::new(genesis_hash, None, Arc::clone(&logger));
1372 (secp_ctx, net_graph_msg_handler)
1376 fn request_full_sync_finite_times() {
1377 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1378 let node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap()[..]).unwrap());
1380 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1381 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1382 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1383 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1384 assert!(net_graph_msg_handler.should_request_full_sync(&node_id));
1385 assert!(!net_graph_msg_handler.should_request_full_sync(&node_id));
1389 fn handling_node_announcements() {
1390 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1392 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1393 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1394 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1395 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1396 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1397 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1398 let zero_hash = Sha256dHash::hash(&[0; 32]);
1399 let first_announcement_time = 500;
1401 let mut unsigned_announcement = UnsignedNodeAnnouncement {
1402 features: NodeFeatures::known(),
1403 timestamp: first_announcement_time,
1407 addresses: Vec::new(),
1408 excess_address_data: Vec::new(),
1409 excess_data: Vec::new(),
1411 let mut msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1412 let valid_announcement = NodeAnnouncement {
1413 signature: secp_ctx.sign(&msghash, node_1_privkey),
1414 contents: unsigned_announcement.clone()
1417 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1419 Err(e) => assert_eq!("No existing channels for node_announcement", e.err)
1423 // Announce a channel to add a corresponding node.
1424 let unsigned_announcement = UnsignedChannelAnnouncement {
1425 features: ChannelFeatures::known(),
1426 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1427 short_channel_id: 0,
1430 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1431 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1432 excess_data: Vec::new(),
1435 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1436 let valid_announcement = ChannelAnnouncement {
1437 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1438 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1439 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1440 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1441 contents: unsigned_announcement.clone(),
1443 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1444 Ok(res) => assert!(res),
1449 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1450 Ok(res) => assert!(res),
1454 let fake_msghash = hash_to_message!(&zero_hash);
1455 match net_graph_msg_handler.handle_node_announcement(
1457 signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
1458 contents: unsigned_announcement.clone()
1461 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1464 unsigned_announcement.timestamp += 1000;
1465 unsigned_announcement.excess_data.push(1);
1466 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1467 let announcement_with_data = NodeAnnouncement {
1468 signature: secp_ctx.sign(&msghash, node_1_privkey),
1469 contents: unsigned_announcement.clone()
1471 // Return false because contains excess data.
1472 match net_graph_msg_handler.handle_node_announcement(&announcement_with_data) {
1473 Ok(res) => assert!(!res),
1476 unsigned_announcement.excess_data = Vec::new();
1478 // Even though previous announcement was not relayed further, we still accepted it,
1479 // so we now won't accept announcements before the previous one.
1480 unsigned_announcement.timestamp -= 10;
1481 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1482 let outdated_announcement = NodeAnnouncement {
1483 signature: secp_ctx.sign(&msghash, node_1_privkey),
1484 contents: unsigned_announcement.clone()
1486 match net_graph_msg_handler.handle_node_announcement(&outdated_announcement) {
1488 Err(e) => assert_eq!(e.err, "Update older than last processed update")
1493 fn handling_channel_announcements() {
1494 let secp_ctx = Secp256k1::new();
1495 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
1497 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1498 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1499 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1500 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1501 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1502 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1504 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
1505 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_1_btckey).serialize())
1506 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_2_btckey).serialize())
1507 .push_opcode(opcodes::all::OP_PUSHNUM_2)
1508 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
1511 let mut unsigned_announcement = UnsignedChannelAnnouncement {
1512 features: ChannelFeatures::known(),
1513 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1514 short_channel_id: 0,
1517 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1518 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1519 excess_data: Vec::new(),
1522 let mut msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1523 let valid_announcement = ChannelAnnouncement {
1524 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1525 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1526 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1527 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1528 contents: unsigned_announcement.clone(),
1531 // Test if the UTXO lookups were not supported
1532 let mut net_graph_msg_handler = NetGraphMsgHandler::new(genesis_block(Network::Testnet).header.block_hash(), None, Arc::clone(&logger));
1533 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1534 Ok(res) => assert!(res),
1539 let network = net_graph_msg_handler.network_graph.read().unwrap();
1540 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1546 // If we receive announcement for the same channel (with UTXO lookups disabled),
1547 // drop new one on the floor, since we can't see any changes.
1548 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1550 Err(e) => assert_eq!(e.err, "Already have knowledge of channel")
1553 // Test if an associated transaction were not on-chain (or not confirmed).
1554 let chain_source = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1555 *chain_source.utxo_ret.lock().unwrap() = Err(chain::AccessError::UnknownTx);
1556 net_graph_msg_handler = NetGraphMsgHandler::new(chain_source.clone().genesis_hash, Some(chain_source.clone()), Arc::clone(&logger));
1557 unsigned_announcement.short_channel_id += 1;
1559 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1560 let valid_announcement = ChannelAnnouncement {
1561 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1562 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1563 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1564 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1565 contents: unsigned_announcement.clone(),
1568 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1570 Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1573 // Now test if the transaction is found in the UTXO set and the script is correct.
1574 unsigned_announcement.short_channel_id += 1;
1575 *chain_source.utxo_ret.lock().unwrap() = Ok(TxOut { value: 0, script_pubkey: good_script.clone() });
1577 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1578 let valid_announcement = ChannelAnnouncement {
1579 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1580 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1581 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1582 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1583 contents: unsigned_announcement.clone(),
1585 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1586 Ok(res) => assert!(res),
1591 let network = net_graph_msg_handler.network_graph.read().unwrap();
1592 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1598 // If we receive announcement for the same channel (but TX is not confirmed),
1599 // drop new one on the floor, since we can't see any changes.
1600 *chain_source.utxo_ret.lock().unwrap() = Err(chain::AccessError::UnknownTx);
1601 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1603 Err(e) => assert_eq!(e.err, "Channel announced without corresponding UTXO entry")
1606 // But if it is confirmed, replace the channel
1607 *chain_source.utxo_ret.lock().unwrap() = Ok(TxOut { value: 0, script_pubkey: good_script });
1608 unsigned_announcement.features = ChannelFeatures::empty();
1609 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1610 let valid_announcement = ChannelAnnouncement {
1611 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1612 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1613 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1614 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1615 contents: unsigned_announcement.clone(),
1617 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1618 Ok(res) => assert!(res),
1622 let network = net_graph_msg_handler.network_graph.read().unwrap();
1623 match network.get_channels().get(&unsigned_announcement.short_channel_id) {
1624 Some(channel_entry) => {
1625 assert_eq!(channel_entry.features, ChannelFeatures::empty());
1631 // Don't relay valid channels with excess data
1632 unsigned_announcement.short_channel_id += 1;
1633 unsigned_announcement.excess_data.push(1);
1634 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1635 let valid_announcement = ChannelAnnouncement {
1636 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1637 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1638 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1639 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1640 contents: unsigned_announcement.clone(),
1642 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1643 Ok(res) => assert!(!res),
1647 unsigned_announcement.excess_data = Vec::new();
1648 let invalid_sig_announcement = ChannelAnnouncement {
1649 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1650 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1651 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1652 bitcoin_signature_2: secp_ctx.sign(&msghash, node_1_btckey),
1653 contents: unsigned_announcement.clone(),
1655 match net_graph_msg_handler.handle_channel_announcement(&invalid_sig_announcement) {
1657 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1660 unsigned_announcement.node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1661 msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1662 let channel_to_itself_announcement = ChannelAnnouncement {
1663 node_signature_1: secp_ctx.sign(&msghash, node_2_privkey),
1664 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1665 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1666 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1667 contents: unsigned_announcement.clone(),
1669 match net_graph_msg_handler.handle_channel_announcement(&channel_to_itself_announcement) {
1671 Err(e) => assert_eq!(e.err, "Channel announcement node had a channel with itself")
1676 fn handling_channel_update() {
1677 let secp_ctx = Secp256k1::new();
1678 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::new());
1679 let chain_source = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1680 let net_graph_msg_handler = NetGraphMsgHandler::new(genesis_block(Network::Testnet).header.block_hash(), Some(chain_source.clone()), Arc::clone(&logger));
1682 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1683 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1684 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1685 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1686 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1687 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1689 let zero_hash = Sha256dHash::hash(&[0; 32]);
1690 let short_channel_id = 0;
1691 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1692 let amount_sats = 1000_000;
1695 // Announce a channel we will update
1696 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
1697 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_1_btckey).serialize())
1698 .push_slice(&PublicKey::from_secret_key(&secp_ctx, node_2_btckey).serialize())
1699 .push_opcode(opcodes::all::OP_PUSHNUM_2)
1700 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
1701 *chain_source.utxo_ret.lock().unwrap() = Ok(TxOut { value: amount_sats, script_pubkey: good_script.clone() });
1702 let unsigned_announcement = UnsignedChannelAnnouncement {
1703 features: ChannelFeatures::empty(),
1708 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1709 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1710 excess_data: Vec::new(),
1713 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1714 let valid_channel_announcement = ChannelAnnouncement {
1715 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1716 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1717 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1718 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1719 contents: unsigned_announcement.clone(),
1721 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1728 let mut unsigned_channel_update = UnsignedChannelUpdate {
1733 cltv_expiry_delta: 144,
1734 htlc_minimum_msat: 1000000,
1735 htlc_maximum_msat: OptionalField::Absent,
1736 fee_base_msat: 10000,
1737 fee_proportional_millionths: 20,
1738 excess_data: Vec::new()
1740 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1741 let valid_channel_update = ChannelUpdate {
1742 signature: secp_ctx.sign(&msghash, node_1_privkey),
1743 contents: unsigned_channel_update.clone()
1746 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1747 Ok(res) => assert!(res),
1752 let network = net_graph_msg_handler.network_graph.read().unwrap();
1753 match network.get_channels().get(&short_channel_id) {
1755 Some(channel_info) => {
1756 assert_eq!(channel_info.one_to_two.as_ref().unwrap().cltv_expiry_delta, 144);
1757 assert!(channel_info.two_to_one.is_none());
1762 unsigned_channel_update.timestamp += 100;
1763 unsigned_channel_update.excess_data.push(1);
1764 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1765 let valid_channel_update = ChannelUpdate {
1766 signature: secp_ctx.sign(&msghash, node_1_privkey),
1767 contents: unsigned_channel_update.clone()
1769 // Return false because contains excess data
1770 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1771 Ok(res) => assert!(!res),
1774 unsigned_channel_update.timestamp += 10;
1776 unsigned_channel_update.short_channel_id += 1;
1777 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1778 let valid_channel_update = ChannelUpdate {
1779 signature: secp_ctx.sign(&msghash, node_1_privkey),
1780 contents: unsigned_channel_update.clone()
1783 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1785 Err(e) => assert_eq!(e.err, "Couldn't find channel for update")
1787 unsigned_channel_update.short_channel_id = short_channel_id;
1789 unsigned_channel_update.htlc_maximum_msat = OptionalField::Present(MAX_VALUE_MSAT + 1);
1790 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1791 let valid_channel_update = ChannelUpdate {
1792 signature: secp_ctx.sign(&msghash, node_1_privkey),
1793 contents: unsigned_channel_update.clone()
1796 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1798 Err(e) => assert_eq!(e.err, "htlc_maximum_msat is larger than maximum possible msats")
1800 unsigned_channel_update.htlc_maximum_msat = OptionalField::Absent;
1802 unsigned_channel_update.htlc_maximum_msat = OptionalField::Present(amount_sats * 1000 + 1);
1803 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1804 let valid_channel_update = ChannelUpdate {
1805 signature: secp_ctx.sign(&msghash, node_1_privkey),
1806 contents: unsigned_channel_update.clone()
1809 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1811 Err(e) => assert_eq!(e.err, "htlc_maximum_msat is larger than channel capacity or capacity is bogus")
1813 unsigned_channel_update.htlc_maximum_msat = OptionalField::Absent;
1815 // Even though previous update was not relayed further, we still accepted it,
1816 // so we now won't accept update before the previous one.
1817 unsigned_channel_update.timestamp -= 10;
1818 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1819 let valid_channel_update = ChannelUpdate {
1820 signature: secp_ctx.sign(&msghash, node_1_privkey),
1821 contents: unsigned_channel_update.clone()
1824 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1826 Err(e) => assert_eq!(e.err, "Update older than last processed update")
1828 unsigned_channel_update.timestamp += 500;
1830 let fake_msghash = hash_to_message!(&zero_hash);
1831 let invalid_sig_channel_update = ChannelUpdate {
1832 signature: secp_ctx.sign(&fake_msghash, node_1_privkey),
1833 contents: unsigned_channel_update.clone()
1836 match net_graph_msg_handler.handle_channel_update(&invalid_sig_channel_update) {
1838 Err(e) => assert_eq!(e.err, "Invalid signature from remote node")
1844 fn handling_htlc_fail_channel_update() {
1845 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1846 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1847 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1848 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1849 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1850 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1851 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1853 let short_channel_id = 0;
1854 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1857 // There is no nodes in the table at the beginning.
1858 let network = net_graph_msg_handler.network_graph.read().unwrap();
1859 assert_eq!(network.get_nodes().len(), 0);
1863 // Announce a channel we will update
1864 let unsigned_announcement = UnsignedChannelAnnouncement {
1865 features: ChannelFeatures::empty(),
1870 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1871 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1872 excess_data: Vec::new(),
1875 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1876 let valid_channel_announcement = ChannelAnnouncement {
1877 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1878 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1879 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1880 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1881 contents: unsigned_announcement.clone(),
1883 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
1888 let unsigned_channel_update = UnsignedChannelUpdate {
1893 cltv_expiry_delta: 144,
1894 htlc_minimum_msat: 1000000,
1895 htlc_maximum_msat: OptionalField::Absent,
1896 fee_base_msat: 10000,
1897 fee_proportional_millionths: 20,
1898 excess_data: Vec::new()
1900 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
1901 let valid_channel_update = ChannelUpdate {
1902 signature: secp_ctx.sign(&msghash, node_1_privkey),
1903 contents: unsigned_channel_update.clone()
1906 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1907 Ok(res) => assert!(res),
1912 // Non-permanent closing just disables a channel
1914 let network = net_graph_msg_handler.network_graph.read().unwrap();
1915 match network.get_channels().get(&short_channel_id) {
1917 Some(channel_info) => {
1918 assert!(channel_info.one_to_two.is_some());
1923 let channel_close_msg = HTLCFailChannelUpdate::ChannelClosed {
1928 net_graph_msg_handler.handle_htlc_fail_channel_update(&channel_close_msg);
1930 // Non-permanent closing just disables a channel
1932 let network = net_graph_msg_handler.network_graph.read().unwrap();
1933 match network.get_channels().get(&short_channel_id) {
1935 Some(channel_info) => {
1936 assert!(!channel_info.one_to_two.as_ref().unwrap().enabled);
1941 let channel_close_msg = HTLCFailChannelUpdate::ChannelClosed {
1946 net_graph_msg_handler.handle_htlc_fail_channel_update(&channel_close_msg);
1948 // Permanent closing deletes a channel
1950 let network = net_graph_msg_handler.network_graph.read().unwrap();
1951 assert_eq!(network.get_channels().len(), 0);
1952 // Nodes are also deleted because there are no associated channels anymore
1953 assert_eq!(network.get_nodes().len(), 0);
1955 // TODO: Test HTLCFailChannelUpdate::NodeFailure, which is not implemented yet.
1959 fn getting_next_channel_announcements() {
1960 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
1961 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
1962 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
1963 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1964 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1965 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
1966 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
1968 let short_channel_id = 1;
1969 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
1971 // Channels were not announced yet.
1972 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(0, 1);
1973 assert_eq!(channels_with_announcements.len(), 0);
1976 // Announce a channel we will update
1977 let unsigned_announcement = UnsignedChannelAnnouncement {
1978 features: ChannelFeatures::empty(),
1983 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
1984 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
1985 excess_data: Vec::new(),
1988 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1989 let valid_channel_announcement = ChannelAnnouncement {
1990 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1991 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1992 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
1993 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
1994 contents: unsigned_announcement.clone(),
1996 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
2002 // Contains initial channel announcement now.
2003 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
2004 assert_eq!(channels_with_announcements.len(), 1);
2005 if let Some(channel_announcements) = channels_with_announcements.first() {
2006 let &(_, ref update_1, ref update_2) = channel_announcements;
2007 assert_eq!(update_1, &None);
2008 assert_eq!(update_2, &None);
2015 // Valid channel update
2016 let unsigned_channel_update = UnsignedChannelUpdate {
2021 cltv_expiry_delta: 144,
2022 htlc_minimum_msat: 1000000,
2023 htlc_maximum_msat: OptionalField::Absent,
2024 fee_base_msat: 10000,
2025 fee_proportional_millionths: 20,
2026 excess_data: Vec::new()
2028 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
2029 let valid_channel_update = ChannelUpdate {
2030 signature: secp_ctx.sign(&msghash, node_1_privkey),
2031 contents: unsigned_channel_update.clone()
2033 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
2039 // Now contains an initial announcement and an update.
2040 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
2041 assert_eq!(channels_with_announcements.len(), 1);
2042 if let Some(channel_announcements) = channels_with_announcements.first() {
2043 let &(_, ref update_1, ref update_2) = channel_announcements;
2044 assert_ne!(update_1, &None);
2045 assert_eq!(update_2, &None);
2052 // Channel update with excess data.
2053 let unsigned_channel_update = UnsignedChannelUpdate {
2058 cltv_expiry_delta: 144,
2059 htlc_minimum_msat: 1000000,
2060 htlc_maximum_msat: OptionalField::Absent,
2061 fee_base_msat: 10000,
2062 fee_proportional_millionths: 20,
2063 excess_data: [1; 3].to_vec()
2065 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_channel_update.encode()[..])[..]);
2066 let valid_channel_update = ChannelUpdate {
2067 signature: secp_ctx.sign(&msghash, node_1_privkey),
2068 contents: unsigned_channel_update.clone()
2070 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
2076 // Test that announcements with excess data won't be returned
2077 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id, 1);
2078 assert_eq!(channels_with_announcements.len(), 1);
2079 if let Some(channel_announcements) = channels_with_announcements.first() {
2080 let &(_, ref update_1, ref update_2) = channel_announcements;
2081 assert_eq!(update_1, &None);
2082 assert_eq!(update_2, &None);
2087 // Further starting point have no channels after it
2088 let channels_with_announcements = net_graph_msg_handler.get_next_channel_announcements(short_channel_id + 1000, 1);
2089 assert_eq!(channels_with_announcements.len(), 0);
2093 fn getting_next_node_announcements() {
2094 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
2095 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2096 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2097 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
2098 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
2099 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
2100 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
2102 let short_channel_id = 1;
2103 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2106 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 10);
2107 assert_eq!(next_announcements.len(), 0);
2110 // Announce a channel to add 2 nodes
2111 let unsigned_announcement = UnsignedChannelAnnouncement {
2112 features: ChannelFeatures::empty(),
2117 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
2118 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
2119 excess_data: Vec::new(),
2122 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
2123 let valid_channel_announcement = ChannelAnnouncement {
2124 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
2125 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
2126 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
2127 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
2128 contents: unsigned_announcement.clone(),
2130 match net_graph_msg_handler.handle_channel_announcement(&valid_channel_announcement) {
2137 // Nodes were never announced
2138 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
2139 assert_eq!(next_announcements.len(), 0);
2142 let mut unsigned_announcement = UnsignedNodeAnnouncement {
2143 features: NodeFeatures::known(),
2148 addresses: Vec::new(),
2149 excess_address_data: Vec::new(),
2150 excess_data: Vec::new(),
2152 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
2153 let valid_announcement = NodeAnnouncement {
2154 signature: secp_ctx.sign(&msghash, node_1_privkey),
2155 contents: unsigned_announcement.clone()
2157 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
2162 unsigned_announcement.node_id = node_id_2;
2163 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
2164 let valid_announcement = NodeAnnouncement {
2165 signature: secp_ctx.sign(&msghash, node_2_privkey),
2166 contents: unsigned_announcement.clone()
2169 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
2175 let next_announcements = net_graph_msg_handler.get_next_node_announcements(None, 3);
2176 assert_eq!(next_announcements.len(), 2);
2178 // Skip the first node.
2179 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
2180 assert_eq!(next_announcements.len(), 1);
2183 // Later announcement which should not be relayed (excess data) prevent us from sharing a node
2184 let unsigned_announcement = UnsignedNodeAnnouncement {
2185 features: NodeFeatures::known(),
2190 addresses: Vec::new(),
2191 excess_address_data: Vec::new(),
2192 excess_data: [1; 3].to_vec(),
2194 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
2195 let valid_announcement = NodeAnnouncement {
2196 signature: secp_ctx.sign(&msghash, node_2_privkey),
2197 contents: unsigned_announcement.clone()
2199 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
2200 Ok(res) => assert!(!res),
2205 let next_announcements = net_graph_msg_handler.get_next_node_announcements(Some(&node_id_1), 2);
2206 assert_eq!(next_announcements.len(), 0);
2210 fn network_graph_serialization() {
2211 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
2213 let node_1_privkey = &SecretKey::from_slice(&[42; 32]).unwrap();
2214 let node_2_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2215 let node_1_btckey = &SecretKey::from_slice(&[40; 32]).unwrap();
2216 let node_2_btckey = &SecretKey::from_slice(&[39; 32]).unwrap();
2218 // Announce a channel to add a corresponding node.
2219 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
2220 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
2221 let unsigned_announcement = UnsignedChannelAnnouncement {
2222 features: ChannelFeatures::known(),
2223 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2224 short_channel_id: 0,
2227 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, node_1_btckey),
2228 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, node_2_btckey),
2229 excess_data: Vec::new(),
2232 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
2233 let valid_announcement = ChannelAnnouncement {
2234 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
2235 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
2236 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_btckey),
2237 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_btckey),
2238 contents: unsigned_announcement.clone(),
2240 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
2241 Ok(res) => assert!(res),
2246 let node_id = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
2247 let unsigned_announcement = UnsignedNodeAnnouncement {
2248 features: NodeFeatures::known(),
2253 addresses: Vec::new(),
2254 excess_address_data: Vec::new(),
2255 excess_data: Vec::new(),
2257 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
2258 let valid_announcement = NodeAnnouncement {
2259 signature: secp_ctx.sign(&msghash, node_1_privkey),
2260 contents: unsigned_announcement.clone()
2263 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
2268 let network = net_graph_msg_handler.network_graph.write().unwrap();
2269 let mut w = test_utils::TestVecWriter(Vec::new());
2270 assert!(!network.get_nodes().is_empty());
2271 assert!(!network.get_channels().is_empty());
2272 network.write(&mut w).unwrap();
2273 assert!(<NetworkGraph>::read(&mut ::std::io::Cursor::new(&w.0)).unwrap() == *network);
2277 fn sending_query_channel_range() {
2278 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
2279 let node_privkey_1 = &SecretKey::from_slice(&[42; 32]).unwrap();
2280 let node_privkey_2 = &SecretKey::from_slice(&[41; 32]).unwrap();
2281 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_privkey_1);
2282 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_privkey_2);
2284 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2285 let first_blocknum = 0;
2286 let number_of_blocks = 0xffff_ffff;
2288 // When no active query exists for the node, it should send a query message and generate a task
2290 let result = net_graph_msg_handler.query_channel_range(&node_id_1, chain_hash, first_blocknum, number_of_blocks);
2291 assert!(result.is_ok());
2293 // It should create a task for the query
2294 assert!(net_graph_msg_handler.chan_range_query_tasks.lock().unwrap().contains_key(&node_id_1));
2296 // It should send a query_channel_range message with the correct information
2297 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
2298 assert_eq!(events.len(), 1);
2300 MessageSendEvent::SendChannelRangeQuery{ node_id, msg } => {
2301 assert_eq!(node_id, &node_id_1);
2302 assert_eq!(msg.chain_hash, chain_hash);
2303 assert_eq!(msg.first_blocknum, first_blocknum);
2304 assert_eq!(msg.number_of_blocks, number_of_blocks);
2306 _ => panic!("Expected MessageSendEvent::SendChannelRangeQuery")
2310 // When an active query exists for the node, when there is a subsequent query request, it
2311 // should fail to initiate a new query
2313 let result = net_graph_msg_handler.query_channel_range(&node_id_1, chain_hash, first_blocknum, number_of_blocks);
2314 assert_eq!(result.is_err(), true);
2317 // When no active query exists for a different node, it should send a query message
2319 let result = net_graph_msg_handler.query_channel_range(&node_id_2, chain_hash, first_blocknum, number_of_blocks);
2320 assert_eq!(result.is_ok(), true);
2322 // It should create a task for the query
2323 assert!(net_graph_msg_handler.chan_range_query_tasks.lock().unwrap().contains_key(&node_id_2));
2325 // It should send a query_channel_message with the correct information
2326 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
2327 assert_eq!(events.len(), 1);
2329 MessageSendEvent::SendChannelRangeQuery{ node_id, msg } => {
2330 assert_eq!(node_id, &node_id_2);
2331 assert_eq!(msg.chain_hash, chain_hash);
2332 assert_eq!(msg.first_blocknum, first_blocknum);
2333 assert_eq!(msg.number_of_blocks, number_of_blocks);
2335 _ => panic!("Expected MessageSendEvent::SendChannelRangeQuery")
2341 fn sending_query_short_channel_ids() {
2342 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
2343 let node_privkey_1 = &SecretKey::from_slice(&[42; 32]).unwrap();
2344 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_privkey_1);
2346 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2348 // The first query should send the batch of scids to the peer
2350 let short_channel_ids: Vec<u64> = vec![0, 1, 2];
2351 let result = net_graph_msg_handler.query_short_channel_ids(&node_id_1, chain_hash, short_channel_ids.clone());
2352 assert!(result.is_ok());
2354 // Validate that we have enqueued a send message event and that it contains the correct information
2355 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
2356 assert_eq!(events.len(), 1);
2358 MessageSendEvent::SendShortIdsQuery{ node_id, msg } => {
2359 assert_eq!(node_id, &node_id_1);
2360 assert_eq!(msg.chain_hash, chain_hash);
2361 assert_eq!(msg.short_channel_ids, short_channel_ids);
2363 _ => panic!("Expected MessageSendEvent::SendShortIdsQuery")
2367 // Subsequent queries for scids should enqueue them to be sent in the next batch which will
2368 // be sent when a reply_short_channel_ids_end message is handled.
2370 let short_channel_ids: Vec<u64> = vec![3, 4, 5];
2371 let result = net_graph_msg_handler.query_short_channel_ids(&node_id_1, chain_hash, short_channel_ids.clone());
2372 assert!(result.is_ok());
2374 // Validate that we have not enqueued another send message event yet
2375 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
2376 assert_eq!(events.len(), 0);
2378 // Validate the task has the queued scids
2380 net_graph_msg_handler.scid_query_tasks.lock().unwrap().get(&node_id_1).unwrap().short_channel_ids,
2387 fn handling_reply_channel_range() {
2388 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
2389 let node_privkey_1 = &SecretKey::from_slice(&[42; 32]).unwrap();
2390 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_privkey_1);
2392 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2394 // Test receipt of an unknown reply message. We expect an error
2396 let result = net_graph_msg_handler.handle_reply_channel_range(&node_id_1, &ReplyChannelRange {
2398 full_information: true,
2399 first_blocknum: 1000,
2400 number_of_blocks: 1050,
2401 short_channel_ids: vec![
2402 0x0003e8_000000_0000, // 1000x0x0
2403 0x0003e9_000000_0000, // 1001x0x0
2404 0x0003f0_000000_0000 // 1008x0x0
2407 assert!(result.is_err());
2410 // Test receipt of a single reply_channel_range that exactly matches the queried range.
2411 // It sends a query_short_channel_ids with the returned scids and removes the pending task
2413 // Initiate a channel range query to create a query task
2414 let result = net_graph_msg_handler.query_channel_range(&node_id_1, chain_hash, 1000, 100);
2415 assert!(result.is_ok());
2417 // Clear the SendRangeQuery event
2418 net_graph_msg_handler.get_and_clear_pending_msg_events();
2420 // Handle a single successful reply that matches the queried channel range
2421 let result = net_graph_msg_handler.handle_reply_channel_range(&node_id_1, &ReplyChannelRange {
2423 full_information: true,
2424 first_blocknum: 1000,
2425 number_of_blocks: 100,
2426 short_channel_ids: vec![
2427 0x0003e8_000000_0000, // 1000x0x0
2428 0x0003e9_000000_0000, // 1001x0x0
2429 0x0003f0_000000_0000 // 1008x0x0
2432 assert!(result.is_ok());
2434 // The query is now complete, so we expect the task to be removed
2435 assert!(net_graph_msg_handler.chan_range_query_tasks.lock().unwrap().is_empty());
2437 // We expect to emit a query_short_channel_ids message with scids in our query range
2438 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
2439 assert_eq!(events.len(), 1);
2441 MessageSendEvent::SendShortIdsQuery { node_id, msg } => {
2442 assert_eq!(node_id, &node_id_1);
2443 assert_eq!(msg.chain_hash, chain_hash);
2444 assert_eq!(msg.short_channel_ids, vec![0x0003e8_000000_0000,0x0003e9_000000_0000,0x0003f0_000000_0000]);
2446 _ => panic!("expected MessageSendEvent::SendShortIdsQuery"),
2449 // Clean up scid_task
2450 net_graph_msg_handler.scid_query_tasks.lock().unwrap().clear();
2453 // Test receipt of a single reply_channel_range for a query that has a u32 overflow. We expect
2454 // it sends a query_short_channel_ids with the returned scids and removes the pending task.
2456 // Initiate a channel range query to create a query task
2457 let result = net_graph_msg_handler.query_channel_range(&node_id_1, chain_hash, 1000, 0xffff_ffff);
2458 assert!(result.is_ok());
2460 // Clear the SendRangeQuery event
2461 net_graph_msg_handler.get_and_clear_pending_msg_events();
2463 // Handle a single successful reply that matches the queried channel range
2464 let result = net_graph_msg_handler.handle_reply_channel_range(&node_id_1, &ReplyChannelRange {
2466 full_information: true,
2467 first_blocknum: 1000,
2468 number_of_blocks: 0xffff_ffff,
2469 short_channel_ids: vec![
2470 0x0003e8_000000_0000, // 1000x0x0
2471 0x0003e9_000000_0000, // 1001x0x0
2472 0x0003f0_000000_0000 // 1008x0x0
2475 assert!(result.is_ok());
2477 // The query is now complete, so we expect the task to be removed
2478 assert!(net_graph_msg_handler.chan_range_query_tasks.lock().unwrap().is_empty());
2480 // We expect to emit a query_short_channel_ids message with scids in our query range
2481 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
2482 assert_eq!(events.len(), 1);
2484 MessageSendEvent::SendShortIdsQuery { node_id, msg } => {
2485 assert_eq!(node_id, &node_id_1);
2486 assert_eq!(msg.chain_hash, chain_hash);
2487 assert_eq!(msg.short_channel_ids, vec![0x0003e8_000000_0000,0x0003e9_000000_0000,0x0003f0_000000_0000]);
2489 _ => panic!("expected MessageSendEvent::SendShortIdsQuery"),
2492 // Clean up scid_task
2493 net_graph_msg_handler.scid_query_tasks.lock().unwrap().clear();
2496 // Test receipt of a single reply that encompasses the queried channel range. This is allowed
2497 // since a reply must contain at least part of the query range. Receipt of the reply should
2498 // send a query_short_channel_ids message with scids filtered to the query range and remove
2499 // the pending task.
2501 // Initiate a channel range query to create a query task
2502 let result = net_graph_msg_handler.query_channel_range(&node_id_1, chain_hash, 1000, 100);
2503 assert!(result.is_ok());
2505 // Clear the SendRangeQuery event
2506 net_graph_msg_handler.get_and_clear_pending_msg_events();
2508 // Handle a single successful reply that encompasses the queried channel range
2509 let result = net_graph_msg_handler.handle_reply_channel_range(&node_id_1, &ReplyChannelRange {
2511 full_information: true,
2513 number_of_blocks: 2000,
2514 short_channel_ids: vec![
2515 0x0003e0_000000_0000, // 992x0x0
2516 0x0003e8_000000_0000, // 1000x0x0
2517 0x0003e9_000000_0000, // 1001x0x0
2518 0x0003f0_000000_0000, // 1008x0x0
2519 0x00044c_000000_0000, // 1100x0x0
2520 0x0006e0_000000_0000, // 1760x0x0
2523 assert!(result.is_ok());
2525 // The query is now complete, so we expect the task to be removed
2526 assert!(net_graph_msg_handler.chan_range_query_tasks.lock().unwrap().is_empty());
2528 // We expect to emit a query_short_channel_ids message with scids filtered to those
2529 // within the original query range.
2530 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
2531 assert_eq!(events.len(), 1);
2533 MessageSendEvent::SendShortIdsQuery { node_id, msg } => {
2534 assert_eq!(node_id, &node_id_1);
2535 assert_eq!(msg.chain_hash, chain_hash);
2536 assert_eq!(msg.short_channel_ids, vec![0x0003e8_000000_0000,0x0003e9_000000_0000,0x0003f0_000000_0000]);
2538 _ => panic!("expected MessageSendEvent::SendShortIdsQuery"),
2541 // Clean up scid_task
2542 net_graph_msg_handler.scid_query_tasks.lock().unwrap().clear();
2545 // Test receipt of multiple reply messages for a single query. This happens when the number
2546 // of scids in the query range exceeds the size limits of a single reply message. We expect
2547 // to initiate a query_short_channel_ids for the first batch of scids and we enqueue the
2548 // remaining scids for later processing. We remove the range query task after receipt of all
2551 // Initiate a channel range query to create a query task
2552 let result = net_graph_msg_handler.query_channel_range(&node_id_1, chain_hash, 1000, 100);
2553 assert!(result.is_ok());
2555 // Clear the SendRangeQuery event
2556 net_graph_msg_handler.get_and_clear_pending_msg_events();
2558 // Handle the first reply message
2559 let reply_1_scids = vec![
2560 0x0003e8_000000_0000, // 1000x0x0
2561 0x0003e9_000000_0000, // 1001x0x0
2562 0x000419_000000_0000, // 1049x0x0
2564 let result = net_graph_msg_handler.handle_reply_channel_range(&node_id_1, &ReplyChannelRange {
2566 full_information: true,
2567 first_blocknum: 1000,
2568 number_of_blocks: 50,
2569 short_channel_ids: reply_1_scids.clone(),
2571 assert!(result.is_ok());
2573 // Handle the next reply in the sequence, which must start at the previous message's
2574 // first_blocknum plus number_of_blocks. The scids in this reply will be queued.
2575 let reply_2_scids = vec![
2576 0x00041a_000000_0000, // 1050x0x0
2577 0x000432_000000_0000, // 1074x0x0
2579 let result = net_graph_msg_handler.handle_reply_channel_range(&node_id_1, &ReplyChannelRange {
2581 full_information: true,
2582 first_blocknum: 1050,
2583 number_of_blocks: 25,
2584 short_channel_ids: reply_2_scids.clone(),
2586 assert!(result.is_ok());
2588 // Handle the final reply in the sequence, which must meet or exceed the initial query's
2589 // first_blocknum plus number_of_blocks. The scids in this reply will be queued.
2590 let reply_3_scids = vec![
2591 0x000433_000000_0000, // 1075x0x0
2592 0x00044b_000000_0000, // 1099x0x0
2594 let result = net_graph_msg_handler.handle_reply_channel_range(&node_id_1, &ReplyChannelRange {
2596 full_information: true,
2597 first_blocknum: 1075,
2598 number_of_blocks: 25,
2599 short_channel_ids: reply_3_scids.clone(),
2601 assert!(result.is_ok());
2603 // After the final reply we expect the query task to be removed
2604 assert!(net_graph_msg_handler.chan_range_query_tasks.lock().unwrap().is_empty());
2606 // We expect to emit a query_short_channel_ids message with the accumulated scids that
2607 // match the queried channel range.
2608 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
2609 assert_eq!(events.len(), 1);
2611 MessageSendEvent::SendShortIdsQuery { node_id, msg } => {
2612 assert_eq!(node_id, &node_id_1);
2613 assert_eq!(msg.chain_hash, chain_hash);
2614 assert_eq!(msg.short_channel_ids, [reply_1_scids, reply_2_scids, reply_3_scids].concat());
2616 _ => panic!("expected MessageSendEvent::SendShortIdsQuery"),
2619 // Clean up scid_task
2620 net_graph_msg_handler.scid_query_tasks.lock().unwrap().clear();
2623 // Test receipt of a sequence of replies with a valid first reply and a second reply that
2624 // resumes on the same block as the first reply. The spec requires a subsequent
2625 // first_blocknum to equal the prior first_blocknum plus number_of_blocks, however
2626 // due to discrepancies in implementation we must loosen this restriction.
2628 // Initiate a channel range query to create a query task
2629 let result = net_graph_msg_handler.query_channel_range(&node_id_1, chain_hash, 1000, 100);
2630 assert!(result.is_ok());
2632 // Clear the SendRangeQuery event
2633 net_graph_msg_handler.get_and_clear_pending_msg_events();
2635 // Handle the first reply message
2636 let reply_1_scids = vec![
2637 0x0003e8_000000_0000, // 1000x0x0
2638 0x0003e9_000000_0000, // 1001x0x0
2639 0x000419_000000_0000, // 1049x0x0
2641 let result = net_graph_msg_handler.handle_reply_channel_range(&node_id_1, &ReplyChannelRange {
2643 full_information: true,
2644 first_blocknum: 1000,
2645 number_of_blocks: 50,
2646 short_channel_ids: reply_1_scids.clone(),
2648 assert!(result.is_ok());
2650 // Handle the next reply in the sequence, which is non-spec but resumes on the last block
2651 // of the first message.
2652 let reply_2_scids = vec![
2653 0x000419_000001_0000, // 1049x1x0
2654 0x00041a_000000_0000, // 1050x0x0
2655 0x000432_000000_0000, // 1074x0x0
2657 let result = net_graph_msg_handler.handle_reply_channel_range(&node_id_1, &ReplyChannelRange {
2659 full_information: true,
2660 first_blocknum: 1049,
2661 number_of_blocks: 51,
2662 short_channel_ids: reply_2_scids.clone(),
2664 assert!(result.is_ok());
2666 // After the final reply we expect the query task to be removed
2667 assert!(net_graph_msg_handler.chan_range_query_tasks.lock().unwrap().is_empty());
2669 // We expect to emit a query_short_channel_ids message with the accumulated scids that
2670 // match the queried channel range
2671 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
2672 assert_eq!(events.len(), 1);
2674 MessageSendEvent::SendShortIdsQuery { node_id, msg } => {
2675 assert_eq!(node_id, &node_id_1);
2676 assert_eq!(msg.chain_hash, chain_hash);
2677 assert_eq!(msg.short_channel_ids, [reply_1_scids, reply_2_scids].concat());
2679 _ => panic!("expected MessageSendEvent::SendShortIdsQuery"),
2682 // Clean up scid_task
2683 net_graph_msg_handler.scid_query_tasks.lock().unwrap().clear();
2686 // Test receipt of reply with a chain_hash that does not match the query. We expect to return
2687 // an error and to remove the query task.
2689 // Initiate a channel range query to create a query task
2690 let result = net_graph_msg_handler.query_channel_range(&node_id_1, chain_hash, 1000, 100);
2691 assert!(result.is_ok());
2693 // Clear the SendRangeQuery event
2694 net_graph_msg_handler.get_and_clear_pending_msg_events();
2696 // Handle the reply with a mismatched chain_hash. We expect IgnoreError result and the
2697 // task should be removed.
2698 let result = net_graph_msg_handler.handle_reply_channel_range(&node_id_1, &ReplyChannelRange {
2699 chain_hash: genesis_block(Network::Bitcoin).header.block_hash(),
2700 full_information: true,
2701 first_blocknum: 1000,
2702 number_of_blocks: 1050,
2703 short_channel_ids: vec![0x0003e8_000000_0000,0x0003e9_000000_0000,0x0003f0_000000_0000],
2705 assert!(result.is_err());
2706 assert_eq!(result.err().unwrap().err, "Received reply_channel_range with invalid chain_hash");
2707 assert!(net_graph_msg_handler.chan_range_query_tasks.lock().unwrap().is_empty());
2710 // Test receipt of a reply that indicates the remote node does not maintain up-to-date
2711 // information for the chain_hash. Because of discrepancies in implementation we use
2712 // full_information=false and short_channel_ids=[] as the signal. We should expect an error
2713 // and the task should be removed.
2715 // Initiate a channel range query to create a query task
2716 let result = net_graph_msg_handler.query_channel_range(&node_id_1, chain_hash, 1000, 100);
2717 assert!(result.is_ok());
2719 // Clear the SendRangeQuery event
2720 net_graph_msg_handler.get_and_clear_pending_msg_events();
2722 // Handle the reply indicating the peer was unable to fulfill our request.
2723 let result = net_graph_msg_handler.handle_reply_channel_range(&node_id_1, &ReplyChannelRange {
2725 full_information: false,
2726 first_blocknum: 1000,
2727 number_of_blocks: 100,
2728 short_channel_ids: vec![],
2730 assert!(result.is_err());
2731 assert_eq!(result.err().unwrap().err, "Received reply_channel_range with no information available");
2732 assert!(net_graph_msg_handler.chan_range_query_tasks.lock().unwrap().is_empty());
2735 // Test receipt of a reply that has a first_blocknum that is above the first_blocknum
2736 // requested in our query. The reply must contain the queried block range. We expect an
2737 // error result and the task should be removed.
2739 // Initiate a channel range query to create a query task
2740 let result = net_graph_msg_handler.query_channel_range(&node_id_1, chain_hash, 1000, 100);
2741 assert!(result.is_ok());
2743 // Clear the SendRangeQuery event
2744 net_graph_msg_handler.get_and_clear_pending_msg_events();
2746 // Handle the reply that has a first_blocknum above the query's first_blocknum
2747 let result = net_graph_msg_handler.handle_reply_channel_range(&node_id_1, &ReplyChannelRange {
2749 full_information: true,
2750 first_blocknum: 1001,
2751 number_of_blocks: 100,
2752 short_channel_ids: vec![],
2754 assert!(result.is_err());
2755 assert_eq!(result.err().unwrap().err, "Failing reply_channel_range with invalid first_blocknum");
2756 assert!(net_graph_msg_handler.chan_range_query_tasks.lock().unwrap().is_empty());
2759 // Test receipt of a first reply that does not overlap the query range at all. The first message
2760 // must have some overlap with the query. We expect an error result and the task should
2763 // Initiate a channel range query to create a query task
2764 let result = net_graph_msg_handler.query_channel_range(&node_id_1, chain_hash, 1000, 100);
2765 assert!(result.is_ok());
2767 // Clear the SendRangeQuery event
2768 net_graph_msg_handler.get_and_clear_pending_msg_events();
2770 // Handle a reply that contains a block range that precedes the queried block range
2771 let result = net_graph_msg_handler.handle_reply_channel_range(&node_id_1, &ReplyChannelRange {
2773 full_information: true,
2775 number_of_blocks: 1000,
2776 short_channel_ids: vec![],
2778 assert!(result.is_err());
2779 assert_eq!(result.err().unwrap().err, "Failing reply_channel_range with non-overlapping first reply");
2780 assert!(net_graph_msg_handler.chan_range_query_tasks.lock().unwrap().is_empty());
2783 // Test receipt of a sequence of replies with a valid first reply and a second reply that is
2784 // non-sequential. The spec requires a subsequent first_blocknum to equal the prior
2785 // first_blocknum plus number_of_blocks. We expect an IgnoreError result and the task should
2788 // Initiate a channel range query to create a query task
2789 let result = net_graph_msg_handler.query_channel_range(&node_id_1, chain_hash, 1000, 100);
2790 assert!(result.is_ok());
2792 // Clear the SendRangeQuery event
2793 net_graph_msg_handler.get_and_clear_pending_msg_events();
2795 // Handle the first reply
2796 let result = net_graph_msg_handler.handle_reply_channel_range(&node_id_1, &ReplyChannelRange {
2798 full_information: true,
2799 first_blocknum: 1000,
2800 number_of_blocks: 50,
2801 short_channel_ids: vec![0x0003e8_000000_0000,0x0003e9_000000_0000,0x0003f0_000000_0000],
2803 assert!(result.is_ok());
2805 // Handle the second reply which does not start at the proper first_blocknum. We expect
2806 // to return an error and remove the task.
2807 let result = net_graph_msg_handler.handle_reply_channel_range(&node_id_1, &ReplyChannelRange {
2809 full_information: true,
2810 first_blocknum: 1051,
2811 number_of_blocks: 50,
2812 short_channel_ids: vec![0x0003f1_000000_0000,0x0003f2_000000_0000],
2814 assert!(result.is_err());
2815 assert_eq!(result.err().unwrap().err, "Failing reply_channel_range with invalid sequence");
2816 assert!(net_graph_msg_handler.chan_range_query_tasks.lock().unwrap().is_empty());
2819 // Test receipt of too many reply messages. We expect an IgnoreError result and the task should
2822 // Initiate a channel range query to create a query task
2823 let result = net_graph_msg_handler.query_channel_range(&node_id_1, chain_hash, 1000, 0xffff_ffff);
2824 assert!(result.is_ok());
2826 // Clear the SendRangeQuery event
2827 net_graph_msg_handler.get_and_clear_pending_msg_events();
2829 // Handle a sequence of replies that will fail once the max number of reply has been exceeded.
2830 for block in 1000..=1000 + super::MAX_REPLY_CHANNEL_RANGE_PER_QUERY + 10 {
2831 let result = net_graph_msg_handler.handle_reply_channel_range(&node_id_1, &ReplyChannelRange {
2833 full_information: true,
2834 first_blocknum: block as u32,
2835 number_of_blocks: 1,
2836 short_channel_ids: vec![(block as u64) << 40],
2838 if block <= 1000 + super::MAX_REPLY_CHANNEL_RANGE_PER_QUERY {
2839 assert!(result.is_ok());
2840 } else if block == 1001 + super::MAX_REPLY_CHANNEL_RANGE_PER_QUERY {
2841 assert!(result.is_err());
2842 assert_eq!(result.err().unwrap().err, "Failing reply_channel_range due to excessive messages");
2844 assert!(result.is_err());
2845 assert_eq!(result.err().unwrap().err, "Received unknown reply_channel_range message");
2849 // Expect the task to be removed
2850 assert!(net_graph_msg_handler.chan_range_query_tasks.lock().unwrap().is_empty());
2855 fn handling_reply_short_channel_ids() {
2856 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
2857 let node_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2858 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
2860 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2862 // Test receipt of a reply when no query exists. We expect an error to be returned
2864 let result = net_graph_msg_handler.handle_reply_short_channel_ids_end(&node_id, &ReplyShortChannelIdsEnd {
2866 full_information: true,
2868 assert!(result.is_err());
2869 assert_eq!(result.err().unwrap().err, "Unknown reply_short_channel_ids_end message");
2872 // Test receipt of a reply that is for a different chain_hash. We expect an error and the task
2873 // should be removed.
2875 // Initiate a query to create a pending query task
2876 let result = net_graph_msg_handler.query_short_channel_ids(&node_id, chain_hash, vec![0x0003e8_000000_0000]);
2877 assert!(result.is_ok());
2879 // Process reply with incorrect chain_hash
2880 let result = net_graph_msg_handler.handle_reply_short_channel_ids_end(&node_id, &ReplyShortChannelIdsEnd {
2881 chain_hash: genesis_block(Network::Bitcoin).header.block_hash(),
2882 full_information: true,
2884 assert!(result.is_err());
2885 assert_eq!(result.err().unwrap().err, "Received reply_short_channel_ids_end with incorrect chain_hash");
2887 // Expect the task to be removed
2888 assert!(net_graph_msg_handler.scid_query_tasks.lock().unwrap().is_empty());
2891 // Test receipt of a reply that indicates the peer does not maintain up-to-date information
2892 // for the chain_hash requested in the query. We expect an error and task should be removed.
2894 // Initiate a query to create a pending query task
2895 let result = net_graph_msg_handler.query_short_channel_ids(&node_id, chain_hash, vec![0x0003e8_000000_0000]);
2896 assert!(result.is_ok());
2898 // Process failed reply
2899 let result = net_graph_msg_handler.handle_reply_short_channel_ids_end(&node_id, &ReplyShortChannelIdsEnd {
2901 full_information: false,
2903 assert!(result.is_err());
2904 assert_eq!(result.err().unwrap().err, "Received reply_short_channel_ids_end with no information");
2906 // Expect the task to be removed
2907 assert!(net_graph_msg_handler.scid_query_tasks.lock().unwrap().is_empty());
2910 // Test receipt of a successful reply when there are no additional scids to query. We expect
2911 // the task to be removed.
2913 // Initiate a query to create a pending query task
2914 let result = net_graph_msg_handler.query_short_channel_ids(&node_id, chain_hash, vec![0x0003e8_000000_0000]);
2915 assert!(result.is_ok());
2917 // Process success reply
2918 let result = net_graph_msg_handler.handle_reply_short_channel_ids_end(&node_id, &ReplyShortChannelIdsEnd {
2920 full_information: true,
2922 assert!(result.is_ok());
2924 // Expect the task to be removed
2925 assert!(net_graph_msg_handler.scid_query_tasks.lock().unwrap().is_empty());
2928 // Test receipt of a successful reply when there are additional scids to query. We expect
2929 // additional queries to be sent until the task can be removed.
2931 // Initiate a query to create a pending query task
2932 let result = net_graph_msg_handler.query_short_channel_ids(&node_id, chain_hash, vec![0x0003e8_000000_0000]);
2933 assert!(result.is_ok());
2935 // Initiate a second query to add pending scids to the task
2936 let result = net_graph_msg_handler.query_short_channel_ids(&node_id, chain_hash, vec![0x0003e9_000000_0000]);
2937 assert!(result.is_ok());
2938 assert_eq!(net_graph_msg_handler.scid_query_tasks.lock().unwrap().get(&node_id).unwrap().short_channel_ids, vec![0x0003e9_000000_0000]);
2940 // Initiate a third query to add pending scids to the task
2941 let result = net_graph_msg_handler.query_short_channel_ids(&node_id, chain_hash, vec![0x0003f0_000000_0000]);
2942 assert!(result.is_ok());
2943 assert_eq!(net_graph_msg_handler.scid_query_tasks.lock().unwrap().get(&node_id).unwrap().short_channel_ids, vec![0x0003e9_000000_0000, 0x0003f0_000000_0000]);
2945 // Clear all of the pending send events
2946 net_graph_msg_handler.get_and_clear_pending_msg_events();
2948 // Handle the first successful reply, which will send the next batch of scids in a new query
2949 let result = net_graph_msg_handler.handle_reply_short_channel_ids_end(&node_id, &ReplyShortChannelIdsEnd {
2951 full_information: true,
2953 assert!(result.is_ok());
2955 // We expect the second batch to be sent in an event
2956 let expected_node_id = &node_id;
2957 let events = net_graph_msg_handler.get_and_clear_pending_msg_events();
2958 assert_eq!(events.len(), 1);
2960 MessageSendEvent::SendShortIdsQuery { node_id, msg } => {
2961 assert_eq!(node_id, expected_node_id);
2962 assert_eq!(msg.chain_hash, chain_hash);
2963 assert_eq!(msg.short_channel_ids, vec![0x0003e9_000000_0000, 0x0003f0_000000_0000]);
2965 _ => panic!("expected MessageSendEvent::SendShortIdsQuery"),
2968 // We expect the scids to be cleared from the task
2969 assert_eq!(net_graph_msg_handler.scid_query_tasks.lock().unwrap().get(&node_id).unwrap().short_channel_ids.len(), 0);
2971 // Handle the second successful reply
2972 let result = net_graph_msg_handler.handle_reply_short_channel_ids_end(&node_id, &ReplyShortChannelIdsEnd {
2974 full_information: true,
2976 assert!(result.is_ok());
2978 // We expect the task should be removed
2979 assert!(net_graph_msg_handler.scid_query_tasks.lock().unwrap().is_empty());
2984 fn handling_query_channel_range() {
2985 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
2986 let node_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
2987 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
2989 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
2991 let result = net_graph_msg_handler.handle_query_channel_range(&node_id, &QueryChannelRange {
2994 number_of_blocks: 0xffff_ffff,
2996 assert!(result.is_err());
3000 fn handling_query_short_channel_ids() {
3001 let (secp_ctx, net_graph_msg_handler) = create_net_graph_msg_handler();
3002 let node_privkey = &SecretKey::from_slice(&[41; 32]).unwrap();
3003 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
3005 let chain_hash = genesis_block(Network::Testnet).header.block_hash();
3007 let result = net_graph_msg_handler.handle_query_short_channel_ids(&node_id, &QueryShortChannelIds {
3009 short_channel_ids: vec![0x0003e8_000000_0000],
3011 assert!(result.is_err());