Dataset Viewer
Auto-converted to Parquet Duplicate
repo
stringclasses
1 value
pull_number
int64
878
3.02k
instance_id
stringclasses
9 values
issue_numbers
sequencelengths
1
2
base_commit
stringclasses
9 values
patch
stringclasses
9 values
test_patch
stringclasses
9 values
problem_statement
stringclasses
9 values
hints_text
stringclasses
4 values
created_at
stringclasses
9 values
version
stringclasses
3 values
AleoNet/snarkOS
3,015
AleoNet__snarkOS-3015
[ "2983" ]
bd165ecfcb81e72a167b2a984ba28531d543ab44
diff --git a/node/bft/events/src/challenge_response.rs b/node/bft/events/src/challenge_response.rs index 0fc678a86d..aad59f760f 100644 --- a/node/bft/events/src/challenge_response.rs +++ b/node/bft/events/src/challenge_response.rs @@ -17,6 +17,7 @@ use super::*; #[derive(Clone, Debug, PartialEq, Eq)] pub struct ChallengeResponse<N: Network> { pub signature: Data<Signature<N>>, + pub nonce: u64, } impl<N: Network> EventTrait for ChallengeResponse<N> { @@ -30,6 +31,7 @@ impl<N: Network> EventTrait for ChallengeResponse<N> { impl<N: Network> ToBytes for ChallengeResponse<N> { fn write_le<W: Write>(&self, mut writer: W) -> IoResult<()> { self.signature.write_le(&mut writer)?; + self.nonce.write_le(&mut writer)?; Ok(()) } } @@ -37,8 +39,9 @@ impl<N: Network> ToBytes for ChallengeResponse<N> { impl<N: Network> FromBytes for ChallengeResponse<N> { fn read_le<R: Read>(mut reader: R) -> IoResult<Self> { let signature = Data::read_le(&mut reader)?; + let nonce = u64::read_le(&mut reader)?; - Ok(Self { signature }) + Ok(Self { signature, nonce }) } } @@ -53,7 +56,7 @@ pub mod prop_tests { }; use bytes::{Buf, BufMut, BytesMut}; - use proptest::prelude::{BoxedStrategy, Strategy}; + use proptest::prelude::{any, BoxedStrategy, Strategy}; use test_strategy::proptest; type CurrentNetwork = snarkvm::prelude::Testnet3; @@ -70,7 +73,9 @@ pub mod prop_tests { } pub fn any_challenge_response() -> BoxedStrategy<ChallengeResponse<CurrentNetwork>> { - any_signature().prop_map(|sig| ChallengeResponse { signature: Data::Object(sig) }).boxed() + (any_signature(), any::<u64>()) + .prop_map(|(sig, nonce)| ChallengeResponse { signature: Data::Object(sig), nonce }) + .boxed() } #[proptest] diff --git a/node/bft/events/src/lib.rs b/node/bft/events/src/lib.rs index d49073b1c5..7a3c6d30ef 100644 --- a/node/bft/events/src/lib.rs +++ b/node/bft/events/src/lib.rs @@ -118,7 +118,7 @@ impl<N: Network> From<DisconnectReason> for Event<N> { impl<N: Network> Event<N> { /// The version of the event protocol; it can be incremented in order to force users to update. - pub const VERSION: u32 = 5; + pub const VERSION: u32 = 6; /// Returns the event name. #[inline] diff --git a/node/bft/src/gateway.rs b/node/bft/src/gateway.rs index d6b8c000d4..ecbfdb110a 100644 --- a/node/bft/src/gateway.rs +++ b/node/bft/src/gateway.rs @@ -1176,11 +1176,13 @@ impl<N: Network> Gateway<N> { /* Step 3: Send the challenge response. */ // Sign the counterparty nonce. - let Ok(our_signature) = self.account.sign_bytes(&peer_request.nonce.to_le_bytes(), rng) else { + let response_nonce: u64 = rng.gen(); + let data = [peer_request.nonce.to_le_bytes(), response_nonce.to_le_bytes()].concat(); + let Ok(our_signature) = self.account.sign_bytes(&data, rng) else { return Err(error(format!("Failed to sign the challenge request nonce from '{peer_addr}'"))); }; // Send the challenge response. - let our_response = ChallengeResponse { signature: Data::Object(our_signature) }; + let our_response = ChallengeResponse { signature: Data::Object(our_signature), nonce: response_nonce }; send_event(&mut framed, peer_addr, Event::ChallengeResponse(our_response)).await?; // Add the peer to the gateway. @@ -1229,11 +1231,13 @@ impl<N: Network> Gateway<N> { let rng = &mut rand::rngs::OsRng; // Sign the counterparty nonce. - let Ok(our_signature) = self.account.sign_bytes(&peer_request.nonce.to_le_bytes(), rng) else { + let response_nonce: u64 = rng.gen(); + let data = [peer_request.nonce.to_le_bytes(), response_nonce.to_le_bytes()].concat(); + let Ok(our_signature) = self.account.sign_bytes(&data, rng) else { return Err(error(format!("Failed to sign the challenge request nonce from '{peer_addr}'"))); }; // Send the challenge response. - let our_response = ChallengeResponse { signature: Data::Object(our_signature) }; + let our_response = ChallengeResponse { signature: Data::Object(our_signature), nonce: response_nonce }; send_event(&mut framed, peer_addr, Event::ChallengeResponse(our_response)).await?; // Sample a random nonce. @@ -1290,14 +1294,14 @@ impl<N: Network> Gateway<N> { expected_nonce: u64, ) -> Option<DisconnectReason> { // Retrieve the components of the challenge response. - let ChallengeResponse { signature } = response; + let ChallengeResponse { signature, nonce } = response; // Perform the deferred non-blocking deserialization of the signature. let Ok(signature) = spawn_blocking!(signature.deserialize_blocking()) else { warn!("{CONTEXT} Gateway handshake with '{peer_addr}' failed (cannot deserialize the signature)"); return Some(DisconnectReason::InvalidChallengeResponse); }; // Verify the signature. - if !signature.verify_bytes(&peer_address, &expected_nonce.to_le_bytes()) { + if !signature.verify_bytes(&peer_address, &[expected_nonce.to_le_bytes(), nonce.to_le_bytes()].concat()) { warn!("{CONTEXT} Gateway handshake with '{peer_addr}' failed (invalid signature)"); return Some(DisconnectReason::InvalidChallengeResponse); } diff --git a/node/router/messages/src/challenge_response.rs b/node/router/messages/src/challenge_response.rs index 3c75d4db19..d51c5bb717 100644 --- a/node/router/messages/src/challenge_response.rs +++ b/node/router/messages/src/challenge_response.rs @@ -25,6 +25,7 @@ use std::borrow::Cow; pub struct ChallengeResponse<N: Network> { pub genesis_header: Header<N>, pub signature: Data<Signature<N>>, + pub nonce: u64, } impl<N: Network> MessageTrait for ChallengeResponse<N> { @@ -38,13 +39,18 @@ impl<N: Network> MessageTrait for ChallengeResponse<N> { impl<N: Network> ToBytes for ChallengeResponse<N> { fn write_le<W: io::Write>(&self, mut writer: W) -> io::Result<()> { self.genesis_header.write_le(&mut writer)?; - self.signature.write_le(&mut writer) + self.signature.write_le(&mut writer)?; + self.nonce.write_le(&mut writer) } } impl<N: Network> FromBytes for ChallengeResponse<N> { fn read_le<R: io::Read>(mut reader: R) -> io::Result<Self> { - Ok(Self { genesis_header: Header::read_le(&mut reader)?, signature: Data::read_le(reader)? }) + Ok(Self { + genesis_header: Header::read_le(&mut reader)?, + signature: Data::read_le(&mut reader)?, + nonce: u64::read_le(reader)?, + }) } } @@ -80,8 +86,12 @@ pub mod prop_tests { } pub fn any_challenge_response() -> BoxedStrategy<ChallengeResponse<CurrentNetwork>> { - (any_signature(), any_genesis_header()) - .prop_map(|(sig, genesis_header)| ChallengeResponse { signature: Data::Object(sig), genesis_header }) + (any_signature(), any_genesis_header(), any::<u64>()) + .prop_map(|(sig, genesis_header, nonce)| ChallengeResponse { + signature: Data::Object(sig), + genesis_header, + nonce, + }) .boxed() } diff --git a/node/router/messages/src/lib.rs b/node/router/messages/src/lib.rs index baa512b5b4..09b065a49d 100644 --- a/node/router/messages/src/lib.rs +++ b/node/router/messages/src/lib.rs @@ -111,7 +111,7 @@ impl<N: Network> From<DisconnectReason> for Message<N> { impl<N: Network> Message<N> { /// The version of the network protocol; it can be incremented in order to force users to update. - pub const VERSION: u32 = 13; + pub const VERSION: u32 = 14; /// Returns the message name. #[inline] diff --git a/node/router/src/handshake.rs b/node/router/src/handshake.rs index 7ccb67fa89..195298eaea 100644 --- a/node/router/src/handshake.rs +++ b/node/router/src/handshake.rs @@ -164,12 +164,15 @@ impl<N: Network> Router<N> { } /* Step 3: Send the challenge response. */ + let response_nonce: u64 = rng.gen(); + let data = [peer_request.nonce.to_le_bytes(), response_nonce.to_le_bytes()].concat(); // Sign the counterparty nonce. - let Ok(our_signature) = self.account.sign_bytes(&peer_request.nonce.to_le_bytes(), rng) else { + let Ok(our_signature) = self.account.sign_bytes(&data, rng) else { return Err(error(format!("Failed to sign the challenge request nonce from '{peer_addr}'"))); }; // Send the challenge response. - let our_response = ChallengeResponse { genesis_header, signature: Data::Object(our_signature) }; + let our_response = + ChallengeResponse { genesis_header, signature: Data::Object(our_signature), nonce: response_nonce }; send(&mut framed, peer_addr, Message::ChallengeResponse(our_response)).await?; // Add the peer to the router. @@ -213,11 +216,14 @@ impl<N: Network> Router<N> { let rng = &mut OsRng; // Sign the counterparty nonce. - let Ok(our_signature) = self.account.sign_bytes(&peer_request.nonce.to_le_bytes(), rng) else { + let response_nonce: u64 = rng.gen(); + let data = [peer_request.nonce.to_le_bytes(), response_nonce.to_le_bytes()].concat(); + let Ok(our_signature) = self.account.sign_bytes(&data, rng) else { return Err(error(format!("Failed to sign the challenge request nonce from '{peer_addr}'"))); }; // Send the challenge response. - let our_response = ChallengeResponse { genesis_header, signature: Data::Object(our_signature) }; + let our_response = + ChallengeResponse { genesis_header, signature: Data::Object(our_signature), nonce: response_nonce }; send(&mut framed, peer_addr, Message::ChallengeResponse(our_response)).await?; // Sample a random nonce. @@ -303,7 +309,7 @@ impl<N: Network> Router<N> { expected_nonce: u64, ) -> Option<DisconnectReason> { // Retrieve the components of the challenge response. - let ChallengeResponse { genesis_header, signature } = response; + let ChallengeResponse { genesis_header, signature, nonce } = response; // Verify the challenge response, by checking that the block header matches. if genesis_header != expected_genesis_header { @@ -316,7 +322,7 @@ impl<N: Network> Router<N> { return Some(DisconnectReason::InvalidChallengeResponse); }; // Verify the signature. - if !signature.verify_bytes(&peer_address, &expected_nonce.to_le_bytes()) { + if !signature.verify_bytes(&peer_address, &[expected_nonce.to_le_bytes(), nonce.to_le_bytes()].concat()) { warn!("Handshake with '{peer_addr}' failed (invalid signature)"); return Some(DisconnectReason::InvalidChallengeResponse); }
diff --git a/node/tests/common/test_peer.rs b/node/tests/common/test_peer.rs index d480c6a3e1..8d9d5e39bb 100644 --- a/node/tests/common/test_peer.rs +++ b/node/tests/common/test_peer.rs @@ -140,10 +140,13 @@ impl Handshake for TestPeer { let peer_request = expect_message!(Message::ChallengeRequest, framed, peer_addr); // Sign the nonce. - let signature = self.account().sign_bytes(&peer_request.nonce.to_le_bytes(), rng).unwrap(); + let response_nonce: u64 = rng.gen(); + let data = [peer_request.nonce.to_le_bytes(), response_nonce.to_le_bytes()].concat(); + let signature = self.account().sign_bytes(&data, rng).unwrap(); // Send the challenge response. - let our_response = ChallengeResponse { genesis_header, signature: Data::Object(signature) }; + let our_response = + ChallengeResponse { genesis_header, signature: Data::Object(signature), nonce: response_nonce }; framed.send(Message::ChallengeResponse(our_response)).await?; } ConnectionSide::Responder => { @@ -151,10 +154,13 @@ impl Handshake for TestPeer { let peer_request = expect_message!(Message::ChallengeRequest, framed, peer_addr); // Sign the nonce. - let signature = self.account().sign_bytes(&peer_request.nonce.to_le_bytes(), rng).unwrap(); + let response_nonce: u64 = rng.gen(); + let data = [peer_request.nonce.to_le_bytes(), response_nonce.to_le_bytes()].concat(); + let signature = self.account().sign_bytes(&data, rng).unwrap(); // Send our challenge bundle. - let our_response = ChallengeResponse { genesis_header, signature: Data::Object(signature) }; + let our_response = + ChallengeResponse { genesis_header, signature: Data::Object(signature), nonce: response_nonce }; framed.send(Message::ChallengeResponse(our_response)).await?; let our_request = ChallengeRequest::new(local_ip.port(), self.node_type(), self.address(), rng.gen()); framed.send(Message::ChallengeRequest(our_request)).await?;
[Bug] Validator sign arbitrary nonce can lead to downgraded length of secure bit. # https://hackerone.com/reports/2279770 ## Summary: During handshake, validator directly sign nonce (u64) sent from counterparty: ``` let Ok(our_signature) = self.account.sign_bytes(&peer_request.nonce.to_le_bytes(), rng) ``` The attacker can exploit this to let validator to sign the message they want. For example, the attacker can brute force and try to find some transaction `hash` that satify `hash < u64.max`. Then let the validator sign this hash as `peer_request.nonce`. In this case the length of secure bit is downgraded from `252/2 = 126` bits to `(252-64)/2 = 94` bits. ## Proof-of-Concept (PoC) As described above. ## Fix Suggestions: Instead of directly sign the nonce, the validator can sign something like `hash('validator_handshake_nonce', nonce)`. Also, consider adding prefix string when generating `batch_id` and `block_hash` to avoid future schema conflict.
2024-01-17T23:29:29Z
2.2
AleoNet/snarkOS
2,902
AleoNet__snarkOS-2902
[ "2894" ]
4896a1200a4605d1de6fe6cb53e1efa9ccdb6152
diff --git a/Cargo.lock b/Cargo.lock index e98d384892..b9f871cccb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3096,6 +3096,7 @@ dependencies = [ "num_cpus", "once_cell", "parking_lot", + "paste", "pea2pea", "rand", "rand_chacha", diff --git a/node/Cargo.toml b/node/Cargo.toml index c76dac9006..664bf96a06 100644 --- a/node/Cargo.toml +++ b/node/Cargo.toml @@ -113,6 +113,9 @@ version = "0.1" [dev-dependencies.deadline] version = "0.2" +[dev-dependencies.paste] +version = "1" + [dev-dependencies.pea2pea] version = "0.46" diff --git a/node/router/src/helpers/cache.rs b/node/router/src/helpers/cache.rs index befd5e9a90..87a0d8831e 100644 --- a/node/router/src/helpers/cache.rs +++ b/node/router/src/helpers/cache.rs @@ -53,6 +53,8 @@ pub struct Cache<N: Network> { seen_outbound_solutions: RwLock<LinkedHashMap<SolutionKey<N>, OffsetDateTime>>, /// The map of transaction IDs to their last seen timestamp. seen_outbound_transactions: RwLock<LinkedHashMap<TransactionKey<N>, OffsetDateTime>>, + /// The map of peer IPs to the number of sent peer requests. + seen_outbound_peer_requests: RwLock<IndexMap<SocketAddr, u32>>, } impl<N: Network> Default for Cache<N> { @@ -75,6 +77,7 @@ impl<N: Network> Cache<N> { seen_outbound_puzzle_requests: Default::default(), seen_outbound_solutions: RwLock::new(LinkedHashMap::with_capacity(MAX_CACHE_SIZE)), seen_outbound_transactions: RwLock::new(LinkedHashMap::with_capacity(MAX_CACHE_SIZE)), + seen_outbound_peer_requests: Default::default(), } } } @@ -166,6 +169,21 @@ impl<N: Network> Cache<N> { ) -> Option<OffsetDateTime> { Self::refresh_and_insert(&self.seen_outbound_transactions, (peer_ip, transaction)) } + + /// Returns `true` if the cache contains a peer request from the given peer. + pub fn contains_outbound_peer_request(&self, peer_ip: SocketAddr) -> bool { + self.seen_outbound_peer_requests.read().get(&peer_ip).map(|r| *r > 0).unwrap_or(false) + } + + /// Increment the peer IP's number of peer requests, returning the updated number of peer requests. + pub fn increment_outbound_peer_requests(&self, peer_ip: SocketAddr) -> u32 { + Self::increment_counter(&self.seen_outbound_peer_requests, peer_ip) + } + + /// Decrement the peer IP's number of peer requests, returning the updated number of peer requests. + pub fn decrement_outbound_peer_requests(&self, peer_ip: SocketAddr) -> u32 { + Self::decrement_counter(&self.seen_outbound_peer_requests, peer_ip) + } } impl<N: Network> Cache<N> { @@ -336,4 +354,35 @@ mod tests { // Check that the cache still contains the transaction. assert_eq!(cache.seen_outbound_transactions.read().len(), 1); } + + #[test] + fn test_outbound_peer_request() { + let cache = Cache::<CurrentNetwork>::default(); + let peer_ip = SocketAddr::new(Ipv4Addr::LOCALHOST.into(), 1234); + + // Check the cache is empty. + assert!(cache.seen_outbound_peer_requests.read().is_empty()); + assert!(!cache.contains_outbound_peer_request(peer_ip)); + + // Increment the peer requests. + assert_eq!(cache.increment_outbound_peer_requests(peer_ip), 1); + + // Check the cache contains the peer request. + assert!(cache.contains_outbound_peer_request(peer_ip)); + + // Increment the peer requests again for the same peer IP. + assert_eq!(cache.increment_outbound_peer_requests(peer_ip), 2); + + // Check the cache still contains the peer request. + assert!(cache.contains_outbound_peer_request(peer_ip)); + + // Decrement the peer requests. + assert_eq!(cache.decrement_outbound_peer_requests(peer_ip), 1); + + // Decrement the peer requests again. + assert_eq!(cache.decrement_outbound_peer_requests(peer_ip), 0); + + // Check the cache is empty. + assert!(!cache.contains_outbound_peer_request(peer_ip)); + } } diff --git a/node/router/src/inbound.rs b/node/router/src/inbound.rs index ac1790f211..0b68800f9a 100644 --- a/node/router/src/inbound.rs +++ b/node/router/src/inbound.rs @@ -117,10 +117,16 @@ pub trait Inbound<N: Network>: Reading + Outbound<N> { true => Ok(()), false => bail!("Peer '{peer_ip}' sent an invalid peer request"), }, - Message::PeerResponse(message) => match self.peer_response(peer_ip, &message.peers) { - true => Ok(()), - false => bail!("Peer '{peer_ip}' sent an invalid peer response"), - }, + Message::PeerResponse(message) => { + if !self.router().cache.contains_outbound_peer_request(peer_ip) { + bail!("Peer '{peer_ip}' is not following the protocol (unexpected peer response)") + } + + match self.peer_response(peer_ip, &message.peers) { + true => Ok(()), + false => bail!("Peer '{peer_ip}' sent an invalid peer response"), + } + } Message::Ping(message) => { // Ensure the message protocol version is not outdated. if message.version < Message::<N>::VERSION { diff --git a/node/router/src/lib.rs b/node/router/src/lib.rs index b51284190b..332cf07075 100644 --- a/node/router/src/lib.rs +++ b/node/router/src/lib.rs @@ -25,7 +25,6 @@ mod helpers; pub use helpers::*; mod handshake; -pub use handshake::*; mod heartbeat; pub use heartbeat::*; diff --git a/node/router/src/outbound.rs b/node/router/src/outbound.rs index ab1a4d037a..20713962c9 100644 --- a/node/router/src/outbound.rs +++ b/node/router/src/outbound.rs @@ -59,6 +59,10 @@ pub trait Outbound<N: Network>: Writing<Message = Message<N>> { if matches!(message, Message::PuzzleRequest(_)) { self.router().cache.increment_outbound_puzzle_requests(peer_ip); } + // If the message type is a peer request, increment the cache. + if matches!(message, Message::PeerRequest(_)) { + self.router().cache.increment_outbound_peer_requests(peer_ip); + } // Retrieve the message name. let name = message.name(); // Send the message to the peer.
diff --git a/node/tests/disconnect.rs b/node/tests/disconnect.rs new file mode 100644 index 0000000000..5b6ec3b925 --- /dev/null +++ b/node/tests/disconnect.rs @@ -0,0 +1,191 @@ +// Copyright (C) 2019-2023 Aleo Systems Inc. +// This file is part of the snarkOS library. + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at: +// http://www.apache.org/licenses/LICENSE-2.0 + +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#![recursion_limit = "256"] + +#[allow(dead_code)] +mod common; +use common::{node::*, test_peer::TestPeer}; + +use snarkos_node_router::Outbound; +use snarkos_node_tcp::P2P; + +use deadline::deadline; +use std::time::Duration; + +// Macro to simply construct disconnect cases. +// Syntax: +// - (full_node |> test_peer): full node disconnects from the synthetic test peer. +// - (full_node <| test_peer): synthetic test peer disconnects from the full node. +// +// Test naming: full_node::handshake_<node or peer>_side::test_peer. +macro_rules! test_disconnect { + ($node_type:ident, $peer_type:ident, $node_disconnects:expr, $($attr:meta)?) => { + #[tokio::test] + $(#[$attr])? + async fn $peer_type() { + use deadline::deadline; + use pea2pea::Pea2Pea; + use snarkos_node_router::Outbound; + use snarkos_node_tcp::P2P; + use std::time::Duration; + + // $crate::common::initialise_logger(2); + + // Spin up a full node. + let node = $crate::$node_type().await; + + // Spin up a test peer (synthetic node). + let peer = $crate::TestPeer::$peer_type().await; + let peer_addr = peer.node().listening_addr().unwrap(); + + // Connect the node to the test peer. + node.router().connect(peer_addr).unwrap().await.unwrap(); + + // Check the peer counts. + let node_clone = node.clone(); + deadline!(Duration::from_secs(5), move || node_clone.router().number_of_connected_peers() == 1); + let node_clone = node.clone(); + deadline!(Duration::from_secs(5), move || node_clone.tcp().num_connected() == 1); + let peer_clone = peer.clone(); + deadline!(Duration::from_secs(5), move || peer_clone.node().num_connected() == 1); + + // Disconnect. + if $node_disconnects { + node.router().disconnect(node.tcp().connected_addrs()[0]).await.unwrap(); + } else { + peer.node().disconnect(peer.node().connected_addrs()[0]).await; + } + + // Check the peer counts have been updated. + let node_clone = node.clone(); + deadline!(Duration::from_secs(5), move || node_clone.router().number_of_connected_peers() == 0); + deadline!(Duration::from_secs(5), move || node.tcp().num_connected() == 0); + deadline!(Duration::from_secs(5), move || peer.node().num_connected() == 0); + + } + }; + + // Node side disconnect. + ($($node_type:ident |> $peer_type:ident $(= $attr:meta)?),*) => { + mod disconnect_node_side { + $( + test_disconnect!($node_type, $peer_type, true, $($attr)?); + )* + } + }; + + // Peer side disconnect. + ($($node_type:ident <| $peer_type:ident $(= $attr:meta)?),*) => { + mod disconnect_peer_side { + $( + test_disconnect!($node_type, $peer_type, false, $($attr)?); + )* + } + }; +} + +mod client { + // Full node disconnects from synthetic peer. + test_disconnect! { + client |> client, + client |> validator, + client |> prover + } + + // Synthetic peer disconnects from the full node. + test_disconnect! { + client <| client, + client <| validator, + client <| prover + } +} + +mod prover { + // Full node disconnects from synthetic peer. + test_disconnect! { + prover |> client, + prover |> validator, + prover |> prover + } + + // Synthetic peer disconnects from the full node. + test_disconnect! { + prover <| client, + prover <| validator, + prover <| prover + } +} + +mod validator { + // Full node disconnects from synthetic peer. + test_disconnect! { + validator |> client, + validator |> validator, + validator |> prover + } + + // Synthetic peer disconnects from the full node. + test_disconnect! { + validator <| client, + validator <| validator, + validator <| prover + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn duplicate_disconnect_attempts() { + // common::initialise_logger(3); + + // Spin up 2 full nodes. + let node1 = validator().await; + let node2 = validator().await; + let addr2 = node2.tcp().listening_addr().unwrap(); + + // Connect node1 to node2. + assert!(node1.router().connect(addr2).unwrap().await.unwrap()); + + // Prepare disconnect attempts. + let node1_clone = node1.clone(); + let disconn1 = tokio::spawn(async move { node1_clone.router().disconnect(addr2).await.unwrap() }); + let node1_clone = node1.clone(); + let disconn2 = tokio::spawn(async move { node1_clone.router().disconnect(addr2).await.unwrap() }); + let node1_clone = node1.clone(); + let disconn3 = tokio::spawn(async move { node1_clone.router().disconnect(addr2).await.unwrap() }); + + // Attempt to disconnect the 1st node from the other one several times at once. + let (result1, result2, result3) = tokio::join!(disconn1, disconn2, disconn3); + // A small anti-flakiness buffer. + + // Count the successes. + let mut successes = 0; + if result1.unwrap() { + successes += 1; + } + if result2.unwrap() { + successes += 1; + } + if result3.unwrap() { + successes += 1; + } + + // There may only be a single success. + assert_eq!(successes, 1); + + // Connection checks. + let node1_clone = node1.clone(); + deadline!(Duration::from_secs(5), move || node1_clone.router().number_of_connected_peers() == 0); + let node2_clone = node2.clone(); + deadline!(Duration::from_secs(5), move || node2_clone.router().number_of_connected_peers() == 0); +} diff --git a/node/tests/peering.rs b/node/tests/peering.rs index 5b6ec3b925..1bae7f6ddc 100644 --- a/node/tests/peering.rs +++ b/node/tests/peering.rs @@ -12,180 +12,71 @@ // See the License for the specific language governing permissions and // limitations under the License. -#![recursion_limit = "256"] - #[allow(dead_code)] mod common; -use common::{node::*, test_peer::TestPeer}; +use common::test_peer::TestPeer; -use snarkos_node_router::Outbound; +use snarkos_node_router::{ + messages::{Message, PeerResponse}, + Outbound, +}; use snarkos_node_tcp::P2P; use deadline::deadline; +use paste::paste; +use pea2pea::{protocols::Writing, Pea2Pea}; use std::time::Duration; -// Macro to simply construct disconnect cases. -// Syntax: -// - (full_node |> test_peer): full node disconnects from the synthetic test peer. -// - (full_node <| test_peer): synthetic test peer disconnects from the full node. -// -// Test naming: full_node::handshake_<node or peer>_side::test_peer. -macro_rules! test_disconnect { - ($node_type:ident, $peer_type:ident, $node_disconnects:expr, $($attr:meta)?) => { - #[tokio::test] - $(#[$attr])? - async fn $peer_type() { - use deadline::deadline; - use pea2pea::Pea2Pea; - use snarkos_node_router::Outbound; - use snarkos_node_tcp::P2P; - use std::time::Duration; - - // $crate::common::initialise_logger(2); - - // Spin up a full node. - let node = $crate::$node_type().await; - - // Spin up a test peer (synthetic node). - let peer = $crate::TestPeer::$peer_type().await; - let peer_addr = peer.node().listening_addr().unwrap(); - - // Connect the node to the test peer. - node.router().connect(peer_addr).unwrap().await.unwrap(); - - // Check the peer counts. - let node_clone = node.clone(); - deadline!(Duration::from_secs(5), move || node_clone.router().number_of_connected_peers() == 1); - let node_clone = node.clone(); - deadline!(Duration::from_secs(5), move || node_clone.tcp().num_connected() == 1); - let peer_clone = peer.clone(); - deadline!(Duration::from_secs(5), move || peer_clone.node().num_connected() == 1); - - // Disconnect. - if $node_disconnects { - node.router().disconnect(node.tcp().connected_addrs()[0]).await.unwrap(); - } else { - peer.node().disconnect(peer.node().connected_addrs()[0]).await; +macro_rules! test_reject_unsolicited_peer_response { + ($($node_type:ident),*) => { + $( + paste! { + #[tokio::test] + async fn [<$node_type _rejects_unsolicited_peer_response>]() { + // Spin up a full node. + let node = $crate::common::node::$node_type().await; + + // Spin up a test peer (synthetic node), it doesn't really matter what type it is. + let peer = TestPeer::validator().await; + let peer_addr = peer.node().listening_addr().unwrap(); + + // Connect the node to the test peer. + node.router().connect(peer_addr).unwrap().await.unwrap(); + + // Check the peer counts. + let node_clone = node.clone(); + deadline!(Duration::from_secs(5), move || node_clone.router().number_of_connected_peers() == 1); + let node_clone = node.clone(); + deadline!(Duration::from_secs(5), move || node_clone.tcp().num_connected() == 1); + let peer_clone = peer.clone(); + deadline!(Duration::from_secs(5), move || peer_clone.node().num_connected() == 1); + + // Check the candidate peers. + assert_eq!(node.router().number_of_candidate_peers(), 0); + + let peers = vec!["1.1.1.1:1111".parse().unwrap(), "2.2.2.2:2222".parse().unwrap()]; + + // Send a `PeerResponse` to the node. + assert!( + peer.unicast( + *peer.node().connected_addrs().first().unwrap(), + Message::PeerResponse(PeerResponse { peers: peers.clone() }) + ) + .is_ok() + ); + + // Wait for the peer to be disconnected for a protocol violation. + let node_clone = node.clone(); + deadline!(Duration::from_secs(5), move || node_clone.router().number_of_connected_peers() == 0); + + // Make sure the sent addresses weren't inserted in the candidate peers. + for peer in peers { + assert!(!node.router().candidate_peers().contains(&peer)); + } + } } - - // Check the peer counts have been updated. - let node_clone = node.clone(); - deadline!(Duration::from_secs(5), move || node_clone.router().number_of_connected_peers() == 0); - deadline!(Duration::from_secs(5), move || node.tcp().num_connected() == 0); - deadline!(Duration::from_secs(5), move || peer.node().num_connected() == 0); - - } - }; - - // Node side disconnect. - ($($node_type:ident |> $peer_type:ident $(= $attr:meta)?),*) => { - mod disconnect_node_side { - $( - test_disconnect!($node_type, $peer_type, true, $($attr)?); - )* - } + )* }; - - // Peer side disconnect. - ($($node_type:ident <| $peer_type:ident $(= $attr:meta)?),*) => { - mod disconnect_peer_side { - $( - test_disconnect!($node_type, $peer_type, false, $($attr)?); - )* - } - }; -} - -mod client { - // Full node disconnects from synthetic peer. - test_disconnect! { - client |> client, - client |> validator, - client |> prover - } - - // Synthetic peer disconnects from the full node. - test_disconnect! { - client <| client, - client <| validator, - client <| prover - } -} - -mod prover { - // Full node disconnects from synthetic peer. - test_disconnect! { - prover |> client, - prover |> validator, - prover |> prover - } - - // Synthetic peer disconnects from the full node. - test_disconnect! { - prover <| client, - prover <| validator, - prover <| prover - } } -mod validator { - // Full node disconnects from synthetic peer. - test_disconnect! { - validator |> client, - validator |> validator, - validator |> prover - } - - // Synthetic peer disconnects from the full node. - test_disconnect! { - validator <| client, - validator <| validator, - validator <| prover - } -} - -#[tokio::test(flavor = "multi_thread")] -async fn duplicate_disconnect_attempts() { - // common::initialise_logger(3); - - // Spin up 2 full nodes. - let node1 = validator().await; - let node2 = validator().await; - let addr2 = node2.tcp().listening_addr().unwrap(); - - // Connect node1 to node2. - assert!(node1.router().connect(addr2).unwrap().await.unwrap()); - - // Prepare disconnect attempts. - let node1_clone = node1.clone(); - let disconn1 = tokio::spawn(async move { node1_clone.router().disconnect(addr2).await.unwrap() }); - let node1_clone = node1.clone(); - let disconn2 = tokio::spawn(async move { node1_clone.router().disconnect(addr2).await.unwrap() }); - let node1_clone = node1.clone(); - let disconn3 = tokio::spawn(async move { node1_clone.router().disconnect(addr2).await.unwrap() }); - - // Attempt to disconnect the 1st node from the other one several times at once. - let (result1, result2, result3) = tokio::join!(disconn1, disconn2, disconn3); - // A small anti-flakiness buffer. - - // Count the successes. - let mut successes = 0; - if result1.unwrap() { - successes += 1; - } - if result2.unwrap() { - successes += 1; - } - if result3.unwrap() { - successes += 1; - } - - // There may only be a single success. - assert_eq!(successes, 1); - - // Connection checks. - let node1_clone = node1.clone(); - deadline!(Duration::from_secs(5), move || node1_clone.router().number_of_connected_peers() == 0); - let node2_clone = node2.clone(); - deadline!(Duration::from_secs(5), move || node2_clone.router().number_of_connected_peers() == 0); -} +test_reject_unsolicited_peer_response!(client, prover, validator);
[Bug] A malicious peer can directly send PeerResponse to other peers with high frequency and flood network with fake peer info # https://hackerone.com/reports/2272999 ## Summary: The router does not check if the PeerResponse is a direct response of a previous PeerRequest https://github.com/AleoHQ/snarkOS/blob/testnet3/node/router/src/inbound.rs#L120 A malicious peer can directly send `PeerResponse` to other peers with high frequency. In this way, the other peers' `candidate_peers` will be full of malicious peer. Gradually, the good peer's connected peers are all malicious. Finally the good peers are disjoint with each oher and whole network is controlled by the malicious peers. ## Steps To Reproduce: 1. Clone https://github.com/AleoHQ/snarkOS and checkout `testnet3` 2. Add the following code at: node/router/src/heartbeat.rs `heartbeat` function ``` /// Handles the heartbeat request. fn heartbeat(&self) { self.safety_check_minimum_number_of_peers(); self.log_connected_peers(); //////////////////// ADD CODE HERE //////////////////// // We can directly send PeerResponse to other peers (without previous PeerRequest). We can send PeerResponse with high frequency. Attacker can leverage this to attck the whole network. for peer_ip in self.router().connected_peers().into_iter() { let ip = "1.1.1.1:111"; let malicious_addr: SocketAddr = ip .parse() .expect("Unable to parse socket address"); self.send(peer_ip, Message::PeerResponse( PeerResponse { peers: vec![malicious_addr; 100] })); } /////////////////// ADD CODE HERE //////////////////// // Remove any stale connected peers. self.remove_stale_connected_peers(); // Remove the oldest connected peer. .... ``` 3. add log at node/router/src/inbound.rs `peer_response` function ``` /// Handles a `PeerResponse` message. fn peer_response(&self, _peer_ip: SocketAddr, peers: &[SocketAddr]) -> bool { // Filter out invalid addresses. //////////////////// ADD LOG HERE //////////////////// warn!("received peer_response {:?}", peers); //////////////////// ADD LOG HERE //////////////////// let peers = peers.iter().copied().filter(|ip| self.router().is_valid_peer_ip(ip)).collect::<Vec<_>>(); // Adds the given peer IPs to the list of candidate peers. self.router().insert_candidate_peers(&peers); true } ``` 4. run ./devnet.sh 5. check log, we will find something like ``` WARN received peer_response [1.1.1.1:111, 1.1.1.1:111, 1.1.1.1:111, 1.1.1.1:111 ``` 6. Attack success: Though the good peer haven't made `PeerRequest`, it received malicious `PeerResponse`. ## Proof-of-Concept (PoC) How this bug can be exploited: 1. The malicious peer starts sending a high frequency of PeerResponse messages directly to other peers. The PeerResponse messages contain information about the other peers which are all controlled by the hacker. 2. The other peers receive these PeerResponse messages and update their candidate_peers list with the information provided by the malicious peer. 3. Due to the high frequency of messages and the continuous updates, the candidate_peers list of the other peers becomes populated mainly or entirely with malicious peer entries. 4. As the good peers' candidate_peers list becomes filled with malicious peers, the chances of connecting to other good peers decrease significantly. 5. Over time, the good peers' connections are predominated by malicious peers, reducing the opportunities for good peers to communicate with each other. 6. Eventually, the good peers become disjointed from each other, as their connections are primarily with malicious peers. 7. With the network effectively controlled by malicious peers, they can manipulate communication, block transactions, tamper with data, or perform other malicious activities without detection or intervention from the good peers. ## Supporting Material/References: ![screenshot-20231205-014632](https://github.com/AleoHQ/snarkOS/assets/136848162/7d8779a0-1f1d-450f-abd4-c3892a7733e3) ## Impact This bug have signigicant impact on all kinds of node: Prover, Validator and Client. The bug allows a malicious peer to flood the network with fake peer information, causing good peers to connect primarily with malicious peers. This gives the malicious peer control over the network and disrupts communication among the good peers. The malicious peers can tamper with transactions, manipulate data, and potentially launch further attacks. This undermines trust in the network and compromises its security and reliability. ## Fix Suggestions: In the short term, verify every `PeerResponse ` is a real response of `PeerRequest`. In the middle or long term, consider formulating specification about the network layer. Also, consider using battle tested framework like `devp2p` and `libp2p`.
2023-12-07T20:12:09Z
2.2
AleoNet/snarkOS
2,221
AleoNet__snarkOS-2221
[ "2149" ]
05e50dd0de11d06b93a31e979c78fb1d9942e181
diff --git a/node/messages/src/challenge_request.rs b/node/messages/src/challenge_request.rs index eaf86a7b3f..35fa4497aa 100644 --- a/node/messages/src/challenge_request.rs +++ b/node/messages/src/challenge_request.rs @@ -48,3 +48,9 @@ impl<N: Network> MessageTrait for ChallengeRequest<N> { Ok(Self { version, listener_port, node_type, address, nonce }) } } + +impl<N: Network> ChallengeRequest<N> { + pub fn new(listener_port: u16, node_type: NodeType, address: Address<N>, nonce: u64) -> Self { + Self { version: Message::<N>::VERSION, listener_port, node_type, address, nonce } + } +} diff --git a/node/messages/src/helpers/codec.rs b/node/messages/src/helpers/codec.rs index 83a6a9bd22..eedf3e26e5 100644 --- a/node/messages/src/helpers/codec.rs +++ b/node/messages/src/helpers/codec.rs @@ -21,6 +21,9 @@ use ::bytes::{BufMut, BytesMut}; use core::marker::PhantomData; use tokio_util::codec::{Decoder, Encoder, LengthDelimitedCodec}; +/// The maximum size of a message that can be transmitted during the handshake. +const MAXIMUM_HANDSHAKE_MESSAGE_SIZE: usize = 1024 * 1024; // 1 MiB + /// The maximum size of a message that can be transmitted in the network. const MAXIMUM_MESSAGE_SIZE: usize = 128 * 1024 * 1024; // 128 MiB @@ -30,10 +33,20 @@ pub struct MessageCodec<N: Network> { _phantom: PhantomData<N>, } +impl<N: Network> MessageCodec<N> { + /// Increases the maximum permitted message size post-handshake. + pub fn update_max_message_len(&mut self) { + self.codec = LengthDelimitedCodec::builder().max_frame_length(MAXIMUM_MESSAGE_SIZE).little_endian().new_codec(); + } +} + impl<N: Network> Default for MessageCodec<N> { fn default() -> Self { Self { - codec: LengthDelimitedCodec::builder().max_frame_length(MAXIMUM_MESSAGE_SIZE).little_endian().new_codec(), + codec: LengthDelimitedCodec::builder() + .max_frame_length(MAXIMUM_HANDSHAKE_MESSAGE_SIZE) + .little_endian() + .new_codec(), _phantom: Default::default(), } } diff --git a/node/router/src/handshake.rs b/node/router/src/handshake.rs index fc473495b4..773fbb783a 100644 --- a/node/router/src/handshake.rs +++ b/node/router/src/handshake.rs @@ -43,8 +43,40 @@ impl<N: Network> P2P for Router<N> { } } +/// A macro unwrapping the expected handshake message or returning an error for unexpected messages. +#[macro_export] +macro_rules! expect_message { + ($msg_ty:path, $framed:expr, $peer_addr:expr) => { + match $framed.try_next().await? { + // Received the expected message, proceed. + Some($msg_ty(data)) => { + trace!("Received '{}' from '{}'", data.name(), $peer_addr); + data + } + // Received a disconnect message, abort. + Some(Message::Disconnect(reason)) => { + return Err(error(format!("'{}' disconnected: {reason:?}", $peer_addr))) + } + // Received an unexpected message, abort. + _ => return Err(error(format!("'{}' did not follow the handshake protocol", $peer_addr))), + } + }; +} + +/// A macro for cutting a handshake short if message verification fails. +#[macro_export] +macro_rules! handle_verification { + ($result:expr, $framed:expr, $peer_addr:expr) => { + if let Some(reason) = $result { + trace!("Sending 'Disconnect' to '{}'", $peer_addr); + $framed.send(Message::Disconnect(Disconnect { reason: reason.clone() })).await?; + return Err(error(format!("Dropped '{}' for reason: {reason:?}", $peer_addr))); + } + }; +} + impl<N: Network> Router<N> { - /// Performs the handshake protocol. + /// Executes the handshake protocol. pub async fn handshake<'a>( &'a self, peer_addr: SocketAddr, @@ -58,133 +90,162 @@ impl<N: Network> Router<N> { debug!("Received a connection request from '{peer_addr}'"); None } else { + debug!("Connecting to {peer_addr}..."); Some(peer_addr) }; // Perform the handshake; we pass on a mutable reference to peer_ip in case the process is broken at any point in time. - let handshake_result = self.handshake_inner(peer_addr, &mut peer_ip, stream, peer_side, genesis_header).await; + let mut handshake_result = if peer_side == ConnectionSide::Responder { + self.handshake_inner_initiator(peer_addr, &mut peer_ip, stream, genesis_header).await + } else { + self.handshake_inner_responder(peer_addr, &mut peer_ip, stream, genesis_header).await + }; // Remove the address from the collection of connecting peers (if the handshake got to the point where it's known). if let Some(ip) = peer_ip { self.connecting_peers.lock().remove(&ip); } + // If the handshake succeeded, announce it and increase the message size limit. + if let Ok((ref peer_ip, ref mut framed)) = handshake_result { + info!("Connected to '{peer_ip}'"); + framed.codec_mut().update_max_message_len(); + } + handshake_result } - /// A helper that facilitates some extra error handling in `Router::handshake`. - async fn handshake_inner<'a>( + /// The connection initiator side of the handshake. + async fn handshake_inner_initiator<'a>( &'a self, peer_addr: SocketAddr, peer_ip: &mut Option<SocketAddr>, stream: &'a mut TcpStream, - peer_side: ConnectionSide, genesis_header: Header<N>, ) -> io::Result<(SocketAddr, Framed<&mut TcpStream, MessageCodec<N>>)> { // Construct the stream. let mut framed = Framed::new(stream, MessageCodec::<N>::default()); + // This value is immediately guaranteed to be present, so it can be unwrapped. + let peer_ip = peer_ip.unwrap(); + /* Step 1: Send the challenge request. */ // Initialize an RNG. let rng = &mut OsRng; // Sample a random nonce. - let nonce_a = rng.gen(); + let our_nonce = rng.gen(); // Send a challenge request to the peer. - let message_a = Message::<N>::ChallengeRequest(ChallengeRequest { - version: Message::<N>::VERSION, - listener_port: self.local_ip().port(), - node_type: self.node_type, - address: self.address(), - nonce: nonce_a, - }); - trace!("Sending '{}-A' to '{peer_addr}'", message_a.name()); - framed.send(message_a).await?; - - /* Step 2: Receive the challenge request. */ + let our_request = ChallengeRequest::new(self.local_ip().port(), self.node_type, self.address(), our_nonce); + trace!("Sending '{}' to '{peer_addr}'", our_request.name()); + framed.send(Message::ChallengeRequest(our_request)).await?; + + /* Step 2: Receive the peer's challenge response followed by the challenge request. */ + + // Listen for the challenge response message. + let peer_response = expect_message!(Message::ChallengeResponse, framed, peer_addr); // Listen for the challenge request message. - let request_b = match framed.try_next().await? { - // Received the challenge request message, proceed. - Some(Message::ChallengeRequest(data)) => data, - // Received a disconnect message, abort. - Some(Message::Disconnect(reason)) => return Err(error(format!("'{peer_addr}' disconnected: {reason:?}"))), - // Received an unexpected message, abort. - _ => return Err(error(format!("'{peer_addr}' did not send a challenge request"))), - }; - trace!("Received '{}-B' from '{peer_addr}'", request_b.name()); + let peer_request = expect_message!(Message::ChallengeRequest, framed, peer_addr); - // Obtain the peer's listening address if it's an inbound connection. - if peer_ip.is_none() { - *peer_ip = Some(SocketAddr::new(peer_addr.ip(), request_b.listener_port)); - } + // Verify the challenge response. If a disconnect reason was returned, send the disconnect message and abort. + handle_verification!( + self.verify_challenge_response(peer_addr, peer_request.address, peer_response, genesis_header, our_nonce) + .await, + framed, + peer_addr + ); + + // Verify the challenge request. If a disconnect reason was returned, send the disconnect message and abort. + handle_verification!(self.verify_challenge_request(peer_addr, &peer_request), framed, peer_addr); + + /* Step 3: Send the challenge response. */ + + // Sign the counterparty nonce. + let our_signature = self + .account + .sign_bytes(&peer_request.nonce.to_le_bytes(), rng) + .map_err(|_| error(format!("Failed to sign the challenge request nonce from '{peer_addr}'")))?; + + // Send the challenge response. + let our_response = ChallengeResponse { genesis_header, signature: Data::Object(our_signature) }; + trace!("Sending '{}' to '{peer_addr}'", our_response.name()); + framed.send(Message::ChallengeResponse(our_response)).await?; + + // Add the peer to the router. + self.insert_connected_peer(Peer::new(peer_ip, &peer_request), peer_addr); + + Ok((peer_ip, framed)) + } + + /// The connection responder side of the handshake. + async fn handshake_inner_responder<'a>( + &'a self, + peer_addr: SocketAddr, + peer_ip: &mut Option<SocketAddr>, + stream: &'a mut TcpStream, + genesis_header: Header<N>, + ) -> io::Result<(SocketAddr, Framed<&mut TcpStream, MessageCodec<N>>)> { + // Construct the stream. + let mut framed = Framed::new(stream, MessageCodec::<N>::default()); + + /* Step 1: Receive the challenge request. */ + + // Listen for the challenge request message. + let peer_request = expect_message!(Message::ChallengeRequest, framed, peer_addr); - // This value is now guaranteed to be present, so it can be unwrapped. + // Obtain the peer's listening address. + *peer_ip = Some(SocketAddr::new(peer_addr.ip(), peer_request.listener_port)); let peer_ip = peer_ip.unwrap(); // Knowing the peer's listening address, ensure it is allowed to connect. - if peer_side == ConnectionSide::Initiator { - if let Err(forbidden_message) = self.ensure_peer_is_allowed(peer_ip) { - return Err(error(format!("{forbidden_message}"))); - } + if let Err(forbidden_message) = self.ensure_peer_is_allowed(peer_ip) { + return Err(error(format!("{forbidden_message}"))); } // Verify the challenge request. If a disconnect reason was returned, send the disconnect message and abort. - if let Some(reason) = self.verify_challenge_request(peer_addr, &request_b) { - trace!("Sending 'Disconnect' to '{peer_addr}'"); - framed.send(Message::Disconnect(Disconnect { reason: reason.clone() })).await?; - return Err(error(format!("Dropped '{peer_addr}' for reason: {reason:?}"))); - } + handle_verification!(self.verify_challenge_request(peer_addr, &peer_request), framed, peer_addr); - /* Step 3: Send the challenge response. */ + /* Step 2: Send the challenge response followed by own challenge request. */ + + // Initialize an RNG. + let rng = &mut OsRng; // Sign the counterparty nonce. - let signature_b = self + let our_signature = self .account - .sign_bytes(&request_b.nonce.to_le_bytes(), rng) + .sign_bytes(&peer_request.nonce.to_le_bytes(), rng) .map_err(|_| error(format!("Failed to sign the challenge request nonce from '{peer_addr}'")))?; + // Sample a random nonce. + let our_nonce = rng.gen(); + // Send the challenge response. - let message_b = - Message::ChallengeResponse(ChallengeResponse { genesis_header, signature: Data::Object(signature_b) }); - trace!("Sending '{}-B' to '{peer_addr}'", message_b.name()); - framed.send(message_b).await?; + let our_response = ChallengeResponse { genesis_header, signature: Data::Object(our_signature) }; + trace!("Sending '{}' to '{peer_addr}'", our_response.name()); + framed.send(Message::ChallengeResponse(our_response)).await?; + + // Send the challenge request. + let our_request = ChallengeRequest::new(self.local_ip().port(), self.node_type, self.address(), our_nonce); + trace!("Sending '{}' to '{peer_addr}'", our_request.name()); + framed.send(Message::ChallengeRequest(our_request)).await?; - /* Step 4: Receive the challenge response. */ + /* Step 3: Receive the challenge response. */ // Listen for the challenge response message. - let response_a = match framed.try_next().await? { - // Received the challenge response message, proceed. - Some(Message::ChallengeResponse(data)) => data, - // Received a disconnect message, abort. - Some(Message::Disconnect(reason)) => return Err(error(format!("'{peer_addr}' disconnected: {reason:?}"))), - // Received an unexpected message, abort. - _ => return Err(error(format!("'{peer_addr}' did not send a challenge response"))), - }; - trace!("Received '{}-A' from '{peer_addr}'", response_a.name()); + let peer_response = expect_message!(Message::ChallengeResponse, framed, peer_addr); // Verify the challenge response. If a disconnect reason was returned, send the disconnect message and abort. - if let Some(reason) = - self.verify_challenge_response(peer_addr, request_b.address, response_a, genesis_header, nonce_a).await - { - trace!("Sending 'Disconnect' to '{peer_addr}'"); - framed.send(Message::Disconnect(Disconnect { reason: reason.clone() })).await?; - return Err(error(format!("Dropped '{peer_addr}' for reason: {reason:?}"))); - } - - /* Step 5: Add the peer to the router. */ - - // Prepare the peer. - let peer_address = request_b.address; - let peer_type = request_b.node_type; - let peer_version = request_b.version; - - // Construct the peer. - let peer = Peer::new(peer_ip, peer_address, peer_type, peer_version); - // Insert the connected peer in the router. - self.insert_connected_peer(peer, peer_addr); - info!("Connected to '{peer_ip}'"); + handle_verification!( + self.verify_challenge_response(peer_addr, peer_request.address, peer_response, genesis_header, our_nonce) + .await, + framed, + peer_addr + ); + + // Add the peer to the router. + self.insert_connected_peer(Peer::new(peer_ip, &peer_request), peer_addr); Ok((peer_ip, framed)) } diff --git a/node/router/src/helpers/peer.rs b/node/router/src/helpers/peer.rs index f0d1d8e496..29016539cc 100644 --- a/node/router/src/helpers/peer.rs +++ b/node/router/src/helpers/peer.rs @@ -14,7 +14,7 @@ // You should have received a copy of the GNU General Public License // along with the snarkOS library. If not, see <https://www.gnu.org/licenses/>. -use snarkos_node_messages::NodeType; +use snarkos_node_messages::{ChallengeRequest, NodeType}; use snarkvm::prelude::{Address, Network}; use parking_lot::RwLock; @@ -39,12 +39,12 @@ pub struct Peer<N: Network> { impl<N: Network> Peer<N> { /// Initializes a new instance of `Peer`. - pub fn new(listening_ip: SocketAddr, address: Address<N>, node_type: NodeType, version: u32) -> Self { + pub fn new(listening_ip: SocketAddr, challenge_request: &ChallengeRequest<N>) -> Self { Self { peer_ip: listening_ip, - address, - node_type, - version, + address: challenge_request.address, + node_type: challenge_request.node_type, + version: challenge_request.version, first_seen: Instant::now(), last_seen: Arc::new(RwLock::new(Instant::now())), } diff --git a/node/router/src/lib.rs b/node/router/src/lib.rs index fe657336db..9473e0646c 100644 --- a/node/router/src/lib.rs +++ b/node/router/src/lib.rs @@ -145,7 +145,6 @@ impl<N: Network> Router<N> { let router = self.clone(); tokio::spawn(async move { // Attempt to connect to the candidate peer. - debug!("Connecting to {peer_ip}..."); match router.tcp.connect(peer_ip).await { // Remove the peer from the candidate peers. Ok(()) => router.remove_candidate_peer(peer_ip),
diff --git a/node/router/tests/connect.rs b/node/router/tests/connect.rs index f5db28463a..f3793dca0b 100644 --- a/node/router/tests/connect.rs +++ b/node/router/tests/connect.rs @@ -23,8 +23,6 @@ use core::time::Duration; #[tokio::test] async fn test_connect_without_handshake() { - initialize_logger(3); - // Create 2 routers. let node0 = validator(0, 2).await; let node1 = client(0, 2).await; @@ -81,8 +79,6 @@ async fn test_connect_without_handshake() { #[tokio::test] async fn test_connect_with_handshake() { - initialize_logger(3); - // Create 2 routers. let node0 = validator(0, 2).await; let node1 = client(0, 2).await; @@ -159,8 +155,6 @@ async fn test_connect_with_handshake() { #[ignore] #[tokio::test] async fn test_connect_simultaneously_with_handshake() { - initialize_logger(3); - // Create 2 routers. let node0 = validator(0, 2).await; let node1 = client(0, 2).await; diff --git a/node/router/tests/disconnect.rs b/node/router/tests/disconnect.rs index efc612c0e4..b7d07a6293 100644 --- a/node/router/tests/disconnect.rs +++ b/node/router/tests/disconnect.rs @@ -23,8 +23,6 @@ use core::time::Duration; #[tokio::test] async fn test_disconnect_without_handshake() { - initialize_logger(3); - // Create 2 routers. let node0 = validator(0, 1).await; let node1 = client(0, 1).await; @@ -67,8 +65,6 @@ async fn test_disconnect_without_handshake() { #[tokio::test] async fn test_disconnect_with_handshake() { - initialize_logger(3); - // Create 2 routers. let node0 = validator(0, 1).await; let node1 = client(0, 1).await; diff --git a/node/tests/common/test_peer.rs b/node/tests/common/test_peer.rs index a7a24e56c5..183786b12b 100644 --- a/node/tests/common/test_peer.rs +++ b/node/tests/common/test_peer.rs @@ -15,7 +15,8 @@ // along with the snarkOS library. If not, see <https://www.gnu.org/licenses/>. use snarkos_account::Account; -use snarkos_node_messages::{ChallengeRequest, ChallengeResponse, Data, Message, MessageCodec, NodeType}; +use snarkos_node_messages::{ChallengeRequest, ChallengeResponse, Data, Message, MessageCodec, MessageTrait, NodeType}; +use snarkos_node_router::expect_message; use snarkvm::prelude::{error, Address, Block, FromBytes, Network, TestRng, Testnet3 as CurrentNetwork}; use std::{ @@ -35,6 +36,7 @@ use pea2pea::{ }; use rand::Rng; use tokio_util::codec::Framed; +use tracing::*; const ALEO_MAXIMUM_FORK_DEPTH: u32 = 4096; @@ -119,47 +121,49 @@ impl Handshake for TestPeer { let local_ip = self.node().listening_addr().expect("listening address should be present"); + let peer_addr = conn.addr(); + let node_side = !conn.side(); let stream = self.borrow_stream(&mut conn); let mut framed = Framed::new(stream, MessageCodec::<CurrentNetwork>::default()); - // Send a challenge request to the peer. - let message = Message::<CurrentNetwork>::ChallengeRequest(ChallengeRequest { - version: Message::<CurrentNetwork>::VERSION, - listener_port: local_ip.port(), - node_type: self.node_type(), - address: self.address(), - nonce: rng.gen(), - }); - framed.send(message).await?; - - // Listen for the challenge request. - let request_b = match framed.try_next().await? { - // Received the challenge request message, proceed. - Some(Message::ChallengeRequest(data)) => data, - // Received a disconnect message, abort. - Some(Message::Disconnect(reason)) => return Err(error(format!("disconnected: {reason:?}"))), - // Received an unexpected message, abort. - _ => return Err(error("didn't send a challenge request")), - }; - - // TODO(nkls): add assertions on the contents. - - // Sign the nonce. - let signature = self.account().sign_bytes(&request_b.nonce.to_le_bytes(), rng).unwrap(); - // Retrieve the genesis block header. let genesis_header = *sample_genesis_block().header(); - // Send the challenge response. - let message = - Message::ChallengeResponse(ChallengeResponse { genesis_header, signature: Data::Object(signature) }); - framed.send(message).await?; - - // Receive the challenge response. - let Message::ChallengeResponse(challenge_response) = framed.try_next().await.unwrap().unwrap() else { - panic!("didn't get challenge response") - }; - assert_eq!(challenge_response.genesis_header, genesis_header); + // TODO(nkls): add assertions on the contents of messages. + match node_side { + ConnectionSide::Initiator => { + // Send a challenge request to the peer. + let our_request = ChallengeRequest::new(local_ip.port(), self.node_type(), self.address(), rng.gen()); + framed.send(Message::ChallengeRequest(our_request)).await?; + + // Receive the peer's challenge bundle. + let _peer_response = expect_message!(Message::ChallengeResponse, framed, peer_addr); + let peer_request = expect_message!(Message::ChallengeRequest, framed, peer_addr); + + // Sign the nonce. + let signature = self.account().sign_bytes(&peer_request.nonce.to_le_bytes(), rng).unwrap(); + + // Send the challenge response. + let our_response = ChallengeResponse { genesis_header, signature: Data::Object(signature) }; + framed.send(Message::ChallengeResponse(our_response)).await?; + } + ConnectionSide::Responder => { + // Listen for the challenge request. + let peer_request = expect_message!(Message::ChallengeRequest, framed, peer_addr); + + // Sign the nonce. + let signature = self.account().sign_bytes(&peer_request.nonce.to_le_bytes(), rng).unwrap(); + + // Send our challenge bundle. + let our_response = ChallengeResponse { genesis_header, signature: Data::Object(signature) }; + framed.send(Message::ChallengeResponse(our_response)).await?; + let our_request = ChallengeRequest::new(local_ip.port(), self.node_type(), self.address(), rng.gen()); + framed.send(Message::ChallengeRequest(our_request)).await?; + + // Listen for the challenge response. + let _peer_response = expect_message!(Message::ChallengeResponse, framed, peer_addr); + } + } Ok(conn) }
Unify the `Connecting to '{peer_ip}'...` message in `Router::handshake` Unify the `Connecting to '{peer_ip}'...` message in `Router::handshake`. _Originally posted by @howardwu in https://github.com/AleoHQ/snarkOS/pull/2108#pullrequestreview-1203846755_
2023-01-24T15:07:38Z
2.0
AleoNet/snarkOS
1,527
AleoNet__snarkOS-1527
[ "1522" ]
9f0b304cb8407eec27077f212a86a79308528919
diff --git a/Cargo.lock b/Cargo.lock index beb2ebf665..e6269726b3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -220,9 +220,9 @@ dependencies = [ [[package]] name = "bumpalo" -version = "3.8.0" +version = "3.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f1e260c3a9040a7c19a12468758f4c16f31a81a1fe087482be9570ec864bb6c" +checksum = "fe438c9d2f2b0fb88a112154ed81e30b0a491c29322afe1db3b6eec5811f5ba0" [[package]] name = "byteorder" @@ -783,9 +783,9 @@ dependencies = [ [[package]] name = "generic-array" -version = "0.14.4" +version = "0.14.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "501466ecc8a30d1d3b7fc9229b122b2ce8ed6e9d9223f1138d4babb253e51817" +checksum = "fd48d33ec7f05fbfa152300fdad764757cbded343c1aa1cff2fbaf4134851803" dependencies = [ "typenum", "version_check", @@ -1983,7 +1983,7 @@ dependencies = [ [[package]] name = "snarkvm" version = "0.7.5" -source = "git+https://github.com/AleoHQ/snarkVM.git?rev=ff10c20#ff10c20512bb7f7853bf8c3f308d951e78a02290" +source = "git+https://github.com/AleoHQ/snarkVM.git?rev=459ea96#459ea966476e73b3c5296bf34ef508e0e7bcf547" dependencies = [ "snarkvm-dpc", "snarkvm-utilities", @@ -1992,7 +1992,7 @@ dependencies = [ [[package]] name = "snarkvm-algorithms" version = "0.7.5" -source = "git+https://github.com/AleoHQ/snarkVM.git?rev=ff10c20#ff10c20512bb7f7853bf8c3f308d951e78a02290" +source = "git+https://github.com/AleoHQ/snarkVM.git?rev=459ea96#459ea966476e73b3c5296bf34ef508e0e7bcf547" dependencies = [ "anyhow", "blake2", @@ -2021,7 +2021,7 @@ dependencies = [ [[package]] name = "snarkvm-curves" version = "0.7.5" -source = "git+https://github.com/AleoHQ/snarkVM.git?rev=ff10c20#ff10c20512bb7f7853bf8c3f308d951e78a02290" +source = "git+https://github.com/AleoHQ/snarkVM.git?rev=459ea96#459ea966476e73b3c5296bf34ef508e0e7bcf547" dependencies = [ "derivative", "rand", @@ -2035,7 +2035,7 @@ dependencies = [ [[package]] name = "snarkvm-derives" version = "0.7.5" -source = "git+https://github.com/AleoHQ/snarkVM.git?rev=ff10c20#ff10c20512bb7f7853bf8c3f308d951e78a02290" +source = "git+https://github.com/AleoHQ/snarkVM.git?rev=459ea96#459ea966476e73b3c5296bf34ef508e0e7bcf547" dependencies = [ "proc-macro-crate", "proc-macro-error", @@ -2047,7 +2047,7 @@ dependencies = [ [[package]] name = "snarkvm-dpc" version = "0.7.5" -source = "git+https://github.com/AleoHQ/snarkVM.git?rev=ff10c20#ff10c20512bb7f7853bf8c3f308d951e78a02290" +source = "git+https://github.com/AleoHQ/snarkVM.git?rev=459ea96#459ea966476e73b3c5296bf34ef508e0e7bcf547" dependencies = [ "anyhow", "base58", @@ -2079,7 +2079,7 @@ dependencies = [ [[package]] name = "snarkvm-fields" version = "0.7.5" -source = "git+https://github.com/AleoHQ/snarkVM.git?rev=ff10c20#ff10c20512bb7f7853bf8c3f308d951e78a02290" +source = "git+https://github.com/AleoHQ/snarkVM.git?rev=459ea96#459ea966476e73b3c5296bf34ef508e0e7bcf547" dependencies = [ "anyhow", "derivative", @@ -2092,7 +2092,7 @@ dependencies = [ [[package]] name = "snarkvm-gadgets" version = "0.7.5" -source = "git+https://github.com/AleoHQ/snarkVM.git?rev=ff10c20#ff10c20512bb7f7853bf8c3f308d951e78a02290" +source = "git+https://github.com/AleoHQ/snarkVM.git?rev=459ea96#459ea966476e73b3c5296bf34ef508e0e7bcf547" dependencies = [ "anyhow", "derivative", @@ -2112,7 +2112,7 @@ dependencies = [ [[package]] name = "snarkvm-marlin" version = "0.7.5" -source = "git+https://github.com/AleoHQ/snarkVM.git?rev=ff10c20#ff10c20512bb7f7853bf8c3f308d951e78a02290" +source = "git+https://github.com/AleoHQ/snarkVM.git?rev=459ea96#459ea966476e73b3c5296bf34ef508e0e7bcf547" dependencies = [ "bincode", "blake2", @@ -2138,7 +2138,7 @@ dependencies = [ [[package]] name = "snarkvm-parameters" version = "0.7.5" -source = "git+https://github.com/AleoHQ/snarkVM.git?rev=ff10c20#ff10c20512bb7f7853bf8c3f308d951e78a02290" +source = "git+https://github.com/AleoHQ/snarkVM.git?rev=459ea96#459ea966476e73b3c5296bf34ef508e0e7bcf547" dependencies = [ "aleo-std", "anyhow", @@ -2155,7 +2155,7 @@ dependencies = [ [[package]] name = "snarkvm-polycommit" version = "0.7.5" -source = "git+https://github.com/AleoHQ/snarkVM.git?rev=ff10c20#ff10c20512bb7f7853bf8c3f308d951e78a02290" +source = "git+https://github.com/AleoHQ/snarkVM.git?rev=459ea96#459ea966476e73b3c5296bf34ef508e0e7bcf547" dependencies = [ "derivative", "digest 0.9.0", @@ -2173,12 +2173,12 @@ dependencies = [ [[package]] name = "snarkvm-profiler" version = "0.7.5" -source = "git+https://github.com/AleoHQ/snarkVM.git?rev=ff10c20#ff10c20512bb7f7853bf8c3f308d951e78a02290" +source = "git+https://github.com/AleoHQ/snarkVM.git?rev=459ea96#459ea966476e73b3c5296bf34ef508e0e7bcf547" [[package]] name = "snarkvm-r1cs" version = "0.7.5" -source = "git+https://github.com/AleoHQ/snarkVM.git?rev=ff10c20#ff10c20512bb7f7853bf8c3f308d951e78a02290" +source = "git+https://github.com/AleoHQ/snarkVM.git?rev=459ea96#459ea966476e73b3c5296bf34ef508e0e7bcf547" dependencies = [ "anyhow", "cfg-if", @@ -2194,7 +2194,7 @@ dependencies = [ [[package]] name = "snarkvm-utilities" version = "0.7.5" -source = "git+https://github.com/AleoHQ/snarkVM.git?rev=ff10c20#ff10c20512bb7f7853bf8c3f308d951e78a02290" +source = "git+https://github.com/AleoHQ/snarkVM.git?rev=459ea96#459ea966476e73b3c5296bf34ef508e0e7bcf547" dependencies = [ "anyhow", "bincode", diff --git a/Cargo.toml b/Cargo.toml index e78e12b054..02387aacab 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -24,7 +24,7 @@ default = [] test = [] [dependencies] -snarkvm = { git = "https://github.com/AleoHQ/snarkVM.git", rev = "ff10c20" } +snarkvm = { git = "https://github.com/AleoHQ/snarkVM.git", rev = "459ea96" } #snarkvm = { path = "../snarkVM" } bytes = "1.0.0" diff --git a/src/environment/mod.rs b/src/environment/mod.rs index 621b350a7f..093ea7841e 100644 --- a/src/environment/mod.rs +++ b/src/environment/mod.rs @@ -19,8 +19,10 @@ use snarkvm::dpc::Network; use once_cell::sync::OnceCell; use std::{ + collections::HashSet, fmt::Debug, marker::PhantomData, + net::SocketAddr, sync::{atomic::AtomicBool, Arc}, }; @@ -40,9 +42,9 @@ pub trait Environment: 'static + Clone + Debug + Default + Send + Sync { const DEFAULT_RPC_PORT: u16 = 3030 + Self::Network::NETWORK_ID; /// The list of beacon nodes to bootstrap the node server with. - const BEACON_NODES: [&'static str; 0] = []; + const BEACON_NODES: &'static [&'static str] = &[]; /// The list of sync nodes to bootstrap the node server with. - const SYNC_NODES: [&'static str; 13] = ["127.0.0.1:4131", "127.0.0.1:4133", "127.0.0.1:4134", "127.0.0.1:4135", "127.0.0.1:4136", "127.0.0.1:4137", "127.0.0.1:4138", "127.0.0.1:4139", "127.0.0.1:4140", "127.0.0.1:4141", "127.0.0.1:4142", "127.0.0.1:4143", "127.0.0.1:4144"]; + const SYNC_NODES: &'static [&'static str] = &["127.0.0.1:4135"]; /// The duration in seconds to sleep in between heartbeat executions. const HEARTBEAT_IN_SECS: u64 = 9; @@ -73,6 +75,18 @@ pub trait Environment: 'static + Clone + Debug + Default + Send + Sync { /// The maximum number of failures tolerated before disconnecting from a peer. const MAXIMUM_NUMBER_OF_FAILURES: usize = 1024; + /// Returns the list of beacon nodes to bootstrap the node server with. + fn beacon_nodes() -> &'static HashSet<SocketAddr> { + static NODES: OnceCell<HashSet<SocketAddr>> = OnceCell::new(); + NODES.get_or_init(|| Self::BEACON_NODES.iter().map(|ip| ip.parse().unwrap()).collect()) + } + + /// Returns the list of sync nodes to bootstrap the node server with. + fn sync_nodes() -> &'static HashSet<SocketAddr> { + static NODES: OnceCell<HashSet<SocketAddr>> = OnceCell::new(); + NODES.get_or_init(|| Self::SYNC_NODES.iter().map(|ip| ip.parse().unwrap()).collect()) + } + /// Returns the tasks handler for the node. fn tasks() -> &'static Tasks<tokio::task::JoinHandle<()>> { static TASKS: OnceCell<Tasks<tokio::task::JoinHandle<()>>> = OnceCell::new(); @@ -135,7 +149,7 @@ impl<N: Network> Environment for Prover<N> { type Network = N; const NODE_TYPE: NodeType = NodeType::Prover; const COINBASE_IS_PUBLIC: bool = true; - const MINIMUM_NUMBER_OF_PEERS: usize = 1; + const MINIMUM_NUMBER_OF_PEERS: usize = 2; const MAXIMUM_NUMBER_OF_PEERS: usize = 21; } @@ -158,7 +172,7 @@ pub struct ClientTrial<N: Network>(PhantomData<N>); impl<N: Network> Environment for ClientTrial<N> { type Network = N; const NODE_TYPE: NodeType = NodeType::Client; - const SYNC_NODES: [&'static str; 13] = [ + const SYNC_NODES: &'static [&'static str] = &[ "144.126.219.193:4132", "165.232.145.194:4132", "143.198.164.241:4132", "188.166.7.13:4132", "167.99.40.226:4132", "159.223.124.150:4132", "137.184.192.155:4132", "147.182.213.228:4132", "137.184.202.162:4132", "159.223.118.35:4132", "161.35.106.91:4132", "157.245.133.62:4132", "143.198.166.150:4132", @@ -174,7 +188,7 @@ pub struct MinerTrial<N: Network>(PhantomData<N>); impl<N: Network> Environment for MinerTrial<N> { type Network = N; const NODE_TYPE: NodeType = NodeType::Miner; - const SYNC_NODES: [&'static str; 13] = [ + const SYNC_NODES: &'static [&'static str] = &[ "144.126.219.193:4132", "165.232.145.194:4132", "143.198.164.241:4132", "188.166.7.13:4132", "167.99.40.226:4132", "159.223.124.150:4132", "137.184.192.155:4132", "147.182.213.228:4132", "137.184.202.162:4132", "159.223.118.35:4132", "161.35.106.91:4132", "157.245.133.62:4132", "143.198.166.150:4132", @@ -191,7 +205,7 @@ pub struct OperatorTrial<N: Network>(PhantomData<N>); impl<N: Network> Environment for OperatorTrial<N> { type Network = N; const NODE_TYPE: NodeType = NodeType::Operator; - const SYNC_NODES: [&'static str; 13] = [ + const SYNC_NODES: &'static [&'static str] = &[ "144.126.219.193:4132", "165.232.145.194:4132", "143.198.164.241:4132", "188.166.7.13:4132", "167.99.40.226:4132", "159.223.124.150:4132", "137.184.192.155:4132", "147.182.213.228:4132", "137.184.202.162:4132", "159.223.118.35:4132", "161.35.106.91:4132", "157.245.133.62:4132", "143.198.166.150:4132", @@ -208,7 +222,7 @@ pub struct ProverTrial<N: Network>(PhantomData<N>); impl<N: Network> Environment for ProverTrial<N> { type Network = N; const NODE_TYPE: NodeType = NodeType::Prover; - const SYNC_NODES: [&'static str; 13] = [ + const SYNC_NODES: &'static [&'static str] = &[ "144.126.219.193:4132", "165.232.145.194:4132", "143.198.164.241:4132", "188.166.7.13:4132", "167.99.40.226:4132", "159.223.124.150:4132", "137.184.192.155:4132", "147.182.213.228:4132", "137.184.202.162:4132", "159.223.118.35:4132", "161.35.106.91:4132", "157.245.133.62:4132", "143.198.166.150:4132", diff --git a/src/helpers/block_requests.rs b/src/helpers/block_requests.rs index b9d3297b4a..4e1a954eb7 100644 --- a/src/helpers/block_requests.rs +++ b/src/helpers/block_requests.rs @@ -18,7 +18,7 @@ use crate::{network::ledger::PeersState, Environment}; use snarkos_storage::{BlockLocators, LedgerState}; use snarkvm::dpc::prelude::*; -use std::{collections::HashSet, net::SocketAddr}; +use std::net::SocketAddr; /// Checks if any of the peers are ahead and have a larger block height, if they are on a fork, and their block locators. /// The maximum known block height and cumulative weight are tracked for the purposes of further operations. @@ -27,8 +27,6 @@ pub fn find_maximal_peer<N: Network, E: Environment>( maximum_block_height: &mut u32, maximum_cumulative_weight: &mut u128, ) -> Option<(SocketAddr, bool, BlockLocators<N>)> { - let sync_nodes: HashSet<SocketAddr> = E::SYNC_NODES.iter().map(|ip| ip.parse().unwrap()).collect(); - // Determine if the peers state has any sync nodes. // TODO: have nodes sync up to tip - 4096 with only sync nodes, then switch to syncing with the longest chain. let peers_contains_sync_node = false; @@ -40,7 +38,7 @@ pub fn find_maximal_peer<N: Network, E: Environment>( for (peer_ip, peer_state) in peers_state.iter() { // Only update the maximal peer if there are no sync nodes or the peer is a sync node. - if !peers_contains_sync_node || sync_nodes.contains(peer_ip) { + if !peers_contains_sync_node || E::sync_nodes().contains(peer_ip) { // Update the maximal peer state if the peer is ahead and the peer knows if you are a fork or not. // This accounts for (Case 1 and Case 2(a)) if let Some((_, _, is_on_fork, block_height, block_locators)) = peer_state { diff --git a/src/network/message.rs b/src/network/message.rs index be4c8c801a..a1837cb96e 100644 --- a/src/network/message.rs +++ b/src/network/message.rs @@ -19,7 +19,7 @@ use crate::{ Environment, }; use snarkos_storage::BlockLocators; -use snarkvm::prelude::*; +use snarkvm::{dpc::posw::PoSWProof, prelude::*}; use ::bytes::{Buf, BytesMut}; use anyhow::{anyhow, Result}; @@ -106,8 +106,8 @@ pub enum Message<N: Network, E: Environment> { PoolRegister(Address<N>), /// PoolRequest := (share_difficulty, block_template) PoolRequest(u64, Data<BlockTemplate<N>>), - /// PoolResponse := (address, block_header) - PoolResponse(Address<N>, Data<BlockHeader<N>>), + /// PoolResponse := (address, nonce, proof) + PoolResponse(Address<N>, N::PoSWNonce, Data<PoSWProof<N>>), /// Unused #[allow(unused)] Unused(PhantomData<E>), @@ -197,7 +197,12 @@ impl<N: Network, E: Environment> Message<N, E> { Self::PoolRequest(share_difficulty, block_template) => { Ok([bincode::serialize(share_difficulty)?, block_template.serialize_blocking()?].concat()) } - Self::PoolResponse(address, block) => Ok([bincode::serialize(address)?, block.serialize_blocking()?].concat()), + Self::PoolResponse(address, nonce, proof) => Ok([ + bincode::serialize(address)?, + bincode::serialize(nonce)?, + proof.serialize_blocking()?, + ] + .concat()), Self::Unused(_) => Ok(vec![]), } } @@ -261,7 +266,11 @@ impl<N: Network, E: Environment> Message<N, E> { 10 => Self::UnconfirmedTransaction(bincode::deserialize(data)?), 11 => Self::PoolRegister(bincode::deserialize(data)?), 12 => Self::PoolRequest(bincode::deserialize(&data[0..8])?, Data::Buffer(data[8..].to_vec())), - 13 => Self::PoolResponse(bincode::deserialize(&data[0..32])?, Data::Buffer(data[32..].to_vec())), + 13 => Self::PoolResponse( + bincode::deserialize(&data[0..32])?, + bincode::deserialize(&data[32..64])?, + Data::Buffer(data[64..].to_vec()), + ), _ => return Err(anyhow!("Invalid message ID {}", id)), }; diff --git a/src/network/operator.rs b/src/network/operator.rs index 0a4f7d4444..568081c362 100644 --- a/src/network/operator.rs +++ b/src/network/operator.rs @@ -27,7 +27,7 @@ use crate::{ ProverRouter, }; use snarkos_storage::{storage::Storage, OperatorState}; -use snarkvm::dpc::prelude::*; +use snarkvm::dpc::{prelude::*, PoSWProof}; use anyhow::Result; use rand::thread_rng; @@ -55,10 +55,10 @@ type OperatorHandler<N> = mpsc::Receiver<OperatorRequest<N>>; /// #[derive(Debug)] pub enum OperatorRequest<N: Network> { - /// PoolRegister := (peer_ip, worker_address) + /// PoolRegister := (peer_ip, prover_address) PoolRegister(SocketAddr, Address<N>), - /// PoolResponse := (peer_ip, proposed_block_header, worker_address) - PoolResponse(SocketAddr, BlockHeader<N>, Address<N>), + /// PoolResponse := (peer_ip, prover_address, nonce, proof) + PoolResponse(SocketAddr, Address<N>, N::PoSWNonce, PoSWProof<N>), } /// The predefined base share difficulty. @@ -263,42 +263,17 @@ impl<N: Network, E: Environment> Operator<N, E> { warn!("[PoolRegister] No current block template exists"); } } - OperatorRequest::PoolResponse(peer_ip, block_header, prover) => { + OperatorRequest::PoolResponse(peer_ip, prover, nonce, proof) => { if let Some(block_template) = self.block_template.read().await.clone() { - // Ensure the given block header corresponds to the correct block height. - if block_template.block_height() != block_header.height() { - warn!("[PoolResponse] Peer {} sent a stale block.", peer_ip); - return; - } - // Ensure the timestamp in the block template matches in the block header. - if block_template.block_timestamp() != block_header.timestamp() { - warn!("[PoolResponse] Peer {} sent a block with an incorrect timestamp.", peer_ip); - return; - } - // Ensure the difficulty target in the block template matches in the block header. - if block_template.difficulty_target() != block_header.difficulty_target() { - warn!("[PoolResponse] Peer {} sent a block with an incorrect difficulty target.", peer_ip); - return; - } - // Ensure the previous ledger root in the block template matches in the block header. - if block_template.previous_ledger_root() != block_header.previous_ledger_root() { - warn!("[PoolResponse] Peer {} sent a block with an incorrect ledger root.", peer_ip); - return; - } - // Ensure the transactions root in the block header matches the one from the block template. - if block_template.transactions().transactions_root() != block_header.transactions_root() { - warn!("[PoolResponse] Peer {} has changed the list of block transactions.", peer_ip); - return; - } // Ensure the given nonce from the prover is new. - if self.known_nonces.read().await.contains(&block_header.nonce()) { + if self.known_nonces.read().await.contains(&nonce) { warn!("[PoolResponse] Peer {} sent a duplicate share", peer_ip); // TODO (julesdesmit): punish? return; } // Update known nonces. - self.known_nonces.write().await.insert(block_header.nonce()); + self.known_nonces.write().await.insert(nonce); // Retrieve the share difficulty for the given prover. let share_difficulty = { @@ -313,12 +288,12 @@ impl<N: Network, E: Environment> Operator<N, E> { }; // Ensure the share difficulty target is met, and the PoSW proof is valid. - let block_height = block_header.height(); + let block_height = block_template.block_height(); if !N::posw().verify( block_height, share_difficulty, - &[*block_header.to_header_root().unwrap(), *block_header.nonce()], - block_header.proof(), + &[*block_template.to_header_root().unwrap(), *nonce], + &proof, ) { warn!("[PoolResponse] PoSW proof verification failed"); return; @@ -336,8 +311,8 @@ impl<N: Network, E: Environment> Operator<N, E> { let coinbase_record = block_template.coinbase_record().clone(); match self.state.increment_share(block_height, coinbase_record, &prover) { Ok(..) => info!( - "Operator received a valid share from {} ({}) for block {}", - peer_ip, prover, block_height, + "Operator has received a valid share from {} ({}) for block {}", + prover, peer_ip, block_height, ), Err(error) => error!("{}", error), } @@ -345,11 +320,19 @@ impl<N: Network, E: Environment> Operator<N, E> { // If the block has satisfactory difficulty and is valid, proceed to broadcast it. let previous_block_hash = block_template.previous_block_hash(); let transactions = block_template.transactions().clone(); - if let Ok(block) = Block::from(previous_block_hash, block_header, transactions) { - info!("Operator has found unconfirmed block {} ({})", block.height(), block.hash()); - let request = LedgerRequest::UnconfirmedBlock(self.local_ip, block, self.prover_router.clone()); - if let Err(error) = self.ledger_router.send(request).await { - warn!("Failed to broadcast mined block - {}", error); + if let Ok(block_header) = BlockHeader::<N>::from( + block_template.previous_ledger_root(), + block_template.transactions().transactions_root(), + BlockHeaderMetadata::new(&block_template), + nonce, + proof, + ) { + if let Ok(block) = Block::from(previous_block_hash, block_header, transactions) { + info!("Operator has found unconfirmed block {} ({})", block.height(), block.hash()); + let request = LedgerRequest::UnconfirmedBlock(self.local_ip, block, self.prover_router.clone()); + if let Err(error) = self.ledger_router.send(request).await { + warn!("Failed to broadcast mined block - {}", error); + } } } } else { diff --git a/src/network/peer.rs b/src/network/peer.rs index 140496c278..86f0c645ad 100644 --- a/src/network/peer.rs +++ b/src/network/peer.rs @@ -706,15 +706,15 @@ impl<N: Network, E: Environment> Peer<N, E> { warn!("[PoolRequest] could not deserialize block template"); } } - Message::PoolResponse(address, block_header) => { + Message::PoolResponse(address, nonce, proof) => { if E::NODE_TYPE != NodeType::Operator { trace!("Skipping 'PoolResponse' from {}", peer_ip); - } else if let Ok(block_header) = block_header.deserialize().await { - if let Err(error) = operator_router.send(OperatorRequest::PoolResponse(peer_ip, block_header, address)).await { + } else if let Ok(proof) = proof.deserialize().await { + if let Err(error) = operator_router.send(OperatorRequest::PoolResponse(peer_ip, address, nonce, proof)).await { warn!("[PoolResponse] {}", error); } } else { - warn!("[PoolResponse] could not deserialize block"); + warn!("[PoolResponse] could not deserialize proof"); } } Message::Unused(_) => break, // Peer is not following the protocol. diff --git a/src/network/peers.rs b/src/network/peers.rs index c4cc57c05a..f4beb24f46 100644 --- a/src/network/peers.rs +++ b/src/network/peers.rs @@ -196,8 +196,7 @@ impl<N: Network, E: Environment> Peers<N, E> { /// pub async fn connected_sync_nodes(&self) -> HashSet<SocketAddr> { let connected_peers: HashSet<SocketAddr> = self.connected_peers.read().await.keys().into_iter().copied().collect(); - let sync_nodes: HashSet<SocketAddr> = E::SYNC_NODES.iter().map(|ip| ip.parse().unwrap()).collect(); - connected_peers.intersection(&sync_nodes).copied().collect() + connected_peers.intersection(E::sync_nodes()).copied().collect() } /// @@ -206,8 +205,7 @@ impl<N: Network, E: Environment> Peers<N, E> { /// pub async fn number_of_connected_sync_nodes(&self) -> usize { let connected_peers: HashSet<SocketAddr> = self.connected_peers.read().await.keys().into_iter().copied().collect(); - let sync_nodes: HashSet<SocketAddr> = E::SYNC_NODES.iter().map(|ip| ip.parse().unwrap()).collect(); - connected_peers.intersection(&sync_nodes).count() + connected_peers.intersection(E::sync_nodes()).count() } /// @@ -324,10 +322,7 @@ impl<N: Network, E: Environment> Peers<N, E> { .read() .await .iter() - .filter(|(&peer_ip, _)| { - let peer_str = peer_ip.to_string(); - !E::SYNC_NODES.contains(&peer_str.as_str()) && !E::BEACON_NODES.contains(&peer_str.as_str()) - }) + .filter(|(peer_ip, _)| !E::sync_nodes().contains(peer_ip) && !E::beacon_nodes().contains(peer_ip)) .take(num_excess_peers) .map(|(&peer_ip, _)| peer_ip) .collect::<Vec<SocketAddr>>(); @@ -347,6 +342,8 @@ impl<N: Network, E: Environment> Peers<N, E> { let number_of_connected_sync_nodes = connected_sync_nodes.len(); let num_excess_sync_nodes = number_of_connected_sync_nodes.saturating_sub(1); if num_excess_sync_nodes > 0 { + debug!("Exceeded maximum number of sync nodes"); + // Proceed to send disconnect requests to these peers. for peer_ip in connected_sync_nodes .iter() @@ -373,14 +370,12 @@ impl<N: Network, E: Environment> Peers<N, E> { }; // Add the sync nodes to the list of candidate peers. - let sync_nodes: Vec<SocketAddr> = E::SYNC_NODES.iter().map(|ip| ip.parse().unwrap()).collect(); if number_of_connected_sync_nodes == 0 { - self.add_candidate_peers(&sync_nodes).await; + self.add_candidate_peers(E::sync_nodes().iter()).await; } // Add the beacon nodes to the list of candidate peers. - let beacon_nodes: Vec<SocketAddr> = E::BEACON_NODES.iter().map(|ip| ip.parse().unwrap()).collect(); - self.add_candidate_peers(&beacon_nodes).await; + self.add_candidate_peers(E::beacon_nodes().iter()).await; // Attempt to connect to more peers if the number of connected peers is below the minimum threshold. // Select the peers randomly from the list of candidate peers. @@ -393,7 +388,7 @@ impl<N: Network, E: Environment> Peers<N, E> { .choose_multiple(&mut OsRng::default(), midpoint_number_of_peers) { // Ensure this node is not connected to more than the permitted number of sync nodes. - if sync_nodes.contains(&peer_ip) && number_of_connected_sync_nodes >= 1 { + if E::sync_nodes().contains(&peer_ip) && number_of_connected_sync_nodes >= 1 { continue; } @@ -528,7 +523,7 @@ impl<N: Network, E: Environment> Peers<N, E> { self.send(recipient, Message::PeerResponse(connected_peers)).await; } PeersRequest::ReceivePeerResponse(peer_ips) => { - self.add_candidate_peers(&peer_ips).await; + self.add_candidate_peers(peer_ips.iter()).await; } } } @@ -539,19 +534,17 @@ impl<N: Network, E: Environment> Peers<N, E> { /// This method skips adding any given peers if the combined size exceeds the threshold, /// as the peer providing this list could be subverting the protocol. /// - async fn add_candidate_peers(&self, peers: &[SocketAddr]) { + async fn add_candidate_peers<'a, T: ExactSizeIterator<Item = &'a SocketAddr> + IntoIterator>(&self, peers: T) { // Acquire the candidate peers write lock. let mut candidate_peers = self.candidate_peers.write().await; // Ensure the combined number of peers does not surpass the threshold. - if candidate_peers.len() + peers.len() < E::MAXIMUM_CANDIDATE_PEERS { - // Proceed to insert each new candidate peer IP. - for peer_ip in peers.iter().take(E::MAXIMUM_CANDIDATE_PEERS) { - // Ensure the peer is not self and is a new candidate peer. - let is_self = *peer_ip == self.local_ip - || (peer_ip.ip().is_unspecified() || peer_ip.ip().is_loopback()) && peer_ip.port() == self.local_ip.port(); - if !is_self && !self.is_connected_to(*peer_ip).await { - candidate_peers.insert(*peer_ip); - } + for peer_ip in peers.take(E::MAXIMUM_CANDIDATE_PEERS.saturating_sub(candidate_peers.len())) { + // Ensure the peer is not self and is a new candidate peer. + let is_self = *peer_ip == self.local_ip + || (peer_ip.ip().is_unspecified() || peer_ip.ip().is_loopback()) && peer_ip.port() == self.local_ip.port(); + if !is_self && !self.is_connected_to(*peer_ip).await { + // Proceed to insert each new candidate peer IP. + candidate_peers.insert(*peer_ip); } } } @@ -587,10 +580,7 @@ impl<N: Network, E: Environment> Peers<N, E> { .connected_peers() .await .iter() - .filter(|peer_ip| { - let peer_str = peer_ip.to_string(); - *peer_ip != &sender && !E::SYNC_NODES.contains(&peer_str.as_str()) && !E::BEACON_NODES.contains(&peer_str.as_str()) - }) + .filter(|peer_ip| *peer_ip != &sender && !E::sync_nodes().contains(peer_ip) && !E::beacon_nodes().contains(peer_ip)) .copied() .collect::<Vec<_>>() { diff --git a/src/network/prover.rs b/src/network/prover.rs index 24e746f957..b0dc51994b 100644 --- a/src/network/prover.rs +++ b/src/network/prover.rs @@ -26,7 +26,7 @@ use crate::{ PeersRouter, }; use snarkos_storage::{storage::Storage, ProverState}; -use snarkvm::dpc::prelude::*; +use snarkvm::dpc::{posw::PoSWProof, prelude::*}; use anyhow::{anyhow, Result}; use rand::thread_rng; @@ -245,6 +245,7 @@ impl<N: Network, E: Environment> Prover<N, E> { E::status().update(State::Mining); let thread_pool = self.thread_pool.clone(); + let block_height = block_template.block_height(); let block_template = block_template.clone(); let result = task::spawn_blocking(move || { @@ -260,8 +261,11 @@ impl<N: Network, E: Environment> Prover<N, E> { &[*block_header.to_header_root().unwrap(), *block_header.nonce()], block_header.proof(), ) { - let proof_difficulty = block_header.proof().to_proof_difficulty()?; - return Ok::<(BlockHeader<N>, u64), anyhow::Error>((block_header, proof_difficulty)); + return Ok::<(N::PoSWNonce, PoSWProof<N>, u64), anyhow::Error>(( + block_header.nonce(), + block_header.proof().clone(), + block_header.proof().to_proof_difficulty()?, + )); } } }) @@ -271,21 +275,20 @@ impl<N: Network, E: Environment> Prover<N, E> { E::status().update(State::Ready); match result { - Ok(Ok((block_header, proof_difficulty))) => { + Ok(Ok((nonce, proof, proof_difficulty))) => { info!( "Prover successfully mined a share for unconfirmed block {} with proof difficulty of {}", - block_header.height(), - proof_difficulty + block_height, proof_difficulty ); // Send a `PoolResponse` to the operator. - let message = Message::PoolResponse(recipient, Data::Object(block_header)); + let message = Message::PoolResponse(recipient, nonce, Data::Object(proof)); if let Err(error) = self.peers_router.send(PeersRequest::MessageSend(operator_ip, message)).await { warn!("[PoolResponse] {}", error); } } Ok(Err(error)) => trace!("{}", error), - Err(error) => trace!("{}", anyhow!("Could not mine next block {}", error)), + Err(error) => trace!("{}", anyhow!("Failed to mine the next block {}", error)), } } } diff --git a/storage/Cargo.toml b/storage/Cargo.toml index 1859c378e2..06fc6f2ad9 100644 --- a/storage/Cargo.toml +++ b/storage/Cargo.toml @@ -17,7 +17,7 @@ license = "GPL-3.0" edition = "2018" [dependencies] -snarkvm = { git = "https://github.com/AleoHQ/snarkVM.git", rev = "ff10c20" } +snarkvm = { git = "https://github.com/AleoHQ/snarkVM.git", rev = "459ea96" } #snarkvm = { path = "../../snarkVM" } [dependencies.anyhow]
diff --git a/testing/Cargo.toml b/testing/Cargo.toml index 300bb826b9..313469f9d5 100644 --- a/testing/Cargo.toml +++ b/testing/Cargo.toml @@ -25,7 +25,7 @@ path = "../storage" [dependencies.snarkvm] git = "https://github.com/AleoHQ/snarkVM.git" -rev = "ff10c20" +rev = "459ea96" #path = "../../snarkVM" [dependencies.anyhow]
[Bug] Pool operator reports "could not deserialize block" There are still issues: The operator reports `could not deserialize block` on `PoolResponse`. It looks like when deserializing `BlockHeader`, there is another `is_valid` check (`snarkVM/dpc/src/block/header.rs`, line 375 -> 143 -> 230) so the operator will be unable to deserialize the header. We might need a `from_unchecked` for `BlockHeader` as well. _Originally posted by @HarukaMa in https://github.com/AleoHQ/snarkOS/issues/1492#issuecomment-1000500810_ I guess this comment was ignored and I was using a modified snarkVM so I didn't think about this again. The line numbers might be out of date but it should still be the deserialization from bytes process.
network/peers.rs I find this code much improved, so one has actually an idea what's going on if de-serialization fails. Message::PoolRequest(share_difficulty, block_template) => { if E::NODE_TYPE != NodeType::Prover { trace!("Skipping 'PoolRequest' from {}", peer_ip); } else { match block_template.deserialize().await { Ok(block_template) => { if let Err(error) = prover_router.send(ProverRequest::PoolRequest(peer_ip, share_difficulty, block_template)).await { warn!("[PoolRequest] {}", error); } } Err(error) => { warn!("[PoolRequest] could not deserialize block template from {}: {}", peer_ip, error); } } } } Message::PoolResponse(address, block_header) => { if E::NODE_TYPE != NodeType::Operator { trace!("Skipping 'PoolResponse' from {}", peer_ip); } else { match block_header.deserialize().await { Ok(block_header) => { if let Err(error) = operator_router.send(OperatorRequest::PoolResponse(peer_ip, block_header, address)).await { warn!("[PoolResponse] {}", error); } } Err(error) => { warn!("[PoolResponse] could not deserialize block from {}: {}", peer_ip, error); } } } } That said, the code now reports as the issue `2022-01-04T16:06:38.772476Z WARN [PoolResponse] could not deserialize block from 192.168.1.114:4006: Invalid block header` I find it odd, to report an issue on de-serialization, when in fact the de-serialization worked, but a downstream check is_valid(), returned false. Can confirm that we have same warning.
2022-01-06T02:55:34Z
2.0
AleoNet/snarkOS
1,427
AleoNet__snarkOS-1427
[ "1492" ]
11679d4e08efa53660eca852a8e7de3275f5f73f
"diff --git a/Cargo.lock b/Cargo.lock\nindex 3148b2de22..0e6d9d84ab 100644\n--- a/Cargo.lock\n+++ b/(...TRUNCATED)
"diff --git a/testing/Cargo.toml b/testing/Cargo.toml\nindex 67b09a297a..3440cd3652 100644\n--- a/te(...TRUNCATED)
"[Bug][Pool S/W] Failed to initialize a block from given inputs due to Invalid block header\n## 🐛(...TRUNCATED)
2021-12-15T07:31:01Z
2.0
AleoNet/snarkOS
1,284
AleoNet__snarkOS-1284
[ "1266" ]
90d33030e0f6913bada2ee1577ada43194d2986c
"diff --git a/ledger/src/helpers/block_locators.rs b/ledger/src/helpers/block_locators.rs\nindex 6e6(...TRUNCATED)
"diff --git a/ledger/src/state/tests.rs b/ledger/src/state/tests.rs\nindex db7c7275eb..5176d1983a 10(...TRUNCATED)
"Track rolled back blocks\n<!-- Thank you for filing a PR! Help us understand by explaining your cha(...TRUNCATED)
2021-11-15T09:40:38Z
2.0
AleoNet/snarkOS
1,026
AleoNet__snarkOS-1026
[ "979" ]
64586b2d15ec6b75dd048d4df87534287ebb87d3
"diff --git a/consensus/src/consensus/inner/agent.rs b/consensus/src/consensus/inner/agent.rs\nindex(...TRUNCATED)
"diff --git a/consensus/tests/consensus_sidechain.rs b/consensus/tests/consensus_sidechain.rs\nindex(...TRUNCATED)
"[Feature] Send fork points in block locator hashes\nTo alleviate issues with syncing with forks aro(...TRUNCATED)
"While this could be a good ad-hoc measure, we could improve the general situation if we just decide(...TRUNCATED)
2021-08-10T00:29:33Z
1.3
AleoNet/snarkOS
927
AleoNet__snarkOS-927
[ "817" ]
16235c8d8968357be41fb03c729dfa4e87536362
"diff --git a/network/src/errors/network.rs b/network/src/errors/network.rs\nindex 4b1a86dab7..c6f79(...TRUNCATED)
"diff --git a/network/tests/peers.rs b/network/tests/peers.rs\nindex 8792a988e7..86fa8fb474 100644\n(...TRUNCATED)
"[Feature] Don't provide unroutable addresses in peer lists\nThe current peer-sharing mechanism only(...TRUNCATED)
2021-07-07T13:45:46Z
1.3
AleoNet/snarkOS
878
AleoNet__snarkOS-878
[ "802", "818" ]
fee2c04ff43bea30047da19b21ab69fe3fec42e2
"diff --git a/Cargo.lock b/Cargo.lock\nindex ca14eb4226..f312fd086c 100644\n--- a/Cargo.lock\n+++ b/(...TRUNCATED)
"diff --git a/network/tests/topology.rs b/network/tests/topology.rs\nindex 78311941f4..ee6cfdf358 10(...TRUNCATED)
"[Feature] Protocol (as opposed to rpc) based network crawler\n## 🚀 Feature\r\n\r\nA network base(...TRUNCATED)
2021-06-17T14:59:02Z
1.3
README.md exists but content is empty.
Downloads last month
1