Skip to content
This repository has been archived by the owner on Nov 20, 2023. It is now read-only.

Commit

Permalink
Update deps (#35)
Browse files Browse the repository at this point in the history
* Doc fix

* Update secp256k1

* Update k256
  • Loading branch information
vorot93 committed May 24, 2022
1 parent 35a1160 commit a4b959d
Show file tree
Hide file tree
Showing 5 changed files with 66 additions and 45 deletions.
19 changes: 9 additions & 10 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,7 @@ keywords = ["ethereum", "enr", "record", "EIP778", "node"]
repository = "https://github.com/rust-ethereum/enr"
categories = ["cryptography::cryptocurrencies"]
license = "MIT"
exclude = [
".gitignore",
".github/*"
]
exclude = [".gitignore", ".github/*"]

[dependencies]
base64 = "0.13"
Expand All @@ -23,20 +20,22 @@ log = "0.4.8"
rand = "0.8"
rlp = "0.5"
zeroize = "1.1.0"
sha3 = "0.9"
k256 = { version = "0.8", features = ["ecdsa", "zeroize"], optional = true }
sha3 = "0.10"
k256 = { version = "0.11", features = ["ecdsa"], optional = true }
serde = { version = "1.0.110", optional = true }
ed25519-dalek = { version = "1.0.0-pre.4", optional = true }
c-secp256k1 = { package = "secp256k1", version = "0.20", optional = true, features = ["global-context"] }
secp256k1 = { version = "0.22", optional = true, default-features = false, features = [
"global-context",
] }

[dev-dependencies]
rand_07 = { package = "rand", version = "0.7" }
c-secp256k1 = { package = "secp256k1", features = ["rand-std"], version = "0.20" }
secp256k1 = { features = ["rand-std"], version = "0.22" }

[features]
default = ["serde", "k256" ]
default = ["serde", "k256"]
ed25519 = ["ed25519-dalek"]
rust-secp256k1 = ["c-secp256k1"]
rust-secp256k1 = ["secp256k1"]

[lib]
name = "enr"
Expand Down
36 changes: 29 additions & 7 deletions src/keys/k256_key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,12 @@ use k256::{
signature::{DigestVerifier, RandomizedDigestSigner, Signature as _},
Signature, SigningKey, VerifyingKey,
},
elliptic_curve::{generic_array::GenericArray, sec1::UntaggedPointSize},
CompressedPoint, EncodedPoint, Secp256k1,
elliptic_curve::{
sec1::{Coordinates, ToEncodedPoint},
subtle::Choice,
DecompressPoint,
},
AffinePoint, CompressedPoint, EncodedPoint,
};
use rand::rngs::OsRng;
use rlp::DecoderError;
Expand All @@ -24,7 +28,7 @@ impl EnrKey for SigningKey {

fn sign_v4(&self, msg: &[u8]) -> Result<Vec<u8>, SigningError> {
// take a keccak256 hash then sign.
let digest = Keccak256::new().chain(msg);
let digest = Keccak256::new().chain_update(msg);
let signature: Signature = self
.try_sign_digest_with_rng(&mut OsRng, digest)
.map_err(|_| SigningError::new("failed to sign"))?;
Expand All @@ -33,7 +37,7 @@ impl EnrKey for SigningKey {
}

fn public(&self) -> Self::PublicKey {
self.verify_key()
self.verifying_key()
}

fn enr_to_public(content: &BTreeMap<Key, Bytes>) -> Result<Self::PublicKey, DecoderError> {
Expand All @@ -58,12 +62,12 @@ impl EnrKeyUnambiguous for SigningKey {

impl EnrPublicKey for VerifyingKey {
type Raw = CompressedPoint;
type RawUncompressed = GenericArray<u8, UntaggedPointSize<Secp256k1>>;
type RawUncompressed = [u8; 64];

fn verify_v4(&self, msg: &[u8], sig: &[u8]) -> bool {
if let Ok(sig) = k256::ecdsa::Signature::try_from(sig) {
return self
.verify_digest(Keccak256::new().chain(msg), &sig)
.verify_digest(Keccak256::new().chain_update(msg), &sig)
.is_ok();
}
false
Expand All @@ -75,7 +79,25 @@ impl EnrPublicKey for VerifyingKey {
}

fn encode_uncompressed(&self) -> Self::RawUncompressed {
EncodedPoint::from(self).to_untagged_bytes().unwrap()
let p = EncodedPoint::from(self);
let (x, y) = match p.coordinates() {
Coordinates::Compact { .. } | Coordinates::Identity => unreachable!(),
Coordinates::Compressed { x, y_is_odd } => (
x,
*AffinePoint::decompress(x, Choice::from(u8::from(y_is_odd)))
.unwrap()
.to_encoded_point(false)
.y()
.unwrap(),
),
Coordinates::Uncompressed { x, y } => (x, *y),
};

let mut coords = [0; 64];
coords[..32].copy_from_slice(x);
coords[32..].copy_from_slice(&y);

coords
}

fn enr_key(&self) -> Key {
Expand Down
8 changes: 4 additions & 4 deletions src/keys/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,19 +9,19 @@
mod combined;
#[cfg(feature = "ed25519")]
mod ed25519;
#[cfg(any(feature = "k256", doc))]
#[cfg(any(feature = "k256"))]
mod k256_key;
#[cfg(feature = "rust-secp256k1")]
mod rust_secp256k1;

#[cfg(feature = "rust-secp256k1")]
pub use c_secp256k1;
#[cfg(all(feature = "ed25519", feature = "k256"))]
pub use combined::{CombinedKey, CombinedPublicKey};
#[cfg(feature = "ed25519")]
pub use ed25519_dalek;
#[cfg(any(feature = "k256", doc))]
#[cfg(any(feature = "k256"))]
pub use k256;
#[cfg(feature = "rust-secp256k1")]
pub use secp256k1;

use crate::Key;
use bytes::Bytes;
Expand Down
28 changes: 14 additions & 14 deletions src/keys/rust_secp256k1.rs
Original file line number Diff line number Diff line change
@@ -1,23 +1,23 @@
use super::{EnrKey, EnrKeyUnambiguous, EnrPublicKey, SigningError};
use crate::{digest, Key};
use bytes::Bytes;
use c_secp256k1::SECP256K1;
use rlp::DecoderError;
use secp256k1::SECP256K1;
use std::collections::BTreeMap;

/// The ENR key that stores the public key in the ENR record.
pub const ENR_KEY: &str = "secp256k1";

impl EnrKey for c_secp256k1::SecretKey {
type PublicKey = c_secp256k1::PublicKey;
impl EnrKey for secp256k1::SecretKey {
type PublicKey = secp256k1::PublicKey;

fn sign_v4(&self, msg: &[u8]) -> Result<Vec<u8>, SigningError> {
// take a keccak256 hash then sign.
let hash = digest(msg);
let m = c_secp256k1::Message::from_slice(&hash)
let m = secp256k1::Message::from_slice(&hash)
.map_err(|_| SigningError::new("failed to parse secp256k1 digest"))?;
// serialize to an uncompressed 64 byte vector
Ok(SECP256K1.sign(&m, self).serialize_compact().to_vec())
Ok(SECP256K1.sign_ecdsa(&m, self).serialize_compact().to_vec())
}

fn public(&self) -> Self::PublicKey {
Expand All @@ -35,23 +35,23 @@ impl EnrKey for c_secp256k1::SecretKey {
}
}

impl EnrKeyUnambiguous for c_secp256k1::SecretKey {
impl EnrKeyUnambiguous for secp256k1::SecretKey {
fn decode_public(bytes: &[u8]) -> Result<Self::PublicKey, DecoderError> {
// should be encoded in compressed form, i.e 33 byte raw secp256k1 public key
c_secp256k1::PublicKey::from_slice(bytes)
secp256k1::PublicKey::from_slice(bytes)
.map_err(|_| DecoderError::Custom("Invalid Secp256k1 Signature"))
}
}

impl EnrPublicKey for c_secp256k1::PublicKey {
type Raw = [u8; c_secp256k1::constants::PUBLIC_KEY_SIZE];
type RawUncompressed = [u8; c_secp256k1::constants::UNCOMPRESSED_PUBLIC_KEY_SIZE - 1];
impl EnrPublicKey for secp256k1::PublicKey {
type Raw = [u8; secp256k1::constants::PUBLIC_KEY_SIZE];
type RawUncompressed = [u8; secp256k1::constants::UNCOMPRESSED_PUBLIC_KEY_SIZE - 1];

fn verify_v4(&self, msg: &[u8], sig: &[u8]) -> bool {
let msg = digest(msg);
if let Ok(sig) = c_secp256k1::Signature::from_compact(sig) {
if let Ok(msg) = c_secp256k1::Message::from_slice(&msg) {
return SECP256K1.verify(&msg, &sig, self).is_ok();
if let Ok(sig) = secp256k1::ecdsa::Signature::from_compact(sig) {
if let Ok(msg) = secp256k1::Message::from_slice(&msg) {
return SECP256K1.verify_ecdsa(&msg, &sig, self).is_ok();
}
}
false
Expand All @@ -62,7 +62,7 @@ impl EnrPublicKey for c_secp256k1::PublicKey {
}

fn encode_uncompressed(&self) -> Self::RawUncompressed {
let mut out = [0_u8; c_secp256k1::constants::UNCOMPRESSED_PUBLIC_KEY_SIZE - 1];
let mut out = [0_u8; secp256k1::constants::UNCOMPRESSED_PUBLIC_KEY_SIZE - 1];
out.copy_from_slice(&self.serialize_uncompressed()[1..]);
out
}
Expand Down
20 changes: 10 additions & 10 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -199,10 +199,10 @@ use std::{

pub use builder::EnrBuilder;

#[cfg(feature = "rust-secp256k1")]
pub use keys::c_secp256k1;
#[cfg(feature = "k256")]
pub use keys::k256;
#[cfg(feature = "rust-secp256k1")]
pub use keys::secp256k1;
#[cfg(all(feature = "ed25519", feature = "k256"))]
pub use keys::{ed25519_dalek, CombinedKey, CombinedPublicKey};

Expand Down Expand Up @@ -242,13 +242,13 @@ impl<K: EnrKey> Enr<K> {

/// The `NodeId` for the record.
#[must_use]
pub fn node_id(&self) -> NodeId {
pub const fn node_id(&self) -> NodeId {
self.node_id
}

/// The current sequence number of the ENR record.
#[must_use]
pub fn seq(&self) -> u64 {
pub const fn seq(&self) -> u64 {
self.seq
}

Expand Down Expand Up @@ -812,7 +812,7 @@ impl<K: EnrKey> FromStr for Enr<K> {
}
}

#[cfg(any(feature = "serde", doc))]
#[cfg(any(feature = "serde"))]
impl<K: EnrKey> Serialize for Enr<K> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
Expand All @@ -822,7 +822,7 @@ impl<K: EnrKey> Serialize for Enr<K> {
}
}

#[cfg(any(feature = "serde", doc))]
#[cfg(any(feature = "serde"))]
impl<'de, K: EnrKey> Deserialize<'de> for Enr<K> {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
Expand Down Expand Up @@ -1068,9 +1068,9 @@ mod tests {

#[cfg(feature = "rust-secp256k1")]
#[test]
fn test_encode_decode_c_secp256k1() {
let mut rng = c_secp256k1::rand::thread_rng();
let key = c_secp256k1::SecretKey::new(&mut rng);
fn test_encode_decode_secp256k1() {
let mut rng = secp256k1::rand::thread_rng();
let key = secp256k1::SecretKey::new(&mut rng);
let ip = Ipv4Addr::new(127, 0, 0, 1);
let tcp = 3000;

Expand All @@ -1083,7 +1083,7 @@ mod tests {

let encoded_enr = rlp::encode(&enr);

let decoded_enr = rlp::decode::<Enr<c_secp256k1::SecretKey>>(&encoded_enr).unwrap();
let decoded_enr = rlp::decode::<Enr<secp256k1::SecretKey>>(&encoded_enr).unwrap();

assert_eq!(decoded_enr.id(), Some("v4".into()));
assert_eq!(decoded_enr.ip4(), Some(ip));
Expand Down

0 comments on commit a4b959d

Please sign in to comment.