ethereum-types refactor

This commit is contained in:
debris 2017-10-30 10:00:58 -07:00
parent f8e4006ec1
commit 6964a4b065
11 changed files with 535 additions and 18 deletions

View File

@ -1,2 +1,2 @@
[workspace]
members = ["uint", "ethereum-types", "tests"]
members = ["uint", "fixed-hash", "ethereum-types", "tests"]

View File

@ -5,8 +5,9 @@ authors = ["debris <marek.kotewicz@gmail.com>"]
[dependencies]
uint = { path = "../uint", version = "0.1" }
fixed-hash = { path = "../fixed-hash", version = "0.1" }
crunchy = "0.1.5"
[features]
std = ["uint/std"]
heapsizeof = ["uint/heapsizeof"]
std = ["uint/std", "fixed-hash/std"]
heapsizeof = ["uint/heapsizeof", "fixed-hash/heapsizeof"]

View File

@ -0,0 +1,73 @@
use U256;
impl_hash!(H32, 4);
impl_hash!(H64, 8);
impl_hash!(H128, 16);
impl_hash!(H160, 20);
impl_hash!(H256, 32);
impl_hash!(H264, 33);
impl_hash!(H512, 64);
impl_hash!(H520, 65);
impl_hash!(H1024, 128);
impl_hash!(H2048, 256);
impl From<U256> for H256 {
fn from(value: U256) -> H256 {
let mut ret = H256::new();
value.to_big_endian(&mut ret);
ret
}
}
impl<'a> From<&'a U256> for H256 {
fn from(value: &'a U256) -> H256 {
let mut ret: H256 = H256::new();
value.to_big_endian(&mut ret);
ret
}
}
impl From<H256> for U256 {
fn from(value: H256) -> U256 {
U256::from(&value)
}
}
impl<'a> From<&'a H256> for U256 {
fn from(value: &'a H256) -> U256 {
U256::from(value.as_ref() as &[u8])
}
}
impl From<H256> for H160 {
fn from(value: H256) -> H160 {
let mut ret = H160::new();
ret.0.copy_from_slice(&value[12..32]);
ret
}
}
impl From<H256> for H64 {
fn from(value: H256) -> H64 {
let mut ret = H64::new();
ret.0.copy_from_slice(&value[20..28]);
ret
}
}
impl From<H160> for H256 {
fn from(value: H160) -> H256 {
let mut ret = H256::new();
ret.0[12..32].copy_from_slice(&value);
ret
}
}
impl<'a> From<&'a H160> for H256 {
fn from(value: &'a H160) -> H256 {
let mut ret = H256::new();
ret.0[12..32].copy_from_slice(value);
ret
}
}

View File

@ -6,7 +6,15 @@ extern crate core;
extern crate crunchy;
#[macro_use]
extern crate uint as uint_crate;
#[macro_use]
extern crate fixed_hash;
mod hash;
mod uint;
pub use uint::{U128, U256, U512};
pub use hash::{H32, H64, H128, H160, H256, H264, H512, H520, H1024, H2048};
pub type Address = H160;
pub type Secret = H256;
pub type Signature = H520;

14
fixed-hash/Cargo.toml Normal file
View File

@ -0,0 +1,14 @@
[package]
name = "fixed-hash"
version = "0.1.0"
authors = ["debris <marek.kotewicz@gmail.com>"]
[dependencies]
heapsize = { version = "0.4", optional = true }
libc = { version = "0.2", default-features = false }
rand = { version = "0.3", optional = true }
rustc-hex = { version = "1.0", optional = true }
[features]
std = ["rustc-hex", "rand"]
heapsizeof = ["heapsize"]

395
fixed-hash/src/hash.rs Normal file
View File

