Skip to content

Commit

Permalink
refactored handshake logic before adding tier1 support (#7602)
Browse files Browse the repository at this point in the history
This change introduces no change to the network protocol, binaries from before and after refactor are expected to connect without problem.
I've extracted handshake state (aka HandshakeSpec) from the PeerActor.
I've reduced the amount of logic in handle_msg_register_peer.
With a dedicated handshake state machine it will be easier to grasp the additions that tier1 support for PeerActor will introduce.
  • Loading branch information
pompon0 authored and nikurt committed Nov 9, 2022
1 parent 3577d2f commit ed8a569
Show file tree
Hide file tree
Showing 14 changed files with 523 additions and 518 deletions.
8 changes: 5 additions & 3 deletions chain/network-primitives/src/network_protocol/edge.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,10 @@ impl PartialEdgeInfo {
}
}

#[derive(thiserror::Error, Debug)]
pub enum InvalidNonceError {
NonceOutOfBoundsError,
#[error("nonce is overflowing i64: {nonce}")]
NonceOutOfBoundsError { nonce: u64 },
}

#[cfg_attr(feature = "deepsize_feature", derive(deepsize::DeepSizeOf))]
Expand Down Expand Up @@ -252,9 +254,9 @@ impl Edge {
}
},
)
.map_err(|_| InvalidNonceError::NonceOutOfBoundsError)
.map_err(|_| InvalidNonceError::NonceOutOfBoundsError { nonce })
} else {
Err(InvalidNonceError::NonceOutOfBoundsError)
Err(InvalidNonceError::NonceOutOfBoundsError { nonce })
}
}
}
Expand Down
12 changes: 1 addition & 11 deletions chain/network-primitives/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ pub use crate::network_protocol::{

pub use crate::blacklist::{Blacklist, Entry as BlacklistEntry};
pub use crate::network_protocol::edge::{
Edge, EdgeState, PartialEdgeInfo, EDGE_MIN_TIMESTAMP_NONCE,
Edge, EdgeState, InvalidNonceError, PartialEdgeInfo, EDGE_MIN_TIMESTAMP_NONCE,
};

/// Number of hops a message is allowed to travel before being dropped.
Expand Down Expand Up @@ -188,15 +188,6 @@ impl InboundTcpConnect {
}
}

/// Actor message to request the creation of an outbound TCP connection to a peer.
#[cfg_attr(feature = "deepsize_feature", derive(deepsize::DeepSizeOf))]
#[derive(Message, Clone, Debug)]
#[rtype(result = "()")]
pub struct OutboundTcpConnect {
/// Peer information of the outbound connection
pub peer_info: PeerInfo,
}

