diff --git a/.travis.yml b/.travis.yml index 5950b71dc..f3d685bb4 100644 --- a/.travis.yml +++ b/.travis.yml @@ -18,6 +18,7 @@ matrix: - cargo install cross script: - cross test --target=aarch64-linux-android -p parity-util-mem + - cross test --target=mips64-unknown-linux-gnuabi64 -p uint - os: osx osx_image: xcode11.3 addons: @@ -26,6 +27,7 @@ matrix: allow_failures: - rust: nightly install: + - rustup target add wasm32-unknown-unknown - curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.3/install.sh | sh - source ~/.nvm/nvm.sh - nvm install --lts @@ -42,6 +44,7 @@ script: cd contract-address/ && cargo test --features=external_doc && cd ..; fi - cd ethbloom/ && cargo test --no-default-features --features="rustc-hex" && cargo check --benches && cd .. + - cd ethereum-types/ && cargo build --no-default-features --features="serialize,rlp" --target=wasm32-unknown-unknown && cd .. - cd fixed-hash/ && cargo test --all-features && cargo test --no-default-features --features="byteorder,rustc-hex" && cd .. - cd uint/ && cargo test --all-features && cargo test --no-default-features && cd .. - cd keccak-hash/ && cargo test --no-default-features && cd .. diff --git a/Cargo.toml b/Cargo.toml index 019b989de..c3380e0da 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -14,7 +14,6 @@ members = [ "plain_hasher", "rlp", "rlp-derive", - "runtime", "transaction-pool", "trace-time", "triehash", diff --git a/contract-address/CHANGELOG.md b/contract-address/CHANGELOG.md index a9b2a3a0b..583ee8569 100644 --- a/contract-address/CHANGELOG.md +++ b/contract-address/CHANGELOG.md @@ -1,11 +1,20 @@ # Changelog -The format is based on [Keep a Changelog]. +The format is based on [Keep a Changelog]. [Keep a Changelog]: http://keepachangelog.com/en/1.0.0/ ## [Unreleased] -## [0.9.0] - 2020-03-16 +## [0.6.0] - 2021-01-27 +### Breaking +- Updated `ethereum-types` to 0.11. [#510](https://github.com/paritytech/parity-common/pull/510) +- Updated `keccak-hash` to 0.7. [#510](https://github.com/paritytech/parity-common/pull/510) + +## [0.5.0] - 2021-01-05 +### Breaking +- Updated `ethereum-types` to 0.10. [#463](https://github.com/paritytech/parity-common/pull/463) + +## [0.4.0] - 2020-03-16 - License changed from MIT to dual MIT/Apache2. [#342](https://github.com/paritytech/parity-common/pull/342) - Updated dependencies. [#361](https://github.com/paritytech/parity-common/pull/361) diff --git a/contract-address/Cargo.toml b/contract-address/Cargo.toml index b8a0b7993..993ffe26c 100644 --- a/contract-address/Cargo.toml +++ b/contract-address/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "contract-address" -version = "0.4.0" +version = "0.6.0" authors = ["Parity Technologies "] license = "MIT OR Apache-2.0" homepage = "https://github.com/paritytech/parity-common" @@ -11,9 +11,9 @@ edition = "2018" readme = "README.md" [dependencies] -ethereum-types = { version = "0.9.0", path = "../ethereum-types" } -rlp = { version = "0.4", path = "../rlp" } -keccak-hash = { version = "0.5", path = "../keccak-hash", default-features = false } +ethereum-types = { version = "0.11.0", path = "../ethereum-types" } +rlp = { version = "0.5", path = "../rlp" } +keccak-hash = { version = "0.7", path = "../keccak-hash", default-features = false } [features] default = [] diff --git a/ethbloom/CHANGELOG.md b/ethbloom/CHANGELOG.md index 67480095f..45781b2e4 100644 --- a/ethbloom/CHANGELOG.md +++ b/ethbloom/CHANGELOG.md @@ -6,6 +6,17 @@ The format is based on [Keep a Changelog]. ## [Unreleased] +## [0.11.0] - 2021-01-27 +### Breaking +- Updated `impl-codec` to 0.5. [#510](https://github.com/paritytech/parity-common/pull/510) + +### Potentially-breaking +- `serialize` feature no longer pulls `std`. [#503](https://github.com/paritytech/parity-common/pull/503) + +## [0.10.0] - 2021-01-05 +### Breaking +- Updated `rlp` to 0.5. [#463](https://github.com/paritytech/parity-common/pull/463) + ## [0.9.2] - 2020-05-18 - Added `codec` feature. [#393](https://github.com/paritytech/parity-common/pull/393) diff --git a/ethbloom/Cargo.toml b/ethbloom/Cargo.toml index f99e61a6c..61a759bad 100644 --- a/ethbloom/Cargo.toml +++ b/ethbloom/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "ethbloom" -version = "0.9.2" +version = "0.11.0" authors = ["Parity Technologies "] description = "Ethereum bloom filter" license = "MIT OR Apache-2.0" @@ -12,22 +12,23 @@ edition = "2018" [dependencies] tiny-keccak = { version = "2.0", features = ["keccak"] } crunchy = { version = "0.2.2", default-features = false, features = ["limit_256"] } -fixed-hash = { path = "../fixed-hash", version = "0.6", default-features = false } +fixed-hash = { path = "../fixed-hash", version = "0.7", default-features = false } impl-serde = { path = "../primitive-types/impls/serde", version = "0.3", default-features = false, optional = true } -impl-rlp = { path = "../primitive-types/impls/rlp", version = "0.2", default-features = false } -impl-codec = { version = "0.4.1", path = "../primitive-types/impls/codec", default-features = false, optional = true } +impl-rlp = { path = "../primitive-types/impls/rlp", version = "0.3", default-features = false, optional = true } +impl-codec = { version = "0.5.0", path = "../primitive-types/impls/codec", default-features = false, optional = true } [dev-dependencies] criterion = "0.3.0" -rand = "0.7.2" +rand = "0.8.0" hex-literal = "0.3.1" [features] -default = ["std", "serialize", "rustc-hex"] +default = ["std", "rlp", "serialize", "rustc-hex"] std = ["fixed-hash/std", "crunchy/std"] -serialize = ["std", "impl-serde"] +serialize = ["impl-serde"] rustc-hex = ["fixed-hash/rustc-hex"] arbitrary = ["fixed-hash/arbitrary"] +rlp = ["impl-rlp"] codec = ["impl-codec"] [[bench]] diff --git a/ethbloom/src/lib.rs b/ethbloom/src/lib.rs index 7b18ec9ee..aa8993aae 100644 --- a/ethbloom/src/lib.rs +++ b/ethbloom/src/lib.rs @@ -56,6 +56,7 @@ use crunchy::unroll; use fixed_hash::*; #[cfg(feature = "codec")] use impl_codec::impl_fixed_hash_codec; +#[cfg(feature = "rlp")] use impl_rlp::impl_fixed_hash_rlp; #[cfg(feature = "serialize")] use impl_serde::impl_fixed_hash_serde; @@ -69,6 +70,7 @@ construct_fixed_hash! { /// Bloom hash type with 256 bytes (2048 bits) size. pub struct Bloom(BLOOM_SIZE); } +#[cfg(feature = "rlp")] impl_fixed_hash_rlp!(Bloom, BLOOM_SIZE); #[cfg(feature = "serialize")] impl_fixed_hash_serde!(Bloom, BLOOM_SIZE); diff --git a/ethereum-types/CHANGELOG.md b/ethereum-types/CHANGELOG.md index 058a2d34c..cfc8d223b 100644 --- a/ethereum-types/CHANGELOG.md +++ b/ethereum-types/CHANGELOG.md @@ -6,6 +6,20 @@ The format is based on [Keep a Changelog]. ## [Unreleased] +## [0.11.0] - 2021-01-27 +### Breaking +- Updated `ethbloom` to 0.11. [#510](https://github.com/paritytech/parity-common/pull/510) +- Updated `primitive-types` to 0.9. [#510](https://github.com/paritytech/parity-common/pull/510) +- Updated `impl-codec` to 0.5. [#510](https://github.com/paritytech/parity-common/pull/510) + +### Potentially-breaking +- `serialize` feature no longer pulls `std`. [#503](https://github.com/paritytech/parity-common/pull/503) + +## [0.10.0] - 2021-01-05 +### Breaking +- Updated `rlp` to 0.5. [#463](https://github.com/paritytech/parity-common/pull/463) +- Updated `uint` to 0.9. [#486](https://github.com/paritytech/parity-common/pull/486) + ## [0.9.2] - 2020-05-18 - Added `codec` feature. [#393](https://github.com/paritytech/parity-common/pull/393) diff --git a/ethereum-types/Cargo.toml b/ethereum-types/Cargo.toml index 496a5f88a..dfe86dc75 100644 --- a/ethereum-types/Cargo.toml +++ b/ethereum-types/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "ethereum-types" -version = "0.9.2" +version = "0.11.0" authors = ["Parity Technologies "] license = "MIT OR Apache-2.0" homepage = "https://github.com/paritytech/parity-common" @@ -8,20 +8,22 @@ description = "Ethereum types" edition = "2018" [dependencies] -ethbloom = { path = "../ethbloom", version = "0.9", default-features = false } -fixed-hash = { path = "../fixed-hash", version = "0.6", default-features = false, features = ["byteorder", "rustc-hex"] } -uint-crate = { path = "../uint", package = "uint", version = "0.8", default-features = false } -primitive-types = { path = "../primitive-types", version = "0.7", features = ["rlp", "byteorder", "rustc-hex"], default-features = false } +ethbloom = { path = "../ethbloom", version = "0.11", default-features = false } +fixed-hash = { path = "../fixed-hash", version = "0.7", default-features = false, features = ["byteorder", "rustc-hex"] } +uint-crate = { path = "../uint", package = "uint", version = "0.9", default-features = false } +primitive-types = { path = "../primitive-types", version = "0.9", features = ["byteorder", "rustc-hex"], default-features = false } impl-serde = { path = "../primitive-types/impls/serde", version = "0.3.0", default-features = false, optional = true } -impl-rlp = { path = "../primitive-types/impls/rlp", version = "0.2", default-features = false } -impl-codec = { version = "0.4.1", path = "../primitive-types/impls/codec", default-features = false, optional = true } +impl-rlp = { path = "../primitive-types/impls/rlp", version = "0.3", default-features = false, optional = true } +impl-codec = { version = "0.5.0", path = "../primitive-types/impls/codec", default-features = false, optional = true } [dev-dependencies] serde_json = "1.0.41" [features] -default = ["std", "serialize"] +default = ["std", "rlp", "serialize"] std = ["uint-crate/std", "fixed-hash/std", "ethbloom/std", "primitive-types/std"] -serialize = ["std", "impl-serde", "primitive-types/serde", "ethbloom/serialize"] +serialize = ["impl-serde", "primitive-types/serde_no_std", "ethbloom/serialize"] arbitrary = ["ethbloom/arbitrary", "fixed-hash/arbitrary", "uint-crate/arbitrary"] +rlp = ["impl-rlp", "ethbloom/rlp", "primitive-types/rlp"] codec = ["impl-codec", "ethbloom/codec"] +num-traits = ["primitive-types/num-traits"] diff --git a/ethereum-types/src/hash.rs b/ethereum-types/src/hash.rs index 25f00557d..596f0fede 100644 --- a/ethereum-types/src/hash.rs +++ b/ethereum-types/src/hash.rs @@ -10,6 +10,7 @@ use crate::{U128, U256, U512, U64}; use fixed_hash::*; #[cfg(feature = "codec")] use impl_codec::impl_fixed_hash_codec; +#[cfg(feature = "rlp")] use impl_rlp::impl_fixed_hash_rlp; #[cfg(feature = "serialize")] use impl_serde::impl_fixed_hash_serde; @@ -22,6 +23,7 @@ pub trait BigEndianHash { } construct_fixed_hash! { pub struct H32(4); } +#[cfg(feature = "rlp")] impl_fixed_hash_rlp!(H32, 4); #[cfg(feature = "serialize")] impl_fixed_hash_serde!(H32, 4); @@ -29,6 +31,7 @@ impl_fixed_hash_serde!(H32, 4); impl_fixed_hash_codec!(H32, 4); construct_fixed_hash! { pub struct H64(8); } +#[cfg(feature = "rlp")] impl_fixed_hash_rlp!(H64, 8); #[cfg(feature = "serialize")] impl_fixed_hash_serde!(H64, 8); @@ -36,6 +39,7 @@ impl_fixed_hash_serde!(H64, 8); impl_fixed_hash_codec!(H64, 8); construct_fixed_hash! { pub struct H128(16); } +#[cfg(feature = "rlp")] impl_fixed_hash_rlp!(H128, 16); #[cfg(feature = "serialize")] impl_fixed_hash_serde!(H128, 16); @@ -46,6 +50,7 @@ pub use primitive_types::H160; pub use primitive_types::H256; construct_fixed_hash! { pub struct H264(33); } +#[cfg(feature = "rlp")] impl_fixed_hash_rlp!(H264, 33); #[cfg(feature = "serialize")] impl_fixed_hash_serde!(H264, 33); @@ -55,6 +60,7 @@ impl_fixed_hash_codec!(H264, 33); pub use primitive_types::H512; construct_fixed_hash! { pub struct H520(65); } +#[cfg(feature = "rlp")] impl_fixed_hash_rlp!(H520, 65); #[cfg(feature = "serialize")] impl_fixed_hash_serde!(H520, 65); @@ -128,6 +134,11 @@ mod tests { } } + #[test] + fn test_parse_0x() { + assert!("0x0000000000000000000000000000000000000000000000000000000000000000".parse::().is_ok()) + } + #[test] fn test_serialize_invalid() { assert!(ser::from_str::("\"0x000000000000000000000000000000000000000000000000000000000000000\"") diff --git a/ethereum-types/src/lib.rs b/ethereum-types/src/lib.rs index d94ae57c0..56963f28d 100644 --- a/ethereum-types/src/lib.rs +++ b/ethereum-types/src/lib.rs @@ -13,7 +13,7 @@ mod uint; pub use ethbloom::{Bloom, BloomRef, Input as BloomInput}; pub use hash::{BigEndianHash, H128, H160, H256, H264, H32, H512, H520, H64}; -pub use uint::{FromDecStrErr, U128, U256, U512, U64}; +pub use uint::{FromDecStrErr, FromStrRadixErr, FromStrRadixErrKind, U128, U256, U512, U64}; pub type Address = H160; pub type Secret = H256; diff --git a/ethereum-types/src/uint.rs b/ethereum-types/src/uint.rs index 881e0ecd6..eaf9bbf49 100644 --- a/ethereum-types/src/uint.rs +++ b/ethereum-types/src/uint.rs @@ -8,17 +8,19 @@ #[cfg(feature = "codec")] use impl_codec::impl_uint_codec; +#[cfg(feature = "rlp")] use impl_rlp::impl_uint_rlp; #[cfg(feature = "serialize")] use impl_serde::impl_uint_serde; use uint_crate::*; -pub use uint_crate::FromDecStrErr; +pub use uint_crate::{FromDecStrErr, FromStrRadixErr, FromStrRadixErrKind}; construct_uint! { /// Unsigned 64-bit integer. pub struct U64(1); } +#[cfg(feature = "rlp")] impl_uint_rlp!(U64, 1); #[cfg(feature = "serialize")] impl_uint_serde!(U64, 1); diff --git a/fixed-hash/CHANGELOG.md b/fixed-hash/CHANGELOG.md index 6db7b6e76..b74c4b3e4 100644 --- a/fixed-hash/CHANGELOG.md +++ b/fixed-hash/CHANGELOG.md @@ -6,6 +6,10 @@ The format is based on [Keep a Changelog]. ## [Unreleased] +## [0.7.0] - 2021-01-05 +### Breaking +- Updated `rand` to 0.8. [#488](https://github.com/paritytech/parity-common/pull/488) + ## [0.6.1] - 2020-04-27 - Added `arbitrary` feature. [#378](https://github.com/paritytech/parity-common/pull/378) diff --git a/fixed-hash/Cargo.toml b/fixed-hash/Cargo.toml index c8e85585f..23c6c5079 100644 --- a/fixed-hash/Cargo.toml +++ b/fixed-hash/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "fixed-hash" -version = "0.6.1" +version = "0.7.0" authors = ["Parity Technologies "] license = "MIT OR Apache-2.0" homepage = "https://github.com/paritytech/parity-common" @@ -14,16 +14,17 @@ edition = "2018" features = ["quickcheck", "api-dummy"] [dependencies] -byteorder = { version = "1.3.2", optional = true, default-features = false } +byteorder = { version = "1.4.2", optional = true, default-features = false } quickcheck = { version = "0.9.0", optional = true } -rand = { version = "0.7.2", optional = true, default-features = false } +rand = { version = "0.8.0", optional = true, default-features = false } rustc-hex = { version = "2.0.1", optional = true, default-features = false } static_assertions = "1.0.0" arbitrary = { version = "0.4", optional = true } [dev-dependencies] -rand_xorshift = "0.2.0" +rand_xorshift = "0.3.0" criterion = "0.3.0" +rand = { version = "0.8.0", default-features = false, features = ["std_rng"] } [features] default = ["std", "rand", "rustc-hex", "byteorder"] diff --git a/fixed-hash/src/hash.rs b/fixed-hash/src/hash.rs index a971b4136..dd80df6d8 100644 --- a/fixed-hash/src/hash.rs +++ b/fixed-hash/src/hash.rs @@ -24,9 +24,9 @@ /// ``` /// use fixed_hash::construct_fixed_hash; /// construct_fixed_hash!{ -/// /// My unformatted 160 bytes sized hash type. -/// #[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))] -/// pub struct H160(20); +/// /// My unformatted 160 bytes sized hash type. +/// #[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))] +/// pub struct H160(20); /// } /// assert_eq!(std::mem::size_of::(), 20); /// ``` @@ -588,6 +588,7 @@ macro_rules! impl_rustc_hex_for_fixed_hash { /// - When encountering invalid non hex-digits /// - Upon empty string input or invalid input length in general fn from_str(input: &str) -> $crate::core_::result::Result<$name, $crate::rustc_hex::FromHexError> { + let input = input.strip_prefix("0x").unwrap_or(input); let mut iter = $crate::rustc_hex::FromHexIter::new(input); let mut result = Self::zero(); for byte in result.as_mut() { diff --git a/fixed-hash/src/tests.rs b/fixed-hash/src/tests.rs index 33c1956b7..5a5f5d94d 100644 --- a/fixed-hash/src/tests.rs +++ b/fixed-hash/src/tests.rs @@ -244,23 +244,8 @@ mod rand { #[test] fn random() { - let default_seed = ::Seed::default(); - let mut rng = StdRng::from_seed(default_seed); - assert_eq!(H32::random_using(&mut rng), H32::from([0x76, 0xa0, 0x40, 0x53])); - } - - #[test] - fn randomize() { - let default_seed = ::Seed::default(); - let mut rng = StdRng::from_seed(default_seed); - assert_eq!( - { - let mut ret = H32::zero(); - ret.randomize_using(&mut rng); - ret - }, - H32::from([0x76, 0xa0, 0x40, 0x53]) - ) + let mut rng = StdRng::seed_from_u64(123); + assert_eq!(H32::random_using(&mut rng), H32::from([0xeb, 0x96, 0xaf, 0x1c])); } } diff --git a/keccak-hash/CHANGELOG.md b/keccak-hash/CHANGELOG.md index e8580f5d2..ce980bbdf 100644 --- a/keccak-hash/CHANGELOG.md +++ b/keccak-hash/CHANGELOG.md @@ -6,6 +6,14 @@ The format is based on [Keep a Changelog]. ## [Unreleased] +## [0.7.0] - 2021-01-27 +### Breaking +- Updated `primitive-types` to 0.9. [#510](https://github.com/paritytech/parity-common/pull/510) + +## [0.6.0] - 2021-01-05 +### Breaking +- Updated `primitive-types` to 0.8. [#463](https://github.com/paritytech/parity-common/pull/463) + ## [0.5.1] - 2020-04-10 - Added `keccak256_range` and `keccak512_range` functions. [#370](https://github.com/paritytech/parity-common/pull/370) diff --git a/keccak-hash/Cargo.toml b/keccak-hash/Cargo.toml index c663c66c5..6f1f29ee1 100644 --- a/keccak-hash/Cargo.toml +++ b/keccak-hash/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "keccak-hash" -version = "0.5.1" +version = "0.7.0" description = "`keccak-hash` is a set of utility functions to facilitate working with Keccak hashes (256/512 bits long)." authors = ["Parity Technologies "] repository = "https://github.com/paritytech/parity-common" @@ -10,10 +10,10 @@ edition = "2018" [dependencies] tiny-keccak = { version = "2.0", features = ["keccak"] } -primitive-types = { path = "../primitive-types", version = "0.7", default-features = false } +primitive-types = { path = "../primitive-types", version = "0.9", default-features = false } [dev-dependencies] -tempdir = "0.3.7" +tempfile = "3.1.0" criterion = "0.3.0" [features] diff --git a/keccak-hash/src/lib.rs b/keccak-hash/src/lib.rs index dbad92af5..e01f6156d 100644 --- a/keccak-hash/src/lib.rs +++ b/keccak-hash/src/lib.rs @@ -189,7 +189,7 @@ mod tests { use std::io::{BufReader, Write}; // given - let tmpdir = tempdir::TempDir::new("keccak").unwrap(); + let tmpdir = tempfile::Builder::new().prefix("keccak").tempdir().unwrap(); let mut path = tmpdir.path().to_owned(); path.push("should_keccak_a_file"); // Prepare file diff --git a/kvdb-memorydb/CHANGELOG.md b/kvdb-memorydb/CHANGELOG.md index 89b2a4ed0..a5d9fa532 100644 --- a/kvdb-memorydb/CHANGELOG.md +++ b/kvdb-memorydb/CHANGELOG.md @@ -6,6 +6,15 @@ The format is based on [Keep a Changelog]. ## [Unreleased] +## [0.9.0] - 2021-01-27 +### Breaking +- Updated `parity-util-mem` to 0.9. [#510](https://github.com/paritytech/parity-common/pull/510) +- Updated `kvdb` to 0.9. [#510](https://github.com/paritytech/parity-common/pull/510) + +## [0.8.0] - 2021-01-05 +### Breaking +- Updated dependencies. [#470](https://github.com/paritytech/parity-common/pull/470) + ## [0.7.0] - 2020-06-24 - Updated `kvdb` to 0.7. [#402](https://github.com/paritytech/parity-common/pull/402) diff --git a/kvdb-memorydb/Cargo.toml b/kvdb-memorydb/Cargo.toml index 1fc78291e..9599421f5 100644 --- a/kvdb-memorydb/Cargo.toml +++ b/kvdb-memorydb/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "kvdb-memorydb" -version = "0.7.0" +version = "0.9.0" authors = ["Parity Technologies "] repository = "https://github.com/paritytech/parity-common" description = "A key-value in-memory database that implements the `KeyValueDB` trait" @@ -8,9 +8,12 @@ license = "MIT OR Apache-2.0" edition = "2018" [dependencies] -parity-util-mem = { path = "../parity-util-mem", version = "0.7", default-features = false, features = ["std"] } -parking_lot = "0.10.0" -kvdb = { version = "0.7", path = "../kvdb" } +parity-util-mem = { path = "../parity-util-mem", version = "0.9", default-features = false, features = ["std"] } +parking_lot = "0.11.1" +kvdb = { version = "0.9", path = "../kvdb" } [dev-dependencies] -kvdb-shared-tests = { path = "../kvdb-shared-tests", version = "0.5" } +kvdb-shared-tests = { path = "../kvdb-shared-tests", version = "0.7" } + +[features] +default = [] diff --git a/kvdb-rocksdb/CHANGELOG.md b/kvdb-rocksdb/CHANGELOG.md index acf6282fb..f55d08a57 100644 --- a/kvdb-rocksdb/CHANGELOG.md +++ b/kvdb-rocksdb/CHANGELOG.md @@ -6,9 +6,18 @@ The format is based on [Keep a Changelog]. ## [Unreleased] +## [0.11.0] - 2021-01-27 +### Breaking +- Updated `kvdb` to 0.9. [#510](https://github.com/paritytech/parity-common/pull/510) +- Updated `parity-util-mem` to 0.9. [#510](https://github.com/paritytech/parity-common/pull/510) + +## [0.10.0] - 2021-01-05 +### Breaking +- Updated dependencies. [#470](https://github.com/paritytech/parity-common/pull/470) + ## [0.9.1] - 2020-08-26 - Updated rocksdb to 0.15. [#424](https://github.com/paritytech/parity-common/pull/424) -- Set `format_version` to 5. [#395](https://github.com/paritytech/parity-common/pull/395) +- Set `format_version` to 5. [#395](https://github.com/paritytech/parity-common/pull/395) ## [0.9.0] - 2020-06-24 - Updated `kvdb` to 0.7. [#402](https://github.com/paritytech/parity-common/pull/402) @@ -18,7 +27,7 @@ The format is based on [Keep a Changelog]. ### Breaking - Updated to the new `kvdb` interface. [#313](https://github.com/paritytech/parity-common/pull/313) - Rename and optimize prefix iteration. [#365](https://github.com/paritytech/parity-common/pull/365) -- Added Secondary Instance API. [#384](https://github.com/paritytech/parity-common/pull/384) +- Added Secondary Instance API. [#384](https://github.com/paritytech/parity-common/pull/384) ## [0.7.0] - 2020-03-16 - Updated dependencies. [#361](https://github.com/paritytech/parity-common/pull/361) diff --git a/kvdb-rocksdb/Cargo.toml b/kvdb-rocksdb/Cargo.toml index 92b2c4d58..9d9b038d5 100644 --- a/kvdb-rocksdb/Cargo.toml +++ b/kvdb-rocksdb/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "kvdb-rocksdb" -version = "0.9.1" +version = "0.11.0" authors = ["Parity Technologies "] repository = "https://github.com/paritytech/parity-common" description = "kvdb implementation backed by RocksDB" @@ -13,24 +13,24 @@ harness = false [dependencies] smallvec = "1.0.0" -fs-swap = "0.2.4" -kvdb = { path = "../kvdb", version = "0.7" } +fs-swap = "0.2.5" +kvdb = { path = "../kvdb", version = "0.9" } log = "0.4.8" num_cpus = "1.10.1" -parking_lot = "0.10.0" +parking_lot = "0.11.1" regex = "1.3.1" rocksdb = { version = "0.15", features = ["snappy"], default-features = false } owning_ref = "0.4.0" -parity-util-mem = { path = "../parity-util-mem", version = "0.7", default-features = false, features = ["std", "smallvec"] } +parity-util-mem = { path = "../parity-util-mem", version = "0.9", default-features = false, features = ["std", "smallvec"] } [dev-dependencies] alloc_counter = "0.0.4" criterion = "0.3" ethereum-types = { path = "../ethereum-types" } -kvdb-shared-tests = { path = "../kvdb-shared-tests", version = "0.5" } -rand = "0.7.2" -tempdir = "0.3.7" +kvdb-shared-tests = { path = "../kvdb-shared-tests", version = "0.7" } +rand = "0.8.0" +tempfile = "3.1.0" keccak-hash = { path = "../keccak-hash" } sysinfo = "0.15.3" ctrlc = "3.1.4" -time = "0.1" +chrono = "0.4" diff --git a/kvdb-rocksdb/benches/bench_read_perf.rs b/kvdb-rocksdb/benches/bench_read_perf.rs index 3a14ac752..5a956020b 100644 --- a/kvdb-rocksdb/benches/bench_read_perf.rs +++ b/kvdb-rocksdb/benches/bench_read_perf.rs @@ -50,7 +50,7 @@ fn open_db() -> Database { /// an `ElasticArray128` so sometimes we save on allocations. fn n_random_bytes(n: usize) -> Vec { let mut rng = rand::thread_rng(); - let variability: i64 = rng.gen_range(0, (n / 5) as i64); + let variability: i64 = rng.gen_range(0..(n / 5) as i64); let plus_or_minus: i64 = if variability % 2 == 0 { 1 } else { -1 }; let range = Uniform::from(0..u8::max_value()); rng.sample_iter(&range).take((n as i64 + plus_or_minus * variability) as usize).collect() diff --git a/kvdb-rocksdb/examples/memtest.rs b/kvdb-rocksdb/examples/memtest.rs index 59fa1a137..54c031c5f 100644 --- a/kvdb-rocksdb/examples/memtest.rs +++ b/kvdb-rocksdb/examples/memtest.rs @@ -99,7 +99,7 @@ fn main() { for c in 0..=COLUMN_COUNT { config.memory_budget.insert(c, mb_per_col); } - let dir = tempdir::TempDir::new("rocksdb-example").unwrap(); + let dir = tempfile::Builder::new().prefix("rocksdb-example").tempdir().unwrap(); println!("Database is put in: {} (maybe check if it was deleted)", dir.path().to_string_lossy()); let db = Database::open(&config, &dir.path().to_string_lossy()).unwrap(); @@ -136,7 +136,7 @@ fn main() { keyvalues = KeyValueSeed::with_seed(seed); if step % 10000 == 9999 { - let timestamp = time::strftime("%Y-%m-%d %H:%M:%S", &time::now()).expect("Error formatting log timestamp"); + let timestamp = chrono::Local::now().format("%Y-%m-%d %H:%M:%S"); println!("{}", timestamp); println!("\tData written: {} keys - {} Mb", step + 1, ((step + 1) * 64 * 128) / 1024 / 1024); diff --git a/kvdb-rocksdb/src/lib.rs b/kvdb-rocksdb/src/lib.rs index d4da1da57..321e1d118 100644 --- a/kvdb-rocksdb/src/lib.rs +++ b/kvdb-rocksdb/src/lib.rs @@ -788,10 +788,10 @@ mod tests { use super::*; use kvdb_shared_tests as st; use std::io::{self, Read}; - use tempdir::TempDir; + use tempfile::Builder as TempfileBuilder; fn create(columns: u32) -> io::Result { - let tempdir = TempDir::new("")?; + let tempdir = TempfileBuilder::new().prefix("").tempdir()?; let config = DatabaseConfig::with_columns(columns); Database::open(&config, tempdir.path().to_str().expect("tempdir path is valid unicode")) } @@ -846,7 +846,7 @@ mod tests { #[test] fn secondary_db_get() -> io::Result<()> { - let primary = TempDir::new("")?; + let primary = TempfileBuilder::new().prefix("").tempdir()?; let config = DatabaseConfig::with_columns(1); let db = Database::open(&config, primary.path().to_str().expect("tempdir path is valid unicode"))?; @@ -856,7 +856,7 @@ mod tests { db.write(transaction)?; let config = DatabaseConfig { - secondary: TempDir::new("")?.path().to_str().map(|s| s.to_string()), + secondary: TempfileBuilder::new().prefix("").tempdir()?.path().to_str().map(|s| s.to_string()), ..DatabaseConfig::with_columns(1) }; let second_db = Database::open(&config, primary.path().to_str().expect("tempdir path is valid unicode"))?; @@ -866,12 +866,12 @@ mod tests { #[test] fn secondary_db_catch_up() -> io::Result<()> { - let primary = TempDir::new("")?; + let primary = TempfileBuilder::new().prefix("").tempdir()?; let config = DatabaseConfig::with_columns(1); let db = Database::open(&config, primary.path().to_str().expect("tempdir path is valid unicode"))?; let config = DatabaseConfig { - secondary: TempDir::new("")?.path().to_str().map(|s| s.to_string()), + secondary: TempfileBuilder::new().prefix("").tempdir()?.path().to_str().map(|s| s.to_string()), ..DatabaseConfig::with_columns(1) }; let second_db = Database::open(&config, primary.path().to_str().expect("tempdir path is valid unicode"))?; @@ -888,7 +888,7 @@ mod tests { #[test] fn mem_tables_size() { - let tempdir = TempDir::new("").unwrap(); + let tempdir = TempfileBuilder::new().prefix("").tempdir().unwrap(); let config = DatabaseConfig { max_open_files: 512, @@ -950,7 +950,7 @@ mod tests { let config_1 = DatabaseConfig::default(); let config_5 = DatabaseConfig::with_columns(5); - let tempdir = TempDir::new("").unwrap(); + let tempdir = TempfileBuilder::new().prefix("").tempdir().unwrap(); // open 1, add 4. { @@ -975,7 +975,7 @@ mod tests { let config_1 = DatabaseConfig::default(); let config_5 = DatabaseConfig::with_columns(5); - let tempdir = TempDir::new("drop_columns").unwrap(); + let tempdir = TempfileBuilder::new().prefix("drop_columns").tempdir().unwrap(); // open 5, remove 4. { @@ -997,7 +997,7 @@ mod tests { #[test] fn test_num_keys() { - let tempdir = TempDir::new("").unwrap(); + let tempdir = TempfileBuilder::new().prefix("").tempdir().unwrap(); let config = DatabaseConfig::with_columns(1); let db = Database::open(&config, tempdir.path().to_str().unwrap()).unwrap(); @@ -1059,7 +1059,7 @@ rocksdb.db.get.micros P50 : 2.000000 P95 : 3.000000 P99 : 4.000000 P100 : 5.0000 cfg.compaction.initial_file_size = 102030; cfg.memory_budget = [(0, 30), (1, 300)].iter().cloned().collect(); - let db_path = TempDir::new("config_test").expect("the OS can create tmp dirs"); + let db_path = TempfileBuilder::new().prefix("config_test").tempdir().expect("the OS can create tmp dirs"); let db = Database::open(&cfg, db_path.path().to_str().unwrap()).expect("can open a db"); let mut rocksdb_log = std::fs::File::open(format!("{}/LOG", db_path.path().to_str().unwrap())) .expect("rocksdb creates a LOG file"); diff --git a/kvdb-shared-tests/CHANGELOG.md b/kvdb-shared-tests/CHANGELOG.md index 545cf7dff..f307aa6c3 100644 --- a/kvdb-shared-tests/CHANGELOG.md +++ b/kvdb-shared-tests/CHANGELOG.md @@ -5,3 +5,7 @@ The format is based on [Keep a Changelog]. [Keep a Changelog]: http://keepachangelog.com/en/1.0.0/ ## [Unreleased] + +## [0.7.0] - 2021-01-27 +### Breaking +- Updated `kvdb` to 0.9. [#510](https://github.com/paritytech/parity-common/pull/510) diff --git a/kvdb-shared-tests/Cargo.toml b/kvdb-shared-tests/Cargo.toml index 4e531d5fc..4ea00030e 100644 --- a/kvdb-shared-tests/Cargo.toml +++ b/kvdb-shared-tests/Cargo.toml @@ -1,10 +1,10 @@ [package] name = "kvdb-shared-tests" -version = "0.5.0" +version = "0.7.0" authors = ["Parity Technologies "] edition = "2018" description = "Shared tests for kvdb functionality, to be executed against actual implementations" license = "MIT OR Apache-2.0" [dependencies] -kvdb = { path = "../kvdb", version = "0.7" } +kvdb = { path = "../kvdb", version = "0.9" } diff --git a/kvdb-web/CHANGELOG.md b/kvdb-web/CHANGELOG.md index 64dd9ba34..323f42614 100644 --- a/kvdb-web/CHANGELOG.md +++ b/kvdb-web/CHANGELOG.md @@ -6,6 +6,16 @@ The format is based on [Keep a Changelog]. ## [Unreleased] +## [0.9.0] - 2021-01-27 +### Breaking +- Updated `kvdb` to 0.9. [#510](https://github.com/paritytech/parity-common/pull/510) +- Updated `kvdb-memorydb` to 0.9. [#510](https://github.com/paritytech/parity-common/pull/510) +- Updated `parity-util-mem` to 0.9. [#510](https://github.com/paritytech/parity-common/pull/510) + +## [0.8.0] - 2021-01-05 +### Breaking +- Updated dependencies. [#470](https://github.com/paritytech/parity-common/pull/470) + ## [0.7.0] - 2020-07-06 - Updated `kvdb` to 0.7.0 [#404](https://github.com/paritytech/parity-common/pull/404) diff --git a/kvdb-web/Cargo.toml b/kvdb-web/Cargo.toml index c2f2155ec..fe04d8c18 100644 --- a/kvdb-web/Cargo.toml +++ b/kvdb-web/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "kvdb-web" -version = "0.7.0" +version = "0.9.0" authors = ["Parity Technologies "] repository = "https://github.com/paritytech/parity-common" description = "A key-value database for use in browsers" @@ -9,17 +9,21 @@ license = "MIT OR Apache-2.0" edition = "2018" [dependencies] -wasm-bindgen = "0.2.54" -js-sys = "0.3.31" -kvdb = { version = "0.7", path = "../kvdb" } -kvdb-memorydb = { version = "0.7", path = "../kvdb-memorydb" } -futures = "0.3" -log = "0.4.8" -send_wrapper = "0.3.0" -parity-util-mem = { path = "../parity-util-mem", version = "0.7", default-features = false } +wasm-bindgen = "0.2.69" +js-sys = "0.3.46" +kvdb = { version = "0.9", path = "../kvdb" } +kvdb-memorydb = { version = "0.9", path = "../kvdb-memorydb" } +futures = "0.3.8" +log = "0.4.11" +send_wrapper = "0.5.0" +parity-util-mem = { path = "../parity-util-mem", version = "0.9", default-features = false } +# TODO: https://github.com/paritytech/parity-common/issues/479 +# This is hack to enable `wasm-bindgen` feature of `parking_lot` in other dependencies. +# Thus, it's not direct dependency and do not remove until a proper fix exists. +parking_lot = { version = "0.11.1", features = ["wasm-bindgen"] } [dependencies.web-sys] -version = "0.3.31" +version = "0.3.46" features = [ 'console', 'Window', @@ -40,6 +44,6 @@ features = [ [dev-dependencies] console_log = "0.2.0" -kvdb-shared-tests = { path = "../kvdb-shared-tests", version = "0.5" } -wasm-bindgen-test = "0.3.4" -wasm-bindgen-futures = "0.4.4" +kvdb-shared-tests = { path = "../kvdb-shared-tests", version = "0.7" } +wasm-bindgen-test = "0.3.19" +wasm-bindgen-futures = "0.4.19" diff --git a/kvdb/CHANGELOG.md b/kvdb/CHANGELOG.md index e67725cd7..9c2c444d0 100644 --- a/kvdb/CHANGELOG.md +++ b/kvdb/CHANGELOG.md @@ -6,6 +6,14 @@ The format is based on [Keep a Changelog]. ## [Unreleased] +## [0.9.0] - 2021-01-27 +### Breaking +- Updated `parity-util-mem` to 0.9. [#510](https://github.com/paritytech/parity-common/pull/510) + +## [0.8.0] - 2021-01-05 +### Breaking +- Updated `parity-util-mem` to 0.8. [#470](https://github.com/paritytech/parity-common/pull/470) + ## [0.7.0] - 2020-06-24 - Updated `parity-util-mem` to 0.7. [#402](https://github.com/paritytech/parity-common/pull/402) diff --git a/kvdb/Cargo.toml b/kvdb/Cargo.toml index 1accfb38b..8f22d0780 100644 --- a/kvdb/Cargo.toml +++ b/kvdb/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "kvdb" -version = "0.7.0" +version = "0.9.0" authors = ["Parity Technologies "] repository = "https://github.com/paritytech/parity-common" description = "Generic key-value trait" @@ -9,4 +9,4 @@ edition = "2018" [dependencies] smallvec = "1.0.0" -parity-util-mem = { path = "../parity-util-mem", version = "0.7", default-features = false } +parity-util-mem = { path = "../parity-util-mem", version = "0.9", default-features = false } diff --git a/parity-crypto/CHANGELOG.md b/parity-crypto/CHANGELOG.md index 19e2174e4..dfa71058d 100644 --- a/parity-crypto/CHANGELOG.md +++ b/parity-crypto/CHANGELOG.md @@ -5,7 +5,17 @@ The format is based on [Keep a Changelog]. [Keep a Changelog]: http://keepachangelog.com/en/1.0.0/ ## [Unreleased] -- Bump `rust-secp256k1` to v0.19, remove infrastructure for handling zero signatures (breaking). [#438](https://github.com/paritytech/parity-common/pull/438) + +## [0.8.0] - 2021-01-27 +### Breaking +- Updated `ethereum-types` to 0.11. [#510](https://github.com/paritytech/parity-common/pull/510) + +## [0.7.0] - 2021-01-05 +### Breaking +- Bump `rust-secp256k1` to v0.19, always allow zero signatures. [#438](https://github.com/paritytech/parity-common/pull/438) +- Updated `rlp` to 0.5. [#463](https://github.com/paritytech/parity-common/pull/463) +- Updated dependencies. [#483](https://github.com/paritytech/parity-common/pull/483) +- Remove deprecated trait impls `FromStr`/`TryFrom` for `Secret` [#495](https://github.com/paritytech/parity-common/pull/495) ## [0.6.2] - 2020-06-19 - Put `Secret` memory on heap. [#400](https://github.com/paritytech/parity-common/pull/400) @@ -14,7 +24,7 @@ The format is based on [Keep a Changelog]. ## [0.6.1] - 2020-04-11 - Add `recover_allowing_all_zero_message()` and `ZeroesAllowedMessage` to accomodate ethereum's `ecrecover` builtin. [#369](https://github.com/paritytech/parity-common/pull/369) - + ## [0.6.0] - 2020-03-16 - License changed from GPL3 to dual MIT/Apache2. [#342](https://github.com/paritytech/parity-common/pull/342) - Updated dependencies. [#361](https://github.com/paritytech/parity-common/pull/361) diff --git a/parity-crypto/Cargo.toml b/parity-crypto/Cargo.toml index 4e23dafda..1f7163425 100644 --- a/parity-crypto/Cargo.toml +++ b/parity-crypto/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "parity-crypto" -version = "0.6.2" +version = "0.8.0" authors = ["Parity Technologies "] repository = "https://github.com/paritytech/parity-common" description = "Crypto utils used by ethstore and network." @@ -14,26 +14,25 @@ harness = false required-features = ["publickey"] [dependencies] -aes = "0.4.0" -aes-ctr = "0.4.0" -block-modes = "0.5.0" -digest = "0.8" -ethereum-types = { version = "0.9.0", optional = true, path = "../ethereum-types" } -hmac = "0.7" -lazy_static = { version = "1.0", optional = true } -pbkdf2 = "0.3.0" -rand = "0.7.2" -ripemd160 = "0.8.0" +aes = "0.6.0" +aes-ctr = "0.6.0" +block-modes = "0.7.0" +digest = "0.9.0" +ethereum-types = { version = "0.11.0", optional = true, path = "../ethereum-types" } +hmac = "0.10.1" +lazy_static = { version = "1.4.0", optional = true } +pbkdf2 = "0.6.0" +ripemd160 = "0.9.1" rustc-hex = { version = "2.1.0", default-features = false, optional = true } -scrypt = { version = "0.2.0", default-features = false } -secp256k1 = { version = "0.19", optional = true, features = ["global-context", "recovery", "rand-std"] } -sha2 = "0.8.0" -subtle = "2.2.1" -tiny-keccak = { version = "2.0", features = ["keccak"] } -zeroize = { version = "1.0.0", default-features = false } +scrypt = { version = "0.5.0" } +secp256k1 = { version = "0.20.0", optional = true, features = ["global-context", "recovery", "rand-std"] } +sha2 = "0.9.2" +subtle = "2.4.0" +tiny-keccak = { version = "2.0.2", features = ["keccak"] } +zeroize = { version = "1.2.0", default-features = false } [dev-dependencies] -criterion = "0.3.0" +criterion = "0.3.3" hex-literal = "0.3.1" [features] diff --git a/parity-crypto/src/aes.rs b/parity-crypto/src/aes.rs index 3ba869958..c7c860183 100644 --- a/parity-crypto/src/aes.rs +++ b/parity-crypto/src/aes.rs @@ -6,9 +6,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use aes::block_cipher::generic_array::GenericArray; +use aes::cipher::generic_array::GenericArray; use aes::{Aes128, Aes256}; -use aes_ctr::stream_cipher::{NewStreamCipher, SyncStreamCipher}; +use aes_ctr::cipher::stream::{NewStreamCipher, SyncStreamCipher}; use block_modes::{ block_padding::{Pkcs7, ZeroPadding}, BlockMode, Cbc, Ecb, diff --git a/parity-crypto/src/digest.rs b/parity-crypto/src/digest.rs index 9ec5edf56..759613f2f 100644 --- a/parity-crypto/src/digest.rs +++ b/parity-crypto/src/digest.rs @@ -93,17 +93,17 @@ impl Hasher { impl Hasher { pub fn update(&mut self, data: &[u8]) { match self.0 { - Inner::Sha256(ref mut ctx) => ctx.input(data), - Inner::Sha512(ref mut ctx) => ctx.input(data), - Inner::Ripemd160(ref mut ctx) => ctx.input(data), + Inner::Sha256(ref mut ctx) => ctx.update(data), + Inner::Sha512(ref mut ctx) => ctx.update(data), + Inner::Ripemd160(ref mut ctx) => ctx.update(data), } } pub fn finish(self) -> Digest { match self.0 { - Inner::Sha256(ctx) => Digest(InnerDigest::Sha256(ctx.result()), PhantomData), - Inner::Sha512(ctx) => Digest(InnerDigest::Sha512(ctx.result()), PhantomData), - Inner::Ripemd160(ctx) => Digest(InnerDigest::Ripemd160(ctx.result()), PhantomData), + Inner::Sha256(ctx) => Digest(InnerDigest::Sha256(ctx.finalize()), PhantomData), + Inner::Sha512(ctx) => Digest(InnerDigest::Sha512(ctx.finalize()), PhantomData), + Inner::Ripemd160(ctx) => Digest(InnerDigest::Ripemd160(ctx.finalize()), PhantomData), } } } diff --git a/parity-crypto/src/error.rs b/parity-crypto/src/error.rs index e1a3cceb0..6f413a247 100644 --- a/parity-crypto/src/error.rs +++ b/parity-crypto/src/error.rs @@ -30,7 +30,7 @@ pub struct SymmError(PrivSymmErr); #[derive(Debug)] enum PrivSymmErr { BlockMode(block_modes::BlockModeError), - KeyStream(aes_ctr::stream_cipher::LoopError), + KeyStream(aes_ctr::cipher::stream::LoopError), InvalidKeyLength(block_modes::InvalidKeyIvLength), } @@ -111,8 +111,8 @@ impl From for SymmError { } } -impl From for SymmError { - fn from(e: aes_ctr::stream_cipher::LoopError) -> SymmError { +impl From for SymmError { + fn from(e: aes_ctr::cipher::stream::LoopError) -> SymmError { SymmError(PrivSymmErr::KeyStream(e)) } } diff --git a/parity-crypto/src/hmac/mod.rs b/parity-crypto/src/hmac/mod.rs index 6d606fdd7..ca20ae1c1 100644 --- a/parity-crypto/src/hmac/mod.rs +++ b/parity-crypto/src/hmac/mod.rs @@ -13,7 +13,7 @@ use digest::generic_array::{ typenum::{U32, U64}, GenericArray, }; -use hmac::{Hmac, Mac as _}; +use hmac::{Hmac, Mac as _, NewMac as _}; use zeroize::Zeroize; use crate::digest::{Sha256, Sha512}; @@ -113,15 +113,15 @@ impl Signer { pub fn update(&mut self, data: &[u8]) { match &mut self.0 { - SignerInner::Sha256(hmac) => hmac.input(data), - SignerInner::Sha512(hmac) => hmac.input(data), + SignerInner::Sha256(hmac) => hmac.update(data), + SignerInner::Sha512(hmac) => hmac.update(data), } } pub fn sign(self) -> Signature { match self.0 { - SignerInner::Sha256(hmac) => Signature(HashInner::Sha256(hmac.result().code()), PhantomData), - SignerInner::Sha512(hmac) => Signature(HashInner::Sha512(hmac.result().code()), PhantomData), + SignerInner::Sha256(hmac) => Signature(HashInner::Sha256(hmac.finalize().into_bytes()), PhantomData), + SignerInner::Sha512(hmac) => Signature(HashInner::Sha512(hmac.finalize().into_bytes()), PhantomData), } } } @@ -146,12 +146,12 @@ pub fn verify(key: &VerifyKey, data: &[u8], sig: &[u8]) -> bool { match &key.0 { KeyInner::Sha256(key_bytes) => { let mut ctx = Hmac::::new_varkey(&key_bytes.0).expect("always returns Ok; qed"); - ctx.input(data); + ctx.update(data); ctx.verify(sig).is_ok() } KeyInner::Sha512(key_bytes) => { let mut ctx = Hmac::::new_varkey(&key_bytes.0).expect("always returns Ok; qed"); - ctx.input(data); + ctx.update(data); ctx.verify(sig).is_ok() } } diff --git a/parity-crypto/src/hmac/test.rs b/parity-crypto/src/hmac/test.rs index a13174784..8f71bd4a9 100644 --- a/parity-crypto/src/hmac/test.rs +++ b/parity-crypto/src/hmac/test.rs @@ -232,21 +232,3 @@ fn ietf_test_vectors() { ), ); } - -#[test] -fn secrets_are_zeroed_on_drop() { - let ptr: *const KeyInner; - let zeros = KeyInner::Sha256(DisposableBox::from_slice(&[0u8; 6][..])); - let expected = KeyInner::Sha256(DisposableBox::from_slice(b"sikrit")); - { - let secret = b"sikrit"; - let signing_key = SigKey::sha256(secret); - ptr = &signing_key.0; - unsafe { - assert_eq!(*ptr, expected); - } - } - unsafe { - assert_eq!(*ptr, zeros); - } -} diff --git a/parity-crypto/src/pbkdf2/mod.rs b/parity-crypto/src/pbkdf2/mod.rs index a3a06e867..c9f1bd565 100644 --- a/parity-crypto/src/pbkdf2/mod.rs +++ b/parity-crypto/src/pbkdf2/mod.rs @@ -10,11 +10,11 @@ pub struct Salt<'a>(pub &'a [u8]); pub struct Secret<'a>(pub &'a [u8]); pub fn sha256(iter: u32, salt: Salt<'_>, sec: Secret<'_>, out: &mut [u8; 32]) { - pbkdf2::pbkdf2::>(sec.0, salt.0, iter as usize, out) + pbkdf2::pbkdf2::>(sec.0, salt.0, iter, out) } pub fn sha512(iter: u32, salt: Salt<'_>, sec: Secret<'_>, out: &mut [u8; 64]) { - pbkdf2::pbkdf2::>(sec.0, salt.0, iter as usize, out) + pbkdf2::pbkdf2::>(sec.0, salt.0, iter, out) } #[cfg(test)] diff --git a/parity-crypto/src/publickey/secret_key.rs b/parity-crypto/src/publickey/secret_key.rs index 269afdf3e..7f5692f1d 100644 --- a/parity-crypto/src/publickey/secret_key.rs +++ b/parity-crypto/src/publickey/secret_key.rs @@ -8,7 +8,6 @@ //! Secret key implementation. -use std::convert::TryFrom; use std::fmt; use std::ops::Deref; use std::str::FromStr; @@ -138,7 +137,7 @@ impl Secret { pub fn dec(&mut self) -> Result<(), Error> { match self.is_zero() { true => { - *self = Secret::try_from(super::MINUS_ONE_KEY) + *self = Self::copy_from_slice(&super::MINUS_ONE_KEY) .expect("Constructing a secret key from a known-good constant works; qed."); Ok(()) } @@ -213,14 +212,6 @@ impl Secret { } } -#[deprecated(since = "0.6.2", note = "please use `copy_from_str` instead, input is not zeroized")] -impl FromStr for Secret { - type Err = Error; - fn from_str(s: &str) -> Result { - Ok(H256::from_str(s).map_err(|e| Error::Custom(format!("{:?}", e)))?.into()) - } -} - impl From<[u8; 32]> for Secret { #[inline(always)] fn from(mut k: [u8; 32]) -> Self { @@ -239,27 +230,6 @@ impl From for Secret { } } -#[deprecated(since = "0.6.2", note = "please use `copy_from_str` instead, input is not zeroized")] -impl TryFrom<&str> for Secret { - type Error = Error; - - fn try_from(s: &str) -> Result { - s.parse().map_err(|e| Error::Custom(format!("{:?}", e))) - } -} - -#[deprecated(since = "0.6.2", note = "please use `copy_from_slice` instead, input is not zeroized")] -impl TryFrom<&[u8]> for Secret { - type Error = Error; - - fn try_from(b: &[u8]) -> Result { - if b.len() != SECP256K1_SECRET_KEY_SIZE { - return Err(Error::InvalidSecretKey); - } - Ok(Self { inner: Box::new(H256::from_slice(b)) }) - } -} - impl From for Secret { #[inline(always)] fn from(key: key::SecretKey) -> Self { diff --git a/parity-util-mem/CHANGELOG.md b/parity-util-mem/CHANGELOG.md index c1ba5fe12..0c88476ca 100644 --- a/parity-util-mem/CHANGELOG.md +++ b/parity-util-mem/CHANGELOG.md @@ -5,7 +5,17 @@ The format is based on [Keep a Changelog]. [Keep a Changelog]: http://keepachangelog.com/en/1.0.0/ ## [Unreleased] + +## [0.9.0] - 2021-01-27 +### Breaking +- Updated `ethereum-types` to 0.11. [#510](https://github.com/paritytech/parity-common/pull/510) +- Updated `primitive-types` to 0.9. [#510](https://github.com/paritytech/parity-common/pull/510) + +## [0.8.0] - 2021-01-05 - Updated dlmalloc to 0.2.1. [#452](https://github.com/paritytech/parity-common/pull/452) +### Breaking +- Updated `ethereum-types` to 0.10. [#463](https://github.com/paritytech/parity-common/pull/463) +- Updated `parking_lot` to 0.11.1. [#470](https://github.com/paritytech/parity-common/pull/470) ## [0.7.0] - 2020-06-24 - Added `const_size` to `MallocSizeOf` to optimize it for flat collections. [#398](https://github.com/paritytech/parity-common/pull/398) diff --git a/parity-util-mem/Cargo.toml b/parity-util-mem/Cargo.toml index 0baba5692..e88ba2eed 100644 --- a/parity-util-mem/Cargo.toml +++ b/parity-util-mem/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "parity-util-mem" -version = "0.7.0" +version = "0.9.0" authors = ["Parity Technologies "] repository = "https://github.com/paritytech/parity-common" description = "Collection of memory related utilities" @@ -23,12 +23,12 @@ hashbrown = { version = "0.9", optional = true } mimalloc = { version = "0.1.18", optional = true } libmimalloc-sys = { version = "0.1.14", optional = true } parity-util-mem-derive = { path = "derive", version = "0.1" } -impl-trait-for-tuples = "0.1.3" +impl-trait-for-tuples = "0.2.0" smallvec = { version = "1.0.0", optional = true } -ethereum-types = { version = "0.9.0", optional = true, path = "../ethereum-types" } -parking_lot = { version = "0.10.0", optional = true } -primitive-types = { version = "0.7", path = "../primitive-types", default-features = false, optional = true } +ethereum-types = { version = "0.11.0", optional = true, path = "../ethereum-types" } +parking_lot = { version = "0.11.1", optional = true } +primitive-types = { version = "0.9", path = "../primitive-types", default-features = false, optional = true } [target.'cfg(target_os = "windows")'.dependencies] winapi = { version = "0.3.8", features = ["heapapi"] } diff --git a/primitive-types/CHANGELOG.md b/primitive-types/CHANGELOG.md index 11242518f..df097bc61 100644 --- a/primitive-types/CHANGELOG.md +++ b/primitive-types/CHANGELOG.md @@ -6,6 +6,17 @@ The format is based on [Keep a Changelog]. ## [Unreleased] +## [0.9.0] - 2021-01-27 +### Breaking +- Updated `impl-codec` to 0.5. [#510](https://github.com/paritytech/parity-common/pull/510) +- Updated `scale-info` to 0.5. [#510](https://github.com/paritytech/parity-common/pull/510) + +## [0.8.0] - 2021-01-05 +- Added `num-traits` feature. [#480](https://github.com/paritytech/parity-common/pull/480) +### Breaking +- Updated `impl-rlp` to `rlp` 0.5. [#463](https://github.com/paritytech/parity-common/pull/463) +- Updated `uint` to 0.9. [#486](https://github.com/paritytech/parity-common/pull/486) + ## [0.7.3] - 2020-11-12 - Added `scale_info` support. [#312](https://github.com/paritytech/parity-common/pull/312) - Added `H128` type. [#434](https://github.com/paritytech/parity-common/pull/434) diff --git a/primitive-types/Cargo.toml b/primitive-types/Cargo.toml index 243a4d31d..9646b344f 100644 --- a/primitive-types/Cargo.toml +++ b/primitive-types/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "primitive-types" -version = "0.7.3" +version = "0.9.0" authors = ["Parity Technologies "] license = "MIT OR Apache-2.0" homepage = "https://github.com/paritytech/parity-common" @@ -8,12 +8,13 @@ description = "Primitive types shared by Ethereum and Substrate" edition = "2018" [dependencies] -fixed-hash = { version = "0.6", path = "../fixed-hash", default-features = false } -uint = { version = "0.8.3", path = "../uint", default-features = false } +fixed-hash = { version = "0.7", path = "../fixed-hash", default-features = false } +uint = { version = "0.9.0", path = "../uint", default-features = false } impl-serde = { version = "0.3.1", path = "impls/serde", default-features = false, optional = true } -impl-codec = { version = "0.4.1", path = "impls/codec", default-features = false, optional = true } -impl-rlp = { version = "0.2", path = "impls/rlp", default-features = false, optional = true } -scale-info = { version = "0.4", features = ["derive"], default-features = false, optional = true } +impl-codec = { version = "0.5.0", path = "impls/codec", default-features = false, optional = true } +impl-num-traits = { version = "0.1.0", path = "impls/num-traits", default-features = false, optional = true } +impl-rlp = { version = "0.3", path = "impls/rlp", default-features = false, optional = true } +scale-info = { version = "0.5", features = ["derive"], default-features = false, optional = true } [features] default = ["std"] @@ -26,6 +27,7 @@ codec = ["impl-codec"] rlp = ["impl-rlp"] arbitrary = ["fixed-hash/arbitrary", "uint/arbitrary"] fp-conversion = ["std"] +num-traits = ["impl-num-traits"] [[test]] name = "scale_info" diff --git a/primitive-types/impls/codec/CHANGELOG.md b/primitive-types/impls/codec/CHANGELOG.md index 927c9dc9c..179be164f 100644 --- a/primitive-types/impls/codec/CHANGELOG.md +++ b/primitive-types/impls/codec/CHANGELOG.md @@ -1,7 +1,11 @@ # Changelog -The format is based on [Keep a Changelog]. +The format is based on [Keep a Changelog]. [Keep a Changelog]: http://keepachangelog.com/en/1.0.0/ ## [Unreleased] + +## [0.5.0] - 2021-01-27 +### Breaking +- Updated `parity-scale-codec` to 2.0. [#510](https://github.com/paritytech/parity-common/pull/510) diff --git a/primitive-types/impls/codec/Cargo.toml b/primitive-types/impls/codec/Cargo.toml index df837fd01..27a4aa7b6 100644 --- a/primitive-types/impls/codec/Cargo.toml +++ b/primitive-types/impls/codec/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "impl-codec" -version = "0.4.2" +version = "0.5.0" authors = ["Parity Technologies "] license = "MIT OR Apache-2.0" homepage = "https://github.com/paritytech/parity-common" @@ -8,7 +8,7 @@ description = "Parity Codec serialization support for uint and fixed hash." edition = "2018" [dependencies] -parity-scale-codec = { version = "1.0.6", default-features = false } +parity-scale-codec = { version = "2.0.0", default-features = false } [features] default = ["std"] diff --git a/primitive-types/impls/num-traits/CHANGELOG.md b/primitive-types/impls/num-traits/CHANGELOG.md new file mode 100644 index 000000000..545cf7dff --- /dev/null +++ b/primitive-types/impls/num-traits/CHANGELOG.md @@ -0,0 +1,7 @@ +# Changelog + +The format is based on [Keep a Changelog]. + +[Keep a Changelog]: http://keepachangelog.com/en/1.0.0/ + +## [Unreleased] diff --git a/primitive-types/impls/num-traits/Cargo.toml b/primitive-types/impls/num-traits/Cargo.toml new file mode 100644 index 000000000..a77774608 --- /dev/null +++ b/primitive-types/impls/num-traits/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "impl-num-traits" +version = "0.1.0" +authors = ["Parity Technologies "] +license = "MIT OR Apache-2.0" +homepage = "https://github.com/paritytech/parity-common" +description = "num-traits implementation for uint." +edition = "2018" + +[dependencies] +num-traits = { version = "0.2", default-features = false } +uint = { version = "0.9.0", path = "../../../uint", default-features = false } diff --git a/primitive-types/impls/num-traits/src/lib.rs b/primitive-types/impls/num-traits/src/lib.rs new file mode 100644 index 000000000..094447592 --- /dev/null +++ b/primitive-types/impls/num-traits/src/lib.rs @@ -0,0 +1,50 @@ +// Copyright 2020 Parity Technologies +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! num-traits support for uint. + +#![no_std] + +#[doc(hidden)] +pub use num_traits; + +#[doc(hidden)] +pub use uint; + +/// Add num-traits support to an integer created by `construct_uint!`. +#[macro_export] +macro_rules! impl_uint_num_traits { + ($name: ident, $len: expr) => { + impl $crate::num_traits::identities::Zero for $name { + #[inline] + fn zero() -> Self { + Self::zero() + } + + #[inline] + fn is_zero(&self) -> bool { + self.is_zero() + } + } + + impl $crate::num_traits::identities::One for $name { + #[inline] + fn one() -> Self { + Self::one() + } + } + + impl $crate::num_traits::Num for $name { + type FromStrRadixErr = $crate::uint::FromStrRadixErr; + + fn from_str_radix(txt: &str, radix: u32) -> Result { + Self::from_str_radix(txt, radix) + } + } + }; +} diff --git a/primitive-types/impls/rlp/CHANGELOG.md b/primitive-types/impls/rlp/CHANGELOG.md index 927c9dc9c..749b49f37 100644 --- a/primitive-types/impls/rlp/CHANGELOG.md +++ b/primitive-types/impls/rlp/CHANGELOG.md @@ -1,7 +1,11 @@ # Changelog -The format is based on [Keep a Changelog]. +The format is based on [Keep a Changelog]. [Keep a Changelog]: http://keepachangelog.com/en/1.0.0/ ## [Unreleased] + +## [0.3.0] - 2021-01-05 +### Breaking +- Updated `rlp` to 0.5. [#463](https://github.com/paritytech/parity-common/pull/463) diff --git a/primitive-types/impls/rlp/Cargo.toml b/primitive-types/impls/rlp/Cargo.toml index fbc12c7fb..622aa0f37 100644 --- a/primitive-types/impls/rlp/Cargo.toml +++ b/primitive-types/impls/rlp/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "impl-rlp" -version = "0.2.1" +version = "0.3.0" authors = ["Parity Technologies "] license = "MIT OR Apache-2.0" homepage = "https://github.com/paritytech/parity-common" @@ -8,7 +8,7 @@ description = "RLP serialization support for uint and fixed hash." edition = "2018" [dependencies] -rlp = { version = "0.4", path = "../../../rlp", default-features = false } +rlp = { version = "0.5", path = "../../../rlp", default-features = false } [features] default = ["std"] diff --git a/primitive-types/impls/serde/Cargo.toml b/primitive-types/impls/serde/Cargo.toml index a76c0e4d9..e75eeba43 100644 --- a/primitive-types/impls/serde/Cargo.toml +++ b/primitive-types/impls/serde/Cargo.toml @@ -18,7 +18,7 @@ serde = { version = "1.0.101", default-features = false, features = ["alloc"] } criterion = "0.3.0" serde_derive = "1.0.101" serde_json = "1.0.41" -uint = { version = "0.8.3", path = "../../../uint" } +uint = { version = "0.9.0", path = "../../../uint" } [[bench]] name = "impl_serde" diff --git a/primitive-types/src/lib.rs b/primitive-types/src/lib.rs index fe1eb4ac7..696ac6898 100644 --- a/primitive-types/src/lib.rs +++ b/primitive-types/src/lib.rs @@ -68,6 +68,16 @@ construct_fixed_hash! { pub struct H512(64); } +#[cfg(feature = "num-traits")] +mod num_traits { + use super::*; + use impl_num_traits::impl_uint_num_traits; + + impl_uint_num_traits!(U128, 2); + impl_uint_num_traits!(U256, 4); + impl_uint_num_traits!(U512, 8); +} + #[cfg(feature = "impl-serde")] mod serde { use super::*; diff --git a/primitive-types/tests/scale_info.rs b/primitive-types/tests/scale_info.rs index 5a61ef133..1acecf54e 100644 --- a/primitive-types/tests/scale_info.rs +++ b/primitive-types/tests/scale_info.rs @@ -13,16 +13,18 @@ use scale_info::{build::Fields, Path, Type, TypeInfo}; #[test] fn u256_scale_info() { - let r#type = - Type::builder().path(Path::new("U256", "primitive_types")).composite(Fields::unnamed().field_of::<[u64; 4]>()); + let r#type = Type::builder() + .path(Path::new("U256", "primitive_types")) + .composite(Fields::unnamed().field_of::<[u64; 4]>("[u64; 4]")); assert_eq!(U256::type_info(), r#type.into()); } #[test] fn h256_scale_info() { - let r#type = - Type::builder().path(Path::new("H256", "primitive_types")).composite(Fields::unnamed().field_of::<[u8; 32]>()); + let r#type = Type::builder() + .path(Path::new("H256", "primitive_types")) + .composite(Fields::unnamed().field_of::<[u8; 32]>("[u8; 32]")); assert_eq!(H256::type_info(), r#type.into()); } diff --git a/rlp-derive/Cargo.toml b/rlp-derive/Cargo.toml index 5059d6d02..16f7e010e 100644 --- a/rlp-derive/Cargo.toml +++ b/rlp-derive/Cargo.toml @@ -16,4 +16,4 @@ quote = "1.0.2" proc-macro2 = "1.0.8" [dev-dependencies] -rlp = "0.4.4" +rlp = { version = "0.5.0", path = "../rlp" } diff --git a/rlp/CHANGELOG.md b/rlp/CHANGELOG.md index 0eff86727..afd84d95c 100644 --- a/rlp/CHANGELOG.md +++ b/rlp/CHANGELOG.md @@ -6,6 +6,10 @@ The format is based on [Keep a Changelog]. ## [Unreleased] +## [0.5.0] - 2021-01-05 +### Breaking +- Use BytesMut for `RlpStream`'s backing buffer. [#453](https://github.com/paritytech/parity-common/pull/453) + ## [0.4.6] - 2020-09-29 - Implement Encodable, Decodable for boxed types. [#427](https://github.com/paritytech/parity-common/pull/427) diff --git a/rlp/Cargo.toml b/rlp/Cargo.toml index ebec7d305..fa1070ec1 100644 --- a/rlp/Cargo.toml +++ b/rlp/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "rlp" -version = "0.4.6" +version = "0.5.0" description = "Recursive-length prefix encoding, decoding, and compression" repository = "https://github.com/paritytech/parity-common" license = "MIT OR Apache-2.0" @@ -8,13 +8,13 @@ authors = ["Parity Technologies "] edition = "2018" [dependencies] -bytes = { version = "0.6", default-features = false } +bytes = { version = "1", default-features = false } rustc-hex = { version = "2.0.1", default-features = false } [dev-dependencies] criterion = "0.3.0" hex-literal = "0.3.1" -primitive-types = { path = "../primitive-types", version = "0.7", features = ["impl-rlp"] } +primitive-types = { path = "../primitive-types", version = "0.9", features = ["impl-rlp"] } [features] default = ["std"] diff --git a/rlp/src/impls.rs b/rlp/src/impls.rs index 02663349e..7aa013925 100644 --- a/rlp/src/impls.rs +++ b/rlp/src/impls.rs @@ -8,6 +8,7 @@ #[cfg(not(feature = "std"))] use alloc::{borrow::ToOwned, boxed::Box, string::String, vec::Vec}; +use bytes::{Bytes, BytesMut}; use core::iter::{empty, once}; use core::{mem, str}; @@ -79,6 +80,30 @@ impl Decodable for Vec { } } +impl Encodable for Bytes { + fn rlp_append(&self, s: &mut RlpStream) { + s.encoder().encode_value(self); + } +} + +impl Decodable for Bytes { + fn decode(rlp: &Rlp) -> Result { + rlp.decoder().decode_value(|bytes| Ok(Bytes::copy_from_slice(bytes))) + } +} + +impl Encodable for BytesMut { + fn rlp_append(&self, s: &mut RlpStream) { + s.encoder().encode_value(self); + } +} + +impl Decodable for BytesMut { + fn decode(rlp: &Rlp) -> Result { + rlp.decoder().decode_value(|bytes| Ok(bytes.into())) + } +} + impl Encodable for Option where T: Encodable, diff --git a/rlp/src/stream.rs b/rlp/src/stream.rs index d99d84c9e..607dc9344 100644 --- a/rlp/src/stream.rs +++ b/rlp/src/stream.rs @@ -29,6 +29,7 @@ impl ListInfo { /// Appendable rlp encoder. pub struct RlpStream { unfinished_lists: Vec, + start_pos: usize, buffer: BytesMut, finished_list: bool, } @@ -52,7 +53,7 @@ impl RlpStream { /// Initializes instance of empty `Stream`. pub fn new_with_buffer(buffer: BytesMut) -> Self { - RlpStream { unfinished_lists: Vec::with_capacity(16), buffer, finished_list: false } + RlpStream { unfinished_lists: Vec::with_capacity(16), start_pos: buffer.len(), buffer, finished_list: false } } /// Initializes the `Stream` as a list. @@ -62,6 +63,10 @@ impl RlpStream { stream } + fn total_written(&self) -> usize { + self.buffer.len() - self.start_pos + } + /// Apends null to the end of stream, chainable. /// /// ``` @@ -183,7 +188,7 @@ impl RlpStream { // by pushing always this 1 byte we may avoid unnecessary shift of data self.buffer.put_u8(0); - let position = self.buffer.len(); + let position = self.total_written(); self.unfinished_lists.push(ListInfo::new(position, Some(len))); } } @@ -198,7 +203,7 @@ impl RlpStream { // payload is longer than 1 byte only for lists > 55 bytes // by pushing always this 1 byte we may avoid unnecessary shift of data self.buffer.put_u8(0); - let position = self.buffer.len(); + let position = self.total_written(); self.unfinished_lists.push(ListInfo::new(position, None)); // return chainable self self @@ -215,7 +220,7 @@ impl RlpStream { /// Calculate total RLP size for appended payload. pub fn estimate_size(&self, add: usize) -> usize { - let total_size = self.buffer.len() + add; + let total_size = self.total_written() + add; let mut base_size = total_size; for list in &self.unfinished_lists[..] { let len = total_size - list.position; @@ -250,7 +255,7 @@ impl RlpStream { /// ``` pub fn clear(&mut self) { // clear bytes - self.buffer.clear(); + self.buffer.truncate(self.start_pos); // clear lists self.unfinished_lists.clear(); @@ -309,7 +314,7 @@ impl RlpStream { }; if should_finish { let x = self.unfinished_lists.pop().unwrap(); - let len = self.buffer.len() - x.position; + let len = self.total_written() - x.position; self.encoder().insert_list_payload(len, x.position); self.note_appended(1); } @@ -317,7 +322,7 @@ impl RlpStream { } pub fn encoder(&mut self) -> BasicEncoder { - BasicEncoder::new(self) + BasicEncoder::new(self, self.start_pos) } /// Finalize current unbounded list. Panics if no unbounded list has been opened. @@ -326,7 +331,7 @@ impl RlpStream { if list.max.is_some() { panic!("List type mismatch."); } - let len = self.buffer.len() - list.position; + let len = self.total_written() - list.position; self.encoder().insert_list_payload(len, list.position); self.note_appended(1); self.finished_list = true; @@ -335,11 +340,16 @@ impl RlpStream { pub struct BasicEncoder<'a> { buffer: &'a mut BytesMut, + start_pos: usize, } impl<'a> BasicEncoder<'a> { - fn new(stream: &'a mut RlpStream) -> Self { - BasicEncoder { buffer: &mut stream.buffer } + fn new(stream: &'a mut RlpStream, start_pos: usize) -> Self { + BasicEncoder { buffer: &mut stream.buffer, start_pos } + } + + fn total_written(&self) -> usize { + self.buffer.len() - self.start_pos } fn insert_size(&mut self, size: usize, position: usize) -> u8 { @@ -347,10 +357,10 @@ impl<'a> BasicEncoder<'a> { let leading_empty_bytes = size.leading_zeros() as usize / 8; let size_bytes = 4 - leading_empty_bytes as u8; let buffer: [u8; 4] = size.to_be_bytes(); - assert!(position <= self.buffer.len()); + assert!(position <= self.total_written()); self.buffer.extend_from_slice(&buffer[leading_empty_bytes..]); - self.buffer[position..].rotate_right(size_bytes as usize); + self.buffer[self.start_pos + position..].rotate_right(size_bytes as usize); size_bytes as u8 } @@ -359,11 +369,11 @@ impl<'a> BasicEncoder<'a> { // 1 byte was already reserved for payload earlier match len { 0..=55 => { - self.buffer[pos - 1] = 0xc0u8 + len as u8; + self.buffer[self.start_pos + pos - 1] = 0xc0u8 + len as u8; } _ => { let inserted_bytes = self.insert_size(len, pos); - self.buffer[pos - 1] = 0xf7u8 + inserted_bytes; + self.buffer[self.start_pos + pos - 1] = 0xf7u8 + inserted_bytes; } }; } @@ -403,9 +413,9 @@ impl<'a> BasicEncoder<'a> { // (prefix + length of length), followed by the length, followd by the string len => { self.buffer.put_u8(0); - let position = self.buffer.len(); + let position = self.total_written(); let inserted_bytes = self.insert_size(len, position); - self.buffer[position - 1] = 0xb7 + inserted_bytes; + self.buffer[self.start_pos + position - 1] = 0xb7 + inserted_bytes; self.buffer.extend(value); } } diff --git a/rlp/src/traits.rs b/rlp/src/traits.rs index e96cf4c46..b83b2ddcb 100644 --- a/rlp/src/traits.rs +++ b/rlp/src/traits.rs @@ -7,8 +7,6 @@ // except according to those terms. //! Common RLP traits -#[cfg(not(feature = "std"))] -use alloc::vec::Vec; use bytes::BytesMut; use crate::{error::DecoderError, rlpin::Rlp, stream::RlpStream}; diff --git a/rlp/tests/tests.rs b/rlp/tests/tests.rs index 77d514b76..9ba2e3592 100644 --- a/rlp/tests/tests.rs +++ b/rlp/tests/tests.rs @@ -8,7 +8,7 @@ use core::{cmp, fmt}; -use bytes::BytesMut; +use bytes::{Bytes, BytesMut}; use hex_literal::hex; use primitive_types::{H160, U256}; use rlp::{Decodable, DecoderError, Encodable, Rlp, RlpStream}; @@ -22,7 +22,7 @@ fn test_rlp_display() { #[test] fn length_overflow() { - let bs = [0xbf, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xe5]; + let bs = hex!("bfffffffffffffffffffffffe5"); let rlp = Rlp::new(&bs); let res: Result = rlp.as_val(); assert_eq!(Err(DecoderError::RlpInvalidLength), res); @@ -150,12 +150,32 @@ where } } +impl From<(T, Repr)> for ETestPair +where + T: Encodable, + Repr: Into>, +{ + fn from((v, repr): (T, Repr)) -> Self { + Self(v, repr.into()) + } +} + +impl From<(Vec, Repr)> for VETestPair +where + T: Encodable, + Repr: Into>, +{ + fn from((v, repr): (Vec, Repr)) -> Self { + Self(v, repr.into()) + } +} + #[test] fn encode_u16() { let tests = vec![ - ETestPair(0u16, vec![0x80u8]), - ETestPair(0x100, vec![0x82, 0x01, 0x00]), - ETestPair(0xffff, vec![0x82, 0xff, 0xff]), + ETestPair::from((0_u16, hex!("80"))), + ETestPair::from((0x100_u16, hex!("820100"))), + ETestPair::from((0xffff_u16, hex!("82ffff"))), ]; run_encode_tests(tests); } @@ -163,9 +183,9 @@ fn encode_u16() { #[test] fn encode_u32() { let tests = vec![ - ETestPair(0u32, vec![0x80u8]), - ETestPair(0x0001_0000, vec![0x83, 0x01, 0x00, 0x00]), - ETestPair(0x00ff_ffff, vec![0x83, 0xff, 0xff, 0xff]), + ETestPair::from((0_u32, hex!("80"))), + ETestPair::from((0x0001_0000_u32, hex!("83010000"))), + ETestPair::from((0x00ff_ffff_u32, hex!("83ffffff"))), ]; run_encode_tests(tests); } @@ -173,9 +193,9 @@ fn encode_u32() { #[test] fn encode_u64() { let tests = vec![ - ETestPair(0u64, vec![0x80u8]), - ETestPair(0x0100_0000, vec![0x84, 0x01, 0x00, 0x00, 0x00]), - ETestPair(0xFFFF_FFFF, vec![0x84, 0xff, 0xff, 0xff, 0xff]), + ETestPair::from((0_u64, hex!("80"))), + ETestPair::from((0x0100_0000_u64, hex!("8401000000"))), + ETestPair::from((0xFFFF_FFFF_u64, hex!("84ffffffff"))), ]; run_encode_tests(tests); } @@ -183,9 +203,9 @@ fn encode_u64() { #[test] fn encode_u128() { let tests = vec![ - ETestPair(0u128, vec![0x80u8]), - ETestPair(0x0100_0000_0000_0000, vec![0x88, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]), - ETestPair(0xFFFF_FFFF_FFFF_FFFF, vec![0x88, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]), + ETestPair::from((0_u128, hex!("80"))), + ETestPair::from((0x0100_0000_0000_0000_u128, hex!("880100000000000000"))), + ETestPair::from((0xFFFF_FFFF_FFFF_FFFF_u128, hex!("88ffffffffffffffff"))), ]; run_encode_tests(tests); } @@ -193,18 +213,13 @@ fn encode_u128() { #[test] fn encode_u256() { let tests = vec![ - ETestPair(U256::from(0u64), vec![0x80u8]), - ETestPair(U256::from(0x0100_0000u64), vec![0x84, 0x01, 0x00, 0x00, 0x00]), - ETestPair(U256::from(0xffff_ffffu64), vec![0x84, 0xff, 0xff, 0xff, 0xff]), - ETestPair( - ("8090a0b0c0d0e0f00910203040506077000000000000\ - 000100000000000012f0") - .into(), - vec![ - 0xa0, 0x80, 0x90, 0xa0, 0xb0, 0xc0, 0xd0, 0xe0, 0xf0, 0x09, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x77, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x12, 0xf0, - ], - ), + ETestPair::from((U256::from(0_u64), hex!("80"))), + ETestPair::from((U256::from(0x0100_0000_u64), hex!("8401000000"))), + ETestPair::from((U256::from(0xffff_ffff_u64), hex!("84ffffffff"))), + ETestPair::from(( + hex!(" 8090a0b0c0d0e0f00910203040506077000000000000000100000000000012f0").into(), + hex!("a08090a0b0c0d0e0f00910203040506077000000000000000100000000000012f0"), + )), ]; run_encode_tests(tests); } @@ -212,11 +227,11 @@ fn encode_u256() { #[test] fn encode_str() { let tests = vec![ - ETestPair("cat", vec![0x83, b'c', b'a', b't']), - ETestPair("dog", vec![0x83, b'd', b'o', b'g']), - ETestPair("Marek", vec![0x85, b'M', b'a', b'r', b'e', b'k']), - ETestPair("", vec![0x80]), - ETestPair( + ETestPair::from(("cat", vec![0x83, b'c', b'a', b't'])), + ETestPair::from(("dog", vec![0x83, b'd', b'o', b'g'])), + ETestPair::from(("Marek", vec![0x85, b'M', b'a', b'r', b'e', b'k'])), + ETestPair::from(("", hex!("80"))), + ETestPair::from(( "Lorem ipsum dolor sit amet, consectetur adipisicing elit", vec![ 0xb8, 0x38, b'L', b'o', b'r', b'e', b'm', b' ', b'i', b'p', b's', b'u', b'm', b' ', b'd', b'o', b'l', @@ -224,7 +239,7 @@ fn encode_str() { b'e', b'c', b't', b'e', b't', b'u', b'r', b' ', b'a', b'd', b'i', b'p', b'i', b's', b'i', b'c', b'i', b'n', b'g', b' ', b'e', b'l', b'i', b't', ], - ), + )), ]; run_encode_tests(tests); } @@ -234,22 +249,31 @@ fn encode_into_existing_buffer() { let mut buffer = BytesMut::new(); buffer.extend_from_slice(b"junk"); - let mut s = RlpStream::new_with_buffer(buffer.split_off(buffer.len())); + let mut split_buffer = buffer.split_off(buffer.len()); + split_buffer.extend_from_slice(b"!"); + + let mut s = RlpStream::new_with_buffer(split_buffer); s.append(&"cat"); buffer.unsplit(s.out()); - assert_eq!(&buffer[..], &[b'j', b'u', b'n', b'k', 0x83, b'c', b'a', b't']); + buffer.extend_from_slice(b" and "); + + let mut s = RlpStream::new_with_buffer(buffer); + s.append(&"dog"); + let buffer = s.out(); + + assert_eq!( + &buffer[..], + &[b'j', b'u', b'n', b'k', b'!', 0x83, b'c', b'a', b't', b' ', b'a', b'n', b'd', b' ', 0x83, b'd', b'o', b'g'] + ); } #[test] fn encode_address() { - let tests = vec![ETestPair( + let tests = vec![ETestPair::from(( H160::from(hex!("ef2d6d194084c2de36e0dabfce45d046b37d1106")), - vec![ - 0x94, 0xef, 0x2d, 0x6d, 0x19, 0x40, 0x84, 0xc2, 0xde, 0x36, 0xe0, 0xda, 0xbf, 0xce, 0x45, 0xd0, 0x46, 0xb3, - 0x7d, 0x11, 0x06, - ], - )]; + hex!("94ef2d6d194084c2de36e0dabfce45d046b37d1106"), + ))]; run_encode_tests(tests); } @@ -257,10 +281,32 @@ fn encode_address() { #[test] fn encode_vector_u8() { let tests = vec![ - ETestPair(vec![], vec![0x80]), - ETestPair(vec![0u8], vec![0]), - ETestPair(vec![0x15], vec![0x15]), - ETestPair(vec![0x40, 0x00], vec![0x82, 0x40, 0x00]), + ETestPair::from((vec![], hex!("80"))), + ETestPair::from((vec![0u8], hex!("00"))), + ETestPair::from((vec![0x15], hex!("15"))), + ETestPair::from((vec![0x40, 0x00], hex!("824000"))), + ]; + run_encode_tests(tests); +} + +#[test] +fn encode_bytes() { + let tests = vec![ + ETestPair::from((Bytes::from_static(&hex!("")), hex!("80"))), + ETestPair::from((Bytes::from_static(&hex!("00")), hex!("00"))), + ETestPair::from((Bytes::from_static(&hex!("15")), hex!("15"))), + ETestPair::from((Bytes::from_static(&hex!("4000")), hex!("824000"))), + ]; + run_encode_tests(tests); +} + +#[test] +fn encode_bytesmut() { + let tests = vec![ + ETestPair::from((BytesMut::from(&[] as &[u8]), hex!("80"))), + ETestPair::from((BytesMut::from(&hex!("00") as &[u8]), hex!("00"))), + ETestPair::from((BytesMut::from(&hex!("15") as &[u8]), hex!("15"))), + ETestPair::from((BytesMut::from(&hex!("4000") as &[u8]), hex!("824000"))), ]; run_encode_tests(tests); } @@ -268,13 +314,10 @@ fn encode_vector_u8() { #[test] fn encode_vector_u64() { let tests = vec![ - VETestPair(vec![], vec![0xc0]), - VETestPair(vec![15u64], vec![0xc1, 0x0f]), - VETestPair(vec![1, 2, 3, 7, 0xff], vec![0xc6, 1, 2, 3, 7, 0x81, 0xff]), - VETestPair( - vec![0xffff_ffff, 1, 2, 3, 7, 0xff], - vec![0xcb, 0x84, 0xff, 0xff, 0xff, 0xff, 1, 2, 3, 7, 0x81, 0xff], - ), + VETestPair::from((vec![], hex!("c0"))), + VETestPair::from((vec![15_u64], hex!("c10f"))), + VETestPair::from((vec![1, 2, 3, 7, 0xff], hex!("c60102030781ff"))), + VETestPair::from((vec![0xffff_ffff, 1, 2, 3, 7, 0xff], hex!("cb84ffffffff0102030781ff"))), ]; run_encode_tests_list(tests); } @@ -285,6 +328,19 @@ fn encode_vector_str() { run_encode_tests_list(tests); } +#[test] +fn clear() { + let mut buffer = BytesMut::new(); + buffer.extend_from_slice(b"junk"); + + let mut s = RlpStream::new_with_buffer(buffer); + s.append(&"parrot"); + s.clear(); + s.append(&"cat"); + + assert_eq!(&s.out()[..], &[b'j', b'u', b'n', b'k', 0x83, b'c', b'a', b't']); +} + struct DTestPair(T, Vec) where T: Decodable + fmt::Debug + cmp::Eq; @@ -315,44 +371,88 @@ where } } +impl From<(T, Repr)> for DTestPair +where + T: Decodable + fmt::Debug + cmp::Eq, + Repr: Into>, +{ + fn from((v, repr): (T, Repr)) -> Self { + Self(v, repr.into()) + } +} + +impl From<(Vec, Repr)> for VDTestPair +where + T: Decodable + fmt::Debug + cmp::Eq, + Repr: Into>, +{ + fn from((v, repr): (Vec, Repr)) -> Self { + Self(v, repr.into()) + } +} + /// Vec (Bytes) is treated as a single value #[test] fn decode_vector_u8() { let tests = vec![ - DTestPair(vec![], vec![0x80]), - DTestPair(vec![0u8], vec![0]), - DTestPair(vec![0x15], vec![0x15]), - DTestPair(vec![0x40, 0x00], vec![0x82, 0x40, 0x00]), + DTestPair::from((vec![], hex!("80"))), + DTestPair::from((vec![0_u8], hex!("00"))), + DTestPair::from((vec![0x15], hex!("15"))), + DTestPair::from((vec![0x40, 0x00], hex!("824000"))), + ]; + run_decode_tests(tests); +} + +#[test] +fn decode_bytes() { + let tests = vec![ + DTestPair::from((Bytes::from_static(&hex!("")), hex!("80"))), + DTestPair::from((Bytes::from_static(&hex!("00")), hex!("00"))), + DTestPair::from((Bytes::from_static(&hex!("15")), hex!("15"))), + DTestPair::from((Bytes::from_static(&hex!("4000")), hex!("824000"))), + ]; + run_decode_tests(tests); +} + +#[test] +fn decode_bytesmut() { + let tests = vec![ + DTestPair::from((BytesMut::from(&hex!("") as &[u8]), hex!("80"))), + DTestPair::from((BytesMut::from(&hex!("00") as &[u8]), hex!("00"))), + DTestPair::from((BytesMut::from(&hex!("15") as &[u8]), hex!("15"))), + DTestPair::from((BytesMut::from(&hex!("4000") as &[u8]), hex!("824000"))), ]; run_decode_tests(tests); } #[test] fn decode_untrusted_u8() { - let tests = vec![DTestPair(0x0u8, vec![0x80]), DTestPair(0x77u8, vec![0x77]), DTestPair(0xccu8, vec![0x81, 0xcc])]; + let tests = vec![ + DTestPair::from((0x0_u8, hex!("80"))), + DTestPair::from((0x77_u8, hex!("77"))), + DTestPair::from((0xcc_u8, hex!("81cc"))), + ]; run_decode_tests(tests); } #[test] fn decode_untrusted_u16() { - let tests = vec![DTestPair(0x100u16, vec![0x82, 0x01, 0x00]), DTestPair(0xffffu16, vec![0x82, 0xff, 0xff])]; + let tests = vec![DTestPair::from((0x100u16, hex!("820100"))), DTestPair::from((0xffffu16, hex!("82ffff")))]; run_decode_tests(tests); } #[test] fn decode_untrusted_u32() { - let tests = vec![ - DTestPair(0x0001_0000u32, vec![0x83, 0x01, 0x00, 0x00]), - DTestPair(0x00ff_ffffu32, vec![0x83, 0xff, 0xff, 0xff]), - ]; + let tests = + vec![DTestPair::from((0x0001_0000u32, hex!("83010000"))), DTestPair::from((0x00ff_ffffu32, hex!("83ffffff")))]; run_decode_tests(tests); } #[test] fn decode_untrusted_u64() { let tests = vec![ - DTestPair(0x0100_0000u64, vec![0x84, 0x01, 0x00, 0x00, 0x00]), - DTestPair(0xFFFF_FFFFu64, vec![0x84, 0xff, 0xff, 0xff, 0xff]), + DTestPair::from((0x0100_0000_u64, hex!("8401000000"))), + DTestPair::from((0xFFFF_FFFF_u64, hex!("84ffffffff"))), ]; run_decode_tests(tests); } @@ -360,8 +460,8 @@ fn decode_untrusted_u64() { #[test] fn decode_untrusted_u128() { let tests = vec![ - DTestPair(0x0100_0000_0000_0000u128, vec![0x88, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]), - DTestPair(0xFFFF_FFFF_FFFF_FFFFu128, vec![0x88, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]), + DTestPair::from((0x0100_0000_0000_0000_u128, hex!("880100000000000000"))), + DTestPair::from((0xFFFF_FFFF_FFFF_FFFF_u128, hex!("88ffffffffffffffff"))), ]; run_decode_tests(tests); } @@ -369,18 +469,13 @@ fn decode_untrusted_u128() { #[test] fn decode_untrusted_u256() { let tests = vec![ - DTestPair(U256::from(0u64), vec![0x80u8]), - DTestPair(U256::from(0x0100_0000u64), vec![0x84, 0x01, 0x00, 0x00, 0x00]), - DTestPair(U256::from(0xffff_ffffu64), vec![0x84, 0xff, 0xff, 0xff, 0xff]), - DTestPair( - ("8090a0b0c0d0e0f00910203040506077000000000000\ - 000100000000000012f0") - .into(), - vec![ - 0xa0, 0x80, 0x90, 0xa0, 0xb0, 0xc0, 0xd0, 0xe0, 0xf0, 0x09, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x77, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x12, 0xf0, - ], - ), + DTestPair::from((U256::from(0_u64), hex!("80"))), + DTestPair::from((U256::from(0x0100_0000_u64), hex!("8401000000"))), + DTestPair::from((U256::from(0xffff_ffff_u64), hex!("84ffffffff"))), + DTestPair::from(( + hex!(" 8090a0b0c0d0e0f00910203040506077000000000000000100000000000012f0").into(), + hex!("a08090a0b0c0d0e0f00910203040506077000000000000000100000000000012f0"), + )), ]; run_decode_tests(tests); } @@ -388,11 +483,11 @@ fn decode_untrusted_u256() { #[test] fn decode_untrusted_str() { let tests = vec![ - DTestPair("cat".to_owned(), vec![0x83, b'c', b'a', b't']), - DTestPair("dog".to_owned(), vec![0x83, b'd', b'o', b'g']), - DTestPair("Marek".to_owned(), vec![0x85, b'M', b'a', b'r', b'e', b'k']), - DTestPair("".to_owned(), vec![0x80]), - DTestPair( + DTestPair::from(("cat".to_owned(), vec![0x83, b'c', b'a', b't'])), + DTestPair::from(("dog".to_owned(), vec![0x83, b'd', b'o', b'g'])), + DTestPair::from(("Marek".to_owned(), vec![0x85, b'M', b'a', b'r', b'e', b'k'])), + DTestPair::from(("".to_owned(), hex!("80"))), + DTestPair::from(( "Lorem ipsum dolor sit amet, consectetur adipisicing elit".to_owned(), vec![ 0xb8, 0x38, b'L', b'o', b'r', b'e', b'm', b' ', b'i', b'p', b's', b'u', b'm', b' ', b'd', b'o', b'l', @@ -400,33 +495,27 @@ fn decode_untrusted_str() { b'e', b'c', b't', b'e', b't', b'u', b'r', b' ', b'a', b'd', b'i', b'p', b'i', b's', b'i', b'c', b'i', b'n', b'g', b' ', b'e', b'l', b'i', b't', ], - ), + )), ]; run_decode_tests(tests); } #[test] fn decode_untrusted_address() { - let tests = vec![DTestPair( + let tests = vec![DTestPair::from(( H160::from(hex!("ef2d6d194084c2de36e0dabfce45d046b37d1106")), - vec![ - 0x94, 0xef, 0x2d, 0x6d, 0x19, 0x40, 0x84, 0xc2, 0xde, 0x36, 0xe0, 0xda, 0xbf, 0xce, 0x45, 0xd0, 0x46, 0xb3, - 0x7d, 0x11, 0x06, - ], - )]; + hex!("94ef2d6d194084c2de36e0dabfce45d046b37d1106"), + ))]; run_decode_tests(tests); } #[test] fn decode_untrusted_vector_u64() { let tests = vec![ - VDTestPair(vec![], vec![0xc0]), - VDTestPair(vec![15u64], vec![0xc1, 0x0f]), - VDTestPair(vec![1, 2, 3, 7, 0xff], vec![0xc6, 1, 2, 3, 7, 0x81, 0xff]), - VDTestPair( - vec![0xffff_ffff, 1, 2, 3, 7, 0xff], - vec![0xcb, 0x84, 0xff, 0xff, 0xff, 0xff, 1, 2, 3, 7, 0x81, 0xff], - ), + VDTestPair::from((vec![], hex!("c0"))), + VDTestPair::from((vec![15_u64], hex!("c10f"))), + VDTestPair::from((vec![1, 2, 3, 7, 0xff], hex!("c60102030781ff"))), + VDTestPair::from((vec![0xffff_ffff, 1, 2, 3, 7, 0xff], hex!("cb84ffffffff0102030781ff"))), ]; run_decode_tests_list(tests); } @@ -451,7 +540,7 @@ fn test_rlp_data_length_check() { #[test] fn test_rlp_long_data_length_check() { - let mut data: Vec = vec![0xb8, 255]; + let mut data = hex!("b8ff").to_vec(); for _ in 0..253 { data.push(b'c'); } @@ -464,7 +553,7 @@ fn test_rlp_long_data_length_check() { #[test] fn test_the_exact_long_string() { - let mut data: Vec = vec![0xb8, 255]; + let mut data = hex!("b8ff").to_vec(); for _ in 0..255 { data.push(b'c'); } @@ -477,7 +566,7 @@ fn test_the_exact_long_string() { #[test] fn test_rlp_2bytes_data_length_check() { - let mut data: Vec = vec![0xb9, 2, 255]; // 512+255 + let mut data = hex!("b902ff").to_vec(); // 512+255 for _ in 0..700 { data.push(b'c'); } @@ -492,13 +581,13 @@ fn test_rlp_2bytes_data_length_check() { fn test_rlp_nested_empty_list_encode() { let mut stream = RlpStream::new_list(2); stream.append_list(&(Vec::new() as Vec)); - stream.append(&40u32); - assert_eq!(stream.out()[..], [0xc2u8, 0xc0u8, 40u8][..]); + stream.append(&0x28_u32); + assert_eq!(stream.out()[..], hex!("c2c028")[..]); } #[test] fn test_rlp_list_length_overflow() { - let data: Vec = vec![0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00]; + let data = hex!("ffffffffffffffffff000000"); let rlp = Rlp::new(&data); let as_val: Result = rlp.val_at(0); assert_eq!(Err(DecoderError::RlpIsTooShort), as_val); diff --git a/runtime/CHANGELOG.md b/runtime/CHANGELOG.md deleted file mode 100644 index 7c02a7690..000000000 --- a/runtime/CHANGELOG.md +++ /dev/null @@ -1,15 +0,0 @@ -# Changelog - -The format is based on [Keep a Changelog]. - -[Keep a Changelog]: http://keepachangelog.com/en/1.0.0/ - -## [Unreleased] - -## [0.1.2] - 2020-07-16 -### Changed -- Port runtime to tokio-compat. [#403](https://github.com/paritytech/parity-common/pull/403) - -## [0.1.1] - 2020-02-11 -### Changed -- Moved to parity common repo, prepared for publishing. [#271](https://github.com/paritytech/parity-common/pull/271) diff --git a/runtime/Cargo.toml b/runtime/Cargo.toml deleted file mode 100644 index 2ab8c8629..000000000 --- a/runtime/Cargo.toml +++ /dev/null @@ -1,21 +0,0 @@ -[package] -name = "parity-runtime" -version = "0.1.2" -authors = ["Parity Technologies "] -edition = "2018" - -description = "Tokio runtime wrapper" -license = "GPL-3.0" -readme = "README.md" -homepage = "https://www.parity.io/" -keywords = ["parity", "runtime", "tokio"] -include = ["Cargo.toml", "src/**/*.rs", "README.md", "CHANGELOG.md"] - -[dependencies] -futures = { version = "0.3", default-features = false, features = ["compat"] } -futures01 = { package = "futures", version = "0.1" } -tokio-compat = "0.1" -tokio = { version = "0.2", features = ["full"] } - -[features] -test-helpers = [] diff --git a/runtime/README.md b/runtime/README.md deleted file mode 100644 index 7cda2a31f..000000000 --- a/runtime/README.md +++ /dev/null @@ -1,6 +0,0 @@ -# parity-runtime - -Wrapper over tokio runtime. Provides: -- Customizable runtime with ability to spawn it in different thread models -- Corresponding runtime executor for tasks -- Runtime handle diff --git a/runtime/examples/simple.rs b/runtime/examples/simple.rs deleted file mode 100644 index c037f74b7..000000000 --- a/runtime/examples/simple.rs +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright 2015-2020 Parity Technologies (UK) Ltd. -// This file is part of Parity Ethereum. - -// Parity Ethereum is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// Parity Ethereum is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with Parity Ethereum. If not, see . - -//! Simple example, illustating usage of runtime wrapper. - -use parity_runtime::Runtime; -use std::{thread::park_timeout, time::Duration}; -use tokio::{fs::read_dir, stream::*}; - -/// Read current directory in a future, which is executed in the created runtime -fn main() { - let runtime = Runtime::with_default_thread_count(); - runtime.executor().spawn_std(async move { - let mut dirs = read_dir(".").await.unwrap(); - while let Some(dir) = dirs.try_next().await.expect("Error") { - println!("{:?}", dir.path()); - } - }); - let timeout = Duration::from_secs(3); - park_timeout(timeout); -} diff --git a/runtime/src/lib.rs b/runtime/src/lib.rs deleted file mode 100644 index 9284454be..000000000 --- a/runtime/src/lib.rs +++ /dev/null @@ -1,215 +0,0 @@ -// Copyright 2015-2020 Parity Technologies (UK) Ltd. -// This file is part of Parity Ethereum. - -// Parity Ethereum is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// Parity Ethereum is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with Parity Ethereum. If not, see . - -//! Tokio Runtime wrapper. - -use futures::compat::*; -use futures01::{Future as Future01, IntoFuture as IntoFuture01}; -use std::{fmt, future::Future, thread}; -pub use tokio_compat::runtime::{Builder as TokioRuntimeBuilder, Runtime as TokioRuntime, TaskExecutor}; - -/// Runtime for futures. -/// -/// Runs in a separate thread. -pub struct Runtime { - executor: Executor, - handle: RuntimeHandle, -} - -const RUNTIME_BUILD_PROOF: &str = - "Building a Tokio runtime will only fail when mio components cannot be initialized (catastrophic)"; - -impl Runtime { - fn new(runtime_bldr: &mut TokioRuntimeBuilder) -> Self { - let mut runtime = runtime_bldr.build().expect(RUNTIME_BUILD_PROOF); - - let (stop, stopped) = tokio::sync::oneshot::channel(); - let (tx, rx) = std::sync::mpsc::channel(); - let handle = thread::spawn(move || { - let executor = runtime.executor(); - runtime.block_on_std(async move { - tx.send(executor).expect("Rx is blocking upper thread."); - let _ = stopped.await; - }); - }); - let executor = rx.recv().expect("tx is transfered to a newly spawned thread."); - - Runtime { - executor: Executor { inner: Mode::Tokio(executor) }, - handle: RuntimeHandle { close: Some(stop), handle: Some(handle) }, - } - } - - /// Spawns a new tokio runtime with a default thread count on a background - /// thread and returns a `Runtime` which can be used to spawn tasks via - /// its executor. - pub fn with_default_thread_count() -> Self { - let mut runtime_bldr = TokioRuntimeBuilder::new(); - Self::new(&mut runtime_bldr) - } - - /// Spawns a new tokio runtime with a the specified thread count on a - /// background thread and returns a `Runtime` which can be used to spawn - /// tasks via its executor. - #[cfg(any(test, feature = "test-helpers"))] - pub fn with_thread_count(thread_count: usize) -> Self { - let mut runtime_bldr = TokioRuntimeBuilder::new(); - runtime_bldr.core_threads(thread_count); - - Self::new(&mut runtime_bldr) - } - - /// Returns this runtime raw executor. - #[cfg(any(test, feature = "test-helpers"))] - pub fn raw_executor(&self) -> TaskExecutor { - if let Mode::Tokio(ref executor) = self.executor.inner { - executor.clone() - } else { - panic!("Runtime is not initialized in Tokio mode.") - } - } - - /// Returns runtime executor. - pub fn executor(&self) -> Executor { - self.executor.clone() - } -} - -#[derive(Clone)] -enum Mode { - Tokio(TaskExecutor), - // Mode used in tests - #[allow(dead_code)] - Sync, - // Mode used in tests - #[allow(dead_code)] - ThreadPerFuture, -} - -impl fmt::Debug for Mode { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - use self::Mode::*; - - match *self { - Tokio(_) => write!(fmt, "tokio"), - Sync => write!(fmt, "synchronous"), - ThreadPerFuture => write!(fmt, "thread per future"), - } - } -} - -fn block_on + Send + 'static>(r: F) { - tokio::runtime::Builder::new().enable_all().basic_scheduler().build().expect(RUNTIME_BUILD_PROOF).block_on(r) -} - -#[derive(Debug, Clone)] -pub struct Executor { - inner: Mode, -} - -impl Executor { - /// Synchronous executor, used for tests. - #[cfg(any(test, feature = "test-helpers"))] - pub fn new_sync() -> Self { - Executor { inner: Mode::Sync } - } - - /// Spawns a new thread for each future (use only for tests). - #[cfg(any(test, feature = "test-helpers"))] - pub fn new_thread_per_future() -> Self { - Executor { inner: Mode::ThreadPerFuture } - } - - /// Spawn a legacy future on this runtime - pub fn spawn(&self, r: R) - where - R: IntoFuture01 + Send + 'static, - R::Future: Send + 'static, - { - self.spawn_std(async move { - let _ = r.into_future().compat().await; - }) - } - - /// Spawn an std future on this runtime - pub fn spawn_std(&self, r: R) - where - R: Future + Send + 'static, - { - match &self.inner { - Mode::Tokio(executor) => { - let _ = executor.spawn_handle_std(r); - } - Mode::Sync => block_on(r), - Mode::ThreadPerFuture => { - thread::spawn(move || block_on(r)); - } - } - } -} - -impl + Send + 'static> futures01::future::Executor for Executor { - fn execute(&self, future: F) -> Result<(), futures01::future::ExecuteError> { - match &self.inner { - Mode::Tokio(executor) => executor.execute(future), - Mode::Sync => { - block_on(async move { - let _ = future.compat().await; - }); - Ok(()) - } - Mode::ThreadPerFuture => { - thread::spawn(move || { - block_on(async move { - let _ = future.compat().await; - }) - }); - Ok(()) - } - } - } -} - -/// A handle to a runtime. Dropping the handle will cause runtime to shutdown. -pub struct RuntimeHandle { - close: Option>, - handle: Option>, -} - -impl From for RuntimeHandle { - fn from(el: Runtime) -> Self { - el.handle - } -} - -impl Drop for RuntimeHandle { - fn drop(&mut self) { - self.close.take().map(|v| v.send(())); - } -} - -impl RuntimeHandle { - /// Blocks current thread and waits until the runtime is finished. - pub fn wait(mut self) -> thread::Result<()> { - self.handle.take().expect("Handle is taken only in `wait`, `wait` is consuming; qed").join() - } - - /// Finishes this runtime. - pub fn close(mut self) { - let _ = - self.close.take().expect("Close is taken only in `close` and `drop`. `close` is consuming; qed").send(()); - } -} diff --git a/transaction-pool/Cargo.toml b/transaction-pool/Cargo.toml index a13bc5767..bb3cb6ad3 100644 --- a/transaction-pool/Cargo.toml +++ b/transaction-pool/Cargo.toml @@ -9,8 +9,7 @@ edition = "2018" [dependencies] log = "0.4.8" -smallvec = "0.6.10" -trace-time = { path = "../trace-time", version = "0.1" } +smallvec = "1.6.0" [dev-dependencies] -ethereum-types = { version = "0.9.0", path = "../ethereum-types" } +ethereum-types = { version = "0.11.0", path = "../ethereum-types" } diff --git a/triehash/CHANGELOG.md b/triehash/CHANGELOG.md index b5f0357b1..2f7d72d64 100644 --- a/triehash/CHANGELOG.md +++ b/triehash/CHANGELOG.md @@ -6,6 +6,8 @@ The format is based on [Keep a Changelog]. ## [Unreleased] +## [0.8.4] - 2020-01-08 +- Updated `rlp` to 0.5. [#463](https://github.com/paritytech/parity-common/pull/463) ## [0.8.3] - 2020-03-16 - License changed from GPL3 to dual MIT/Apache2. [#342](https://github.com/paritytech/parity-common/pull/342) ## [0.8.2] - 2019-12-15 diff --git a/triehash/Cargo.toml b/triehash/Cargo.toml index e50537e76..0825f7b7e 100644 --- a/triehash/Cargo.toml +++ b/triehash/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "triehash" -version = "0.8.3" +version = "0.8.4" authors = ["Parity Technologies "] description = "In-memory patricia trie operations" repository = "https://github.com/paritytech/parity-common" @@ -9,12 +9,12 @@ edition = "2018" [dependencies] hash-db = { version = "0.15.2", default-features = false } -rlp = { version = "0.4", path = "../rlp", default-features = false } +rlp = { version = "0.5", path = "../rlp", default-features = false } [dev-dependencies] criterion = "0.3.0" keccak-hasher = "0.15.2" -ethereum-types = { version = "0.9.0", path = "../ethereum-types" } +ethereum-types = { version = "0.11.0", path = "../ethereum-types" } tiny-keccak = { version = "2.0", features = ["keccak"] } trie-standardmap = "0.15.2" hex-literal = "0.3.1" diff --git a/uint/CHANGELOG.md b/uint/CHANGELOG.md index b856d52fc..3e3ddad3f 100644 --- a/uint/CHANGELOG.md +++ b/uint/CHANGELOG.md @@ -6,6 +6,11 @@ The format is based on [Keep a Changelog]. ## [Unreleased] +## [0.9.0] - 2021-01-05 +- Allow `0x` prefix in `from_str`. [#487](https://github.com/paritytech/parity-common/pull/487) +### Breaking +- Optimized FromStr, made it no_std-compatible. [#468](https://github.com/paritytech/parity-common/pull/468) + ## [0.8.5] - 2020-08-12 - Make const matching work again. [#421](https://github.com/paritytech/parity-common/pull/421) diff --git a/uint/Cargo.toml b/uint/Cargo.toml index 05c208ed4..2e731c06c 100644 --- a/uint/Cargo.toml +++ b/uint/Cargo.toml @@ -4,24 +4,24 @@ homepage = "http://parity.io" repository = "https://github.com/paritytech/parity-common" license = "MIT OR Apache-2.0" name = "uint" -version = "0.8.5" +version = "0.9.0" authors = ["Parity Technologies "] readme = "README.md" edition = "2018" [dependencies] -byteorder = { version = "1.3.2", default-features = false } +byteorder = { version = "1.4.2", default-features = false } crunchy = { version = "0.2.2", default-features = false } qc = { package = "quickcheck", version = "0.9.0", optional = true } -rand = { version = "0.7.2", default-features = false, optional = true } -rustc-hex = { version = "2.0.1", default-features = false } +rand07 = { package = "rand", version = "0.7", default-features = false, optional = true } +hex = { version = "0.4", default-features = false } static_assertions = "1.0.0" arbitrary = { version = "0.4", optional = true } [features] default = ["std"] -std = ["byteorder/std", "rustc-hex/std", "crunchy/std"] -quickcheck = ["qc", "rand"] +std = ["byteorder/std", "crunchy/std", "hex/std"] +quickcheck = ["qc", "rand07"] [[example]] name = "modular" @@ -34,7 +34,7 @@ required-features = ["std"] criterion = "0.3.0" num-bigint = "0.3.1" -[target.'cfg(unix)'.dev-dependencies] +[target.'cfg(all(unix, target_arch = "x86_64"))'.dev-dependencies] rug = { version = "1.6.0", default-features = false, features = ["integer"] } [[bench]] diff --git a/uint/benches/bigint.rs b/uint/benches/bigint.rs index c7767c7ae..a79c01d8e 100644 --- a/uint/benches/bigint.rs +++ b/uint/benches/bigint.rs @@ -71,6 +71,7 @@ criterion_group!( u128_mul, u128_div, from_fixed_array, + from_str, ); criterion_main!(bigint); @@ -642,3 +643,13 @@ fn from_fixed_array(c: &mut Criterion) { }) }); } + +fn from_str(c: &mut Criterion) { + c.bench_function("from_str", move |b| { + b.iter(|| { + black_box(U512::from_str(black_box("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF")).unwrap()); + black_box(U512::from_str(black_box("0FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF")).unwrap()); + black_box(U512::from_str(black_box("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF")).unwrap()); + }) + }); +} diff --git a/uint/src/lib.rs b/uint/src/lib.rs index 7da1f24a5..83ab957a2 100644 --- a/uint/src/lib.rs +++ b/uint/src/lib.rs @@ -19,7 +19,7 @@ pub use byteorder; pub use core as core_; #[doc(hidden)] -pub use rustc_hex; +pub use hex; #[cfg(feature = "quickcheck")] #[doc(hidden)] @@ -27,7 +27,7 @@ pub use qc; #[cfg(feature = "quickcheck")] #[doc(hidden)] -pub use rand; +pub use rand07; #[cfg(feature = "arbitrary")] #[doc(hidden)] diff --git a/uint/src/uint.rs b/uint/src/uint.rs index 84cc8d9a5..702e59e86 100644 --- a/uint/src/uint.rs +++ b/uint/src/uint.rs @@ -29,6 +29,104 @@ //! implementations for even more speed, hidden behind the `x64_arithmetic` //! feature flag. +use core::fmt; + +/// A list of error categories encountered when parsing numbers. +#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)] +#[non_exhaustive] +pub enum FromStrRadixErrKind { + /// A character in the input string is not valid for the given radix. + InvalidCharacter, + + /// The input length is not valid for the given radix. + InvalidLength, + + /// The given radix is not supported. + UnsupportedRadix, +} + +#[derive(Debug)] +enum FromStrRadixErrSrc { + Hex(FromHexError), + Dec(FromDecStrErr), +} + +impl fmt::Display for FromStrRadixErrSrc { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + FromStrRadixErrSrc::Dec(d) => write!(f, "{}", d), + FromStrRadixErrSrc::Hex(h) => write!(f, "{}", h), + } + } +} + +/// The error type for parsing numbers from strings. +#[derive(Debug)] +pub struct FromStrRadixErr { + kind: FromStrRadixErrKind, + source: Option, +} + +impl FromStrRadixErr { + #[doc(hidden)] + pub fn unsupported() -> Self { + Self { kind: FromStrRadixErrKind::UnsupportedRadix, source: None } + } + + /// Returns the corresponding `FromStrRadixErrKind` for this error. + pub fn kind(&self) -> FromStrRadixErrKind { + self.kind + } +} + +impl fmt::Display for FromStrRadixErr { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + if let Some(ref src) = self.source { + return write!(f, "{}", src); + } + + match self.kind { + FromStrRadixErrKind::UnsupportedRadix => write!(f, "the given radix is not supported"), + FromStrRadixErrKind::InvalidCharacter => write!(f, "input contains an invalid character"), + FromStrRadixErrKind::InvalidLength => write!(f, "length not supported for radix or type"), + } + } +} + +#[cfg(feature = "std")] +impl std::error::Error for FromStrRadixErr { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self.source { + Some(FromStrRadixErrSrc::Dec(ref d)) => Some(d), + Some(FromStrRadixErrSrc::Hex(ref h)) => Some(h), + None => None, + } + } +} + +impl From for FromStrRadixErr { + fn from(e: FromDecStrErr) -> Self { + let kind = match e { + FromDecStrErr::InvalidCharacter => FromStrRadixErrKind::InvalidCharacter, + FromDecStrErr::InvalidLength => FromStrRadixErrKind::InvalidLength, + }; + + Self { kind, source: Some(FromStrRadixErrSrc::Dec(e)) } + } +} + +impl From for FromStrRadixErr { + fn from(e: FromHexError) -> Self { + let kind = match e.inner { + hex::FromHexError::InvalidHexCharacter { .. } => FromStrRadixErrKind::InvalidCharacter, + hex::FromHexError::InvalidStringLength => FromStrRadixErrKind::InvalidLength, + hex::FromHexError::OddLength => FromStrRadixErrKind::InvalidLength, + }; + + Self { kind, source: Some(FromStrRadixErrSrc::Hex(e)) } + } +} + /// Conversion from decimal string error #[derive(Debug, PartialEq)] pub enum FromDecStrErr { @@ -38,9 +136,8 @@ pub enum FromDecStrErr { InvalidLength, } -#[cfg(feature = "std")] -impl std::fmt::Display for FromDecStrErr { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +impl fmt::Display for FromDecStrErr { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "{}", @@ -55,6 +152,31 @@ impl std::fmt::Display for FromDecStrErr { #[cfg(feature = "std")] impl std::error::Error for FromDecStrErr {} +#[derive(Debug)] +pub struct FromHexError { + inner: hex::FromHexError, +} + +impl fmt::Display for FromHexError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}", self.inner) + } +} + +#[cfg(feature = "std")] +impl std::error::Error for FromHexError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + Some(&self.inner) + } +} + +#[doc(hidden)] +impl From for FromHexError { + fn from(inner: hex::FromHexError) -> Self { + Self { inner } + } +} + #[macro_export] #[doc(hidden)] macro_rules! impl_map_from { @@ -467,6 +589,18 @@ macro_rules! construct_uint { /// Maximum value. pub const MAX: $name = $name([u64::max_value(); $n_words]); + /// Converts a string slice in a given base to an integer. Only supports radixes of 10 + /// and 16. + pub fn from_str_radix(txt: &str, radix: u32) -> Result { + let parsed = match radix { + 10 => Self::from_dec_str(txt)?, + 16 => core::str::FromStr::from_str(txt)?, + _ => return Err($crate::FromStrRadixErr::unsupported()), + }; + + Ok(parsed) + } + /// Convert from a decimal string. pub fn from_dec_str(value: &str) -> $crate::core_::result::Result { if !value.bytes().all(|b| b >= 48 && b <= 57) { @@ -1550,31 +1684,35 @@ macro_rules! construct_uint { } } - $crate::impl_std_for_uint!($name, $n_words); - // `$n_words * 8` because macro expects bytes and - // uints use 64 bit (8 byte) words - $crate::impl_quickcheck_arbitrary_for_uint!($name, ($n_words * 8)); - $crate::impl_arbitrary_for_uint!($name, ($n_words * 8)); - } -} - -#[cfg(feature = "std")] -#[macro_export] -#[doc(hidden)] -macro_rules! impl_std_for_uint { - ($name: ident, $n_words: tt) => { impl $crate::core_::str::FromStr for $name { - type Err = $crate::rustc_hex::FromHexError; + type Err = $crate::FromHexError; fn from_str(value: &str) -> $crate::core_::result::Result<$name, Self::Err> { - use $crate::rustc_hex::FromHex; - let bytes: Vec = match value.len() % 2 == 0 { - true => value.from_hex()?, - false => ("0".to_owned() + value).from_hex()?, - }; + let value = value.strip_prefix("0x").unwrap_or(value); + const BYTES_LEN: usize = $n_words * 8; + const MAX_ENCODED_LEN: usize = BYTES_LEN * 2; + + let mut bytes = [0_u8; BYTES_LEN]; + + let encoded = value.as_bytes(); - if $n_words * 8 < bytes.len() { - return Err(Self::Err::InvalidHexLength); + if encoded.len() > MAX_ENCODED_LEN { + return Err($crate::hex::FromHexError::InvalidStringLength.into()); + } + + if encoded.len() % 2 == 0 { + let out = &mut bytes[BYTES_LEN - encoded.len() / 2..]; + + $crate::hex::decode_to_slice(encoded, out).map_err(Self::Err::from)?; + } else { + // Prepend '0' by overlaying our value on a scratch buffer filled with '0' characters. + let mut s = [b'0'; MAX_ENCODED_LEN]; + s[MAX_ENCODED_LEN - encoded.len()..].copy_from_slice(encoded); + let encoded = &s[MAX_ENCODED_LEN - encoded.len() - 1..]; + + let out = &mut bytes[BYTES_LEN - encoded.len() / 2..]; + + $crate::hex::decode_to_slice(encoded, out).map_err(Self::Err::from)?; } let bytes_ref: &[u8] = &bytes; @@ -1587,14 +1725,12 @@ macro_rules! impl_std_for_uint { s.parse().unwrap() } } - }; -} -#[cfg(not(feature = "std"))] -#[macro_export] -#[doc(hidden)] -macro_rules! impl_std_for_uint { - ($name: ident, $n_words: tt) => {}; + // `$n_words * 8` because macro expects bytes and + // uints use 64 bit (8 byte) words + $crate::impl_quickcheck_arbitrary_for_uint!($name, ($n_words * 8)); + $crate::impl_arbitrary_for_uint!($name, ($n_words * 8)); + } } #[cfg(feature = "quickcheck")] @@ -1606,8 +1742,8 @@ macro_rules! impl_quickcheck_arbitrary_for_uint { fn arbitrary(g: &mut G) -> Self { let mut res = [0u8; $n_bytes]; - use $crate::rand::Rng; - let p: f64 = $crate::rand::rngs::OsRng.gen(); + use $crate::rand07::Rng; + let p: f64 = $crate::rand07::rngs::OsRng.gen(); // make it more likely to generate smaller numbers that // don't use up the full $n_bytes let range = diff --git a/uint/tests/uint_tests.rs b/uint/tests/uint_tests.rs index 9319b40e1..318253279 100644 --- a/uint/tests/uint_tests.rs +++ b/uint/tests/uint_tests.rs @@ -133,7 +133,12 @@ fn uint256_from() { // test initializtion from string let sa = U256::from_str("0a").unwrap(); + let sa2 = U256::from_str("0x0a").unwrap(); + assert_eq!(sa2, sa); assert_eq!(e, sa); + assert_eq!(U256([0, 0, 0, 0]), U256::from_str("").unwrap()); + assert_eq!(U256([0x1, 0, 0, 0]), U256::from_str("1").unwrap()); + assert_eq!(U256([0x101, 0, 0, 0]), U256::from_str("101").unwrap()); assert_eq!(U256([0x1010, 0, 0, 0]), U256::from_str("1010").unwrap()); assert_eq!(U256([0x12f0, 0, 0, 0]), U256::from_str("12f0").unwrap()); assert_eq!(U256([0x12f0, 0, 0, 0]), U256::from_str("0000000012f0").unwrap()); @@ -145,6 +150,7 @@ fn uint256_from() { // This string contains more bits than what fits in a U256. assert!(U256::from_str("000000000000000000000000000000000000000000000000000000000000000000").is_err()); + assert!(U256::from_str("100000000000000000000000000000000000000000000000000000000000000000").is_err()); } #[test] @@ -1012,6 +1018,15 @@ fn leading_zeros() { assert_eq!(U256::from("0000000000000000000000000000000000000000000000000000000000000000").leading_zeros(), 256); } +#[test] +fn issue_507_roundtrip() { + let mut b32 = <[u8; 32]>::default(); + let a = U256::from(10); + a.to_little_endian(&mut b32); + let b = U256::from_little_endian(&b32[..]); + assert_eq!(a, b); +} + #[test] fn trailing_zeros() { assert_eq!(U256::from("1adbdd6bd6ff027485484b97f8a6a4c7129756dd100000000000000000000000").trailing_zeros(), 92);