@ -0,0 +1,395 @@
// Copyright 2015-2017 Parity Technologies
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/// Return `s` without the `0x` at the beginning of it, if any.
pub fn clean_0x(s: &str) -> &str {
if s.starts_with("0x") {
&s[2..]
} else {
s
}
}
#[macro_export]
macro_rules! impl_hash {
($from: ident, $size: expr) => {
#[repr(C)]
/// Unformatted binary data of fixed length.
pub struct $from (pub [u8; $size]);
impl From<[u8; $size]> for $from {
fn from(bytes: [u8; $size]) -> Self {
$from(bytes)
}
}
impl From<$from> for [u8; $size] {
fn from(s: $from) -> Self {
s.0
}
}
impl ::core::ops::Deref for $from {
type Target = [u8];
#[inline]
fn deref(&self) -> &[u8] {
&self.0
}
}
impl AsRef<[u8]> for $from {
#[inline]
fn as_ref(&self) -> &[u8] {
&self.0
}
}
impl ::core::ops::DerefMut for $from {
#[inline]
fn deref_mut(&mut self) -> &mut [u8] {
&mut self.0
}
}
impl $from {
/// Create a new, zero-initialised, instance.
pub fn new() -> $from {
$from([0; $size])
}
/// Synonym for `new()`. Prefer to new as it's more readable.
pub fn zero() -> $from {
$from([0; $size])
}
/// Get the size of this object in bytes.
pub fn len() -> usize {
$size
}
#[inline]
/// Assign self to be of the same value as a slice of bytes of length `len()`.
pub fn clone_from_slice(&mut self, src: &[u8]) -> usize {
let min = ::core::cmp::min($size, src.len());
self.0[..min].copy_from_slice(&src[..min]);
min
}
/// Convert a slice of bytes of length `len()` to an instance of this type.
pub fn from_slice(src: &[u8]) -> Self {
let mut r = Self::new();
r.clone_from_slice(src);
r
}
/// Copy the data of this object into some mutable slice of length `len()`.
pub fn copy_to(&self, dest: &mut[u8]) {
let min = ::core::cmp::min($size, dest.len());
dest[..min].copy_from_slice(&self.0[..min]);
}
/// Returns `true` if all bits set in `b` are also set in `self`.
pub fn contains<'a>(&'a self, b: &'a Self) -> bool {
&(b & self) == b
}
/// Returns `true` if no bits are set.
pub fn is_zero(&self) -> bool {
self.eq(&Self::new())
}
/// Returns the lowest 8 bytes interpreted as a BigEndian integer.
pub fn low_u64(&self) -> u64 {
let mut ret = 0u64;
for i in 0..::core::cmp::min($size, 8) {
ret |= (self.0[$size - 1 - i] as u64) << (i * 8);
}
ret
}
impl_std_for_hash_internals!($from, $size);
}
impl ::core::fmt::Debug for $from {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
for i in &self.0[..] {
write!(f, "{:02x}", i)?;
}
Ok(())
}
}
impl ::core::fmt::Display for $from {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
for i in &self.0[0..2] {
write!(f, "{:02x}", i)?;
}
write!(f, "")?;
for i in &self.0[$size - 2..$size] {
write!(f, "{:02x}", i)?;
}
Ok(())
}
}
impl Copy for $from {}
#[cfg_attr(feature="dev", allow(expl_impl_clone_on_copy))]
impl Clone for $from {
fn clone(&self) -> $from {
let mut ret = $from::new();
ret.0.copy_from_slice(&self.0);
ret
}
}
impl Eq for $from {}
impl PartialEq for $from {
fn eq(&self, other: &Self) -> bool {
unsafe { $crate::libc::memcmp(self.0.as_ptr() as *const $crate::libc::c_void, other.0.as_ptr() as *const $crate::libc::c_void, $size) == 0 }
}
}
impl Ord for $from {
fn cmp(&self, other: &Self) -> ::core::cmp::Ordering {
let r = unsafe { $crate::libc::memcmp(self.0.as_ptr() as *const $crate::libc::c_void, other.0.as_ptr() as *const $crate::libc::c_void, $size) };
if r < 0 { return ::core::cmp::Ordering::Less }
if r > 0 { return ::core::cmp::Ordering::Greater }
return ::core::cmp::Ordering::Equal;
}
}
impl PartialOrd for $from {
fn partial_cmp(&self, other: &Self) -> Option<::core::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl ::core::hash::Hash for $from {
fn hash<H>(&self, state: &mut H) where H: ::core::hash::Hasher {
state.write(&self.0);
state.finish();
}
}
impl ::core::ops::Index<usize> for $from {
type Output = u8;
fn index(&self, index: usize) -> &u8 {
&self.0[index]
}
}
impl ::core::ops::IndexMut<usize> for $from {
fn index_mut(&mut self, index: usize) -> &mut u8 {
&mut self.0[index]
}
}
impl ::core::ops::Index<::core::ops::Range<usize>> for $from {
type Output = [u8];
fn index(&self, index: ::core::ops::Range<usize>) -> &[u8] {
&self.0[index]
}
}
impl ::core::ops::IndexMut<::core::ops::Range<usize>> for $from {
fn index_mut(&mut self, index: ::core::ops::Range<usize>) -> &mut [u8] {
&mut self.0[index]
}
}
impl ::core::ops::Index<::core::ops::RangeFull> for $from {
type Output = [u8];
fn index(&self, _index: ::core::ops::RangeFull) -> &[u8] {
&self.0
}
}
impl ::core::ops::IndexMut<::core::ops::RangeFull> for $from {
fn index_mut(&mut self, _index: ::core::ops::RangeFull) -> &mut [u8] {
&mut self.0
}
}
/// `BitOr` on references
impl<'a> ::core::ops::BitOr for &'a $from {
type Output = $from;
fn bitor(self, rhs: Self) -> Self::Output {
let mut ret: $from = $from::default();
for i in 0..$size {
ret.0[i] = self.0[i] | rhs.0[i];
}
ret
}
}
/// Moving `BitOr`
impl ::core::ops::BitOr for $from {
type Output = $from;
fn bitor(self, rhs: Self) -> Self::Output {
&self | &rhs
}
}
/// `BitAnd` on references
impl <'a> ::core::ops::BitAnd for &'a $from {
type Output = $from;
fn bitand(self, rhs: Self) -> Self::Output {
let mut ret: $from = $from::default();
for i in 0..$size {
ret.0[i] = self.0[i] & rhs.0[i];
}
ret
}
}
/// Moving `BitAnd`
impl ::core::ops::BitAnd for $from {
type Output = $from;
fn bitand(self, rhs: Self) -> Self::Output {
&self & &rhs
}
}
/// `BitXor` on references
impl <'a> ::core::ops::BitXor for &'a $from {
type Output = $from;
fn bitxor(self, rhs: Self) -> Self::Output {
let mut ret: $from = $from::default();
for i in 0..$size {
ret.0[i] = self.0[i] ^ rhs.0[i];
}
ret
}
}
/// Moving `BitXor`
impl ::core::ops::BitXor for $from {
type Output = $from;
fn bitxor(self, rhs: Self) -> Self::Output {
&self ^ &rhs
}
}
impl Default for $from {
fn default() -> Self { $from::new() }
}
impl From<u64> for $from {
fn from(mut value: u64) -> $from {
let mut ret = $from::new();
for i in 0..8 {
if i < $size {
ret.0[$size - i - 1] = (value & 0xff) as u8;
value >>= 8;
}
}
ret
}
}
impl<'a> From<&'a [u8]> for $from {
fn from(s: &'a [u8]) -> $from {
$from::from_slice(s)
}
}
impl_std_for_hash!($from, $size);
}
}
#[cfg(feature="std")]
#[macro_export]
#[doc(hidden)]
macro_rules! impl_std_for_hash {
($from: ident, $size: tt) => {
impl $from {
/// Get a hex representation.
pub fn hex(&self) -> String {
format!("{:?}", self)
}
}
impl $crate::rand::Rand for $from {
fn rand<R: $crate::rand::Rng>(r: &mut R) -> Self {
let mut hash = $from::new();
r.fill_bytes(&mut hash.0);
hash
}
}
impl ::core::str::FromStr for $from {
type Err = $crate::rustc_hex::FromHexError;
fn from_str(s: &str) -> Result<$from, $crate::rustc_hex::FromHexError> {
use $crate::rustc_hex::FromHex;
let a = s.from_hex()?;
if a.len() != $size {
return Err($crate::rustc_hex::FromHexError::InvalidHexLength);
}
let mut ret = [0; $size];
ret.copy_from_slice(&a);
Ok($from(ret))
}
}
impl From<&'static str> for $from {
fn from(s: &'static str) -> $from {
let s = $crate::clean_0x(s);
if s.len() % 2 == 1 {
("0".to_owned() + s).parse().unwrap()
} else {
s.parse().unwrap()
}
}
}
}
}
#[cfg(not(feature="std"))]
#[macro_export]
#[doc(hidden)]
macro_rules! impl_std_for_hash {
($from: ident, $size: tt) => {}
}
#[cfg(feature="std")]
#[macro_export]
#[doc(hidden)]
macro_rules! impl_std_for_hash_internals {
($from: ident, $size: tt) => {
/// Create a new, cryptographically random, instance.
pub fn random() -> $from {
let mut hash = $from::new();
hash.randomize();
hash
}
/// Assign self have a cryptographically random value.
pub fn randomize(&mut self) {
let mut rng = $crate::rand::OsRng::new().unwrap();
*self = $crate::rand::Rand::rand(&mut rng);
}
}
}
#[cfg(not(feature="std"))]
#[macro_export]
#[doc(hidden)]
macro_rules! impl_std_for_hash_internals {
($from: ident, $size: tt) => {}
}