/// Ban reason.
#[cfg_attr(feature = "deepsize_feature", derive(deepsize::DeepSizeOf))]
#[derive(BorshSerialize, BorshDeserialize, Debug, Clone, PartialEq, Eq, Copy)]
Expand Down Expand Up @@ -360,7 +351,6 @@ mod tests {
assert_size!(RoutedMessage);
assert_size!(KnownPeerState);
assert_size!(InboundTcpConnect);
assert_size!(OutboundTcpConnect);
assert_size!(Ban);
assert_size!(StateResponseInfoV1);
assert_size!(PartialEncodedChunkRequestMsg);
Expand Down
37 changes: 9 additions & 28 deletions chain/network/src/network_protocol/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,8 @@ use near_primitives::hash::CryptoHash;
use near_primitives::network::{AnnounceAccount, PeerId};
use near_primitives::syncing::{EpochSyncFinalizationResponse, EpochSyncResponse};
use near_primitives::transaction::SignedTransaction;
use near_primitives::types::{AccountId, EpochId, ProtocolVersion};
use near_primitives::types::{AccountId, EpochId};
use near_primitives::validator_signer::ValidatorSigner;
use near_primitives::version::PEER_MIN_ALLOWED_PROTOCOL_VERSION;
use protobuf::Message as _;
use std::fmt;
use std::sync::Arc;
Expand Down Expand Up @@ -202,27 +201,6 @@ pub struct Handshake {
pub(crate) partial_edge_info: PartialEdgeInfo,
}

impl Handshake {
pub fn new(
version: ProtocolVersion,
peer_id: PeerId,
target_peer_id: PeerId,
listen_port: Option<u16>,
chain_info: PeerChainInfoV2,
partial_edge_info: PartialEdgeInfo,
) -> Self {
Handshake {
protocol_version: version,
oldest_supported_version: PEER_MIN_ALLOWED_PROTOCOL_VERSION,
sender_peer_id: peer_id,
target_peer_id,
sender_listen_port: listen_port,
sender_chain_info: chain_info,
partial_edge_info,
}
}
}

#[derive(PartialEq, Eq, Clone, Debug, strum::IntoStaticStr)]
pub enum HandshakeFailureReason {
ProtocolVersionMismatch { version: u32, oldest_supported_version: u32 },
Expand Down Expand Up @@ -298,14 +276,17 @@ pub enum ParsePeerMessageError {
}

impl PeerMessage {
pub fn serialize(&self, enc: Encoding) -> Vec<u8> {
pub(crate) fn serialize(&self, enc: Encoding) -> Vec<u8> {
match enc {
Encoding::Borsh => borsh::PeerMessage::from(self).try_to_vec().unwrap(),
Encoding::Proto => proto::PeerMessage::from(self).write_to_bytes().unwrap(),
}
}

pub fn deserialize(enc: Encoding, data: &[u8]) -> Result<PeerMessage, ParsePeerMessageError> {
pub(crate) fn deserialize(
enc: Encoding,
data: &[u8],
) -> Result<PeerMessage, ParsePeerMessageError> {
Ok(match enc {
Encoding::Borsh => (&borsh::PeerMessage::try_from_slice(data)
.map_err(ParsePeerMessageError::BorshDecode)?)
Expand All @@ -318,14 +299,14 @@ impl PeerMessage {
})
}

pub fn msg_variant(&self) -> &'static str {
pub(crate) fn msg_variant(&self) -> &'static str {
match self {
PeerMessage::Routed(routed_msg) => routed_msg.body_variant(),
_ => self.into(),
}
}

pub fn is_client_message(&self) -> bool {
pub(crate) fn is_client_message(&self) -> bool {
match self {
PeerMessage::Block(_)
| PeerMessage::BlockHeaders(_)
Expand All @@ -348,7 +329,7 @@ impl PeerMessage {
}
}

pub fn is_view_client_message(&self) -> bool {
pub(crate) fn is_view_client_message(&self) -> bool {
match self {
PeerMessage::BlockHeadersRequest(_)
| PeerMessage::BlockRequest(_)
Expand Down
53 changes: 27 additions & 26 deletions chain/network/src/network_protocol/testonly.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ use near_primitives::sharding::{
use near_primitives::transaction::SignedTransaction;
use near_primitives::types::{AccountId, BlockHeight, EpochId, StateRoot};
use near_primitives::validator_signer::{InMemoryValidatorSigner, ValidatorSigner};
use near_primitives::version::PROTOCOL_VERSION;
use near_primitives::version;
use rand::distributions::Standard;
use rand::Rng;
use std::collections::HashMap;
Expand All @@ -28,7 +28,7 @@ use std::sync::Arc;

pub fn make_genesis_block(_clock: &time::Clock, chunks: Vec<ShardChunk>) -> Block {
Block::genesis(
PROTOCOL_VERSION,
version::PROTOCOL_VERSION,
chunks.into_iter().map(|c| c.take_header()).collect(),
// TODO: this should be clock.now(), but Block::genesis has to be migrated
// from chrono to time first.
Expand All @@ -47,22 +47,22 @@ pub fn make_block(
chunks: Vec<ShardChunk>,
) -> Block {
Block::produce(
PROTOCOL_VERSION, // this_epoch_protocol_version
PROTOCOL_VERSION, // next_epoch_protocol_version
prev.header(), // prev
prev.header().height() + 5, // height
prev.header().block_ordinal() + 1, // block_ordinal
version::PROTOCOL_VERSION, // this_epoch_protocol_version
version::PROTOCOL_VERSION, // next_epoch_protocol_version
prev.header(), // prev
prev.header().height() + 5, // height
prev.header().block_ordinal() + 1, // block_ordinal
chunks.into_iter().map(|c| c.take_header()).collect(), // chunks
EpochId::default(), // epoch_id
EpochId::default(), // next_epoch_id
None, // epoch_sync_data_hash
vec![], // approvals
Ratio::from_integer(0), // gas_price_adjustment_rate
0, // min_gas_price
0, // max_gas_price
Some(0), // minted_amount
vec![], // challenges_result
vec![], // challenges
EpochId::default(), // epoch_id
EpochId::default(), // next_epoch_id
None, // epoch_sync_data_hash
vec![], // approvals
Ratio::from_integer(0), // gas_price_adjustment_rate
0, // min_gas_price
0, // max_gas_price
Some(0), // minted_amount
vec![], // challenges_result
vec![], // challenges
signer,
CryptoHash::default(), // next_bp_hash
CryptoHash::default(), // block_merkle_root
Expand Down Expand Up @@ -223,7 +223,7 @@ impl ChunkSet {
4, // num_shards
1000, // initial_gas_limit
0, // genesis_height
PROTOCOL_VERSION,
version::PROTOCOL_VERSION,
);
self.chunks.extend(chunks.iter().map(|c| (c.chunk_hash(), c.clone())));
chunks
Expand Down Expand Up @@ -340,14 +340,15 @@ pub fn make_handshake<R: Rng>(rng: &mut R, chain: &Chain) -> Handshake {
let b = make_signer(rng);
let a_id = PeerId::new(a.public_key);
let b_id = PeerId::new(b.public_key);
Handshake::new(
PROTOCOL_VERSION,
a_id,
b_id,
Some(rng.gen()),
chain.get_peer_chain_info(),
make_partial_edge(rng),
)
Handshake {
protocol_version: version::PROTOCOL_VERSION,
oldest_supported_version: version::PEER_MIN_ALLOWED_PROTOCOL_VERSION,
sender_peer_id: a_id,
target_peer_id: b_id,
sender_listen_port: Some(rng.gen()),
sender_chain_info: chain.get_peer_chain_info(),
partial_edge_info: make_partial_edge(rng),
}
}

pub fn make_routed_message<R: Rng>(rng: &mut R, body: RoutedMessageBody) -> RoutedMessageV2 {
Expand Down
Loading

0 comments on commit ed8a569

Please sign in to comment.