feat: Alloy migration (#4737)

Co-authored-by: Alessandro Mazza <121622391+alessandromazza98@users.noreply.github.com>
Co-authored-by: Supernovahs.eth <91280922+supernovahs@users.noreply.github.com>
Co-authored-by: Oliver Nordbjerg <hi@notbjerg.me>
This commit is contained in:
DaniPopes
2023-09-28 17:55:39 +02:00
committed by GitHub
parent 3ef0364e42
commit 5f9a917fb1
348 changed files with 3593 additions and 7066 deletions

View File

@ -13,15 +13,15 @@ Ethereum network discovery
[dependencies]
# reth
reth-primitives.workspace = true
reth-rlp.workspace = true
reth-rlp-derive = { path = "../../rlp/rlp-derive" }
reth-net-common = { path = "../common" }
reth-net-nat = { path = "../nat" }
# ethereum
alloy-rlp = { workspace = true, features = ["derive"] }
discv5.workspace = true
secp256k1 = { workspace = true, features = ["global-context", "rand-std", "recovery", "serde"] }
enr = { workspace = true, default-features = false, features = ["rust-secp256k1"] }
rlp = "0.5" # needed for enr
# async/futures
tokio = { workspace = true, features = ["io-util", "net", "time"] }
@ -31,7 +31,6 @@ tokio-stream.workspace = true
tracing.workspace = true
thiserror.workspace = true
parking_lot.workspace = true
hex = "0.4"
rand = { workspace = true, optional = true }
generic-array = "0.14"
serde = { workspace = true, optional = true }

View File

@ -3,13 +3,13 @@
//! This basis of this file has been taken from the discv5 codebase:
//! <https://github.com/sigp/discv5>
use alloy_rlp::Encodable;
use reth_net_common::ban_list::BanList;
use reth_net_nat::{NatResolver, ResolveNatInterval};
use reth_primitives::{
bytes::{Bytes, BytesMut},
NodeRecord,
};
use reth_rlp::Encodable;
use std::{
collections::{HashMap, HashSet},
time::Duration,

View File

@ -7,7 +7,7 @@ use tokio::sync::{mpsc::error::SendError, oneshot::error::RecvError};
#[allow(missing_docs)]
pub enum DecodePacketError {
#[error("Failed to rlp decode: {0:?}")]
Rlp(#[from] reth_rlp::DecodeError),
Rlp(#[from] alloy_rlp::Error),
#[error("Received packet len too short.")]
PacketTooShort,
#[error("Hash of the header not equals to the hash of the data.")]

View File

@ -29,6 +29,7 @@ use crate::{
error::{DecodePacketError, Discv4Error},
proto::{FindNode, Message, Neighbours, Packet, Ping, Pong},
};
use alloy_rlp::{RlpDecodable, RlpEncodable};
use discv5::{
kbucket,
kbucket::{
@ -42,9 +43,8 @@ use parking_lot::Mutex;
use proto::{EnrRequest, EnrResponse, EnrWrapper};
use reth_primitives::{
bytes::{Bytes, BytesMut},
ForkId, PeerId, H256,
hex, ForkId, PeerId, B256,
};
use reth_rlp::{RlpDecodable, RlpEncodable};
use secp256k1::SecretKey;
use std::{
cell::RefCell,
@ -352,7 +352,7 @@ impl Discv4 {
/// Sets the pair in the EIP-868 [`Enr`] of the node.
///
/// If the key already exists, this will update it.
pub fn set_eip868_rlp(&self, key: Vec<u8>, value: impl reth_rlp::Encodable) {
pub fn set_eip868_rlp(&self, key: Vec<u8>, value: impl alloy_rlp::Encodable) {
let mut buf = BytesMut::new();
value.encode(&mut buf);
self.set_eip868_rlp_pair(key, buf.freeze())
@ -929,7 +929,7 @@ impl Discv4Service {
}
/// Encodes the packet, sends it and returns the hash.
pub(crate) fn send_packet(&mut self, msg: Message, to: SocketAddr) -> H256 {
pub(crate) fn send_packet(&mut self, msg: Message, to: SocketAddr) -> B256 {
let (payload, hash) = msg.encode(&self.secret_key);
trace!(target : "discv4", r#type=?msg.msg_type(), ?to, ?hash, "sending packet");
let _ = self.egress.try_send((payload, to)).map_err(|err| {
@ -943,7 +943,7 @@ impl Discv4Service {
}
/// Message handler for an incoming `Ping`
fn on_ping(&mut self, ping: Ping, remote_addr: SocketAddr, remote_id: PeerId, hash: H256) {
fn on_ping(&mut self, ping: Ping, remote_addr: SocketAddr, remote_id: PeerId, hash: B256) {
if self.is_expired(ping.expire) {
// ping's expiration timestamp is in the past
return
@ -1067,7 +1067,7 @@ impl Discv4Service {
/// Sends a ping message to the node's UDP address.
///
/// Returns the echo hash of the ping message.
pub(crate) fn send_ping(&mut self, node: NodeRecord, reason: PingReason) -> H256 {
pub(crate) fn send_ping(&mut self, node: NodeRecord, reason: PingReason) -> B256 {
let remote_addr = node.udp_addr();
let id = node.id;
let ping = Ping {
@ -1200,7 +1200,7 @@ impl Discv4Service {
msg: EnrRequest,
remote_addr: SocketAddr,
id: PeerId,
request_hash: H256,
request_hash: B256,
) {
if !self.config.enable_eip868 || self.is_expired(msg.expire) {
return
@ -1720,7 +1720,7 @@ struct PingRequest {
// Node to which the request was sent.
node: NodeRecord,
// Hash sent in the Ping request
echo_hash: H256,
echo_hash: B256,
/// Why this ping was sent.
reason: PingReason,
}
@ -1929,7 +1929,7 @@ struct EnrRequestState {
// Timestamp when the request was sent.
sent_at: Instant,
// Hash sent in the Ping request
echo_hash: H256,
echo_hash: B256,
}
/// Stored node info.
@ -2057,9 +2057,9 @@ impl From<ForkId> for EnrForkIdEntry {
mod tests {
use super::*;
use crate::test_utils::{create_discv4, create_discv4_with_config, rng_endpoint, rng_record};
use alloy_rlp::{Decodable, Encodable};
use rand::{thread_rng, Rng};
use reth_primitives::{hex_literal::hex, mainnet_nodes, ForkHash};
use reth_rlp::{Decodable, Encodable};
use reth_primitives::{hex, mainnet_nodes, ForkHash};
use std::{future::poll_fn, net::Ipv4Addr};
#[tokio::test]
@ -2191,8 +2191,8 @@ mod tests {
enr_sq: Some(rng.gen()),
};
let id = PeerId::random();
service.on_ping(ping, addr, id, H256::random());
let id = PeerId::random_with(&mut rng);
service.on_ping(ping, addr, id, rng.gen());
let key = kad_key(id);
match service.kbuckets.entry(&key) {
@ -2223,8 +2223,8 @@ mod tests {
enr_sq: Some(rng.gen()),
};
let id = PeerId::random();
service.on_ping(ping, addr, id, H256::random());
let id = PeerId::random_with(&mut rng);
service.on_ping(ping, addr, id, rng.gen());
let key = kad_key(id);
match service.kbuckets.entry(&key) {

View File

@ -13,8 +13,8 @@ impl From<PeerId> for NodeKey {
impl From<NodeKey> for discv5::Key<NodeKey> {
fn from(value: NodeKey) -> Self {
let hash = keccak256(value.0.as_bytes());
let hash = *GenericArray::from_slice(hash.as_bytes());
let hash = keccak256(value.0.as_slice());
let hash = *GenericArray::from_slice(hash.as_slice());
discv5::Key::new_raw(value, hash)
}
}

View File

@ -3,15 +3,14 @@
#![allow(missing_docs)]
use crate::{error::DecodePacketError, EnrForkIdEntry, PeerId, MAX_PACKET_SIZE, MIN_PACKET_SIZE};
use alloy_rlp::{
length_of_length, Decodable, Encodable, Error as RlpError, Header, RlpDecodable, RlpEncodable,
};
use enr::{Enr, EnrKey};
use reth_primitives::{
bytes::{Buf, BufMut, Bytes, BytesMut},
keccak256,
rpc_utils::rlp,
ForkId, NodeRecord, H256,
keccak256, ForkId, NodeRecord, B256,
};
use reth_rlp::{length_of_length, Decodable, DecodeError, Encodable, Header};
use reth_rlp_derive::{RlpDecodable, RlpEncodable};
use secp256k1::{
ecdsa::{RecoverableSignature, RecoveryId},
SecretKey, SECP256K1,
@ -78,13 +77,13 @@ impl Message {
///
/// The datagram is `header || payload`
/// where header is `hash || signature || packet-type`
pub fn encode(&self, secret_key: &SecretKey) -> (Bytes, H256) {
pub fn encode(&self, secret_key: &SecretKey) -> (Bytes, B256) {
// allocate max packet size
let mut datagram = BytesMut::with_capacity(MAX_PACKET_SIZE);
// since signature has fixed len, we can split and fill the datagram buffer at fixed
// positions, this way we can encode the message directly in the datagram buffer
let mut sig_bytes = datagram.split_off(H256::len_bytes());
let mut sig_bytes = datagram.split_off(B256::len_bytes());
let mut payload = sig_bytes.split_off(secp256k1::constants::COMPACT_SIGNATURE_SIZE + 1);
match self {
@ -126,7 +125,7 @@ impl Message {
sig_bytes.unsplit(payload);
let hash = keccak256(&sig_bytes);
datagram.extend_from_slice(hash.as_bytes());
datagram.extend_from_slice(hash.as_slice());
datagram.unsplit(sig_bytes);
(datagram.freeze(), hash)
@ -146,7 +145,7 @@ impl Message {
// signature = sign(packet-type || packet-data)
let header_hash = keccak256(&packet[32..]);
let data_hash = H256::from_slice(&packet[..32]);
let data_hash = B256::from_slice(&packet[..32]);
if data_hash != header_hash {
return Err(DecodePacketError::HashMismatch)
}
@ -156,7 +155,7 @@ impl Message {
let recoverable_sig = RecoverableSignature::from_compact(signature, recovery_id)?;
// recover the public key
let msg = secp256k1::Message::from_slice(keccak256(&packet[97..]).as_bytes())?;
let msg = secp256k1::Message::from_slice(keccak256(&packet[97..]).as_slice())?;
let pk = SECP256K1.recover_ecdsa(&msg, &recoverable_sig)?;
let node_id = PeerId::from_slice(&pk.serialize_uncompressed()[1..]);
@ -182,7 +181,7 @@ impl Message {
pub struct Packet {
pub msg: Message,
pub node_id: PeerId,
pub hash: H256,
pub hash: B256,
}
/// Represents the `from`, `to` fields in the packets
@ -258,24 +257,24 @@ where
}
impl<K: EnrKey> Decodable for EnrWrapper<K> {
fn decode(buf: &mut &[u8]) -> Result<Self, DecodeError> {
fn decode(buf: &mut &[u8]) -> alloy_rlp::Result<Self> {
let enr = <Enr<K> as rlp::Decodable>::decode(&rlp::Rlp::new(buf))
.map_err(|e| match e {
rlp::DecoderError::RlpIsTooShort => DecodeError::InputTooShort,
rlp::DecoderError::RlpInvalidLength => DecodeError::Overflow,
rlp::DecoderError::RlpExpectedToBeList => DecodeError::UnexpectedString,
rlp::DecoderError::RlpExpectedToBeData => DecodeError::UnexpectedList,
rlp::DecoderError::RlpIsTooShort => RlpError::InputTooShort,
rlp::DecoderError::RlpInvalidLength => RlpError::Overflow,
rlp::DecoderError::RlpExpectedToBeList => RlpError::UnexpectedString,
rlp::DecoderError::RlpExpectedToBeData => RlpError::UnexpectedList,
rlp::DecoderError::RlpDataLenWithZeroPrefix |
rlp::DecoderError::RlpListLenWithZeroPrefix => DecodeError::LeadingZero,
rlp::DecoderError::RlpInvalidIndirection => DecodeError::NonCanonicalSize,
rlp::DecoderError::RlpListLenWithZeroPrefix => RlpError::LeadingZero,
rlp::DecoderError::RlpInvalidIndirection => RlpError::NonCanonicalSize,
rlp::DecoderError::RlpIncorrectListLen => {
DecodeError::Custom("incorrect list length when decoding rlp")
RlpError::Custom("incorrect list length when decoding rlp")
}
rlp::DecoderError::RlpIsTooBig => DecodeError::Custom("rlp is too big"),
rlp::DecoderError::RlpIsTooBig => RlpError::Custom("rlp is too big"),
rlp::DecoderError::RlpInconsistentLengthAndData => {
DecodeError::Custom("inconsistent length and data when decoding rlp")
RlpError::Custom("inconsistent length and data when decoding rlp")
}
rlp::DecoderError::Custom(s) => DecodeError::Custom(s),
rlp::DecoderError::Custom(s) => RlpError::Custom(s),
})
.map(EnrWrapper::new);
if enr.is_ok() {
@ -296,7 +295,7 @@ pub struct EnrRequest {
/// A [ENRResponse packet](https://github.com/ethereum/devp2p/blob/master/discv4.md#enrresponse-packet-0x06).
#[derive(Clone, Debug, Eq, PartialEq, RlpEncodable)]
pub struct EnrResponse {
pub request_hash: H256,
pub request_hash: B256,
pub enr: EnrWrapper<SecretKey>,
}
@ -313,22 +312,22 @@ impl EnrResponse {
}
impl Decodable for EnrResponse {
fn decode(buf: &mut &[u8]) -> Result<Self, DecodeError> {
fn decode(buf: &mut &[u8]) -> alloy_rlp::Result<Self> {
let b = &mut &**buf;
let rlp_head = Header::decode(b)?;
if !rlp_head.list {
return Err(DecodeError::UnexpectedString)
return Err(RlpError::UnexpectedString)
}
// let started_len = b.len();
let this = Self {
request_hash: reth_rlp::Decodable::decode(b)?,
request_hash: alloy_rlp::Decodable::decode(b)?,
enr: EnrWrapper::<SecretKey>::decode(b)?,
};
// TODO: `Decodable` can be derived once we have native reth_rlp decoding for ENR: <https://github.com/paradigmxyz/reth/issues/482>
// TODO: `Decodable` can be derived once we have native alloy_rlp decoding for ENR: <https://github.com/paradigmxyz/reth/issues/482>
// Skipping the size check here is fine since the `buf` is the UDP datagram
// let consumed = started_len - b.len();
// if consumed != rlp_head.payload_length {
// return Err(reth_rlp::DecodeError::ListLengthMismatch {
// return Err(alloy_rlp::Error::ListLengthMismatch {
// expected: rlp_head.payload_length,
// got: consumed,
// })
@ -388,11 +387,11 @@ impl Encodable for Ping {
}
impl Decodable for Ping {
fn decode(buf: &mut &[u8]) -> Result<Self, DecodeError> {
fn decode(buf: &mut &[u8]) -> alloy_rlp::Result<Self> {
let b = &mut &**buf;
let rlp_head = Header::decode(b)?;
if !rlp_head.list {
return Err(DecodeError::UnexpectedString)
return Err(RlpError::UnexpectedString)
}
let started_len = b.len();
let _version = u32::decode(b)?;
@ -410,7 +409,7 @@ impl Decodable for Ping {
let consumed = started_len - b.len();
if consumed > rlp_head.payload_length {
return Err(DecodeError::ListLengthMismatch {
return Err(RlpError::ListLengthMismatch {
expected: rlp_head.payload_length,
got: consumed,
})
@ -426,7 +425,7 @@ impl Decodable for Ping {
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Pong {
pub to: NodeEndpoint,
pub echo: H256,
pub echo: B256,
pub expire: u64,
/// Optional enr_seq for <https://eips.ethereum.org/EIPS/eip-868>
pub enr_sq: Option<u64>,
@ -437,7 +436,7 @@ impl Encodable for Pong {
#[derive(RlpEncodable)]
struct PongMessageEIP868<'a> {
to: &'a NodeEndpoint,
echo: &'a H256,
echo: &'a B256,
expire: u64,
enr_seq: u64,
}
@ -445,7 +444,7 @@ impl Encodable for Pong {
#[derive(RlpEncodable)]
struct PongMessage<'a> {
to: &'a NodeEndpoint,
echo: &'a H256,
echo: &'a B256,
expire: u64,
}
@ -459,11 +458,11 @@ impl Encodable for Pong {
}
impl Decodable for Pong {
fn decode(buf: &mut &[u8]) -> Result<Self, DecodeError> {
fn decode(buf: &mut &[u8]) -> alloy_rlp::Result<Self> {
let b = &mut &**buf;
let rlp_head = Header::decode(b)?;
if !rlp_head.list {
return Err(DecodeError::UnexpectedString)
return Err(RlpError::UnexpectedString)
}
let started_len = b.len();
let mut this = Self {
@ -480,7 +479,7 @@ impl Decodable for Pong {
let consumed = started_len - b.len();
if consumed > rlp_head.payload_length {
return Err(DecodeError::ListLengthMismatch {
return Err(RlpError::ListLengthMismatch {
expected: rlp_head.payload_length,
got: consumed,
})
@ -502,7 +501,7 @@ mod tests {
};
use enr::{EnrBuilder, EnrPublicKey};
use rand::{thread_rng, Rng, RngCore};
use reth_primitives::{hex_literal::hex, ForkHash};
use reth_primitives::{hex, ForkHash};
#[test]
fn test_endpoint_ipv_v4() {
@ -594,7 +593,7 @@ mod tests {
rng.fill_bytes(&mut ip);
let msg = Pong {
to: rng_endpoint(&mut rng),
echo: H256::random(),
echo: rng.gen(),
expire: rng.gen(),
enr_sq: None,
};
@ -615,7 +614,7 @@ mod tests {
rng.fill_bytes(&mut ip);
let msg = Pong {
to: rng_endpoint(&mut rng),
echo: H256::random(),
echo: rng.gen(),
expire: rng.gen(),
enr_sq: Some(rng.gen()),
};
@ -719,11 +718,12 @@ mod tests {
#[test]
fn encode_decode_enr_msg() {
use self::EnrWrapper;
use alloy_rlp::Decodable;
use enr::secp256k1::SecretKey;
use reth_rlp::Decodable;
use std::net::Ipv4Addr;
let key = SecretKey::new(&mut rand::rngs::OsRng);
let mut rng = rand::rngs::OsRng;
let key = SecretKey::new(&mut rng);
let ip = Ipv4Addr::new(127, 0, 0, 1);
let tcp = 3000;
@ -740,7 +740,7 @@ mod tests {
EnrWrapper::new(builder.build(&key).unwrap())
};
let enr_respone = EnrResponse { request_hash: H256::random(), enr };
let enr_respone = EnrResponse { request_hash: rng.gen(), enr };
let mut buf = Vec::new();
enr_respone.encode(&mut buf);
@ -757,8 +757,8 @@ mod tests {
#[test]
fn encode_known_rlp_enr() {
use self::EnrWrapper;
use alloy_rlp::Decodable;
use enr::{secp256k1::SecretKey, EnrPublicKey};
use reth_rlp::Decodable;
use std::net::Ipv4Addr;
let valid_record =

View File

@ -8,7 +8,7 @@ use crate::{
IngressReceiver, PeerId, SAFE_MAX_DATAGRAM_NEIGHBOUR_RECORDS,
};
use rand::{thread_rng, Rng, RngCore};
use reth_primitives::{hex_literal::hex, ForkHash, ForkId, NodeRecord, H256};
use reth_primitives::{hex, ForkHash, ForkId, NodeRecord, B256};
use secp256k1::{SecretKey, SECP256K1};
use std::{
collections::{HashMap, HashSet},
@ -113,7 +113,7 @@ impl MockDiscovery {
}
/// Encodes the packet, sends it and returns the hash.
fn send_packet(&mut self, msg: Message, to: SocketAddr) -> H256 {
fn send_packet(&mut self, msg: Message, to: SocketAddr) -> B256 {
let (payload, hash) = msg.encode(&self.secret_key);
let _ = self.egress.try_send((payload, to));
hash
@ -236,21 +236,21 @@ pub fn rng_endpoint(rng: &mut impl Rng) -> NodeEndpoint {
pub fn rng_record(rng: &mut impl RngCore) -> NodeRecord {
let NodeEndpoint { address, udp_port, tcp_port } = rng_endpoint(rng);
NodeRecord { address, tcp_port, udp_port, id: PeerId::random() }
NodeRecord { address, tcp_port, udp_port, id: rng.gen() }
}
pub fn rng_ipv6_record(rng: &mut impl RngCore) -> NodeRecord {
let mut ip = [0u8; 16];
rng.fill_bytes(&mut ip);
let address = IpAddr::V6(ip.into());
NodeRecord { address, tcp_port: rng.gen(), udp_port: rng.gen(), id: PeerId::random() }
NodeRecord { address, tcp_port: rng.gen(), udp_port: rng.gen(), id: rng.gen() }
}
pub fn rng_ipv4_record(rng: &mut impl RngCore) -> NodeRecord {
let mut ip = [0u8; 4];
rng.fill_bytes(&mut ip);
let address = IpAddr::V4(ip.into());
NodeRecord { address, tcp_port: rng.gen(), udp_port: rng.gen(), id: PeerId::random() }
NodeRecord { address, tcp_port: rng.gen(), udp_port: rng.gen(), id: rng.gen() }
}
pub fn rng_message(rng: &mut impl RngCore) -> Message {
@ -263,11 +263,11 @@ pub fn rng_message(rng: &mut impl RngCore) -> Message {
}),
2 => Message::Pong(Pong {
to: rng_endpoint(rng),
echo: H256::random(),
echo: rng.gen(),
expire: rng.gen(),
enr_sq: None,
}),
3 => Message::FindNode(FindNode { id: PeerId::random(), expire: rng.gen() }),
3 => Message::FindNode(FindNode { id: rng.gen(), expire: rng.gen() }),
4 => {
let num: usize = rng.gen_range(1..=SAFE_MAX_DATAGRAM_NEIGHBOUR_RECORDS);
Message::Neighbours(Neighbours {

View File

@ -12,9 +12,9 @@ description = "Support for EIP-1459 Node Discovery via DNS"
# reth
reth-primitives.workspace = true
reth-net-common = { path = "../common" }
reth-rlp.workspace = true
# ethereum
alloy-rlp.workspace = true
secp256k1 = { workspace = true, features = ["global-context", "rand-std", "recovery", "serde"] }
enr = { workspace = true, default-features = false, features = ["rust-secp256k1"] }

View File

@ -389,7 +389,7 @@ pub enum DnsDiscoveryEvent {
/// Converts an [Enr] into a [NodeRecord]
fn convert_enr_node_record(enr: &Enr<SecretKey>) -> Option<DnsNodeRecordUpdate> {
use reth_rlp::Decodable;
use alloy_rlp::Decodable;
let node_record = NodeRecord {
address: enr.ip4().map(IpAddr::from).or_else(|| enr.ip6().map(IpAddr::from))?,
@ -409,9 +409,9 @@ fn convert_enr_node_record(enr: &Enr<SecretKey>) -> Option<DnsNodeRecordUpdate>
mod tests {
use super::*;
use crate::tree::TreeRootEntry;
use alloy_rlp::Encodable;
use enr::{EnrBuilder, EnrKey};
use reth_primitives::{Chain, Hardfork, MAINNET};
use reth_rlp::Encodable;
use secp256k1::rand::thread_rng;
use std::{future::poll_fn, net::Ipv4Addr};
use tokio_stream::StreamExt;

View File

@ -25,7 +25,7 @@ use crate::error::{
};
use data_encoding::{BASE32_NOPAD, BASE64URL_NOPAD};
use enr::{Enr, EnrError, EnrKey, EnrKeyUnambiguous, EnrPublicKey};
use reth_primitives::{bytes::Bytes, hex};
use reth_primitives::{hex, Bytes};
use secp256k1::SecretKey;
use std::{
fmt,

View File

@ -33,7 +33,7 @@ rayon.workspace = true
thiserror.workspace = true
# optional deps for the test-utils feature
reth-rlp = { workspace = true, optional = true }
alloy-rlp = { workspace = true, optional = true }
tempfile = { version = "3.3", optional = true }
itertools = { workspace = true, optional = true }
@ -44,10 +44,10 @@ reth-tracing = { path = "../../tracing" }
assert_matches.workspace = true
tokio = { workspace = true, features = ["macros", "rt-multi-thread"] }
reth-rlp.workspace = true
alloy-rlp.workspace = true
itertools.workspace = true
tempfile = "3.3"
[features]
test-utils = ["dep:reth-rlp", "dep:tempfile", "dep:itertools"]
test-utils = ["dep:alloy-rlp", "dep:tempfile", "dep:itertools"]

View File

@ -605,7 +605,7 @@ mod tests {
use futures_util::stream::StreamExt;
use reth_db::test_utils::create_test_rw_db;
use reth_interfaces::test_utils::{generators, generators::random_block_range, TestConsensus};
use reth_primitives::{BlockBody, H256};
use reth_primitives::{BlockBody, B256};
use std::{collections::HashMap, sync::Arc};
// Check that the blocks are emitted in order of block number, not in order of
@ -642,7 +642,7 @@ mod tests {
// Generate some random blocks
let db = create_test_rw_db();
let mut rng = generators::rng();
let blocks = random_block_range(&mut rng, 0..=199, H256::zero(), 1..2);
let blocks = random_block_range(&mut rng, 0..=199, B256::ZERO, 1..2);
let headers = blocks.iter().map(|block| block.header.clone()).collect::<Vec<_>>();
let bodies = blocks

View File

@ -8,7 +8,7 @@ use reth_interfaces::{
priority::Priority,
},
};
use reth_primitives::{BlockBody, PeerId, SealedBlock, SealedHeader, WithPeerId, H256};
use reth_primitives::{BlockBody, PeerId, SealedBlock, SealedHeader, WithPeerId, B256};
use std::{
collections::VecDeque,
mem,
@ -98,14 +98,14 @@ where
}
/// Retrieve header hashes for the next request.
fn next_request(&self) -> Option<Vec<H256>> {
fn next_request(&self) -> Option<Vec<B256>> {
let mut hashes =
self.pending_headers.iter().filter(|h| !h.is_empty()).map(|h| h.hash()).peekable();
hashes.peek().is_some().then(|| hashes.collect())
}
/// Submit the request with the given priority.
fn submit_request(&mut self, req: Vec<H256>, priority: Priority) {
fn submit_request(&mut self, req: Vec<B256>, priority: Priority) {
tracing::trace!(target: "downloaders::bodies", request_len = req.len(), "Requesting bodies");
let client = Arc::clone(&self.client);
self.last_request_len = Some(req.len());
@ -254,14 +254,14 @@ mod tests {
p2p::bodies::response::BlockResponse,
test_utils::{generators, generators::random_header_range, TestConsensus},
};
use reth_primitives::H256;
use reth_primitives::B256;
use std::sync::Arc;
/// Check if future returns empty bodies without dispathing any requests.
#[tokio::test]
async fn request_returns_empty_bodies() {
let mut rng = generators::rng();
let headers = random_header_range(&mut rng, 0..20, H256::zero());
let headers = random_header_range(&mut rng, 0..20, B256::ZERO);
let client = Arc::new(TestBodiesClient::default());
let fut = BodiesRequestFuture::new(

View File

@ -2,12 +2,12 @@
//! Test helper impls for generating bodies
use reth_db::{database::Database, tables, transaction::DbTxMut, DatabaseEnv};
use reth_interfaces::{db, p2p::bodies::response::BlockResponse};
use reth_primitives::{Block, BlockBody, SealedBlock, SealedHeader, H256};
use reth_primitives::{Block, BlockBody, SealedBlock, SealedHeader, B256};
use std::collections::HashMap;
pub(crate) fn zip_blocks<'a>(
headers: impl Iterator<Item = &'a SealedHeader>,
bodies: &mut HashMap<H256, BlockBody>,
bodies: &mut HashMap<B256, BlockBody>,
) -> Vec<BlockResponse> {
headers
.into_iter()
@ -29,7 +29,7 @@ pub(crate) fn zip_blocks<'a>(
pub(crate) fn create_raw_bodies<'a>(
headers: impl Iterator<Item = &'a SealedHeader>,
bodies: &mut HashMap<H256, BlockBody>,
bodies: &mut HashMap<B256, BlockBody>,
) -> Vec<Block> {
headers
.into_iter()

View File

@ -18,7 +18,7 @@ use reth_interfaces::{
},
};
use reth_primitives::{
BlockHashOrNumber, BlockNumber, Header, HeadersDirection, PeerId, SealedHeader, H256,
BlockHashOrNumber, BlockNumber, Header, HeadersDirection, PeerId, SealedHeader, B256,
};
use reth_tasks::{TaskSpawner, TokioTaskExecutor};
use std::{
@ -989,13 +989,13 @@ impl std::error::Error for HeadersResponseError {}
#[derive(Clone, Debug)]
pub enum SyncTargetBlock {
/// Block hash of the targeted block
Hash(H256),
Hash(B256),
/// Block number of the targeted block
Number(u64),
/// Both the block hash and number of the targeted block
HashAndNumber {
/// Block hash of the targeted block
hash: H256,
hash: B256,
/// Block number of the targeted block
number: u64,
},
@ -1003,7 +1003,7 @@ pub enum SyncTargetBlock {
impl SyncTargetBlock {
/// Create new instance from hash.
fn from_hash(hash: H256) -> Self {
fn from_hash(hash: B256) -> Self {
Self::Hash(hash)
}
@ -1013,7 +1013,7 @@ impl SyncTargetBlock {
}
/// Set the hash for the sync target.
fn with_hash(self, hash: H256) -> Self {
fn with_hash(self, hash: B256) -> Self {
match self {
Self::Hash(_) => Self::Hash(hash),
Self::Number(number) => Self::HashAndNumber { hash, number },
@ -1054,7 +1054,7 @@ impl SyncTargetBlock {
}
/// Return the hash of the target block, if it is set.
fn hash(&self) -> Option<H256> {
fn hash(&self) -> Option<B256> {
match self {
Self::Hash(hash) => Some(*hash),
Self::Number(_) => None,
@ -1235,7 +1235,7 @@ mod tests {
let fixtures = vec![
Fixture {
sync_target_block: SyncTargetBlock::Hash(H256::random()),
sync_target_block: SyncTargetBlock::Hash(B256::random()),
// Hash maps to None here, all other variants map to Some
sync_target_option: None,
replace_number: 1,
@ -1251,7 +1251,7 @@ mod tests {
},
Fixture {
sync_target_block: SyncTargetBlock::HashAndNumber {
hash: H256::random(),
hash: B256::random(),
number: 1,
},
sync_target_option: Some(1),
@ -1284,16 +1284,16 @@ mod tests {
let mut downloader = ReverseHeadersDownloaderBuilder::default()
.build(Arc::clone(&client), Arc::new(TestConsensus::default()));
downloader.update_local_head(genesis);
downloader.update_sync_target(SyncTarget::Tip(H256::random()));
downloader.update_sync_target(SyncTarget::Tip(B256::random()));
downloader.sync_target_request.take();
let target = SyncTarget::Tip(H256::random());
let target = SyncTarget::Tip(B256::random());
downloader.update_sync_target(target);
assert!(downloader.sync_target_request.is_some());
downloader.sync_target_request.take();
let target = SyncTarget::Gap(Header::default().seal(H256::random()));
let target = SyncTarget::Gap(Header::default().seal(B256::random()));
downloader.update_sync_target(target);
assert!(downloader.sync_target_request.is_none());
assert_matches!(
@ -1312,12 +1312,12 @@ mod tests {
let mut downloader = ReverseHeadersDownloaderBuilder::default()
.build(Arc::clone(&client), Arc::new(TestConsensus::default()));
downloader.update_local_head(header.clone());
downloader.update_sync_target(SyncTarget::Tip(H256::random()));
downloader.update_sync_target(SyncTarget::Tip(B256::random()));
downloader.queued_validated_headers.push(header.clone());
let mut next = header.as_ref().clone();
next.number += 1;
downloader.update_local_head(next.seal(H256::random()));
downloader.update_local_head(next.seal(B256::random()));
assert!(downloader.queued_validated_headers.is_empty());
}
@ -1353,7 +1353,7 @@ mod tests {
.request_limit(batch_size)
.build(Arc::clone(&client), Arc::new(TestConsensus::default()));
downloader.update_local_head(genesis);
downloader.update_sync_target(SyncTarget::Tip(H256::random()));
downloader.update_sync_target(SyncTarget::Tip(B256::random()));
downloader.next_request_block_number = start;

View File

@ -3,7 +3,7 @@ use reth_interfaces::p2p::{
download::DownloadClient,
priority::Priority,
};
use reth_primitives::{BlockBody, PeerId, H256};
use reth_primitives::{BlockBody, PeerId, B256};
use std::{
collections::HashMap,
fmt::Debug,
@ -18,14 +18,14 @@ use tokio::sync::Mutex;
/// A [BodiesClient] for testing.
#[derive(Debug, Default)]
pub struct TestBodiesClient {
bodies: Arc<Mutex<HashMap<H256, BlockBody>>>,
bodies: Arc<Mutex<HashMap<B256, BlockBody>>>,
should_delay: bool,
max_batch_size: Option<usize>,
times_requested: AtomicU64,
}
impl TestBodiesClient {
pub(crate) fn with_bodies(mut self, bodies: HashMap<H256, BlockBody>) -> Self {
pub(crate) fn with_bodies(mut self, bodies: HashMap<B256, BlockBody>) -> Self {
self.bodies = Arc::new(Mutex::new(bodies));
self
}
@ -60,7 +60,7 @@ impl BodiesClient for TestBodiesClient {
fn get_block_bodies_with_priority(
&self,
hashes: Vec<H256>,
hashes: Vec<B256>,
_priority: Priority,
) -> Self::Output {
let should_delay = self.should_delay;
@ -71,7 +71,7 @@ impl BodiesClient for TestBodiesClient {
Box::pin(async move {
if should_delay {
tokio::time::sleep(Duration::from_millis(hashes[0].to_low_u64_be() % 100)).await;
tokio::time::sleep(Duration::from_millis((hashes[0][0] % 100) as u64)).await;
}
let bodies = &mut *bodies.lock().await;

View File

@ -1,4 +1,5 @@
use super::file_codec::BlockFileCodec;
use alloy_rlp::{Decodable, Header as RlpHeader};
use itertools::Either;
use reth_interfaces::{
p2p::{
@ -12,9 +13,8 @@ use reth_interfaces::{
};
use reth_primitives::{
Block, BlockBody, BlockHash, BlockHashOrNumber, BlockNumber, Header, HeadersDirection, PeerId,
H256,
B256,
};
use reth_rlp::{Decodable, Header as RlpHeader};
use std::{
collections::HashMap,
iter::zip,
@ -65,7 +65,7 @@ pub enum FileClientError {
/// An error occurred when decoding blocks, headers, or rlp headers from the file.
#[error(transparent)]
Rlp(#[from] reth_rlp::DecodeError),
Rlp(#[from] alloy_rlp::Error),
}
impl FileClient {
@ -115,7 +115,7 @@ impl FileClient {
}
/// Get the tip hash of the chain.
pub fn tip(&self) -> Option<H256> {
pub fn tip(&self) -> Option<B256> {
self.headers.get(&(self.headers.len() as u64)).map(|h| h.hash_slow())
}
@ -213,7 +213,7 @@ impl BodiesClient for FileClient {
fn get_block_bodies_with_priority(
&self,
hashes: Vec<H256>,
hashes: Vec<B256>,
_priority: Priority,
) -> Self::Output {
// this just searches the buffer, and fails if it can't find the block
@ -255,6 +255,7 @@ mod tests {
headers::{reverse_headers::ReverseHeadersDownloaderBuilder, test_utils::child_header},
test_utils::{generate_bodies, generate_bodies_file},
};
use alloy_rlp::Encodable;
use assert_matches::assert_matches;
use futures::SinkExt;
use futures_util::stream::StreamExt;
@ -267,7 +268,6 @@ mod tests {
test_utils::TestConsensus,
};
use reth_primitives::SealedHeader;
use reth_rlp::Encodable;
use std::{
io::{Read, Seek, SeekFrom, Write},
sync::Arc,

View File

@ -1,17 +1,17 @@
//! Codec for reading raw block bodies from a file.
use super::FileClientError;
use alloy_rlp::{Decodable, Encodable};
use reth_primitives::{
bytes::{Buf, BytesMut},
Block,
};
use reth_rlp::{Decodable, Encodable};
use tokio_util::codec::{Decoder, Encoder};
/// Codec for reading raw block bodies from a file.
///
/// If using with [`FramedRead`](tokio_util::codec::FramedRead), the user should make sure the
/// framed reader has capacity for the entire block file. Otherwise, the decoder will return
/// [`InputTooShort`](reth_rlp::DecodeError::InputTooShort), because RLP headers can only be
/// [`InputTooShort`](alloy_rlp::Error::InputTooShort), because RLP headers can only be
/// decoded if the internal buffer is large enough to contain the entire block body.
///
/// Without ensuring the framed reader has capacity for the entire file, a block body is likely to

View File

@ -3,7 +3,7 @@
use crate::bodies::test_utils::create_raw_bodies;
use futures::SinkExt;
use reth_interfaces::test_utils::generators::random_block_range;
use reth_primitives::{BlockBody, SealedHeader, H256};
use reth_primitives::{BlockBody, SealedHeader, B256};
use std::{collections::HashMap, io::SeekFrom, ops::RangeInclusive};
use tokio::{
fs::File,
@ -26,9 +26,9 @@ pub(crate) const TEST_SCOPE: &str = "downloaders.test";
/// Generate a set of bodies and their corresponding block hashes
pub(crate) fn generate_bodies(
range: RangeInclusive<u64>,
) -> (Vec<SealedHeader>, HashMap<H256, BlockBody>) {
) -> (Vec<SealedHeader>, HashMap<B256, BlockBody>) {
let mut rng = generators::rng();
let blocks = random_block_range(&mut rng, range, H256::zero(), 0..2);
let blocks = random_block_range(&mut rng, range, B256::ZERO, 0..2);
let headers = blocks.iter().map(|block| block.header.clone()).collect();
let bodies = blocks
@ -52,7 +52,7 @@ pub(crate) fn generate_bodies(
/// bodies and corresponding block hashes
pub(crate) async fn generate_bodies_file(
rng: RangeInclusive<u64>,
) -> (tokio::fs::File, Vec<SealedHeader>, HashMap<H256, BlockBody>) {
) -> (tokio::fs::File, Vec<SealedHeader>, HashMap<B256, BlockBody>) {
let (headers, mut bodies) = generate_bodies(0..=19);
let raw_block_bodies = create_raw_bodies(headers.clone().iter(), &mut bodies.clone());

View File

@ -8,10 +8,10 @@ homepage.workspace = true
repository.workspace = true
[dependencies]
reth-rlp = { workspace = true, features = ["derive", "ethereum-types", "std"] }
reth-primitives.workspace = true
reth-net-common = { path = "../common" }
alloy-rlp = { workspace = true, features = ["derive"] }
futures.workspace = true
thiserror.workspace = true
tokio = { workspace = true, features = ["full"] }
@ -38,6 +38,3 @@ aes = "0.8.1"
hmac = "0.12.1"
block-padding = "0.3.2"
cipher = { version = "0.4.3", features = ["block-padding"] }
[dev-dependencies]
hex-literal.workspace = true

View File

@ -6,6 +6,7 @@ use crate::{
ECIESError,
};
use aes::{cipher::StreamCipher, Aes128, Aes256};
use alloy_rlp::{Encodable, Rlp, RlpEncodable, RlpMaxEncodedLen};
use byteorder::{BigEndian, ByteOrder, ReadBytesExt};
use ctr::Ctr64BE;
use digest::{crypto_common::KeyIvInit, Digest};
@ -13,9 +14,8 @@ use educe::Educe;
use rand::{thread_rng, Rng};
use reth_primitives::{
bytes::{BufMut, Bytes, BytesMut},
H128, H256, H512 as PeerId,
B128, B256, B512 as PeerId,
};
use reth_rlp::{Encodable, Rlp, RlpEncodable, RlpMaxEncodedLen};
use secp256k1::{
ecdsa::{RecoverableSignature, RecoveryId},
PublicKey, SecretKey, SECP256K1,
@ -31,12 +31,12 @@ const PROTOCOL_VERSION: usize = 4;
///
/// This uses the given remote public key and local (ephemeral) secret key to [compute a shared
/// secp256k1 point](secp256k1::ecdh::shared_secret_point) and slices off the y coordinate from the
/// returned pair, returning only the bytes of the x coordinate as a [`H256`].
fn ecdh_x(public_key: &PublicKey, secret_key: &SecretKey) -> H256 {
H256::from_slice(&secp256k1::ecdh::shared_secret_point(public_key, secret_key)[..32])
/// returned pair, returning only the bytes of the x coordinate as a [`B256`].
fn ecdh_x(public_key: &PublicKey, secret_key: &SecretKey) -> B256 {
B256::from_slice(&secp256k1::ecdh::shared_secret_point(public_key, secret_key)[..32])
}
fn kdf(secret: H256, s1: &[u8], dest: &mut [u8]) {
fn kdf(secret: B256, s1: &[u8], dest: &mut [u8]) {
// SEC/ISO/Shoup specify counter size SHOULD be equivalent
// to size of hash output, however, it also notes that
// the 4 bytes is okay. NIST specifies 4 bytes.
@ -46,7 +46,7 @@ fn kdf(secret: H256, s1: &[u8], dest: &mut [u8]) {
let mut hasher = Sha256::default();
let ctrs = [(ctr >> 24) as u8, (ctr >> 16) as u8, (ctr >> 8) as u8, ctr as u8];
hasher.update(ctrs);
hasher.update(secret.as_bytes());
hasher.update(secret.as_slice());
hasher.update(s1);
let d = hasher.finalize();
dest[written..(written + 32)].copy_from_slice(&d);
@ -68,11 +68,11 @@ pub struct ECIES {
#[educe(Debug(ignore))]
ephemeral_secret_key: SecretKey,
ephemeral_public_key: PublicKey,
ephemeral_shared_secret: Option<H256>,
ephemeral_shared_secret: Option<B256>,
remote_ephemeral_public_key: Option<PublicKey>,
nonce: H256,
remote_nonce: Option<H256>,
nonce: B256,
remote_nonce: Option<B256>,
#[educe(Debug(ignore))]
ingress_aes: Option<Ctr64BE<Aes256>>,
@ -100,7 +100,7 @@ impl ECIES {
fn new_static_client(
secret_key: SecretKey,
remote_id: PeerId,
nonce: H256,
nonce: B256,
ephemeral_secret_key: SecretKey,
) -> Result<Self, ECIESError> {
let public_key = PublicKey::from_secret_key(SECP256K1, &secret_key);
@ -133,9 +133,9 @@ impl ECIES {
/// Create a new ECIES client with the given static secret key and remote peer ID.
pub fn new_client(secret_key: SecretKey, remote_id: PeerId) -> Result<Self, ECIESError> {
let nonce = H256::random();
let ephemeral_secret_key = SecretKey::new(&mut secp256k1::rand::thread_rng());
let mut rng = thread_rng();
let nonce = rng.gen();
let ephemeral_secret_key = SecretKey::new(&mut rng);
Self::new_static_client(secret_key, remote_id, nonce, ephemeral_secret_key)
}
@ -143,7 +143,7 @@ impl ECIES {
/// key.
pub fn new_static_server(
secret_key: SecretKey,
nonce: H256,
nonce: B256,
ephemeral_secret_key: SecretKey,
) -> Result<Self, ECIESError> {
let public_key = PublicKey::from_secret_key(SECP256K1, &secret_key);
@ -175,9 +175,9 @@ impl ECIES {
/// Create a new ECIES server with the given static secret key.
pub fn new_server(secret_key: SecretKey) -> Result<Self, ECIESError> {
let nonce = H256::random();
let ephemeral_secret_key = SecretKey::new(&mut secp256k1::rand::thread_rng());
let mut rng = thread_rng();
let nonce = rng.gen();
let ephemeral_secret_key = SecretKey::new(&mut rng);
Self::new_static_server(secret_key, nonce, ephemeral_secret_key)
}
@ -187,9 +187,11 @@ impl ECIES {
}
fn encrypt_message(&self, data: &[u8], out: &mut BytesMut) {
let mut rng = thread_rng();
out.reserve(secp256k1::constants::UNCOMPRESSED_PUBLIC_KEY_SIZE + 16 + data.len() + 32);
let secret_key = SecretKey::new(&mut secp256k1::rand::thread_rng());
let secret_key = SecretKey::new(&mut rng);
out.extend_from_slice(
&PublicKey::from_secret_key(SECP256K1, &secret_key).serialize_uncompressed(),
);
@ -198,11 +200,11 @@ impl ECIES {
let mut key = [0u8; 32];
kdf(x, &[], &mut key);
let enc_key = H128::from_slice(&key[..16]);
let enc_key = B128::from_slice(&key[..16]);
let mac_key = sha256(&key[16..32]);
let iv = H128::random();
let mut encryptor = Ctr64BE::<Aes128>::new(enc_key.as_ref().into(), iv.as_ref().into());
let iv: B128 = rng.gen();
let mut encryptor = Ctr64BE::<Aes128>::new((&enc_key.0).into(), (&iv.0).into());
let mut encrypted = data.to_vec();
encryptor.apply_keystream(&mut encrypted);
@ -210,9 +212,9 @@ impl ECIES {
let total_size: u16 = u16::try_from(65 + 16 + data.len() + 32).unwrap();
let tag =
hmac_sha256(mac_key.as_ref(), &[iv.as_bytes(), &encrypted], &total_size.to_be_bytes());
hmac_sha256(mac_key.as_ref(), &[iv.as_slice(), &encrypted], &total_size.to_be_bytes());
out.extend_from_slice(iv.as_bytes());
out.extend_from_slice(iv.as_slice());
out.extend_from_slice(&encrypted);
out.extend_from_slice(tag.as_ref());
}
@ -223,12 +225,12 @@ impl ECIES {
let public_key = PublicKey::from_slice(pubkey_bytes)?;
let (data_iv, tag_bytes) = split_at_mut(encrypted, encrypted.len() - 32)?;
let (iv, encrypted_data) = split_at_mut(data_iv, 16)?;
let tag = H256::from_slice(tag_bytes);
let tag = B256::from_slice(tag_bytes);
let x = ecdh_x(&public_key, &self.secret_key);
let mut key = [0u8; 32];
kdf(x, &[], &mut key);
let enc_key = H128::from_slice(&key[..16]);
let enc_key = B128::from_slice(&key[..16]);
let mac_key = sha256(&key[16..32]);
let check_tag = hmac_sha256(mac_key.as_ref(), &[iv, encrypted_data], auth_data);
@ -238,7 +240,7 @@ impl ECIES {
let decrypted_data = encrypted_data;
let mut decryptor = Ctr64BE::<Aes128>::new(enc_key.as_ref().into(), (*iv).into());
let mut decryptor = Ctr64BE::<Aes128>::new((&enc_key.0).into(), (*iv).into());
decryptor.apply_keystream(decrypted_data);
Ok(decrypted_data)
@ -249,7 +251,7 @@ impl ECIES {
let msg = x ^ self.nonce;
let (rec_id, sig) = SECP256K1
.sign_ecdsa_recoverable(
&secp256k1::Message::from_slice(msg.as_bytes()).unwrap(),
&secp256k1::Message::from_slice(msg.as_slice()).unwrap(),
&self.ephemeral_secret_key,
)
.serialize_compact();
@ -264,7 +266,7 @@ impl ECIES {
struct S<'a> {
sig_bytes: &'a [u8; 65],
id: &'a PeerId,
nonce: &'a H256,
nonce: &'a B256,
protocol_version: u8,
}
@ -346,11 +348,11 @@ impl ECIES {
#[derive(RlpEncodable, RlpMaxEncodedLen)]
struct S {
id: PeerId,
nonce: H256,
nonce: B256,
protocol_version: u8,
}
reth_rlp::encode_fixed_size(&S {
alloy_rlp::encode_fixed_size(&S {
id: pk2id(&self.ephemeral_public_key),
nonce: self.nonce,
protocol_version: PROTOCOL_VERSION as u8,
@ -425,32 +427,30 @@ impl ECIES {
} {
hasher.update(el);
}
let h_nonce = H256::from(hasher.finalize().as_ref());
let h_nonce = B256::from(hasher.finalize().as_ref());
let iv = H128::default();
let shared_secret: H256 = {
let iv = B128::default();
let shared_secret: B256 = {
let mut hasher = Keccak256::new();
hasher.update(self.ephemeral_shared_secret.unwrap().0.as_ref());
hasher.update(h_nonce.0.as_ref());
H256::from(hasher.finalize().as_ref())
B256::from(hasher.finalize().as_ref())
};
let aes_secret: H256 = {
let aes_secret: B256 = {
let mut hasher = Keccak256::new();
hasher.update(self.ephemeral_shared_secret.unwrap().0.as_ref());
hasher.update(shared_secret.0.as_ref());
H256::from(hasher.finalize().as_ref())
B256::from(hasher.finalize().as_ref())
};
self.ingress_aes =
Some(Ctr64BE::<Aes256>::new(aes_secret.0.as_ref().into(), iv.as_ref().into()));
self.egress_aes =
Some(Ctr64BE::<Aes256>::new(aes_secret.0.as_ref().into(), iv.as_ref().into()));
self.ingress_aes = Some(Ctr64BE::<Aes256>::new((&aes_secret.0).into(), (&iv.0).into()));
self.egress_aes = Some(Ctr64BE::<Aes256>::new((&aes_secret.0).into(), (&iv.0).into()));
let mac_secret: H256 = {
let mac_secret: B256 = {
let mut hasher = Keccak256::new();
hasher.update(self.ephemeral_shared_secret.unwrap().0.as_ref());
hasher.update(aes_secret.0.as_ref());
H256::from(hasher.finalize().as_ref())
B256::from(hasher.finalize().as_ref())
};
self.ingress_mac = Some(MAC::new(mac_secret));
self.ingress_mac.as_mut().unwrap().update((mac_secret ^ self.nonce).as_ref());
@ -484,13 +484,13 @@ impl ECIES {
out.reserve(ECIES::header_len());
out.extend_from_slice(&header);
out.extend_from_slice(tag.as_bytes());
out.extend_from_slice(tag.as_slice());
}
pub fn read_header(&mut self, data: &mut [u8]) -> Result<usize, ECIESError> {
let (header_bytes, mac_bytes) = split_at_mut(data, 16)?;
let header = HeaderBytes::from_mut_slice(header_bytes);
let mac = H128::from_slice(&mac_bytes[..16]);
let mac = B128::from_slice(&mac_bytes[..16]);
self.ingress_mac.as_mut().unwrap().update_header(header);
let check_mac = self.ingress_mac.as_mut().unwrap().digest();
@ -538,12 +538,12 @@ impl ECIES {
self.egress_mac.as_mut().unwrap().update_body(encrypted);
let tag = self.egress_mac.as_mut().unwrap().digest();
out.extend_from_slice(tag.as_bytes());
out.extend_from_slice(tag.as_slice());
}
pub fn read_body<'a>(&mut self, data: &'a mut [u8]) -> Result<&'a mut [u8], ECIESError> {
let (body, mac_bytes) = split_at_mut(data, data.len() - 16)?;
let mac = H128::from_slice(mac_bytes);
let mac = B128::from_slice(mac_bytes);
self.ingress_mac.as_mut().unwrap().update_body(body);
let check_mac = self.ingress_mac.as_mut().unwrap().digest();
if check_mac != mac {
@ -561,7 +561,7 @@ impl ECIES {
#[cfg(test)]
mod tests {
use super::*;
use hex_literal::hex;
use reth_primitives::{b256, hex};
#[test]
fn ecdh() {
@ -573,15 +573,16 @@ mod tests {
assert_eq!(
ecdh_x(&remote_public_key, &our_secret_key),
hex!("821ce7e01ea11b111a52b2dafae8a3031a372d83bdf1a78109fa0783c2b9d5d3").into()
hex!("821ce7e01ea11b111a52b2dafae8a3031a372d83bdf1a78109fa0783c2b9d5d3")
)
}
#[test]
fn communicate() {
let server_secret_key = SecretKey::new(&mut secp256k1::rand::thread_rng());
let mut rng = thread_rng();
let server_secret_key = SecretKey::new(&mut rng);
let server_public_key = PublicKey::from_secret_key(SECP256K1, &server_secret_key);
let client_secret_key = SecretKey::new(&mut secp256k1::rand::thread_rng());
let client_secret_key = SecretKey::new(&mut rng);
let mut server_ecies = ECIES::new_server(server_secret_key).unwrap();
let mut client_ecies =
@ -667,7 +668,7 @@ mod tests {
.unwrap();
let client_nonce =
H256(hex!("7e968bba13b6c50e2c4cd7f241cc0d64d1ac25c7f5952df231ac6a2bda8ee5d6"));
b256!("7e968bba13b6c50e2c4cd7f241cc0d64d1ac25c7f5952df231ac6a2bda8ee5d6");
let server_id = pk2id(&PublicKey::from_secret_key(SECP256K1, &eip8_test_server_key()));
@ -682,7 +683,7 @@ mod tests {
.unwrap();
let server_nonce =
H256(hex!("559aead08264d5795d3909718cdd05abd49572e84fe55590eef31a88a08fdffd"));
b256!("559aead08264d5795d3909718cdd05abd49572e84fe55590eef31a88a08fdffd");
ECIES::new_static_server(eip8_test_server_key(), server_nonce, server_ephemeral_key)
.unwrap()

View File

@ -1,5 +1,5 @@
use crate::{algorithm::ECIES, ECIESError, EgressECIESValue, IngressECIESValue};
use reth_primitives::{bytes::BytesMut, H512 as PeerId};
use reth_primitives::{bytes::BytesMut, B512 as PeerId};
use secp256k1::SecretKey;
use std::{fmt::Debug, io};
use tokio_util::codec::{Decoder, Encoder};

View File

@ -63,7 +63,7 @@ pub enum ECIESErrorImpl {
Secp256k1(secp256k1::Error),
/// Error when decoding RLP data
#[error(transparent)]
RLPDecoding(reth_rlp::DecodeError),
RLPDecoding(alloy_rlp::Error),
/// Error when converting to integer
#[error(transparent)]
FromInt(std::num::TryFromIntError),
@ -111,8 +111,8 @@ impl From<secp256k1::Error> for ECIESError {
}
}
impl From<reth_rlp::DecodeError> for ECIESError {
fn from(source: reth_rlp::DecodeError) -> Self {
impl From<alloy_rlp::Error> for ECIESError {
fn from(source: alloy_rlp::Error) -> Self {
ECIESErrorImpl::RLPDecoding(source).into()
}
}

View File

@ -21,7 +21,7 @@ mod codec;
use reth_primitives::{
bytes::{Bytes, BytesMut},
H512 as PeerId,
B512 as PeerId,
};
/// Raw egress values for an ECIES protocol

View File

@ -4,7 +4,7 @@ use block_padding::NoPadding;
use cipher::BlockEncrypt;
use digest::KeyInit;
use generic_array::GenericArray;
use reth_primitives::{H128, H256};
use reth_primitives::{B128, B256};
use sha3::{Digest, Keccak256};
use typenum::U16;
@ -19,13 +19,13 @@ pub type HeaderBytes = GenericArray<u8, U16>;
/// and is not defined as a general MAC.
#[derive(Debug)]
pub struct MAC {
secret: H256,
secret: B256,
hasher: Keccak256,
}
impl MAC {
/// Initialize the MAC with the given secret
pub fn new(secret: H256) -> Self {
pub fn new(secret: B256) -> Self {
Self { secret, hasher: Keccak256::new() }
}
@ -37,9 +37,9 @@ impl MAC {
/// Accumulate the given [`HeaderBytes`] into the MAC's internal state.
pub fn update_header(&mut self, data: &HeaderBytes) {
let aes = Aes256Enc::new_from_slice(self.secret.as_ref()).unwrap();
let mut encrypted = self.digest().to_fixed_bytes();
let mut encrypted = self.digest().0;
aes.encrypt_padded::<NoPadding>(&mut encrypted, H128::len_bytes()).unwrap();
aes.encrypt_padded::<NoPadding>(&mut encrypted, B128::len_bytes()).unwrap();
for i in 0..data.len() {
encrypted[i] ^= data[i];
}
@ -51,9 +51,9 @@ impl MAC {
self.hasher.update(data);
let prev = self.digest();
let aes = Aes256Enc::new_from_slice(self.secret.as_ref()).unwrap();
let mut encrypted = self.digest().to_fixed_bytes();
let mut encrypted = self.digest().0;
aes.encrypt_padded::<NoPadding>(&mut encrypted, H128::len_bytes()).unwrap();
aes.encrypt_padded::<NoPadding>(&mut encrypted, B128::len_bytes()).unwrap();
for i in 0..16 {
encrypted[i] ^= prev[i];
}
@ -62,7 +62,7 @@ impl MAC {
/// Produce a digest by finalizing the internal keccak256 hasher and returning the first 128
/// bits.
pub fn digest(&self) -> H128 {
H128::from_slice(&self.hasher.clone().finalize()[..16])
pub fn digest(&self) -> B128 {
B128::from_slice(&self.hasher.clone().finalize()[..16])
}
}

View File

@ -6,7 +6,7 @@ use futures::{ready, Sink, SinkExt};
use reth_net_common::stream::HasRemoteAddr;
use reth_primitives::{
bytes::{Bytes, BytesMut},
H512 as PeerId,
B512 as PeerId,
};
use secp256k1::SecretKey;
use std::{

View File

@ -1,25 +1,25 @@
//! Utility functions for hashing and encoding.
use hmac::{Hmac, Mac};
use reth_primitives::{H256, H512 as PeerId};
use reth_primitives::{B256, B512 as PeerId};
use secp256k1::PublicKey;
use sha2::{Digest, Sha256};
/// Hashes the input data with SHA256.
pub(crate) fn sha256(data: &[u8]) -> H256 {
H256::from(Sha256::digest(data).as_ref())
pub(crate) fn sha256(data: &[u8]) -> B256 {
B256::from(Sha256::digest(data).as_ref())
}
/// Produces a HMAC_SHA256 digest of the `input_data` and `auth_data` with the given `key`.
/// This is done by accumulating each slice in `input_data` into the HMAC state, then accumulating
/// the `auth_data` and returning the resulting digest.
pub(crate) fn hmac_sha256(key: &[u8], input: &[&[u8]], auth_data: &[u8]) -> H256 {
pub(crate) fn hmac_sha256(key: &[u8], input: &[&[u8]], auth_data: &[u8]) -> B256 {
let mut hmac = Hmac::<Sha256>::new_from_slice(key).unwrap();
for input in input {
hmac.update(input);
}
hmac.update(auth_data);
H256::from_slice(&hmac.finalize().into_bytes())
B256::from_slice(&hmac.finalize().into_bytes())
}
/// Converts a [secp256k1::PublicKey] to a [PeerId] by stripping the
@ -31,13 +31,13 @@ pub fn pk2id(pk: &PublicKey) -> PeerId {
/// Converts a [PeerId] to a [secp256k1::PublicKey] by prepending the [PeerId] bytes with the
/// SECP256K1_TAG_PUBKEY_UNCOMPRESSED tag.
pub(crate) fn id2pk(id: PeerId) -> Result<PublicKey, secp256k1::Error> {
// NOTE: H512 is used as a PeerId not because it represents a hash, but because 512 bits is
// NOTE: B512 is used as a PeerId not because it represents a hash, but because 512 bits is
// enough to represent an uncompressed public key.
let mut s = [0u8; 65];
// SECP256K1_TAG_PUBKEY_UNCOMPRESSED = 0x04
// see: https://github.com/bitcoin-core/secp256k1/blob/master/include/secp256k1.h#L211
s[0] = 4;
s[1..].copy_from_slice(id.as_bytes());
s[1..].copy_from_slice(id.as_slice());
PublicKey::from_slice(&s)
}

View File

@ -9,24 +9,20 @@ homepage.workspace = true
repository.workspace = true
[dependencies]
bytes.workspace = true
thiserror.workspace = true
serde = { workspace = true, optional = true }
# reth
reth-codecs = { path = "../../storage/codecs" }
reth-primitives.workspace = true
reth-ecies = { path = "../ecies" }
reth-rlp = { workspace = true, features = ["alloc", "derive", "std", "ethereum-types", "smol_str"] }
alloy-rlp = { workspace = true, features = ["derive"] }
reth-discv4 = { path = "../discv4" }
# metrics
reth-metrics.workspace = true
metrics.workspace = true
# used for Chain and builders
ethers-core = { workspace = true, default-features = false }
bytes.workspace = true
thiserror.workspace = true
serde = { workspace = true, optional = true }
tokio = { workspace = true, features = ["full"] }
tokio-util = { workspace = true, features = ["io", "codec"] }
futures.workspace = true
@ -34,7 +30,6 @@ tokio-stream.workspace = true
pin-project.workspace = true
tracing.workspace = true
snap = "1.0.5"
smol_str = "0.2"
async-trait.workspace = true
# arbitrary utils
@ -49,8 +44,6 @@ ethers-core = { workspace = true, default-features = false }
test-fuzz = "4"
tokio-util = { workspace = true, features = ["io", "codec"] }
hex-literal.workspace = true
hex = "0.4"
rand.workspace = true
secp256k1 = { workspace = true, features = ["global-context", "rand-std", "recovery"] }
@ -60,7 +53,7 @@ proptest-derive.workspace = true
[features]
default = ["serde"]
serde = ["dep:serde", "smol_str/serde"]
serde = ["dep:serde"]
arbitrary = ["reth-primitives/arbitrary", "dep:arbitrary", "dep:proptest", "dep:proptest-derive"]
[[test]]

View File

@ -4,23 +4,23 @@ use crate::{
capability::Capability, hello::HelloMessage, p2pstream::ProtocolVersion, EthVersion, Status,
};
use reth_discv4::DEFAULT_DISCOVERY_PORT;
use reth_primitives::{Chain, ForkId, PeerId, H256, U256};
use reth_primitives::{Chain, ForkId, PeerId, B256, U256};
/// Builder for [`Status`] messages.
///
/// # Example
/// ```
/// use reth_eth_wire::EthVersion;
/// use reth_primitives::{Chain, U256, H256, MAINNET_GENESIS, MAINNET, Hardfork};
/// use reth_primitives::{Chain, U256, B256, MAINNET_GENESIS, MAINNET, Hardfork};
/// use reth_eth_wire::types::Status;
///
/// // this is just an example status message!
/// let status = Status::builder()
/// .version(EthVersion::Eth66.into())
/// .chain(Chain::Named(ethers_core::types::Chain::Mainnet))
/// .chain(Chain::mainnet())
/// .total_difficulty(U256::from(100))
/// .blockhash(H256::from(MAINNET_GENESIS))
/// .genesis(H256::from(MAINNET_GENESIS))
/// .blockhash(B256::from(MAINNET_GENESIS))
/// .genesis(B256::from(MAINNET_GENESIS))
/// .forkid(Hardfork::Paris.fork_id(&MAINNET).unwrap())
/// .build();
///
@ -28,10 +28,10 @@ use reth_primitives::{Chain, ForkId, PeerId, H256, U256};
/// status,
/// Status {
/// version: EthVersion::Eth66.into(),
/// chain: Chain::Named(ethers_core::types::Chain::Mainnet),
/// chain: Chain::mainnet(),
/// total_difficulty: U256::from(100),
/// blockhash: H256::from(MAINNET_GENESIS),
/// genesis: H256::from(MAINNET_GENESIS),
/// blockhash: B256::from(MAINNET_GENESIS),
/// genesis: B256::from(MAINNET_GENESIS),
/// forkid: Hardfork::Paris.fork_id(&MAINNET).unwrap(),
/// }
/// );
@ -66,13 +66,13 @@ impl StatusBuilder {
}
/// Sets the block hash.
pub fn blockhash(mut self, blockhash: H256) -> Self {
pub fn blockhash(mut self, blockhash: B256) -> Self {
self.status.blockhash = blockhash;
self
}
/// Sets the genesis hash.
pub fn genesis(mut self, genesis: H256) -> Self {
pub fn genesis(mut self, genesis: B256) -> Self {
self.status.genesis = genesis;
self
}

View File

@ -1,10 +1,9 @@
//! All capability related types
use crate::{version::ParseVersionError, EthMessage, EthVersion};
use alloy_rlp::{Decodable, Encodable, RlpDecodable, RlpEncodable};
use reth_codecs::add_arbitrary_tests;
use reth_primitives::bytes::{BufMut, Bytes};
use reth_rlp::{Decodable, DecodeError, Encodable, RlpDecodable, RlpEncodable};
use smol_str::SmolStr;
use std::fmt;
#[cfg(feature = "serde")]
@ -43,14 +42,14 @@ pub enum CapabilityMessage {
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Capability {
/// The name of the subprotocol
pub name: SmolStr,
pub name: String,
/// The version of the subprotocol
pub version: usize,
}
impl Capability {
/// Create a new `Capability` with the given name and version.
pub fn new(name: SmolStr, version: usize) -> Self {
pub fn new(name: String, version: usize) -> Self {
Self { name, version }
}
@ -83,7 +82,7 @@ impl fmt::Display for Capability {
impl<'a> arbitrary::Arbitrary<'a> for Capability {
fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
let version = u.int_in_range(0..=32)?; // TODO: What's the max?
let name: SmolStr = String::arbitrary(u)?.into(); // TODO: what possible values?
let name = String::arbitrary(u)?; // TODO: what possible values?
Ok(Self { name, version })
}
}
@ -95,7 +94,7 @@ impl proptest::arbitrary::Arbitrary for Capability {
any_with::<String>(args) // TODO: what possible values?
.prop_flat_map(move |name| {
any_with::<usize>(()) // TODO: What's the max?
.prop_map(move |version| Capability { name: name.clone().into(), version })
.prop_map(move |version| Capability { name: name.clone(), version })
})
.boxed()
}
@ -169,7 +168,7 @@ impl Encodable for Capabilities {
}
impl Decodable for Capabilities {
fn decode(buf: &mut &[u8]) -> Result<Self, DecodeError> {
fn decode(buf: &mut &[u8]) -> alloy_rlp::Result<Self> {
let inner = Vec::<Capability>::decode(buf)?;
Ok(Self {
@ -189,7 +188,7 @@ pub enum SharedCapability {
Eth { version: EthVersion, offset: u8 },
/// An unknown capability.
UnknownCapability { name: SmolStr, version: u8, offset: u8 },
UnknownCapability { name: String, version: u8, offset: u8 },
}
impl SharedCapability {

View File

@ -1,11 +1,10 @@
//! Disconnect
use bytes::Bytes;
use alloy_rlp::{Decodable, Encodable, Error as RlpError, Header};
use futures::{Sink, SinkExt};
use reth_codecs::derive_arbitrary;
use reth_ecies::stream::ECIESStream;
use reth_primitives::bytes::{Buf, BufMut};
use reth_rlp::{Decodable, DecodeError, Encodable, Header};
use std::fmt::Display;
use thiserror::Error;
use tokio::io::AsyncWrite;
@ -120,11 +119,11 @@ impl Encodable for DisconnectReason {
/// The [`Decodable`] implementation for [`DisconnectReason`] supports either a disconnect reason
/// encoded a single byte or a RLP list containing the disconnect reason.
impl Decodable for DisconnectReason {
fn decode(buf: &mut &[u8]) -> Result<Self, DecodeError> {
fn decode(buf: &mut &[u8]) -> alloy_rlp::Result<Self> {
if buf.is_empty() {
return Err(DecodeError::InputTooShort)
return Err(RlpError::InputTooShort)
} else if buf.len() > 2 {
return Err(DecodeError::Overflow)
return Err(RlpError::Overflow)
}
if buf.len() > 1 {
@ -132,7 +131,7 @@ impl Decodable for DisconnectReason {
// buf[0] is the first (and only) element of the list.
let header = Header::decode(buf)?;
if !header.list {
return Err(DecodeError::UnexpectedString)
return Err(RlpError::UnexpectedString)
}
}
@ -143,7 +142,7 @@ impl Decodable for DisconnectReason {
Ok(DisconnectReason::DisconnectRequested)
} else {
DisconnectReason::try_from(u8::decode(buf)?)
.map_err(|_| DecodeError::Custom("unknown disconnect reason"))
.map_err(|_| RlpError::Custom("unknown disconnect reason"))
}
}
}
@ -178,7 +177,7 @@ where
}
#[async_trait::async_trait]
impl<S> CanDisconnect<Bytes> for ECIESStream<S>
impl<S> CanDisconnect<bytes::Bytes> for ECIESStream<S>
where
S: AsyncWrite + Unpin + Send,
{
@ -190,8 +189,8 @@ where
#[cfg(test)]
mod tests {
use crate::{p2pstream::P2PMessage, DisconnectReason};
use alloy_rlp::{Decodable, Encodable};
use reth_primitives::hex;
use reth_rlp::{Decodable, Encodable};
fn all_reasons() -> Vec<DisconnectReason> {
vec![

View File

@ -2,7 +2,7 @@
use crate::{
errors::P2PStreamError, version::ParseVersionError, DisconnectReason, EthMessageID, EthVersion,
};
use reth_primitives::{Chain, ValidationError, H256};
use reth_primitives::{Chain, ValidationError, B256};
use std::io;
/// Errors when sending/receiving messages
@ -50,8 +50,8 @@ impl From<io::Error> for EthStreamError {
}
}
impl From<reth_rlp::DecodeError> for EthStreamError {
fn from(err: reth_rlp::DecodeError) -> Self {
impl From<alloy_rlp::Error> for EthStreamError {
fn from(err: alloy_rlp::Error) -> Self {
P2PStreamError::from(err).into()
}
}
@ -69,7 +69,7 @@ pub enum EthHandshakeError {
#[error(transparent)]
InvalidFork(#[from] ValidationError),
#[error("mismatched genesis in Status message. expected: {expected:?}, got: {got:?}")]
MismatchedGenesis { expected: H256, got: H256 },
MismatchedGenesis { expected: B256, got: B256 },
#[error("mismatched protocol version in Status message. expected: {expected:?}, got: {got:?}")]
MismatchedProtocolVersion { expected: u8, got: u8 },
#[error("mismatched chain in Status message. expected: {expected:?}, got: {got:?}")]

View File

@ -12,7 +12,7 @@ pub enum P2PStreamError {
#[error(transparent)]
Io(#[from] io::Error),
#[error(transparent)]
Rlp(#[from] reth_rlp::DecodeError),
Rlp(#[from] alloy_rlp::Error),
#[error(transparent)]
Snap(#[from] snap::Error),
#[error(transparent)]
@ -73,7 +73,7 @@ pub enum P2PHandshakeError {
#[error("Disconnected by peer: {0}")]
Disconnected(DisconnectReason),
#[error("error decoding a message during handshake: {0}")]
DecodeError(#[from] reth_rlp::DecodeError),
DecodeError(#[from] alloy_rlp::Error),
}
/// An error that can occur when interacting with a pinger.

View File

@ -4,13 +4,13 @@ use crate::{
types::{EthMessage, ProtocolMessage, Status},
CanDisconnect, DisconnectReason, EthVersion,
};
use alloy_rlp::Encodable;
use futures::{ready, Sink, SinkExt, StreamExt};
use pin_project::pin_project;
use reth_primitives::{
bytes::{Bytes, BytesMut},
ForkFilter,
};
use reth_rlp::Encodable;
use std::{
pin::Pin,
task::{Context, Poll},
@ -322,25 +322,24 @@ mod tests {
types::{broadcast::BlockHashNumber, EthMessage, EthVersion, Status},
EthStream, PassthroughCodec,
};
use ethers_core::types::Chain;
use futures::{SinkExt, StreamExt};
use reth_discv4::DEFAULT_DISCOVERY_PORT;
use reth_ecies::{stream::ECIESStream, util::pk2id};
use reth_primitives::{ForkFilter, Head, H256, U256};
use reth_primitives::{ForkFilter, Head, NamedChain, B256, U256};
use secp256k1::{SecretKey, SECP256K1};
use tokio::net::{TcpListener, TcpStream};
use tokio_util::codec::Decoder;
#[tokio::test]
async fn can_handshake() {
let genesis = H256::random();
let genesis = B256::random();
let fork_filter = ForkFilter::new(Head::default(), genesis, 0, Vec::new());
let status = Status {
version: EthVersion::Eth67 as u8,
chain: Chain::Mainnet.into(),
chain: NamedChain::Mainnet.into(),
total_difficulty: U256::ZERO,
blockhash: H256::random(),
blockhash: B256::random(),
genesis,
// Pass the current fork id.
forkid: fork_filter.current(),
@ -380,14 +379,14 @@ mod tests {
#[tokio::test]
async fn pass_handshake_on_low_td_bitlen() {
let genesis = H256::random();
let genesis = B256::random();
let fork_filter = ForkFilter::new(Head::default(), genesis, 0, Vec::new());
let status = Status {
version: EthVersion::Eth67 as u8,
chain: Chain::Mainnet.into(),
chain: NamedChain::Mainnet.into(),
total_difficulty: U256::from(2).pow(U256::from(100)) - U256::from(1),
blockhash: H256::random(),
blockhash: B256::random(),
genesis,
// Pass the current fork id.
forkid: fork_filter.current(),
@ -427,14 +426,14 @@ mod tests {
#[tokio::test]
async fn fail_handshake_on_high_td_bitlen() {
let genesis = H256::random();
let genesis = B256::random();
let fork_filter = ForkFilter::new(Head::default(), genesis, 0, Vec::new());
let status = Status {
version: EthVersion::Eth67 as u8,
chain: Chain::Mainnet.into(),
chain: NamedChain::Mainnet.into(),
total_difficulty: U256::from(2).pow(U256::from(100)),
blockhash: H256::random(),
blockhash: B256::random(),
genesis,
// Pass the current fork id.
forkid: fork_filter.current(),
@ -485,8 +484,8 @@ mod tests {
let local_addr = listener.local_addr().unwrap();
let test_msg = EthMessage::NewBlockHashes(
vec![
BlockHashNumber { hash: H256::random(), number: 5 },
BlockHashNumber { hash: H256::random(), number: 6 },
BlockHashNumber { hash: B256::random(), number: 5 },
BlockHashNumber { hash: B256::random(), number: 6 },
]
.into(),
);
@ -520,8 +519,8 @@ mod tests {
let server_key = SecretKey::new(&mut rand::thread_rng());
let test_msg = EthMessage::NewBlockHashes(
vec![
BlockHashNumber { hash: H256::random(), number: 5 },
BlockHashNumber { hash: H256::random(), number: 6 },
BlockHashNumber { hash: B256::random(), number: 5 },
BlockHashNumber { hash: B256::random(), number: 6 },
]
.into(),
);
@ -562,20 +561,20 @@ mod tests {
let server_key = SecretKey::new(&mut rand::thread_rng());
let test_msg = EthMessage::NewBlockHashes(
vec![
BlockHashNumber { hash: H256::random(), number: 5 },
BlockHashNumber { hash: H256::random(), number: 6 },
BlockHashNumber { hash: B256::random(), number: 5 },
BlockHashNumber { hash: B256::random(), number: 6 },
]
.into(),
);
let genesis = H256::random();
let genesis = B256::random();
let fork_filter = ForkFilter::new(Head::default(), genesis, 0, Vec::new());
let status = Status {
version: EthVersion::Eth67 as u8,
chain: Chain::Mainnet.into(),
chain: NamedChain::Mainnet.into(),
total_difficulty: U256::ZERO,
blockhash: H256::random(),
blockhash: B256::random(),
genesis,
// Pass the current fork id.
forkid: fork_filter.current(),

View File

@ -1,8 +1,8 @@
use crate::{capability::Capability, EthVersion, ProtocolVersion};
use alloy_rlp::{RlpDecodable, RlpEncodable};
use reth_codecs::derive_arbitrary;
use reth_discv4::DEFAULT_DISCOVERY_PORT;
use reth_primitives::{constants::RETH_CLIENT_VERSION, PeerId};
use reth_rlp::{RlpDecodable, RlpEncodable};
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
@ -109,9 +109,9 @@ impl HelloMessageBuilder {
#[cfg(test)]
mod tests {
use alloy_rlp::{Decodable, Encodable, EMPTY_STRING_CODE};
use reth_discv4::DEFAULT_DISCOVERY_PORT;
use reth_ecies::util::pk2id;
use reth_rlp::{Decodable, Encodable, EMPTY_STRING_CODE};
use secp256k1::{SecretKey, SECP256K1};
use crate::{

View File

@ -6,6 +6,7 @@ use crate::{
pinger::{Pinger, PingerEvent},
DisconnectReason, HelloMessage,
};
use alloy_rlp::{Decodable, Encodable, Error as RlpError, EMPTY_LIST_CODE};
use futures::{Sink, SinkExt, StreamExt};
use pin_project::pin_project;
use reth_codecs::derive_arbitrary;
@ -14,7 +15,6 @@ use reth_primitives::{
bytes::{Buf, BufMut, Bytes, BytesMut},
hex,
};
use reth_rlp::{Decodable, DecodeError, Encodable, EMPTY_LIST_CODE};
use std::{
collections::{BTreeSet, HashMap, HashSet, VecDeque},
io,
@ -732,14 +732,14 @@ impl Encodable for P2PMessage {
/// The [`Decodable`] implementation for [`P2PMessage::Ping`] and [`P2PMessage::Pong`] expects a
/// snappy encoded payload, see [`Encodable`] implementation.
impl Decodable for P2PMessage {
fn decode(buf: &mut &[u8]) -> Result<Self, DecodeError> {
fn decode(buf: &mut &[u8]) -> alloy_rlp::Result<Self> {
/// Removes the snappy prefix from the Ping/Pong buffer
fn advance_snappy_ping_pong_payload(buf: &mut &[u8]) -> Result<(), DecodeError> {
fn advance_snappy_ping_pong_payload(buf: &mut &[u8]) -> alloy_rlp::Result<()> {
if buf.len() < 3 {
return Err(DecodeError::InputTooShort)
return Err(RlpError::InputTooShort)
}
if buf[..3] != [0x01, 0x00, EMPTY_LIST_CODE] {
return Err(DecodeError::Custom("expected snappy payload"))
return Err(RlpError::Custom("expected snappy payload"))
}
buf.advance(3);
Ok(())
@ -747,7 +747,7 @@ impl Decodable for P2PMessage {
let message_id = u8::decode(&mut &buf[..])?;
let id = P2PMessageID::try_from(message_id)
.or(Err(DecodeError::Custom("unknown p2p message id")))?;
.or(Err(RlpError::Custom("unknown p2p message id")))?;
buf.advance(1);
match id {
P2PMessageID::Hello => Ok(P2PMessage::Hello(HelloMessage::decode(buf)?)),
@ -828,12 +828,12 @@ impl Encodable for ProtocolVersion {
}
impl Decodable for ProtocolVersion {
fn decode(buf: &mut &[u8]) -> Result<Self, DecodeError> {
fn decode(buf: &mut &[u8]) -> alloy_rlp::Result<Self> {
let version = u8::decode(buf)?;
match version {
4 => Ok(ProtocolVersion::V4),
5 => Ok(ProtocolVersion::V5),
_ => Err(DecodeError::Custom("unknown p2p protocol version")),
_ => Err(RlpError::Custom("unknown p2p protocol version")),
}
}
}

View File

@ -1,8 +1,8 @@
//! Implements the `GetBlockHeaders`, `GetBlockBodies`, `BlockHeaders`, and `BlockBodies` message
//! types.
use alloy_rlp::{RlpDecodable, RlpDecodableWrapper, RlpEncodable, RlpEncodableWrapper};
use reth_codecs::derive_arbitrary;
use reth_primitives::{BlockBody, BlockHashOrNumber, Header, HeadersDirection, H256};
use reth_rlp::{RlpDecodable, RlpDecodableWrapper, RlpEncodable, RlpEncodableWrapper};
use reth_primitives::{BlockBody, BlockHashOrNumber, Header, HeadersDirection, B256};
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
@ -57,11 +57,11 @@ impl From<Vec<Header>> for BlockHeaders {
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct GetBlockBodies(
/// The block hashes to request bodies for.
pub Vec<H256>,
pub Vec<B256>,
);
impl From<Vec<H256>> for GetBlockBodies {
fn from(hashes: Vec<H256>) -> Self {
impl From<Vec<B256>> for GetBlockBodies {
fn from(hashes: Vec<B256>) -> Self {
GetBlockBodies(hashes)
}
}
@ -93,12 +93,11 @@ mod test {
use crate::types::{
message::RequestPair, BlockBodies, BlockHeaders, GetBlockBodies, GetBlockHeaders,
};
use hex_literal::hex;
use alloy_rlp::{Decodable, Encodable};
use reth_primitives::{
BlockHashOrNumber, Header, HeadersDirection, Signature, Transaction, TransactionKind,
hex, BlockHashOrNumber, Header, HeadersDirection, Signature, Transaction, TransactionKind,
TransactionSigned, TxLegacy, U256,
};
use reth_rlp::{Decodable, Encodable};
use std::str::FromStr;
use super::BlockBody;

View File

@ -1,11 +1,10 @@
//! Types for broadcasting new data.
use crate::{EthMessage, EthVersion};
use bytes::Bytes;
use reth_codecs::derive_arbitrary;
use reth_primitives::{Block, TransactionSigned, H256, U128};
use reth_rlp::{
use alloy_rlp::{
Decodable, Encodable, RlpDecodable, RlpDecodableWrapper, RlpEncodable, RlpEncodableWrapper,
};
use reth_codecs::derive_arbitrary;
use reth_primitives::{Block, Bytes, TransactionSigned, B256, U128};
use std::sync::Arc;
#[cfg(feature = "serde")]
@ -41,7 +40,7 @@ impl NewBlockHashes {
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct BlockHashNumber {
/// The block hash
pub hash: H256,
pub hash: B256,
/// The block number
pub number: u64,
}
@ -137,7 +136,7 @@ impl NewPooledTransactionHashes {
}
/// Returns an iterator over all transaction hashes.
pub fn iter_hashes(&self) -> impl Iterator<Item = &H256> + '_ {
pub fn iter_hashes(&self) -> impl Iterator<Item = &B256> + '_ {
match self {
NewPooledTransactionHashes::Eth66(msg) => msg.0.iter(),
NewPooledTransactionHashes::Eth68(msg) => msg.hashes.iter(),
@ -145,7 +144,7 @@ impl NewPooledTransactionHashes {
}
/// Consumes the type and returns all hashes
pub fn into_hashes(self) -> Vec<H256> {
pub fn into_hashes(self) -> Vec<B256> {
match self {
NewPooledTransactionHashes::Eth66(msg) => msg.0,
NewPooledTransactionHashes::Eth68(msg) => msg.hashes,
@ -153,7 +152,7 @@ impl NewPooledTransactionHashes {
}
/// Returns an iterator over all transaction hashes.
pub fn into_iter_hashes(self) -> impl Iterator<Item = H256> {
pub fn into_iter_hashes(self) -> impl Iterator<Item = B256> {
match self {
NewPooledTransactionHashes::Eth66(msg) => msg.0.into_iter(),
NewPooledTransactionHashes::Eth68(msg) => msg.hashes.into_iter(),
@ -220,11 +219,11 @@ pub struct NewPooledTransactionHashes66(
/// Transaction hashes for new transactions that have appeared on the network.
/// Clients should request the transactions with the given hashes using a
/// [`GetPooledTransactions`](crate::GetPooledTransactions) message.
pub Vec<H256>,
pub Vec<B256>,
);
impl From<Vec<H256>> for NewPooledTransactionHashes66 {
fn from(v: Vec<H256>) -> Self {
impl From<Vec<B256>> for NewPooledTransactionHashes66 {
fn from(v: Vec<B256>) -> Self {
NewPooledTransactionHashes66(v)
}
}
@ -243,8 +242,8 @@ pub struct NewPooledTransactionHashes68 {
/// the following way:
/// * `[type_0: B_1, type_1: B_1, ...]`
///
/// This would make it seem like the [`Encodable`](reth_rlp::Encodable) and
/// [`Decodable`](reth_rlp::Decodable) implementations should directly use a `Vec<u8>` for
/// This would make it seem like the [`Encodable`](alloy_rlp::Encodable) and
/// [`Decodable`](alloy_rlp::Decodable) implementations should directly use a `Vec<u8>` for
/// encoding and decoding, because it looks like this field should be encoded as a _list_ of
/// bytes.
///
@ -255,14 +254,14 @@ pub struct NewPooledTransactionHashes68 {
/// **not** a RLP list.
///
/// Because of this, we do not directly use the `Vec<u8>` when encoding and decoding, and
/// instead use the [`Encodable`](reth_rlp::Encodable) and [`Decodable`](reth_rlp::Decodable)
/// instead use the [`Encodable`](alloy_rlp::Encodable) and [`Decodable`](alloy_rlp::Decodable)
/// implementations for `&[u8]` instead, which encodes into a RLP string, and expects an RLP
/// string when decoding.
pub types: Vec<u8>,
/// Transaction sizes for new transactions that have appeared on the network.
pub sizes: Vec<usize>,
/// Transaction hashes for new transactions that have appeared on the network.
pub hashes: Vec<H256>,
pub hashes: Vec<B256>,
}
impl Encodable for NewPooledTransactionHashes68 {
@ -271,7 +270,7 @@ impl Encodable for NewPooledTransactionHashes68 {
struct EncodableNewPooledTransactionHashes68<'a> {
types: &'a [u8],
sizes: &'a Vec<usize>,
hashes: &'a Vec<H256>,
hashes: &'a Vec<B256>,
}
let encodable = EncodableNewPooledTransactionHashes68 {
@ -287,7 +286,7 @@ impl Encodable for NewPooledTransactionHashes68 {
struct EncodableNewPooledTransactionHashes68<'a> {
types: &'a [u8],
sizes: &'a Vec<usize>,
hashes: &'a Vec<H256>,
hashes: &'a Vec<B256>,
}
let encodable = EncodableNewPooledTransactionHashes68 {
@ -301,12 +300,12 @@ impl Encodable for NewPooledTransactionHashes68 {
}
impl Decodable for NewPooledTransactionHashes68 {
fn decode(buf: &mut &[u8]) -> Result<Self, reth_rlp::DecodeError> {
fn decode(buf: &mut &[u8]) -> alloy_rlp::Result<Self> {
#[derive(RlpDecodable)]
struct EncodableNewPooledTransactionHashes68 {
types: Bytes,
sizes: Vec<usize>,
hashes: Vec<H256>,
hashes: Vec<B256>,
}
let encodable = EncodableNewPooledTransactionHashes68::decode(buf)?;
@ -316,13 +315,11 @@ impl Decodable for NewPooledTransactionHashes68 {
#[cfg(test)]
mod tests {
use std::str::FromStr;
use bytes::BytesMut;
use hex_literal::hex;
use reth_rlp::{Decodable, Encodable};
use super::*;
use alloy_rlp::{Decodable, Encodable};
use bytes::BytesMut;
use reth_primitives::hex;
use std::str::FromStr;
/// Takes as input a struct / encoded hex message pair, ensuring that we encode to the exact hex
/// message, and decode to the exact struct.
@ -341,12 +338,12 @@ mod tests {
#[test]
fn can_return_latest_block() {
let mut blocks = NewBlockHashes(vec![BlockHashNumber { hash: H256::random(), number: 0 }]);
let mut blocks = NewBlockHashes(vec![BlockHashNumber { hash: B256::random(), number: 0 }]);
let latest = blocks.latest().unwrap();
assert_eq!(latest.number, 0);
blocks.0.push(BlockHashNumber { hash: H256::random(), number: 100 });
blocks.0.push(BlockHashNumber { hash: H256::random(), number: 2 });
blocks.0.push(BlockHashNumber { hash: B256::random(), number: 100 });
blocks.0.push(BlockHashNumber { hash: B256::random(), number: 2 });
let latest = blocks.latest().unwrap();
assert_eq!(latest.number, 100);
}
@ -362,7 +359,7 @@ mod tests {
NewPooledTransactionHashes68 {
types: vec![0x00],
sizes: vec![0x00],
hashes: vec![H256::from_str(
hashes: vec![B256::from_str(
"0x0000000000000000000000000000000000000000000000000000000000000000",
)
.unwrap()],
@ -374,11 +371,11 @@ mod tests {
types: vec![0x00, 0x00],
sizes: vec![0x00, 0x00],
hashes: vec![
H256::from_str(
B256::from_str(
"0x0000000000000000000000000000000000000000000000000000000000000000",
)
.unwrap(),
H256::from_str(
B256::from_str(
"0x0000000000000000000000000000000000000000000000000000000000000000",
)
.unwrap(),
@ -390,7 +387,7 @@ mod tests {
NewPooledTransactionHashes68 {
types: vec![0x02],
sizes: vec![0xb6],
hashes: vec![H256::from_str(
hashes: vec![B256::from_str(
"0xfecbed04c7b88d8e7221a0a3f5dc33f220212347fc167459ea5cc9c3eb4c1124",
)
.unwrap()],
@ -402,11 +399,11 @@ mod tests {
types: vec![0xff, 0xff],
sizes: vec![0xffffffff, 0xffffffff],
hashes: vec![
H256::from_str(
B256::from_str(
"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
)
.unwrap(),
H256::from_str(
B256::from_str(
"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
)
.unwrap(),
@ -419,11 +416,11 @@ mod tests {
types: vec![0xff, 0xff],
sizes: vec![0xffffffff, 0xffffffff],
hashes: vec![
H256::from_str(
B256::from_str(
"0xbeefcafebeefcafebeefcafebeefcafebeefcafebeefcafebeefcafebeefcafe",
)
.unwrap(),
H256::from_str(
B256::from_str(
"0xbeefcafebeefcafebeefcafebeefcafebeefcafebeefcafebeefcafebeefcafe",
)
.unwrap(),
@ -436,11 +433,11 @@ mod tests {
types: vec![0x10, 0x10],
sizes: vec![0xdeadc0de, 0xdeadc0de],
hashes: vec![
H256::from_str(
B256::from_str(
"0x3b9aca00f0671c9a2a1b817a0a78d3fe0c0f776cccb2a8c3c1b412a4f4e4d4e2",
)
.unwrap(),
H256::from_str(
B256::from_str(
"0x3b9aca00f0671c9a2a1b817a0a78d3fe0c0f776cccb2a8c3c1b412a4f4e4d4e2",
)
.unwrap(),
@ -453,11 +450,11 @@ mod tests {
types: vec![0x6f, 0x6f],
sizes: vec![0x7fffffff, 0x7fffffff],
hashes: vec![
H256::from_str(
B256::from_str(
"0x0000000000000000000000000000000000000000000000000000000000000002",
)
.unwrap(),
H256::from_str(
B256::from_str(
"0x0000000000000000000000000000000000000000000000000000000000000002",
)
.unwrap(),

View File

@ -5,8 +5,8 @@ use super::{
NewPooledTransactionHashes68, NodeData, PooledTransactions, Receipts, Status, Transactions,
};
use crate::{errors::EthStreamError, EthVersion, SharedTransactions};
use alloy_rlp::{length_of_length, Decodable, Encodable, Header};
use reth_primitives::bytes::{Buf, BufMut};
use reth_rlp::{length_of_length, Decodable, Encodable, Header};
use std::{fmt::Debug, sync::Arc};
#[cfg(feature = "serde")]
@ -325,8 +325,8 @@ impl Encodable for EthMessageID {
}
impl Decodable for EthMessageID {
fn decode(buf: &mut &[u8]) -> Result<Self, reth_rlp::DecodeError> {
let id = buf.first().ok_or(reth_rlp::DecodeError::InputTooShort)?;
fn decode(buf: &mut &[u8]) -> alloy_rlp::Result<Self> {
let id = buf.first().ok_or(alloy_rlp::Error::InputTooShort)?;
let id = match id {
0x00 => EthMessageID::Status,
0x01 => EthMessageID::NewBlockHashes,
@ -343,7 +343,7 @@ impl Decodable for EthMessageID {
0x0e => EthMessageID::NodeData,
0x0f => EthMessageID::GetReceipts,
0x10 => EthMessageID::Receipts,
_ => return Err(reth_rlp::DecodeError::Custom("Invalid message ID")),
_ => return Err(alloy_rlp::Error::Custom("Invalid message ID")),
};
buf.advance(1);
Ok(id)
@ -393,7 +393,7 @@ impl<T> Encodable for RequestPair<T>
where
T: Encodable,
{
fn encode(&self, out: &mut dyn reth_rlp::BufMut) {
fn encode(&self, out: &mut dyn alloy_rlp::BufMut) {
let header =
Header { list: true, payload_length: self.request_id.length() + self.message.length() };
@ -416,7 +416,7 @@ impl<T> Decodable for RequestPair<T>
where
T: Decodable,
{
fn decode(buf: &mut &[u8]) -> Result<Self, reth_rlp::DecodeError> {
fn decode(buf: &mut &[u8]) -> alloy_rlp::Result<Self> {
let _header = Header::decode(buf)?;
Ok(Self { request_id: u64::decode(buf)?, message: T::decode(buf)? })
}
@ -428,8 +428,8 @@ mod test {
errors::EthStreamError, types::message::RequestPair, EthMessage, EthMessageID, GetNodeData,
NodeData, ProtocolMessage,
};
use hex_literal::hex;
use reth_rlp::{Decodable, Encodable};
use alloy_rlp::{Decodable, Encodable};
use reth_primitives::hex;
fn encode<T: Encodable>(value: T) -> Vec<u8> {
let mut buf = vec![];

View File

@ -1,7 +1,7 @@
//! Implements the `GetReceipts` and `Receipts` message types.
use alloy_rlp::{RlpDecodableWrapper, RlpEncodableWrapper};
use reth_codecs::derive_arbitrary;
use reth_primitives::{ReceiptWithBloom, H256};
use reth_rlp::{RlpDecodableWrapper, RlpEncodableWrapper};
use reth_primitives::{ReceiptWithBloom, B256};
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
@ -12,7 +12,7 @@ use serde::{Deserialize, Serialize};
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct GetReceipts(
/// The block hashes to request receipts for.
pub Vec<H256>,
pub Vec<B256>,
);
/// The response to [`GetReceipts`], containing receipt lists that correspond to each block
@ -37,9 +37,8 @@ mod test {
types::{message::RequestPair, GetReceipts},
Receipts,
};
use hex_literal::hex;
use reth_primitives::{Log, Receipt, ReceiptWithBloom, TxType};
use reth_rlp::{Decodable, Encodable};
use alloy_rlp::{Decodable, Encodable};
use reth_primitives::{hex, Log, Receipt, ReceiptWithBloom, TxType};
#[test]
fn roundtrip_eip1559() {

View File

@ -1,7 +1,7 @@
//! Implements the `GetNodeData` and `NodeData` message types.
use alloy_rlp::{RlpDecodableWrapper, RlpEncodableWrapper};
use reth_codecs::derive_arbitrary;
use reth_primitives::{Bytes, H256};
use reth_rlp::{RlpDecodableWrapper, RlpEncodableWrapper};
use reth_primitives::{Bytes, B256};
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
@ -12,7 +12,7 @@ use serde::{Deserialize, Serialize};
#[derive_arbitrary(rlp)]
#[derive(Clone, Debug, PartialEq, Eq, RlpEncodableWrapper, RlpDecodableWrapper, Default)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct GetNodeData(pub Vec<H256>);
pub struct GetNodeData(pub Vec<B256>);
/// The response to [`GetNodeData`], containing the state tree nodes or contract bytecode
/// corresponding to the requested hashes.
@ -26,10 +26,10 @@ pub struct NodeData(pub Vec<Bytes>);
#[cfg(test)]
mod test {
use hex_literal::hex;
use reth_primitives::hex;
use crate::{message::RequestPair, GetNodeData, NodeData};
use reth_rlp::{Decodable, Encodable};
use alloy_rlp::{Decodable, Encodable};
#[test]
// Test vector from: https://eips.ethereum.org/EIPS/eip-2481

View File

@ -1,10 +1,9 @@
use crate::{EthVersion, StatusBuilder};
use alloy_rlp::{RlpDecodable, RlpEncodable};
use reth_codecs::derive_arbitrary;
use reth_primitives::{
hex, Chain, ChainSpec, ForkId, Genesis, Hardfork, Head, H256, MAINNET, U256,
hex, Chain, ChainSpec, ForkId, Genesis, Hardfork, Head, NamedChain, B256, MAINNET, U256,
};
use reth_rlp::{RlpDecodable, RlpEncodable};
use std::fmt::{Debug, Display};
#[cfg(feature = "serde")]
@ -31,10 +30,10 @@ pub struct Status {
pub total_difficulty: U256,
/// The highest difficulty block hash the peer has seen
pub blockhash: H256,
pub blockhash: B256,
/// The genesis hash of the peer's chain.
pub genesis: H256,
pub genesis: B256,
/// The fork identifier, a [CRC32
/// checksum](https://en.wikipedia.org/wiki/Cyclic_redundancy_check#CRC-32_algorithm) for
@ -134,7 +133,7 @@ impl Default for Status {
let mainnet_genesis = MAINNET.genesis_hash();
Status {
version: EthVersion::Eth68 as u8,
chain: Chain::Named(ethers_core::types::Chain::Mainnet),
chain: Chain::Named(NamedChain::Mainnet),
total_difficulty: U256::from(17_179_869_184u64),
blockhash: mainnet_genesis,
genesis: mainnet_genesis,
@ -148,13 +147,12 @@ impl Default for Status {
#[cfg(test)]
mod tests {
use crate::types::{EthVersion, Status};
use ethers_core::types::Chain as NamedChain;
use hex_literal::hex;
use alloy_rlp::{Decodable, Encodable};
use rand::Rng;
use reth_primitives::{
Chain, ChainSpec, ForkCondition, ForkHash, ForkId, Genesis, Hardfork, Head, H256, U256,
hex, Chain, ChainSpec, ForkCondition, ForkHash, ForkId, Genesis, Hardfork, Head,
NamedChain, B256, U256,
};
use reth_rlp::{Decodable, Encodable};
use std::str::FromStr;
#[test]
@ -164,11 +162,11 @@ mod tests {
version: EthVersion::Eth67 as u8,
chain: Chain::Named(NamedChain::Mainnet),
total_difficulty: U256::from(36206751599115524359527u128),
blockhash: H256::from_str(
blockhash: B256::from_str(
"feb27336ca7923f8fab3bd617fcb6e75841538f71c1bcfc267d7838489d9e13d",
)
.unwrap(),
genesis: H256::from_str(
genesis: B256::from_str(
"d4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3",
)
.unwrap(),
@ -187,11 +185,11 @@ mod tests {
version: EthVersion::Eth67 as u8,
chain: Chain::Named(NamedChain::Mainnet),
total_difficulty: U256::from(36206751599115524359527u128),
blockhash: H256::from_str(
blockhash: B256::from_str(
"feb27336ca7923f8fab3bd617fcb6e75841538f71c1bcfc267d7838489d9e13d",
)
.unwrap(),
genesis: H256::from_str(
genesis: B256::from_str(
"d4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3",
)
.unwrap(),
@ -208,11 +206,11 @@ mod tests {
version: EthVersion::Eth66 as u8,
chain: Chain::Named(NamedChain::BinanceSmartChain),
total_difficulty: U256::from(37851386u64),
blockhash: H256::from_str(
blockhash: B256::from_str(
"f8514c4680ef27700751b08f37645309ce65a449616a3ea966bf39dd935bb27b",
)
.unwrap(),
genesis: H256::from_str(
genesis: B256::from_str(
"0d21840abff46b96c84b2ac9e10e4f5cdaeb5693cb665db62a2f3b02d2d57b5b",
)
.unwrap(),
@ -231,11 +229,11 @@ mod tests {
version: EthVersion::Eth66 as u8,
chain: Chain::Named(NamedChain::BinanceSmartChain),
total_difficulty: U256::from(37851386u64),
blockhash: H256::from_str(
blockhash: B256::from_str(
"f8514c4680ef27700751b08f37645309ce65a449616a3ea966bf39dd935bb27b",
)
.unwrap(),
genesis: H256::from_str(
genesis: B256::from_str(
"0d21840abff46b96c84b2ac9e10e4f5cdaeb5693cb665db62a2f3b02d2d57b5b",
)
.unwrap(),
@ -255,11 +253,11 @@ mod tests {
"0x000000000000000000000000006d68fcffffffffffffffffffffffffdeab81b8",
)
.unwrap(),
blockhash: H256::from_str(
blockhash: B256::from_str(
"523e8163a6d620a4cc152c547a05f28a03fec91a2a615194cb86df9731372c0c",
)
.unwrap(),
genesis: H256::from_str(
genesis: B256::from_str(
"6499dccdc7c7def3ebb1ce4c6ee27ec6bd02aee570625ca391919faf77ef27bd",
)
.unwrap(),
@ -271,8 +269,8 @@ mod tests {
#[test]
fn init_custom_status_fields() {
let head_hash = H256::random();
let mut rng = rand::thread_rng();
let head_hash = rng.gen();
let total_difficulty = U256::from(rng.gen::<u64>());
// create a genesis that has a random part, so we can check that the hash is preserved

View File

@ -1,7 +1,7 @@
//! Implements the `GetPooledTransactions` and `PooledTransactions` message types.
use alloy_rlp::{RlpDecodableWrapper, RlpEncodableWrapper};
use reth_codecs::derive_arbitrary;
use reth_primitives::{PooledTransactionsElement, TransactionSigned, H256};
use reth_rlp::{RlpDecodableWrapper, RlpEncodableWrapper};
use reth_primitives::{PooledTransactionsElement, TransactionSigned, B256};
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
@ -12,12 +12,12 @@ use serde::{Deserialize, Serialize};
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct GetPooledTransactions(
/// The transaction hashes to request transaction bodies for.
pub Vec<H256>,
pub Vec<B256>,
);
impl<T> From<Vec<T>> for GetPooledTransactions
where
T: Into<H256>,
T: Into<B256>,
{
fn from(hashes: Vec<T>) -> Self {
GetPooledTransactions(hashes.into_iter().map(|h| h.into()).collect())
@ -48,11 +48,10 @@ impl From<Vec<TransactionSigned>> for PooledTransactions {
#[cfg(test)]
mod test {
use crate::{message::RequestPair, GetPooledTransactions, PooledTransactions};
use hex_literal::hex;
use alloy_rlp::{Decodable, Encodable};
use reth_primitives::{
hex, Signature, Transaction, TransactionKind, TransactionSigned, TxEip1559, TxLegacy, U256,
};
use reth_rlp::{Decodable, Encodable};
use std::str::FromStr;
#[test]

View File

@ -1,10 +1,10 @@
//! Round-trip encoding fuzzing for the `eth-wire` crate.
use reth_rlp::{Decodable, Encodable};
use alloy_rlp::{Decodable, Encodable};
use serde::Serialize;
use std::fmt::Debug;
/// Creates a fuzz test for a type that should be [`Encodable`](reth_rlp::Encodable) and
/// [`Decodable`](reth_rlp::Decodable).
/// Creates a fuzz test for a type that should be [`Encodable`](alloy_rlp::Encodable) and
/// [`Decodable`](alloy_rlp::Decodable).
///
/// The test will create a random instance of the type, encode it, and then decode it.
fn roundtrip_encoding<T>(thing: T)
@ -48,6 +48,7 @@ macro_rules! fuzz_type_and_name {
#[cfg(any(test, feature = "bench"))]
pub mod fuzz_rlp {
use crate::roundtrip_encoding;
use alloy_rlp::{RlpDecodableWrapper, RlpEncodableWrapper};
use reth_codecs::derive_arbitrary;
use reth_eth_wire::{
BlockBodies, BlockHeaders, DisconnectReason, GetBlockBodies, GetBlockHeaders, GetNodeData,
@ -56,7 +57,6 @@ pub mod fuzz_rlp {
PooledTransactions, Receipts, Status, Transactions,
};
use reth_primitives::{BlockHashOrNumber, TransactionSigned};
use reth_rlp::{RlpDecodableWrapper, RlpEncodableWrapper};
use serde::{Deserialize, Serialize};
use test_fuzz::test_fuzz;

View File

@ -1,7 +1,7 @@
//! Decoding tests for [`NewBlock`]
use alloy_rlp::Decodable;
use reth_eth_wire::NewBlock;
use reth_primitives::hex;
use reth_rlp::Decodable;
use std::{fs, path::PathBuf};
#[test]

View File

@ -1,7 +1,7 @@
//! Decoding tests for [`NewPooledTransactions`]
use alloy_rlp::Decodable;
use reth_eth_wire::NewPooledTransactionHashes66;
use reth_primitives::hex;
use reth_rlp::Decodable;
use std::{fs, path::PathBuf};
#[test]

View File

@ -1,7 +1,7 @@
//! Decoding tests for [`PooledTransactions`]
use alloy_rlp::Decodable;
use reth_eth_wire::PooledTransactions;
use reth_primitives::{hex, Bytes, PooledTransactionsElement};
use reth_rlp::Decodable;
use std::{fs, path::PathBuf};
#[test]

View File

@ -26,13 +26,13 @@ reth-discv4 = { path = "../discv4" }
reth-dns-discovery = { path = "../dns" }
reth-eth-wire = { path = "../eth-wire" }
reth-ecies = { path = "../ecies" }
reth-rlp.workspace = true
reth-rlp-derive = { path = "../../rlp/rlp-derive" }
reth-tasks.workspace = true
reth-transaction-pool.workspace = true
reth-provider.workspace = true
reth-rpc-types.workspace = true
alloy-rlp.workspace = true
# async/futures
futures.workspace = true
pin-project.workspace = true
@ -63,7 +63,6 @@ rand.workspace = true
secp256k1 = { workspace = true, features = ["global-context", "rand-std", "recovery"] }
enr = { workspace = true, features = ["rust-secp256k1"], optional = true }
ethers-core = { workspace = true, default-features = false, optional = true }
tempfile = { version = "3.3", optional = true }
[dev-dependencies]
@ -88,12 +87,11 @@ ethers-middleware = { workspace = true, default-features = false }
enr = { workspace = true, features = ["serde", "rust-secp256k1"] }
# misc
hex = "0.4"
serial_test.workspace = true
tempfile = "3.3"
[features]
default = ["serde"]
serde = ["dep:serde", "dep:humantime-serde", "secp256k1/serde", "enr?/serde", "dep:serde_json"]
test-utils = ["reth-provider/test-utils", "dep:enr", "dep:ethers-core", "dep:tempfile"]
test-utils = ["reth-provider/test-utils", "dep:enr", "dep:tempfile"]
geth-tests = []

View File

@ -11,15 +11,12 @@ use reth_interfaces::p2p::{
priority::Priority,
};
use reth_network_api::ReputationChangeKind;
use reth_primitives::{Header, PeerId, H256};
use reth_primitives::{Header, PeerId, B256};
use std::sync::{
atomic::{AtomicUsize, Ordering},
Arc,
};
use tokio::sync::{
mpsc::UnboundedSender,
oneshot::{self},
};
use tokio::sync::{mpsc::UnboundedSender, oneshot};
/// Front-end API for fetching data from the network.
///
@ -111,7 +108,7 @@ impl BodiesClient for FetchClient {
/// Sends a `GetBlockBodies` request to an available peer.
fn get_block_bodies_with_priority(
&self,
request: Vec<H256>,
request: Vec<B256>,
priority: Priority,
) -> Self::Output {
let (response, rx) = oneshot::channel();

View File

@ -9,7 +9,7 @@ use reth_interfaces::p2p::{
priority::Priority,
};
use reth_network_api::ReputationChangeKind;
use reth_primitives::{BlockBody, Header, PeerId, H256};
use reth_primitives::{BlockBody, Header, PeerId, B256};
use std::{
collections::{HashMap, VecDeque},
sync::{
@ -37,7 +37,7 @@ pub struct StateFetcher {
HashMap<PeerId, Request<HeadersRequest, PeerRequestResult<Vec<Header>>>>,
/// Currently active [`GetBlockBodies`] requests
inflight_bodies_requests:
HashMap<PeerId, Request<Vec<H256>, PeerRequestResult<Vec<BlockBody>>>>,
HashMap<PeerId, Request<Vec<B256>, PeerRequestResult<Vec<BlockBody>>>>,
/// The list of _available_ peers for requests.
peers: HashMap<PeerId, Peer>,
/// The handle to the peers manager
@ -73,7 +73,7 @@ impl StateFetcher {
pub(crate) fn new_active_peer(
&mut self,
peer_id: PeerId,
best_hash: H256,
best_hash: B256,
best_number: u64,
timeout: Arc<AtomicU64>,
) {
@ -100,7 +100,7 @@ impl StateFetcher {
/// Updates the block information for the peer.
///
/// Returns `true` if this a newer block
pub(crate) fn update_peer_block(&mut self, peer_id: &PeerId, hash: H256, number: u64) -> bool {
pub(crate) fn update_peer_block(&mut self, peer_id: &PeerId, hash: B256, number: u64) -> bool {
if let Some(peer) = self.peers.get_mut(peer_id) {
if number > peer.best_number {
peer.best_hash = hash;
@ -302,7 +302,7 @@ struct Peer {
/// The state this peer currently resides in.
state: PeerState,
/// Best known hash that the peer has
best_hash: H256,
best_hash: B256,
/// Tracks the best number of the peer.
best_number: u64,
/// Tracks the current timeout value we use for the peer.
@ -372,7 +372,7 @@ pub(crate) enum DownloadRequest {
},
/// Download the requested headers and send response through channel
GetBlockBodies {
request: Vec<H256>,
request: Vec<B256>,
response: oneshot::Sender<PeerRequestResult<Vec<BlockBody>>>,
priority: Priority,
},
@ -429,7 +429,7 @@ pub(crate) enum BlockResponseOutcome {
mod tests {
use super::*;
use crate::{peers::PeersManager, PeersConfig};
use reth_primitives::{SealedHeader, H256, H512};
use reth_primitives::{SealedHeader, B256, B512};
use std::future::poll_fn;
#[tokio::test(flavor = "multi_thread")]
@ -457,10 +457,10 @@ mod tests {
let manager = PeersManager::new(PeersConfig::default());
let mut fetcher = StateFetcher::new(manager.handle(), Default::default());
// Add a few random peers
let peer1 = H512::random();
let peer2 = H512::random();
fetcher.new_active_peer(peer1, H256::random(), 1, Arc::new(AtomicU64::new(1)));
fetcher.new_active_peer(peer2, H256::random(), 2, Arc::new(AtomicU64::new(1)));
let peer1 = B512::random();
let peer2 = B512::random();
fetcher.new_active_peer(peer1, B256::random(), 1, Arc::new(AtomicU64::new(1)));
fetcher.new_active_peer(peer2, B256::random(), 2, Arc::new(AtomicU64::new(1)));
let first_peer = fetcher.next_peer().unwrap();
assert!(first_peer == peer1 || first_peer == peer2);
@ -480,15 +480,15 @@ mod tests {
let manager = PeersManager::new(PeersConfig::default());
let mut fetcher = StateFetcher::new(manager.handle(), Default::default());
// Add a few random peers
let peer1 = H512::random();
let peer2 = H512::random();
let peer3 = H512::random();
let peer1 = B512::random();
let peer2 = B512::random();
let peer3 = B512::random();
let peer2_timeout = Arc::new(AtomicU64::new(300));
fetcher.new_active_peer(peer1, H256::random(), 1, Arc::new(AtomicU64::new(30)));
fetcher.new_active_peer(peer2, H256::random(), 2, Arc::clone(&peer2_timeout));
fetcher.new_active_peer(peer3, H256::random(), 3, Arc::new(AtomicU64::new(50)));
fetcher.new_active_peer(peer1, B256::random(), 1, Arc::new(AtomicU64::new(30)));
fetcher.new_active_peer(peer2, B256::random(), 2, Arc::clone(&peer2_timeout));
fetcher.new_active_peer(peer3, B256::random(), 3, Arc::new(AtomicU64::new(50)));
// Must always get peer1 (lowest timeout)
assert_eq!(fetcher.next_peer(), Some(peer1));
@ -504,7 +504,7 @@ mod tests {
async fn test_on_block_headers_response() {
let manager = PeersManager::new(PeersConfig::default());
let mut fetcher = StateFetcher::new(manager.handle(), Default::default());
let peer_id = H512::random();
let peer_id = B512::random();
assert_eq!(fetcher.on_block_headers_response(peer_id, Ok(vec![Header::default()])), None);
@ -534,7 +534,7 @@ mod tests {
async fn test_header_response_outcome() {
let manager = PeersManager::new(PeersConfig::default());
let mut fetcher = StateFetcher::new(manager.handle(), Default::default());
let peer_id = H512::random();
let peer_id = B512::random();
let request_pair = || {
let (tx, _rx) = oneshot::channel();

View File

@ -41,7 +41,7 @@ use reth_eth_wire::{
use reth_metrics::common::mpsc::UnboundedMeteredSender;
use reth_net_common::bandwidth_meter::BandwidthMeter;
use reth_network_api::ReputationChangeKind;
use reth_primitives::{listener::EventListeners, ForkId, NodeRecord, PeerId, H256};
use reth_primitives::{listener::EventListeners, ForkId, NodeRecord, PeerId, B256};
use reth_provider::{BlockNumReader, BlockReader};
use reth_rpc_types::{EthProtocolInfo, NetworkStatus};
use std::{
@ -301,7 +301,7 @@ where
}
/// Returns the configured genesis hash
pub fn genesis_hash(&self) -> H256 {
pub fn genesis_hash(&self) -> B256 {
self.swarm.state().genesis_hash()
}

View File

@ -12,7 +12,7 @@ use reth_eth_wire::{
};
use reth_interfaces::p2p::error::{RequestError, RequestResult};
use reth_primitives::{
BlockBody, Bytes, Header, PeerId, PooledTransactionsElement, ReceiptWithBloom, H256,
BlockBody, Bytes, Header, PeerId, PooledTransactionsElement, ReceiptWithBloom, B256,
};
use std::{
fmt,
@ -25,7 +25,7 @@ use tokio::sync::{mpsc, mpsc::error::TrySendError, oneshot};
#[derive(Debug, Clone)]
pub struct NewBlockMessage {
/// Hash of the block
pub hash: H256,
pub hash: B256,
/// Raw received message
pub block: Arc<NewBlock>,
}

View File

@ -11,7 +11,7 @@ use reth_network_api::{
NetworkError, NetworkInfo, PeerInfo, PeerKind, Peers, PeersInfo, Reputation,
ReputationChangeKind,
};
use reth_primitives::{Head, NodeRecord, PeerId, TransactionSigned, H256};
use reth_primitives::{Head, NodeRecord, PeerId, TransactionSigned, B256};
use reth_rpc_types::NetworkStatus;
use std::{
net::SocketAddr,
@ -135,7 +135,7 @@ impl NetworkHandle {
/// Caution: in PoS this is a noop, since new block are no longer announced over devp2p, but are
/// instead sent to node node by the CL. However, they can still be requested over devp2p, but
/// broadcasting them is a considered a protocol violation..
pub fn announce_block(&self, block: NewBlock, hash: H256) {
pub fn announce_block(&self, block: NewBlock, hash: B256) {
self.send_message(NetworkHandleMessage::AnnounceBlock(block, hash))
}
@ -332,7 +332,7 @@ pub(crate) enum NetworkHandleMessage {
/// Add a new listener for [`NetworkEvent`].
EventListener(UnboundedSender<NetworkEvent>),
/// Broadcast event to announce a new block to all nodes.
AnnounceBlock(NewBlock, H256),
AnnounceBlock(NewBlock, B256),
/// Sends the list of transactions to the given peer.
SendTransaction { peer_id: PeerId, msg: SharedTransactions },
/// Sends the list of transactions hashes to the given peer.

View File

@ -1349,7 +1349,7 @@ mod test {
};
use reth_net_common::ban_list::BanList;
use reth_network_api::ReputationChangeKind;
use reth_primitives::{PeerId, H512};
use reth_primitives::{PeerId, B512};
use std::{
collections::HashSet,
future::{poll_fn, Future},
@ -2002,7 +2002,7 @@ mod test {
let ban_list = BanList::new(HashSet::new(), vec![ip]);
let config = PeersConfig::default().with_ban_list(ban_list);
let mut peer_manager = PeersManager::new(config);
peer_manager.add_peer(H512::default(), socket_addr, None);
peer_manager.add_peer(B512::default(), socket_addr, None);
assert!(peer_manager.peers.is_empty());
}
@ -2031,7 +2031,7 @@ mod test {
async fn test_on_active_inbound_ban_list() {
let ip = IpAddr::V4(Ipv4Addr::new(127, 0, 1, 2));
let socket_addr = SocketAddr::new(ip, 8008);
let given_peer_id: PeerId = H512::from_low_u64_ne(123403423412);
let given_peer_id = PeerId::random();
let ban_list = BanList::new(vec![given_peer_id], HashSet::new());
let config = PeersConfig::default().with_ban_list(ban_list);
let mut peer_manager = PeersManager::new(config);

View File

@ -16,7 +16,7 @@ use reth_eth_wire::{
capability::Capabilities, BlockHashNumber, DisconnectReason, NewBlockHashes, Status,
};
use reth_network_api::PeerKind;
use reth_primitives::{ForkId, PeerId, H256};
use reth_primitives::{ForkId, PeerId, B256};
use reth_provider::BlockNumReader;
use std::{
collections::{HashMap, VecDeque},
@ -60,7 +60,7 @@ pub struct NetworkState<C> {
/// Network discovery.
discovery: Discovery,
/// The genesis hash of the network we're on
genesis_hash: H256,
genesis_hash: B256,
/// The type that handles requests.
///
/// The fetcher streams RLPx related requests on a per-peer basis to this type. This type will
@ -77,7 +77,7 @@ where
client: C,
discovery: Discovery,
peers_manager: PeersManager,
genesis_hash: H256,
genesis_hash: B256,
num_active_peers: Arc<AtomicUsize>,
) -> Self {
let state_fetcher = StateFetcher::new(peers_manager.handle(), num_active_peers);
@ -113,7 +113,7 @@ where
}
/// Configured genesis hash.
pub fn genesis_hash(&self) -> H256 {
pub fn genesis_hash(&self) -> B256 {
self.genesis_hash
}
@ -227,7 +227,7 @@ where
}
/// Updates the block information for the peer.
pub(crate) fn update_peer_block(&mut self, peer_id: &PeerId, hash: H256, number: u64) {
pub(crate) fn update_peer_block(&mut self, peer_id: &PeerId, hash: B256, number: u64) {
if let Some(peer) = self.active_peers.get_mut(peer_id) {
peer.best_hash = hash;
}
@ -242,7 +242,7 @@ where
/// Invoked after a `NewBlock` message was received by the peer.
///
/// This will keep track of blocks we know a peer has
pub(crate) fn on_new_block(&mut self, peer_id: PeerId, hash: H256) {
pub(crate) fn on_new_block(&mut self, peer_id: PeerId, hash: B256) {
// Mark the blocks as seen
if let Some(peer) = self.active_peers.get_mut(&peer_id) {
peer.blocks.insert(hash);
@ -469,7 +469,7 @@ where
#[derive(Debug)]
pub(crate) struct ActivePeer {
/// Best block of the peer.
pub(crate) best_hash: H256,
pub(crate) best_hash: B256,
/// The capabilities of the remote peer.
#[allow(unused)]
pub(crate) capabilities: Arc<Capabilities>,
@ -478,7 +478,7 @@ pub(crate) struct ActivePeer {
/// The response receiver for a currently active request to that peer.
pub(crate) pending_response: Option<PeerResponse>,
/// Blocks we know the peer has.
pub(crate) blocks: LruCache<H256>,
pub(crate) blocks: LruCache<B256>,
}
/// Message variants triggered by the [`NetworkState`]
@ -530,7 +530,7 @@ mod tests {
BlockBodies, EthVersion, Status,
};
use reth_interfaces::p2p::{bodies::client::BodiesClient, error::RequestError};
use reth_primitives::{BlockBody, Header, PeerId, H256};
use reth_primitives::{BlockBody, Header, PeerId, B256};
use reth_provider::test_utils::NoopProvider;
use std::{
future::poll_fn,
@ -606,11 +606,11 @@ mod tests {
});
// send requests to the state via the client
let (peer, bodies) = client.get_block_bodies(vec![H256::random()]).await.unwrap().split();
let (peer, bodies) = client.get_block_bodies(vec![B256::random()]).await.unwrap().split();
assert_eq!(peer, peer_id);
assert_eq!(bodies, vec![body]);
let resp = client.get_block_bodies(vec![H256::random()]).await;
let resp = client.get_block_bodies(vec![B256::random()]).await;
assert!(resp.is_err());
assert_eq!(resp.unwrap_err(), RequestError::ConnectionDropped);
}

View File

@ -20,7 +20,7 @@ use reth_metrics::common::mpsc::UnboundedMeteredReceiver;
use reth_network_api::{Peers, ReputationChangeKind};
use reth_primitives::{
FromRecoveredPooledTransaction, IntoRecoveredTransaction, PeerId, PooledTransactionsElement,
TransactionSigned, TxHash, H256,
TransactionSigned, TxHash, B256,
};
use reth_transaction_pool::{
error::PoolResult, GetPooledTransactionLimit, PoolTransaction, PropagateKind,
@ -911,7 +911,7 @@ impl Future for GetPooledTxRequestFut {
#[derive(Debug)]
struct Peer {
/// Keeps track of transactions that we know the peer has seen.
transactions: LruCache<H256>,
transactions: LruCache<B256>,
/// A communication channel directly to the peer's session task.
request_tx: PeerRequestSender,
/// negotiated version of the session.
@ -925,9 +925,9 @@ struct Peer {
#[derive(Debug)]
enum TransactionsCommand {
/// Propagate a transaction hash to the network.
PropagateHash(H256),
PropagateHash(B256),
/// Propagate transaction hashes to a specific peer.
PropagateHashesTo(Vec<H256>, PeerId),
PropagateHashesTo(Vec<B256>, PeerId),
/// Request the list of active peer IDs from the [`TransactionsManager`].
GetActivePeers,
/// Propagate a collection of full transactions to a specific peer.
@ -960,10 +960,11 @@ pub enum NetworkTransactionEvent {
mod tests {
use super::*;
use crate::{test_utils::Testnet, NetworkConfigBuilder, NetworkManager};
use alloy_rlp::Decodable;
use reth_interfaces::sync::{NetworkSyncUpdater, SyncState};
use reth_network_api::NetworkInfo;
use reth_primitives::hex;
use reth_provider::test_utils::NoopProvider;
use reth_rlp::Decodable;
use reth_transaction_pool::test_utils::{testing_pool, MockTransaction};
use secp256k1::SecretKey;
use std::future::poll_fn;
@ -1036,7 +1037,7 @@ mod tests {
}
}
// random tx: <https://etherscan.io/getRawTx?tx=0x9448608d36e721ef403c53b00546068a6474d6cbab6816c3926de449898e7bce>
let input = hex::decode("02f871018302a90f808504890aef60826b6c94ddf4c5025d1a5742cf12f74eec246d4432c295e487e09c3bbcc12b2b80c080a0f21a4eacd0bf8fea9c5105c543be5a1d8c796516875710fafafdf16d16d8ee23a001280915021bb446d1973501a67f93d2b38894a514b976e7b46dc2fe54598d76").unwrap();
let input = hex!("02f871018302a90f808504890aef60826b6c94ddf4c5025d1a5742cf12f74eec246d4432c295e487e09c3bbcc12b2b80c080a0f21a4eacd0bf8fea9c5105c543be5a1d8c796516875710fafafdf16d16d8ee23a001280915021bb446d1973501a67f93d2b38894a514b976e7b46dc2fe54598d76");
let signed_tx = TransactionSigned::decode(&mut &input[..]).unwrap();
transactions.on_network_tx_event(NetworkTransactionEvent::IncomingTransactions {
peer_id: *handle1.peer_id(),
@ -1122,7 +1123,7 @@ mod tests {
}
}
// random tx: <https://etherscan.io/getRawTx?tx=0x9448608d36e721ef403c53b00546068a6474d6cbab6816c3926de449898e7bce>
let input = hex::decode("02f871018302a90f808504890aef60826b6c94ddf4c5025d1a5742cf12f74eec246d4432c295e487e09c3bbcc12b2b80c080a0f21a4eacd0bf8fea9c5105c543be5a1d8c796516875710fafafdf16d16d8ee23a001280915021bb446d1973501a67f93d2b38894a514b976e7b46dc2fe54598d76").unwrap();
let input = hex!("02f871018302a90f808504890aef60826b6c94ddf4c5025d1a5742cf12f74eec246d4432c295e487e09c3bbcc12b2b80c080a0f21a4eacd0bf8fea9c5105c543be5a1d8c796516875710fafafdf16d16d8ee23a001280915021bb446d1973501a67f93d2b38894a514b976e7b46dc2fe54598d76");
let signed_tx = TransactionSigned::decode(&mut &input[..]).unwrap();
transactions.on_network_tx_event(NetworkTransactionEvent::IncomingTransactions {
peer_id: *handle1.peer_id(),
@ -1205,7 +1206,7 @@ mod tests {
}
}
// random tx: <https://etherscan.io/getRawTx?tx=0x9448608d36e721ef403c53b00546068a6474d6cbab6816c3926de449898e7bce>
let input = hex::decode("02f871018302a90f808504890aef60826b6c94ddf4c5025d1a5742cf12f74eec246d4432c295e487e09c3bbcc12b2b80c080a0f21a4eacd0bf8fea9c5105c543be5a1d8c796516875710fafafdf16d16d8ee23a001280915021bb446d1973501a67f93d2b38894a514b976e7b46dc2fe54598d76").unwrap();
let input = hex!("02f871018302a90f808504890aef60826b6c94ddf4c5025d1a5742cf12f74eec246d4432c295e487e09c3bbcc12b2b80c080a0f21a4eacd0bf8fea9c5105c543be5a1d8c796516875710fafafdf16d16d8ee23a001280915021bb446d1973501a67f93d2b38894a514b976e7b46dc2fe54598d76");
let signed_tx = TransactionSigned::decode(&mut &input[..]).unwrap();
transactions.on_network_tx_event(NetworkTransactionEvent::IncomingTransactions {
peer_id: *handle1.peer_id(),

View File

@ -10,7 +10,7 @@ use ethers_middleware::SignerMiddleware;
use ethers_providers::Middleware;
use ethers_signers::Signer;
use reth_network::test_utils::enr_to_peer_id;
use reth_primitives::PeerId;
use reth_primitives::{hex, PeerId};
use thiserror::Error;
use tracing::trace;

View File

@ -1,6 +1,6 @@
use crate::clique::{CliqueGethInstance, CliqueMiddleware};
use ethers_core::{
types::{transaction::eip2718::TypedTransaction, Eip1559TransactionRequest, H160, U64},
types::{transaction::eip2718::TypedTransaction, Address, Eip1559TransactionRequest},
utils::Geth,
};
use ethers_providers::Middleware;
@ -113,7 +113,7 @@ async fn init_geth() -> (CliqueGethInstance, Arc<ChainSpec>) {
let txs = nonces.map(|nonce| {
// create a tx that just sends to the zero addr
TypedTransaction::Eip1559(
Eip1559TransactionRequest::new().to(H160::zero()).value(1u64).nonce(nonce),
Eip1559TransactionRequest::new().to(Address::zero()).value(1u64).nonce(nonce),
)
});
tracing::info!("generated transactions for blocks");
@ -122,7 +122,7 @@ async fn init_geth() -> (CliqueGethInstance, Arc<ChainSpec>) {
clique.provider.send_requests(txs).await.unwrap();
let block = clique.provider.get_block_number().await.unwrap();
assert!(block > U64::zero());
assert!(block.as_u64() > 0);
(clique, Arc::new(chainspec))
}

View File

@ -9,7 +9,7 @@ use reth_network::test_utils::{NetworkEventStream, Testnet};
use reth_network_api::{NetworkInfo, Peers};
use reth_primitives::{
Block, BlockBody, Bytes, Header, HeadersDirection, Signature, Transaction, TransactionKind,
TransactionSigned, TxEip2930, H256, U256,
TransactionSigned, TxEip2930, U256,
};
use reth_provider::test_utils::MockEthProvider;
use std::sync::Arc;
@ -58,7 +58,7 @@ async fn test_get_body() {
// request some blocks
for _ in 0..100 {
// Set a new random block to the mock storage and request it via the network
let block_hash = H256::random();
let block_hash = rng.gen();
let mut block = Block::default();
block.body.push(rng_transaction(&mut rng));
@ -100,12 +100,12 @@ async fn test_get_header() {
assert_eq!(connected, *handle1.peer_id());
let start: u64 = rng.gen();
let mut hash = H256::random();
let mut hash = rng.gen();
// request some headers
for idx in 0..100 {
// Set a new random header to the mock storage and request it via the network
let header = Header { number: start + idx, parent_hash: hash, ..Default::default() };
hash = H256::random();
hash = rng.gen();
mock_provider.add_header(hash, header.clone());