Skip to content

Commit

Permalink
refactor: use k256 crate
Browse files Browse the repository at this point in the history
  • Loading branch information
mattsse committed Nov 6, 2022
1 parent 9c40f82 commit 47d551d
Show file tree
Hide file tree
Showing 7 changed files with 125 additions and 70 deletions.
59 changes: 51 additions & 8 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,6 @@ members = [
"crates/libmdbx-rs/mdbx-sys"
]
default-members = ["bin/reth"]

[patch.crates-io]
ecdsa = { git = "https://github.com/RustCrypto/signatures.git" }
9 changes: 3 additions & 6 deletions crates/net/discv4/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,8 @@ reth-rlp-derive = { path = "../../common/rlp-derive" }

# ethereum
discv5 = { git = "https://github.com/sigp/discv5" }
secp256k1 = { version = "0.24", features = [
"global-context",
"rand-std",
"recovery",
] }
k256 = { git = "https://github.com/RustCrypto/elliptic-curves", default-features = false, features = ["ecdsa", "std"] }
sha3 = { version = "0.10", default-features = false }

# async/futures
tokio = { version = "1", features = ["io-util", "net", "time"] }
Expand All @@ -43,4 +40,4 @@ tokio = { version = "1", features = ["full"] }
tracing-test = "0.2"