29
fixed-hash/src/lib.rs Normal file
View File

@ -0,0 +1,29 @@
// Copyright 2015-2017 Parity Technologies
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#[doc(hidden)]
pub extern crate libc;
#[cfg(feature="heapsizeof")]
#[doc(hidden)]
pub extern crate heapsize;
#[cfg(feature="std")]
#[doc(hidden)]
pub extern crate core;
#[cfg(feature="std")]
#[doc(hidden)]
pub extern crate rustc_hex;
#[cfg(feature="std")]
#[doc(hidden)]
pub extern crate rand;
mod hash;
pub use hash::*;

View File

@ -4,7 +4,7 @@ version = "0.1.0"
authors = ["debris <marek.kotewicz@gmail.com>"]
[dependencies]
uint = { path = "../uint" }
ethereum-types = { path ="../ethereum-types", features = ["std", "heapsizeof"] }
crunchy = "0.1.5"
ethereum-types = { path ="../ethereum-types", features = ["std", "heapsizeof"] }
quickcheck = "0.4"
uint = { path = "../uint" }

View File

@ -1,14 +1,14 @@
extern crate core;
#[cfg(test)]
#[macro_use]
extern crate uint;
extern crate ethereum_types;
#[cfg(test)]
#[macro_use]
extern crate crunchy;
#[cfg(test)]
#[macro_use]
extern crate quickcheck;
//#[macro_use]
//extern crate uint;
//extern crate rustc_hex;
mod uint_tests;
#[cfg(test)]
pub mod uint_tests;

View File

@ -975,7 +975,7 @@ fn trailing_zeros() {
assert_eq!(U256::from("0000000000000000000000000000000000000000000000000000000000000000").trailing_zeros(), 256);
}
mod laws {
pub mod laws {
construct_uint!(U128, 2);
construct_uint!(U256, 4);
construct_uint!(U512, 8);
@ -1013,7 +1013,7 @@ mod laws {
($mod_name:ident, $uint_ty:ident) => {
mod $mod_name {
use quickcheck::TestResult;
use super::{U128, U256, U512};
use super::{$uint_ty};
quickcheck! {
fn associative_add(x: $uint_ty, y: $uint_ty, z: $uint_ty) -> TestResult {

View File

@ -12,16 +12,13 @@ build = "build.rs"
rustc_version = "0.2"
[dependencies]
rustc-hex = { version = "1.0", optional = true }
heapsize = { version = "0.4", optional = true }
byteorder = { version = "1", default-features = false }
[dev-dependencies]
quickcheck = "0.4"
heapsize = { version = "0.4", optional = true }
rustc-hex = { version = "1.0", optional = true }
[features]
heapsizeof = ["heapsize", "std"]
std = ["rustc-hex"]
heapsizeof = ["heapsize"]
[[example]]
name = "modular"