[features]
mock = ["rand"]
mock = ["rand"]
4 changes: 3 additions & 1 deletion crates/net/discv4/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,9 @@ pub enum DecodePacketError {
#[error("Message id {0} is not supported.")]
UnknownMessage(u8),
#[error("Failed to recover public key: {0:?}")]
Secp256k1(#[from] secp256k1::Error),
RecoveryError(#[from] k256::ecdsa::Error),
#[error("Recovery id {0} too large")]
InvalidRecoveryId(u8),
}

/// High level errors that can occur when interacting with the discovery service
Expand Down
27 changes: 14 additions & 13 deletions crates/net/discv4/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,8 @@ use discv5::{
},
ConnectionDirection, ConnectionState,
};
use k256::ecdsa::SigningKey;
use reth_primitives::{H256, H512};
use secp256k1::SecretKey;
use std::{
cell::RefCell,
collections::{btree_map, hash_map::Entry, BTreeMap, HashMap, VecDeque},
Expand Down Expand Up @@ -122,10 +122,10 @@ impl Discv4 {
pub async fn spawn(
local_address: SocketAddr,
local_enr: NodeRecord,
secret_key: SecretKey,
signing_key: SigningKey,
config: Discv4Config,
) -> io::Result<Self> {
let (discv4, service) = Self::bind(local_address, local_enr, secret_key, config).await?;
let (discv4, service) = Self::bind(local_address, local_enr, signing_key, config).await?;

let _ = service.spawn();

Expand All @@ -138,14 +138,15 @@ impl Discv4 {
/// # use std::io;
/// use std::net::SocketAddr;
/// use std::str::FromStr;
/// use k256::ecdsa::{SigningKey, VerifyingKey};
/// use rand::thread_rng;
/// use secp256k1::SECP256K1;
/// use reth_discv4::{Discv4, Discv4Config, NodeId, NodeRecord};
/// # async fn t() -> io::Result<()> {
/// // generate a (random) keypair
/// let mut rng = thread_rng();
/// let (secret_key, pk) = SECP256K1.generate_keypair(&mut rng);
/// let id = NodeId::from_slice(&pk.serialize_uncompressed()[1..]);
/// let signing_key = SigningKey::random(&mut rng);
/// let verifying_key = VerifyingKey::from(&signing_key);
/// let id = NodeId::from_slice(&verifying_key.to_encoded_point(false).as_bytes()[1..]);
///
/// let socket = SocketAddr::from_str("0.0.0.0:0").unwrap();
/// let local_enr = NodeRecord {
Expand All @@ -156,7 +157,7 @@ impl Discv4 {
/// };
/// let config = Discv4Config::default();
///
/// let(discv4, mut service) = Discv4::bind(socket, local_enr, secret_key, config).await.unwrap();
/// let(discv4, mut service) = Discv4::bind(socket, local_enr, signing_key, config).await.unwrap();
///
/// // get an update strea
/// let updates = service.update_stream();
Expand All @@ -172,7 +173,7 @@ impl Discv4 {
pub async fn bind(
local_address: SocketAddr,
mut local_enr: NodeRecord,
secret_key: SecretKey,
signing_key: SigningKey,
config: Discv4Config,
) -> io::Result<(Self, Discv4Service)> {
let socket = UdpSocket::bind(local_address).await?;
Expand All @@ -183,7 +184,7 @@ impl Discv4 {
// We don't expect many commands, so the buffer can be quite small here.
let (to_service, rx) = mpsc::channel(5);
let service =
Discv4Service::new(socket, local_addr, local_enr, secret_key, config, Some(rx));
Discv4Service::new(socket, local_addr, local_enr, signing_key, config, Some(rx));
let discv4 = Discv4 { local_addr, to_service };
Ok((discv4, service))
}
Expand Down Expand Up @@ -240,7 +241,7 @@ pub struct Discv4Service {
/// Local ENR of the server.
local_enr: NodeRecord,
/// The secret key used to sign payloads
secret_key: SecretKey,
signing_key: SigningKey,
/// The UDP socket for sending and receiving messages.
_socket: Arc<UdpSocket>,
/// The spawned UDP tasks.
Expand Down Expand Up @@ -288,7 +289,7 @@ impl Discv4Service {
socket: UdpSocket,
local_address: SocketAddr,
local_enr: NodeRecord,
secret_key: SecretKey,
signing_key: SigningKey,
config: Discv4Config,
commands_rx: Option<mpsc::Receiver<Discv4Command>>,
) -> Self {
Expand Down Expand Up @@ -331,7 +332,7 @@ impl Discv4Service {
local_enr,
_socket: socket,
kbuckets,
secret_key,
signing_key,
_tasks: tasks,
ingress: ingress_rx,
egress: egress_tx,
Expand Down Expand Up @@ -540,7 +541,7 @@ impl Discv4Service {

/// Encodes the packet, sends it and returns the hash.
pub(crate) fn send_packet(&mut self, msg: Message, to: SocketAddr) -> H256 {
let (payload, hash) = msg.encode(&self.secret_key);
let (payload, hash) = msg.encode(&self.signing_key).unwrap();
trace!(r#type=?msg.msg_type(), ?to, ?hash, target = "net::disc", "sending packet");
let _ = self.egress.try_send((payload, to));
hash
Expand Down
20 changes: 11 additions & 9 deletions crates/net/discv4/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ use crate::{
receive_loop, send_loop, Discv4, Discv4Config, Discv4Service, EgressSender, IngressEvent,
IngressReceiver, NodeId, SAFE_MAX_DATAGRAM_NEIGHBOUR_RECORDS,
};
use k256::ecdsa::{SigningKey, VerifyingKey};
use rand::{thread_rng, Rng, RngCore};
use reth_primitives::H256;
use secp256k1::{SecretKey, SECP256K1};
use std::{
collections::{HashMap, HashSet},
io,
Expand All @@ -33,7 +33,7 @@ use tracing::error;
pub struct MockDiscovery {
local_addr: SocketAddr,
local_enr: NodeRecord,
secret_key: SecretKey,
signing_key: SigningKey,
udp: Arc<UdpSocket>,
_tasks: JoinSet<()>,
/// Receiver for incoming messages
Expand All @@ -50,8 +50,9 @@ impl MockDiscovery {
pub async fn new() -> io::Result<(Self, mpsc::Sender<MockCommand>)> {
let mut rng = thread_rng();
let socket = SocketAddr::from_str("0.0.0.0:0").unwrap();
let (secret_key, pk) = SECP256K1.generate_keypair(&mut rng);
let id = NodeId::from_slice(&pk.serialize_uncompressed()[1..]);
let signing_key = SigningKey::random(&mut rng);
let verifying_key = VerifyingKey::from(&signing_key);
let id = NodeId::from_slice(&verifying_key.to_encoded_point(false).as_bytes()[1..]);
let socket = Arc::new(UdpSocket::bind(socket).await?);
let local_addr = socket.local_addr()?;
let local_enr = NodeRecord {
Expand All @@ -78,7 +79,7 @@ impl MockDiscovery {
egress: egress_tx,
local_addr,
local_enr,
secret_key,
signing_key,
udp: socket,
pending_pongs: Default::default(),
pending_neighbours: Default::default(),
Expand Down Expand Up @@ -114,7 +115,7 @@ impl MockDiscovery {

/// Encodes the packet, sends it and returns the hash.
fn send_packet(&mut self, msg: Message, to: SocketAddr) -> H256 {
let (payload, hash) = msg.encode(&self.secret_key);
let (payload, hash) = msg.encode(&self.signing_key);
let _ = self.egress.try_send((payload, to));
hash
}
Expand Down Expand Up @@ -208,12 +209,13 @@ pub async fn create_discv4() -> (Discv4, Discv4Service) {
pub async fn create_discv4_with_config(config: Discv4Config) -> (Discv4, Discv4Service) {
let mut rng = thread_rng();
let socket = SocketAddr::from_str("0.0.0.0:0").unwrap();
let (secret_key, pk) = SECP256K1.generate_keypair(&mut rng);
let id = NodeId::from_slice(&pk.serialize_uncompressed()[1..]);
let signing_key = SigningKey::random(&mut rng);
let verifying_key = VerifyingKey::from(&signing_key);
let id = NodeId::from_slice(&verifying_key.to_encoded_point(false).as_bytes()[1..]);
let external_addr = public_ip::addr().await.unwrap_or_else(|| socket.ip());
let local_enr =
NodeRecord { address: external_addr, tcp_port: socket.port(), udp_port: socket.port(), id };
Discv4::bind(socket, local_enr, secret_key, config).await.unwrap()
Discv4::bind(socket, local_enr, signing_key, config).await.unwrap()
}

pub fn rng_endpoint(rng: &mut impl Rng) -> NodeEndpoint {
Expand Down
Loading

0 comments on commit 47d551d

Please sign in to comment.