From a0f406e26b5585218c94a8066d5f832dfba3b656 Mon Sep 17 00:00:00 2001 From: rakita Date: Fri, 12 Mar 2021 10:12:42 +0100 Subject: [PATCH] Ethereum-types and various libs upgrade (#315) * Upgrade Eth types ethereum-types -> 0.9.2 rlp -> 0.4.6 keccak-hash -> 0.5.0 parity-crypto -> 0.6.2 ethabi -> 0.12.0 ethabi-derive -> 0.12.0 ethabi-contract -> 0.11.0 ethbloom -> 0.9.1 rand -> 0.7.3 trie-standardmap -> 0.15.2 triehash -> 0.5.0 * backport #10714. Small changes, merge fixes Co-authored-by: mdben1247 --- Cargo.lock | 828 ++++++++---------- Cargo.toml | 10 +- bin/ethkey/Cargo.toml | 1 + bin/ethkey/src/main.rs | 23 +- bin/evmbin/Cargo.toml | 2 +- bin/evmbin/src/display/json.rs | 7 +- bin/evmbin/src/display/std_json.rs | 7 +- bin/evmbin/src/info.rs | 5 +- bin/evmbin/src/main.rs | 5 +- bin/oe/account_utils.rs | 15 +- bin/oe/configuration.rs | 4 +- bin/oe/helpers.rs | 10 +- bin/oe/lib.rs | 1 + bin/oe/presale.rs | 5 +- bin/oe/run.rs | 6 +- bin/oe/secretstore.rs | 3 +- crates/accounts/Cargo.toml | 3 +- crates/accounts/ethkey/Cargo.toml | 8 +- crates/accounts/ethkey/src/brain.rs | 23 +- crates/accounts/ethkey/src/brain_prefix.rs | 16 +- crates/accounts/ethkey/src/brain_recover.rs | 7 +- crates/accounts/ethkey/src/crypto.rs | 202 ----- crates/accounts/ethkey/src/error.rs | 81 -- crates/accounts/ethkey/src/extended.rs | 589 ------------- crates/accounts/ethkey/src/keccak.rs | 33 - crates/accounts/ethkey/src/keypair.rs | 120 --- crates/accounts/ethkey/src/lib.rs | 54 +- crates/accounts/ethkey/src/math.rs | 134 --- crates/accounts/ethkey/src/prefix.rs | 20 +- crates/accounts/ethkey/src/random.rs | 42 - crates/accounts/ethkey/src/secret.rs | 322 ------- crates/accounts/ethkey/src/signature.rs | 325 ------- crates/accounts/ethstore/Cargo.toml | 6 +- .../accounts/ethstore/src/account/crypto.rs | 18 +- .../ethstore/src/account/safe_account.rs | 19 +- .../ethstore/src/accounts_dir/disk.rs | 8 +- .../ethstore/src/accounts_dir/memory.rs | 4 +- crates/accounts/ethstore/src/error.rs | 30 +- crates/accounts/ethstore/src/ethkey.rs | 1 + crates/accounts/ethstore/src/ethstore.rs | 33 +- crates/accounts/ethstore/src/import.rs | 2 +- crates/accounts/ethstore/src/lib.rs | 2 +- crates/accounts/ethstore/src/presale.rs | 12 +- crates/accounts/ethstore/src/random.rs | 10 +- crates/accounts/ethstore/src/secret_store.rs | 5 +- crates/accounts/ethstore/tests/api.rs | 64 +- .../ethstore/tests/util/transient_dir.rs | 4 +- crates/accounts/src/account_data.rs | 3 +- crates/accounts/src/lib.rs | 67 +- crates/accounts/src/stores.rs | 19 +- crates/concensus/ethash/Cargo.toml | 5 +- crates/concensus/ethash/src/cache.rs | 26 +- crates/concensus/ethash/src/compute.rs | 135 ++- crates/concensus/ethash/src/keccak.rs | 43 +- crates/concensus/ethash/src/lib.rs | 30 +- crates/concensus/miner/Cargo.toml | 15 +- crates/concensus/miner/local-store/Cargo.toml | 3 +- crates/concensus/miner/local-store/src/lib.rs | 7 +- crates/concensus/miner/src/external.rs | 8 +- crates/concensus/miner/src/lib.rs | 6 +- crates/concensus/miner/src/pool/listener.rs | 3 +- .../miner/src/pool/local_transactions.rs | 4 +- crates/concensus/miner/src/pool/mod.rs | 4 +- crates/concensus/miner/src/pool/replace.rs | 18 +- crates/concensus/miner/src/pool/tests/tx.rs | 10 +- crates/concensus/miner/stratum/Cargo.toml | 4 +- crates/db/blooms-db/Cargo.toml | 2 +- crates/db/blooms-db/benches/blooms.rs | 10 +- crates/db/blooms-db/src/db.rs | 50 +- crates/db/blooms-db/src/file.rs | 10 +- crates/db/db/Cargo.toml | 6 +- crates/db/db/src/db.rs | 40 +- crates/db/db/src/keys.rs | 46 +- crates/db/journaldb/Cargo.toml | 8 +- crates/db/journaldb/src/archivedb.rs | 12 +- crates/db/journaldb/src/earlymergedb.rs | 30 +- crates/db/journaldb/src/lib.rs | 2 +- crates/db/journaldb/src/overlaydb.rs | 6 +- crates/db/journaldb/src/overlayrecentdb.rs | 26 +- crates/db/journaldb/src/refcounteddb.rs | 7 +- crates/db/memory-db/Cargo.toml | 12 +- crates/db/memory-db/src/lib.rs | 14 +- crates/db/patricia-trie-ethereum/Cargo.toml | 6 +- crates/db/patricia-trie-ethereum/src/lib.rs | 4 +- crates/ethcore/Cargo.toml | 20 +- crates/ethcore/benches/builtin.rs | 8 +- crates/ethcore/blockchain/Cargo.toml | 11 +- crates/ethcore/blockchain/src/blockchain.rs | 95 +- crates/ethcore/blockchain/src/import_route.rs | 31 +- crates/ethcore/blockchain/src/lib.rs | 2 + crates/ethcore/service/Cargo.toml | 2 +- crates/ethcore/src/account_db.rs | 4 +- crates/ethcore/src/block.rs | 2 +- crates/ethcore/src/client/client.rs | 29 +- crates/ethcore/src/client/test_client.rs | 24 +- .../src/engines/authority_round/mod.rs | 27 +- crates/ethcore/src/engines/basic_authority.rs | 9 +- crates/ethcore/src/engines/block_reward.rs | 19 +- .../ethcore/src/engines/clique/block_state.rs | 2 +- crates/ethcore/src/engines/clique/mod.rs | 8 +- crates/ethcore/src/engines/clique/tests.rs | 11 +- crates/ethcore/src/engines/clique/util.rs | 11 +- crates/ethcore/src/engines/mod.rs | 2 +- crates/ethcore/src/engines/signer.rs | 29 +- .../src/engines/validator_set/contract.rs | 4 +- .../src/engines/validator_set/multi.rs | 2 +- .../engines/validator_set/safe_contract.rs | 2 +- .../src/engines/validator_set/simple_list.rs | 10 +- .../ethcore/src/engines/validator_set/test.rs | 9 +- crates/ethcore/src/error.rs | 2 +- crates/ethcore/src/ethereum/ethash.rs | 26 +- crates/ethcore/src/ethereum/mod.rs | 27 +- crates/ethcore/src/executive.rs | 76 +- crates/ethcore/src/externalities.rs | 29 +- crates/ethcore/src/json_tests/executive.rs | 8 +- crates/ethcore/src/lib.rs | 6 +- crates/ethcore/src/machine/impls.rs | 11 +- crates/ethcore/src/miner/miner.rs | 10 +- crates/ethcore/src/miner/stratum.rs | 10 +- crates/ethcore/src/pod_account.rs | 57 +- crates/ethcore/src/pod_state.rs | 27 +- crates/ethcore/src/snapshot/account.rs | 4 +- crates/ethcore/src/snapshot/block.rs | 25 +- crates/ethcore/src/snapshot/consensus/work.rs | 4 +- crates/ethcore/src/snapshot/mod.rs | 4 +- crates/ethcore/src/snapshot/tests/helpers.rs | 2 +- .../src/snapshot/tests/proof_of_authority.rs | 4 +- crates/ethcore/src/snapshot/tests/service.rs | 2 + crates/ethcore/src/snapshot/tests/state.rs | 11 +- crates/ethcore/src/snapshot/watcher.rs | 4 +- crates/ethcore/src/spec/spec.rs | 24 +- crates/ethcore/src/state/account.rs | 68 +- crates/ethcore/src/state/mod.rs | 542 +++++++----- crates/ethcore/src/state/substate.rs | 15 +- crates/ethcore/src/test_helpers.rs | 6 +- crates/ethcore/src/tests/client.rs | 2 +- crates/ethcore/src/tests/evm.rs | 16 +- crates/ethcore/src/tests/trace.rs | 8 +- crates/ethcore/src/trace/db.rs | 51 +- crates/ethcore/src/trace/types/error.rs | 3 +- crates/ethcore/src/trace/types/filter.rs | 119 +-- crates/ethcore/src/trace/types/flat.rs | 30 +- crates/ethcore/src/trace/types/trace.rs | 14 +- crates/ethcore/src/tx_filter.rs | 99 ++- crates/ethcore/src/verification/queue/kind.rs | 21 +- crates/ethcore/src/verification/queue/mod.rs | 27 +- .../ethcore/src/verification/verification.rs | 25 +- crates/ethcore/sync/Cargo.toml | 13 +- crates/ethcore/sync/src/api.rs | 2 +- crates/ethcore/sync/src/block_sync.rs | 10 +- crates/ethcore/sync/src/blocks.rs | 31 +- crates/ethcore/sync/src/chain/handler.rs | 6 +- crates/ethcore/sync/src/chain/mod.rs | 28 +- crates/ethcore/sync/src/chain/propagator.rs | 4 +- crates/ethcore/sync/src/chain/supplier.rs | 34 +- crates/ethcore/sync/src/lib.rs | 7 +- crates/ethcore/sync/src/snapshot.rs | 16 +- crates/ethcore/sync/src/tests/consensus.rs | 6 +- crates/ethcore/sync/src/tests/helpers.rs | 5 +- crates/ethcore/sync/src/tests/snapshot.rs | 8 +- crates/ethcore/sync/src/transactions_stats.rs | 11 +- crates/ethcore/types/Cargo.toml | 10 +- crates/ethcore/types/src/account_diff.rs | 12 +- crates/ethcore/types/src/encoded.rs | 26 +- crates/ethcore/types/src/filter.rs | 123 ++- crates/ethcore/types/src/header.rs | 10 +- crates/ethcore/types/src/lib.rs | 4 +- crates/ethcore/types/src/log_entry.rs | 21 +- crates/ethcore/types/src/receipt.rs | 34 +- crates/ethcore/types/src/transaction/error.rs | 5 +- .../types/src/transaction/transaction.rs | 144 ++- crates/ethcore/types/src/views/block.rs | 5 +- crates/ethcore/types/src/views/header.rs | 23 +- crates/ethjson/Cargo.toml | 4 +- crates/ethjson/src/hash.rs | 15 +- crates/ethjson/src/lib.rs | 2 +- crates/ethjson/src/spec/authority_round.rs | 13 +- crates/ethjson/src/spec/basic_authority.rs | 7 +- crates/ethjson/src/spec/ethash.rs | 87 +- crates/ethjson/src/spec/genesis.rs | 37 +- crates/ethjson/src/spec/seal.rs | 18 +- crates/ethjson/src/spec/validator_set.rs | 19 +- crates/ethjson/src/state/test.rs | 7 +- crates/ethjson/src/uint.rs | 7 +- crates/net/network-devp2p/Cargo.toml | 10 +- crates/net/network-devp2p/src/connection.rs | 272 +++--- crates/net/network-devp2p/src/discovery.rs | 36 +- crates/net/network-devp2p/src/handshake.rs | 61 +- crates/net/network-devp2p/src/host.rs | 6 +- crates/net/network-devp2p/src/node_table.rs | 7 +- crates/net/network-devp2p/tests/tests.rs | 6 +- crates/net/network/Cargo.toml | 6 +- crates/net/network/src/error.rs | 11 +- crates/net/network/src/lib.rs | 2 +- crates/net/node-filter/Cargo.toml | 10 +- crates/net/node-filter/src/lib.rs | 19 +- crates/rpc/Cargo.toml | 11 +- crates/rpc/src/authcodes.rs | 9 +- crates/rpc/src/v1/extractors.rs | 10 +- crates/rpc/src/v1/helpers/dispatch/mod.rs | 3 +- crates/rpc/src/v1/helpers/dispatch/signing.rs | 3 +- crates/rpc/src/v1/helpers/engine_signer.rs | 7 +- .../helpers/external_signer/signing_queue.rs | 17 +- crates/rpc/src/v1/helpers/secretstore.rs | 32 +- crates/rpc/src/v1/helpers/signature.rs | 8 +- crates/rpc/src/v1/helpers/subscribers.rs | 39 +- .../src/v1/helpers/subscription_manager.rs | 4 +- crates/rpc/src/v1/impls/eth.rs | 17 +- crates/rpc/src/v1/impls/eth_pubsub.rs | 6 +- crates/rpc/src/v1/impls/parity.rs | 9 +- crates/rpc/src/v1/impls/parity_accounts.rs | 7 +- crates/rpc/src/v1/impls/parity_set.rs | 3 +- crates/rpc/src/v1/impls/personal.rs | 4 +- crates/rpc/src/v1/impls/secretstore.rs | 8 +- crates/rpc/src/v1/impls/signer.rs | 24 +- crates/rpc/src/v1/tests/eth.rs | 2 +- .../rpc/src/v1/tests/helpers/sync_provider.rs | 14 +- crates/rpc/src/v1/tests/mocked/eth.rs | 51 +- crates/rpc/src/v1/tests/mocked/eth_pubsub.rs | 38 +- crates/rpc/src/v1/tests/mocked/parity.rs | 36 +- .../src/v1/tests/mocked/parity_accounts.rs | 8 +- crates/rpc/src/v1/tests/mocked/parity_set.rs | 4 +- crates/rpc/src/v1/tests/mocked/personal.rs | 10 +- crates/rpc/src/v1/tests/mocked/pubsub.rs | 8 +- crates/rpc/src/v1/tests/mocked/secretstore.rs | 6 +- crates/rpc/src/v1/tests/mocked/signer.rs | 12 +- crates/rpc/src/v1/tests/mocked/signing.rs | 28 +- .../rpc/src/v1/tests/mocked/signing_unsafe.rs | 2 +- crates/rpc/src/v1/tests/mocked/traces.rs | 9 +- crates/rpc/src/v1/types/call_request.rs | 6 +- crates/rpc/src/v1/types/confirmations.rs | 22 +- crates/rpc/src/v1/types/eth_types.rs | 14 +- crates/rpc/src/v1/types/filter.rs | 12 +- crates/rpc/src/v1/types/provenance.rs | 11 +- crates/rpc/src/v1/types/receipt.rs | 9 +- crates/rpc/src/v1/types/secretstore.rs | 9 +- crates/rpc/src/v1/types/sync.rs | 3 +- crates/rpc/src/v1/types/trace.rs | 49 +- crates/rpc/src/v1/types/trace_filter.rs | 4 +- crates/rpc/src/v1/types/transaction.rs | 7 +- .../rpc/src/v1/types/transaction_request.rs | 6 +- crates/util/EIP-712/Cargo.toml | 6 +- crates/util/EIP-712/src/encode.rs | 12 +- crates/util/cli-signer/Cargo.toml | 2 +- crates/util/cli-signer/rpc-client/Cargo.toml | 4 +- crates/util/dir/Cargo.toml | 2 +- crates/util/dir/src/lib.rs | 8 +- crates/util/fastmap/Cargo.toml | 2 +- crates/util/fastmap/src/lib.rs | 2 +- crates/util/keccak-hasher/Cargo.toml | 2 +- crates/util/memory-cache/Cargo.toml | 2 +- crates/util/memory-cache/src/lib.rs | 12 +- crates/util/rlp-compress/Cargo.toml | 2 +- crates/util/rlp-derive/Cargo.toml | 2 +- crates/util/triehash-ethereum/Cargo.toml | 4 +- crates/util/triehash-ethereum/src/lib.rs | 5 +- crates/util/version/Cargo.toml | 2 +- crates/vm/builtin/Cargo.toml | 6 +- crates/vm/builtin/src/lib.rs | 20 +- crates/vm/call-contract/Cargo.toml | 2 +- crates/vm/evm/Cargo.toml | 6 +- crates/vm/evm/benches/basic.rs | 1 - crates/vm/evm/src/interpreter/gasometer.rs | 10 +- crates/vm/evm/src/interpreter/mod.rs | 40 +- crates/vm/evm/src/interpreter/shared_cache.rs | 15 +- crates/vm/evm/src/lib.rs | 2 +- crates/vm/evm/src/tests.rs | 34 +- crates/vm/vm/Cargo.toml | 6 +- crates/vm/vm/src/access_list.rs | 89 +- crates/vm/vm/src/action_params.rs | 10 +- crates/vm/vm/src/tests.rs | 9 +- crates/vm/wasm/Cargo.toml | 2 +- crates/vm/wasm/src/runtime.rs | 22 +- 273 files changed, 3051 insertions(+), 4775 deletions(-) delete mode 100644 crates/accounts/ethkey/src/crypto.rs delete mode 100644 crates/accounts/ethkey/src/error.rs delete mode 100644 crates/accounts/ethkey/src/extended.rs delete mode 100644 crates/accounts/ethkey/src/keccak.rs delete mode 100644 crates/accounts/ethkey/src/keypair.rs delete mode 100644 crates/accounts/ethkey/src/math.rs delete mode 100644 crates/accounts/ethkey/src/random.rs delete mode 100644 crates/accounts/ethkey/src/secret.rs delete mode 100644 crates/accounts/ethkey/src/signature.rs diff --git a/Cargo.lock b/Cargo.lock index 32155cafd..97cb5d193 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -45,6 +45,21 @@ dependencies = [ "stream-cipher", ] +[[package]] +name = "ahash" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29661b60bec623f0586702976ff4d0c9942dcb6723161c2df0eea78455cfedfb" +dependencies = [ + "const-random", +] + +[[package]] +name = "ahash" +version = "0.3.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8fd72866655d1904d6b0997d0b07ba561047d070fbe29de039031c641b61217" + [[package]] name = "aho-corasick" version = "0.6.10" @@ -89,12 +104,6 @@ dependencies = [ "xdg", ] -[[package]] -name = "arrayref" -version = "0.3.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d382e583f07208808f6b1249e60848879ba3543f57c32277bf52d69c2f0f0ee" - [[package]] name = "arrayvec" version = "0.4.12" @@ -145,7 +154,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "924c76597f0d9ca25d762c25a4d369d51267536465dc5064bdf0eb073ed477ea" dependencies = [ "backtrace-sys", - "cfg-if", + "cfg-if 0.1.10", "libc", "rustc-demangle", ] @@ -216,16 +225,6 @@ dependencies = [ "radium", ] -[[package]] -name = "block-buffer" -version = "0.3.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a076c298b9ecdb530ed9d967e74a6027d6a7478924520acddcddc24c1c8ab3ab" -dependencies = [ - "arrayref", - "byte-tools 0.2.0", -] - [[package]] name = "block-buffer" version = "0.7.3" @@ -233,9 +232,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c0940dc441f31689269e10ac70eb1002a3a1d3ad1390e030043662eb7fe4688b" dependencies = [ "block-padding", - "byte-tools 0.3.1", + "byte-tools", "byteorder", - "generic-array 0.12.3", + "generic-array", ] [[package]] @@ -244,7 +243,7 @@ version = "0.6.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1c924d49bd09e7c06003acda26cd9742e796e34282ec6c1189404dee0c1f4774" dependencies = [ - "generic-array 0.12.3", + "generic-array", ] [[package]] @@ -263,7 +262,7 @@ version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6d4dc3af3ee2e12f3e5d224e5e1e3d73668abbeb69e566d361f7d5563a4fdf09" dependencies = [ - "byte-tools 0.3.1", + "byte-tools", ] [[package]] @@ -272,7 +271,7 @@ version = "0.1.0" dependencies = [ "byteorder", "criterion 0.3.0", - "ethbloom 0.5.0", + "ethbloom", "parking_lot 0.7.1", "tempdir", "tiny-keccak 1.5.0", @@ -287,7 +286,7 @@ dependencies = [ "crunchy 0.2.2", "lazy_static", "rand 0.5.6", - "rustc-hex 2.0.1", + "rustc-hex 2.1.0", ] [[package]] @@ -314,12 +313,6 @@ version = "0.3.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b0a5e3906bcbf133e33c1d4d95afc664ad37fbdb9f6568d8043e7ea8c27d93d3" -[[package]] -name = "byte-tools" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "560c32574a12a89ecd91f5e742165893f86e3ab98d21f8ea548658eb9eef5f40" - [[package]] name = "byte-tools" version = "0.3.1" @@ -360,9 +353,9 @@ checksum = "926013f2860c46252efceabb19f4a6b308197505082c609025aa6706c011d427" [[package]] name = "cc" -version = "1.0.47" +version = "1.0.41" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aa87058dce70a3ff5621797f1506cb837edd02ac4c0ae642b4542dce802908b8" +checksum = "8dae9c4b8fedcae85592ba623c4fd08cfdab3e3b72d6df780c6ead964a69bfff" [[package]] name = "cfg-if" @@ -370,6 +363,12 @@ version = "0.1.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822" +[[package]] +name = "cfg-if" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" + [[package]] name = "chainspec" version = "0.1.0" @@ -409,7 +408,7 @@ dependencies = [ name = "cli-signer" version = "1.4.0" dependencies = [ - "ethereum-types 0.4.2", + "ethereum-types", "futures", "parity-rpc", "parity-rpc-client", @@ -438,12 +437,12 @@ dependencies = [ name = "common-types" version = "0.1.0" dependencies = [ - "ethereum-types 0.4.2", - "ethkey", - "heapsize", + "ethereum-types", "keccak-hash", "parity-bytes", - "rlp 0.3.0", + "parity-crypto", + "parity-util-mem", + "rlp", "rlp_derive", "rustc-hex 1.0.0", "serde", @@ -453,10 +452,26 @@ dependencies = [ ] [[package]] -name = "constant_time_eq" -version = "0.1.4" +name = "const-random" +version = "0.1.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "995a44c877f9212528ccc74b21a232f66ad69001e40ede5bcee2ac9ef2657120" +checksum = "f590d95d011aa80b063ffe3253422ed5aa462af4e9867d43ce8337562bac77c4" +dependencies = [ + "const-random-macro", + "proc-macro-hack", +] + +[[package]] +name = "const-random-macro" +version = "0.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "615f6e27d000a2bffbc7f2f6a8669179378fa27ee4d0a509e985dfc0a7defb40" +dependencies = [ + "getrandom 0.2.2", + "lazy_static", + "proc-macro-hack", + "tiny-keccak 2.0.2", +] [[package]] name = "crc" @@ -567,7 +582,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fedcd6772e37f3da2a9af9bf12ebe046c0dfe657992377b4df982a2b54cd37a9" dependencies = [ "arrayvec 0.4.12", - "cfg-if", + "cfg-if 0.1.10", "crossbeam-utils 0.6.6", "lazy_static", "memoffset", @@ -589,7 +604,7 @@ version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "774ba60a54c213d409d5353bda12d49cd68d14e45036a285234c8d6f91f92570" dependencies = [ - "cfg-if", + "cfg-if 0.1.10", "crossbeam-utils 0.7.2", "maybe-uninit", ] @@ -600,7 +615,7 @@ version = "0.6.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "04973fa96e96579258a5091af6003abde64af786b860f18622b82e026cca60e6" dependencies = [ - "cfg-if", + "cfg-if 0.1.10", "lazy_static", ] @@ -611,7 +626,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c3c7c73a2d1e9fc0886a08b93e98eb643461230d5f1925e4036204d5f2e261a8" dependencies = [ "autocfg 1.0.0", - "cfg-if", + "cfg-if 0.1.10", "lazy_static", ] @@ -627,23 +642,13 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7a81dae078cea95a014a339291cec439d2f232ebe854a9d672b796c6afafa9b7" -[[package]] -name = "crypto-mac" -version = "0.6.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7afa06d05a046c7a47c3a849907ec303504608c927f4e85f7bfff22b7180d971" -dependencies = [ - "constant_time_eq", - "generic-array 0.9.0", -] - [[package]] name = "crypto-mac" version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4434400df11d95d556bac068ddfedd482915eb18fe8bea89bc80b6e4b1c179e5" dependencies = [ - "generic-array 0.12.3", + "generic-array", "subtle 1.0.0", ] @@ -715,22 +720,13 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b3304d19798a8e067e48d8e69b2c37f0b5e9b4e462504ad9e27e9f3fce02bba8" -[[package]] -name = "digest" -version = "0.7.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "03b072242a8cbaf9c145665af9d250c59af3b958f83ed6824e13533cf76d5b90" -dependencies = [ - "generic-array 0.9.0", -] - [[package]] name = "digest" version = "0.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f3d0c8c8752312f9713efd397ff63acb9f85585afbf179282e720e7704954dd5" dependencies = [ - "generic-array 0.12.3", + "generic-array", ] [[package]] @@ -738,7 +734,7 @@ name = "dir" version = "0.1.2" dependencies = [ "app_dirs", - "ethereum-types 0.4.2", + "ethereum-types", "home 0.3.4", "journaldb", ] @@ -765,7 +761,7 @@ checksum = "bbbaaaf38131deb9ca518a274a45bfdb8771f139517b073b16c2d3d32ae5037b" name = "eip-152" version = "0.1.0" dependencies = [ - "rustc-hex 2.0.1", + "rustc-hex 2.1.0", ] [[package]] @@ -773,7 +769,7 @@ name = "eip-712" version = "0.1.0" dependencies = [ "ethabi", - "ethereum-types 0.4.2", + "ethereum-types", "failure", "indexmap", "itertools 0.7.11", @@ -781,7 +777,7 @@ dependencies = [ "lazy_static", "lunarity-lexer", "regex 1.3.9", - "rustc-hex 2.0.1", + "rustc-hex 2.1.0", "serde", "serde_derive", "serde_json", @@ -839,12 +835,12 @@ dependencies = [ [[package]] name = "eth-secp256k1" version = "0.5.7" -source = "git+https://github.com/paritytech/rust-secp256k1?rev=ccc06e7480148b723eb44ac56cf4d20eec380b6f#ccc06e7480148b723eb44ac56cf4d20eec380b6f" +source = "git+https://github.com/paritytech/rust-secp256k1?rev=9791e79f21a5309dcb6e0bd254b1ef88fca2f1f4#9791e79f21a5309dcb6e0bd254b1ef88fca2f1f4" dependencies = [ "arrayvec 0.4.12", "cc", - "cfg-if", - "rand 0.4.6", + "cfg-if 0.1.10", + "rand 0.6.5", ] [[package]] @@ -875,36 +871,35 @@ dependencies = [ [[package]] name = "ethabi" -version = "6.1.0" +version = "12.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8eb362fde43ed0b50b258bb0c72b72b3dccfd29f8de9506295eaf9251c49ca31" +checksum = "052a565e3de82944527d6d10a465697e6bb92476b772ca7141080c901f6a63c6" dependencies = [ - "error-chain", - "ethereum-types 0.4.2", - "rustc-hex 2.0.1", + "ethereum-types", + "rustc-hex 2.1.0", "serde", - "serde_derive", "serde_json", "tiny-keccak 1.5.0", + "uint", ] [[package]] name = "ethabi-contract" -version = "6.0.0" +version = "11.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "795e25fd868e12a59ca235dbe1f6cc8f1eba8f67d6a39438b29535e0126e0c27" +checksum = "88d4002f1f77d8233685dafd8589efe1c9dfa63e21ca6c11134372acc7f68032" [[package]] name = "ethabi-derive" -version = "6.0.2" +version = "12.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "66a587250c8190be9d6ae28d67b8957ed97cb9eee2e272173a20593ab054a075" +checksum = "b7c0fe66618e0cfcf111afc863e7940413f2a88240cf63b38cc61206fe7be025" dependencies = [ "ethabi", "heck", - "proc-macro2 0.4.30", - "quote 0.6.13", - "syn 0.15.26", + "proc-macro2 1.0.20", + "quote 1.0.7", + "syn 1.0.40", ] [[package]] @@ -914,7 +909,7 @@ dependencies = [ "criterion 0.2.11", "crunchy 0.1.6", "either", - "ethereum-types 0.4.2", + "ethereum-types", "keccak-hash", "log", "memmap", @@ -923,19 +918,7 @@ dependencies = [ "rustc-hex 1.0.0", "serde_json", "tempdir", -] - -[[package]] -name = "ethbloom" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a93a43ce2e9f09071449da36bfa7a1b20b950ee344b6904ff23de493b03b386" -dependencies = [ - "crunchy 0.1.6", - "ethereum-types-serialize", - "fixed-hash 0.2.2", - "serde", - "tiny-keccak 1.5.0", + "tiny-keccak 2.0.2", ] [[package]] @@ -945,7 +928,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "71a6567e6fd35589fea0c63b94b4cf2e55573e413901bdbe60ab15cf0e25e5df" dependencies = [ "crunchy 0.2.2", - "fixed-hash 0.6.1", + "fixed-hash", "impl-rlp", "impl-serde", "tiny-keccak 2.0.2", @@ -976,14 +959,13 @@ dependencies = [ "ethcore-io", "ethcore-miner", "ethcore-stratum", - "ethereum-types 0.4.2", + "ethereum-types", "ethjson", "ethkey", "evm", "fetch", "globset", - "hash-db", - "heapsize", + "hash-db 0.11.0", "hex-literal", "itertools 0.5.10", "journaldb", @@ -1002,14 +984,17 @@ dependencies = [ "memory-db 0.11.0", "num_cpus", "parity-bytes", + "parity-crypto", "parity-runtime", "parity-snappy", + "parity-util-mem", "parking_lot 0.7.1", "patricia-trie-ethereum", - "rand 0.4.6", + "rand 0.7.3", + "rand_xorshift 0.2.0", "rayon", "regex 1.3.9", - "rlp 0.3.0", + "rlp", "rlp_compress", "rlp_derive", "rustc-hex 1.0.0", @@ -1037,10 +1022,11 @@ name = "ethcore-accounts" version = "0.1.0" dependencies = [ "common-types", - "ethereum-types 0.4.2", + "ethereum-types", "ethkey", "ethstore", "log", + "parity-crypto", "parking_lot 0.7.1", "serde", "serde_derive", @@ -1057,19 +1043,20 @@ dependencies = [ "common-types", "env_logger", "ethcore-db", - "ethereum-types 0.4.2", + "ethereum-types", "ethkey", - "heapsize", "itertools 0.5.10", "keccak-hash", "kvdb", "kvdb-memorydb", "log", "parity-bytes", + "parity-crypto", + "parity-util-mem", "parking_lot 0.7.1", - "rand 0.6.5", + "rand 0.7.3", "rayon", - "rlp 0.3.0", + "rlp", "rlp_compress", "rlp_derive", "rustc-hex 1.0.0", @@ -1093,7 +1080,7 @@ dependencies = [ "byteorder", "eip-152", "eth_pairings", - "ethereum-types 0.4.2", + "ethereum-types", "ethjson", "ethkey", "hex-literal", @@ -1103,7 +1090,7 @@ dependencies = [ "maplit", "num", "parity-bytes", - "parity-crypto 0.4.2", + "parity-crypto", "rustc-hex 1.0.0", ] @@ -1112,7 +1099,7 @@ name = "ethcore-call-contract" version = "0.1.0" dependencies = [ "common-types", - "ethereum-types 0.4.2", + "ethereum-types", "parity-bytes", ] @@ -1121,13 +1108,13 @@ name = "ethcore-db" version = "0.1.0" dependencies = [ "common-types", - "ethereum-types 0.4.2", - "heapsize", + "ethereum-types", "kvdb", "kvdb-memorydb", "kvdb-rocksdb", + "parity-util-mem", "parking_lot 0.7.1", - "rlp 0.3.0", + "rlp", "rlp_derive", "stats", ] @@ -1177,19 +1164,20 @@ dependencies = [ "ethabi-derive", "ethash", "ethcore-call-contract", - "ethereum-types 0.4.2", + "ethereum-types", "ethkey", "fetch", "futures", - "heapsize", "hyper 0.12.35", "keccak-hash", "linked-hash-map", "log", + "parity-crypto", "parity-runtime", + "parity-util-mem", "parking_lot 0.7.1", "price-info", - "rlp 0.3.0", + "rlp", "rustc-hex 1.0.0", "trace-time", "transaction-pool", @@ -1203,14 +1191,14 @@ dependencies = [ "assert_matches", "error-chain", "ethcore-io", - "ethereum-types 0.4.2", + "ethereum-types", "ethkey", "ipnetwork", "lazy_static", "libc", - "parity-crypto 0.3.1", + "parity-crypto", "parity-snappy", - "rlp 0.3.0", + "rlp", "semver", "serde", "serde_derive", @@ -1227,7 +1215,7 @@ dependencies = [ "error-chain", "ethcore-io", "ethcore-network", - "ethereum-types 0.4.2", + "ethereum-types", "ethkey", "igd", "ipnetwork", @@ -1237,12 +1225,12 @@ dependencies = [ "lru-cache", "mio", "parity-bytes", - "parity-crypto 0.3.1", + "parity-crypto", "parity-path", "parity-snappy", "parking_lot 0.7.1", - "rand 0.4.6", - "rlp 0.3.0", + "rand 0.7.3", + "rlp", "rust-crypto", "rustc-hex 1.0.0", "serde", @@ -1264,7 +1252,7 @@ dependencies = [ "ethcore-db", "ethcore-io", "ethcore-sync", - "ethereum-types 0.4.2", + "ethereum-types", "kvdb", "kvdb-rocksdb", "log", @@ -1277,7 +1265,7 @@ name = "ethcore-stratum" version = "1.12.0" dependencies = [ "env_logger", - "ethereum-types 0.4.2", + "ethereum-types", "jsonrpc-core", "jsonrpc-tcp-server", "keccak-hash", @@ -1300,12 +1288,11 @@ dependencies = [ "ethcore-network", "ethcore-network-devp2p", "ethereum-forkid", - "ethereum-types 0.4.2", + "ethereum-types", "ethkey", "ethstore", "fastmap", - "hash-db", - "heapsize", + "hash-db 0.11.0", "keccak-hash", "keccak-hasher 0.1.1", "kvdb", @@ -1313,11 +1300,13 @@ dependencies = [ "log", "macros", "parity-bytes", + "parity-crypto", + "parity-util-mem", "parking_lot 0.7.1", "primitive-types", - "rand 0.4.6", - "rlp 0.3.0", - "rlp 0.4.5", + "rand 0.7.3", + "rand_xorshift 0.2.0", + "rlp", "rustc-hex 1.0.0", "stats", "trace-time", @@ -1331,48 +1320,25 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3010d8372e3a76d4e2c44de0a080257ab62b6d108857ee7bd70fe8dfb2815f13" dependencies = [ "crc", - "ethereum-types 0.9.2", + "ethereum-types", "maplit", "parity-util-mem", - "rlp 0.4.5", + "rlp", "rlp-derive", ] -[[package]] -name = "ethereum-types" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e742184dc63a01c8ea0637369f8faa27c40f537949908a237f95c05e68d2c96" -dependencies = [ - "crunchy 0.1.6", - "ethbloom 0.5.0", - "ethereum-types-serialize", - "fixed-hash 0.2.2", - "serde", - "uint 0.4.1", -] - [[package]] name = "ethereum-types" version = "0.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "473aecff686bd8e7b9db0165cbbb53562376b39bf35b427f0c60446a9e1634b0" dependencies = [ - "ethbloom 0.9.2", - "fixed-hash 0.6.1", + "ethbloom", + "fixed-hash", "impl-rlp", "impl-serde", "primitive-types", - "uint 0.8.5", -] - -[[package]] -name = "ethereum-types-serialize" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1873d77b32bc1891a79dad925f2acbc318ee942b38b9110f9dbc5fbeffcea350" -dependencies = [ - "serde", + "uint", ] [[package]] @@ -1380,10 +1346,10 @@ name = "ethjson" version = "0.1.0" dependencies = [ "common-types", - "ethereum-types 0.4.2", - "ethkey", + "ethereum-types", "macros", "maplit", + "parity-crypto", "rustc-hex 1.0.0", "serde", "serde_derive", @@ -1396,14 +1362,14 @@ version = "0.3.0" dependencies = [ "edit-distance", "eth-secp256k1", - "ethereum-types 0.4.2", + "ethereum-types", "lazy_static", "log", "memzero", - "parity-crypto 0.3.1", + "parity-crypto", "parity-wordlist", "quick-error", - "rand 0.4.6", + "rand 0.7.3", "rustc-hex 1.0.0", "serde", "serde_derive", @@ -1418,6 +1384,7 @@ dependencies = [ "env_logger", "ethkey", "panic_hook", + "parity-crypto", "parity-wordlist", "rustc-hex 1.0.0", "serde", @@ -1429,17 +1396,17 @@ dependencies = [ name = "ethstore" version = "0.2.1" dependencies = [ - "ethereum-types 0.4.2", + "ethereum-types", "ethkey", "itertools 0.5.10", "lazy_static", "libc", "log", "matches", - "parity-crypto 0.3.1", + "parity-crypto", "parity-wordlist", "parking_lot 0.7.1", - "rand 0.4.6", + "rand 0.7.3", "rustc-hex 1.0.0", "serde", "serde_derive", @@ -1473,8 +1440,7 @@ dependencies = [ "bit-set", "criterion 0.2.11", "ethcore-builtin", - "ethereum-types 0.4.2", - "heapsize", + "ethereum-types", "hex-literal", "keccak-hash", "lazy_static", @@ -1482,6 +1448,7 @@ dependencies = [ "memory-cache", "num-bigint 0.2.3", "parity-bytes", + "parity-util-mem", "parking_lot 0.7.1", "rustc-hex 1.0.0", "vm", @@ -1496,7 +1463,7 @@ dependencies = [ "docopt", "env_logger", "ethcore", - "ethereum-types 0.4.2", + "ethereum-types", "ethjson", "evm", "panic_hook", @@ -1529,7 +1496,7 @@ dependencies = [ "proc-macro2 1.0.20", "quote 1.0.7", "syn 1.0.40", - "synstructure 0.12.2", + "synstructure", ] [[package]] @@ -1551,7 +1518,7 @@ checksum = "e88a8acf291dafb59c2d96e8f59828f3838bb1a70398823ade51a84de6a6deed" name = "fastmap" version = "0.1.0" dependencies = [ - "ethereum-types 0.4.2", + "ethereum-types", "plain_hasher", ] @@ -1578,18 +1545,6 @@ dependencies = [ "url 2.1.0", ] -[[package]] -name = "fixed-hash" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d5ec8112f00ea8a483e04748a85522184418fd1cf02890b626d8fc28683f7de" -dependencies = [ - "heapsize", - "libc", - "rand 0.4.6", - "rustc-hex 1.0.0", -] - [[package]] name = "fixed-hash" version = "0.6.1" @@ -1597,8 +1552,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "11498d382790b7a8f2fd211780bec78619bba81cdad3a283997c0c41f836759c" dependencies = [ "byteorder", - "rand 0.7.2", - "rustc-hex 2.0.1", + "rand 0.7.3", + "rustc-hex 2.1.0", "static_assertions", ] @@ -1642,12 +1597,6 @@ dependencies = [ "winapi 0.3.8", ] -[[package]] -name = "fs_extra" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5f2a4a2034423744d2cc7ca2068453168dcdb82c438419e639a26bd87839c674" - [[package]] name = "fuchsia-cprng" version = "0.1.1" @@ -1701,15 +1650,6 @@ version = "0.3.55" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f5f3913fa0bfe7ee1fd8248b6b9f42a5af4b9d65ec2dd2c3c26132b950ecfc2" -[[package]] -name = "generic-array" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ef25c5683767570c2bbd7deba372926a55eaae9982d7726ee2a1050239d45b9d" -dependencies = [ - "typenum", -] - [[package]] name = "generic-array" version = "0.12.3" @@ -1734,9 +1674,20 @@ version = "0.1.13" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e7db7ca94ed4cd01190ceee0d8a8052f08a247aa1b469a7f68c6a3b71afcf407" dependencies = [ - "cfg-if", + "cfg-if 0.1.10", "libc", - "wasi", + "wasi 0.7.0", +] + +[[package]] +name = "getrandom" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9495705279e7140bf035dde1f6e750c162df8b625267cd52cc44e0b156732c8" +dependencies = [ + "cfg-if 1.0.0", + "libc", + "wasi 0.10.2+wasi-snapshot-preview1", ] [[package]] @@ -1782,6 +1733,12 @@ version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1b03501f6e1a2a97f1618879aba3156f14ca2847faa530c4e28859638bd11483" +[[package]] +name = "hash-db" +version = "0.15.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d23bd4e7b5eda0d0f3a307e8b381fdc8ba9000f26fbe912250c0a4cc3956364a" + [[package]] name = "hash256-std-hasher" version = "0.11.0" @@ -1791,12 +1748,41 @@ dependencies = [ "crunchy 0.2.2", ] +[[package]] +name = "hash256-std-hasher" +version = "0.15.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92c171d55b98633f4ed3860808f004099b36c1cc29c42cfc53aa8591b21efcf2" +dependencies = [ + "crunchy 0.2.2", +] + +[[package]] +name = "hashbrown" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e6073d0ca812575946eb5f35ff68dbe519907b25c42530389ff946dc84c6ead" +dependencies = [ + "ahash 0.2.19", + "autocfg 0.1.7", +] + +[[package]] +name = "hashbrown" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e91b62f79061a0bc2e046024cb7ba44b08419ed238ecbd9adbd787434b9e8c25" +dependencies = [ + "ahash 0.3.8", + "autocfg 1.0.0", +] + [[package]] name = "heapsize" version = "0.4.2" -source = "git+https://github.com/cheme/heapsize.git?branch=ec-macfix#c07ffe843acb9da570682e290a48540741afdce1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1679e6ea370dee694f91f1dc469bf94cf8f52051d147aec3e1f9497c6fc22461" dependencies = [ - "jemallocator", "winapi 0.3.8", ] @@ -1837,24 +1823,14 @@ dependencies = [ "proc-macro-hack", ] -[[package]] -name = "hmac" -version = "0.6.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "733e1b3ac906631ca01ebb577e9bb0f5e37a454032b9036b5eaea4013ed6f99a" -dependencies = [ - "crypto-mac 0.6.2", - "digest 0.7.6", -] - [[package]] name = "hmac" version = "0.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5dcb5e64cda4c23119ab41ba960d1e170a774c8e4b9d9e6a9bc18aabf5e59695" dependencies = [ - "crypto-mac 0.7.0", - "digest 0.8.1", + "crypto-mac", + "digest", ] [[package]] @@ -2048,7 +2024,7 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f7a72f11830b52333f36e3b09a288333888bf54380fd0ac0790a3c31ab0f3c5" dependencies = [ - "rlp 0.4.5", + "rlp", ] [[package]] @@ -2134,37 +2110,15 @@ version = "0.4.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "501266b7edd0174f8530248f87f99c88fbe60ca4ef3dd486835b8d8d53136f7f" -[[package]] -name = "jemalloc-sys" -version = "0.1.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bfc62c8e50e381768ce8ee0428ee53741929f7ebd73e4d83f669bcf7693e00ae" -dependencies = [ - "cc", - "fs_extra", - "libc", -] - -[[package]] -name = "jemallocator" -version = "0.1.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9f0cd42ac65f758063fea55126b0148b1ce0a6354ff78e07a4d6806bc65c4ab3" -dependencies = [ - "jemalloc-sys", - "libc", -] - [[package]] name = "journaldb" version = "0.2.0" dependencies = [ "env_logger", "ethcore-db", - "ethereum-types 0.4.2", + "ethereum-types", "fastmap", - "hash-db", - "heapsize", + "hash-db 0.11.0", "keccak-hash", "keccak-hasher 0.1.1", "kvdb", @@ -2172,8 +2126,9 @@ dependencies = [ "log", "memory-db 0.11.0", "parity-bytes", + "parity-util-mem", "parking_lot 0.7.1", - "rlp 0.3.0", + "rlp", ] [[package]] @@ -2239,7 +2194,7 @@ dependencies = [ "jsonrpc-core", "log", "parking_lot 0.10.2", - "rand 0.7.2", + "rand 0.7.3", "serde", ] @@ -2288,20 +2243,20 @@ dependencies = [ [[package]] name = "keccak-hash" -version = "0.1.2" +version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "253bbe643c32c816bf58fa5a88248fafedeebb139705ad17a62add3517854a86" +checksum = "1f58a51ef3df9398cf2434bea8d4eb61fb748d0feb1571f87388579a120a4c8f" dependencies = [ - "ethereum-types 0.4.2", - "tiny-keccak 1.5.0", + "primitive-types", + "tiny-keccak 2.0.2", ] [[package]] name = "keccak-hasher" version = "0.1.1" dependencies = [ - "ethereum-types 0.4.2", - "hash-db", + "ethereum-types", + "hash-db 0.11.0", "plain_hasher", "tiny-keccak 1.5.0", ] @@ -2312,11 +2267,22 @@ version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cb9d3670023f4c04153d90b8a557a822d1b27ed702bb015a87cf7bffead5b611" dependencies = [ - "hash-db", - "hash256-std-hasher", + "hash-db 0.11.0", + "hash256-std-hasher 0.11.0", "tiny-keccak 1.5.0", ] +[[package]] +name = "keccak-hasher" +version = "0.15.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "711adba9940a039f4374fc5724c0a5eaca84a2d558cce62256bfe26f0dbef05e" +dependencies = [ + "hash-db 0.15.2", + "hash256-std-hasher 0.15.2", + "tiny-keccak 2.0.2", +] + [[package]] name = "kernel32-sys" version = "0.2.2" @@ -2447,7 +2413,7 @@ version = "0.4.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "14b6052be84e6b71ab17edffc2eeabf5c2c3ae1fdb464aae35ac50c67a44e1f7" dependencies = [ - "cfg-if", + "cfg-if 0.1.10", ] [[package]] @@ -2473,6 +2439,15 @@ dependencies = [ "utf8-ranges", ] +[[package]] +name = "lru" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35c456c123957de3a220cd03786e0d86aa542a88b46029973b542f426da6ef34" +dependencies = [ + "hashbrown 0.6.3", +] + [[package]] name = "lru-cache" version = "0.1.2" @@ -2545,8 +2520,8 @@ dependencies = [ name = "memory-cache" version = "0.1.0" dependencies = [ - "heapsize", "lru-cache", + "parity-util-mem", ] [[package]] @@ -2554,9 +2529,9 @@ name = "memory-db" version = "0.11.0" dependencies = [ "criterion 0.2.11", - "hash-db", - "heapsize", + "hash-db 0.11.0", "keccak-hasher 0.11.0", + "parity-util-mem", ] [[package]] @@ -2565,7 +2540,7 @@ version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94da53143d45f6bad3753f532e56ad57a6a26c0ca6881794583310c7cb4c885f" dependencies = [ - "hash-db", + "hash-db 0.11.0", "heapsize", ] @@ -2602,7 +2577,7 @@ version = "0.6.22" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fce347092656428bc8eaf6201042cb551b8d67855af7374542a92a0fbfcac430" dependencies = [ - "cfg-if", + "cfg-if 0.1.10", "fuchsia-zircon", "fuchsia-zircon-sys", "iovec", @@ -2684,7 +2659,7 @@ version = "0.2.33" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "42550d9fb7b6684a6d404d9fa7250c2eb2646df731d1c06afc06dcee9e1bcf88" dependencies = [ - "cfg-if", + "cfg-if 0.1.10", "libc", "winapi 0.3.8", ] @@ -2700,7 +2675,7 @@ dependencies = [ "ethcore-io", "ethcore-network", "ethcore-network-devp2p", - "ethereum-types 0.4.2", + "ethereum-types", "kvdb-memorydb", "log", "lru-cache", @@ -2853,7 +2828,7 @@ dependencies = [ "ethcore-network", "ethcore-service", "ethcore-sync", - "ethereum-types 0.4.2", + "ethereum-types", "ethkey", "ethstore", "fake-fetch", @@ -2875,6 +2850,7 @@ dependencies = [ "number_prefix", "panic_hook", "parity-bytes", + "parity-crypto", "parity-daemonize", "parity-local-store", "parity-path", @@ -2885,7 +2861,7 @@ dependencies = [ "pretty_assertions", "prometheus", "regex 1.3.9", - "rlp 0.3.0", + "rlp", "rpassword", "rustc-hex 1.0.0", "rustc_version", @@ -2937,41 +2913,26 @@ checksum = "0c276d76c5333b8c2579e02d49a06733a55b8282d2d9b13e8d53b6406bd7e30a" [[package]] name = "parity-crypto" -version = "0.3.1" +version = "0.6.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf1b9c063d87e1507cb3807493c8d21859ef23b5414b39f81c53f0ba267d64c1" +checksum = "88e15b5e11d7a4829490630a797c537a68c9e864a139f56fe7a1e6a51f0da25d" dependencies = [ "aes", "aes-ctr", "block-modes", - "digest 0.8.1", - "quick-error", - "ring", + "digest", + "ethereum-types", + "hmac", + "lazy_static", + "pbkdf2", + "rand 0.7.3", "ripemd160", - "scrypt 0.1.2", - "sha2 0.8.0", - "tiny-keccak 1.5.0", -] - -[[package]] -name = "parity-crypto" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "27a9c2b525c93d717a234eb220c26474f8d97b08ac50d79faeac4cb6c74bf0b9" -dependencies = [ - "aes", - "aes-ctr", - "block-modes", - "digest 0.8.1", - "hmac 0.7.1", - "pbkdf2 0.3.0", - "rand 0.7.2", - "ripemd160", - "rustc-hex 2.0.1", - "scrypt 0.2.0", - "sha2 0.8.0", + "rustc-hex 2.1.0", + "scrypt", + "secp256k1", + "sha2", "subtle 2.3.0", - "tiny-keccak 1.5.0", + "tiny-keccak 2.0.2", "zeroize", ] @@ -2999,7 +2960,8 @@ dependencies = [ "kvdb", "kvdb-memorydb", "log", - "rlp 0.3.0", + "parity-crypto", + "rlp", "serde", "serde_derive", "serde_json", @@ -3052,7 +3014,7 @@ dependencies = [ "ethcore-miner", "ethcore-network", "ethcore-sync", - "ethereum-types 0.4.2", + "ethereum-types", "ethjson", "ethkey", "ethstore", @@ -3071,13 +3033,14 @@ dependencies = [ "macros", "order-stat", "parity-bytes", - "parity-crypto 0.3.1", + "parity-crypto", "parity-runtime", "parity-version", "parking_lot 0.7.1", "pretty_assertions", - "rand 0.4.6", - "rlp 0.3.0", + "rand 0.7.3", + "rand_xorshift 0.2.0", + "rlp", "rustc-hex 1.0.0", "serde", "serde_derive", @@ -3095,7 +3058,7 @@ dependencies = [ name = "parity-rpc-client" version = "1.4.0" dependencies = [ - "ethereum-types 0.4.2", + "ethereum-types", "futures", "jsonrpc-core", "jsonrpc-ws-server", @@ -3161,7 +3124,7 @@ dependencies = [ "log", "mio-named-pipes", "miow 0.3.3", - "rand 0.7.2", + "rand 0.7.3", "tokio", "tokio-named-pipes", "tokio-uds", @@ -3174,11 +3137,15 @@ version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "297ff91fa36aec49ce183484b102f6b75b46776822bd81525bfc4cc9b0dd0f5c" dependencies = [ - "cfg-if", - "ethereum-types 0.9.2", + "cfg-if 0.1.10", + "ethereum-types", + "hashbrown 0.8.2", "impl-trait-for-tuples", + "lru", "parity-util-mem-derive", + "parking_lot 0.10.2", "primitive-types", + "smallvec 1.4.2", "winapi 0.3.8", ] @@ -3190,7 +3157,7 @@ checksum = "f557c32c6d268a07c921471619c0295f5efad3a0e76d4f97a05c091a51d110b2" dependencies = [ "proc-macro2 1.0.20", "syn 1.0.40", - "synstructure 0.12.2", + "synstructure", ] [[package]] @@ -3198,7 +3165,7 @@ name = "parity-version" version = "3.2.0" dependencies = [ "parity-bytes", - "rlp 0.3.0", + "rlp", "rustc_version", "target_info", "toml 0.4.10", @@ -3236,7 +3203,7 @@ dependencies = [ "log", "mio", "mio-extras", - "rand 0.7.2", + "rand 0.7.3", "sha-1", "slab 0.4.2", "url 2.1.0", @@ -3318,7 +3285,7 @@ version = "0.6.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b876b1b9e7ac6e1a74a6da34d25c42e17e8862aa409cbbbdcfc8d86c6f3bc62b" dependencies = [ - "cfg-if", + "cfg-if 0.1.10", "cloudabi", "libc", "redox_syscall", @@ -3333,7 +3300,7 @@ version = "0.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d58c7c768d4ba344e3e8d72518ac13e259d7c7ade24167003b8488e10b6740a3" dependencies = [ - "cfg-if", + "cfg-if 0.1.10", "cloudabi", "libc", "redox_syscall", @@ -3346,28 +3313,17 @@ name = "patricia-trie-ethereum" version = "0.1.0" dependencies = [ "elastic-array", - "ethereum-types 0.4.2", - "hash-db", + "ethereum-types", + "hash-db 0.11.0", "journaldb", "keccak-hash", "keccak-hasher 0.1.1", "memory-db 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)", "parity-bytes", - "rlp 0.3.0", + "rlp", "trie-db", ] -[[package]] -name = "pbkdf2" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c09cddfbfc98de7f76931acf44460972edb4023eb14d0c6d4018800e552d8e0" -dependencies = [ - "byteorder", - "crypto-mac 0.6.2", - "generic-array 0.9.0", -] - [[package]] name = "pbkdf2" version = "0.3.0" @@ -3376,10 +3332,10 @@ checksum = "006c038a43a45995a9670da19e67600114740e8511d4333bf97a56e66a7542d9" dependencies = [ "base64 0.9.3", "byteorder", - "crypto-mac 0.7.0", - "hmac 0.7.1", + "crypto-mac", + "hmac", "rand 0.5.6", - "sha2 0.8.0", + "sha2", "subtle 1.0.0", ] @@ -3495,11 +3451,11 @@ version = "0.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c55c21c64d0eaa4d7ed885d959ef2d62d9e488c27c0e02d9aa5ce6c877b7d5f8" dependencies = [ - "fixed-hash 0.6.1", + "fixed-hash", "impl-codec", "impl-rlp", "impl-serde", - "uint 0.8.5", + "uint", ] [[package]] @@ -3513,14 +3469,9 @@ dependencies = [ [[package]] name = "proc-macro-hack" -version = "0.5.11" +version = "0.5.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ecd45702f76d6d3c75a80564378ae228a85f0b59d2f3ed43c91b4a69eb2ebfc5" -dependencies = [ - "proc-macro2 1.0.20", - "quote 1.0.7", - "syn 1.0.40", -] +checksum = "dbf0c48bc1d91375ae5c3cd81e3722dff1abcf81a30960240640d223f59fe0e5" [[package]] name = "proc-macro2" @@ -3546,7 +3497,7 @@ version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dd0ced56dee39a6e960c15c74dc48849d614586db2eaada6497477af7c7811cd" dependencies = [ - "cfg-if", + "cfg-if 0.1.10", "fnv", "lazy_static", "protobuf", @@ -3661,17 +3612,17 @@ dependencies = [ "rand_jitter", "rand_os 0.1.3", "rand_pcg", - "rand_xorshift", + "rand_xorshift 0.1.1", "winapi 0.3.8", ] [[package]] name = "rand" -version = "0.7.2" +version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ae1b169243eaf61759b8475a998f0a385e42042370f3a7dbaf35246eacc8412" +checksum = "6a6b1679d49b24bbfe0c803429aa1874472f50d9b363131f0e89fc356b544d03" dependencies = [ - "getrandom", + "getrandom 0.1.13", "libc", "rand_chacha 0.2.1", "rand_core 0.5.1", @@ -3719,7 +3670,7 @@ version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "90bde5296fc891b0cef12a6d03ddccc162ce7b2aff54160af9338f8d40df6d19" dependencies = [ - "getrandom", + "getrandom 0.1.13", ] [[package]] @@ -3780,7 +3731,7 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a788ae3edb696cfcba1c19bfd388cc4b8c21f8a408432b199c072825084da58a" dependencies = [ - "getrandom", + "getrandom 0.1.13", "rand_core 0.5.1", ] @@ -3803,6 +3754,15 @@ dependencies = [ "rand_core 0.3.1", ] +[[package]] +name = "rand_xorshift" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77d416b86801d23dde1aa643023b775c3a462efc0ed96443add11546cdf1dca8" +dependencies = [ + "rand_core 0.5.1", +] + [[package]] name = "rand_xoshiro" version = "0.1.0" @@ -3948,41 +3908,18 @@ version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ad5112e0dbbb87577bfbc56c42450235e3012ce336e29c5befd7807bd626da4a" dependencies = [ - "block-buffer 0.7.3", - "digest 0.8.1", + "block-buffer", + "digest", "opaque-debug", ] [[package]] name = "rlp" -version = "0.2.4" +version = "0.4.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "524c5ad554859785dfc8469df3ed5e0b5784d4d335877ed47c8d90fc0eb238fe" +checksum = "1190dcc8c3a512f1eef5d09bb8c84c7f39e1054e174d1795482e18f5272f2e73" dependencies = [ - "byteorder", - "elastic-array", - "ethereum-types 0.4.2", - "rustc-hex 2.0.1", -] - -[[package]] -name = "rlp" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "16d1effe9845d54f90e7be8420ee49e5c94623140b97ee4bc6fb5bfddb745720" -dependencies = [ - "byteorder", - "ethereum-types 0.4.2", - "rustc-hex 2.0.1", -] - -[[package]] -name = "rlp" -version = "0.4.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4a7d3f9bed94764eac15b8f14af59fac420c236adaff743b7bcc88e265cb4345" -dependencies = [ - "rustc-hex 2.0.1", + "rustc-hex 2.1.0", ] [[package]] @@ -4002,7 +3939,7 @@ version = "0.1.0" dependencies = [ "elastic-array", "lazy_static", - "rlp 0.3.0", + "rlp", ] [[package]] @@ -4011,7 +3948,7 @@ version = "0.1.0" dependencies = [ "proc-macro2 0.4.30", "quote 0.6.13", - "rlp 0.3.0", + "rlp", "syn 0.15.26", ] @@ -4060,9 +3997,9 @@ checksum = "0ceb8ce7a5e520de349e1fa172baeba4a9e8d5ef06c47471863530bc4972ee1e" [[package]] name = "rustc-hex" -version = "2.0.1" +version = "2.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "403bb3a286107a04825a5f82e1270acc1e14028d3d554d7a1e08914549575ab8" +checksum = "3e75f6a532d0fd9f7f13144f392b6ad56a32696bfcd9c78f797f16bbb6f072d6" [[package]] name = "rustc-serialize" @@ -4132,30 +4069,17 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd" -[[package]] -name = "scrypt" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8570c5e2fa69cb29d492fd4e9974b6b5facb5a888e1c6da630d4a3cd7ebfef4a" -dependencies = [ - "byte-tools 0.3.1", - "byteorder", - "hmac 0.6.3", - "pbkdf2 0.2.3", - "sha2 0.7.1", -] - [[package]] name = "scrypt" version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "656c79d0e90d0ab28ac86bf3c3d10bfbbac91450d3f190113b4e76d9fec3cfdd" dependencies = [ - "byte-tools 0.3.1", + "byte-tools", "byteorder", - "hmac 0.7.1", - "pbkdf2 0.3.0", - "sha2 0.8.0", + "hmac", + "pbkdf2", + "sha2", ] [[package]] @@ -4168,6 +4092,25 @@ dependencies = [ "untrusted", ] +[[package]] +name = "secp256k1" +version = "0.17.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2932dc07acd2066ff2e3921a4419606b220ba6cd03a9935123856cc534877056" +dependencies = [ + "rand 0.6.5", + "secp256k1-sys", +] + +[[package]] +name = "secp256k1-sys" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ab2c26f0d3552a0f12e639ae8a64afc2e3db9c52fe32f5fc6c289d38519f220" +dependencies = [ + "cc", +] + [[package]] name = "semver" version = "0.9.0" @@ -4232,32 +4175,20 @@ version = "0.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "23962131a91661d643c98940b20fcaffe62d776a823247be80a48fcb8b6fce68" dependencies = [ - "block-buffer 0.7.3", - "digest 0.8.1", + "block-buffer", + "digest", "fake-simd", "opaque-debug", ] -[[package]] -name = "sha2" -version = "0.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9eb6be24e4c23a84d7184280d2722f7f2731fcdd4a9d886efbfe4413e4847ea0" -dependencies = [ - "block-buffer 0.3.3", - "byte-tools 0.2.0", - "digest 0.7.6", - "fake-simd", -] - [[package]] name = "sha2" version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7b4d8bfd0e469f417657573d8451fb33d16cfe0989359b93baf3a1ffc639543d" dependencies = [ - "block-buffer 0.7.3", - "digest 0.8.1", + "block-buffer", + "digest", "fake-simd", "opaque-debug", ] @@ -4279,7 +4210,7 @@ source = "git+https://github.com/matter-labs/eip1962.git?rev=ece6cbabc41948db420 dependencies = [ "byteorder", "crunchy 0.2.2", - "rustc-hex 2.0.1", + "rustc-hex 2.1.0", "static_assertions", ] @@ -4338,7 +4269,7 @@ version = "0.3.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e8b74de517221a2cb01a53349cf54182acdc31a074727d3079068448c0676d85" dependencies = [ - "cfg-if", + "cfg-if 0.1.10", "libc", "redox_syscall", "winapi 0.3.8", @@ -4376,7 +4307,7 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8131256a5896cabcf5eb04f4d6dacbe1aefda854b0d9896e09cb58829ec5638c" dependencies = [ - "generic-array 0.12.3", + "generic-array", ] [[package]] @@ -4434,18 +4365,6 @@ dependencies = [ "unicode-xid 0.2.0", ] -[[package]] -name = "synstructure" -version = "0.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "73687139bf99285483c96ac0add482c3776528beac1d97d444f6e91f203a2015" -dependencies = [ - "proc-macro2 0.4.30", - "quote 0.6.13", - "syn 0.15.26", - "unicode-xid 0.1.0", -] - [[package]] name = "synstructure" version = "0.12.2" @@ -4480,9 +4399,9 @@ version = "3.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7a6e24d9338a0a5be79593e2fa15a648add6138caa803e2d5bc782c371732ca9" dependencies = [ - "cfg-if", + "cfg-if 0.1.10", "libc", - "rand 0.7.2", + "rand 0.7.3", "redox_syscall", "remove_dir_all", "winapi 0.3.8", @@ -4964,38 +4883,36 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3c7319e28ca295f27359d944a682f7f65b419158bf1590c92cadc0000258d788" dependencies = [ "elastic-array", - "hash-db", + "hash-db 0.11.0", "log", "rand 0.6.5", ] [[package]] name = "trie-standardmap" -version = "0.1.1" +version = "0.15.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0e26f52976a57a0859616d6fcec87092ac35d08eabbd78dc3dabee93b480ea5f" +checksum = "c3161ba520ab28cd8e6b68e1126f1009f6e335339d1a73b978139011703264c8" dependencies = [ - "ethereum-types 0.4.2", - "keccak-hash", - "parity-bytes", - "rlp 0.2.4", + "hash-db 0.15.2", + "keccak-hasher 0.15.3", ] [[package]] name = "triehash" -version = "0.4.0" +version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d26efb4ddf87870fc08dc9a6580dc3061be350d7b9d0eb30aef1c8b4227aa46" +checksum = "92148b4d8d55eff71bc8c9e3c5f714e266c2a05e724dce5405a10deabbf449a8" dependencies = [ - "hash-db", - "rlp 0.3.0", + "hash-db 0.11.0", + "rlp", ] [[package]] name = "triehash-ethereum" version = "0.2.0" dependencies = [ - "ethereum-types 0.4.2", + "ethereum-types", "keccak-hasher 0.1.1", "triehash", ] @@ -5024,18 +4941,6 @@ version = "0.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c85f514e095d348c279b1e5cd76795082cf15bd59b93207832abe0b1d8fed236" -[[package]] -name = "uint" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "754ba11732b9161b94c41798e5197e5e75388d012f760c42adb5000353e98646" -dependencies = [ - "byteorder", - "crunchy 0.1.6", - "heapsize", - "rustc-hex 2.0.1", -] - [[package]] name = "uint" version = "0.8.5" @@ -5044,7 +4949,7 @@ checksum = "9db035e67dfaf7edd9aebfe8676afcd63eed53c8a4044fed514c8cccf1835177" dependencies = [ "byteorder", "crunchy 0.2.2", - "rustc-hex 2.0.1", + "rustc-hex 2.1.0", "static_assertions", ] @@ -5197,12 +5102,12 @@ checksum = "914b1a6776c4c929a602fafd8bc742e06365d4bcbe48c30f9cca5824f70dc9dd" name = "vm" version = "0.1.0" dependencies = [ - "ethereum-types 0.4.2", + "ethereum-types", "ethjson", "keccak-hash", "parity-bytes", "patricia-trie-ethereum", - "rlp 0.3.0", + "rlp", ] [[package]] @@ -5244,13 +5149,19 @@ version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b89c3ce4ce14bdc6fb6beaf9ec7928ca331de5df7e5ea278375642a2f478570d" +[[package]] +name = "wasi" +version = "0.10.2+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd6fbd9a79829dd1ad0cc20627bf1ed606756a7f77edff7b66b7064f9cb327c6" + [[package]] name = "wasm" version = "0.1.0" dependencies = [ "byteorder", "env_logger", - "ethereum-types 0.4.2", + "ethereum-types", "libc", "log", "parity-wasm", @@ -5380,21 +5291,6 @@ dependencies = [ [[package]] name = "zeroize" -version = "0.9.3" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "45af6a010d13e4cf5b54c94ba5a2b2eba5596b9e46bf5875612d332a1f2b3f86" -dependencies = [ - "zeroize_derive", -] - -[[package]] -name = "zeroize_derive" -version = "0.9.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "080616bd0e31f36095288bb0acdf1f78ef02c2fa15527d7e993f2a6c7591643e" -dependencies = [ - "proc-macro2 0.4.30", - "quote 0.6.13", - "syn 0.15.26", - "synstructure 0.10.1", -] +checksum = "81a974bcdd357f0dca4d41677db03436324d45a4c9ed2d0b873a5a360ce41c36" diff --git a/Cargo.toml b/Cargo.toml index 2906d1545..0d42b6342 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -47,12 +47,13 @@ ethcore-miner = { path = "crates/concensus/miner" } ethcore-network = { path = "crates/net/network" } ethcore-service = { path = "crates/ethcore/service" } ethcore-sync = { path = "crates/ethcore/sync" } -ethereum-types = "0.4" +ethereum-types = "0.9.2" ethkey = { path = "crates/accounts/ethkey" } ethstore = { path = "crates/accounts/ethstore" } fetch = { path = "crates/net/fetch" } node-filter = { path = "crates/net/node-filter" } -rlp = { version = "0.3.0", features = ["ethereum"] } +parity-crypto = { version = "0.6.2", features = [ "publickey" ] } +rlp = { version = "0.4.6" } cli-signer= { path = "crates/util/cli-signer" } parity-daemonize = "0.3" parity-local-store = { path = "crates/concensus/miner/local-store" } @@ -62,7 +63,7 @@ parity-version = { path = "crates/util/version" } parity-path = "0.1" dir = { path = "crates/util/dir" } panic_hook = { path = "crates/util/panic-hook" } -keccak-hash = "0.1" +keccak-hash = "0.5.0" migration-rocksdb = { path = "crates/db/migration-rocksdb" } kvdb = "0.1" kvdb-rocksdb = "0.1.3" @@ -130,6 +131,3 @@ members = [ "bin/evmbin", "bin/chainspec" ] - -[patch.crates-io] -heapsize = { git = "https://github.com/cheme/heapsize.git", branch = "ec-macfix" } diff --git a/bin/ethkey/Cargo.toml b/bin/ethkey/Cargo.toml index e649202e0..d5af93f26 100644 --- a/bin/ethkey/Cargo.toml +++ b/bin/ethkey/Cargo.toml @@ -9,6 +9,7 @@ docopt = "1.0" env_logger = "0.5" ethkey = { path = "../../crates/accounts/ethkey" } panic_hook = { path = "../../crates/util/panic-hook" } +parity-crypto = { version = "0.6.2", features = [ "publickey" ] } parity-wordlist="1.3" rustc-hex = "1.0" serde = "1.0" diff --git a/bin/ethkey/src/main.rs b/bin/ethkey/src/main.rs index 7327553e1..230351ef4 100644 --- a/bin/ethkey/src/main.rs +++ b/bin/ethkey/src/main.rs @@ -18,6 +18,7 @@ extern crate docopt; extern crate env_logger; extern crate ethkey; extern crate panic_hook; +extern crate parity_crypto as crypto; extern crate parity_wordlist; extern crate rustc_hex; extern crate serde; @@ -28,11 +29,11 @@ extern crate serde_derive; use std::{env, fmt, io, num::ParseIntError, process, sync}; -use docopt::Docopt; -use ethkey::{ - brain_recover, sign, verify_address, verify_public, Brain, BrainPrefix, Error as EthkeyError, - Generator, KeyPair, Prefix, Random, +use crypto::publickey::{ + sign, verify_address, verify_public, Error as EthkeyError, Generator, KeyPair, Random, }; +use docopt::Docopt; +use ethkey::{brain_recover, Brain, BrainPrefix, Prefix}; use rustc_hex::{FromHex, FromHexError}; const USAGE: &'static str = r#" @@ -202,15 +203,13 @@ where let result = if args.flag_brain { let phrase = args.arg_secret_or_phrase; let phrase_info = validate_phrase(&phrase); - let keypair = Brain::new(phrase) - .generate() - .expect("Brain wallet generator is infallible; qed"); + let keypair = Brain::new(phrase).generate(); (keypair, Some(phrase_info)) } else { let secret = args .arg_secret_or_phrase .parse() - .map_err(|_| EthkeyError::InvalidSecret)?; + .map_err(|_| EthkeyError::InvalidSecretKey)?; (KeyPair::from_secret(secret)?, None) }; Ok(display(result, display_mode)) @@ -223,7 +222,7 @@ where let phrase = format!("recovery phrase: {}", brain.phrase()); (keypair, Some(phrase)) } else { - (Random.generate()?, None) + (Random.generate(), None) } } else if args.cmd_prefix { let prefix = args.arg_prefix.from_hex()?; @@ -254,7 +253,7 @@ where let secret = args .arg_secret .parse() - .map_err(|_| EthkeyError::InvalidSecret)?; + .map_err(|_| EthkeyError::InvalidSecretKey)?; let message = args .arg_message .parse() @@ -274,7 +273,7 @@ where let public = args .arg_public .parse() - .map_err(|_| EthkeyError::InvalidPublic)?; + .map_err(|_| EthkeyError::InvalidPublicKey)?; verify_public(&public, &signature, &message)? } else if args.cmd_address { let address = args @@ -301,7 +300,7 @@ where while let Some(phrase) = it.next() { i += 1; - let keypair = Brain::new(phrase.clone()).generate().unwrap(); + let keypair = Brain::new(phrase.clone()).generate(); if keypair.address() == address { return Ok(Some((phrase, keypair))); } diff --git a/bin/evmbin/Cargo.toml b/bin/evmbin/Cargo.toml index 1e0ac33ad..d6b896051 100644 --- a/bin/evmbin/Cargo.toml +++ b/bin/evmbin/Cargo.toml @@ -13,7 +13,7 @@ common-types = { path = "../../crates/ethcore/types", features = ["test-helpers" docopt = "1.0" env_logger = "0.5" ethcore = { path = "../../crates/ethcore", features = ["test-helpers", "json-tests", "to-pod-full"] } -ethereum-types = "0.4" +ethereum-types = "0.9.2" ethjson = { path = "../../crates/ethjson" } evm = { path = "../../crates/vm/evm" } panic_hook = { path = "../../crates/util/panic-hook" } diff --git a/bin/evmbin/src/display/json.rs b/bin/evmbin/src/display/json.rs index 55b70f86d..08658abf0 100644 --- a/bin/evmbin/src/display/json.rs +++ b/bin/evmbin/src/display/json.rs @@ -22,7 +22,7 @@ use super::config::Config; use bytes::ToPretty; use display; use ethcore::trace; -use ethereum_types::{H256, U256}; +use ethereum_types::{BigEndianHash, H256, U256}; use info as vm; /// JSON formatting informant. @@ -208,7 +208,10 @@ impl trace::VMTracer for Informant { } if let Some((pos, val)) = store_diff { - informant.storage.insert(pos.into(), val.into()); + informant.storage.insert( + BigEndianHash::from_uint(&pos), + BigEndianHash::from_uint(&val), + ); } if !informant.subtraces.is_empty() { diff --git a/bin/evmbin/src/display/std_json.rs b/bin/evmbin/src/display/std_json.rs index ae7e5a7e0..4114f719c 100644 --- a/bin/evmbin/src/display/std_json.rs +++ b/bin/evmbin/src/display/std_json.rs @@ -22,7 +22,7 @@ use super::config::Config; use bytes::ToPretty; use display; use ethcore::{pod_state, trace}; -use ethereum_types::{H256, U256}; +use ethereum_types::{BigEndianHash, H256, U256}; use info as vm; pub trait Writer: io::Write + Send + Sized { @@ -237,7 +237,10 @@ impl trace::VMTracer for Informant { let subdepth = self.subdepth; Self::with_informant_in_depth(self, subdepth, |informant: &mut Informant| { if let Some((pos, val)) = store_written { - informant.storage.insert(pos.into(), val.into()); + informant.storage.insert( + BigEndianHash::from_uint(&pos), + BigEndianHash::from_uint(&val), + ); } }); } diff --git a/bin/evmbin/src/info.rs b/bin/evmbin/src/info.rs index 8519e1d4b..4e308d264 100644 --- a/bin/evmbin/src/info.rs +++ b/bin/evmbin/src/info.rs @@ -103,7 +103,7 @@ pub fn run_action( Ok(r) => (Ok(r.return_data.to_vec()), Some(r.gas_left)), Err(err) => (Err(err), None), }; - (result.0, 0.into(), None, result.1, informant.drain()) + (result.0, H256::zero(), None, result.1, informant.drain()) }, ) } @@ -262,6 +262,7 @@ where #[cfg(test)] pub mod tests { use super::*; + use ethereum_types::Address; use rustc_hex::FromHex; use std::sync::Arc; use tempdir::TempDir; @@ -291,7 +292,7 @@ pub mod tests { let (inf, res) = informant(Config::default()); let mut params = ActionParams::default(); - params.code_address = 0x20.into(); + params.code_address = Address::from_low_u64_be(0x20); params.gas = 0xffff.into(); let spec = ::ethcore::ethereum::load(None, include_bytes!("../res/testchain.json")); diff --git a/bin/evmbin/src/main.rs b/bin/evmbin/src/main.rs index 45b28f583..c6a7f987e 100644 --- a/bin/evmbin/src/main.rs +++ b/bin/evmbin/src/main.rs @@ -429,6 +429,7 @@ fn die(msg: T) -> ! { mod tests { use super::{Args, USAGE}; use docopt::Docopt; + use ethereum_types::Address; fn run>(args: &[T]) -> Args { Docopt::new(USAGE) @@ -468,8 +469,8 @@ mod tests { assert_eq!(args.flag_std_out_only, true); assert_eq!(args.gas(), Ok(1.into())); assert_eq!(args.gas_price(), Ok(2.into())); - assert_eq!(args.from(), Ok(3.into())); - assert_eq!(args.to(), Ok(4.into())); + assert_eq!(args.from(), Ok(Address::from_low_u64_be(3))); + assert_eq!(args.to(), Ok(Address::from_low_u64_be(4))); assert_eq!(args.code(), Ok(Some(vec![05]))); assert_eq!(args.data(), Ok(Some(vec![06]))); assert_eq!(args.flag_chain, Some("./testfile".to_owned())); diff --git a/bin/oe/account_utils.rs b/bin/oe/account_utils.rs index 36a91a06e..902e557cc 100644 --- a/bin/oe/account_utils.rs +++ b/bin/oe/account_utils.rs @@ -16,8 +16,9 @@ use std::sync::Arc; +use crypto::publickey; use dir::Directories; -use ethereum_types::Address; +use ethereum_types::{Address, H160}; use ethkey::Password; use params::{AccountsConfig, SpecType}; @@ -70,6 +71,7 @@ mod accounts { #[cfg(feature = "accounts")] mod accounts { use super::*; + use std::str::FromStr; use upgrade::upgrade_key_location; pub use accounts::AccountProvider; @@ -103,7 +105,8 @@ mod accounts { | SpecType::Goerli | SpecType::Sokol | SpecType::Dev => vec![], - _ => vec!["00a329c0648769a73afac7f9381e08fb43dbea72".into()], + _ => vec![H160::from_str("00a329c0648769a73afac7f9381e08fb43dbea72") + .expect("the string is valid hex; qed")], }, }; @@ -216,9 +219,11 @@ mod accounts { } fn insert_dev_account(account_provider: &AccountProvider) { - let secret: ethkey::Secret = - "4d5db4107d237df6a3d58ee5f70ae63d73d7658d4026f2eefd2f204c81682cb7".into(); - let dev_account = ethkey::KeyPair::from_secret(secret.clone()) + let secret = publickey::Secret::from_str( + "4d5db4107d237df6a3d58ee5f70ae63d73d7658d4026f2eefd2f204c81682cb7", + ) + .expect("Valid account;qed"); + let dev_account = publickey::KeyPair::from_secret(secret.clone()) .expect("Valid secret produces valid key;qed"); if !account_provider.has_account(dev_account.address()) { match account_provider.insert_account(secret, &Password::from(String::new())) { diff --git a/bin/oe/configuration.rs b/bin/oe/configuration.rs index 79fc2f5ec..84c83bca8 100644 --- a/bin/oe/configuration.rs +++ b/bin/oe/configuration.rs @@ -17,6 +17,7 @@ use ansi_term::Colour; use bytes::Bytes; use cli::{Args, ArgsError}; +use crypto::publickey::{Public, Secret}; use ethcore::{ client::VMType, miner::{stratum, MinerOptions}, @@ -24,7 +25,6 @@ use ethcore::{ verification::queue::VerifierSettings, }; use ethereum_types::{Address, H256, U256}; -use ethkey::{Public, Secret}; use hash::keccak; use metrics::MetricsConfiguration; use miner::pool; @@ -810,7 +810,7 @@ impl Configuration { ret.public_address = public.map(|p| format!("{}", p)); ret.use_secret = match self.args.arg_node_key.as_ref().map(|s| { s.parse::() - .or_else(|_| Secret::from_unsafe_slice(&keccak(s))) + .or_else(|_| Secret::import_key(keccak(s).as_bytes())) .map_err(|e| format!("Invalid key: {:?}", e)) }) { None => None, diff --git a/bin/oe/helpers.rs b/bin/oe/helpers.rs index 01f831073..e9cdf93df 100644 --- a/bin/oe/helpers.rs +++ b/bin/oe/helpers.rs @@ -21,7 +21,7 @@ use ethcore::{ client::{BlockId, ClientConfig, DatabaseCompactionProfile, Mode, VMType, VerifierType}, miner::{Penalization, PendingSet}, }; -use ethereum_types::{clean_0x, Address, U256}; +use ethereum_types::{Address, U256}; use ethkey::Password; use journaldb::Algorithm; use miner::pool::PrioritizationStrategy; @@ -39,6 +39,14 @@ pub fn to_duration(s: &str) -> Result { to_seconds(s).map(Duration::from_secs) } +fn clean_0x(s: &str) -> &str { + if s.starts_with("0x") { + &s[2..] + } else { + s + } +} + fn to_seconds(s: &str) -> Result { let bad = |_| { format!( diff --git a/bin/oe/lib.rs b/bin/oe/lib.rs index 09d8ae5d0..ed9a7166e 100644 --- a/bin/oe/lib.rs +++ b/bin/oe/lib.rs @@ -61,6 +61,7 @@ extern crate keccak_hash as hash; extern crate kvdb; extern crate node_filter; extern crate parity_bytes as bytes; +extern crate parity_crypto as crypto; extern crate parity_local_store as local_store; extern crate parity_path as path; extern crate parity_rpc; diff --git a/bin/oe/presale.rs b/bin/oe/presale.rs index b160ab774..5a5fecf0c 100644 --- a/bin/oe/presale.rs +++ b/bin/oe/presale.rs @@ -14,6 +14,7 @@ // You should have received a copy of the GNU General Public License // along with OpenEthereum. If not, see . +use crypto::publickey; use ethkey::Password; use ethstore::PresaleWallet; use helpers::{password_from_file, password_prompt}; @@ -44,7 +45,7 @@ pub fn execute(cmd: ImportWallet) -> Result { } #[cfg(feature = "accounts")] -pub fn import_account(cmd: &ImportWallet, kp: ethkey::KeyPair, password: Password) { +pub fn import_account(cmd: &ImportWallet, kp: publickey::KeyPair, password: Password) { use accounts::{AccountProvider, AccountProviderSettings}; use ethstore::{accounts_dir::RootDiskDirectory, EthStore}; @@ -57,4 +58,4 @@ pub fn import_account(cmd: &ImportWallet, kp: ethkey::KeyPair, password: Passwor } #[cfg(not(feature = "accounts"))] -pub fn import_account(_cmd: &ImportWallet, _kp: ethkey::KeyPair, _password: Password) {} +pub fn import_account(_cmd: &ImportWallet, _kp: publickey::KeyPair, _password: Password) {} diff --git a/bin/oe/run.rs b/bin/oe/run.rs index d4aac267c..91d274a67 100644 --- a/bin/oe/run.rs +++ b/bin/oe/run.rs @@ -16,6 +16,7 @@ use std::{ any::Any, + str::FromStr, sync::{atomic, Arc, Weak}, thread, time::{Duration, Instant}, @@ -606,7 +607,10 @@ pub fn execute(cmd: RunCmd, logger: Arc) -> Result Vec { match *spec { SpecType::Ropsten => { - vec!["1eac3d16c642411f13c287e29144c6f58fda859407c8f24c38deb168e1040714".into()] + vec![ + H256::from_str("1eac3d16c642411f13c287e29144c6f58fda859407c8f24c38deb168e1040714") + .expect("Valid hex string"), + ] } _ => vec![], } diff --git a/bin/oe/secretstore.rs b/bin/oe/secretstore.rs index a55bfd90b..6ef0b23e1 100644 --- a/bin/oe/secretstore.rs +++ b/bin/oe/secretstore.rs @@ -15,10 +15,11 @@ // along with OpenEthereum. If not, see . use account_utils::AccountProvider; +use crypto::publickey::{Public, Secret}; use dir::{default_data_path, helpers::replace_home}; use ethcore::{client::Client, miner::Miner}; use ethereum_types::Address; -use ethkey::{Password, Public, Secret}; +use ethkey::Password; use parity_runtime::Executor; use std::{collections::BTreeMap, sync::Arc}; use sync::SyncProvider; diff --git a/crates/accounts/Cargo.toml b/crates/accounts/Cargo.toml index e88d77683..56ad94278 100644 --- a/crates/accounts/Cargo.toml +++ b/crates/accounts/Cargo.toml @@ -12,11 +12,12 @@ common-types = { path = "../ethcore/types" } ethkey = { path = "ethkey" } ethstore = { path = "ethstore" } log = "0.4" +parity-crypto = { version = "0.6.2", features = [ "publickey" ] } parking_lot = "0.7" serde = "1.0" serde_derive = "1.0" serde_json = "1.0" [dev-dependencies] -ethereum-types = "0.4" +ethereum-types = "0.9.2" tempdir = "0.3" diff --git a/crates/accounts/ethkey/Cargo.toml b/crates/accounts/ethkey/Cargo.toml index 6348230d3..5b32bbaa2 100644 --- a/crates/accounts/ethkey/Cargo.toml +++ b/crates/accounts/ethkey/Cargo.toml @@ -6,15 +6,15 @@ authors = ["Parity Technologies "] [dependencies] edit-distance = "2.0" -parity-crypto = "0.3.0" -eth-secp256k1 = { git = "https://github.com/paritytech/rust-secp256k1", rev = "ccc06e7480148b723eb44ac56cf4d20eec380b6f" } -ethereum-types = "0.4" +parity-crypto = { version = "0.6.2", features = ["publickey"] } +eth-secp256k1 = { git = "https://github.com/paritytech/rust-secp256k1", rev = "9791e79f21a5309dcb6e0bd254b1ef88fca2f1f4" } +ethereum-types = "0.9.2" lazy_static = "1.0" log = "0.4" memzero = { path = "../../../crates/util/memzero" } parity-wordlist = "1.3" quick-error = "1.2.2" -rand = "0.4" +rand = "0.7.3" rustc-hex = "1.0" serde = "1.0" serde_derive = "1.0" diff --git a/crates/accounts/ethkey/src/brain.rs b/crates/accounts/ethkey/src/brain.rs index 9d835f118..2cb6806fc 100644 --- a/crates/accounts/ethkey/src/brain.rs +++ b/crates/accounts/ethkey/src/brain.rs @@ -14,8 +14,10 @@ // You should have received a copy of the GNU General Public License // along with OpenEthereum. If not, see . -use super::{Generator, KeyPair, Secret}; -use keccak::Keccak256; +use parity_crypto::{ + publickey::{KeyPair, Secret}, + Keccak256, +}; use parity_wordlist; /// Simple brainwallet. @@ -29,12 +31,8 @@ impl Brain { pub fn validate_phrase(phrase: &str, expected_words: usize) -> Result<(), ::WordlistError> { parity_wordlist::validate_phrase(phrase, expected_words) } -} -impl Generator for Brain { - type Error = ::Void; - - fn generate(&mut self) -> Result { + pub fn generate(&mut self) -> KeyPair { let seed = self.0.clone(); let mut secret = seed.into_bytes().keccak256(); @@ -45,12 +43,10 @@ impl Generator for Brain { match i > 16384 { false => i += 1, true => { - if let Ok(pair) = - Secret::from_unsafe_slice(&secret).and_then(KeyPair::from_secret) - { + if let Ok(pair) = Secret::import_key(&secret).and_then(KeyPair::from_secret) { if pair.address()[0] == 0 { trace!("Testing: {}, got: {:?}", self.0, pair.address()); - return Ok(pair); + return pair; } } } @@ -62,13 +58,12 @@ impl Generator for Brain { #[cfg(test)] mod tests { use Brain; - use Generator; #[test] fn test_brain() { let words = "this is sparta!".to_owned(); - let first_keypair = Brain::new(words.clone()).generate().unwrap(); - let second_keypair = Brain::new(words.clone()).generate().unwrap(); + let first_keypair = Brain::new(words.clone()).generate(); + let second_keypair = Brain::new(words.clone()).generate(); assert_eq!(first_keypair.secret(), second_keypair.secret()); } } diff --git a/crates/accounts/ethkey/src/brain_prefix.rs b/crates/accounts/ethkey/src/brain_prefix.rs index cc25a03f2..819dce564 100644 --- a/crates/accounts/ethkey/src/brain_prefix.rs +++ b/crates/accounts/ethkey/src/brain_prefix.rs @@ -14,7 +14,8 @@ // You should have received a copy of the GNU General Public License // along with OpenEthereum. If not, see . -use super::{Brain, Error, Generator, KeyPair}; +use super::Brain; +use parity_crypto::publickey::{Error, KeyPair}; use parity_wordlist as wordlist; /// Tries to find brain-seed keypair with address starting with given prefix. @@ -38,16 +39,12 @@ impl BrainPrefix { pub fn phrase(&self) -> &str { &self.last_phrase } -} -impl Generator for BrainPrefix { - type Error = Error; - - fn generate(&mut self) -> Result { + pub fn generate(&mut self) -> Result { for _ in 0..self.iterations { let phrase = wordlist::random_phrase(self.no_of_words); - let keypair = Brain::new(phrase.clone()).generate().unwrap(); - if keypair.address().starts_with(&self.prefix) { + let keypair = Brain::new(phrase.clone()).generate(); + if keypair.address().as_ref().starts_with(&self.prefix) { self.last_phrase = phrase; return Ok(keypair); } @@ -60,7 +57,6 @@ impl Generator for BrainPrefix { #[cfg(test)] mod tests { use BrainPrefix; - use Generator; #[test] fn prefix_generator() { @@ -68,6 +64,6 @@ mod tests { let keypair = BrainPrefix::new(prefix.clone(), usize::max_value(), 12) .generate() .unwrap(); - assert!(keypair.address().starts_with(&prefix)); + assert!(keypair.address().as_bytes().starts_with(&prefix)); } } diff --git a/crates/accounts/ethkey/src/brain_recover.rs b/crates/accounts/ethkey/src/brain_recover.rs index 92cd7df1e..611893f4a 100644 --- a/crates/accounts/ethkey/src/brain_recover.rs +++ b/crates/accounts/ethkey/src/brain_recover.rs @@ -17,9 +17,10 @@ use std::collections::HashSet; use edit_distance::edit_distance; +use parity_crypto::publickey::Address; use parity_wordlist; -use super::{Address, Brain, Generator}; +use super::Brain; /// Tries to find a phrase for address, given the number /// of expected words and a partial phrase. @@ -32,9 +33,7 @@ pub fn brain_recover( ) -> Option { let it = PhrasesIterator::from_known_phrase(known_phrase, expected_words); for phrase in it { - let keypair = Brain::new(phrase.clone()) - .generate() - .expect("Brain wallets are infallible; qed"); + let keypair = Brain::new(phrase.clone()).generate(); trace!("Testing: {}, got: {:?}", phrase, keypair.address()); if &keypair.address() == address { return Some(phrase); diff --git a/crates/accounts/ethkey/src/crypto.rs b/crates/accounts/ethkey/src/crypto.rs deleted file mode 100644 index 4fa1ee690..000000000 --- a/crates/accounts/ethkey/src/crypto.rs +++ /dev/null @@ -1,202 +0,0 @@ -// Copyright 2015-2020 Parity Technologies (UK) Ltd. -// This file is part of OpenEthereum. - -// OpenEthereum 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. - -// OpenEthereum 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 OpenEthereum. If not, see . - -#![allow(deprecated)] - -use parity_crypto::error::SymmError; -use secp256k1; -use std::io; - -quick_error! { - #[derive(Debug)] - pub enum Error { - Secp(e: secp256k1::Error) { - display("secp256k1 error: {}", e) - cause(e) - from() - } - Io(e: io::Error) { - display("i/o error: {}", e) - cause(e) - from() - } - InvalidMessage { - display("invalid message") - } - Symm(e: SymmError) { - cause(e) - from() - } - } -} - -/// ECDH functions -pub mod ecdh { - use super::Error; - use secp256k1::{self, ecdh, key}; - use Public; - use Secret; - use SECP256K1; - - /// Agree on a shared secret - pub fn agree(secret: &Secret, public: &Public) -> Result { - let context = &SECP256K1; - let pdata = { - let mut temp = [4u8; 65]; - (&mut temp[1..65]).copy_from_slice(&public[0..64]); - temp - }; - - let publ = key::PublicKey::from_slice(context, &pdata)?; - let sec = key::SecretKey::from_slice(context, &secret)?; - let shared = ecdh::SharedSecret::new_raw(context, &publ, &sec); - - Secret::from_unsafe_slice(&shared[0..32]) - .map_err(|_| Error::Secp(secp256k1::Error::InvalidSecretKey)) - } -} - -/// ECIES function -pub mod ecies { - use super::{ecdh, Error}; - use ethereum_types::H128; - use parity_crypto::{aes, digest, hmac, is_equal}; - use Generator; - use Public; - use Random; - use Secret; - - /// Encrypt a message with a public key, writing an HMAC covering both - /// the plaintext and authenticated data. - /// - /// Authenticated data may be empty. - pub fn encrypt(public: &Public, auth_data: &[u8], plain: &[u8]) -> Result, Error> { - let r = Random.generate()?; - let z = ecdh::agree(r.secret(), public)?; - let mut key = [0u8; 32]; - kdf(&z, &[0u8; 0], &mut key); - - let ekey = &key[0..16]; - let mkey = hmac::SigKey::sha256(&digest::sha256(&key[16..32])); - - let mut msg = vec![0u8; 1 + 64 + 16 + plain.len() + 32]; - msg[0] = 0x04u8; - { - let msgd = &mut msg[1..]; - msgd[0..64].copy_from_slice(r.public()); - let iv = H128::random(); - msgd[64..80].copy_from_slice(&iv); - { - let cipher = &mut msgd[(64 + 16)..(64 + 16 + plain.len())]; - aes::encrypt_128_ctr(ekey, &iv, plain, cipher)?; - } - let mut hmac = hmac::Signer::with(&mkey); - { - let cipher_iv = &msgd[64..(64 + 16 + plain.len())]; - hmac.update(cipher_iv); - } - hmac.update(auth_data); - let sig = hmac.sign(); - msgd[(64 + 16 + plain.len())..].copy_from_slice(&sig); - } - Ok(msg) - } - - /// Decrypt a message with a secret key, checking HMAC for ciphertext - /// and authenticated data validity. - pub fn decrypt(secret: &Secret, auth_data: &[u8], encrypted: &[u8]) -> Result, Error> { - let meta_len = 1 + 64 + 16 + 32; - if encrypted.len() < meta_len || encrypted[0] < 2 || encrypted[0] > 4 { - return Err(Error::InvalidMessage); //invalid message: publickey - } - - let e = &encrypted[1..]; - let p = Public::from_slice(&e[0..64]); - let z = ecdh::agree(secret, &p)?; - let mut key = [0u8; 32]; - kdf(&z, &[0u8; 0], &mut key); - - let ekey = &key[0..16]; - let mkey = hmac::SigKey::sha256(&digest::sha256(&key[16..32])); - - let clen = encrypted.len() - meta_len; - let cipher_with_iv = &e[64..(64 + 16 + clen)]; - let cipher_iv = &cipher_with_iv[0..16]; - let cipher_no_iv = &cipher_with_iv[16..]; - let msg_mac = &e[(64 + 16 + clen)..]; - - // Verify tag - let mut hmac = hmac::Signer::with(&mkey); - hmac.update(cipher_with_iv); - hmac.update(auth_data); - let mac = hmac.sign(); - - if !is_equal(&mac.as_ref()[..], msg_mac) { - return Err(Error::InvalidMessage); - } - - let mut msg = vec![0u8; clen]; - aes::decrypt_128_ctr(ekey, cipher_iv, cipher_no_iv, &mut msg[..])?; - Ok(msg) - } - - fn kdf(secret: &Secret, s1: &[u8], dest: &mut [u8]) { - // SEC/ISO/Shoup specify counter size SHOULD be equivalent - // to size of hash output, however, it also notes that - // the 4 bytes is okay. NIST specifies 4 bytes. - let mut ctr = 1u32; - let mut written = 0usize; - while written < dest.len() { - let mut hasher = digest::Hasher::sha256(); - let ctrs = [ - (ctr >> 24) as u8, - (ctr >> 16) as u8, - (ctr >> 8) as u8, - ctr as u8, - ]; - hasher.update(&ctrs); - hasher.update(secret); - hasher.update(s1); - let d = hasher.finish(); - &mut dest[written..(written + 32)].copy_from_slice(&d); - written += 32; - ctr += 1; - } - } -} - -#[cfg(test)] -mod tests { - use super::ecies; - use Generator; - use Random; - - #[test] - fn ecies_shared() { - let kp = Random.generate().unwrap(); - let message = b"So many books, so little time"; - - let shared = b"shared"; - let wrong_shared = b"incorrect"; - let encrypted = ecies::encrypt(kp.public(), shared, message).unwrap(); - assert!(encrypted[..] != message[..]); - assert_eq!(encrypted[0], 0x04); - - assert!(ecies::decrypt(kp.secret(), wrong_shared, &encrypted).is_err()); - let decrypted = ecies::decrypt(kp.secret(), shared, &encrypted).unwrap(); - assert_eq!(decrypted[..message.len()], message[..]); - } -} diff --git a/crates/accounts/ethkey/src/error.rs b/crates/accounts/ethkey/src/error.rs deleted file mode 100644 index 3e66a905d..000000000 --- a/crates/accounts/ethkey/src/error.rs +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright 2015-2020 Parity Technologies (UK) Ltd. -// This file is part of OpenEthereum. - -// OpenEthereum 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. - -// OpenEthereum 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 OpenEthereum. If not, see . - -use std::{error, fmt}; - -#[derive(Debug)] -/// Crypto error -pub enum Error { - /// Invalid secret key - InvalidSecret, - /// Invalid public key - InvalidPublic, - /// Invalid address - InvalidAddress, - /// Invalid EC signature - InvalidSignature, - /// Invalid AES message - InvalidMessage, - /// IO Error - Io(::std::io::Error), - /// Custom - Custom(String), -} - -impl fmt::Display for Error { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - let msg = match *self { - Error::InvalidSecret => "Invalid secret".into(), - Error::InvalidPublic => "Invalid public".into(), - Error::InvalidAddress => "Invalid address".into(), - Error::InvalidSignature => "Invalid EC signature".into(), - Error::InvalidMessage => "Invalid AES message".into(), - Error::Io(ref err) => format!("I/O error: {}", err), - Error::Custom(ref s) => s.clone(), - }; - - f.write_fmt(format_args!("Crypto error ({})", msg)) - } -} - -impl error::Error for Error { - fn description(&self) -> &str { - "Crypto error" - } -} - -impl Into for Error { - fn into(self) -> String { - format!("{}", self) - } -} - -impl From<::secp256k1::Error> for Error { - fn from(e: ::secp256k1::Error) -> Error { - match e { - ::secp256k1::Error::InvalidMessage => Error::InvalidMessage, - ::secp256k1::Error::InvalidPublicKey => Error::InvalidPublic, - ::secp256k1::Error::InvalidSecretKey => Error::InvalidSecret, - _ => Error::InvalidSignature, - } - } -} - -impl From<::std::io::Error> for Error { - fn from(err: ::std::io::Error) -> Error { - Error::Io(err) - } -} diff --git a/crates/accounts/ethkey/src/extended.rs b/crates/accounts/ethkey/src/extended.rs deleted file mode 100644 index 663f555e7..000000000 --- a/crates/accounts/ethkey/src/extended.rs +++ /dev/null @@ -1,589 +0,0 @@ -// Copyright 2015-2020 Parity Technologies (UK) Ltd. -// This file is part of OpenEthereum. - -// OpenEthereum 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. - -// OpenEthereum 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 OpenEthereum. If not, see . - -//! Extended keys - -pub use self::derivation::Error as DerivationError; -use ethereum_types::H256; -use secret::Secret; -use Public; - -/// Represents label that can be stored as a part of key derivation -pub trait Label { - /// Length of the data that label occupies - fn len() -> usize; - - /// Store label data to the key derivation sequence - /// Must not use more than `len()` bytes from slice - fn store(&self, target: &mut [u8]); -} - -impl Label for u32 { - fn len() -> usize { - 4 - } - - fn store(&self, target: &mut [u8]) { - let bytes = self.to_be_bytes(); - target[0..4].copy_from_slice(&bytes); - } -} - -/// Key derivation over generic label `T` -pub enum Derivation { - /// Soft key derivation (allow proof of parent) - Soft(T), - /// Hard key derivation (does not allow proof of parent) - Hard(T), -} - -impl From for Derivation { - fn from(index: u32) -> Self { - if index < (2 << 30) { - Derivation::Soft(index) - } else { - Derivation::Hard(index) - } - } -} - -impl Label for H256 { - fn len() -> usize { - 32 - } - - fn store(&self, target: &mut [u8]) { - self.copy_to(&mut target[0..32]); - } -} - -/// Extended secret key, allows deterministic derivation of subsequent keys. -pub struct ExtendedSecret { - secret: Secret, - chain_code: H256, -} - -impl ExtendedSecret { - /// New extended key from given secret and chain code. - pub fn with_code(secret: Secret, chain_code: H256) -> ExtendedSecret { - ExtendedSecret { - secret: secret, - chain_code: chain_code, - } - } - - /// New extended key from given secret with the random chain code. - pub fn new_random(secret: Secret) -> ExtendedSecret { - ExtendedSecret::with_code(secret, H256::random()) - } - - /// New extended key from given secret. - /// Chain code will be derived from the secret itself (in a deterministic way). - pub fn new(secret: Secret) -> ExtendedSecret { - let chain_code = derivation::chain_code(*secret); - ExtendedSecret::with_code(secret, chain_code) - } - - /// Derive new private key - pub fn derive(&self, index: Derivation) -> ExtendedSecret - where - T: Label, - { - let (derived_key, next_chain_code) = - derivation::private(*self.secret, self.chain_code, index); - - let derived_secret = Secret::from(derived_key.0); - - ExtendedSecret::with_code(derived_secret, next_chain_code) - } - - /// Private key component of the extended key. - pub fn as_raw(&self) -> &Secret { - &self.secret - } -} - -/// Extended public key, allows deterministic derivation of subsequent keys. -pub struct ExtendedPublic { - public: Public, - chain_code: H256, -} - -impl ExtendedPublic { - /// New extended public key from known parent and chain code - pub fn new(public: Public, chain_code: H256) -> Self { - ExtendedPublic { - public: public, - chain_code: chain_code, - } - } - - /// Create new extended public key from known secret - pub fn from_secret(secret: &ExtendedSecret) -> Result { - Ok(ExtendedPublic::new( - derivation::point(**secret.as_raw())?, - secret.chain_code.clone(), - )) - } - - /// Derive new public key - /// Operation is defined only for index belongs [0..2^31) - pub fn derive(&self, index: Derivation) -> Result - where - T: Label, - { - let (derived_key, next_chain_code) = - derivation::public(self.public, self.chain_code, index)?; - Ok(ExtendedPublic::new(derived_key, next_chain_code)) - } - - pub fn public(&self) -> &Public { - &self.public - } -} - -pub struct ExtendedKeyPair { - secret: ExtendedSecret, - public: ExtendedPublic, -} - -impl ExtendedKeyPair { - pub fn new(secret: Secret) -> Self { - let extended_secret = ExtendedSecret::new(secret); - let extended_public = ExtendedPublic::from_secret(&extended_secret) - .expect("Valid `Secret` always produces valid public; qed"); - ExtendedKeyPair { - secret: extended_secret, - public: extended_public, - } - } - - pub fn with_code(secret: Secret, public: Public, chain_code: H256) -> Self { - ExtendedKeyPair { - secret: ExtendedSecret::with_code(secret, chain_code.clone()), - public: ExtendedPublic::new(public, chain_code), - } - } - - pub fn with_secret(secret: Secret, chain_code: H256) -> Self { - let extended_secret = ExtendedSecret::with_code(secret, chain_code); - let extended_public = ExtendedPublic::from_secret(&extended_secret) - .expect("Valid `Secret` always produces valid public; qed"); - ExtendedKeyPair { - secret: extended_secret, - public: extended_public, - } - } - - pub fn with_seed(seed: &[u8]) -> Result { - let (master_key, chain_code) = derivation::seed_pair(seed); - Ok(ExtendedKeyPair::with_secret( - Secret::from_unsafe_slice(&*master_key).map_err(|_| DerivationError::InvalidSeed)?, - chain_code, - )) - } - - pub fn secret(&self) -> &ExtendedSecret { - &self.secret - } - - pub fn public(&self) -> &ExtendedPublic { - &self.public - } - - pub fn derive(&self, index: Derivation) -> Result - where - T: Label, - { - let derived = self.secret.derive(index); - - Ok(ExtendedKeyPair { - public: ExtendedPublic::from_secret(&derived)?, - secret: derived, - }) - } -} - -// Derivation functions for private and public keys -// Work is based on BIP0032 -// https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki -mod derivation { - use super::{Derivation, Label}; - use ethereum_types::{H256, H512, U256, U512}; - use keccak; - use math::curve_order; - use parity_crypto::hmac; - use secp256k1::key::{PublicKey, SecretKey}; - use SECP256K1; - - #[derive(Debug)] - pub enum Error { - InvalidHardenedUse, - InvalidPoint, - MissingIndex, - InvalidSeed, - } - - // Deterministic derivation of the key using secp256k1 elliptic curve. - // Derivation can be either hardened or not. - // For hardened derivation, pass u32 index at least 2^31 or custom Derivation::Hard(T) enum - // - // Can panic if passed `private_key` is not a valid secp256k1 private key - // (outside of (0..curve_order()]) field - pub fn private(private_key: H256, chain_code: H256, index: Derivation) -> (H256, H256) - where - T: Label, - { - match index { - Derivation::Soft(index) => private_soft(private_key, chain_code, index), - Derivation::Hard(index) => private_hard(private_key, chain_code, index), - } - } - - fn hmac_pair(data: &[u8], private_key: H256, chain_code: H256) -> (H256, H256) { - let private: U256 = private_key.into(); - - // produces 512-bit derived hmac (I) - let skey = hmac::SigKey::sha512(&*chain_code); - let i_512 = hmac::sign(&skey, &data[..]); - - // left most 256 bits are later added to original private key - let hmac_key: U256 = H256::from_slice(&i_512[0..32]).into(); - // right most 256 bits are new chain code for later derivations - let next_chain_code = H256::from(&i_512[32..64]); - - let child_key = private_add(hmac_key, private).into(); - (child_key, next_chain_code) - } - - // Can panic if passed `private_key` is not a valid secp256k1 private key - // (outside of (0..curve_order()]) field - fn private_soft(private_key: H256, chain_code: H256, index: T) -> (H256, H256) - where - T: Label, - { - let mut data = vec![0u8; 33 + T::len()]; - - let sec_private = SecretKey::from_slice(&SECP256K1, &*private_key) - .expect("Caller should provide valid private key"); - let sec_public = PublicKey::from_secret_key(&SECP256K1, &sec_private) - .expect("Caller should provide valid private key"); - let public_serialized = sec_public.serialize_vec(&SECP256K1, true); - - // curve point (compressed public key) -- index - // 0.33 -- 33..end - data[0..33].copy_from_slice(&public_serialized); - index.store(&mut data[33..]); - - hmac_pair(&data, private_key, chain_code) - } - - // Deterministic derivation of the key using secp256k1 elliptic curve - // This is hardened derivation and does not allow to associate - // corresponding public keys of the original and derived private keys - fn private_hard(private_key: H256, chain_code: H256, index: T) -> (H256, H256) - where - T: Label, - { - let mut data: Vec = vec![0u8; 33 + T::len()]; - let private: U256 = private_key.into(); - - // 0x00 (padding) -- private_key -- index - // 0 -- 1..33 -- 33..end - private.to_big_endian(&mut data[1..33]); - index.store(&mut data[33..(33 + T::len())]); - - hmac_pair(&data, private_key, chain_code) - } - - fn private_add(k1: U256, k2: U256) -> U256 { - let sum = U512::from(k1) + U512::from(k2); - modulo(sum, curve_order()) - } - - // todo: surely can be optimized - fn modulo(u1: U512, u2: U256) -> U256 { - let dv = u1 / U512::from(u2); - let md = u1 - (dv * U512::from(u2)); - md.into() - } - - pub fn public( - public_key: H512, - chain_code: H256, - derivation: Derivation, - ) -> Result<(H512, H256), Error> - where - T: Label, - { - let index = match derivation { - Derivation::Soft(index) => index, - Derivation::Hard(_) => { - return Err(Error::InvalidHardenedUse); - } - }; - - let mut public_sec_raw = [0u8; 65]; - public_sec_raw[0] = 4; - public_sec_raw[1..65].copy_from_slice(&*public_key); - let public_sec = - PublicKey::from_slice(&SECP256K1, &public_sec_raw).map_err(|_| Error::InvalidPoint)?; - let public_serialized = public_sec.serialize_vec(&SECP256K1, true); - - let mut data = vec![0u8; 33 + T::len()]; - // curve point (compressed public key) -- index - // 0.33 -- 33..end - data[0..33].copy_from_slice(&public_serialized); - index.store(&mut data[33..(33 + T::len())]); - - // HMAC512SHA produces [derived private(256); new chain code(256)] - let skey = hmac::SigKey::sha512(&*chain_code); - let i_512 = hmac::sign(&skey, &data[..]); - - let new_private = H256::from(&i_512[0..32]); - let new_chain_code = H256::from(&i_512[32..64]); - - // Generated private key can (extremely rarely) be out of secp256k1 key field - if curve_order() <= new_private.clone().into() { - return Err(Error::MissingIndex); - } - let new_private_sec = SecretKey::from_slice(&SECP256K1, &*new_private) - .expect("Private key belongs to the field [0..CURVE_ORDER) (checked above); So initializing can never fail; qed"); - let mut new_public = PublicKey::from_secret_key(&SECP256K1, &new_private_sec) - .expect("Valid private key produces valid public key"); - - // Adding two points on the elliptic curves (combining two public keys) - new_public - .add_assign(&SECP256K1, &public_sec) - .expect("Addition of two valid points produce valid point"); - - let serialized = new_public.serialize_vec(&SECP256K1, false); - - Ok((H512::from(&serialized[1..65]), new_chain_code)) - } - - fn sha3(slc: &[u8]) -> H256 { - keccak::Keccak256::keccak256(slc).into() - } - - pub fn chain_code(secret: H256) -> H256 { - // 10,000 rounds of sha3 - let mut running_sha3 = sha3(&*secret); - for _ in 0..99999 { - running_sha3 = sha3(&*running_sha3); - } - running_sha3 - } - - pub fn point(secret: H256) -> Result { - let sec = SecretKey::from_slice(&SECP256K1, &*secret).map_err(|_| Error::InvalidPoint)?; - let public_sec = - PublicKey::from_secret_key(&SECP256K1, &sec).map_err(|_| Error::InvalidPoint)?; - let serialized = public_sec.serialize_vec(&SECP256K1, false); - Ok(H512::from(&serialized[1..65])) - } - - pub fn seed_pair(seed: &[u8]) -> (H256, H256) { - let skey = hmac::SigKey::sha512(b"Bitcoin seed"); - let i_512 = hmac::sign(&skey, seed); - - let master_key = H256::from_slice(&i_512[0..32]); - let chain_code = H256::from_slice(&i_512[32..64]); - - (master_key, chain_code) - } -} - -#[cfg(test)] -mod tests { - use super::{derivation, Derivation, ExtendedKeyPair, ExtendedPublic, ExtendedSecret}; - use ethereum_types::{H128, H256}; - use secret::Secret; - use std::str::FromStr; - - fn master_chain_basic() -> (H256, H256) { - let seed = H128::from_str("000102030405060708090a0b0c0d0e0f") - .expect("Seed should be valid H128") - .to_vec(); - - derivation::seed_pair(&*seed) - } - - fn test_extended(f: F, test_private: H256) - where - F: Fn(ExtendedSecret) -> ExtendedSecret, - { - let (private_seed, chain_code) = master_chain_basic(); - let extended_secret = ExtendedSecret::with_code(Secret::from(private_seed.0), chain_code); - let derived = f(extended_secret); - assert_eq!(**derived.as_raw(), test_private); - } - - #[test] - fn smoky() { - let secret = - Secret::from_str("a100df7a048e50ed308ea696dc600215098141cb391e9527329df289f9383f65") - .unwrap(); - let extended_secret = ExtendedSecret::with_code(secret.clone(), 0u64.into()); - - // hardened - assert_eq!(&**extended_secret.as_raw(), &*secret); - assert_eq!( - &**extended_secret.derive(2147483648.into()).as_raw(), - &"0927453daed47839608e414a3738dfad10aed17c459bbd9ab53f89b026c834b6".into() - ); - assert_eq!( - &**extended_secret.derive(2147483649.into()).as_raw(), - &"44238b6a29c6dcbe9b401364141ba11e2198c289a5fed243a1c11af35c19dc0f".into() - ); - - // normal - assert_eq!( - &**extended_secret.derive(0.into()).as_raw(), - &"bf6a74e3f7b36fc4c96a1e12f31abc817f9f5904f5a8fc27713163d1f0b713f6".into() - ); - assert_eq!( - &**extended_secret.derive(1.into()).as_raw(), - &"bd4fca9eb1f9c201e9448c1eecd66e302d68d4d313ce895b8c134f512205c1bc".into() - ); - assert_eq!( - &**extended_secret.derive(2.into()).as_raw(), - &"86932b542d6cab4d9c65490c7ef502d89ecc0e2a5f4852157649e3251e2a3268".into() - ); - - let extended_public = ExtendedPublic::from_secret(&extended_secret) - .expect("Extended public should be created"); - let derived_public = extended_public - .derive(0.into()) - .expect("First derivation of public should succeed"); - assert_eq!(&*derived_public.public(), &"f7b3244c96688f92372bfd4def26dc4151529747bab9f188a4ad34e141d47bd66522ff048bc6f19a0a4429b04318b1a8796c000265b4fa200dae5f6dda92dd94".into()); - - let keypair = ExtendedKeyPair::with_secret( - Secret::from_str("a100df7a048e50ed308ea696dc600215098141cb391e9527329df289f9383f65") - .unwrap(), - 064.into(), - ); - assert_eq!( - &**keypair - .derive(2147483648u32.into()) - .expect("Derivation of keypair should succeed") - .secret() - .as_raw(), - &"edef54414c03196557cf73774bc97a645c9a1df2164ed34f0c2a78d1375a930c".into() - ); - } - - #[test] - fn h256_soft_match() { - let secret = - Secret::from_str("a100df7a048e50ed308ea696dc600215098141cb391e9527329df289f9383f65") - .unwrap(); - let derivation_secret = - H256::from_str("51eaf04f9dbbc1417dc97e789edd0c37ecda88bac490434e367ea81b71b7b015") - .unwrap(); - - let extended_secret = ExtendedSecret::with_code(secret.clone(), 0u64.into()); - let extended_public = ExtendedPublic::from_secret(&extended_secret) - .expect("Extended public should be created"); - - let derived_secret0 = extended_secret.derive(Derivation::Soft(derivation_secret)); - let derived_public0 = extended_public - .derive(Derivation::Soft(derivation_secret)) - .expect("First derivation of public should succeed"); - - let public_from_secret0 = ExtendedPublic::from_secret(&derived_secret0) - .expect("Extended public should be created"); - - assert_eq!(public_from_secret0.public(), derived_public0.public()); - } - - #[test] - fn h256_hard() { - let secret = - Secret::from_str("a100df7a048e50ed308ea696dc600215098141cb391e9527329df289f9383f65") - .unwrap(); - let derivation_secret = - H256::from_str("51eaf04f9dbbc1417dc97e789edd0c37ecda88bac490434e367ea81b71b7b015") - .unwrap(); - let extended_secret = ExtendedSecret::with_code(secret.clone(), 1u64.into()); - - assert_eq!( - &**extended_secret - .derive(Derivation::Hard(derivation_secret)) - .as_raw(), - &"2bc2d696fb744d77ff813b4a1ef0ad64e1e5188b622c54ba917acc5ebc7c5486".into() - ); - } - - #[test] - fn match_() { - let secret = - Secret::from_str("a100df7a048e50ed308ea696dc600215098141cb391e9527329df289f9383f65") - .unwrap(); - let extended_secret = ExtendedSecret::with_code(secret.clone(), 1.into()); - let extended_public = ExtendedPublic::from_secret(&extended_secret) - .expect("Extended public should be created"); - - let derived_secret0 = extended_secret.derive(0.into()); - let derived_public0 = extended_public - .derive(0.into()) - .expect("First derivation of public should succeed"); - - let public_from_secret0 = ExtendedPublic::from_secret(&derived_secret0) - .expect("Extended public should be created"); - - assert_eq!(public_from_secret0.public(), derived_public0.public()); - } - - #[test] - fn test_seeds() { - let seed = H128::from_str("000102030405060708090a0b0c0d0e0f") - .expect("Seed should be valid H128") - .to_vec(); - - // private key from bitcoin test vector - // xprv9wTYmMFdV23N2TdNG573QoEsfRrWKQgWeibmLntzniatZvR9BmLnvSxqu53Kw1UmYPxLgboyZQaXwTCg8MSY3H2EU4pWcQDnRnrVA1xe8fs - let test_private = - H256::from_str("e8f32e723decf4051aefac8e2c93c9c5b214313817cdb01a1494b917c8436b35") - .expect("Private should be decoded ok"); - - let (private_seed, _) = derivation::seed_pair(&*seed); - - assert_eq!(private_seed, test_private); - } - - #[test] - fn test_vector_1() { - // xprv9uHRZZhk6KAJC1avXpDAp4MDc3sQKNxDiPvvkX8Br5ngLNv1TxvUxt4cV1rGL5hj6KCesnDYUhd7oWgT11eZG7XnxHrnYeSvkzY7d2bhkJ7 - // H(0) - test_extended( - |secret| secret.derive(2147483648.into()), - H256::from_str("edb2e14f9ee77d26dd93b4ecede8d16ed408ce149b6cd80b0715a2d911a0afea") - .expect("Private should be decoded ok"), - ); - } - - #[test] - fn test_vector_2() { - // xprv9wTYmMFdV23N2TdNG573QoEsfRrWKQgWeibmLntzniatZvR9BmLnvSxqu53Kw1UmYPxLgboyZQaXwTCg8MSY3H2EU4pWcQDnRnrVA1xe8fs - // H(0)/1 - test_extended( - |secret| secret.derive(2147483648.into()).derive(1.into()), - H256::from_str("3c6cb8d0f6a264c91ea8b5030fadaa8e538b020f0a387421a12de9319dc93368") - .expect("Private should be decoded ok"), - ); - } -} diff --git a/crates/accounts/ethkey/src/keccak.rs b/crates/accounts/ethkey/src/keccak.rs deleted file mode 100644 index e3c67b34d..000000000 --- a/crates/accounts/ethkey/src/keccak.rs +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright 2015-2020 Parity Technologies (UK) Ltd. -// This file is part of OpenEthereum. - -// OpenEthereum 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. - -// OpenEthereum 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 OpenEthereum. If not, see . - -use tiny_keccak::Keccak; - -pub trait Keccak256 { - fn keccak256(&self) -> T - where - T: Sized; -} - -impl Keccak256<[u8; 32]> for [u8] { - fn keccak256(&self) -> [u8; 32] { - let mut keccak = Keccak::new_keccak256(); - let mut result = [0u8; 32]; - keccak.update(self); - keccak.finalize(&mut result); - result - } -} diff --git a/crates/accounts/ethkey/src/keypair.rs b/crates/accounts/ethkey/src/keypair.rs deleted file mode 100644 index 7f97e03fb..000000000 --- a/crates/accounts/ethkey/src/keypair.rs +++ /dev/null @@ -1,120 +0,0 @@ -// Copyright 2015-2020 Parity Technologies (UK) Ltd. -// This file is part of OpenEthereum. - -// OpenEthereum 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. - -// OpenEthereum 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 OpenEthereum. If not, see . - -use super::{Address, Error, Public, Secret, SECP256K1}; -use keccak::Keccak256; -use rustc_hex::ToHex; -use secp256k1::key; -use std::fmt; - -pub fn public_to_address(public: &Public) -> Address { - let hash = public.keccak256(); - let mut result = Address::default(); - result.copy_from_slice(&hash[12..]); - result -} - -#[derive(Debug, Clone, PartialEq)] -/// secp256k1 key pair -pub struct KeyPair { - secret: Secret, - public: Public, -} - -impl fmt::Display for KeyPair { - fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { - writeln!(f, "secret: {}", self.secret.to_hex())?; - writeln!(f, "public: {}", self.public.to_hex())?; - write!(f, "address: {}", self.address().to_hex()) - } -} - -impl KeyPair { - /// Create a pair from secret key - pub fn from_secret(secret: Secret) -> Result { - let context = &SECP256K1; - let s: key::SecretKey = key::SecretKey::from_slice(context, &secret[..])?; - let pub_key = key::PublicKey::from_secret_key(context, &s)?; - let serialized = pub_key.serialize_vec(context, false); - - let mut public = Public::default(); - public.copy_from_slice(&serialized[1..65]); - - let keypair = KeyPair { - secret: secret, - public: public, - }; - - Ok(keypair) - } - - pub fn from_secret_slice(slice: &[u8]) -> Result { - Self::from_secret(Secret::from_unsafe_slice(slice)?) - } - - pub fn from_keypair(sec: key::SecretKey, publ: key::PublicKey) -> Self { - let context = &SECP256K1; - let serialized = publ.serialize_vec(context, false); - let secret = Secret::from(sec); - let mut public = Public::default(); - public.copy_from_slice(&serialized[1..65]); - - KeyPair { - secret: secret, - public: public, - } - } - - pub fn secret(&self) -> &Secret { - &self.secret - } - - pub fn public(&self) -> &Public { - &self.public - } - - pub fn address(&self) -> Address { - public_to_address(&self.public) - } -} - -#[cfg(test)] -mod tests { - use std::str::FromStr; - use KeyPair; - use Secret; - - #[test] - fn from_secret() { - let secret = - Secret::from_str("a100df7a048e50ed308ea696dc600215098141cb391e9527329df289f9383f65") - .unwrap(); - let _ = KeyPair::from_secret(secret).unwrap(); - } - - #[test] - fn keypair_display() { - let expected = -"secret: a100df7a048e50ed308ea696dc600215098141cb391e9527329df289f9383f65 -public: 8ce0db0b0359ffc5866ba61903cc2518c3675ef2cf380a7e54bde7ea20e6fa1ab45b7617346cd11b7610001ee6ae5b0155c41cad9527cbcdff44ec67848943a4 -address: 5b073e9233944b5e729e46d618f0d8edf3d9c34a".to_owned(); - let secret = - Secret::from_str("a100df7a048e50ed308ea696dc600215098141cb391e9527329df289f9383f65") - .unwrap(); - let kp = KeyPair::from_secret(secret).unwrap(); - assert_eq!(format!("{}", kp), expected); - } -} diff --git a/crates/accounts/ethkey/src/lib.rs b/crates/accounts/ethkey/src/lib.rs index 4aa436dc2..19accc4e1 100644 --- a/crates/accounts/ethkey/src/lib.rs +++ b/crates/accounts/ethkey/src/lib.rs @@ -17,20 +17,10 @@ // #![warn(missing_docs)] extern crate edit_distance; -extern crate ethereum_types; -extern crate memzero; extern crate parity_crypto; extern crate parity_wordlist; -#[macro_use] -extern crate quick_error; -extern crate rand; -extern crate rustc_hex; -extern crate secp256k1; extern crate serde; -extern crate tiny_keccak; -#[macro_use] -extern crate lazy_static; #[macro_use] extern crate log; #[macro_use] @@ -38,52 +28,12 @@ extern crate serde_derive; mod brain; mod brain_prefix; -mod error; -mod extended; -mod keccak; -mod keypair; mod password; mod prefix; -mod random; -mod secret; -mod signature; pub mod brain_recover; -pub mod crypto; -pub mod math; pub use self::{ - brain::Brain, - brain_prefix::BrainPrefix, - error::Error, - extended::{Derivation, DerivationError, ExtendedKeyPair, ExtendedPublic, ExtendedSecret}, - keypair::{public_to_address, KeyPair}, - math::public_is_valid, - parity_wordlist::Error as WordlistError, - password::Password, - prefix::Prefix, - random::Random, - secret::Secret, - signature::{recover, sign, verify_address, verify_public, Signature}, + brain::Brain, brain_prefix::BrainPrefix, parity_wordlist::Error as WordlistError, + password::Password, prefix::Prefix, }; - -use ethereum_types::H256; - -pub use ethereum_types::{Address, Public}; -pub type Message = H256; - -lazy_static! { - pub static ref SECP256K1: secp256k1::Secp256k1 = secp256k1::Secp256k1::new(); -} - -/// Uninstantiatable error type for infallible generators. -#[derive(Debug)] -pub enum Void {} - -/// Generates new keypair. -pub trait Generator { - type Error; - - /// Should be called to generate new keypair. - fn generate(&mut self) -> Result; -} diff --git a/crates/accounts/ethkey/src/math.rs b/crates/accounts/ethkey/src/math.rs deleted file mode 100644 index 5b61cd05d..000000000 --- a/crates/accounts/ethkey/src/math.rs +++ /dev/null @@ -1,134 +0,0 @@ -// Copyright 2015-2020 Parity Technologies (UK) Ltd. -// This file is part of OpenEthereum. - -// OpenEthereum 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. - -// OpenEthereum 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 OpenEthereum. If not, see . - -use super::{Error, Public, Secret, SECP256K1}; -use ethereum_types::{H256, U256}; -use secp256k1::{ - constants::{CURVE_ORDER, GENERATOR_X, GENERATOR_Y}, - key, -}; - -/// Whether the public key is valid. -pub fn public_is_valid(public: &Public) -> bool { - to_secp256k1_public(public) - .ok() - .map_or(false, |p| p.is_valid()) -} - -/// Inplace multiply public key by secret key (EC point * scalar) -pub fn public_mul_secret(public: &mut Public, secret: &Secret) -> Result<(), Error> { - let key_secret = secret.to_secp256k1_secret()?; - let mut key_public = to_secp256k1_public(public)?; - key_public.mul_assign(&SECP256K1, &key_secret)?; - set_public(public, &key_public); - Ok(()) -} - -/// Inplace add one public key to another (EC point + EC point) -pub fn public_add(public: &mut Public, other: &Public) -> Result<(), Error> { - let mut key_public = to_secp256k1_public(public)?; - let other_public = to_secp256k1_public(other)?; - key_public.add_assign(&SECP256K1, &other_public)?; - set_public(public, &key_public); - Ok(()) -} - -/// Inplace sub one public key from another (EC point - EC point) -pub fn public_sub(public: &mut Public, other: &Public) -> Result<(), Error> { - let mut key_neg_other = to_secp256k1_public(other)?; - key_neg_other.mul_assign(&SECP256K1, &key::MINUS_ONE_KEY)?; - - let mut key_public = to_secp256k1_public(public)?; - key_public.add_assign(&SECP256K1, &key_neg_other)?; - set_public(public, &key_public); - Ok(()) -} - -/// Replace public key with its negation (EC point = - EC point) -pub fn public_negate(public: &mut Public) -> Result<(), Error> { - let mut key_public = to_secp256k1_public(public)?; - key_public.mul_assign(&SECP256K1, &key::MINUS_ONE_KEY)?; - set_public(public, &key_public); - Ok(()) -} - -/// Return base point of secp256k1 -pub fn generation_point() -> Public { - let mut public_sec_raw = [0u8; 65]; - public_sec_raw[0] = 4; - public_sec_raw[1..33].copy_from_slice(&GENERATOR_X); - public_sec_raw[33..65].copy_from_slice(&GENERATOR_Y); - - let public_key = key::PublicKey::from_slice(&SECP256K1, &public_sec_raw) - .expect("constructing using predefined constants; qed"); - let mut public = Public::default(); - set_public(&mut public, &public_key); - public -} - -/// Return secp256k1 elliptic curve order -pub fn curve_order() -> U256 { - H256::from_slice(&CURVE_ORDER).into() -} - -fn to_secp256k1_public(public: &Public) -> Result { - let public_data = { - let mut temp = [4u8; 65]; - (&mut temp[1..65]).copy_from_slice(&public[0..64]); - temp - }; - - Ok(key::PublicKey::from_slice(&SECP256K1, &public_data)?) -} - -fn set_public(public: &mut Public, key_public: &key::PublicKey) { - let key_public_serialized = key_public.serialize_vec(&SECP256K1, false); - public.copy_from_slice(&key_public_serialized[1..65]); -} - -#[cfg(test)] -mod tests { - use super::{ - super::{Generator, Random}, - public_add, public_sub, - }; - - #[test] - fn public_addition_is_commutative() { - let public1 = Random.generate().unwrap().public().clone(); - let public2 = Random.generate().unwrap().public().clone(); - - let mut left = public1.clone(); - public_add(&mut left, &public2).unwrap(); - - let mut right = public2.clone(); - public_add(&mut right, &public1).unwrap(); - - assert_eq!(left, right); - } - - #[test] - fn public_addition_is_reversible_with_subtraction() { - let public1 = Random.generate().unwrap().public().clone(); - let public2 = Random.generate().unwrap().public().clone(); - - let mut sum = public1.clone(); - public_add(&mut sum, &public2).unwrap(); - public_sub(&mut sum, &public2).unwrap(); - - assert_eq!(sum, public1); - } -} diff --git a/crates/accounts/ethkey/src/prefix.rs b/crates/accounts/ethkey/src/prefix.rs index 61382e721..e037c41fe 100644 --- a/crates/accounts/ethkey/src/prefix.rs +++ b/crates/accounts/ethkey/src/prefix.rs @@ -14,7 +14,7 @@ // You should have received a copy of the GNU General Public License // along with OpenEthereum. If not, see . -use super::{Error, Generator, KeyPair, Random}; +use parity_crypto::publickey::{Error, Generator, KeyPair, Random}; /// Tries to find keypair with address starting with given prefix. pub struct Prefix { @@ -24,20 +24,13 @@ pub struct Prefix { impl Prefix { pub fn new(prefix: Vec, iterations: usize) -> Self { - Prefix { - prefix: prefix, - iterations: iterations, - } + Prefix { prefix, iterations } } -} -impl Generator for Prefix { - type Error = Error; - - fn generate(&mut self) -> Result { + pub fn generate(&mut self) -> Result { for _ in 0..self.iterations { - let keypair = Random.generate()?; - if keypair.address().starts_with(&self.prefix) { + let keypair = Random.generate(); + if keypair.address().as_ref().starts_with(&self.prefix) { return Ok(keypair); } } @@ -48,7 +41,6 @@ impl Generator for Prefix { #[cfg(test)] mod tests { - use Generator; use Prefix; #[test] @@ -57,6 +49,6 @@ mod tests { let keypair = Prefix::new(prefix.clone(), usize::max_value()) .generate() .unwrap(); - assert!(keypair.address().starts_with(&prefix)); + assert!(keypair.address().as_bytes().starts_with(&prefix)); } } diff --git a/crates/accounts/ethkey/src/random.rs b/crates/accounts/ethkey/src/random.rs deleted file mode 100644 index 3efc4df97..000000000 --- a/crates/accounts/ethkey/src/random.rs +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright 2015-2020 Parity Technologies (UK) Ltd. -// This file is part of OpenEthereum. - -// OpenEthereum 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. - -// OpenEthereum 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 OpenEthereum. If not, see . - -use super::{Generator, KeyPair, SECP256K1}; -use rand::os::OsRng; - -/// Randomly generates new keypair, instantiating the RNG each time. -pub struct Random; - -impl Generator for Random { - type Error = ::std::io::Error; - - fn generate(&mut self) -> Result { - let mut rng = OsRng::new()?; - rng.generate().or_else(|void| match void {}) - } -} - -impl Generator for OsRng { - type Error = ::Void; - - fn generate(&mut self) -> Result { - let (sec, publ) = SECP256K1 - .generate_keypair(self) - .expect("context always created with full capabilities; qed"); - - Ok(KeyPair::from_keypair(sec, publ)) - } -} diff --git a/crates/accounts/ethkey/src/secret.rs b/crates/accounts/ethkey/src/secret.rs deleted file mode 100644 index ab78e494d..000000000 --- a/crates/accounts/ethkey/src/secret.rs +++ /dev/null @@ -1,322 +0,0 @@ -// Copyright 2015-2020 Parity Technologies (UK) Ltd. -// This file is part of OpenEthereum. - -// OpenEthereum 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. - -// OpenEthereum 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 OpenEthereum. If not, see . - -use ethereum_types::H256; -use memzero::Memzero; -use rustc_hex::ToHex; -use secp256k1::{constants::SECRET_KEY_SIZE as SECP256K1_SECRET_KEY_SIZE, key}; -use std::{fmt, ops::Deref, str::FromStr}; -use Error; -use SECP256K1; - -#[derive(Clone, PartialEq, Eq)] -pub struct Secret { - inner: Memzero, -} - -impl ToHex for Secret { - fn to_hex(&self) -> String { - format!("{:x}", *self.inner) - } -} - -impl fmt::LowerHex for Secret { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - self.inner.fmt(fmt) - } -} - -impl fmt::Debug for Secret { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - self.inner.fmt(fmt) - } -} - -impl fmt::Display for Secret { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - write!( - fmt, - "Secret: 0x{:x}{:x}..{:x}{:x}", - self.inner[0], self.inner[1], self.inner[30], self.inner[31] - ) - } -} - -impl Secret { - /// Creates a `Secret` from the given slice, returning `None` if the slice length != 32. - pub fn from_slice(key: &[u8]) -> Option { - if key.len() != 32 { - return None; - } - let mut h = H256::default(); - h.copy_from_slice(&key[0..32]); - Some(Secret { - inner: Memzero::from(h), - }) - } - - /// Creates zero key, which is invalid for crypto operations, but valid for math operation. - pub fn zero() -> Self { - Secret { - inner: Memzero::from(H256::default()), - } - } - - /// Imports and validates the key. - pub fn from_unsafe_slice(key: &[u8]) -> Result { - let secret = key::SecretKey::from_slice(&super::SECP256K1, key)?; - Ok(secret.into()) - } - - /// Checks validity of this key. - pub fn check_validity(&self) -> Result<(), Error> { - self.to_secp256k1_secret().map(|_| ()) - } - - /// Inplace add one secret key to another (scalar + scalar) - pub fn add(&mut self, other: &Secret) -> Result<(), Error> { - match (self.is_zero(), other.is_zero()) { - (true, true) | (false, true) => Ok(()), - (true, false) => { - *self = other.clone(); - Ok(()) - } - (false, false) => { - let mut key_secret = self.to_secp256k1_secret()?; - let other_secret = other.to_secp256k1_secret()?; - key_secret.add_assign(&SECP256K1, &other_secret)?; - - *self = key_secret.into(); - Ok(()) - } - } - } - - /// Inplace subtract one secret key from another (scalar - scalar) - pub fn sub(&mut self, other: &Secret) -> Result<(), Error> { - match (self.is_zero(), other.is_zero()) { - (true, true) | (false, true) => Ok(()), - (true, false) => { - *self = other.clone(); - self.neg() - } - (false, false) => { - let mut key_secret = self.to_secp256k1_secret()?; - let mut other_secret = other.to_secp256k1_secret()?; - other_secret.mul_assign(&SECP256K1, &key::MINUS_ONE_KEY)?; - key_secret.add_assign(&SECP256K1, &other_secret)?; - - *self = key_secret.into(); - Ok(()) - } - } - } - - /// Inplace decrease secret key (scalar - 1) - pub fn dec(&mut self) -> Result<(), Error> { - match self.is_zero() { - true => { - *self = key::MINUS_ONE_KEY.into(); - Ok(()) - } - false => { - let mut key_secret = self.to_secp256k1_secret()?; - key_secret.add_assign(&SECP256K1, &key::MINUS_ONE_KEY)?; - - *self = key_secret.into(); - Ok(()) - } - } - } - - /// Inplace multiply one secret key to another (scalar * scalar) - pub fn mul(&mut self, other: &Secret) -> Result<(), Error> { - match (self.is_zero(), other.is_zero()) { - (true, true) | (true, false) => Ok(()), - (false, true) => { - *self = Self::zero(); - Ok(()) - } - (false, false) => { - let mut key_secret = self.to_secp256k1_secret()?; - let other_secret = other.to_secp256k1_secret()?; - key_secret.mul_assign(&SECP256K1, &other_secret)?; - - *self = key_secret.into(); - Ok(()) - } - } - } - - /// Inplace negate secret key (-scalar) - pub fn neg(&mut self) -> Result<(), Error> { - match self.is_zero() { - true => Ok(()), - false => { - let mut key_secret = self.to_secp256k1_secret()?; - key_secret.mul_assign(&SECP256K1, &key::MINUS_ONE_KEY)?; - - *self = key_secret.into(); - Ok(()) - } - } - } - - /// Inplace inverse secret key (1 / scalar) - pub fn inv(&mut self) -> Result<(), Error> { - let mut key_secret = self.to_secp256k1_secret()?; - key_secret.inv_assign(&SECP256K1)?; - - *self = key_secret.into(); - Ok(()) - } - - /// Compute power of secret key inplace (secret ^ pow). - /// This function is not intended to be used with large powers. - pub fn pow(&mut self, pow: usize) -> Result<(), Error> { - if self.is_zero() { - return Ok(()); - } - - match pow { - 0 => *self = key::ONE_KEY.into(), - 1 => (), - _ => { - let c = self.clone(); - for _ in 1..pow { - self.mul(&c)?; - } - } - } - - Ok(()) - } - - /// Create `secp256k1::key::SecretKey` based on this secret - pub fn to_secp256k1_secret(&self) -> Result { - Ok(key::SecretKey::from_slice(&SECP256K1, &self[..])?) - } -} - -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 { - fn from(k: [u8; 32]) -> Self { - Secret { - inner: Memzero::from(H256(k)), - } - } -} - -impl From for Secret { - fn from(s: H256) -> Self { - s.0.into() - } -} - -impl From<&'static str> for Secret { - fn from(s: &'static str) -> Self { - s.parse().expect(&format!( - "invalid string literal for {}: '{}'", - stringify!(Self), - s - )) - } -} - -impl From for Secret { - fn from(key: key::SecretKey) -> Self { - let mut a = [0; SECP256K1_SECRET_KEY_SIZE]; - a.copy_from_slice(&key[0..SECP256K1_SECRET_KEY_SIZE]); - a.into() - } -} - -impl Deref for Secret { - type Target = H256; - - fn deref(&self) -> &Self::Target { - &self.inner - } -} - -#[cfg(test)] -mod tests { - use super::{ - super::{Generator, Random}, - Secret, - }; - use std::str::FromStr; - - #[test] - fn multiplicating_secret_inversion_with_secret_gives_one() { - let secret = Random.generate().unwrap().secret().clone(); - let mut inversion = secret.clone(); - inversion.inv().unwrap(); - inversion.mul(&secret).unwrap(); - assert_eq!( - inversion, - Secret::from_str("0000000000000000000000000000000000000000000000000000000000000001") - .unwrap() - ); - } - - #[test] - fn secret_inversion_is_reversible_with_inversion() { - let secret = Random.generate().unwrap().secret().clone(); - let mut inversion = secret.clone(); - inversion.inv().unwrap(); - inversion.inv().unwrap(); - assert_eq!(inversion, secret); - } - - #[test] - fn secret_pow() { - let secret = Random.generate().unwrap().secret().clone(); - - let mut pow0 = secret.clone(); - pow0.pow(0).unwrap(); - assert_eq!( - pow0, - Secret::from_str("0000000000000000000000000000000000000000000000000000000000000001") - .unwrap() - ); - - let mut pow1 = secret.clone(); - pow1.pow(1).unwrap(); - assert_eq!(pow1, secret); - - let mut pow2 = secret.clone(); - pow2.pow(2).unwrap(); - let mut pow2_expected = secret.clone(); - pow2_expected.mul(&secret).unwrap(); - assert_eq!(pow2, pow2_expected); - - let mut pow3 = secret.clone(); - pow3.pow(3).unwrap(); - let mut pow3_expected = secret.clone(); - pow3_expected.mul(&secret).unwrap(); - pow3_expected.mul(&secret).unwrap(); - assert_eq!(pow3, pow3_expected); - } -} diff --git a/crates/accounts/ethkey/src/signature.rs b/crates/accounts/ethkey/src/signature.rs deleted file mode 100644 index fdb7b4c10..000000000 --- a/crates/accounts/ethkey/src/signature.rs +++ /dev/null @@ -1,325 +0,0 @@ -// Copyright 2015-2020 Parity Technologies (UK) Ltd. -// This file is part of OpenEthereum. - -// OpenEthereum 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. - -// OpenEthereum 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 OpenEthereum. If not, see . - -use ethereum_types::{H256, H520}; -use public_to_address; -use rustc_hex::{FromHex, ToHex}; -use secp256k1::{ - key::{PublicKey, SecretKey}, - Error as SecpError, Message as SecpMessage, RecoverableSignature, RecoveryId, -}; -use std::{ - cmp::PartialEq, - fmt, - hash::{Hash, Hasher}, - ops::{Deref, DerefMut}, - str::FromStr, -}; -use Address; -use Error; -use Message; -use Public; -use Secret; -use SECP256K1; - -/// Signature encoded as RSV components -#[repr(C)] -pub struct Signature([u8; 65]); - -impl Signature { - /// Get a slice into the 'r' portion of the data. - pub fn r(&self) -> &[u8] { - &self.0[0..32] - } - - /// Get a slice into the 's' portion of the data. - pub fn s(&self) -> &[u8] { - &self.0[32..64] - } - - /// Get the recovery byte. - pub fn v(&self) -> u8 { - self.0[64] - } - - /// Encode the signature into RSV array (V altered to be in "Electrum" notation). - pub fn into_electrum(mut self) -> [u8; 65] { - self.0[64] += 27; - self.0 - } - - /// Parse bytes as a signature encoded as RSV (V in "Electrum" notation). - /// May return empty (invalid) signature if given data has invalid length. - pub fn from_electrum(data: &[u8]) -> Self { - if data.len() != 65 || data[64] < 27 { - // fallback to empty (invalid) signature - return Signature::default(); - } - - let mut sig = [0u8; 65]; - sig.copy_from_slice(data); - sig[64] -= 27; - Signature(sig) - } - - /// Create a signature object from the sig. - pub fn from_rsv(r: &H256, s: &H256, v: u8) -> Self { - let mut sig = [0u8; 65]; - sig[0..32].copy_from_slice(&r); - sig[32..64].copy_from_slice(&s); - sig[64] = v; - Signature(sig) - } - - /// Check if this is a "low" signature. - pub fn is_low_s(&self) -> bool { - H256::from_slice(self.s()) - <= "7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0".into() - } - - /// Check if each component of the signature is in range. - pub fn is_valid(&self) -> bool { - self.v() <= 1 - && H256::from_slice(self.r()) - < "fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141".into() - && H256::from_slice(self.r()) >= 1.into() - && H256::from_slice(self.s()) - < "fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141".into() - && H256::from_slice(self.s()) >= 1.into() - } -} - -// manual implementation large arrays don't have trait impls by default. -// remove when integer generics exist -impl PartialEq for Signature { - fn eq(&self, other: &Self) -> bool { - &self.0[..] == &other.0[..] - } -} - -// manual implementation required in Rust 1.13+, see `std::cmp::AssertParamIsEq`. -impl Eq for Signature {} - -// also manual for the same reason, but the pretty printing might be useful. -impl fmt::Debug for Signature { - fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { - f.debug_struct("Signature") - .field("r", &self.0[0..32].to_hex()) - .field("s", &self.0[32..64].to_hex()) - .field("v", &self.0[64..65].to_hex()) - .finish() - } -} - -impl fmt::Display for Signature { - fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { - write!(f, "{}", self.to_hex()) - } -} - -impl FromStr for Signature { - type Err = Error; - - fn from_str(s: &str) -> Result { - match s.from_hex() { - Ok(ref hex) if hex.len() == 65 => { - let mut data = [0; 65]; - data.copy_from_slice(&hex[0..65]); - Ok(Signature(data)) - } - _ => Err(Error::InvalidSignature), - } - } -} - -impl Default for Signature { - fn default() -> Self { - Signature([0; 65]) - } -} - -impl Hash for Signature { - fn hash(&self, state: &mut H) { - H520::from(self.0).hash(state); - } -} - -impl Clone for Signature { - fn clone(&self) -> Self { - Signature(self.0) - } -} - -impl From<[u8; 65]> for Signature { - fn from(s: [u8; 65]) -> Self { - Signature(s) - } -} - -impl Into<[u8; 65]> for Signature { - fn into(self) -> [u8; 65] { - self.0 - } -} - -impl From for H520 { - fn from(s: Signature) -> Self { - H520::from(s.0) - } -} - -impl From for Signature { - fn from(bytes: H520) -> Self { - Signature(bytes.into()) - } -} - -impl Deref for Signature { - type Target = [u8; 65]; - - fn deref(&self) -> &Self::Target { - &self.0 - } -} - -impl DerefMut for Signature { - fn deref_mut(&mut self) -> &mut Self::Target { - &mut self.0 - } -} - -pub fn sign(secret: &Secret, message: &Message) -> Result { - let context = &SECP256K1; - let sec = SecretKey::from_slice(context, &secret)?; - let s = context.sign_recoverable(&SecpMessage::from_slice(&message[..])?, &sec)?; - let (rec_id, data) = s.serialize_compact(context); - let mut data_arr = [0; 65]; - - // no need to check if s is low, it always is - data_arr[0..64].copy_from_slice(&data[0..64]); - data_arr[64] = rec_id.to_i32() as u8; - Ok(Signature(data_arr)) -} - -pub fn verify_public( - public: &Public, - signature: &Signature, - message: &Message, -) -> Result { - let context = &SECP256K1; - let rsig = RecoverableSignature::from_compact( - context, - &signature[0..64], - RecoveryId::from_i32(signature[64] as i32)?, - )?; - let sig = rsig.to_standard(context); - - let pdata: [u8; 65] = { - let mut temp = [4u8; 65]; - temp[1..65].copy_from_slice(&**public); - temp - }; - - let publ = PublicKey::from_slice(context, &pdata)?; - match context.verify(&SecpMessage::from_slice(&message[..])?, &sig, &publ) { - Ok(_) => Ok(true), - Err(SecpError::IncorrectSignature) => Ok(false), - Err(x) => Err(Error::from(x)), - } -} - -pub fn verify_address( - address: &Address, - signature: &Signature, - message: &Message, -) -> Result { - let public = recover(signature, message)?; - let recovered_address = public_to_address(&public); - Ok(address == &recovered_address) -} - -pub fn recover(signature: &Signature, message: &Message) -> Result { - let context = &SECP256K1; - let rsig = RecoverableSignature::from_compact( - context, - &signature[0..64], - RecoveryId::from_i32(signature[64] as i32)?, - )?; - let pubkey = context.recover(&SecpMessage::from_slice(&message[..])?, &rsig)?; - let serialized = pubkey.serialize_vec(context, false); - - let mut public = Public::default(); - public.copy_from_slice(&serialized[1..65]); - Ok(public) -} - -#[cfg(test)] -mod tests { - use super::{recover, sign, verify_address, verify_public, Signature}; - use std::str::FromStr; - use Generator; - use Message; - use Random; - - #[test] - fn vrs_conversion() { - // given - let keypair = Random.generate().unwrap(); - let message = Message::default(); - let signature = sign(keypair.secret(), &message).unwrap(); - - // when - let vrs = signature.clone().into_electrum(); - let from_vrs = Signature::from_electrum(&vrs); - - // then - assert_eq!(signature, from_vrs); - } - - #[test] - fn signature_to_and_from_str() { - let keypair = Random.generate().unwrap(); - let message = Message::default(); - let signature = sign(keypair.secret(), &message).unwrap(); - let string = format!("{}", signature); - let deserialized = Signature::from_str(&string).unwrap(); - assert_eq!(signature, deserialized); - } - - #[test] - fn sign_and_recover_public() { - let keypair = Random.generate().unwrap(); - let message = Message::default(); - let signature = sign(keypair.secret(), &message).unwrap(); - assert_eq!(keypair.public(), &recover(&signature, &message).unwrap()); - } - - #[test] - fn sign_and_verify_public() { - let keypair = Random.generate().unwrap(); - let message = Message::default(); - let signature = sign(keypair.secret(), &message).unwrap(); - assert!(verify_public(keypair.public(), &signature, &message).unwrap()); - } - - #[test] - fn sign_and_verify_address() { - let keypair = Random.generate().unwrap(); - let message = Message::default(); - let signature = sign(keypair.secret(), &message).unwrap(); - assert!(verify_address(&keypair.address(), &signature, &message).unwrap()); - } -} diff --git a/crates/accounts/ethstore/Cargo.toml b/crates/accounts/ethstore/Cargo.toml index cdcae98e4..3f2f22f1f 100644 --- a/crates/accounts/ethstore/Cargo.toml +++ b/crates/accounts/ethstore/Cargo.toml @@ -7,7 +7,7 @@ authors = ["Parity Technologies "] [dependencies] log = "0.4" libc = "0.2" -rand = "0.4" +rand = "0.7.3" ethkey = { path = "../ethkey" } serde = "1.0" serde_json = "1.0" @@ -16,8 +16,8 @@ rustc-hex = "1.0" time = "0.1.34" itertools = "0.5" parking_lot = "0.7" -parity-crypto = "0.3.0" -ethereum-types = "0.4" +parity-crypto = { version = "0.6.2", features = [ "publickey"] } +ethereum-types = "0.9.2" smallvec = "0.6" parity-wordlist = "1.3" tempdir = "0.3" diff --git a/crates/accounts/ethstore/src/account/crypto.rs b/crates/accounts/ethstore/src/account/crypto.rs index 5b30dbbba..ea5149c8f 100644 --- a/crates/accounts/ethstore/src/account/crypto.rs +++ b/crates/accounts/ethstore/src/account/crypto.rs @@ -15,8 +15,8 @@ // along with OpenEthereum. If not, see . use account::{Aes128Ctr, Cipher, Kdf, Pbkdf2, Prf}; -use crypto::{self, Keccak256}; -use ethkey::{Password, Secret}; +use crypto::{self, publickey::Secret, Keccak256}; +use ethkey::Password; use json; use random::Random; use smallvec::SmallVec; @@ -79,7 +79,7 @@ impl Crypto { password: &Password, iterations: NonZeroU32, ) -> Result { - Crypto::with_plain(&*secret, password, iterations) + Crypto::with_plain(secret.as_bytes(), password, iterations) } /// Encrypt custom plain data @@ -94,7 +94,7 @@ impl Crypto { // two parts of derived key // DK = [ DK[0..15] DK[16..31] ] = [derived_left_bits, derived_right_bits] let (derived_left_bits, derived_right_bits) = - crypto::derive_key_iterations(password.as_bytes(), &salt, iterations); + crypto::derive_key_iterations(password.as_bytes(), &salt, iterations.get()); // preallocated (on-stack in case of `Secret`) buffer to hold cipher // length = length(plain) as we are using CTR-approach @@ -127,7 +127,7 @@ impl Crypto { } let secret = self.do_decrypt(password, 32)?; - Ok(Secret::from_unsafe_slice(&secret)?) + Ok(Secret::import_key(&secret)?) } /// Try to decrypt and return result as is @@ -139,7 +139,7 @@ impl Crypto { fn do_decrypt(&self, password: &Password, expected_len: usize) -> Result, Error> { let (derived_left_bits, derived_right_bits) = match self.kdf { Kdf::Pbkdf2(ref params) => { - crypto::derive_key_iterations(password.as_bytes(), ¶ms.salt, params.c) + crypto::derive_key_iterations(password.as_bytes(), ¶ms.salt, params.c.get()) } Kdf::Scrypt(ref params) => crypto::scrypt::derive_key( password.as_bytes(), @@ -179,7 +179,7 @@ impl Crypto { #[cfg(test)] mod tests { use super::{Crypto, Error, NonZeroU32}; - use ethkey::{Generator, Random}; + use crypto::publickey::{Generator, Random}; lazy_static! { static ref ITERATIONS: NonZeroU32 = NonZeroU32::new(10240).expect("10240 > 0; qed"); @@ -187,7 +187,7 @@ mod tests { #[test] fn crypto_with_secret_create() { - let keypair = Random.generate().unwrap(); + let keypair = Random.generate(); let passwd = "this is sparta".into(); let crypto = Crypto::with_secret(keypair.secret(), &passwd, *ITERATIONS).unwrap(); let secret = crypto.secret(&passwd).unwrap(); @@ -196,7 +196,7 @@ mod tests { #[test] fn crypto_with_secret_invalid_password() { - let keypair = Random.generate().unwrap(); + let keypair = Random.generate(); let crypto = Crypto::with_secret(keypair.secret(), &"this is sparta".into(), *ITERATIONS).unwrap(); assert_matches!( diff --git a/crates/accounts/ethstore/src/account/safe_account.rs b/crates/accounts/ethstore/src/account/safe_account.rs index a6f3d007d..89b4d17a5 100644 --- a/crates/accounts/ethstore/src/account/safe_account.rs +++ b/crates/accounts/ethstore/src/account/safe_account.rs @@ -16,10 +16,11 @@ use super::crypto::Crypto; use account::Version; -use crypto; -use ethkey::{ - self, crypto::ecdh::agree, sign, Address, KeyPair, Message, Password, Public, Secret, Signature, +use crypto::{ + self, + publickey::{ecdh::agree, sign, Address, KeyPair, Message, Public, Secret, Signature}, }; +use ethkey::Password; use json; use std::num::NonZeroU32; use Error; @@ -193,7 +194,7 @@ impl SafeAccount { message: &[u8], ) -> Result, Error> { let secret = self.crypto.secret(password)?; - ethkey::crypto::ecies::decrypt(&secret, shared_mac, message).map_err(From::from) + crypto::publickey::ecies::decrypt(&secret, shared_mac, message).map_err(From::from) } /// Agree on shared key. @@ -237,7 +238,7 @@ impl SafeAccount { #[cfg(test)] mod tests { use super::{NonZeroU32, SafeAccount}; - use ethkey::{verify_public, Generator, Message, Random}; + use crypto::publickey::{verify_public, Generator, Random}; lazy_static! { static ref ITERATIONS: NonZeroU32 = NonZeroU32::new(10240).expect("10240 > 0; qed"); @@ -245,9 +246,9 @@ mod tests { #[test] fn sign_and_verify_public() { - let keypair = Random.generate().unwrap(); + let keypair = Random.generate(); let password = "hello world".into(); - let message = Message::default(); + let message = [1u8; 32].into(); let account = SafeAccount::create( &keypair, [0u8; 16], @@ -262,10 +263,10 @@ mod tests { #[test] fn change_password() { - let keypair = Random.generate().unwrap(); + let keypair = Random.generate(); let first_password = "hello world".into(); let sec_password = "this is sparta".into(); - let message = Message::default(); + let message = [1u8; 32].into(); let account = SafeAccount::create( &keypair, [0u8; 16], diff --git a/crates/accounts/ethstore/src/accounts_dir/disk.rs b/crates/accounts/ethstore/src/accounts_dir/disk.rs index c981f6949..13a8b7c28 100644 --- a/crates/accounts/ethstore/src/accounts_dir/disk.rs +++ b/crates/accounts/ethstore/src/accounts_dir/disk.rs @@ -420,7 +420,7 @@ mod test { use self::tempdir::TempDir; use super::{KeyDirectory, RootDiskDirectory, VaultKey}; use account::SafeAccount; - use ethkey::{Generator, Random}; + use crypto::publickey::{Generator, Random}; use std::{env, fs, num::NonZeroU32}; lazy_static! { @@ -432,7 +432,7 @@ mod test { // given let mut dir = env::temp_dir(); dir.push("ethstore_should_create_new_account"); - let keypair = Random.generate().unwrap(); + let keypair = Random.generate(); let password = "hello world".into(); let directory = RootDiskDirectory::create(dir.clone()).unwrap(); @@ -463,7 +463,7 @@ mod test { // given let mut dir = env::temp_dir(); dir.push("ethstore_should_handle_duplicate_filenames"); - let keypair = Random.generate().unwrap(); + let keypair = Random.generate(); let password = "hello world".into(); let directory = RootDiskDirectory::create(dir.clone()).unwrap(); @@ -582,7 +582,7 @@ mod test { .expect("Files hash should be calculated ok"); assert_eq!(hash, 15130871412783076140); - let keypair = Random.generate().unwrap(); + let keypair = Random.generate(); let password = "test pass".into(); let account = SafeAccount::create( &keypair, diff --git a/crates/accounts/ethstore/src/accounts_dir/memory.rs b/crates/accounts/ethstore/src/accounts_dir/memory.rs index 80ecb6676..73f48ef7c 100644 --- a/crates/accounts/ethstore/src/accounts_dir/memory.rs +++ b/crates/accounts/ethstore/src/accounts_dir/memory.rs @@ -14,7 +14,7 @@ // You should have received a copy of the GNU General Public License // along with OpenEthereum. If not, see . -use ethkey::Address; +use crypto::publickey::Address; use itertools; use parking_lot::RwLock; use std::collections::HashMap; @@ -70,7 +70,7 @@ impl KeyDirectory for MemoryDirectory { let mut val = 0u64; let accounts = self.accounts.read(); for acc in accounts.keys() { - val = val ^ acc.low_u64() + val = val ^ acc.to_low_u64_be() } Ok(val) } diff --git a/crates/accounts/ethstore/src/error.rs b/crates/accounts/ethstore/src/error.rs index 72372db87..646f47339 100644 --- a/crates/accounts/ethstore/src/error.rs +++ b/crates/accounts/ethstore/src/error.rs @@ -14,8 +14,7 @@ // You should have received a copy of the GNU General Public License // along with OpenEthereum. If not, see . -use crypto::{self, Error as EthCryptoError}; -use ethkey::{self, DerivationError, Error as EthKeyError}; +use crypto::publickey::DerivationError; use std::{fmt, io::Error as IoError}; /// Account-related errors. @@ -45,12 +44,10 @@ pub enum Error { VaultNotFound, /// Account creation failed. CreationFailed, - /// `EthKey` error - EthKey(EthKeyError), - /// `ethkey::crypto::Error` - EthKeyCrypto(ethkey::crypto::Error), + /// `crypto::publickey::Error` + EthCrypto(crypto::Error), /// `EthCrypto` error - EthCrypto(EthCryptoError), + EthCryptoPublicKey(crypto::publickey::Error), /// Derivation error Derivation(DerivationError), /// Custom error @@ -72,9 +69,8 @@ impl fmt::Display for Error { Error::InvalidVaultName => "Invalid vault name".into(), Error::VaultNotFound => "Vault not found".into(), Error::CreationFailed => "Account creation failed".into(), - Error::EthKey(ref err) => err.to_string(), - Error::EthKeyCrypto(ref err) => err.to_string(), Error::EthCrypto(ref err) => err.to_string(), + Error::EthCryptoPublicKey(ref err) => err.to_string(), Error::Derivation(ref err) => format!("Derivation error: {:?}", err), Error::Custom(ref s) => s.clone(), }; @@ -89,20 +85,14 @@ impl From for Error { } } -impl From for Error { - fn from(err: EthKeyError) -> Self { - Error::EthKey(err) +impl From for Error { + fn from(err: crypto::publickey::Error) -> Self { + Error::EthCryptoPublicKey(err) } } -impl From for Error { - fn from(err: ethkey::crypto::Error) -> Self { - Error::EthKeyCrypto(err) - } -} - -impl From for Error { - fn from(err: EthCryptoError) -> Self { +impl From for Error { + fn from(err: crypto::Error) -> Self { Error::EthCrypto(err) } } diff --git a/crates/accounts/ethstore/src/ethkey.rs b/crates/accounts/ethstore/src/ethkey.rs index dc08af419..aed0695bb 100644 --- a/crates/accounts/ethstore/src/ethkey.rs +++ b/crates/accounts/ethstore/src/ethkey.rs @@ -16,6 +16,7 @@ //! ethkey reexport to make documentation look pretty. pub use _ethkey::*; +pub use crypto::publickey::Address; use json; impl Into for Address { diff --git a/crates/accounts/ethstore/src/ethstore.rs b/crates/accounts/ethstore/src/ethstore.rs index 3de0d1380..bf674e458 100644 --- a/crates/accounts/ethstore/src/ethstore.rs +++ b/crates/accounts/ethstore/src/ethstore.rs @@ -24,9 +24,10 @@ use std::{ use account::SafeAccount; use accounts_dir::{KeyDirectory, SetKeyError, VaultKey, VaultKeyDirectory}; -use ethkey::{ - self, Address, ExtendedKeyPair, KeyPair, Message, Password, Public, Secret, Signature, +use crypto::publickey::{ + self, Address, ExtendedKeyPair, KeyPair, Message, Public, Secret, Signature, }; +use ethkey::Password; use json::{self, OpaqueKeyFile, Uuid}; use presale::PresaleWallet; use random::Random; @@ -554,17 +555,17 @@ impl EthMultiStore { Derivation::Hierarchical(path) => { for path_item in path { extended = extended.derive(if path_item.soft { - ethkey::Derivation::Soft(path_item.index) + publickey::Derivation::Soft(path_item.index) } else { - ethkey::Derivation::Hard(path_item.index) + publickey::Derivation::Hard(path_item.index) })?; } } Derivation::SoftHash(h256) => { - extended = extended.derive(ethkey::Derivation::Soft(h256))?; + extended = extended.derive(publickey::Derivation::Soft(h256))?; } Derivation::HardHash(h256) => { - extended = extended.derive(ethkey::Derivation::Hard(h256))?; + extended = extended.derive(publickey::Derivation::Hard(h256))?; } } Ok(extended) @@ -615,7 +616,7 @@ impl SimpleSecretStore for EthMultiStore { let accounts = self.get_matching(&account_ref, password)?; for account in accounts { let extended = self.generate(account.crypto.secret(password)?, derivation)?; - return Ok(ethkey::public_to_address(extended.public().public())); + return Ok(publickey::public_to_address(extended.public().public())); } Err(Error::InvalidPassword) } @@ -631,7 +632,7 @@ impl SimpleSecretStore for EthMultiStore { for account in accounts { let extended = self.generate(account.crypto.secret(password)?, derivation)?; let secret = extended.secret().as_raw(); - return Ok(ethkey::sign(&secret, message)?); + return Ok(publickey::sign(&secret, message)?); } Err(Error::InvalidPassword) } @@ -898,14 +899,14 @@ mod tests { use self::tempdir::TempDir; use super::{EthMultiStore, EthStore}; use accounts_dir::{KeyDirectory, MemoryDirectory, RootDiskDirectory}; + use crypto::publickey::{Generator, KeyPair, Random}; use ethereum_types::H256; - use ethkey::{Generator, KeyPair, Random}; use secret_store::{ Derivation, SecretStore, SecretVaultRef, SimpleSecretStore, StoreAccountRef, }; fn keypair() -> KeyPair { - Random.generate().unwrap() + Random.generate() } fn store() -> EthStore { @@ -1051,6 +1052,7 @@ mod tests { let passwd2 = "xzy".into(); let multi_store = multi_store(); let keypair = keypair(); + let message = [1u8; 32].into(); let address = store .insert_account(SecretVaultRef::Root, keypair.secret().clone(), &passwd1) .unwrap(); @@ -1073,9 +1075,7 @@ mod tests { "First password should work for store." ); assert!( - multi_store - .sign(&address, &passwd2, &Default::default()) - .is_ok(), + multi_store.sign(&address, &passwd2, &message).is_ok(), "Second password should work for second store." ); assert_eq!(multi_store.accounts().unwrap().len(), 1); @@ -1462,7 +1462,7 @@ mod tests { SecretVaultRef::Root, &address, &"test".into(), - Derivation::HardHash(H256::from(0)), + Derivation::HardHash(H256::zero()), ) .unwrap(); @@ -1470,11 +1470,10 @@ mod tests { let accounts = store.accounts().unwrap(); assert_eq!(accounts.len(), 2); + let message = [1u8; 32].into(); // and we can sign with the derived contract assert!( - store - .sign(&derived, &"test".into(), &Default::default()) - .is_ok(), + store.sign(&derived, &"test".into(), &message).is_ok(), "Second password should work for second store." ); } diff --git a/crates/accounts/ethstore/src/import.rs b/crates/accounts/ethstore/src/import.rs index 949d37db7..20cbcd787 100644 --- a/crates/accounts/ethstore/src/import.rs +++ b/crates/accounts/ethstore/src/import.rs @@ -17,7 +17,7 @@ use std::{collections::HashSet, fs, path::Path}; use accounts_dir::{DiskKeyFileManager, KeyDirectory, KeyFileManager}; -use ethkey::Address; +use crypto::publickey::Address; use Error; /// Import an account from a file. diff --git a/crates/accounts/ethstore/src/lib.rs b/crates/accounts/ethstore/src/lib.rs index 5830ab998..5abfdf2ae 100644 --- a/crates/accounts/ethstore/src/lib.rs +++ b/crates/accounts/ethstore/src/lib.rs @@ -74,4 +74,4 @@ pub use self::{ }; /// An opaque wrapper for secret. -pub struct OpaqueSecret(::ethkey::Secret); +pub struct OpaqueSecret(crypto::publickey::Secret); diff --git a/crates/accounts/ethstore/src/presale.rs b/crates/accounts/ethstore/src/presale.rs index 0bf5905a9..45cc0de5d 100644 --- a/crates/accounts/ethstore/src/presale.rs +++ b/crates/accounts/ethstore/src/presale.rs @@ -14,8 +14,12 @@ // You should have received a copy of the GNU General Public License // along with OpenEthereum. If not, see . -use crypto::{self, pbkdf2, Keccak256}; -use ethkey::{Address, KeyPair, Password, Secret}; +use crypto::{ + self, pbkdf2, + publickey::{Address, KeyPair, Secret}, + Keccak256, +}; +use ethkey::Password; use json; use std::{fs, num::NonZeroU32, path::Path}; use Error; @@ -61,7 +65,7 @@ impl PresaleWallet { let salt = pbkdf2::Salt(password.as_bytes()); let sec = pbkdf2::Secret(password.as_bytes()); let iter = NonZeroU32::new(2000).expect("2000 > 0; qed"); - pbkdf2::sha256(iter, salt, sec, &mut derived_key); + pbkdf2::sha256(iter.get(), salt, sec, &mut derived_key); let mut key = vec![0; self.ciphertext.len()]; let len = @@ -69,7 +73,7 @@ impl PresaleWallet { .map_err(|_| Error::InvalidPassword)?; let unpadded = &key[..len]; - let secret = Secret::from_unsafe_slice(&unpadded.keccak256())?; + let secret = Secret::import_key(&unpadded.keccak256())?; if let Ok(kp) = KeyPair::from_secret(secret) { if kp.address() == self.address { return Ok(kp); diff --git a/crates/accounts/ethstore/src/random.rs b/crates/accounts/ethstore/src/random.rs index c50abf85f..405873c94 100644 --- a/crates/accounts/ethstore/src/random.rs +++ b/crates/accounts/ethstore/src/random.rs @@ -14,7 +14,7 @@ // You should have received a copy of the GNU General Public License // along with OpenEthereum. If not, see . -use rand::{OsRng, Rng}; +use rand::{distributions::Alphanumeric, rngs::OsRng, Rng, RngCore}; pub trait Random { fn random() -> Self @@ -25,7 +25,7 @@ pub trait Random { impl Random for [u8; 16] { fn random() -> Self { let mut result = [0u8; 16]; - let mut rng = OsRng::new().unwrap(); + let mut rng = OsRng; rng.fill_bytes(&mut result); result } @@ -34,7 +34,7 @@ impl Random for [u8; 16] { impl Random for [u8; 32] { fn random() -> Self { let mut result = [0u8; 32]; - let mut rng = OsRng::new().unwrap(); + let mut rng = OsRng; rng.fill_bytes(&mut result); result } @@ -42,6 +42,6 @@ impl Random for [u8; 32] { /// Generate a random string of given length. pub fn random_string(length: usize) -> String { - let mut rng = OsRng::new().expect("Not able to operate without random source."); - rng.gen_ascii_chars().take(length).collect() + let rng = OsRng; + rng.sample_iter(&Alphanumeric).take(length).collect() } diff --git a/crates/accounts/ethstore/src/secret_store.rs b/crates/accounts/ethstore/src/secret_store.rs index b9c098c46..36c6f9ed5 100644 --- a/crates/accounts/ethstore/src/secret_store.rs +++ b/crates/accounts/ethstore/src/secret_store.rs @@ -14,8 +14,9 @@ // You should have received a copy of the GNU General Public License // along with OpenEthereum. If not, see . +use crypto::publickey::{Address, Message, Public, Secret, Signature}; use ethereum_types::H256; -use ethkey::{Address, Message, Password, Public, Secret, Signature}; +use ethkey::Password; use json::{OpaqueKeyFile, Uuid}; use std::{ cmp::Ordering, @@ -174,7 +175,7 @@ pub trait SecretStore: SimpleSecretStore { secret: &OpaqueSecret, message: &Message, ) -> Result { - Ok(::ethkey::sign(&secret.0, message)?) + Ok(crypto::publickey::sign(&secret.0, message)?) } /// Imports presale wallet diff --git a/crates/accounts/ethstore/tests/api.rs b/crates/accounts/ethstore/tests/api.rs index c37100c22..1eb2fa7f0 100644 --- a/crates/accounts/ethstore/tests/api.rs +++ b/crates/accounts/ethstore/tests/api.rs @@ -14,15 +14,19 @@ // You should have received a copy of the GNU General Public License // along with OpenEthereum. If not, see . +extern crate ethereum_types; extern crate ethstore; +extern crate parity_crypto as crypto; extern crate rand; mod util; +use std::str::FromStr; + +use crypto::publickey::{verify_address, Generator, KeyPair, Random, Secret}; +use ethereum_types::H160; use ethstore::{ - accounts_dir::RootDiskDirectory, - ethkey::{verify_address, Generator, KeyPair, Random, Secret}, - EthStore, SecretVaultRef, SimpleSecretStore, StoreAccountRef, + accounts_dir::RootDiskDirectory, EthStore, SecretVaultRef, SimpleSecretStore, StoreAccountRef, }; use util::TransientDir; @@ -40,7 +44,7 @@ fn secret_store_open_not_existing() { } fn random_secret() -> Secret { - Random.generate().unwrap().secret().clone() + Random.generate().secret().clone() } #[test] @@ -66,13 +70,10 @@ fn secret_store_sign() { .insert_account(SecretVaultRef::Root, random_secret(), &"".into()) .is_ok()); let accounts = store.accounts().unwrap(); + let message = [1u8; 32].into(); assert_eq!(accounts.len(), 1); - assert!(store - .sign(&accounts[0], &"".into(), &Default::default()) - .is_ok()); - assert!(store - .sign(&accounts[0], &"1".into(), &Default::default()) - .is_err()); + assert!(store.sign(&accounts[0], &"".into(), &message).is_ok()); + assert!(store.sign(&accounts[0], &"1".into(), &message).is_err()); } #[test] @@ -83,19 +84,14 @@ fn secret_store_change_password() { .insert_account(SecretVaultRef::Root, random_secret(), &"".into()) .is_ok()); let accounts = store.accounts().unwrap(); + let message = [1u8; 32].into(); assert_eq!(accounts.len(), 1); - assert!(store - .sign(&accounts[0], &"".into(), &Default::default()) - .is_ok()); + assert!(store.sign(&accounts[0], &"".into(), &message).is_ok()); assert!(store .change_password(&accounts[0], &"".into(), &"1".into()) .is_ok()); - assert!(store - .sign(&accounts[0], &"".into(), &Default::default()) - .is_err()); - assert!(store - .sign(&accounts[0], &"1".into(), &Default::default()) - .is_ok()); + assert!(store.sign(&accounts[0], &"".into(), &message).is_err()); + assert!(store.sign(&accounts[0], &"1".into(), &message).is_ok()); } #[test] @@ -140,9 +136,15 @@ fn secret_store_laod_geth_files() { assert_eq!( store.accounts().unwrap(), vec![ - StoreAccountRef::root("3f49624084b67849c7b4e805c5988c21a430f9d9".into()), - StoreAccountRef::root("5ba4dcf897e97c2bdf8315b9ef26c13c085988cf".into()), - StoreAccountRef::root("63121b431a52f8043c16fcf0d1df9cb7b5f66649".into()), + StoreAccountRef::root( + H160::from_str("3f49624084b67849c7b4e805c5988c21a430f9d9").unwrap() + ), + StoreAccountRef::root( + H160::from_str("5ba4dcf897e97c2bdf8315b9ef26c13c085988cf").unwrap() + ), + StoreAccountRef::root( + H160::from_str("63121b431a52f8043c16fcf0d1df9cb7b5f66649").unwrap() + ), ] ); } @@ -154,8 +156,12 @@ fn secret_store_load_pat_files() { assert_eq!( store.accounts().unwrap(), vec![ - StoreAccountRef::root("3f49624084b67849c7b4e805c5988c21a430f9d9".into()), - StoreAccountRef::root("5ba4dcf897e97c2bdf8315b9ef26c13c085988cf".into()), + StoreAccountRef::root( + H160::from_str("3f49624084b67849c7b4e805c5988c21a430f9d9").unwrap() + ), + StoreAccountRef::root( + H160::from_str("5ba4dcf897e97c2bdf8315b9ef26c13c085988cf").unwrap() + ), ] ); } @@ -182,12 +188,16 @@ fn test_decrypting_files_with_short_ciphertext() { assert_eq!( accounts, vec![ - StoreAccountRef::root("31e9d1e6d844bd3a536800ef8d8be6a9975db509".into()), - StoreAccountRef::root("d1e64e5480bfaf733ba7d48712decb8227797a4e".into()), + StoreAccountRef::root( + H160::from_str("31e9d1e6d844bd3a536800ef8d8be6a9975db509").unwrap() + ), + StoreAccountRef::root( + H160::from_str("d1e64e5480bfaf733ba7d48712decb8227797a4e").unwrap() + ), ] ); - let message = Default::default(); + let message = [1u8; 32].into(); let s1 = store.sign(&accounts[0], &"foo".into(), &message).unwrap(); let s2 = store.sign(&accounts[1], &"foo".into(), &message).unwrap(); diff --git a/crates/accounts/ethstore/tests/util/transient_dir.rs b/crates/accounts/ethstore/tests/util/transient_dir.rs index 88fb755c1..5f22e7efd 100644 --- a/crates/accounts/ethstore/tests/util/transient_dir.rs +++ b/crates/accounts/ethstore/tests/util/transient_dir.rs @@ -18,11 +18,11 @@ use ethstore::{ accounts_dir::{KeyDirectory, RootDiskDirectory}, Error, SafeAccount, }; -use rand::{OsRng, Rng}; +use rand::{rngs::OsRng, RngCore}; use std::{env, fs, path::PathBuf}; pub fn random_dir() -> PathBuf { - let mut rng = OsRng::new().unwrap(); + let mut rng = OsRng; let mut dir = env::temp_dir(); dir.push(format!("{:x}-{:x}", rng.next_u64(), rng.next_u64())); dir diff --git a/crates/accounts/src/account_data.rs b/crates/accounts/src/account_data.rs index 5bb41daf2..2c9c3bd32 100644 --- a/crates/accounts/src/account_data.rs +++ b/crates/accounts/src/account_data.rs @@ -18,7 +18,8 @@ use std::{collections::HashMap, time::Instant}; -use ethkey::{Address, Password}; +use crypto::publickey::Address; +use ethkey::Password; use serde_derive::{Deserialize, Serialize}; use serde_json; diff --git a/crates/accounts/src/lib.rs b/crates/accounts/src/lib.rs index d7003d56c..d68ba61f0 100644 --- a/crates/accounts/src/lib.rs +++ b/crates/accounts/src/lib.rs @@ -18,6 +18,8 @@ //! Account management. +extern crate parity_crypto as crypto; + mod account_data; mod error; mod stores; @@ -32,7 +34,8 @@ use std::{ time::{Duration, Instant}, }; -use ethkey::{Address, Generator, Message, Password, Public, Random, Secret}; +use crypto::publickey::{Address, Generator, Message, Public, Random, Secret}; +use ethkey::Password; use ethstore::{ accounts_dir::MemoryDirectory, random_string, EthMultiStore, EthStore, OpaqueSecret, SecretStore, SecretVaultRef, SimpleSecretStore, StoreAccountRef, @@ -40,7 +43,7 @@ use ethstore::{ use log::*; use parking_lot::RwLock; -pub use ethkey::Signature; +pub use crypto::publickey::Signature; pub use ethstore::{Derivation, Error, IndexDerivation, KeyFile}; pub use self::{account_data::AccountMeta, error::SignError}; @@ -134,9 +137,7 @@ impl AccountProvider { /// Creates new random account and returns address and public key pub fn new_account_and_public(&self, password: &Password) -> Result<(Address, Public), Error> { - let acc = Random - .generate() - .expect("secp context has generation capabilities; qed"); + let acc = Random.generate(); let public = acc.public().clone(); let secret = acc.secret().clone(); let account = self @@ -355,7 +356,8 @@ impl AccountProvider { } else { // verify password by signing dump message // result may be discarded - let _ = self.sstore.sign(&account, &password, &Default::default())?; + let dummy_msg = [1u8; 32].into(); + let _ = self.sstore.sign(&account, &password, &dummy_msg)?; } let data = AccountData { @@ -632,15 +634,16 @@ impl AccountProvider { #[cfg(test)] mod tests { use super::{AccountProvider, Unlock}; + use crypto::publickey::{Address, Generator, Random}; use ethereum_types::H256; - use ethkey::{Address, Generator, Random}; use ethstore::{Derivation, StoreAccountRef}; use std::time::{Duration, Instant}; #[test] fn unlock_account_temp() { - let kp = Random.generate().unwrap(); + let kp = Random.generate(); let ap = AccountProvider::transient_provider(); + let dummy_msg = [1u8; 32].into(); assert!(ap .insert_account(kp.secret().clone(), &"test".into()) .is_ok()); @@ -650,13 +653,13 @@ mod tests { assert!(ap .unlock_account_temporarily(kp.address(), "test".into()) .is_ok()); - assert!(ap.sign(kp.address(), None, Default::default()).is_ok()); - assert!(ap.sign(kp.address(), None, Default::default()).is_err()); + assert!(ap.sign(kp.address(), None, dummy_msg).is_ok()); + assert!(ap.sign(kp.address(), None, dummy_msg).is_err()); } #[test] fn derived_account_nosave() { - let kp = Random.generate().unwrap(); + let kp = Random.generate(); let ap = AccountProvider::transient_provider(); assert!(ap .insert_account(kp.secret().clone(), &"base".into()) @@ -669,7 +672,7 @@ mod tests { .derive_account( &kp.address(), None, - Derivation::SoftHash(H256::from(999)), + Derivation::SoftHash(H256::from_low_u64_be(999)), false, ) .expect("Derivation should not fail"); @@ -683,7 +686,7 @@ mod tests { #[test] fn derived_account_save() { - let kp = Random.generate().unwrap(); + let kp = Random.generate(); let ap = AccountProvider::transient_provider(); assert!(ap .insert_account(kp.secret().clone(), &"base".into()) @@ -696,7 +699,7 @@ mod tests { .derive_account( &kp.address(), None, - Derivation::SoftHash(H256::from(999)), + Derivation::SoftHash(H256::from_low_u64_be(999)), true, ) .expect("Derivation should not fail"); @@ -716,7 +719,7 @@ mod tests { #[test] fn derived_account_sign() { - let kp = Random.generate().unwrap(); + let kp = Random.generate(); let ap = AccountProvider::transient_provider(); assert!(ap .insert_account(kp.secret().clone(), &"base".into()) @@ -729,14 +732,14 @@ mod tests { .derive_account( &kp.address(), None, - Derivation::SoftHash(H256::from(1999)), + Derivation::SoftHash(H256::from_low_u64_be(1999)), true, ) .expect("Derivation should not fail"); ap.unlock_account_permanently(derived_addr, "base".into()) .expect("Should be ok because account is saved and password is valid"); - let msg = Default::default(); + let msg = [2u8; 32].into(); let signed_msg1 = ap .sign(derived_addr, None, msg) .expect("Signing with existing unlocked account should not fail"); @@ -744,7 +747,7 @@ mod tests { .sign_derived( &kp.address(), None, - Derivation::SoftHash(H256::from(1999)), + Derivation::SoftHash(H256::from_low_u64_be(1999)), msg, ) .expect("Derived signing with existing unlocked account should not fail"); @@ -754,8 +757,9 @@ mod tests { #[test] fn unlock_account_perm() { - let kp = Random.generate().unwrap(); + let kp = Random.generate(); let ap = AccountProvider::transient_provider(); + let dummy_msg = [1u8; 32].into(); assert!(ap .insert_account(kp.secret().clone(), &"test".into()) .is_ok()); @@ -765,19 +769,20 @@ mod tests { assert!(ap .unlock_account_permanently(kp.address(), "test".into()) .is_ok()); - assert!(ap.sign(kp.address(), None, Default::default()).is_ok()); - assert!(ap.sign(kp.address(), None, Default::default()).is_ok()); + assert!(ap.sign(kp.address(), None, dummy_msg).is_ok()); + assert!(ap.sign(kp.address(), None, dummy_msg).is_ok()); assert!(ap .unlock_account_temporarily(kp.address(), "test".into()) .is_ok()); - assert!(ap.sign(kp.address(), None, Default::default()).is_ok()); - assert!(ap.sign(kp.address(), None, Default::default()).is_ok()); + assert!(ap.sign(kp.address(), None, dummy_msg).is_ok()); + assert!(ap.sign(kp.address(), None, dummy_msg).is_ok()); } #[test] fn unlock_account_timer() { - let kp = Random.generate().unwrap(); + let kp = Random.generate(); let ap = AccountProvider::transient_provider(); + let dummy_msg = [1u8; 32].into(); assert!(ap .insert_account(kp.secret().clone(), &"test".into()) .is_ok()); @@ -787,35 +792,35 @@ mod tests { assert!(ap .unlock_account_timed(kp.address(), "test".into(), Duration::from_secs(60)) .is_ok()); - assert!(ap.sign(kp.address(), None, Default::default()).is_ok()); + assert!(ap.sign(kp.address(), None, dummy_msg).is_ok()); ap.unlocked .write() .get_mut(&StoreAccountRef::root(kp.address())) .unwrap() .unlock = Unlock::Timed(Instant::now()); - assert!(ap.sign(kp.address(), None, Default::default()).is_err()); + assert!(ap.sign(kp.address(), None, dummy_msg).is_err()); } #[test] fn should_sign_and_return_token() { // given - let kp = Random.generate().unwrap(); + let kp = Random.generate(); let ap = AccountProvider::transient_provider(); + let dummy_msg = [1u8; 32].into(); assert!(ap .insert_account(kp.secret().clone(), &"test".into()) .is_ok()); // when let (_signature, token) = ap - .sign_with_token(kp.address(), "test".into(), Default::default()) + .sign_with_token(kp.address(), "test".into(), dummy_msg) .unwrap(); // then - ap.sign_with_token(kp.address(), token.clone(), Default::default()) + ap.sign_with_token(kp.address(), token.clone(), dummy_msg) .expect("First usage of token should be correct."); assert!( - ap.sign_with_token(kp.address(), token, Default::default()) - .is_err(), + ap.sign_with_token(kp.address(), token, dummy_msg).is_err(), "Second usage of the same token should fail." ); } diff --git a/crates/accounts/src/stores.rs b/crates/accounts/src/stores.rs index 63a551be1..f6accb66d 100644 --- a/crates/accounts/src/stores.rs +++ b/crates/accounts/src/stores.rs @@ -22,7 +22,7 @@ use std::{ path::{Path, PathBuf}, }; -use ethkey::Address; +use crypto::publickey::Address; use log::{trace, warn}; use crate::AccountMeta; @@ -172,6 +172,7 @@ impl DiskMap { mod tests { use super::AddressBook; use crate::account_data::AccountMeta; + use ethereum_types::H160; use std::collections::HashMap; use tempdir::TempDir; @@ -179,8 +180,8 @@ mod tests { fn should_save_and_reload_address_book() { let tempdir = TempDir::new("").unwrap(); let mut b = AddressBook::new(tempdir.path()); - b.set_name(1.into(), "One".to_owned()); - b.set_meta(1.into(), "{1:1}".to_owned()); + b.set_name(H160::from_low_u64_be(1), "One".to_owned()); + b.set_meta(H160::from_low_u64_be(1), "{1:1}".to_owned()); let b = AddressBook::new(tempdir.path()); assert_eq!( b.get(), @@ -193,7 +194,7 @@ mod tests { } )] .into_iter() - .map(|(a, b)| (a.into(), b)) + .map(|(a, b)| (H160::from_low_u64_be(a), b)) .collect::>() ); } @@ -203,10 +204,10 @@ mod tests { let tempdir = TempDir::new("").unwrap(); let mut b = AddressBook::new(tempdir.path()); - b.set_name(1.into(), "One".to_owned()); - b.set_name(2.into(), "Two".to_owned()); - b.set_name(3.into(), "Three".to_owned()); - b.remove(2.into()); + b.set_name(H160::from_low_u64_be(1), "One".to_owned()); + b.set_name(H160::from_low_u64_be(2), "Two".to_owned()); + b.set_name(H160::from_low_u64_be(3), "Three".to_owned()); + b.remove(H160::from_low_u64_be(2)); let b = AddressBook::new(tempdir.path()); assert_eq!( @@ -230,7 +231,7 @@ mod tests { ), ] .into_iter() - .map(|(a, b)| (a.into(), b)) + .map(|(a, b)| (H160::from_low_u64_be(a), b)) .collect::>() ); } diff --git a/crates/concensus/ethash/Cargo.toml b/crates/concensus/ethash/Cargo.toml index 06ee93f88..9ae4ff7f5 100644 --- a/crates/concensus/ethash/Cargo.toml +++ b/crates/concensus/ethash/Cargo.toml @@ -7,8 +7,9 @@ authors = ["Parity Technologies "] [dependencies] crunchy = "0.1.0" either = "1.0.0" -ethereum-types = "0.4" -keccak-hash = "0.1" +ethereum-types = "0.9.2" +keccak-hash = "0.5.0" +tiny-keccak = "2.0.2" log = "0.4" memmap = "0.6" parking_lot = "0.7" diff --git a/crates/concensus/ethash/src/cache.rs b/crates/concensus/ethash/src/cache.rs index ab3407a07..38b2b2de6 100644 --- a/crates/concensus/ethash/src/cache.rs +++ b/crates/concensus/ethash/src/cache.rs @@ -21,7 +21,7 @@ use memmap::MmapMut; use parking_lot::Mutex; use seed_compute::SeedHashCompute; -use shared::{epoch, get_cache_size, to_hex, Node, ETHASH_CACHE_ROUNDS, NODE_BYTES, NODE_DWORDS}; +use shared::{epoch, get_cache_size, to_hex, Node, ETHASH_CACHE_ROUNDS, NODE_BYTES}; use std::{ borrow::Cow, @@ -318,27 +318,22 @@ impl AsRef<[Node]> for NodeCache { // out. It counts as a read and causes all writes afterwards to be elided. Yes, really. I know, I // want to refactor this to use less `unsafe` as much as the next rustacean. unsafe fn initialize_memory(memory: *mut Node, num_nodes: usize, ident: &H256) { - let dst = memory as *mut u8; + // We use raw pointers here, see above + let dst = slice::from_raw_parts_mut(memory as *mut u8, NODE_BYTES); debug_assert_eq!(ident.len(), 32); - keccak_512::unchecked(dst, NODE_BYTES, ident.as_ptr(), ident.len()); + keccak_512::write(&ident[..], dst); for i in 1..num_nodes { // We use raw pointers here, see above - let dst = memory.offset(i as _) as *mut u8; - let src = memory.offset(i as isize - 1) as *mut u8; - - keccak_512::unchecked(dst, NODE_BYTES, src, NODE_BYTES); + let dst = slice::from_raw_parts_mut(memory.offset(i as _) as *mut u8, NODE_BYTES); + let src = slice::from_raw_parts(memory.offset(i as isize - 1) as *mut u8, NODE_BYTES); + keccak_512::write(src, dst); } // Now this is initialized, we can treat it as a slice. let nodes: &mut [Node] = slice::from_raw_parts_mut(memory, num_nodes); - // For `unroll!`, see below. If the literal in `unroll!` is not the same as the RHS here then - // these have got out of sync! Don't let this happen! - debug_assert_eq!(NODE_DWORDS, 8); - - // This _should_ get unrolled by the compiler, since it's not using the loop variable. for _ in 0..ETHASH_CACHE_ROUNDS { for i in 0..num_nodes { let data_idx = (num_nodes - 1 + i) % num_nodes; @@ -348,11 +343,8 @@ unsafe fn initialize_memory(memory: *mut Node, num_nodes: usize, ident: &H256) { let mut data: Node = nodes.get_unchecked(data_idx).clone(); let rhs: &Node = nodes.get_unchecked(idx); - unroll! { - for w in 0..8 { - *data.as_dwords_mut().get_unchecked_mut(w) ^= - *rhs.as_dwords().get_unchecked(w); - } + for (a, b) in data.as_dwords_mut().iter_mut().zip(rhs.as_dwords()) { + *a ^= *b; } data diff --git a/crates/concensus/ethash/src/compute.rs b/crates/concensus/ethash/src/compute.rs index 648b157b1..00bbcd96d 100644 --- a/crates/concensus/ethash/src/compute.rs +++ b/crates/concensus/ethash/src/compute.rs @@ -26,7 +26,7 @@ use seed_compute::SeedHashCompute; use shared::*; use std::io; -use std::{mem, path::Path, ptr}; +use std::{mem, path::Path}; const MIX_WORDS: usize = ETHASH_MIX_BYTES / 4; const MIX_NODES: usize = MIX_WORDS / NODE_WORDS; @@ -141,31 +141,24 @@ pub fn quick_get_difficulty( mix_hash: &H256, progpow: bool, ) -> H256 { - unsafe { - if progpow { - let seed = keccak_f800_short(*header_hash, nonce, [0u32; 8]); - keccak_f800_long(*header_hash, seed, mem::transmute(*mix_hash)) - } else { - // This is safe - the `keccak_512` call below reads the first 40 bytes (which we explicitly set - // with two `copy_nonoverlapping` calls) but writes the first 64, and then we explicitly write - // the next 32 bytes before we read the whole thing with `keccak_256`. - // - // This cannot be elided by the compiler as it doesn't know the implementation of - // `keccak_512`. - let mut buf: [u8; 64 + 32] = ::mem::MaybeUninit::uninit().assume_init(); + if progpow { + let seed = keccak_f800_short(*header_hash, nonce, [0u32; 8]); + keccak_f800_long(*header_hash, seed, unsafe { mem::transmute(*mix_hash) }) + } else { + let mut buf = [0u8; 64 + 32]; - ptr::copy_nonoverlapping(header_hash.as_ptr(), buf.as_mut_ptr(), 32); - ptr::copy_nonoverlapping(&nonce as *const u64 as *const u8, buf[32..].as_mut_ptr(), 8); + let hash_len = header_hash.len(); + buf[..hash_len].copy_from_slice(header_hash); + let end = hash_len + mem::size_of::(); + buf[hash_len..end].copy_from_slice(&nonce.to_ne_bytes()); - keccak_512::unchecked(buf.as_mut_ptr(), 64, buf.as_ptr(), 40); - ptr::copy_nonoverlapping(mix_hash.as_ptr(), buf[64..].as_mut_ptr(), 32); + keccak_512::inplace_range(&mut buf, 0..end); + buf[64..].copy_from_slice(mix_hash); - // This is initialized in `keccak_256` - let mut hash: [u8; 32] = ::mem::MaybeUninit::uninit().assume_init(); - keccak_256::unchecked(hash.as_mut_ptr(), hash.len(), buf.as_ptr(), buf.len()); + let mut hash = [0u8; 32]; + keccak_256::write(&buf, &mut hash); - hash - } + hash } } @@ -214,32 +207,21 @@ fn hash_compute(light: &Light, full_size: usize, header_hash: &H256, nonce: u64) // improvements, since I can't imagine that 3-5% of our runtime is taken up by catting two // arrays together. let mut buf: MixBuf = MixBuf { - half_mix: unsafe { + half_mix: { // Pack `header_hash` and `nonce` together - // We explicitly write the first 40 bytes, leaving the last 24 as uninitialized. Then - // `keccak_512` reads the first 40 bytes (4th parameter) and overwrites the entire array, - // leaving it fully initialized. - let mut out: [u8; NODE_BYTES] = ::mem::MaybeUninit::uninit().assume_init(); + let mut out = [0u8; NODE_BYTES]; - ptr::copy_nonoverlapping(header_hash.as_ptr(), out.as_mut_ptr(), header_hash.len()); - ptr::copy_nonoverlapping( - &nonce as *const u64 as *const u8, - out[header_hash.len()..].as_mut_ptr(), - mem::size_of::(), - ); + let hash_len = header_hash.len(); + out[..hash_len].copy_from_slice(header_hash); + let end = hash_len + mem::size_of::(); + out[hash_len..end].copy_from_slice(&nonce.to_ne_bytes()); // compute keccak-512 hash and replicate across mix - keccak_512::unchecked( - out.as_mut_ptr(), - NODE_BYTES, - out.as_ptr(), - header_hash.len() + mem::size_of::(), - ); + keccak_512::inplace_range(&mut out, 0..end); Node { bytes: out } }, - // This is fully initialized before being read, see `let mut compress = ...` below - compress_bytes: unsafe { ::mem::MaybeUninit::uninit().assume_init() }, + compress_bytes: [0u8; MIX_WORDS], }; let mut mix: [_; MIX_NODES] = [buf.half_mix.clone(), buf.half_mix.clone()]; @@ -263,24 +245,13 @@ fn hash_compute(light: &Light, full_size: usize, header_hash: &H256, nonce: u64) fnv_hash(first_val ^ i, mix_words[i as usize % MIX_WORDS]) % num_full_pages }; - unroll! { - // MIX_NODES - for n in 0..2 { - let tmp_node = calculate_dag_item( - index * MIX_NODES as u32 + n as u32, - cache, - ); + // MIX_NODES + for n in 0..2 { + let tmp_node = calculate_dag_item(index * MIX_NODES as u32 + n as u32, cache); - unroll! { - // NODE_WORDS - for w in 0..16 { - mix[n].as_words_mut()[w] = - fnv_hash( - mix[n].as_words()[w], - tmp_node.as_words()[w], - ); - } - } + // NODE_WORDS + for (a, b) in mix[n].as_words_mut().iter_mut().zip(tmp_node.as_words()) { + *a = fnv_hash(*a, *b); } } } @@ -288,25 +259,27 @@ fn hash_compute(light: &Light, full_size: usize, header_hash: &H256, nonce: u64) let mix_words: [u32; MIX_WORDS] = unsafe { mem::transmute(mix) }; { - // This is an uninitialized buffer to begin with, but we iterate precisely `compress.len()` - // times and set each index, leaving the array fully initialized. THIS ONLY WORKS ON LITTLE- - // ENDIAN MACHINES. See a future PR to make this and the rest of the code work correctly on + // We iterate precisely `compress.len()` times and set each index, + // leaving the array fully initialized. THIS ONLY WORKS ON LITTLE-ENDIAN MACHINES. + // See a future PR to make this and the rest of the code work correctly on // big-endian arches like mips. let compress: &mut [u32; MIX_WORDS / 4] = unsafe { make_const_array!(MIX_WORDS / 4, &mut buf.compress_bytes) }; + #[cfg(target_endian = "big")] + { + compile_error!("OpenEthereum currently only supports little-endian targets"); + } // Compress mix debug_assert_eq!(MIX_WORDS / 4, 8); - unroll! { - for i in 0..8 { - let w = i * 4; + for i in 0..8 { + let w = i * 4; - let mut reduction = mix_words[w + 0]; - reduction = reduction.wrapping_mul(FNV_PRIME) ^ mix_words[w + 1]; - reduction = reduction.wrapping_mul(FNV_PRIME) ^ mix_words[w + 2]; - reduction = reduction.wrapping_mul(FNV_PRIME) ^ mix_words[w + 3]; - compress[i] = reduction; - } + let mut reduction = mix_words[w + 0]; + reduction = reduction.wrapping_mul(FNV_PRIME) ^ mix_words[w + 1]; + reduction = reduction.wrapping_mul(FNV_PRIME) ^ mix_words[w + 2]; + reduction = reduction.wrapping_mul(FNV_PRIME) ^ mix_words[w + 3]; + compress[i] = reduction; } } @@ -315,24 +288,20 @@ fn hash_compute(light: &Light, full_size: usize, header_hash: &H256, nonce: u64) let value: H256 = { // We can interpret the buffer as an array of `u8`s, since it's `repr(C)`. let read_ptr: *const u8 = &buf as *const MixBuf as *const u8; - // We overwrite the second half since `keccak_256` has an internal buffer and so allows - // overlapping arrays as input. - let write_ptr: *mut u8 = &mut buf.compress_bytes as *mut [u8; 32] as *mut u8; - unsafe { - keccak_256::unchecked( - write_ptr, - buf.compress_bytes.len(), + let buffer = unsafe { + core::slice::from_raw_parts( read_ptr, buf.half_mix.bytes.len() + buf.compress_bytes.len(), - ); - } + ) + }; + // We overwrite the buf.compress_bytes since `keccak_256` has an internal buffer and so allows + // overlapping arrays as input. + keccak_256::write(buffer, &mut buf.compress_bytes); + buf.compress_bytes }; - ProofOfWork { - mix_hash: mix_hash, - value: value, - } + ProofOfWork { mix_hash, value } } // TODO: Use the `simd` crate diff --git a/crates/concensus/ethash/src/keccak.rs b/crates/concensus/ethash/src/keccak.rs index f09ce56f8..134a11fb2 100644 --- a/crates/concensus/ethash/src/keccak.rs +++ b/crates/concensus/ethash/src/keccak.rs @@ -21,46 +21,15 @@ pub type H256 = [u8; 32]; pub mod keccak_512 { use super::hash; - pub use self::hash::keccak_512_unchecked as unchecked; - - pub fn write(input: &[u8], output: &mut [u8]) { - hash::keccak_512(input, output); - } - - pub fn inplace(input: &mut [u8]) { - // This is safe since `keccak_*` uses an internal buffer and copies the result to the output. This - // means that we can reuse the input buffer for both input and output. - unsafe { - hash::keccak_512_unchecked( - input.as_mut_ptr(), - input.len(), - input.as_ptr(), - input.len(), - ); - } - } + pub use self::hash::{ + keccak512 as inplace, keccak512_range as inplace_range, keccak_512 as write, + }; } pub mod keccak_256 { use super::hash; - pub use self::hash::keccak_256_unchecked as unchecked; - - #[allow(dead_code)] - pub fn write(input: &[u8], output: &mut [u8]) { - hash::keccak_256(input, output); - } - - pub fn inplace(input: &mut [u8]) { - // This is safe since `keccak_*` uses an internal buffer and copies the result to the output. This - // means that we can reuse the input buffer for both input and output. - unsafe { - hash::keccak_256_unchecked( - input.as_mut_ptr(), - input.len(), - input.as_ptr(), - input.len(), - ); - } - } + pub use self::hash::{ + keccak256 as inplace, keccak256_range as inplace_range, keccak_256 as write, + }; } diff --git a/crates/concensus/ethash/src/lib.rs b/crates/concensus/ethash/src/lib.rs index e56b09358..2232d2431 100644 --- a/crates/concensus/ethash/src/lib.rs +++ b/crates/concensus/ethash/src/lib.rs @@ -19,6 +19,7 @@ extern crate ethereum_types; extern crate memmap; extern crate parking_lot; extern crate primal; +extern crate tiny_keccak; #[macro_use] extern crate crunchy; @@ -52,12 +53,13 @@ mod progpow; pub use cache::{NodeCacheBuilder, OptimizeFor}; use compute::Light; pub use compute::{quick_get_difficulty, slow_hash_block_number, ProofOfWork}; -use ethereum_types::{U256, U512}; +use ethereum_types::{BigEndianHash, U256, U512}; use keccak::H256; use parking_lot::Mutex; pub use seed_compute::SeedHashCompute; pub use shared::ETHASH_EPOCH_LENGTH; use std::{ + convert::TryFrom, mem, path::{Path, PathBuf}, }; @@ -168,12 +170,12 @@ impl EthashManager { /// Convert an Ethash boundary to its original difficulty. Basically just `f(x) = 2^256 / x`. pub fn boundary_to_difficulty(boundary: ðereum_types::H256) -> U256 { - difficulty_to_boundary_aux(&**boundary) + difficulty_to_boundary_aux(&boundary.into_uint()) } /// Convert an Ethash difficulty to the target boundary. Basically just `f(x) = 2^256 / x`. pub fn difficulty_to_boundary(difficulty: &U256) -> ethereum_types::H256 { - difficulty_to_boundary_aux(difficulty).into() + BigEndianHash::from_uint(&difficulty_to_boundary_aux(difficulty)) } fn difficulty_to_boundary_aux>(difficulty: T) -> ethereum_types::U256 { @@ -184,8 +186,8 @@ fn difficulty_to_boundary_aux>(difficulty: T) -> ethereum_types::U if difficulty == U512::one() { U256::max_value() } else { - // difficulty > 1, so result should never overflow 256 bits - U256::from((U512::one() << 256) / difficulty) + const PROOF: &str = "difficulty > 1, so result never overflows 256 bits; qed"; + U256::try_from((U512::one() << 256) / difficulty).expect(PROOF) } } @@ -210,12 +212,12 @@ fn test_lru() { #[test] fn test_difficulty_to_boundary() { - use ethereum_types::H256; + use ethereum_types::{BigEndianHash, H256}; use std::str::FromStr; assert_eq!( difficulty_to_boundary(&U256::from(1)), - H256::from(U256::max_value()) + BigEndianHash::from_uint(&U256::max_value()) ); assert_eq!( difficulty_to_boundary(&U256::from(2)), @@ -243,16 +245,18 @@ fn test_difficulty_to_boundary_regression() { boundary_to_difficulty(&difficulty_to_boundary(&difficulty.into())) ); assert_eq!( - H256::from(difficulty), - difficulty_to_boundary(&boundary_to_difficulty(&difficulty.into())) + H256::from_low_u64_be(difficulty), + difficulty_to_boundary(&boundary_to_difficulty(&H256::from_low_u64_be(difficulty))) ); assert_eq!( U256::from(difficulty), - boundary_to_difficulty(&boundary_to_difficulty(&difficulty.into()).into()) + boundary_to_difficulty(&BigEndianHash::from_uint(&boundary_to_difficulty( + &H256::from_low_u64_be(difficulty) + ))), ); assert_eq!( - H256::from(difficulty), - difficulty_to_boundary(&difficulty_to_boundary(&difficulty.into()).into()) + H256::from_low_u64_be(difficulty), + difficulty_to_boundary(&difficulty_to_boundary(&difficulty.into()).into_uint()) ); } } @@ -266,5 +270,5 @@ fn test_difficulty_to_boundary_panics_on_zero() { #[test] #[should_panic] fn test_boundary_to_difficulty_panics_on_zero() { - boundary_to_difficulty(ðereum_types::H256::from(0)); + boundary_to_difficulty(ðereum_types::H256::zero()); } diff --git a/crates/concensus/miner/Cargo.toml b/crates/concensus/miner/Cargo.toml index d7bb02b56..0fae0fa7b 100644 --- a/crates/concensus/miner/Cargo.toml +++ b/crates/concensus/miner/Cargo.toml @@ -17,20 +17,21 @@ url = { version = "2", optional = true } ansi_term = "0.10" common-types = { path = "../../ethcore/types" } error-chain = "0.12" -ethabi = "6.0" -ethabi-derive = "6.0" -ethabi-contract = "6.0" +ethabi = "12.0.0" +ethabi-derive = "12.0.0" +ethabi-contract = "11.0.0" ethcore-call-contract = { path = "../../vm/call-contract" } -ethereum-types = "0.4" +ethereum-types = "0.9.2" futures = "0.1" -heapsize = "0.4" -keccak-hash = "0.1" +keccak-hash = "0.5.0" linked-hash-map = "0.5" log = "0.4" +parity-crypto = { version = "0.6.2", features = [ "publickey" ] } parity-runtime = { path = "../../runtime/runtime" } +parity-util-mem = "0.7" parking_lot = "0.7" price-info = { path = "./price-info", optional = true } -rlp = { version = "0.3.0", features = ["ethereum"] } +rlp = { version = "0.4.6" } trace-time = "0.1" transaction-pool = "2.0.1" diff --git a/crates/concensus/miner/local-store/Cargo.toml b/crates/concensus/miner/local-store/Cargo.toml index 463470c86..554ea9301 100644 --- a/crates/concensus/miner/local-store/Cargo.toml +++ b/crates/concensus/miner/local-store/Cargo.toml @@ -10,7 +10,8 @@ ethcore-io = { path = "../../../runtime/io" } ethcore-db = { path = "../../../db/db"} kvdb = "0.1" log = "0.4" -rlp = { version = "0.3.0", features = ["ethereum"] } +parity-crypto = { version = "0.6.2", features = [ "publickey" ] } +rlp = { version = "0.4.6" } serde = "1.0" serde_derive = "1.0" serde_json = "1.0" diff --git a/crates/concensus/miner/local-store/src/lib.rs b/crates/concensus/miner/local-store/src/lib.rs index 0d2a3657c..d1aee1065 100644 --- a/crates/concensus/miner/local-store/src/lib.rs +++ b/crates/concensus/miner/local-store/src/lib.rs @@ -29,6 +29,7 @@ extern crate common_types as types; extern crate ethcore_db; extern crate ethcore_io as io; extern crate kvdb; +extern crate parity_crypto as crypto; extern crate rlp; extern crate serde; extern crate serde_json; @@ -238,7 +239,7 @@ impl Drop for LocalDataStore { mod tests { use super::NodeInfo; - use ethkey::{Brain, Generator}; + use ethkey::Brain; use std::sync::Arc; use types::transaction::{Condition, PendingTransaction, Transaction, TypedTransaction}; @@ -269,7 +270,7 @@ mod tests { #[test] fn with_condition() { - let keypair = Brain::new("abcd".into()).generate().unwrap(); + let keypair = Brain::new("abcd".into()).generate(); let transactions: Vec<_> = (0..10u64) .map(|nonce| { let mut tx = TypedTransaction::Legacy(Transaction::default()); @@ -306,7 +307,7 @@ mod tests { #[test] fn skips_bad_transactions() { - let keypair = Brain::new("abcd".into()).generate().unwrap(); + let keypair = Brain::new("abcd".into()).generate(); let mut transactions: Vec<_> = (0..10u64) .map(|nonce| { let mut tx = TypedTransaction::Legacy(Transaction::default()); diff --git a/crates/concensus/miner/src/external.rs b/crates/concensus/miner/src/external.rs index 403f6949d..2a68b4e35 100644 --- a/crates/concensus/miner/src/external.rs +++ b/crates/concensus/miner/src/external.rs @@ -92,7 +92,7 @@ mod tests { // given let m = miner(); assert_eq!(m.hashrate(), U256::from(0)); - m.submit_hashrate(U256::from(10), H256::from(1)); + m.submit_hashrate(U256::from(10), H256::from_low_u64_be(1)); assert_eq!(m.hashrate(), U256::from(10)); // when @@ -107,12 +107,12 @@ mod tests { // given let m = miner(); assert_eq!(m.hashrate(), U256::from(0)); - m.submit_hashrate(U256::from(10), H256::from(1)); + m.submit_hashrate(U256::from(10), H256::from_low_u64_be(1)); assert_eq!(m.hashrate(), U256::from(10)); // when - m.submit_hashrate(U256::from(15), H256::from(1)); - m.submit_hashrate(U256::from(20), H256::from(2)); + m.submit_hashrate(U256::from(15), H256::from_low_u64_be(1)); + m.submit_hashrate(U256::from(20), H256::from_low_u64_be(2)); // then assert_eq!(m.hashrate(), U256::from(35)); diff --git a/crates/concensus/miner/src/lib.rs b/crates/concensus/miner/src/lib.rs index 89bd18c4f..46280c152 100644 --- a/crates/concensus/miner/src/lib.rs +++ b/crates/concensus/miner/src/lib.rs @@ -22,13 +22,15 @@ extern crate ansi_term; extern crate common_types as types; extern crate ethabi; +extern crate ethabi_derive; extern crate ethcore_call_contract as call_contract; extern crate ethereum_types; extern crate futures; -extern crate heapsize; extern crate keccak_hash as hash; extern crate linked_hash_map; +extern crate parity_crypto as crypto; extern crate parity_runtime; +extern crate parity_util_mem; extern crate parking_lot; #[cfg(feature = "price-info")] extern crate price_info; @@ -38,8 +40,6 @@ extern crate transaction_pool as txpool; #[macro_use] extern crate ethabi_contract; #[macro_use] -extern crate ethabi_derive; -#[macro_use] extern crate error_chain; #[macro_use] extern crate log; diff --git a/crates/concensus/miner/src/pool/listener.rs b/crates/concensus/miner/src/pool/listener.rs index 6cb190ca9..5d1b936b9 100644 --- a/crates/concensus/miner/src/pool/listener.rs +++ b/crates/concensus/miner/src/pool/listener.rs @@ -124,6 +124,7 @@ impl txpool::Listener for Logger { #[cfg(test)] mod tests { use super::*; + use ethereum_types::H160; use parking_lot::Mutex; use txpool::Listener; use types::transaction; @@ -166,7 +167,7 @@ mod tests { gas_price: 5.into(), value: 0.into(), }) - .fake_sign(5.into()); + .fake_sign(H160::from_low_u64_be(5)); Arc::new(Transaction::from_pending_block_transaction(signed)) } diff --git a/crates/concensus/miner/src/pool/local_transactions.rs b/crates/concensus/miner/src/pool/local_transactions.rs index 8c0037c58..bb86f76f9 100644 --- a/crates/concensus/miner/src/pool/local_transactions.rs +++ b/crates/concensus/miner/src/pool/local_transactions.rs @@ -254,8 +254,8 @@ impl txpool::Listener for LocalTransactionsList { #[cfg(test)] mod tests { use super::*; + use crypto::publickey::{Generator, Random}; use ethereum_types::U256; - use ethkey::{Generator, Random}; use txpool::Listener; use types::transaction; @@ -339,7 +339,7 @@ mod tests { } fn new_tx>(nonce: T) -> Arc { - let keypair = Random.generate().unwrap(); + let keypair = Random.generate(); let signed = transaction::TypedTransaction::Legacy(transaction::Transaction { action: transaction::Action::Create, value: U256::from(100), diff --git a/crates/concensus/miner/src/pool/mod.rs b/crates/concensus/miner/src/pool/mod.rs index 8d11c43d9..1467a1f23 100644 --- a/crates/concensus/miner/src/pool/mod.rs +++ b/crates/concensus/miner/src/pool/mod.rs @@ -17,7 +17,7 @@ //! Transaction Pool use ethereum_types::{Address, H256, U256}; -use heapsize::HeapSizeOf; +use parity_util_mem::MallocSizeOfExt; use txpool; use types::transaction; @@ -177,7 +177,7 @@ impl txpool::VerifiedTransaction for VerifiedTransaction { } fn mem_usage(&self) -> usize { - self.transaction.heap_size_of_children() + self.transaction.malloc_size_of() } fn sender(&self) -> &Address { diff --git a/crates/concensus/miner/src/pool/replace.rs b/crates/concensus/miner/src/pool/replace.rs index 0e2b7cc95..d7d9ac1d9 100644 --- a/crates/concensus/miner/src/pool/replace.rs +++ b/crates/concensus/miner/src/pool/replace.rs @@ -117,7 +117,7 @@ where mod tests { use super::*; - use ethkey::{Generator, KeyPair, Random}; + use crypto::publickey::{Generator, KeyPair, Random}; use pool::{ scoring::*, tests::{ @@ -160,7 +160,7 @@ mod tests { let replace = ReplaceByScoreAndReadiness::new(scoring, client); // same sender txs - let keypair = Random.generate().unwrap(); + let keypair = Random.generate(); let same_sender_tx1 = local_tx_verified( Tx { @@ -190,7 +190,7 @@ mod tests { ); // different sender txs - let sender1 = Random.generate().unwrap(); + let sender1 = Random.generate(); let different_sender_tx1 = local_tx_verified( Tx { nonce: 2, @@ -200,7 +200,7 @@ mod tests { &sender1, ); - let sender2 = Random.generate().unwrap(); + let sender2 = Random.generate(); let different_sender_tx2 = local_tx_verified( Tx { nonce: 1, @@ -274,7 +274,7 @@ mod tests { ..Default::default() }; - let keypair = Random.generate().unwrap(); + let keypair = Random.generate(); let txs = vec![tx1, tx2, tx3, tx4] .into_iter() .map(|tx| tx.unsigned().sign(keypair.secret(), None).verified()) @@ -440,7 +440,7 @@ mod tests { let client = TestClient::new().with_nonce(1); let replace = ReplaceByScoreAndReadiness::new(scoring, client); - let old_sender = Random.generate().unwrap(); + let old_sender = Random.generate(); let tx_old_ready_1 = { let tx = Tx { nonce: 1, @@ -518,7 +518,7 @@ mod tests { tx.signed().verified() }; - let new_sender = Random.generate().unwrap(); + let new_sender = Random.generate(); let tx_new_ready_1 = { let tx = Tx { nonce: 1, @@ -586,7 +586,7 @@ mod tests { tx.signed().verified() }; - let new_sender = Random.generate().unwrap(); + let new_sender = Random.generate(); let tx_new_ready_1 = local_tx_verified( Tx { nonce: 1, @@ -641,7 +641,7 @@ mod tests { tx.signed().verified() }; - let new_sender = Random.generate().unwrap(); + let new_sender = Random.generate(); let tx_new_ready_1 = local_tx_verified( Tx { nonce: 1, diff --git a/crates/concensus/miner/src/pool/tests/tx.rs b/crates/concensus/miner/src/pool/tests/tx.rs index 51c276d44..84187cbd1 100644 --- a/crates/concensus/miner/src/pool/tests/tx.rs +++ b/crates/concensus/miner/src/pool/tests/tx.rs @@ -14,8 +14,8 @@ // You should have received a copy of the GNU General Public License // along with OpenEthereum. If not, see . +use crypto::publickey::{Generator, Random}; use ethereum_types::{H256, U256}; -use ethkey::{Generator, Random}; use rustc_hex::FromHex; use types::transaction::{ self, SignedTransaction, Transaction, TypedTransaction, UnverifiedTransaction, @@ -49,7 +49,7 @@ impl Tx { } pub fn signed(self) -> SignedTransaction { - let keypair = Random.generate().unwrap(); + let keypair = Random.generate(); self.unsigned().sign(keypair.secret(), None) } @@ -59,7 +59,7 @@ impl Tx { } pub fn signed_triple(mut self) -> (SignedTransaction, SignedTransaction, SignedTransaction) { - let keypair = Random.generate().unwrap(); + let keypair = Random.generate(); let tx1 = self.clone().unsigned().sign(keypair.secret(), None); self.nonce += 1; let tx2 = self.clone().unsigned().sign(keypair.secret(), None); @@ -70,7 +70,7 @@ impl Tx { } pub fn signed_replacement(mut self) -> (SignedTransaction, SignedTransaction) { - let keypair = Random.generate().unwrap(); + let keypair = Random.generate(); let tx1 = self.clone().unsigned().sign(keypair.secret(), None); self.gas_price += 1; let tx2 = self.unsigned().sign(keypair.secret(), None); @@ -90,7 +90,7 @@ impl Tx { } pub fn big_one(self) -> SignedTransaction { - let keypair = Random.generate().unwrap(); + let keypair = Random.generate(); let tx = TypedTransaction::Legacy(Transaction { action: transaction::Action::Create, value: U256::from(100), diff --git a/crates/concensus/miner/stratum/Cargo.toml b/crates/concensus/miner/stratum/Cargo.toml index a4977555e..2b1248576 100644 --- a/crates/concensus/miner/stratum/Cargo.toml +++ b/crates/concensus/miner/stratum/Cargo.toml @@ -6,8 +6,8 @@ license = "GPL-3.0" authors = ["Parity Technologies "] [dependencies] -ethereum-types = "0.4" -keccak-hash = "0.1" +ethereum-types = "0.9.2" +keccak-hash = "0.5.0" jsonrpc-core = "15.0.0" jsonrpc-tcp-server = "15.0.0" log = "0.4" diff --git a/crates/db/blooms-db/Cargo.toml b/crates/db/blooms-db/Cargo.toml index 543a79877..a531ca5d6 100644 --- a/crates/db/blooms-db/Cargo.toml +++ b/crates/db/blooms-db/Cargo.toml @@ -6,7 +6,7 @@ authors = ["Parity Technologies "] [dependencies] byteorder = "1.2" -ethbloom = "=0.5.0" +ethbloom = "0.9.1" parking_lot = "0.7" tiny-keccak = "1.4" diff --git a/crates/db/blooms-db/benches/blooms.rs b/crates/db/blooms-db/benches/blooms.rs index 42f59c37b..9713a676a 100644 --- a/crates/db/blooms-db/benches/blooms.rs +++ b/crates/db/blooms-db/benches/blooms.rs @@ -40,7 +40,7 @@ fn bench_blooms_filter_1_million_ok(c: &mut Criterion) { database .insert_blooms(999_999, iter::once(&Bloom::zero())) .unwrap(); - let bloom = Bloom::from(0x001); + let bloom = Bloom::from_low_u64_be(0x001); database.insert_blooms(200_000, iter::once(&bloom)).unwrap(); database.insert_blooms(400_000, iter::once(&bloom)).unwrap(); database.insert_blooms(600_000, iter::once(&bloom)).unwrap(); @@ -60,8 +60,8 @@ fn bench_blooms_filter_1_million_miss(c: &mut Criterion) { database .insert_blooms(999_999, iter::once(&Bloom::zero())) .unwrap(); - let bloom = Bloom::from(0x001); - let bad_bloom = Bloom::from(0x0001); + let bloom = Bloom::from_low_u64_be(0x001); + let bad_bloom = Bloom::from_low_u64_be(0x0001); database.insert_blooms(200_000, iter::once(&bloom)).unwrap(); database.insert_blooms(400_000, iter::once(&bloom)).unwrap(); database.insert_blooms(600_000, iter::once(&bloom)).unwrap(); @@ -81,8 +81,8 @@ fn bench_blooms_filter_1_million_miss_and_ok(c: &mut Criterion) { database .insert_blooms(999_999, iter::once(&Bloom::zero())) .unwrap(); - let bloom = Bloom::from(0x001); - let bad_bloom = Bloom::from(0x0001); + let bloom = Bloom::from_low_u64_be(0x001); + let bad_bloom = Bloom::from_low_u64_be(0x0001); database.insert_blooms(200_000, iter::once(&bloom)).unwrap(); database.insert_blooms(400_000, iter::once(&bloom)).unwrap(); database.insert_blooms(600_000, iter::once(&bloom)).unwrap(); diff --git a/crates/db/blooms-db/src/db.rs b/crates/db/blooms-db/src/db.rs index 752120b26..f174ffeb1 100644 --- a/crates/db/blooms-db/src/db.rs +++ b/crates/db/blooms-db/src/db.rs @@ -346,59 +346,59 @@ mod tests { .insert_blooms( 0, vec![ - Bloom::from(0), - Bloom::from(0x01), - Bloom::from(0x10), - Bloom::from(0x11), + Bloom::zero(), + Bloom::from_low_u64_be(0x01), + Bloom::from_low_u64_be(0x10), + Bloom::from_low_u64_be(0x11), ] .iter(), ) .unwrap(); let matches = database - .iterate_matching(0, 3, Some(&Bloom::from(0))) + .iterate_matching(0, 3, Some(&Bloom::zero())) .unwrap() .collect::, _>>() .unwrap(); assert_eq!(matches, vec![0, 1, 2, 3]); let matches = database - .iterate_matching(0, 4, Some(&Bloom::from(0))) + .iterate_matching(0, 4, Some(&Bloom::zero())) .unwrap() .collect::, _>>() .unwrap(); assert_eq!(matches, vec![0, 1, 2, 3]); let matches = database - .iterate_matching(1, 3, Some(&Bloom::from(0))) + .iterate_matching(1, 3, Some(&Bloom::zero())) .unwrap() .collect::, _>>() .unwrap(); assert_eq!(matches, vec![1, 2, 3]); let matches = database - .iterate_matching(1, 2, Some(&Bloom::from(0))) + .iterate_matching(1, 2, Some(&Bloom::zero())) .unwrap() .collect::, _>>() .unwrap(); assert_eq!(matches, vec![1, 2]); let matches = database - .iterate_matching(0, 3, Some(&Bloom::from(0x01))) + .iterate_matching(0, 3, Some(&Bloom::from_low_u64_be(0x01))) .unwrap() .collect::, _>>() .unwrap(); assert_eq!(matches, vec![1, 3]); let matches = database - .iterate_matching(0, 3, Some(&Bloom::from(0x10))) + .iterate_matching(0, 3, Some(&Bloom::from_low_u64_be(0x10))) .unwrap() .collect::, _>>() .unwrap(); assert_eq!(matches, vec![2, 3]); let matches = database - .iterate_matching(2, 2, Some(&Bloom::from(0x10))) + .iterate_matching(2, 2, Some(&Bloom::from_low_u64_be(0x10))) .unwrap() .collect::, _>>() .unwrap(); @@ -413,52 +413,52 @@ mod tests { .insert_blooms( 254, vec![ - Bloom::from(0x100), - Bloom::from(0x01), - Bloom::from(0x10), - Bloom::from(0x11), + Bloom::from_low_u64_be(0x100), + Bloom::from_low_u64_be(0x01), + Bloom::from_low_u64_be(0x10), + Bloom::from_low_u64_be(0x11), ] .iter(), ) .unwrap(); let matches = database - .iterate_matching(0, 257, Some(&Bloom::from(0x01))) + .iterate_matching(0, 257, Some(&Bloom::from_low_u64_be(0x01))) .unwrap() .collect::, _>>() .unwrap(); assert_eq!(matches, vec![255, 257]); let matches = database - .iterate_matching(0, 258, Some(&Bloom::from(0x100))) + .iterate_matching(0, 258, Some(&Bloom::from_low_u64_be(0x100))) .unwrap() .collect::, _>>() .unwrap(); assert_eq!(matches, vec![254]); let matches = database - .iterate_matching(0, 256, Some(&Bloom::from(0x01))) + .iterate_matching(0, 256, Some(&Bloom::from_low_u64_be(0x01))) .unwrap() .collect::, _>>() .unwrap(); assert_eq!(matches, vec![255]); let matches = database - .iterate_matching(255, 255, Some(&Bloom::from(0x01))) + .iterate_matching(255, 255, Some(&Bloom::from_low_u64_be(0x01))) .unwrap() .collect::, _>>() .unwrap(); assert_eq!(matches, vec![255]); let matches = database - .iterate_matching(256, 256, Some(&Bloom::from(0x10))) + .iterate_matching(256, 256, Some(&Bloom::from_low_u64_be(0x10))) .unwrap() .collect::, _>>() .unwrap(); assert_eq!(matches, vec![256]); let matches = database - .iterate_matching(256, 257, Some(&Bloom::from(0x10))) + .iterate_matching(256, 257, Some(&Bloom::from_low_u64_be(0x10))) .unwrap() .collect::, _>>() .unwrap(); @@ -469,10 +469,10 @@ mod tests { fn test_db_close() { let tempdir = TempDir::new("").unwrap(); let blooms = vec![ - Bloom::from(0x100), - Bloom::from(0x01), - Bloom::from(0x10), - Bloom::from(0x11), + Bloom::from_low_u64_be(0x100), + Bloom::from_low_u64_be(0x01), + Bloom::from_low_u64_be(0x10), + Bloom::from_low_u64_be(0x11), ]; let mut database = Database::open(tempdir.path()).unwrap(); diff --git a/crates/db/blooms-db/src/file.rs b/crates/db/blooms-db/src/file.rs index edb236d92..1d1efaebc 100644 --- a/crates/db/blooms-db/src/file.rs +++ b/crates/db/blooms-db/src/file.rs @@ -66,7 +66,7 @@ impl File { let mut file_ref = &self.file; file_ref.seek(SeekFrom::Start(pos * 256))?; let mut bloom = ethbloom::Bloom::default(); - file_ref.read_exact(&mut bloom)?; + file_ref.read_exact(bloom.as_bytes_mut())?; Ok(bloom) } @@ -80,7 +80,7 @@ impl File { old_bloom.accrue_bloom(bloom); let mut file_ref = &self.file; file_ref.seek(SeekFrom::Start(pos * 256))?; - file_ref.write_all(&old_bloom) + file_ref.write_all(old_bloom.as_bytes()) } /// Replace bloom at given position with a new one. @@ -133,7 +133,7 @@ impl<'a> Iterator for FileIterator<'a> { fn next(&mut self) -> Option { let mut bloom = ethbloom::Bloom::default(); - match self.file.read_exact(&mut bloom) { + match self.file.read_exact(bloom.as_bytes_mut()) { Ok(_) => Some(Ok(bloom)), Err(ref err) if err.kind() == io::ErrorKind::UnexpectedEof => None, Err(err) => Some(Err(err)), @@ -151,8 +151,8 @@ mod tests { fn test_file() { let tempdir = TempDir::new("").unwrap(); let mut file = File::open(tempdir.path().join("file")).unwrap(); - file.accrue_bloom(0, &Bloom::from(1)).unwrap(); + file.accrue_bloom(0, &Bloom::from_low_u64_be(1)).unwrap(); file.flush().unwrap(); - assert_eq!(file.read_bloom(0).unwrap(), Bloom::from(1)); + assert_eq!(file.read_bloom(0).unwrap(), Bloom::from_low_u64_be(1)); } } diff --git a/crates/db/db/Cargo.toml b/crates/db/db/Cargo.toml index 7b6ebbfde..6cfd27ce6 100644 --- a/crates/db/db/Cargo.toml +++ b/crates/db/db/Cargo.toml @@ -9,12 +9,12 @@ edition = "2018" [dependencies] common-types = { path = "../../ethcore/types" } -ethereum-types = "0.4" -heapsize = "0.4" +ethereum-types = "0.9.2" kvdb = "0.1" kvdb-rocksdb = "0.1.3" kvdb-memorydb = "0.1" +parity-util-mem = "0.7" parking_lot = "0.7" -rlp = { version = "0.3.0", features = ["ethereum"] } +rlp = { version = "0.4.6" } rlp_derive = { path = "../../util/rlp-derive" } stats = { path = "../../util/stats" } \ No newline at end of file diff --git a/crates/db/db/src/db.rs b/crates/db/db/src/db.rs index 464300a25..170ab9863 100644 --- a/crates/db/db/src/db.rs +++ b/crates/db/db/src/db.rs @@ -20,7 +20,7 @@ use kvdb::DBTransaction; use kvdb_rocksdb::Database; use parking_lot::RwLock; use stats::{PrometheusMetrics, PrometheusRegistry}; -use std::{collections::HashMap, hash::Hash, io::Read, ops::Deref}; +use std::{collections::HashMap, hash::Hash, io::Read}; use rlp; @@ -84,7 +84,7 @@ where /// Should be used to get database key associated with given value. pub trait Key { /// The db key associated with this value. - type Target: Deref; + type Target: AsRef<[u8]>; /// Returns db key. fn key(&self) -> Self::Target; @@ -96,13 +96,13 @@ pub trait Writable { fn write(&mut self, col: Option, key: &dyn Key, value: &T) where T: rlp::Encodable, - R: Deref; + R: AsRef<[u8]>; /// Deletes key from the databse. fn delete(&mut self, col: Option, key: &dyn Key) where T: rlp::Encodable, - R: Deref; + R: AsRef<[u8]>; /// Writes the value into the database and updates the cache. fn write_with_cache( @@ -115,7 +115,7 @@ pub trait Writable { ) where K: Key + Hash + Eq, T: rlp::Encodable, - R: Deref, + R: AsRef<[u8]>, { self.write(col, &key, &value); match policy { @@ -138,7 +138,7 @@ pub trait Writable { ) where K: Key + Hash + Eq, T: rlp::Encodable, - R: Deref, + R: AsRef<[u8]>, { match policy { CacheUpdatePolicy::Overwrite => { @@ -166,7 +166,7 @@ pub trait Writable { ) where K: Key + Hash + Eq, T: rlp::Encodable, - R: Deref, + R: AsRef<[u8]>, { match policy { CacheUpdatePolicy::Overwrite => { @@ -197,7 +197,7 @@ pub trait Readable { fn read(&self, col: Option, key: &dyn Key) -> Option where T: rlp::Decodable, - R: Deref; + R: AsRef<[u8]>; /// Returns value for given key either in cache or in database. fn read_with_cache(&self, col: Option, cache: &RwLock, key: &K) -> Option @@ -246,13 +246,13 @@ pub trait Readable { /// Returns true if given value exists. fn exists(&self, col: Option, key: &dyn Key) -> bool where - R: Deref; + R: AsRef<[u8]>; /// Returns true if given value exists either in cache or in database. fn exists_with_cache(&self, col: Option, cache: &RwLock, key: &K) -> bool where K: Eq + Hash + Key, - R: Deref, + R: AsRef<[u8]>, C: Cache, { { @@ -270,17 +270,17 @@ impl Writable for DBTransaction { fn write(&mut self, col: Option, key: &dyn Key, value: &T) where T: rlp::Encodable, - R: Deref, + R: AsRef<[u8]>, { - self.put(col, &key.key(), &rlp::encode(value)); + self.put(col, key.key().as_ref(), &rlp::encode(value)); } fn delete(&mut self, col: Option, key: &dyn Key) where T: rlp::Encodable, - R: Deref, + R: AsRef<[u8]>, { - self.delete(col, &key.key()); + self.delete(col, key.key().as_ref()); } } @@ -288,25 +288,25 @@ impl Readable for KVDB { fn read(&self, col: Option, key: &dyn Key) -> Option where T: rlp::Decodable, - R: Deref, + R: AsRef<[u8]>, { - self.get(col, &key.key()) - .expect(&format!("db get failed, key: {:?}", &key.key() as &[u8])) + self.get(col, key.key().as_ref()) + .expect(&format!("db get failed, key: {:?}", key.key().as_ref())) .map(|v| rlp::decode(&v).expect("decode db value failed")) } fn exists(&self, col: Option, key: &dyn Key) -> bool where - R: Deref, + R: AsRef<[u8]>, { - let result = self.get(col, &key.key()); + let result = self.get(col, key.key().as_ref()); match result { Ok(v) => v.is_some(), Err(err) => { panic!( "db get failed, key: {:?}, err: {:?}", - &key.key() as &[u8], + key.key().as_ref(), err ); } diff --git a/crates/db/db/src/keys.rs b/crates/db/db/src/keys.rs index ded42045f..e3c26df3f 100644 --- a/crates/db/db/src/keys.rs +++ b/crates/db/db/src/keys.rs @@ -16,14 +16,14 @@ //! Blockchain DB extras. -use std::{io::Write, ops}; +use std::io::Write; use common_types::{ engines::epoch::Transition as EpochTransition, receipt::TypedReceipt, BlockNumber, }; use ethereum_types::{H256, H264, U256}; -use heapsize::HeapSizeOf; use kvdb::PREFIX_LEN as DB_PREFIX_LEN; +use parity_util_mem::MallocSizeOf; use rlp; use rlp_derive::{RlpDecodable, RlpEncodable}; @@ -48,19 +48,17 @@ pub enum ExtrasIndex { fn with_index(hash: &H256, i: ExtrasIndex) -> H264 { let mut result = H264::default(); - result[0] = i as u8; - (*result)[1..].clone_from_slice(hash); + result.as_bytes_mut()[0] = i as u8; + result.as_bytes_mut()[1..].clone_from_slice(hash.as_bytes()); result } /// Wrapper for block number used as a DB key. pub struct BlockNumberKey([u8; 5]); -impl ops::Deref for BlockNumberKey { - type Target = [u8]; - - fn deref(&self) -> &Self::Target { - &self.0 +impl AsRef<[u8]> for BlockNumberKey { + fn as_ref(&self) -> &[u8] { + &self.0[..] } } @@ -133,10 +131,8 @@ pub const EPOCH_KEY_PREFIX: &'static [u8; DB_PREFIX_LEN] = &[ /// Epoch transitions key pub struct EpochTransitionsKey([u8; EPOCH_KEY_LEN]); -impl ops::Deref for EpochTransitionsKey { - type Target = [u8]; - - fn deref(&self) -> &[u8] { +impl AsRef<[u8]> for EpochTransitionsKey { + fn as_ref(&self) -> &[u8] { &self.0[..] } } @@ -156,7 +152,7 @@ impl Key for u64 { } /// Familial details concerning a block -#[derive(Debug, Clone)] +#[derive(Debug, Clone, MallocSizeOf)] pub struct BlockDetails { /// Block number pub number: BlockNumber, @@ -215,14 +211,8 @@ impl rlp::Decodable for BlockDetails { } } -impl HeapSizeOf for BlockDetails { - fn heap_size_of_children(&self) -> usize { - self.children.heap_size_of_children() - } -} - /// Represents address of certain transaction within block -#[derive(Debug, PartialEq, Clone, RlpEncodable, RlpDecodable)] +#[derive(Debug, PartialEq, Clone, RlpEncodable, RlpDecodable, MallocSizeOf)] pub struct TransactionAddress { /// Block hash pub block_hash: H256, @@ -230,14 +220,8 @@ pub struct TransactionAddress { pub index: usize, } -impl HeapSizeOf for TransactionAddress { - fn heap_size_of_children(&self) -> usize { - 0 - } -} - /// Contains all block receipts. -#[derive(Clone)] +#[derive(Clone, MallocSizeOf)] pub struct BlockReceipts { /// Block receipts pub receipts: Vec, @@ -262,12 +246,6 @@ impl BlockReceipts { } } -impl HeapSizeOf for BlockReceipts { - fn heap_size_of_children(&self) -> usize { - self.receipts.heap_size_of_children() - } -} - /// Candidate transitions to an epoch with specific number. #[derive(Clone, RlpEncodable, RlpDecodable)] pub struct EpochTransitions { diff --git a/crates/db/journaldb/Cargo.toml b/crates/db/journaldb/Cargo.toml index 9c331e14d..7bd8abf40 100644 --- a/crates/db/journaldb/Cargo.toml +++ b/crates/db/journaldb/Cargo.toml @@ -7,19 +7,19 @@ license = "GPL3" [dependencies] parity-bytes = "0.1" -ethereum-types = "0.4" +ethereum-types = "0.9.2" hash-db = "0.11.0" -heapsize = "0.4" keccak-hasher = { path = "../../util/keccak-hasher" } ethcore-db = { path = "../../db/db"} kvdb = "0.1" log = "0.4" memory-db = { path = "../memory-db" } +parity-util-mem = "0.7" parking_lot = "0.7" fastmap = { path = "../../util/fastmap" } -rlp = { version = "0.3.0", features = ["ethereum"] } +rlp = { version = "0.4.6" } [dev-dependencies] env_logger = "0.5" -keccak-hash = "0.1" +keccak-hash = "0.5.0" kvdb-memorydb = "=0.1.0" diff --git a/crates/db/journaldb/src/archivedb.rs b/crates/db/journaldb/src/archivedb.rs index 79cafcd7b..5d4ddfe44 100644 --- a/crates/db/journaldb/src/archivedb.rs +++ b/crates/db/journaldb/src/archivedb.rs @@ -63,7 +63,7 @@ impl ArchiveDB { fn payload(&self, key: &H256) -> Option { self.backing - .get(self.column, key) + .get(self.column, key.as_bytes()) .expect("Low-level database error. Some issue with your hard disk?") } } @@ -147,7 +147,7 @@ impl JournalDB for ArchiveDB { for i in self.overlay.drain() { let (key, (value, rc)) = i; if rc > 0 { - batch.put(self.column, &key, &value); + batch.put(self.column, key.as_bytes(), &value); inserts += 1; } if rc < 0 { @@ -180,18 +180,18 @@ impl JournalDB for ArchiveDB { for i in self.overlay.drain() { let (key, (value, rc)) = i; if rc > 0 { - if self.backing.get(self.column, &key)?.is_some() { + if self.backing.get(self.column, key.as_bytes())?.is_some() { return Err(error_key_already_exists(&key)); } - batch.put(self.column, &key, &value); + batch.put(self.column, key.as_bytes(), &value); inserts += 1; } if rc < 0 { assert!(rc == -1); - if self.backing.get(self.column, &key)?.is_none() { + if self.backing.get(self.column, key.as_bytes())?.is_none() { return Err(error_negatively_reference_hash(&key)); } - batch.delete(self.column, &key); + batch.delete(self.column, key.as_bytes()); deletes += 1; } } diff --git a/crates/db/journaldb/src/earlymergedb.rs b/crates/db/journaldb/src/earlymergedb.rs index 2d1c5be69..4455ff43e 100644 --- a/crates/db/journaldb/src/earlymergedb.rs +++ b/crates/db/journaldb/src/earlymergedb.rs @@ -29,25 +29,19 @@ use bytes::Bytes; use ethcore_db::{DBTransaction, DBValue, KeyValueDB}; use ethereum_types::H256; use hash_db::HashDB; -use heapsize::HeapSizeOf; use keccak_hasher::KeccakHasher; use memory_db::*; +use parity_util_mem::MallocSizeOf; use parking_lot::RwLock; use rlp::{decode, encode}; use util::{DatabaseKey, DatabaseValueRef, DatabaseValueView}; -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq, MallocSizeOf)] struct RefInfo { queue_refs: usize, in_archive: bool, } -impl HeapSizeOf for RefInfo { - fn heap_size_of_children(&self) -> usize { - 0 - } -} - #[derive(Clone, PartialEq, Eq)] enum RemoveFrom { Queue, @@ -133,7 +127,7 @@ impl EarlyMergeDB { } fn morph_key(key: &H256, index: u8) -> Bytes { - let mut ret = (&**key).to_owned(); + let mut ret = key.as_bytes().to_owned(); ret.push(index); ret } @@ -170,7 +164,7 @@ impl EarlyMergeDB { Entry::Vacant(entry) => { // this is the first entry for this node in the journal. let in_archive = backing - .get(col, h) + .get(col, h.as_bytes()) .expect("Low-level database error. Some issue with your hard disk?") .is_some(); if in_archive { @@ -182,7 +176,7 @@ impl EarlyMergeDB { //Self::reset_already_in(&h); assert!(!Self::is_already_in(backing, col, h)); trace!(target: "jdb.fine", " insert({}): New to queue, not in DB: Inserting into queue and DB", h); - batch.put(col, h, d); + batch.put(col, h.as_bytes(), d); } entry.insert(RefInfo { queue_refs: 1, @@ -258,7 +252,7 @@ impl EarlyMergeDB { } (1, false) => { entry.remove(); - batch.delete(col, h); + batch.delete(col, h.as_bytes()); trace!(target: "jdb.fine", " remove({}): Not in archive, only 1 ref in queue: Removing from queue and DB", h); } _ => panic!("Invalid value in refs: {:?}", entry.get()), @@ -267,7 +261,7 @@ impl EarlyMergeDB { Entry::Vacant(_entry) => { // Gets removed when moving from 1 to 0 additional refs. Should never be here at 0 additional refs. //assert!(!Self::is_already_in(db, &h)); - batch.delete(col, h); + batch.delete(col, h.as_bytes()); trace!(target: "jdb.fine", " remove({}): Not in queue - MUST BE IN ARCHIVE: Removing from DB", h); } } @@ -308,7 +302,7 @@ impl EarlyMergeDB { fn payload(&self, key: &H256) -> Option { self.backing - .get(self.column, key) + .get(self.column, key.as_bytes()) .expect("Low-level database error. Some issue with your hard disk?") } @@ -593,16 +587,16 @@ impl JournalDB for EarlyMergeDB { match rc { 0 => {} 1 => { - if self.backing.get(self.column, &key)?.is_some() { + if self.backing.get(self.column, key.as_bytes())?.is_some() { return Err(error_key_already_exists(&key)); } - batch.put(self.column, &key, &value) + batch.put(self.column, key.as_bytes(), &value) } -1 => { - if self.backing.get(self.column, &key)?.is_none() { + if self.backing.get(self.column, key.as_bytes())?.is_none() { return Err(error_negatively_reference_hash(&key)); } - batch.delete(self.column, &key) + batch.delete(self.column, key.as_bytes()) } _ => panic!("Attempted to inject invalid state."), } diff --git a/crates/db/journaldb/src/lib.rs b/crates/db/journaldb/src/lib.rs index 1365302f5..4ac6da48c 100644 --- a/crates/db/journaldb/src/lib.rs +++ b/crates/db/journaldb/src/lib.rs @@ -16,7 +16,6 @@ //! `JournalDB` interface and implementation. -extern crate heapsize; #[macro_use] extern crate log; @@ -28,6 +27,7 @@ extern crate keccak_hasher; extern crate kvdb; extern crate memory_db; extern crate parity_bytes as bytes; +extern crate parity_util_mem; extern crate parking_lot; extern crate rlp; diff --git a/crates/db/journaldb/src/overlaydb.rs b/crates/db/journaldb/src/overlaydb.rs index 5df5d0bc4..c11db5a3b 100644 --- a/crates/db/journaldb/src/overlaydb.rs +++ b/crates/db/journaldb/src/overlaydb.rs @@ -149,7 +149,7 @@ impl OverlayDB { /// Get the refs and value of the given key. fn payload(&self, key: &H256) -> Option { self.backing - .get(self.column, key) + .get(self.column, key.as_bytes()) .expect("Low-level database error. Some issue with your hard disk?") .map(|ref d| decode(d).expect("decoding db value failed")) } @@ -162,10 +162,10 @@ impl OverlayDB { payload: &Payload, ) -> bool { if payload.count > 0 { - batch.put(self.column, key, &encode(payload)); + batch.put(self.column, key.as_bytes(), &encode(payload)); false } else { - batch.delete(self.column, key); + batch.delete(self.column, key.as_bytes()); true } } diff --git a/crates/db/journaldb/src/overlayrecentdb.rs b/crates/db/journaldb/src/overlayrecentdb.rs index 84ae4b3ad..cd7eb171a 100644 --- a/crates/db/journaldb/src/overlayrecentdb.rs +++ b/crates/db/journaldb/src/overlayrecentdb.rs @@ -27,9 +27,9 @@ use ethcore_db::{DBTransaction, DBValue, KeyValueDB}; use ethereum_types::H256; use fastmap::H256FastMap; use hash_db::HashDB; -use heapsize::HeapSizeOf; use keccak_hasher::KeccakHasher; use memory_db::*; +use parity_util_mem::MallocSizeOf; use parking_lot::RwLock; use rlp::{decode, encode, Decodable, DecoderError, Encodable, Rlp, RlpStream}; use util::DatabaseKey; @@ -132,19 +132,13 @@ struct JournalOverlay { cumulative_size: usize, // cumulative size of all entries. } -#[derive(PartialEq)] +#[derive(PartialEq, MallocSizeOf)] struct JournalEntry { id: H256, insertions: Vec, deletions: Vec, } -impl HeapSizeOf for JournalEntry { - fn heap_size_of_children(&self) -> usize { - self.insertions.heap_size_of_children() + self.deletions.heap_size_of_children() - } -} - impl Clone for OverlayRecentDB { fn clone(&self) -> OverlayRecentDB { OverlayRecentDB { @@ -181,7 +175,7 @@ impl OverlayRecentDB { fn payload(&self, key: &H256) -> Option { self.backing - .get(self.column, key) + .get(self.column, key.as_bytes()) .expect("Low-level database error. Some issue with your hard disk?") } @@ -256,7 +250,7 @@ impl OverlayRecentDB { #[inline] fn to_short_key(key: &H256) -> H256 { - let mut k = H256::new(); + let mut k = H256::zero(); k[0..DB_PREFIX_LEN].copy_from_slice(&key[0..DB_PREFIX_LEN]); k } @@ -453,7 +447,7 @@ impl JournalDB for OverlayRecentDB { // apply canon inserts first for (k, v) in canon_insertions { - batch.put(self.column, &k, &v); + batch.put(self.column, k.as_bytes(), &v); journal_overlay.pending_overlay.insert(to_short_key(&k), v); } // update the overlay @@ -468,7 +462,7 @@ impl JournalDB for OverlayRecentDB { // apply canon deletions for k in canon_deletions { if !journal_overlay.backing_overlay.contains(&to_short_key(&k)) { - batch.delete(self.column, &k); + batch.delete(self.column, k.as_bytes()); } } } @@ -496,12 +490,14 @@ impl JournalDB for OverlayRecentDB { match rc { 0 => {} - _ if rc > 0 => batch.put(self.column, &key, &value), + _ if rc > 0 => batch.put(self.column, key.as_bytes(), &value), -1 => { - if cfg!(debug_assertions) && self.backing.get(self.column, &key)?.is_none() { + if cfg!(debug_assertions) + && self.backing.get(self.column, key.as_bytes())?.is_none() + { return Err(error_negatively_reference_hash(&key)); } - batch.delete(self.column, &key) + batch.delete(self.column, key.as_bytes()) } _ => panic!("Attempted to inject invalid state ({})", rc), } diff --git a/crates/db/journaldb/src/refcounteddb.rs b/crates/db/journaldb/src/refcounteddb.rs index 73ac77945..15b353c6e 100644 --- a/crates/db/journaldb/src/refcounteddb.rs +++ b/crates/db/journaldb/src/refcounteddb.rs @@ -26,10 +26,10 @@ use super::{traits::JournalDB, LATEST_ERA_KEY}; use ethcore_db::{DBTransaction, DBValue, KeyValueDB}; use ethereum_types::H256; use hash_db::HashDB; -use heapsize::HeapSizeOf; use keccak_hasher::KeccakHasher; use memory_db::MemoryDB; use overlaydb::OverlayDB; +use parity_util_mem::{allocators::new_malloc_size_ops, MallocSizeOf}; use rlp::{decode, encode}; use util::{DatabaseKey, DatabaseValueRef, DatabaseValueView}; @@ -121,13 +121,14 @@ impl JournalDB for RefCountedDB { } fn get_sizes(&self, sizes: &mut BTreeMap) { + let mut ops = new_malloc_size_ops(); sizes.insert( String::from("db_ref_counted_inserts"), - self.inserts.heap_size_of_children(), + self.inserts.size_of(&mut ops), ); sizes.insert( String::from("db_ref_counted_removes"), - self.removes.heap_size_of_children(), + self.removes.size_of(&mut ops), ); } diff --git a/crates/db/memory-db/Cargo.toml b/crates/db/memory-db/Cargo.toml index 03af7f22a..90c3cd895 100644 --- a/crates/db/memory-db/Cargo.toml +++ b/crates/db/memory-db/Cargo.toml @@ -21,13 +21,15 @@ repository = "https://github.com/paritytech/parity-common" [[bench]] name = "bench" harness = false -[dependencies.hash-db] -version = "0.11.0" -[dependencies.heapsize] -version = "0.4" +[dependencies] +hash-db = "0.11.0" + [dev-dependencies.criterion] version = "0.2.8" [dev-dependencies.keccak-hasher] -version = "0.11.0" \ No newline at end of file +version = "0.11.0" + +[dependencies.parity-util-mem] +version = "0.7" diff --git a/crates/db/memory-db/src/lib.rs b/crates/db/memory-db/src/lib.rs index c7bf97eb8..7baa58cab 100644 --- a/crates/db/memory-db/src/lib.rs +++ b/crates/db/memory-db/src/lib.rs @@ -15,12 +15,13 @@ //! Reference-counted memory-based `HashDB` implementation. extern crate hash_db; -extern crate heapsize; +extern crate parity_util_mem; + #[cfg(test)] extern crate keccak_hasher; use hash_db::{AsHashDB, AsPlainDB, HashDB, HashDBRef, Hasher as KeyHasher, PlainDB, PlainDBRef}; -use heapsize::HeapSizeOf; +use parity_util_mem::MallocSizeOf; use std::{ collections::{hash_map::Entry, HashMap}, hash, mem, @@ -233,12 +234,15 @@ where impl MemoryDB where H: KeyHasher, - T: HeapSizeOf, + T: MallocSizeOf, { /// Returns the size of allocated heap memory pub fn mem_used(&self) -> usize { - 0 //self.data.heap_size_of_children() - // TODO Reenable above when HeapSizeOf supports arrays. + // TODO: figure out how to call malloc_size_of() + //let mut ops = new_malloc_size_ops(); + //self.data.size_of(&mut ops) + //self.data.malloc_size_of() + 0 } } diff --git a/crates/db/patricia-trie-ethereum/Cargo.toml b/crates/db/patricia-trie-ethereum/Cargo.toml index 1a2bdf344..1064bdb30 100644 --- a/crates/db/patricia-trie-ethereum/Cargo.toml +++ b/crates/db/patricia-trie-ethereum/Cargo.toml @@ -9,12 +9,12 @@ license = "GPL-3.0" trie-db = "0.11.0" keccak-hasher = { version = "0.1.1", path = "../../util/keccak-hasher" } hash-db = "0.11.0" -rlp = { version = "0.3.0", features = ["ethereum"] } +rlp = { version = "0.4.6" } parity-bytes = "0.1" -ethereum-types = "0.4" +ethereum-types = "0.9.2" elastic-array = "0.10" [dev-dependencies] memory-db = "0.11.0" -keccak-hash = "0.1.2" +keccak-hash = "0.5.0" journaldb = { path = "../journaldb" } diff --git a/crates/db/patricia-trie-ethereum/src/lib.rs b/crates/db/patricia-trie-ethereum/src/lib.rs index 4dc474853..d6828ee70 100644 --- a/crates/db/patricia-trie-ethereum/src/lib.rs +++ b/crates/db/patricia-trie-ethereum/src/lib.rs @@ -63,7 +63,7 @@ pub type RlpCodec = RlpNodeCodec; /// /// fn main() { /// let mut memdb = journaldb::new_memory_db(); -/// let mut root = H256::new(); +/// let mut root = H256::default(); /// TrieDBMut::new(&mut memdb, &mut root).insert(b"foo", b"bar").unwrap(); /// let t = TrieDB::new(&memdb, &root).unwrap(); /// assert!(t.contains(b"foo").unwrap()); @@ -107,7 +107,7 @@ pub type FatDB<'db> = trie::FatDB<'db, KeccakHasher, RlpCodec>; /// /// fn main() { /// let mut memdb = journaldb::new_memory_db(); -/// let mut root = H256::new(); +/// let mut root = H256::default(); /// let mut t = TrieDBMut::new(&mut memdb, &mut root); /// assert!(t.is_empty()); /// assert_eq!(*t.root(), KECCAK_NULL_RLP); diff --git a/crates/ethcore/Cargo.toml b/crates/ethcore/Cargo.toml index ab6eba7a0..1d18f1648 100644 --- a/crates/ethcore/Cargo.toml +++ b/crates/ethcore/Cargo.toml @@ -14,9 +14,9 @@ crossbeam-utils = "0.6" eip-152 = { version = "0.1", path = "../util/EIP-152" } env_logger = { version = "0.5", optional = true } error-chain = { version = "0.12", default-features = false } -ethabi = "6.0" -ethabi-contract = "6.0" -ethabi-derive = "6.0" +ethabi = "12.0.0" +ethabi-contract = "11.0.0" +ethabi-derive = "12.0.0" ethash = { path = "../concensus/ethash" } ethcore-blockchain = { path = "./blockchain" } ethcore-bloom-journal = { path = "../db/bloom" } @@ -26,16 +26,15 @@ ethcore-db = { path = "../db/db" } ethcore-io = { path = "../runtime/io" } ethcore-miner = { path = "../concensus/miner" } ethcore-stratum = { path = "../concensus/miner/stratum", optional = true } -ethereum-types = "0.4" +ethereum-types = "0.9.2" ethjson = { path = "../ethjson" } ethkey = { path = "../accounts/ethkey" } evm = { path = "../vm/evm" } globset = "0.4" hash-db = "0.11.0" -heapsize = "0.4" itertools = "0.5" journaldb = { path = "../db/journaldb" } -keccak-hash = "0.1" +keccak-hash = "0.5.0" keccak-hasher = { path = "../util/keccak-hasher" } kvdb = "0.1" kvdb-memorydb = "0.1" @@ -50,14 +49,17 @@ memory-cache = { path = "../util/memory-cache" } memory-db = { path = "../db/memory-db" } num_cpus = "1.2" parity-bytes = "0.1" +parity-crypto = { version = "0.6.2", features = [ "publickey" ] } parity-snappy = "0.1" +parity-util-mem = "0.7" parking_lot = "0.7" trie-db = "0.11.0" patricia-trie-ethereum = { path = "../db/patricia-trie-ethereum" } -rand = "0.4" +rand = "0.7.3" +rand_xorshift = "0.2.0" rayon = "1.1" regex = "1.3.9" -rlp = { version = "0.3.0", features = ["ethereum"] } +rlp = { version = "0.4.6" } rlp_derive = { path = "../util/rlp-derive" } rustc-hex = "1.0" serde = "1.0" @@ -87,7 +89,7 @@ kvdb-rocksdb = "0.1.3" parity-runtime = { path = "../runtime/runtime" } rlp_compress = { path = "../util/rlp-compress" } tempdir = "0.3" -trie-standardmap = "0.1" +trie-standardmap = "0.15.2" [features] parity = ["work-notify", "price-info", "stratum"] diff --git a/crates/ethcore/benches/builtin.rs b/crates/ethcore/benches/builtin.rs index 6eaf50562..47c6cd568 100644 --- a/crates/ethcore/benches/builtin.rs +++ b/crates/ethcore/benches/builtin.rs @@ -25,10 +25,13 @@ extern crate ethereum_types; extern crate parity_bytes as bytes; extern crate rustc_hex; +use std::str::FromStr; + use bytes::BytesRef; use criterion::{Bencher, Criterion}; use ethcore::{ethereum::new_byzantium_test_machine, machine::EthereumMachine}; use ethcore_builtin::Builtin; +use ethereum_types::H160; use rustc_hex::FromHex; lazy_static! { @@ -45,7 +48,10 @@ impl<'a> BuiltinBenchmark<'a> { fn new(builtin_address: &'static str, input: &str, expected: &str) -> BuiltinBenchmark<'a> { let builtins = BYZANTIUM_MACHINE.builtins(); - let builtin = builtins.get(&builtin_address.into()).unwrap().clone(); + let builtin = builtins + .get(&H160::from_str(builtin_address).unwrap()) + .unwrap() + .clone(); let input = FromHex::from_hex(input).unwrap(); let expected = FromHex::from_hex(expected).unwrap(); diff --git a/crates/ethcore/blockchain/Cargo.toml b/crates/ethcore/blockchain/Cargo.toml index 75f3135a5..4c93eb8a4 100644 --- a/crates/ethcore/blockchain/Cargo.toml +++ b/crates/ethcore/blockchain/Cargo.toml @@ -12,17 +12,18 @@ ansi_term = "0.11" blooms-db = { path = "../../db/blooms-db" } common-types = { path = "../types" } ethcore-db = { path = "../../db/db" } -ethereum-types = "0.4" -heapsize = "0.4" +ethereum-types = "0.9.2" itertools = "0.5" -keccak-hash = "0.1" +keccak-hash = "0.5.0" kvdb = "0.1" log = "0.4" parity-bytes = "0.1" +parity-crypto = { version = "0.6.2", features = [ "publickey" ] } +parity-util-mem = "0.7" parking_lot = "0.7" -rand = "0.6" +rand = "0.7.3" rayon = "1.1" -rlp = { version = "0.3.0", features = ["ethereum"] } +rlp = { version = "0.4.6" } rlp_compress = { path = "../../util/rlp-compress" } rlp_derive = { path = "../../util/rlp-derive" } triehash-ethereum = { version = "0.2", path = "../../util/triehash-ethereum" } diff --git a/crates/ethcore/blockchain/src/blockchain.rs b/crates/ethcore/blockchain/src/blockchain.rs index 1363304ff..76778d34b 100644 --- a/crates/ethcore/blockchain/src/blockchain.rs +++ b/crates/ethcore/blockchain/src/blockchain.rs @@ -49,10 +49,10 @@ use ethcore_db::{ CacheUpdatePolicy, Readable, Writable, }; use ethereum_types::{Bloom, BloomRef, H256, U256}; -use heapsize::HeapSizeOf; use itertools::Itertools; use log::{info, trace, warn}; use parity_bytes::Bytes; +use parity_util_mem::{allocators::new_malloc_size_ops, MallocSizeOf}; use parking_lot::{Mutex, RwLock}; use rayon::prelude::*; use rlp::RlpStream; @@ -324,9 +324,13 @@ impl BlockProvider for BlockChain { } // Read from DB and populate cache - let b = self.db.key_value().get(db::COL_HEADERS, hash).expect( - "Low level database error when fetching block header data. Some issue with disk?", - )?; + let b = self + .db + .key_value() + .get(db::COL_HEADERS, hash.as_bytes()) + .expect( + "Low level database error when fetching block header data. Some issue with disk?", + )?; let header = encoded::Header::new(decompress(&b, blocks_swapper()).into_vec()); let mut write = self.block_headers.write(); @@ -357,9 +361,13 @@ impl BlockProvider for BlockChain { } // Read from DB and populate cache - let b = self.db.key_value().get(db::COL_BODIES, hash).expect( - "Low level database error when fetching block body data. Some issue with disk?", - )?; + let b = self + .db + .key_value() + .get(db::COL_BODIES, hash.as_bytes()) + .expect( + "Low level database error when fetching block body data. Some issue with disk?", + )?; let body = encoded::Body::new(decompress(&b, blocks_swapper()).into_vec()); let mut write = self.block_bodies.write(); @@ -672,13 +680,21 @@ impl BlockChain { }; let mut batch = DBTransaction::new(); - batch.put(db::COL_HEADERS, &hash, block.header_rlp().as_raw()); - batch.put(db::COL_BODIES, &hash, &Self::block_to_body(genesis)); + batch.put( + db::COL_HEADERS, + hash.as_bytes(), + block.header_rlp().as_raw(), + ); + batch.put( + db::COL_BODIES, + hash.as_bytes(), + &Self::block_to_body(genesis), + ); batch.write(db::COL_EXTRA, &hash, &details); batch.write(db::COL_EXTRA, &header.number(), &hash); - batch.put(db::COL_EXTRA, b"best", &hash); + batch.put(db::COL_EXTRA, b"best", hash.as_bytes()); bc.db.key_value().write(batch).expect( "Low level database error when fetching 'best' block. Some issue with disk?", ); @@ -752,7 +768,7 @@ impl BlockChain { if hash != bc.genesis_hash() { info!("First new block calculated: {:?}", hash); let mut batch = db.key_value().transaction(); - batch.put(db::COL_EXTRA, b"first", &hash); + batch.put(db::COL_EXTRA, b"first", hash.as_bytes()); db.key_value().write(batch).expect("Low level database error when writing 'first' block. Some issue with disk?"); bc.first_block = Some(hash); } @@ -916,8 +932,8 @@ impl BlockChain { let compressed_body = compress(&Self::block_to_body(block.raw()), blocks_swapper()); // store block in db - batch.put(db::COL_HEADERS, &hash, &compressed_header); - batch.put(db::COL_BODIES, &hash, &compressed_body); + batch.put(db::COL_HEADERS, hash.as_bytes(), &compressed_header); + batch.put(db::COL_BODIES, hash.as_bytes(), &compressed_body); let maybe_parent = self.uncommitted_block_details(&block_parent_hash); @@ -1115,7 +1131,7 @@ impl BlockChain { *pending_best_ancient_block = Some(None); } else if block_number > ancient_number { trace!(target: "blockchain", "Updating the best ancient block to {}.", block_number); - batch.put(db::COL_EXTRA, b"ancient", &block_hash); + batch.put(db::COL_EXTRA, b"ancient", block_hash.as_bytes()); *pending_best_ancient_block = Some(Some(BestAncientBlock { hash: *block_hash, number: block_number, @@ -1301,8 +1317,8 @@ impl BlockChain { let compressed_body = compress(&Self::block_to_body(block.raw()), blocks_swapper()); // store block in db - batch.put(db::COL_HEADERS, &hash, &compressed_header); - batch.put(db::COL_BODIES, &hash, &compressed_body); + batch.put(db::COL_HEADERS, hash.as_bytes(), &compressed_header); + batch.put(db::COL_BODIES, hash.as_bytes(), &compressed_body); let info = self.block_info(&block.header_view(), route, &extras); @@ -1444,7 +1460,7 @@ impl BlockChain { { let mut best_block = self.pending_best_block.write(); if is_best && update.info.location != BlockLocation::Branch { - batch.put(db::COL_EXTRA, b"best", &update.info.hash); + batch.put(db::COL_EXTRA, b"best", update.info.hash.as_bytes()); *best_block = Some(BestBlock { total_difficulty: update.info.total_difficulty, header: update.block.decode_header(), @@ -1818,12 +1834,13 @@ impl BlockChain { /// Get current cache size. pub fn cache_size(&self) -> CacheSize { + let mut ops = new_malloc_size_ops(); CacheSize { - blocks: self.block_headers.read().heap_size_of_children() - + self.block_bodies.read().heap_size_of_children(), - block_details: self.block_details.read().heap_size_of_children(), - transaction_addresses: self.transaction_addresses.read().heap_size_of_children(), - block_receipts: self.block_receipts.read().heap_size_of_children(), + blocks: self.block_headers.read().size_of(&mut ops) + + self.block_bodies.read().size_of(&mut ops), + block_details: self.block_details.read().size_of(&mut ops), + transaction_addresses: self.transaction_addresses.read().size_of(&mut ops), + block_receipts: self.block_receipts.read().size_of(&mut ops), } } @@ -1870,12 +1887,13 @@ impl BlockChain { transaction_addresses.shrink_to_fit(); block_receipts.shrink_to_fit(); - block_headers.heap_size_of_children() - + block_bodies.heap_size_of_children() - + block_details.heap_size_of_children() - + block_hashes.heap_size_of_children() - + transaction_addresses.heap_size_of_children() - + block_receipts.heap_size_of_children() + let mut ops = new_malloc_size_ops(); + block_headers.size_of(&mut ops) + + block_bodies.size_of(&mut ops) + + block_details.size_of(&mut ops) + + block_hashes.size_of(&mut ops) + + transaction_addresses.size_of(&mut ops) + + block_receipts.size_of(&mut ops) }); } @@ -1918,14 +1936,14 @@ impl BlockChain { mod tests { use super::*; - use std::iter; + use std::{iter, str::FromStr}; use crate::generator::{BlockBuilder, BlockGenerator, BlockOptions}; use common_types::{ receipt::{LegacyReceipt, TransactionOutcome, TypedReceipt}, transaction::{Action, Transaction, TypedTransaction}, }; - use ethkey::Secret; + use crypto::publickey::Secret; use keccak_hash::keccak; use rustc_hex::FromHex; use tempdir::TempDir; @@ -2492,8 +2510,9 @@ mod tests { fn find_transaction_by_hash() { let genesis = "f901fcf901f7a00000000000000000000000000000000000000000000000000000000000000000a01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347948888f1f195afa192cfee860698584c030f4c9db1a0af81e09f8c46ca322193edfda764fa7e88e81923f802f1d325ec0b0308ac2cd0a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421b9010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000830200008083023e38808454c98c8142a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421880102030405060708c0c0".from_hex().unwrap(); let b1 = "f904a8f901faa0ce1f26f798dd03c8782d63b3e42e79a64eaea5694ea686ac5d7ce3df5171d1aea01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347948888f1f195afa192cfee860698584c030f4c9db1a0a65c2364cd0f1542d761823dc0109c6b072f14c20459598c5455c274601438f4a070616ebd7ad2ed6fb7860cf7e9df00163842351c38a87cac2c1cb193895035a2a05c5b4fc43c2d45787f54e1ae7d27afdb4ad16dfc567c5692070d5c4556e0b1d7b9010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000830200000183023ec683021536845685109780a029f07836e4e59229b3a065913afc27702642c683bba689910b2b2fd45db310d3888957e6d004a31802f902a7f85f800a8255f094aaaf5374fce5edbc8e2a8697c15331677e6ebf0b0a801ca0575da4e21b66fa764be5f74da9389e67693d066fb0d1312e19e17e501da00ecda06baf5a5327595f6619dfc2fcb3f2e6fb410b5810af3cb52d0e7508038e91a188f85f010a82520894bbbf5374fce5edbc8e2a8697c15331677e6ebf0b0a801ba04fa966bf34b93abc1bcd665554b7f316b50f928477b50be0f3285ead29d18c5ba017bba0eeec1625ab433746955e125d46d80b7fdc97386c51266f842d8e02192ef85f020a82520894bbbf5374fce5edbc8e2a8697c15331677e6ebf0b0a801ca004377418ae981cc32b1312b4a427a1d69a821b28db8584f5f2bd8c6d42458adaa053a1dba1af177fac92f3b6af0a9fa46a22adf56e686c93794b6a012bf254abf5f85f030a82520894bbbf5374fce5edbc8e2a8697c15331677e6ebf0b0a801ca04fe13febd28a05f4fcb2f451d7ddc2dda56486d9f8c79a62b0ba4da775122615a0651b2382dd402df9ebc27f8cb4b2e0f3cea68dda2dca0ee9603608f0b6f51668f85f040a82520894bbbf5374fce5edbc8e2a8697c15331677e6ebf0b0a801ba078e6a0ba086a08f8450e208a399bb2f2d2a0d984acd2517c7c7df66ccfab567da013254002cd45a97fac049ae00afbc43ed0d9961d0c56a3b2382c80ce41c198ddf85f050a82520894bbbf5374fce5edbc8e2a8697c15331677e6ebf0b0a801ba0a7174d8f43ea71c8e3ca9477691add8d80ac8e0ed89d8d8b572041eef81f4a54a0534ea2e28ec4da3b5b944b18c51ec84a5cf35f5b3343c5fb86521fd2d388f506f85f060a82520894bbbf5374fce5edbc8e2a8697c15331677e6ebf0b0a801ba034bd04065833536a10c77ee2a43a5371bc6d34837088b861dd9d4b7f44074b59a078807715786a13876d3455716a6b9cb2186b7a4887a5c31160fc877454958616c0".from_hex().unwrap(); - let b1_hash: H256 = - "f53f268d23a71e85c7d6d83a9504298712b84c1a2ba220441c86eeda0bf0b6e3".into(); + let b1_hash = + H256::from_str("f53f268d23a71e85c7d6d83a9504298712b84c1a2ba220441c86eeda0bf0b6e3") + .unwrap(); let db = new_db(); let bc = new_chain(encoded::Block::new(genesis), db.clone()); @@ -2745,11 +2764,11 @@ mod tests { #[test] fn test_bloom_filter_simple() { - let bloom_b1: Bloom = "00000020000000000000000000000000000000000000000002000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000040000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008000400000000000000000000002000".into(); + let bloom_b1 = Bloom::from_str("00000020000000000000000000000000000000000000000002000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000040000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008000400000000000000000000002000").unwrap(); - let bloom_b2: Bloom = "00000000000000000000000000000000000000000000020000001000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000008000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000000000000000000000000000002000000000000000000040000000000000000000000000000000000000000000000000000000000000000000000000000000000000000".into(); + let bloom_b2 = Bloom::from_str("00000000000000000000000000000000000000000000020000001000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000008000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000000000000000000000000000002000000000000000000040000000000000000000000000000000000000000000000000000000000000000000000000000000000000000").unwrap(); - let bloom_ba: Bloom = "00000000000000000000000000000000000000000000020000000800000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000008000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000000000000000000000000000002000000000000000000040000000000000000000000000000000000000000000000000000000000000000000000000000000000000000".into(); + let bloom_ba = Bloom::from_str("00000000000000000000000000000000000000000000020000000800000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000008000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000000000000000000000000000002000000000000000000040000000000000000000000000000000000000000000000000000000000000000000000000000000000000000").unwrap(); let genesis = BlockBuilder::genesis(); let b1 = genesis.add_block_with(|| BlockOptions { @@ -2813,11 +2832,11 @@ mod tests { #[test] fn test_insert_unordered() { - let bloom_b1: Bloom = "00000020000000000000000000000000000000000000000002000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000040000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008000400000000000000000000002000".into(); + let bloom_b1 = Bloom::from_str("00000020000000000000000000000000000000000000000002000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000040000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008000400000000000000000000002000").unwrap(); - let bloom_b2: Bloom = "00000000000000000000000000000000000000000000020000001000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000008000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000000000000000000000000000002000000000000000000040000000000000000000000000000000000000000000000000000000000000000000000000000000000000000".into(); + let bloom_b2 = Bloom::from_str("00000000000000000000000000000000000000000000020000001000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000008000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000000000000000000000000000002000000000000000000040000000000000000000000000000000000000000000000000000000000000000000000000000000000000000").unwrap(); - let bloom_b3: Bloom = "00000000000000000000000000000000000000000000020000000800000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000008000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000000000000000000000000000002000000000000000000040000000000000000000000000000000000000000000000000000000000000000000000000000000000000000".into(); + let bloom_b3 = Bloom::from_str("00000000000000000000000000000000000000000000020000000800000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000008000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000000000000000000000000000002000000000000000000040000000000000000000000000000000000000000000000000000000000000000000000000000000000000000").unwrap(); let genesis = BlockBuilder::genesis(); let b1 = genesis.add_block_with_bloom(bloom_b1); diff --git a/crates/ethcore/blockchain/src/import_route.rs b/crates/ethcore/blockchain/src/import_route.rs index 126b5068a..6519eb653 100644 --- a/crates/ethcore/blockchain/src/import_route.rs +++ b/crates/ethcore/blockchain/src/import_route.rs @@ -70,7 +70,7 @@ impl From for ImportRoute { mod tests { use super::ImportRoute; use crate::block_info::{BlockInfo, BlockLocation, BranchBecomingCanonChainData}; - use ethereum_types::{H256, U256}; + use ethereum_types::{BigEndianHash, U256}; #[test] fn import_route_none() { @@ -87,7 +87,7 @@ mod tests { #[test] fn import_route_branch() { let info = BlockInfo { - hash: H256::from(U256::from(1)), + hash: BigEndianHash::from_uint(&U256::from(1)), number: 0, total_difficulty: U256::from(0), location: BlockLocation::Branch, @@ -98,7 +98,7 @@ mod tests { ImportRoute { retracted: vec![], enacted: vec![], - omitted: vec![H256::from(U256::from(1))], + omitted: vec![BigEndianHash::from_uint(&U256::from(1))], } ); } @@ -106,7 +106,7 @@ mod tests { #[test] fn import_route_canon_chain() { let info = BlockInfo { - hash: H256::from(U256::from(1)), + hash: BigEndianHash::from_uint(&U256::from(1)), number: 0, total_difficulty: U256::from(0), location: BlockLocation::CanonChain, @@ -116,7 +116,7 @@ mod tests { ImportRoute::from(info), ImportRoute { retracted: vec![], - enacted: vec![H256::from(U256::from(1))], + enacted: vec![BigEndianHash::from_uint(&U256::from(1))], omitted: vec![], } ); @@ -125,21 +125,30 @@ mod tests { #[test] fn import_route_branch_becoming_canon_chain() { let info = BlockInfo { - hash: H256::from(U256::from(2)), + hash: BigEndianHash::from_uint(&U256::from(2)), number: 0, total_difficulty: U256::from(0), location: BlockLocation::BranchBecomingCanonChain(BranchBecomingCanonChainData { - ancestor: H256::from(U256::from(0)), - enacted: vec![H256::from(U256::from(1))], - retracted: vec![H256::from(U256::from(3)), H256::from(U256::from(4))], + ancestor: BigEndianHash::from_uint(&U256::from(0)), + enacted: vec![BigEndianHash::from_uint(&U256::from(1))], + retracted: vec![ + BigEndianHash::from_uint(&U256::from(3)), + BigEndianHash::from_uint(&U256::from(4)), + ], }), }; assert_eq!( ImportRoute::from(info), ImportRoute { - retracted: vec![H256::from(U256::from(3)), H256::from(U256::from(4))], - enacted: vec![H256::from(U256::from(1)), H256::from(U256::from(2))], + retracted: vec![ + BigEndianHash::from_uint(&U256::from(3)), + BigEndianHash::from_uint(&U256::from(4)) + ], + enacted: vec![ + BigEndianHash::from_uint(&U256::from(1)), + BigEndianHash::from_uint(&U256::from(2)) + ], omitted: vec![], } ); diff --git a/crates/ethcore/blockchain/src/lib.rs b/crates/ethcore/blockchain/src/lib.rs index 943bc3c89..38284cd40 100644 --- a/crates/ethcore/blockchain/src/lib.rs +++ b/crates/ethcore/blockchain/src/lib.rs @@ -18,6 +18,8 @@ #![warn(missing_docs)] +extern crate parity_crypto as crypto; + mod best_block; mod block_info; mod blockchain; diff --git a/crates/ethcore/service/Cargo.toml b/crates/ethcore/service/Cargo.toml index cd0f9e112..bab712483 100644 --- a/crates/ethcore/service/Cargo.toml +++ b/crates/ethcore/service/Cargo.toml @@ -11,7 +11,7 @@ ethcore = { path = ".." } ethcore-blockchain = { path = "../blockchain" } ethcore-io = { path = "../../runtime/io" } ethcore-sync = { path = "../sync" } -ethereum-types = "0.4" +ethereum-types = "0.9.2" kvdb = "0.1" log = "0.4" trace-time = "0.1" diff --git a/crates/ethcore/src/account_db.rs b/crates/ethcore/src/account_db.rs index d0464cf2e..b3e50b163 100644 --- a/crates/ethcore/src/account_db.rs +++ b/crates/ethcore/src/account_db.rs @@ -31,8 +31,8 @@ use ethereum_types::Address; fn combine_key<'a>(address_hash: &'a H256, key: &'a H256) -> H256 { let mut dst = key.clone(); { - let last_src: &[u8] = &*address_hash; - let last_dst: &mut [u8] = &mut *dst; + let last_src: &[u8] = address_hash.as_bytes(); + let last_dst: &mut [u8] = dst.as_bytes_mut(); for (k, a) in last_dst[12..].iter_mut().zip(&last_src[12..]) { *k ^= *a } diff --git a/crates/ethcore/src/block.rs b/crates/ethcore/src/block.rs index eee50c46d..9c31849f6 100644 --- a/crates/ethcore/src/block.rs +++ b/crates/ethcore/src/block.rs @@ -662,7 +662,7 @@ mod tests { db, parent, last_hashes, - Address::new(), + Address::default(), (3141562.into(), 31415620.into()), vec![], false, diff --git a/crates/ethcore/src/client/client.rs b/crates/ethcore/src/client/client.rs index 5f183ba04..46b8eb419 100644 --- a/crates/ethcore/src/client/client.rs +++ b/crates/ethcore/src/client/client.rs @@ -40,7 +40,7 @@ use ethereum_types::{Address, H256, H264, U256}; use hash::keccak; use itertools::Itertools; use parking_lot::{Mutex, RwLock}; -use rand::OsRng; +use rand::rngs::OsRng; use rlp::{PayloadInfo, Rlp}; use rustc_hex::FromHex; use trie::{Trie, TrieFactory, TrieSpec}; @@ -541,7 +541,7 @@ impl Importer { { trace_time!("import_old_block"); // verify the block, passing the chain for updating the epoch verifier. - let mut rng = OsRng::new()?; + let mut rng = OsRng; self.ancient_verifier .verify(&mut rng, &unverified.header, &chain)?; @@ -1641,8 +1641,8 @@ impl BlockChainReset for Client { best_block_hash = current_header.parent_hash(); let (number, hash) = (current_header.number(), current_header.hash()); - batch.delete(::db::COL_HEADERS, &hash); - batch.delete(::db::COL_BODIES, &hash); + batch.delete(::db::COL_HEADERS, hash.as_bytes()); + batch.delete(::db::COL_BODIES, hash.as_bytes()); Writable::delete::(&mut batch, ::db::COL_EXTRA, &hash); Writable::delete::(&mut batch, ::db::COL_EXTRA, &number); @@ -1673,7 +1673,7 @@ impl BlockChainReset for Client { best_block_details.children.retain(|h| *h != *last_hash); batch.write(::db::COL_EXTRA, &best_block_hash, &best_block_details); // update the new best block hash - batch.put(::db::COL_EXTRA, b"best", &best_block_hash); + batch.put(::db::COL_EXTRA, b"best", best_block_hash.as_bytes()); self.db .read() @@ -2203,7 +2203,7 @@ impl BlockChainClient for Client { }; if let Some(after) = after { - if let Err(e) = iter.seek(after) { + if let Err(e) = iter.seek(after.as_bytes()) { trace!(target: "fatdb", "list_accounts: Couldn't seek the DB: {:?}", e); } else { // Position the iterator after the `after` element @@ -2261,7 +2261,7 @@ impl BlockChainClient for Client { }; if let Some(after) = after { - if let Err(e) = iter.seek(after) { + if let Err(e) = iter.seek(after.as_bytes()) { trace!(target: "fatdb", "list_storage: Couldn't seek the DB: {:?}", e); } else { // Position the iterator after the `after` element @@ -3404,6 +3404,7 @@ impl PrometheusMetrics for Client { #[cfg(test)] mod tests { use blockchain::{BlockProvider, ExtrasInsert}; + use ethereum_types::{H160, H256}; use spec::Spec; use test_helpers::generate_dummy_client_with_spec_and_data; @@ -3484,7 +3485,7 @@ mod tests { #[test] fn should_return_correct_log_index() { use super::transaction_receipt; - use ethkey::KeyPair; + use crypto::publickey::KeyPair; use hash::keccak; use types::{ log_entry::{LocalizedLogEntry, LogEntry}, @@ -3493,19 +3494,19 @@ mod tests { }; // given - let key = KeyPair::from_secret_slice(&keccak("test")).unwrap(); + let key = KeyPair::from_secret_slice(keccak("test").as_bytes()).unwrap(); let secret = key.secret(); let machine = ::ethereum::new_frontier_test_machine(); let block_number = 1; - let block_hash = 5.into(); - let state_root = 99.into(); + let block_hash = H256::from_low_u64_be(5); + let state_root = H256::from_low_u64_be(99); let gas_used = 10.into(); let raw_tx = TypedTransaction::Legacy(Transaction { nonce: 0.into(), gas_price: 0.into(), gas: 21000.into(), - action: Action::Call(10.into()), + action: Action::Call(H160::from_low_u64_be(10)), value: 0.into(), data: vec![], }); @@ -3519,12 +3520,12 @@ mod tests { }; let logs = vec![ LogEntry { - address: 5.into(), + address: H160::from_low_u64_be(5), topics: vec![], data: vec![], }, LogEntry { - address: 15.into(), + address: H160::from_low_u64_be(15), topics: vec![], data: vec![], }, diff --git a/crates/ethcore/src/client/test_client.rs b/crates/ethcore/src/client/test_client.rs index c0f62aff6..e59b18631 100644 --- a/crates/ethcore/src/client/test_client.rs +++ b/crates/ethcore/src/client/test_client.rs @@ -18,6 +18,7 @@ use std::{ collections::{BTreeMap, HashMap}, + str::FromStr, sync::{ atomic::{AtomicBool, AtomicUsize, Ordering as AtomicOrder}, Arc, @@ -26,10 +27,10 @@ use std::{ use blockchain::{BlockReceipts, TreeRoute}; use bytes::Bytes; +use crypto::publickey::{Generator, Random}; use db::{COL_STATE, NUM_COLUMNS}; use ethcore_miner::pool::VerifiedTransaction; use ethereum_types::{Address, H256, U256}; -use ethkey::{Generator, Random}; use ethtrie; use hash::keccak; use itertools::Itertools; @@ -174,9 +175,9 @@ impl TestBlockChainClient { let mut client = TestBlockChainClient { blocks: RwLock::new(HashMap::new()), numbers: RwLock::new(HashMap::new()), - genesis_hash: H256::new(), + genesis_hash: H256::default(), extra_data: extra_data, - last_hash: RwLock::new(H256::new()), + last_hash: RwLock::new(H256::default()), difficulty: RwLock::new(spec.genesis_header().difficulty().clone()), balances: RwLock::new(HashMap::new()), nonces: RwLock::new(HashMap::new()), @@ -293,7 +294,7 @@ impl TestBlockChainClient { _ => 1, }; let mut txs = RlpStream::new_list(num_transactions); - let keypair = Random.generate().unwrap(); + let keypair = Random.generate(); let mut nonce = U256::zero(); for _ in 0..num_transactions { @@ -340,7 +341,7 @@ impl TestBlockChainClient { .unwrap() .decode() .expect("decoding failed"); - header.set_parent_hash(H256::from(42)); + header.set_parent_hash(H256::from_low_u64_be(42)); let mut rlp = RlpStream::new_list(3); rlp.append(&header); rlp.append_raw(&::rlp::NULL_RLP, 1); @@ -370,7 +371,7 @@ impl TestBlockChainClient { /// Inserts a transaction with given gas price to miners transactions queue. pub fn insert_transaction_with_gas_price_to_queue(&self, gas_price: U256) -> H256 { - let keypair = Random.generate().unwrap(); + let keypair = Random.generate(); let tx = TypedTransaction::Legacy(Transaction { action: Action::Create, value: U256::from(100), @@ -753,7 +754,7 @@ impl BlockChainClient for TestBlockChainClient { .clone() .unwrap() .into_iter() - .map(|t| t.transaction_hash.unwrap_or(H256::new())) + .map(|t| t.transaction_hash.unwrap_or(H256::default())) .zip(self.execution_result.read().clone().unwrap().into_iter()), )) } @@ -784,7 +785,7 @@ impl BlockChainClient for TestBlockChainClient { .read() .get(&(address.clone(), position.clone())) .cloned() - .unwrap_or_else(H256::new), + .unwrap_or_else(H256::default), ), _ => None, } @@ -902,7 +903,7 @@ impl BlockChainClient for TestBlockChainClient { // works only if blocks are one after another 1 -> 2 -> 3 fn tree_route(&self, from: &H256, to: &H256) -> Option { Some(TreeRoute { - ancestor: H256::new(), + ancestor: H256::default(), index: 0, blocks: { let numbers_read = self.numbers.read(); @@ -943,7 +944,10 @@ impl BlockChainClient for TestBlockChainClient { fn block_receipts(&self, hash: &H256) -> Option { // starts with 'f' ? - if *hash > H256::from("f000000000000000000000000000000000000000000000000000000000000000") { + if *hash + > H256::from_str("f000000000000000000000000000000000000000000000000000000000000000") + .unwrap() + { let receipt = BlockReceipts::new(vec![TypedReceipt::new( TypedTxId::Legacy, LegacyReceipt::new( diff --git a/crates/ethcore/src/engines/authority_round/mod.rs b/crates/ethcore/src/engines/authority_round/mod.rs index dee1a03c0..9afdedfc0 100644 --- a/crates/ethcore/src/engines/authority_round/mod.rs +++ b/crates/ethcore/src/engines/authority_round/mod.rs @@ -36,6 +36,7 @@ use super::{ }; use block::*; use client::{traits::ForceUpdateSealing, EngineClient}; +use crypto::publickey::{self, Signature}; use engines::{ block_reward, block_reward::{BlockRewardContract, RewardKind}, @@ -43,8 +44,8 @@ use engines::{ }; use error::{BlockError, Error, ErrorKind}; use ethereum_types::{Address, H256, H520, U128, U256}; + use ethjson::{self, uint::Uint}; -use ethkey::{self, Signature}; use hash::keccak; use io::{IoContext, IoHandler, IoService, TimerToken}; use itertools::{self, Itertools}; @@ -378,14 +379,14 @@ impl EmptyStep { let message = keccak(empty_step_rlp(self.step, &self.parent_hash)); let correct_proposer = step_proposer(validators, &self.parent_hash, self.step); - ethkey::verify_address(&correct_proposer, &self.signature.into(), &message) + publickey::verify_address(&correct_proposer, &self.signature.into(), &message) .map_err(|e| e.into()) } fn author(&self) -> Result { let message = keccak(empty_step_rlp(self.step, &self.parent_hash)); - let public = ethkey::recover(&self.signature.into(), &message)?; - Ok(ethkey::public_to_address(&public)) + let public = publickey::recover(&self.signature.into(), &message)?; + Ok(publickey::public_to_address(&public)) } fn sealed(&self) -> SealedEmptyStep { @@ -583,7 +584,7 @@ impl super::EpochVerifier for EpochVerifier { fn header_seal_hash(header: &Header, empty_steps_rlp: Option<&[u8]>) -> H256 { match empty_steps_rlp { Some(empty_steps_rlp) => { - let mut message = header.bare_hash().to_vec(); + let mut message = header.bare_hash().as_bytes().to_vec(); message.extend_from_slice(empty_steps_rlp); keccak(message) } @@ -717,7 +718,7 @@ fn verify_external( }; let header_seal_hash = header_seal_hash(header, empty_steps_rlp); - !ethkey::verify_address(&correct_proposer, &proposer_signature, &header_seal_hash)? + !publickey::verify_address(&correct_proposer, &proposer_signature, &header_seal_hash)? }; if is_invalid_proposer { @@ -1312,7 +1313,7 @@ impl Engine for AuthorityRound { } let mut fields = - vec![encode(&step), encode(&(&H520::from(signature) as &[u8]))]; + vec![encode(&step), encode(&(H520::from(signature).as_bytes()))]; if let Some(empty_steps_rlp) = empty_steps_rlp { fields.push(empty_steps_rlp); @@ -1738,7 +1739,7 @@ impl Engine for AuthorityRound { .signer .read() .as_ref() - .ok_or(ethkey::Error::InvalidAddress)? + .ok_or(publickey::Error::InvalidAddress)? .sign(hash)?) } @@ -1782,13 +1783,13 @@ mod tests { }; use accounts::AccountProvider; use block::*; + use crypto::publickey::Signature; use engines::{ validator_set::{SimpleList, TestSet}, Engine, EngineError, EthEngine, Seal, }; use error::{Error, ErrorKind}; use ethereum_types::{Address, H256, H520, U256}; - use ethkey::Signature; use hash::keccak; use rlp::encode; use spec::Spec; @@ -2187,7 +2188,7 @@ mod tests { fn set_empty_steps_seal( header: &mut Header, step: u64, - block_signature: ðkey::Signature, + block_signature: &crypto::publickey::Signature, empty_steps: &[SealedEmptyStep], ) { header.set_seal(vec![ @@ -2539,7 +2540,7 @@ mod tests { // empty step with invalid step let empty_steps = vec![SealedEmptyStep { - signature: 0.into(), + signature: H520::zero(), step: 2, }]; set_empty_steps_seal(&mut header, 2, &signature, &empty_steps); @@ -2551,7 +2552,7 @@ mod tests { // empty step with invalid signature let empty_steps = vec![SealedEmptyStep { - signature: 0.into(), + signature: H520::zero(), step: 1, }]; set_empty_steps_seal(&mut header, 2, &signature, &empty_steps); @@ -2703,7 +2704,7 @@ mod tests { p.maximum_empty_steps = 0; }); - let parent_hash: H256 = 1.into(); + let parent_hash = H256::from_low_u64_be(1); let signature = H520::default(); let step = |step: u64| EmptyStep { step, diff --git a/crates/ethcore/src/engines/basic_authority.rs b/crates/ethcore/src/engines/basic_authority.rs index 8164e65a6..f1b9e7baf 100644 --- a/crates/ethcore/src/engines/basic_authority.rs +++ b/crates/ethcore/src/engines/basic_authority.rs @@ -19,11 +19,11 @@ use super::validator_set::{new_validator_set, SimpleList, ValidatorSet}; use block::*; use client::EngineClient; +use crypto::publickey::{self, Signature}; use engines::{signer::EngineSigner, ConstructedVerifier, Engine, EngineError, Seal}; use error::{BlockError, Error}; use ethereum_types::{H256, H520}; use ethjson; -use ethkey::{self, Signature}; use machine::{AuxiliaryData, Call, EthereumMachine}; use parking_lot::RwLock; use std::sync::Weak; @@ -59,7 +59,8 @@ fn verify_external(header: &Header, validators: &dyn ValidatorSet) -> Result<(), // Check if the signature belongs to a validator, can depend on parent state. let sig = Rlp::new(&header.seal()[0]).as_val::()?; - let signer = ethkey::public_to_address(ðkey::recover(&sig.into(), &header.bare_hash())?); + let signer = + publickey::public_to_address(&publickey::recover(&sig.into(), &header.bare_hash())?); if *header.author() != signer { return Err(EngineError::NotAuthorized(*header.author()).into()); @@ -114,7 +115,7 @@ impl Engine for BasicAuthority { if self.validators.contains(header.parent_hash(), author) { // account should be pernamently unlocked, otherwise sealing will fail if let Ok(signature) = self.sign(header.bare_hash()) { - return Seal::Regular(vec![::rlp::encode(&(&H520::from(signature) as &[u8]))]); + return Seal::Regular(vec![::rlp::encode(&(H520::from(signature).as_bytes()))]); } else { trace!(target: "basicauthority", "generate_seal: FAIL: accounts secret key unavailable"); } @@ -205,7 +206,7 @@ impl Engine for BasicAuthority { .signer .read() .as_ref() - .ok_or_else(|| ethkey::Error::InvalidAddress)? + .ok_or_else(|| publickey::Error::InvalidAddress)? .sign(hash)?) } diff --git a/crates/ethcore/src/engines/block_reward.rs b/crates/ethcore/src/engines/block_reward.rs index 1cdd2cc95..90c05a8a7 100644 --- a/crates/ethcore/src/engines/block_reward.rs +++ b/crates/ethcore/src/engines/block_reward.rs @@ -196,12 +196,13 @@ pub fn apply_block_rewards( #[cfg(test)] mod test { use client::PrepareOpenBlock; - use ethereum_types::U256; + use ethereum_types::{H160, U256}; use spec::Spec; use test_helpers::generate_dummy_client_with_spec; use super::{BlockRewardContract, RewardKind}; use engines::SystemOrCodeCallKind; + use std::str::FromStr; #[test] fn block_reward_contract() { @@ -211,13 +212,13 @@ mod test { // the spec has a block reward contract defined at the given address let block_reward_contract = BlockRewardContract::new_from_address( - "0000000000000000000000000000000000000042".into(), + H160::from_str("0000000000000000000000000000000000000042").unwrap(), ); let mut call = |to, data| { let mut block = client .prepare_open_block( - "0000000000000000000000000000000000000001".into(), + H160::from_str("0000000000000000000000000000000000000001").unwrap(), (3141562.into(), 31415620.into()), vec![], ) @@ -244,15 +245,15 @@ mod test { // the contract rewards (1000 + kind) for each benefactor let beneficiaries = vec![ ( - "0000000000000000000000000000000000000033".into(), + H160::from_str("0000000000000000000000000000000000000033").unwrap(), RewardKind::Author, ), ( - "0000000000000000000000000000000000000034".into(), + H160::from_str("0000000000000000000000000000000000000034").unwrap(), RewardKind::Uncle(1), ), ( - "0000000000000000000000000000000000000035".into(), + H160::from_str("0000000000000000000000000000000000000035").unwrap(), RewardKind::EmptyStep, ), ]; @@ -262,15 +263,15 @@ mod test { .unwrap(); let expected = vec![ ( - "0000000000000000000000000000000000000033".into(), + H160::from_str("0000000000000000000000000000000000000033").unwrap(), U256::from(1000), ), ( - "0000000000000000000000000000000000000034".into(), + H160::from_str("0000000000000000000000000000000000000034").unwrap(), U256::from(1000 + 101), ), ( - "0000000000000000000000000000000000000035".into(), + H160::from_str("0000000000000000000000000000000000000035").unwrap(), U256::from(1000 + 2), ), ]; diff --git a/crates/ethcore/src/engines/clique/block_state.rs b/crates/ethcore/src/engines/clique/block_state.rs index 424911cf9..53565693d 100644 --- a/crates/ethcore/src/engines/clique/block_state.rs +++ b/crates/ethcore/src/engines/clique/block_state.rs @@ -221,7 +221,7 @@ impl CliqueBlockState { }))? } - let nonce: H64 = decoded_seal[1].into(); + let nonce = H64::from_slice(decoded_seal[1]); self.update_signers_on_vote( VoteType::from_nonce(nonce)?, creator, diff --git a/crates/ethcore/src/engines/clique/mod.rs b/crates/ethcore/src/engines/clique/mod.rs index 1839f1f82..9952e87a1 100644 --- a/crates/ethcore/src/engines/clique/mod.rs +++ b/crates/ethcore/src/engines/clique/mod.rs @@ -68,13 +68,13 @@ use std::{ use super::signer::EngineSigner; use block::ExecutedBlock; use client::{traits::ForceUpdateSealing, BlockId, EngineClient}; +use crypto::publickey::Signature; use engines::{ clique::util::{extract_signers, recover_creator}, Engine, EngineError, Seal, }; use error::{BlockError, Error}; use ethereum_types::{Address, H160, H256, H64, U256}; -use ethkey::Signature; use hash::KECCAK_EMPTY_LIST_RLP; use itertools::Itertools; use lru_cache::LruCache; @@ -590,7 +590,7 @@ impl Engine for Clique { if is_checkpoint && *header.author() != NULL_AUTHOR { return Err(EngineError::CliqueWrongAuthorCheckpoint(Mismatch { - expected: 0.into(), + expected: H160::zero(), found: *header.author(), }))?; } @@ -603,8 +603,8 @@ impl Engine for Clique { }))? } - let mixhash: H256 = seal_fields[0].into(); - let nonce: H64 = seal_fields[1].into(); + let mixhash = H256::from_slice(seal_fields[0]); + let nonce = H64::from_slice(seal_fields[1]); // Nonce must be 0x00..0 or 0xff..f if nonce != NONCE_DROP_VOTE && nonce != NONCE_AUTH_VOTE { diff --git a/crates/ethcore/src/engines/clique/tests.rs b/crates/ethcore/src/engines/clique/tests.rs index a243a3893..22135731f 100644 --- a/crates/ethcore/src/engines/clique/tests.rs +++ b/crates/ethcore/src/engines/clique/tests.rs @@ -18,10 +18,10 @@ use super::*; use block::*; +use crypto::publickey::{KeyPair, Secret}; use engines::Engine; use error::{Error, ErrorKind}; use ethereum_types::{Address, H256}; -use ethkey::{KeyPair, Secret}; use state_db::StateDB; use test_helpers::get_temp_state_db; @@ -72,10 +72,10 @@ impl CliqueTester { let mut extra_data = vec![0; VANITY_LENGTH]; for &signer in SIGNER_TAGS.iter() { - let secret = Secret::from(H256::from(signer as u64)); + let secret = Secret::from(H256::from_low_u64_be(signer as u64)); let keypair = KeyPair::from_secret(secret).unwrap(); if initial_signers.contains(&signer) { - extra_data.extend(&*keypair.address()); + extra_data.extend(keypair.address().as_bytes()); } signers.insert(signer, keypair); } @@ -167,7 +167,7 @@ impl CliqueTester { CliqueBlockType::Checkpoint => { let signers = self.clique.state(&last_header).unwrap().signers().clone(); for signer in signers { - extra_data.extend(&*signer); + extra_data.extend(signer.as_bytes()); } } CliqueBlockType::Vote(v) => seal = v.as_rlp(), @@ -203,7 +203,8 @@ impl CliqueTester { b.header.set_difficulty(difficulty); b.header.set_seal(seal); - let sign = ethkey::sign(self.signers[&signer].secret(), &b.header.hash()).unwrap(); + let sign = + crypto::publickey::sign(self.signers[&signer].secret(), &b.header.hash()).unwrap(); let mut extra_data = b.header.extra_data().clone(); extra_data.extend_from_slice(&*sign); b.header.set_extra_data(extra_data); diff --git a/crates/ethcore/src/engines/clique/util.rs b/crates/ethcore/src/engines/clique/util.rs index 81751fa04..a5fd9f14a 100644 --- a/crates/ethcore/src/engines/clique/util.rs +++ b/crates/ethcore/src/engines/clique/util.rs @@ -16,13 +16,13 @@ use std::collections::BTreeSet; +use crypto::publickey::{public_to_address, recover as ec_recover, Signature}; use engines::{ clique::{ADDRESS_LENGTH, NULL_MIXHASH, NULL_NONCE, SIGNATURE_LENGTH, VANITY_LENGTH}, EngineError, }; use error::Error; -use ethereum_types::{Address, H256}; -use ethkey::{public_to_address, recover as ec_recover, Signature}; +use ethereum_types::{Address, H160, H256}; use lru_cache::LruCache; use parking_lot::RwLock; use rlp::encode; @@ -106,7 +106,7 @@ pub fn extract_signers(header: &Header) -> Result, Error> { .map(|i| { let start = i * ADDRESS_LENGTH; let end = start + ADDRESS_LENGTH; - signers_raw[start..end].into() + H160::from_slice(&signers_raw[start..end]) }) .collect(); @@ -115,5 +115,8 @@ pub fn extract_signers(header: &Header) -> Result, Error> { /// Retrieve `null_seal` pub fn null_seal() -> Vec> { - vec![encode(&NULL_MIXHASH.to_vec()), encode(&NULL_NONCE.to_vec())] + vec![ + encode(&NULL_MIXHASH.as_bytes().to_vec()), + encode(&NULL_NONCE.as_bytes().to_vec()), + ] } diff --git a/crates/ethcore/src/engines/mod.rs b/crates/ethcore/src/engines/mod.rs index 7c49fea56..f2c2f66ae 100644 --- a/crates/ethcore/src/engines/mod.rs +++ b/crates/ethcore/src/engines/mod.rs @@ -60,8 +60,8 @@ use vm::{ActionValue, CallType, CreateContractAddress, EnvInfo, Schedule}; use block::ExecutedBlock; use bytes::Bytes; +use crypto::publickey::Signature; use ethereum_types::{Address, H256, H64, U256}; -use ethkey::Signature; use machine::{self, AuxiliaryData, AuxiliaryRequest, Machine}; use types::ancestry_action::AncestryAction; use unexpected::{Mismatch, OutOfBounds}; diff --git a/crates/ethcore/src/engines/signer.rs b/crates/ethcore/src/engines/signer.rs index d4a31802d..74fb61f9c 100644 --- a/crates/ethcore/src/engines/signer.rs +++ b/crates/ethcore/src/engines/signer.rs @@ -16,28 +16,28 @@ //! A signer used by Engines which need to sign messages. +use crypto::publickey::{self, Signature}; use ethereum_types::{Address, H256}; -use ethkey::{self, Signature}; /// Everything that an Engine needs to sign messages. pub trait EngineSigner: Send + Sync { /// Sign a consensus message hash. - fn sign(&self, hash: H256) -> Result; + fn sign(&self, hash: H256) -> Result; /// Signing address fn address(&self) -> Address; } /// Creates a new `EngineSigner` from given key pair. -pub fn from_keypair(keypair: ethkey::KeyPair) -> Box { +pub fn from_keypair(keypair: publickey::KeyPair) -> Box { Box::new(Signer(keypair)) } -struct Signer(ethkey::KeyPair); +struct Signer(publickey::KeyPair); impl EngineSigner for Signer { - fn sign(&self, hash: H256) -> Result { - ethkey::sign(self.0.secret(), &hash) + fn sign(&self, hash: H256) -> Result { + publickey::sign(self.0.secret(), &hash) } fn address(&self) -> Address { @@ -47,26 +47,29 @@ impl EngineSigner for Signer { #[cfg(test)] mod test_signer { + + extern crate ethkey; + use std::sync::Arc; + use self::ethkey::Password; use accounts::{self, AccountProvider, SignError}; - use ethkey::Password; use super::*; impl EngineSigner for (Arc, Address, Password) { - fn sign(&self, hash: H256) -> Result { + fn sign(&self, hash: H256) -> Result { match self.0.sign(self.1, Some(self.2.clone()), hash) { Err(SignError::NotUnlocked) => unreachable!(), - Err(SignError::NotFound) => Err(ethkey::Error::InvalidAddress), - Err(SignError::SStore(accounts::Error::EthKey(err))) => Err(err), - Err(SignError::SStore(accounts::Error::EthKeyCrypto(err))) => { + Err(SignError::NotFound) => Err(crypto::publickey::Error::InvalidAddress), + Err(SignError::SStore(accounts::Error::EthCryptoPublicKey(err))) => Err(err), + Err(SignError::SStore(accounts::Error::EthCrypto(err))) => { warn!("Low level crypto error: {:?}", err); - Err(ethkey::Error::InvalidSecret) + Err(crypto::publickey::Error::InvalidSecretKey) } Err(SignError::SStore(err)) => { warn!("Error signing for engine: {:?}", err); - Err(ethkey::Error::InvalidSignature) + Err(crypto::publickey::Error::InvalidSignature) } Ok(ok) => Ok(ok), } diff --git a/crates/ethcore/src/engines/validator_set/contract.rs b/crates/ethcore/src/engines/validator_set/contract.rs index b742120f2..451d8e39c 100644 --- a/crates/ethcore/src/engines/validator_set/contract.rs +++ b/crates/ethcore/src/engines/validator_set/contract.rs @@ -211,7 +211,7 @@ mod tests { // Check a block that is a bit in future, reject it but don't report the validator. let mut header = Header::default(); - let seal = vec![encode(&4u8), encode(&(&H520::default() as &[u8]))]; + let seal = vec![encode(&4u8), encode(&(H520::default().as_bytes()))]; header.set_seal(seal); header.set_author(v1); header.set_number(2); @@ -222,7 +222,7 @@ mod tests { // Now create one that is more in future. That one should be rejected and validator should be reported. let mut header = Header::default(); - let seal = vec![encode(&8u8), encode(&(&H520::default() as &[u8]))]; + let seal = vec![encode(&8u8), encode(&(H520::default().as_bytes()))]; header.set_seal(seal); header.set_author(v1); header.set_number(2); diff --git a/crates/ethcore/src/engines/validator_set/multi.rs b/crates/ethcore/src/engines/validator_set/multi.rs index b5b290167..01618e5af 100644 --- a/crates/ethcore/src/engines/validator_set/multi.rs +++ b/crates/ethcore/src/engines/validator_set/multi.rs @@ -183,9 +183,9 @@ impl ValidatorSet for Multi { mod tests { use accounts::AccountProvider; use client::{traits::ForceUpdateSealing, BlockChainClient, BlockInfo, ChainInfo, ImportBlock}; + use crypto::publickey::Secret; use engines::{validator_set::ValidatorSet, EpochChange}; use ethereum_types::Address; - use ethkey::Secret; use hash::keccak; use miner::{self, MinerService}; use spec::Spec; diff --git a/crates/ethcore/src/engines/validator_set/safe_contract.rs b/crates/ethcore/src/engines/validator_set/safe_contract.rs index 6e36015aa..30e8403f1 100644 --- a/crates/ethcore/src/engines/validator_set/safe_contract.rs +++ b/crates/ethcore/src/engines/validator_set/safe_contract.rs @@ -481,8 +481,8 @@ mod tests { traits::{EngineClient, ForceUpdateSealing}, BlockInfo, ChainInfo, ImportBlock, }; + use crypto::publickey::Secret; use ethereum_types::Address; - use ethkey::Secret; use hash::keccak; use miner::{self, MinerService}; use rustc_hex::FromHex; diff --git a/crates/ethcore/src/engines/validator_set/simple_list.rs b/crates/ethcore/src/engines/validator_set/simple_list.rs index 5911d749c..8e4420462 100644 --- a/crates/ethcore/src/engines/validator_set/simple_list.rs +++ b/crates/ethcore/src/engines/validator_set/simple_list.rs @@ -16,14 +16,14 @@ use ethereum_types::{Address, H256}; /// Preconfigured validator list. -use heapsize::HeapSizeOf; +use parity_util_mem::MallocSizeOf; use super::ValidatorSet; use machine::{AuxiliaryData, Call, EthereumMachine}; use types::{header::Header, BlockNumber}; /// Validator set containing a known set of addresses. -#[derive(Clone, Debug, PartialEq, Eq, Default)] +#[derive(Clone, Debug, PartialEq, Eq, Default, MallocSizeOf)] pub struct SimpleList { validators: Vec
, } @@ -58,12 +58,6 @@ impl From> for SimpleList { } } -impl HeapSizeOf for SimpleList { - fn heap_size_of_children(&self) -> usize { - self.validators.heap_size_of_children() - } -} - impl ValidatorSet for SimpleList { fn default_caller(&self, _block_id: ::types::ids::BlockId) -> Box { Box::new(|_, _| Err("Simple list doesn't require calls.".into())) diff --git a/crates/ethcore/src/engines/validator_set/test.rs b/crates/ethcore/src/engines/validator_set/test.rs index afc4cb1d0..ab96a42e6 100644 --- a/crates/ethcore/src/engines/validator_set/test.rs +++ b/crates/ethcore/src/engines/validator_set/test.rs @@ -23,13 +23,14 @@ use std::sync::{ use bytes::Bytes; use ethereum_types::{Address, H256}; -use heapsize::HeapSizeOf; +use parity_util_mem::MallocSizeOf; use types::{header::Header, BlockNumber}; use super::{SimpleList, ValidatorSet}; use machine::{AuxiliaryData, Call, EthereumMachine}; /// Set used for testing with a single validator. +#[derive(MallocSizeOf)] pub struct TestSet { validator: SimpleList, last_malicious: Arc, @@ -55,12 +56,6 @@ impl TestSet { } } -impl HeapSizeOf for TestSet { - fn heap_size_of_children(&self) -> usize { - self.validator.heap_size_of_children() - } -} - impl ValidatorSet for TestSet { fn default_caller(&self, _block_id: ::types::ids::BlockId) -> Box { Box::new(|_, _| Err("Test set doesn't require calls.".into())) diff --git a/crates/ethcore/src/error.rs b/crates/ethcore/src/error.rs index 5081c85bf..5a246f12c 100644 --- a/crates/ethcore/src/error.rs +++ b/crates/ethcore/src/error.rs @@ -22,8 +22,8 @@ use std::{error, fmt, time::SystemTime}; +use crypto::publickey::Error as EthkeyError; use ethereum_types::{Address, Bloom, H256, U256}; -use ethkey::Error as EthkeyError; use ethtrie::TrieError; use rlp; use snappy::InvalidInput; diff --git a/crates/ethcore/src/ethereum/ethash.rs b/crates/ethcore/src/ethereum/ethash.rs index 9210d1a4d..ffd55eb84 100644 --- a/crates/ethcore/src/ethereum/ethash.rs +++ b/crates/ethcore/src/ethereum/ethash.rs @@ -362,7 +362,7 @@ impl Engine for Arc { let difficulty = ethash::boundary_to_difficulty(&H256(quick_get_difficulty( &header.bare_hash().0, - seal.nonce.low_u64(), + seal.nonce.to_low_u64_be(), &seal.mix_hash.0, header.number() >= self.ethash_params.progpow_transition, ))); @@ -384,7 +384,7 @@ impl Engine for Arc { let result = self.pow.compute_light( header.number() as u64, &header.bare_hash().0, - seal.nonce.low_u64(), + seal.nonce.to_low_u64_be(), ); let mix = H256(result.mix_hash); let difficulty = ethash::boundary_to_difficulty(&H256(result.value)); @@ -392,7 +392,7 @@ impl Engine for Arc { num = header.number() as u64, seed = H256(slow_hash_block_number(header.number() as u64)), h = header.bare_hash(), - non = seal.nonce.low_u64(), + non = seal.nonce.to_low_u64_be(), mix = H256(result.mix_hash), res = H256(result.value)); if mix != seal.mix_hash { @@ -692,7 +692,7 @@ mod tests { ) .unwrap(); let mut uncle = Header::new(); - let uncle_author: Address = "ef2d6d194084c2de36e0dabfce45d046b37d1106".into(); + let uncle_author = Address::from_str("ef2d6d194084c2de36e0dabfce45d046b37d1106").unwrap(); uncle.set_author(uncle_author); b.push_uncle(uncle).unwrap(); @@ -732,8 +732,8 @@ mod tests { .unwrap(); let b = b.close().unwrap(); - let ubi_contract: Address = "00efdd5883ec628983e9063c7d969fe268bbf310".into(); - let dev_contract: Address = "00756cf8159095948496617f5fb17ed95059f536".into(); + let ubi_contract = Address::from_str("00efdd5883ec628983e9063c7d969fe268bbf310").unwrap(); + let dev_contract = Address::from_str("00756cf8159095948496617f5fb17ed95059f536").unwrap(); assert_eq!( b.state.balance(&Address::zero()).unwrap(), U256::from_str("d8d726b7177a80000").unwrap() @@ -888,9 +888,10 @@ mod tests { let engine = test_spec().engine; let mut header: Header = Header::default(); header.set_seal(vec![ - rlp::encode(&H256::from( - "b251bd2e0283d0658f2cadfdc8ca619b5de94eca5742725e2e757dd13ed7503d", - )), + rlp::encode( + &H256::from_str("b251bd2e0283d0658f2cadfdc8ca619b5de94eca5742725e2e757dd13ed7503d") + .unwrap(), + ), rlp::encode(&H64::zero()), ]); header.set_difficulty( @@ -1025,9 +1026,10 @@ mod tests { let ethash = Ethash::new(tempdir.path(), ethparams, machine, None); let mut header = Header::default(); header.set_seal(vec![ - rlp::encode(&H256::from( - "b251bd2e0283d0658f2cadfdc8ca619b5de94eca5742725e2e757dd13ed7503d", - )), + rlp::encode( + &H256::from_str("b251bd2e0283d0658f2cadfdc8ca619b5de94eca5742725e2e757dd13ed7503d") + .unwrap(), + ), rlp::encode(&H64::zero()), ]); let info = ethash.extra_info(&header); diff --git a/crates/ethcore/src/ethereum/mod.rs b/crates/ethcore/src/ethereum/mod.rs index b527ff9c9..0b412b12e 100644 --- a/crates/ethcore/src/ethereum/mod.rs +++ b/crates/ethcore/src/ethereum/mod.rs @@ -346,8 +346,9 @@ pub fn new_kovan_wasm_test_machine() -> EthereumMachine { #[cfg(test)] mod tests { use super::*; - use ethereum_types::U256; + use ethereum_types::{H160, H256, U256}; use state::*; + use std::str::FromStr; use test_helpers::get_temp_state_db; use types::{view, views::BlockView}; @@ -367,32 +368,32 @@ mod tests { ) .unwrap(); assert_eq!( - s.balance(&"0000000000000000000000000000000000000001".into()) + s.balance(&H160::from_str("0000000000000000000000000000000000000001").unwrap()) .unwrap(), 1u64.into() ); assert_eq!( - s.balance(&"0000000000000000000000000000000000000002".into()) + s.balance(&H160::from_str("0000000000000000000000000000000000000002").unwrap()) .unwrap(), 1u64.into() ); assert_eq!( - s.balance(&"0000000000000000000000000000000000000003".into()) + s.balance(&H160::from_str("0000000000000000000000000000000000000003").unwrap()) .unwrap(), 1u64.into() ); assert_eq!( - s.balance(&"0000000000000000000000000000000000000004".into()) + s.balance(&H160::from_str("0000000000000000000000000000000000000004").unwrap()) .unwrap(), 1u64.into() ); assert_eq!( - s.balance(&"102e61f5d8f9bc71d0ad4a084df4e65e05ce0e1c".into()) + s.balance(&H160::from_str("102e61f5d8f9bc71d0ad4a084df4e65e05ce0e1c").unwrap()) .unwrap(), U256::from(1u64) << 200 ); assert_eq!( - s.balance(&"0000000000000000000000000000000000000000".into()) + s.balance(&H160::from_str("0000000000000000000000000000000000000000").unwrap()) .unwrap(), 0u64.into() ); @@ -404,12 +405,14 @@ mod tests { assert_eq!( morden.state_root(), - "f3f4696bbf3b3b07775128eb7a3763279a394e382130f27c21e70233e04946a9".into() + H256::from_str("f3f4696bbf3b3b07775128eb7a3763279a394e382130f27c21e70233e04946a9") + .unwrap() ); let genesis = morden.genesis_block(); assert_eq!( view!(BlockView, &genesis).header_view().hash(), - "0cd786a2425d16f152c658316c423e6ce1181e15c3295826d7c9904cba9ce303".into() + H256::from_str("0cd786a2425d16f152c658316c423e6ce1181e15c3295826d7c9904cba9ce303") + .unwrap() ); let _ = morden.engine; @@ -421,12 +424,14 @@ mod tests { assert_eq!( frontier.state_root(), - "d7f8974fb5ac78d9ac099b9ad5018bedc2ce0a72dad1827a1709da30580f0544".into() + H256::from_str("d7f8974fb5ac78d9ac099b9ad5018bedc2ce0a72dad1827a1709da30580f0544") + .unwrap() ); let genesis = frontier.genesis_block(); assert_eq!( view!(BlockView, &genesis).header_view().hash(), - "d4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3".into() + H256::from_str("d4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3") + .unwrap() ); let _ = frontier.engine; diff --git a/crates/ethcore/src/executive.rs b/crates/ethcore/src/executive.rs index 485bb4275..6834c1723 100644 --- a/crates/ethcore/src/executive.rs +++ b/crates/ethcore/src/executive.rs @@ -25,7 +25,7 @@ use factory::VmFactory; use hash::keccak; use machine::EthereumMachine as Machine; use state::{Backend as StateBackend, CleanupMode, State, Substate}; -use std::{cmp, sync::Arc}; +use std::{cmp, convert::TryFrom, sync::Arc}; use trace::{self, Tracer, VMTracer}; use transaction_ext::Transaction; use types::transaction::{Action, SignedTransaction, TypedTransaction}; @@ -1220,7 +1220,7 @@ impl<'a, B: 'a + StateBackend> Executive<'a, B> { } self.state.sub_balance( &sender, - &U256::from(gas_cost), + &U256::try_from(gas_cost).expect("Total cost (value + gas_cost) is lower than max allowed balance (U256); gas_cost has to fit U256; qed"), &mut substate.to_cleanup_mode(&schedule), )?; @@ -1561,9 +1561,9 @@ impl<'a, B: 'a + StateBackend> Executive<'a, B> { #[allow(dead_code)] mod tests { use super::*; + use crypto::publickey::{Generator, Random}; use error::ExecutionError; - use ethereum_types::{Address, H256, U256, U512}; - use ethkey::{Generator, Random}; + use ethereum_types::{Address, BigEndianHash, H160, H256, U256, U512}; use evm::{Factory, VMType}; use machine::EthereumMachine; use rustc_hex::FromHex; @@ -1640,8 +1640,8 @@ mod tests { assert_eq!(gas_left, U256::from(79_975)); assert_eq!( - state.storage_at(&address, &H256::new()).unwrap(), - H256::from(&U256::from(0xf9u64)) + state.storage_at(&address, &H256::default()).unwrap(), + BigEndianHash::from_uint(&U256::from(0xf9u64)) ); assert_eq!(state.balance(&sender).unwrap(), U256::from(0xf9)); assert_eq!(state.balance(&address).unwrap(), U256::from(0x7)); @@ -1759,8 +1759,8 @@ mod tests { vec![ FlatTrace { action: trace::Action::Call(trace::Call { - from: "4444444444444444444444444444444444444444".into(), - to: "5555555555555555555555555555555555555555".into(), + from: H160::from_str("4444444444444444444444444444444444444444").unwrap(), + to: H160::from_str("5555555555555555555555555555555555555555").unwrap(), value: 100.into(), gas: 100_000.into(), input: vec![], @@ -1775,8 +1775,8 @@ mod tests { }, FlatTrace { action: trace::Action::Call(trace::Call { - from: "5555555555555555555555555555555555555555".into(), - to: "0000000000000000000000000000000000000003".into(), + from: H160::from_str("5555555555555555555555555555555555555555").unwrap(), + to: H160::from_str("0000000000000000000000000000000000000003").unwrap(), value: 1.into(), gas: 66560.into(), input: vec![], @@ -1866,8 +1866,8 @@ mod tests { trace_address: Default::default(), subtraces: 1, action: trace::Action::Call(trace::Call { - from: "cd1722f3947def4cf144679da39c4c32bdc35681".into(), - to: "b010143a42d5980c7e5ef0e4a4416dc098a4fed3".into(), + from: H160::from_str("cd1722f3947def4cf144679da39c4c32bdc35681").unwrap(), + to: H160::from_str("b010143a42d5980c7e5ef0e4a4416dc098a4fed3").unwrap(), value: 100.into(), gas: 100000.into(), input: vec![], @@ -1882,7 +1882,7 @@ mod tests { trace_address: vec![0].into_iter().collect(), subtraces: 0, action: trace::Action::Create(trace::Create { - from: "b010143a42d5980c7e5ef0e4a4416dc098a4fed3".into(), + from: H160::from_str("b010143a42d5980c7e5ef0e4a4416dc098a4fed3").unwrap(), value: 23.into(), gas: 67979.into(), init: vec![ @@ -1997,8 +1997,8 @@ mod tests { trace_address: Default::default(), subtraces: 1, action: trace::Action::Call(trace::Call { - from: "cd1722f3947def4cf144679da39c4c32bdc35681".into(), - to: "b010143a42d5980c7e5ef0e4a4416dc098a4fed3".into(), + from: H160::from_str("cd1722f3947def4cf144679da39c4c32bdc35681").unwrap(), + to: H160::from_str("b010143a42d5980c7e5ef0e4a4416dc098a4fed3").unwrap(), value: 100.into(), gas: 100_000.into(), input: vec![], @@ -2013,7 +2013,7 @@ mod tests { trace_address: vec![0].into_iter().collect(), subtraces: 0, action: trace::Action::Create(trace::Create { - from: "b010143a42d5980c7e5ef0e4a4416dc098a4fed3".into(), + from: H160::from_str("b010143a42d5980c7e5ef0e4a4416dc098a4fed3").unwrap(), value: 23.into(), gas: 66_917.into(), init: vec![0x60, 0x01, 0x60, 0x00, 0xfd], @@ -2392,9 +2392,9 @@ mod tests { assert_eq!(gas_left, U256::from(73_237)); assert_eq!( state - .storage_at(&address_a, &H256::from(&U256::from(0x23))) + .storage_at(&address_a, &BigEndianHash::from_uint(&U256::from(0x23))) .unwrap(), - H256::from(&U256::from(1)) + BigEndianHash::from_uint(&U256::from(1)) ); } @@ -2451,15 +2451,15 @@ mod tests { assert_eq!(gas_left, U256::from(59_870)); assert_eq!( state - .storage_at(&address, &H256::from(&U256::zero())) + .storage_at(&address, &BigEndianHash::from_uint(&U256::zero())) .unwrap(), - H256::from(&U256::from(1)) + BigEndianHash::from_uint(&U256::from(1)) ); assert_eq!( state - .storage_at(&address, &H256::from(&U256::one())) + .storage_at(&address, &BigEndianHash::from_uint(&U256::one())) .unwrap(), - H256::from(&U256::from(1)) + BigEndianHash::from_uint(&U256::from(1)) ); } @@ -2467,7 +2467,7 @@ mod tests { // TODO: fix (preferred) or remove evm_test_ignore! {test_transact_simple: test_transact_simple_int} fn test_transact_simple(factory: Factory) { - let keypair = Random.generate().unwrap(); + let keypair = Random.generate(); let t = TypedTransaction::Legacy(Transaction { action: Action::Create, value: U256::from(17), @@ -2511,14 +2511,14 @@ mod tests { assert_eq!(state.balance(&contract).unwrap(), U256::from(17)); assert_eq!(state.nonce(&sender).unwrap(), U256::from(1)); assert_eq!( - state.storage_at(&contract, &H256::new()).unwrap(), - H256::from(&U256::from(1)) + state.storage_at(&contract, &H256::zero()).unwrap(), + BigEndianHash::from_uint(&U256::from(1)) ); } evm_test! {test_transact_invalid_nonce: test_transact_invalid_nonce_int} fn test_transact_invalid_nonce(factory: Factory) { - let keypair = Random.generate().unwrap(); + let keypair = Random.generate(); let t = TypedTransaction::Legacy(Transaction { action: Action::Create, value: U256::from(17), @@ -2557,7 +2557,7 @@ mod tests { evm_test! {test_transact_gas_limit_reached: test_transact_gas_limit_reached_int} fn test_transact_gas_limit_reached(factory: Factory) { - let keypair = Random.generate().unwrap(); + let keypair = Random.generate(); let t = TypedTransaction::Legacy(Transaction { action: Action::Create, value: U256::from(17), @@ -2602,7 +2602,7 @@ mod tests { evm_test! {test_not_enough_cash: test_not_enough_cash_int} fn test_not_enough_cash(factory: Factory) { - let keypair = Random.generate().unwrap(); + let keypair = Random.generate(); let t = TypedTransaction::Legacy(Transaction { action: Action::Create, value: U256::from(18), @@ -2730,20 +2730,20 @@ mod tests { assert_eq!(output[..], returns[..]); assert_eq!( state - .storage_at(&contract_address, &H256::from(&U256::zero())) + .storage_at(&contract_address, &BigEndianHash::from_uint(&U256::zero())) .unwrap(), - H256::from(&U256::from(0)) + BigEndianHash::from_uint(&U256::from(0)) ); } evm_test! {test_eip1283: test_eip1283_int} fn test_eip1283(factory: Factory) { - let x1 = Address::from(0x1000); - let x2 = Address::from(0x1001); - let y1 = Address::from(0x2001); - let y2 = Address::from(0x2002); - let operating_address = Address::from(0); - let k = H256::new(); + let x1 = Address::from_low_u64_be(0x1000); + let x2 = Address::from_low_u64_be(0x1001); + let y1 = Address::from_low_u64_be(0x2001); + let y2 = Address::from_low_u64_be(0x2002); + let operating_address = Address::from_low_u64_be(0); + let k = H256::default(); let mut state = get_temp_state_with_factory(factory.clone()); state @@ -2777,7 +2777,7 @@ mod tests { assert_eq!( state.storage_at(&operating_address, &k).unwrap(), - H256::from(U256::from(0)) + BigEndianHash::from_uint(&U256::from(0)) ); // Test a call via top-level -> y1 -> x1 let (FinalizationResult { gas_left, .. }, refund, gas) = { @@ -2804,7 +2804,7 @@ mod tests { assert_eq!( state.storage_at(&operating_address, &k).unwrap(), - H256::from(U256::from(1)) + BigEndianHash::from_uint(&U256::from(1)) ); // Test a call via top-level -> y2 -> x2 let (FinalizationResult { gas_left, .. }, refund, gas) = { diff --git a/crates/ethcore/src/externalities.rs b/crates/ethcore/src/externalities.rs index d1910dd27..41c722e8f 100644 --- a/crates/ethcore/src/externalities.rs +++ b/crates/ethcore/src/externalities.rs @@ -16,7 +16,7 @@ //! Transaction Execution environment. use bytes::Bytes; -use ethereum_types::{Address, H256, U256}; +use ethereum_types::{Address, BigEndianHash, H256, U256}; use executive::*; use machine::EthereumMachine as Machine; use state::{Backend as StateBackend, CleanupMode, State, Substate}; @@ -187,6 +187,8 @@ where Err(_) => return H256::zero(), }; + let data: H256 = BigEndianHash::from_uint(number); + let params = ActionParams { sender: self.origin_info.address.clone(), address: blockhash_contract_address.clone(), @@ -197,7 +199,7 @@ where gas_price: 0.into(), code: code, code_hash: code_hash, - data: Some(H256::from(number).to_vec()), + data: Some(data.as_bytes().to_vec()), call_type: CallType::Call, params_type: vm::ParamsType::Separate, access_list: AccessList::default(), @@ -212,8 +214,8 @@ where self.vm_tracer, ); let output = match &r { - Ok(ref r) => H256::from(&r.return_data[..32]), - _ => H256::new(), + Ok(ref r) => H256::from_slice(&r.return_data[..32]), + _ => H256::default(), }; trace!( "ext: blockhash contract({}) -> {:?}({}) self.env_info.number={}\n", @@ -558,6 +560,7 @@ mod tests { use ethereum_types::{Address, U256}; use evm::{CallType, EnvInfo, Ext}; use state::{State, Substate}; + use std::str::FromStr; use test_helpers::get_temp_state; use trace::{NoopTracer, NoopVMTracer}; @@ -573,7 +576,7 @@ mod tests { fn get_test_env_info() -> EnvInfo { EnvInfo { number: 100, - author: 0.into(), + author: Address::zero(), timestamp: 0, difficulty: 0.into(), last_hashes: Arc::new(vec![]), @@ -672,7 +675,8 @@ mod tests { #[test] fn can_return_block_hash() { let test_hash = - H256::from("afafafafafafafafafafafbcbcbcbcbcbcbcbcbcbeeeeeeeeeeeeedddddddddd"); + H256::from_str("afafafafafafafafafafafbcbcbcbcbcbcbcbcbcbeeeeeeeeeeeeedddddddddd") + .unwrap(); let test_env_number = 0x120001; let mut setup = TestSetup::new(); @@ -741,15 +745,15 @@ mod tests { &"0000000000000000000000000000000000000000000000000000000000120000" .parse::() .unwrap(), - &Address::new(), - &Address::new(), + &Address::default(), + &Address::default(), Some( "0000000000000000000000000000000000000000000000000000000000150000" .parse::() .unwrap(), ), &[], - &Address::new(), + &Address::default(), CallType::Call, false, ) @@ -760,9 +764,10 @@ mod tests { #[test] fn can_log() { let log_data = vec![120u8, 110u8]; - let log_topics = vec![H256::from( + let log_topics = vec![H256::from_str( "af0fa234a6af46afa23faf23bcbc1c1cb4bcb7bcbe7e7e7ee3ee2edddddddddd", - )]; + ) + .unwrap()]; let mut setup = TestSetup::new(); let state = &mut setup.state; @@ -793,7 +798,7 @@ mod tests { #[test] fn can_suicide() { - let refund_account = &Address::new(); + let refund_account = &Address::default(); let mut setup = TestSetup::new(); let state = &mut setup.state; diff --git a/crates/ethcore/src/json_tests/executive.rs b/crates/ethcore/src/json_tests/executive.rs index 515b73045..ffd20e935 100644 --- a/crates/ethcore/src/json_tests/executive.rs +++ b/crates/ethcore/src/json_tests/executive.rs @@ -16,6 +16,7 @@ use super::test_common::*; use bytes::Bytes; +use ethereum_types::BigEndianHash; use ethjson; use ethtrie; use evm::Finalize; @@ -398,10 +399,11 @@ pub fn json_executive_test( for (k, v) in storage { let key: U256 = k.into(); let value: U256 = v.into(); - let found_storage = - try_fail!(state.storage_at(&address, &From::from(&key))); + let found_storage = try_fail!( + state.storage_at(&address, &BigEndianHash::from_uint(&key)) + ); fail_unless( - found_storage == From::from(&value), + found_storage == BigEndianHash::from_uint(&value), "storage is incorrect", ); } diff --git a/crates/ethcore/src/lib.rs b/crates/ethcore/src/lib.rs index ba87d3ef4..1b8dcac70 100644 --- a/crates/ethcore/src/lib.rs +++ b/crates/ethcore/src/lib.rs @@ -31,9 +31,7 @@ extern crate ethcore_io as io; extern crate ethcore_miner; extern crate ethereum_types; extern crate ethjson; -extern crate ethkey; extern crate hash_db; -extern crate heapsize; extern crate itertools; extern crate journaldb; extern crate keccak_hash as hash; @@ -46,7 +44,9 @@ extern crate memory_cache; extern crate memory_db; extern crate num_cpus; extern crate parity_bytes as bytes; +extern crate parity_crypto as crypto; extern crate parity_snappy as snappy; +extern crate parity_util_mem; extern crate parking_lot; extern crate patricia_trie_ethereum as ethtrie; extern crate rand; @@ -84,8 +84,6 @@ extern crate tempfile; #[cfg(feature = "json-tests")] extern crate walkdir; -#[macro_use] -extern crate ethabi_derive; #[macro_use] extern crate ethabi_contract; #[macro_use] diff --git a/crates/ethcore/src/machine/impls.rs b/crates/ethcore/src/machine/impls.rs index b11a463b2..f5924e044 100644 --- a/crates/ethcore/src/machine/impls.rs +++ b/crates/ethcore/src/machine/impls.rs @@ -72,7 +72,7 @@ impl From<::ethjson::spec::EthashParams> for EthashExtensions { .map_or(u64::max_value(), Into::into), dao_hardfork_beneficiary: p .dao_hardfork_beneficiary - .map_or_else(Address::new, Into::into), + .map_or_else(Address::default, Into::into), dao_hardfork_accounts: p .dao_hardfork_accounts .unwrap_or_else(Vec::new) @@ -232,7 +232,7 @@ impl EthereumMachine { block, params.eip210_contract_address, params.eip210_contract_gas, - Some(parent_hash.to_vec()), + Some(parent_hash.as_bytes().to_vec()), )?; } Ok(()) @@ -546,12 +546,15 @@ fn round_block_gas_limit(gas_limit: U256, lower_limit: U256, upper_limit: U256) #[cfg(test)] mod tests { use super::*; + use ethereum_types::H160; + use std::str::FromStr; fn get_default_ethash_extensions() -> EthashExtensions { EthashExtensions { homestead_transition: 1150000, dao_hardfork_transition: u64::max_value(), - dao_hardfork_beneficiary: "0000000000000000000000000000000000000001".into(), + dao_hardfork_beneficiary: H160::from_str("0000000000000000000000000000000000000001") + .unwrap(), dao_hardfork_accounts: Vec::new(), } } @@ -576,7 +579,7 @@ mod tests { assert_eq!( res, Err(transaction::Error::InvalidSignature( - "Crypto error (Invalid EC signature)".into() + "invalid EC signature".into() )) ); } diff --git a/crates/ethcore/src/miner/miner.rs b/crates/ethcore/src/miner/miner.rs index 919059d20..4335093c7 100644 --- a/crates/ethcore/src/miner/miner.rs +++ b/crates/ethcore/src/miner/miner.rs @@ -1502,7 +1502,7 @@ mod tests { use super::*; use accounts::AccountProvider; - use ethkey::{Generator, Random}; + use crypto::publickey::{Generator, Random}; use hash::keccak; use rustc_hex::FromHex; use types::BlockNumber; @@ -1583,7 +1583,7 @@ mod tests { } fn transaction_with_chain_id(chain_id: u64) -> SignedTransaction { - let keypair = Random.generate().unwrap(); + let keypair = Random.generate(); TypedTransaction::Legacy(Transaction { action: Action::Create, value: U256::zero(), @@ -1636,7 +1636,7 @@ mod tests { // when new block is imported let client = generate_dummy_client(2); - let imported = [0.into()]; + let imported = [H256::zero()]; let empty = &[]; miner.chain_new_blocks(&*client, &imported, empty, &imported, empty, false); @@ -1716,7 +1716,7 @@ mod tests { #[test] fn should_treat_unfamiliar_locals_selectively() { // given - let keypair = Random.generate().unwrap(); + let keypair = Random.generate(); let client = TestBlockChainClient::default(); let mut local_accounts = ::std::collections::HashSet::new(); local_accounts.insert(keypair.address()); @@ -1917,7 +1917,7 @@ mod tests { let addr = tap.insert_account(keccak("1").into(), &"".into()).unwrap(); let client = generate_dummy_client_with_spec(spec); let engine_signer = Box::new((tap.clone(), addr, "".into())); - let msg = Default::default(); + let msg = [1u8; 32].into(); assert!(client.engine().sign(msg).is_err()); // should set engine signer and miner author diff --git a/crates/ethcore/src/miner/stratum.rs b/crates/ethcore/src/miner/stratum.rs index c08c02ca1..180be26cc 100644 --- a/crates/ethcore/src/miner/stratum.rs +++ b/crates/ethcore/src/miner/stratum.rs @@ -29,7 +29,7 @@ use ethcore_miner::work_notify::NotifyWork; #[cfg(feature = "work-notify")] use ethcore_stratum::PushWorkHandler; use ethcore_stratum::{Error as StratumServiceError, JobDispatcher, Stratum as StratumService}; -use ethereum_types::{clean_0x, H256, H64, U256}; +use ethereum_types::{H256, H64, U256}; use miner::{Miner, MinerService}; use parking_lot::Mutex; use rlp::encode; @@ -47,6 +47,14 @@ pub struct Options { pub secret: Option, } +fn clean_0x(s: &str) -> &str { + if s.starts_with("0x") { + &s[2..] + } else { + s + } +} + struct SubmitPayload { nonce: H64, pow_hash: H256, diff --git a/crates/ethcore/src/pod_account.rs b/crates/ethcore/src/pod_account.rs index ed7311e5a..6187072db 100644 --- a/crates/ethcore/src/pod_account.rs +++ b/crates/ethcore/src/pod_account.rs @@ -17,7 +17,7 @@ //! Account system expressed in Plain Old Data. use bytes::Bytes; -use ethereum_types::{H256, U256}; +use ethereum_types::{BigEndianHash, H256, U256}; use ethjson; use ethtrie::RlpCodec; use hash::keccak; @@ -85,7 +85,7 @@ impl PodAccount { stream.append(&sec_trie_root( self.storage .iter() - .map(|(k, v)| (k, rlp::encode(&U256::from(&**v)))), + .map(|(k, v)| (k, rlp::encode(&v.into_uint()))), )); stream.append(&keccak(&self.code.as_ref().unwrap_or(&vec![]))); stream.out() @@ -103,10 +103,10 @@ impl PodAccount { } _ => {} } - let mut r = H256::new(); + let mut r = H256::default(); let mut t = factory.create(db, &mut r); for (k, v) in &self.storage { - if let Err(e) = t.insert(k, &rlp::encode(&U256::from(&**v))) { + if let Err(e) = t.insert(k.as_bytes(), &rlp::encode(&v.into_uint())) { warn!("Encountered potential DB corruption: {}", e); } } @@ -125,7 +125,10 @@ impl From for PodAccount { .map(|(key, value)| { let key: U256 = key.into(); let value: U256 = value.into(); - (H256::from(key), H256::from(value)) + ( + BigEndianHash::from_uint(&key), + BigEndianHash::from_uint(&value), + ) }) .collect(), } @@ -143,7 +146,10 @@ impl From for PodAccount { .map(|(key, value)| { let key: U256 = key.into(); let value: U256 = value.into(); - (H256::from(key), H256::from(value)) + ( + BigEndianHash::from_uint(&key), + BigEndianHash::from_uint(&value), + ) }) .collect() }), @@ -159,7 +165,7 @@ impl fmt::Display for PodAccount { self.balance, self.nonce, self.code.as_ref().map_or(0, |c| c.len()), - self.code.as_ref().map_or_else(H256::new, |c| keccak(c)), + self.code.as_ref().map_or_else(H256::default, |c| keccak(c)), self.storage.len(), ) } @@ -183,7 +189,7 @@ pub fn diff_pod(pre: Option<&PodAccount>, post: Option<&PodAccount>) -> Option { let storage: Vec<_> = pre.storage.keys().merge(post.storage.keys()) - .filter(|k| pre.storage.get(k).unwrap_or(&H256::new()) != post.storage.get(k).unwrap_or(&H256::new())) + .filter(|k| pre.storage.get(k).unwrap_or(&H256::default()) != post.storage.get(k).unwrap_or(&H256::default())) .collect(); let r = AccountDiff { balance: Diff::new(pre.balance, post.balance), @@ -194,8 +200,8 @@ pub fn diff_pod(pre: Option<&PodAccount>, post: Option<&PodAccount>) -> Option, post: Option<&PodAccount>) -> Option 1, 2 => 2, 3 => 3, 4 => 4, 5 => 0, 6 => 0, 7 => 0], + storage: map_into![ + H256::from_low_u64_be(1) => H256::from_low_u64_be(1), + H256::from_low_u64_be(2) => H256::from_low_u64_be(2), + H256::from_low_u64_be(3) => H256::from_low_u64_be(3), + H256::from_low_u64_be(4) => H256::from_low_u64_be(4), + H256::from_low_u64_be(5) => H256::from_low_u64_be(0), + H256::from_low_u64_be(6) => H256::from_low_u64_be(0), + H256::from_low_u64_be(7) => H256::from_low_u64_be(0) + ], }; let b = PodAccount { balance: 0.into(), nonce: 0.into(), code: Some(vec![]), - storage: map_into![1 => 1, 2 => 3, 3 => 0, 5 => 0, 7 => 7, 8 => 0, 9 => 9], + storage: map_into![ + H256::from_low_u64_be(1) => H256::from_low_u64_be(1), + H256::from_low_u64_be(2) => H256::from_low_u64_be(3), + H256::from_low_u64_be(3) => H256::from_low_u64_be(0), + H256::from_low_u64_be(5) => H256::from_low_u64_be(0), + H256::from_low_u64_be(7) => H256::from_low_u64_be(7), + H256::from_low_u64_be(8) => H256::from_low_u64_be(0), + H256::from_low_u64_be(9) => H256::from_low_u64_be(9) + ], }; assert_eq!( diff_pod(Some(&a), Some(&b)), @@ -305,11 +328,11 @@ mod test { nonce: Diff::Same, code: Diff::Same, storage: map![ - 2.into() => Diff::new(2.into(), 3.into()), - 3.into() => Diff::new(3.into(), 0.into()), - 4.into() => Diff::new(4.into(), 0.into()), - 7.into() => Diff::new(0.into(), 7.into()), - 9.into() => Diff::new(0.into(), 9.into()) + H256::from_low_u64_be(2) => Diff::new(H256::from_low_u64_be(2), H256::from_low_u64_be(3)), + H256::from_low_u64_be(3) => Diff::new(H256::from_low_u64_be(3), H256::from_low_u64_be(0)), + H256::from_low_u64_be(4) => Diff::new(H256::from_low_u64_be(4), H256::from_low_u64_be(0)), + H256::from_low_u64_be(7) => Diff::new(H256::from_low_u64_be(0), H256::from_low_u64_be(7)), + H256::from_low_u64_be(9) => Diff::new(H256::from_low_u64_be(0), H256::from_low_u64_be(9)) ], }) ); diff --git a/crates/ethcore/src/pod_state.rs b/crates/ethcore/src/pod_state.rs index 5eafca568..c28797836 100644 --- a/crates/ethcore/src/pod_state.rs +++ b/crates/ethcore/src/pod_state.rs @@ -103,6 +103,7 @@ pub fn diff_pod(pre: &PodState, post: &PodState) -> StateDiff { #[cfg(test)] mod test { use super::PodState; + use ethereum_types::H160; use pod_account::PodAccount; use std::collections::BTreeMap; use types::{account_diff::*, state_diff::*}; @@ -110,7 +111,7 @@ mod test { #[test] fn create_delete() { let a = PodState::from(map![ - 1.into() => PodAccount { + H160::from_low_u64_be(1) => PodAccount { balance: 69.into(), nonce: 0.into(), code: Some(Vec::new()), @@ -121,7 +122,7 @@ mod test { super::diff_pod(&a, &PodState::new()), StateDiff { raw: map![ - 1.into() => AccountDiff{ + H160::from_low_u64_be(1) => AccountDiff{ balance: Diff::Died(69.into()), nonce: Diff::Died(0.into()), code: Diff::Died(vec![]), @@ -134,7 +135,7 @@ mod test { super::diff_pod(&PodState::new(), &a), StateDiff { raw: map![ - 1.into() => AccountDiff{ + H160::from_low_u64_be(1) => AccountDiff{ balance: Diff::Born(69.into()), nonce: Diff::Born(0.into()), code: Diff::Born(vec![]), @@ -148,7 +149,7 @@ mod test { #[test] fn create_delete_with_unchanged() { let a = PodState::from(map![ - 1.into() => PodAccount { + H160::from_low_u64_be(1) => PodAccount { balance: 69.into(), nonce: 0.into(), code: Some(Vec::new()), @@ -156,13 +157,13 @@ mod test { } ]); let b = PodState::from(map![ - 1.into() => PodAccount { + H160::from_low_u64_be(1) => PodAccount { balance: 69.into(), nonce: 0.into(), code: Some(Vec::new()), storage: map![], }, - 2.into() => PodAccount { + H160::from_low_u64_be(2) => PodAccount { balance: 69.into(), nonce: 0.into(), code: Some(Vec::new()), @@ -173,7 +174,7 @@ mod test { super::diff_pod(&a, &b), StateDiff { raw: map![ - 2.into() => AccountDiff{ + H160::from_low_u64_be(2) => AccountDiff{ balance: Diff::Born(69.into()), nonce: Diff::Born(0.into()), code: Diff::Born(vec![]), @@ -186,7 +187,7 @@ mod test { super::diff_pod(&b, &a), StateDiff { raw: map![ - 2.into() => AccountDiff{ + H160::from_low_u64_be(2) => AccountDiff{ balance: Diff::Died(69.into()), nonce: Diff::Died(0.into()), code: Diff::Died(vec![]), @@ -200,13 +201,13 @@ mod test { #[test] fn change_with_unchanged() { let a = PodState::from(map![ - 1.into() => PodAccount { + H160::from_low_u64_be(1) => PodAccount { balance: 69.into(), nonce: 0.into(), code: Some(Vec::new()), storage: map![], }, - 2.into() => PodAccount { + H160::from_low_u64_be(2) => PodAccount { balance: 69.into(), nonce: 0.into(), code: Some(Vec::new()), @@ -214,13 +215,13 @@ mod test { } ]); let b = PodState::from(map![ - 1.into() => PodAccount { + H160::from_low_u64_be(1) => PodAccount { balance: 69.into(), nonce: 1.into(), code: Some(Vec::new()), storage: map![], }, - 2.into() => PodAccount { + H160::from_low_u64_be(2) => PodAccount { balance: 69.into(), nonce: 0.into(), code: Some(Vec::new()), @@ -231,7 +232,7 @@ mod test { super::diff_pod(&a, &b), StateDiff { raw: map![ - 1.into() => AccountDiff{ + H160::from_low_u64_be(1) => AccountDiff{ balance: Diff::Same, nonce: Diff::Changed(0.into(), 1.into()), code: Diff::Same, diff --git a/crates/ethcore/src/snapshot/account.rs b/crates/ethcore/src/snapshot/account.rs index cb3f5e154..7ce25e72c 100644 --- a/crates/ethcore/src/snapshot/account.rs +++ b/crates/ethcore/src/snapshot/account.rs @@ -135,7 +135,7 @@ pub fn to_fat_rlps( stream.drain() }; if !account_stream.append_raw_checked(&pair, 1, target_chunk_size) { - account_stream.complete_unbounded_list(); + account_stream.finalize_unbounded_list(); let stream = ::std::mem::replace(&mut account_stream, RlpStream::new_list(2)); chunks.push(stream.out()); @@ -148,7 +148,7 @@ pub fn to_fat_rlps( return Err(e.into()); } None => { - account_stream.complete_unbounded_list(); + account_stream.finalize_unbounded_list(); let stream = ::std::mem::replace(&mut account_stream, RlpStream::new_list(2)); chunks.push(stream.out()); return Ok(chunks); diff --git a/crates/ethcore/src/snapshot/block.rs b/crates/ethcore/src/snapshot/block.rs index c602f6088..9b276621c 100644 --- a/crates/ethcore/src/snapshot/block.rs +++ b/crates/ethcore/src/snapshot/block.rs @@ -154,7 +154,12 @@ mod tests { let encoded = encode_block(&b); let abridged = AbridgedBlock::from_block_view(&view!(BlockView, &encoded)); - assert_eq!(abridged.to_block(H256::new(), 0, receipts_root).unwrap(), b); + assert_eq!( + abridged + .to_block(H256::default(), 0, receipts_root) + .unwrap(), + b + ); } #[test] @@ -165,7 +170,12 @@ mod tests { let encoded = encode_block(&b); let abridged = AbridgedBlock::from_block_view(&view!(BlockView, &encoded)); - assert_eq!(abridged.to_block(H256::new(), 2, receipts_root).unwrap(), b); + assert_eq!( + abridged + .to_block(H256::default(), 2, receipts_root) + .unwrap(), + b + ); } #[test] @@ -180,7 +190,7 @@ mod tests { value: U256::from(1), data: b"Hello!".to_vec(), }) - .fake_sign(Address::from(0x69)); + .fake_sign(Address::from_low_u64_be(0x69)); let t2 = TypedTransaction::Legacy(Transaction { action: Action::Create, @@ -190,7 +200,7 @@ mod tests { value: U256::from(1000000000), data: "Eep!".into(), }) - .fake_sign(Address::from(0x55)); + .fake_sign(Address::from_low_u64_be(0x55)); b.transactions.push(t1.into()); b.transactions.push(t2.into()); @@ -204,6 +214,11 @@ mod tests { let encoded = encode_block(&b); let abridged = AbridgedBlock::from_block_view(&view!(BlockView, &encoded[..])); - assert_eq!(abridged.to_block(H256::new(), 0, receipts_root).unwrap(), b); + assert_eq!( + abridged + .to_block(H256::default(), 0, receipts_root) + .unwrap(), + b + ); } } diff --git a/crates/ethcore/src/snapshot/consensus/work.rs b/crates/ethcore/src/snapshot/consensus/work.rs index ae9dc364b..5c5d5305a 100644 --- a/crates/ethcore/src/snapshot/consensus/work.rs +++ b/crates/ethcore/src/snapshot/consensus/work.rs @@ -35,7 +35,7 @@ use bytes::Bytes; use db::KeyValueDB; use engines::EthEngine; use ethereum_types::H256; -use rand::OsRng; +use rand::rngs::OsRng; use rlp::{Rlp, RlpStream}; use snapshot::{block::AbridgedBlock, Error, ManifestData, Progress}; use types::encoded; @@ -242,7 +242,7 @@ impl PowRebuilder { Ok(PowRebuilder { chain: chain, db: db, - rng: OsRng::new()?, + rng: OsRng, disconnected: Vec::new(), best_number: manifest.block_number, best_hash: manifest.block_hash, diff --git a/crates/ethcore/src/snapshot/mod.rs b/crates/ethcore/src/snapshot/mod.rs index 444b49429..32182de39 100644 --- a/crates/ethcore/src/snapshot/mod.rs +++ b/crates/ethcore/src/snapshot/mod.rs @@ -50,7 +50,7 @@ use trie::{Trie, TrieMut}; use self::io::SnapshotWriter; use crossbeam_utils::thread; -use rand::{OsRng, Rng}; +use rand::{rngs::OsRng, Rng}; pub use self::error::Error; @@ -496,7 +496,7 @@ impl StateRebuilder { return Err(Error::RestorationAborted.into()); } - account_trie.insert(&hash, &thin_rlp)?; + account_trie.insert(hash.as_bytes(), &thin_rlp)?; } } trace!(target: "snapshot", "current state root: {:?}", self.state_root); diff --git a/crates/ethcore/src/snapshot/tests/helpers.rs b/crates/ethcore/src/snapshot/tests/helpers.rs index 7203a51ff..fadc7067d 100644 --- a/crates/ethcore/src/snapshot/tests/helpers.rs +++ b/crates/ethcore/src/snapshot/tests/helpers.rs @@ -129,7 +129,7 @@ pub fn fill_storage(mut db: AccountDBMut, root: &mut H256, seed: &mut H256) { SecTrieDBMut::from_existing(&mut db, root).unwrap() }; - for (k, v) in map.make_with(seed) { + for (k, v) in map.make_with(&mut seed.to_fixed_bytes()) { trie.insert(&k, &v).unwrap(); } } diff --git a/crates/ethcore/src/snapshot/tests/proof_of_authority.rs b/crates/ethcore/src/snapshot/tests/proof_of_authority.rs index a68e90cb9..dc111a025 100644 --- a/crates/ethcore/src/snapshot/tests/proof_of_authority.rs +++ b/crates/ethcore/src/snapshot/tests/proof_of_authority.rs @@ -20,7 +20,7 @@ use std::{cell::RefCell, str::FromStr, sync::Arc}; use accounts::AccountProvider; use client::{BlockChainClient, ChainInfo, Client}; -use ethkey::Secret; +use crypto::publickey::Secret; use snapshot::tests::helpers as snapshot_helpers; use spec::Spec; use tempdir::TempDir; @@ -132,7 +132,7 @@ fn make_chain( nonce: *nonce, gas_price: 1.into(), gas: 21_000.into(), - action: Action::Call(Address::new()), + action: Action::Call(Address::default()), value: 1.into(), data: Vec::new(), }) diff --git a/crates/ethcore/src/snapshot/tests/service.rs b/crates/ethcore/src/snapshot/tests/service.rs index 90bdc1923..801c11a20 100644 --- a/crates/ethcore/src/snapshot/tests/service.rs +++ b/crates/ethcore/src/snapshot/tests/service.rs @@ -364,6 +364,8 @@ fn recover_aborted_recovery() { e => panic!("Snapshot restoration must be ongoing ; {:?}", e), } + service.abort_restore(); + // Remove the snapshot directory, and restart the restoration // It shouldn't have restored any previous blocks fs::remove_dir_all(tempdir.path()).unwrap(); diff --git a/crates/ethcore/src/snapshot/tests/state.rs b/crates/ethcore/src/snapshot/tests/state.rs index 03653acf6..39eb380c8 100644 --- a/crates/ethcore/src/snapshot/tests/state.rs +++ b/crates/ethcore/src/snapshot/tests/state.rs @@ -16,6 +16,8 @@ //! State snapshotting tests. +extern crate rand_xorshift; + use hash::{keccak, KECCAK_NULL_RLP}; use std::sync::{atomic::AtomicBool, Arc}; @@ -29,18 +31,21 @@ use types::basic_account::BasicAccount; use error::{Error, ErrorKind}; +use self::rand_xorshift::XorShiftRng; use ethereum_types::H256; use journaldb::{self, Algorithm}; use kvdb_rocksdb::{Database, DatabaseConfig}; use parking_lot::Mutex; -use rand::{SeedableRng, XorShiftRng}; +use rand::SeedableRng; use tempdir::TempDir; +const RNG_SEED: [u8; 16] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]; + #[test] fn snap_and_restore() { use hash_db::HashDB; let mut producer = StateProducer::new(); - let mut rng = XorShiftRng::from_seed([1, 2, 3, 4]); + let mut rng = XorShiftRng::from_seed(RNG_SEED); let mut old_db = journaldb::new_memory_db(); let db_cfg = DatabaseConfig::with_columns(::db::NUM_COLUMNS); @@ -190,7 +195,7 @@ fn get_code_from_prev_chunk() { #[test] fn checks_flag() { let mut producer = StateProducer::new(); - let mut rng = XorShiftRng::from_seed([5, 6, 7, 8]); + let mut rng = XorShiftRng::from_seed(RNG_SEED); let mut old_db = journaldb::new_memory_db(); let db_cfg = DatabaseConfig::with_columns(::db::NUM_COLUMNS); diff --git a/crates/ethcore/src/snapshot/watcher.rs b/crates/ethcore/src/snapshot/watcher.rs index d949c1c4a..968d1e08c 100644 --- a/crates/ethcore/src/snapshot/watcher.rs +++ b/crates/ethcore/src/snapshot/watcher.rs @@ -141,7 +141,7 @@ mod tests { use client::{ChainNotify, ChainRoute, NewBlocks}; - use ethereum_types::{H256, U256}; + use ethereum_types::{BigEndianHash, H256, U256}; use std::{collections::HashMap, time::Duration}; @@ -176,7 +176,7 @@ mod tests { let hashes: Vec<_> = numbers .clone() .into_iter() - .map(|x| H256::from(U256::from(x))) + .map(|x| BigEndianHash::from_uint(&U256::from(x))) .collect(); let map = hashes.clone().into_iter().zip(numbers).collect(); diff --git a/crates/ethcore/src/spec/spec.rs b/crates/ethcore/src/spec/spec.rs index 24688c21d..2d0bb719d 100644 --- a/crates/ethcore/src/spec/spec.rs +++ b/crates/ethcore/src/spec/spec.rs @@ -25,7 +25,7 @@ use std::{ }; use bytes::Bytes; -use ethereum_types::{Address, Bloom, H256, U256}; +use ethereum_types::{Address, Bloom, H160, H256, U256}; use ethjson; use hash::{keccak, KECCAK_NULL_RLP}; use parking_lot::RwLock; @@ -318,7 +318,9 @@ impl From for CommonParams { eip210_transition: p .eip210_transition .map_or_else(BlockNumber::max_value, Into::into), - eip210_contract_address: p.eip210_contract_address.map_or(0xf0.into(), Into::into), + eip210_contract_address: p + .eip210_contract_address + .map_or(H160::from_low_u64_be(0xf0), Into::into), eip210_contract_code: p.eip210_contract_code.map_or_else( || { DEFAULT_BLOCKHASH_CONTRACT @@ -382,7 +384,7 @@ impl From for CommonParams { nonce_cap_increment: p.nonce_cap_increment.map_or(64, Into::into), remove_dust_contracts: p.remove_dust_contracts.unwrap_or(false), gas_limit_bound_divisor: p.gas_limit_bound_divisor.into(), - registrar: p.registrar.map_or_else(Address::new, Into::into), + registrar: p.registrar.map_or_else(Address::default, Into::into), node_permission_contract: p.node_permission_contract.map(Into::into), max_code_size: p.max_code_size.map_or(u64::max_value(), Into::into), max_transaction_size: p @@ -742,7 +744,7 @@ impl Spec { let mut t = factories.trie.create(db.as_hash_db_mut(), &mut root); for (address, account) in self.genesis_state.get().iter() { - t.insert(&**address, &account.rlp())?; + t.insert(address.as_bytes(), &account.rlp())?; } } @@ -1119,7 +1121,9 @@ impl Spec { #[cfg(test)] mod tests { use super::*; + use ethereum_types::{H160, H256}; use state::State; + use std::str::FromStr; use tempdir::TempDir; use test_helpers::get_temp_state_db; use types::{view, views::BlockView}; @@ -1136,12 +1140,14 @@ mod tests { assert_eq!( test_spec.state_root(), - "f3f4696bbf3b3b07775128eb7a3763279a394e382130f27c21e70233e04946a9".into() + H256::from_str("f3f4696bbf3b3b07775128eb7a3763279a394e382130f27c21e70233e04946a9") + .unwrap() ); let genesis = test_spec.genesis_block(); assert_eq!( view!(BlockView, &genesis).header_view().hash(), - "0cd786a2425d16f152c658316c423e6ce1181e15c3295826d7c9904cba9ce303".into() + H256::from_str("0cd786a2425d16f152c658316c423e6ce1181e15c3295826d7c9904cba9ce303") + .unwrap() ); } @@ -1159,8 +1165,10 @@ mod tests { Default::default(), ) .unwrap(); - let expected = "0000000000000000000000000000000000000000000000000000000000000001".into(); - let address = "0000000000000000000000000000000000001337".into(); + let expected = + H256::from_str("0000000000000000000000000000000000000000000000000000000000000001") + .unwrap(); + let address = H160::from_str("0000000000000000000000000000000000001337").unwrap(); assert_eq!(state.storage_at(&address, &H256::zero()).unwrap(), expected); assert_eq!(state.balance(&address).unwrap(), 1.into()); diff --git a/crates/ethcore/src/state/account.rs b/crates/ethcore/src/state/account.rs index 799fc24d6..e524285c5 100644 --- a/crates/ethcore/src/state/account.rs +++ b/crates/ethcore/src/state/account.rs @@ -18,7 +18,7 @@ use bytes::{Bytes, ToPretty}; use error::Error; -use ethereum_types::{Address, H256, U256}; +use ethereum_types::{Address, BigEndianHash, H256, U256}; use ethtrie::{Result as TrieResult, SecTrieDB, TrieDB, TrieFactory}; use hash::{keccak, KECCAK_EMPTY, KECCAK_NULL_RLP}; use hash_db::HashDB; @@ -279,9 +279,9 @@ impl Account { let panicky_decoder = |bytes: &[u8]| ::rlp::decode(&bytes).expect("decoding db value failed"); let item: U256 = db - .get_with(key, panicky_decoder)? + .get_with(key.as_bytes(), panicky_decoder)? .unwrap_or_else(U256::zero); - let value: H256 = item.into(); + let value: H256 = BigEndianHash::from_uint(&item); storage_cache.insert(key.clone(), value.clone()); Ok(value) } @@ -311,7 +311,7 @@ impl Account { // If storage root is empty RLP, then early return zero value. Practically, this makes it so that if // `original_storage_cache` is used, then `storage_cache` will always remain empty. if self.storage_root == KECCAK_NULL_RLP { - return Some(H256::new()); + return Some(H256::default()); } self.storage_cache @@ -538,8 +538,8 @@ impl Account { // cast key and value to trait type, // so we can call overloaded `to_bytes` method match v.is_zero() { - true => t.remove(&k)?, - false => t.insert(&k, &encode(&U256::from(&*v)))?, + true => t.remove(k.as_bytes())?, + false => t.insert(k.as_bytes(), &encode(&v.into_uint()))?, }; self.storage_cache.borrow_mut().insert(k, v); @@ -661,13 +661,13 @@ impl Account { let panicky_decoder = |bytes: &[u8]| ::rlp::decode(bytes).expect("decoding db value failed"); let query = (&mut recorder, panicky_decoder); - trie.get_with(&storage_key, query)? + trie.get_with(storage_key.as_bytes(), query)? .unwrap_or_else(U256::zero) }; Ok(( recorder.drain().into_iter().map(|r| r.data).collect(), - item.into(), + BigEndianHash::from_uint(&item), )) } } @@ -694,6 +694,7 @@ mod tests { use ethereum_types::{Address, H256}; use journaldb::new_memory_db; use rlp_compress::{compress, decompress, snapshot_swapper}; + use std::str::FromStr; #[test] fn account_compress() { @@ -707,10 +708,13 @@ mod tests { #[test] fn storage_at() { let mut db = new_memory_db(); - let mut db = AccountDBMut::new(&mut db, &Address::new()); + let mut db = AccountDBMut::new(&mut db, &Address::default()); let rlp = { let mut a = Account::new_contract(69.into(), 0.into(), KECCAK_NULL_RLP); - a.set_storage(0x00u64.into(), 0x1234u64.into()); + a.set_storage( + H256::from_low_u64_be(0x00u64), + H256::from_low_u64_be(0x1234u64), + ); a.commit_storage(&Default::default(), &mut db).unwrap(); a.init_code(vec![]); a.commit_code(&mut db); @@ -720,14 +724,17 @@ mod tests { let a = Account::from_rlp(&rlp).expect("decoding db value failed"); assert_eq!( a.storage_root().unwrap(), - "c57e1afb758b07f8d2c8f13a3b6e44fa5ff94ab266facc5a4fd3f062426e50b2".into() + H256::from_str("c57e1afb758b07f8d2c8f13a3b6e44fa5ff94ab266facc5a4fd3f062426e50b2") + .unwrap() ); assert_eq!( - a.storage_at(&db.immutable(), &0x00u64.into()).unwrap(), - 0x1234u64.into() + a.storage_at(&db.immutable(), &H256::from_low_u64_be(0x00u64)) + .unwrap(), + H256::from_low_u64_be(0x1234u64) ); assert_eq!( - a.storage_at(&db.immutable(), &0x01u64.into()).unwrap(), + a.storage_at(&db.immutable(), &H256::from_low_u64_be(0x01u64)) + .unwrap(), H256::default() ); } @@ -735,7 +742,7 @@ mod tests { #[test] fn note_code() { let mut db = new_memory_db(); - let mut db = AccountDBMut::new(&mut db, &Address::new()); + let mut db = AccountDBMut::new(&mut db, &Address::default()); let rlp = { let mut a = Account::new_contract(69.into(), 0.into(), KECCAK_NULL_RLP); @@ -755,13 +762,14 @@ mod tests { fn commit_storage() { let mut a = Account::new_contract(69.into(), 0.into(), KECCAK_NULL_RLP); let mut db = new_memory_db(); - let mut db = AccountDBMut::new(&mut db, &Address::new()); - a.set_storage(0.into(), 0x1234.into()); + let mut db = AccountDBMut::new(&mut db, &Address::default()); + a.set_storage(H256::from_low_u64_be(0), H256::from_low_u64_be(0x1234)); assert_eq!(a.storage_root(), None); a.commit_storage(&Default::default(), &mut db).unwrap(); assert_eq!( a.storage_root().unwrap(), - "c57e1afb758b07f8d2c8f13a3b6e44fa5ff94ab266facc5a4fd3f062426e50b2".into() + H256::from_str("c57e1afb758b07f8d2c8f13a3b6e44fa5ff94ab266facc5a4fd3f062426e50b2") + .unwrap() ); } @@ -769,16 +777,17 @@ mod tests { fn commit_remove_commit_storage() { let mut a = Account::new_contract(69.into(), 0.into(), KECCAK_NULL_RLP); let mut db = new_memory_db(); - let mut db = AccountDBMut::new(&mut db, &Address::new()); - a.set_storage(0.into(), 0x1234.into()); + let mut db = AccountDBMut::new(&mut db, &Address::default()); + a.set_storage(H256::from_low_u64_be(0), H256::from_low_u64_be(0x1234)); a.commit_storage(&Default::default(), &mut db).unwrap(); - a.set_storage(1.into(), 0x1234.into()); + a.set_storage(H256::from_low_u64_be(1), H256::from_low_u64_be(0x1234)); a.commit_storage(&Default::default(), &mut db).unwrap(); - a.set_storage(1.into(), 0.into()); + a.set_storage(H256::from_low_u64_be(1), H256::from_low_u64_be(0)); a.commit_storage(&Default::default(), &mut db).unwrap(); assert_eq!( a.storage_root().unwrap(), - "c57e1afb758b07f8d2c8f13a3b6e44fa5ff94ab266facc5a4fd3f062426e50b2".into() + H256::from_str("c57e1afb758b07f8d2c8f13a3b6e44fa5ff94ab266facc5a4fd3f062426e50b2") + .unwrap() ); } @@ -786,14 +795,15 @@ mod tests { fn commit_code() { let mut a = Account::new_contract(69.into(), 0.into(), KECCAK_NULL_RLP); let mut db = new_memory_db(); - let mut db = AccountDBMut::new(&mut db, &Address::new()); + let mut db = AccountDBMut::new(&mut db, &Address::default()); a.init_code(vec![0x55, 0x44, 0xffu8]); assert_eq!(a.code_filth, Filth::Dirty); assert_eq!(a.code_size(), Some(3)); a.commit_code(&mut db); assert_eq!( a.code_hash(), - "af231e631776a517ca23125370d542873eca1fb4d613ed9b5d5335a46ae5b7eb".into() + H256::from_str("af231e631776a517ca23125370d542873eca1fb4d613ed9b5d5335a46ae5b7eb") + .unwrap() ); } @@ -801,21 +811,23 @@ mod tests { fn reset_code() { let mut a = Account::new_contract(69.into(), 0.into(), KECCAK_NULL_RLP); let mut db = new_memory_db(); - let mut db = AccountDBMut::new(&mut db, &Address::new()); + let mut db = AccountDBMut::new(&mut db, &Address::default()); a.init_code(vec![0x55, 0x44, 0xffu8]); assert_eq!(a.code_filth, Filth::Dirty); a.commit_code(&mut db); assert_eq!(a.code_filth, Filth::Clean); assert_eq!( a.code_hash(), - "af231e631776a517ca23125370d542873eca1fb4d613ed9b5d5335a46ae5b7eb".into() + H256::from_str("af231e631776a517ca23125370d542873eca1fb4d613ed9b5d5335a46ae5b7eb") + .unwrap() ); a.reset_code(vec![0x55]); assert_eq!(a.code_filth, Filth::Dirty); a.commit_code(&mut db); assert_eq!( a.code_hash(), - "37bf2238b11b68cdc8382cece82651b59d3c3988873b6e0f33d79694aa45f1be".into() + H256::from_str("37bf2238b11b68cdc8382cece82651b59d3c3988873b6e0f33d79694aa45f1be") + .unwrap() ); } diff --git a/crates/ethcore/src/state/mod.rs b/crates/ethcore/src/state/mod.rs index f15e2b77d..2617412c2 100644 --- a/crates/ethcore/src/state/mod.rs +++ b/crates/ethcore/src/state/mod.rs @@ -371,7 +371,7 @@ impl State { /// Creates new state with empty state root /// Used for tests. pub fn new(mut db: B, account_start_nonce: U256, factories: Factories) -> State { - let mut root = H256::new(); + let mut root = H256::default(); { // init trie and reset root to null let _ = factories.trie.create(db.as_hash_db_mut(), &mut root); @@ -528,7 +528,7 @@ impl State { let (nonce, overflow) = self.account_start_nonce.overflowing_add(nonce_offset); if overflow { return Err(Box::new(TrieError::DecoderError( - H256::from(contract), + H256::from(contract.clone()), rlp::DecoderError::Custom("Nonce overflow".into()), ))); } @@ -658,12 +658,14 @@ impl State { // would always be empty. Note that this branch is actually never called, because // `cached_storage_at` handled this case. warn!(target: "state", "Trying to get an account's cached storage value, but base storage root does not equal to original storage root! Assuming the value is empty."); - return Ok(Some(H256::new())); + return Ok(Some(H256::default())); } } } // The account didn't exist at that point. Return empty value. - Some(Some(AccountEntry { account: None, .. })) => return Ok(Some(H256::new())), + Some(Some(AccountEntry { account: None, .. })) => { + return Ok(Some(H256::default())) + } // The value was not cached at that checkpoint, meaning it was not modified at all. Some(None) => { kind = Some(ReturnKind::OriginalAt); @@ -718,12 +720,12 @@ impl State { local_account = Some(maybe_acc); } } - _ => return Ok(H256::new()), + _ => return Ok(H256::default()), } } // check the global cache and and cache storage key there if found, let trie_res = self.db.get_cached(address, |acc| match acc { - None => Ok(H256::new()), + None => Ok(H256::default()), Some(a) => { let account_db = self .factories @@ -746,7 +748,7 @@ impl State { .readonly(self.db.as_hash_db(), account.address_hash(address)); return f_at(account, account_db.as_hash_db(), key); } else { - return Ok(H256::new()); + return Ok(H256::default()); } } } @@ -759,8 +761,8 @@ impl State { .readonly(db, &self.root) .expect(SEC_TRIE_DB_UNWRAP_STR); let from_rlp = |b: &[u8]| Account::from_rlp(b).expect("decoding db value failed"); - let maybe_acc = db.get_with(address, from_rlp)?; - let r = maybe_acc.as_ref().map_or(Ok(H256::new()), |a| { + let maybe_acc = db.get_with(address.as_bytes(), from_rlp)?; + let r = maybe_acc.as_ref().map_or(Ok(H256::zero()), |a| { let account_db = self .factories .accountdb @@ -1025,10 +1027,10 @@ impl State { a.state = AccountState::Committed; match a.account { Some(ref mut account) => { - trie.insert(address, &account.rlp())?; + trie.insert(address.as_bytes(), &account.rlp())?; } None => { - trie.remove(address)?; + trie.remove(address.as_bytes())?; } }; } @@ -1151,6 +1153,7 @@ impl State { account: &Account, address: &Address, ) -> Result { + use ethereum_types::BigEndianHash; let mut pod_storage = BTreeMap::new(); let addr_hash = account.address_hash(address); let accountdb = self @@ -1164,10 +1167,11 @@ impl State { for o_kv in trie.iter()? { if let Ok((key, val)) = o_kv { pod_storage.insert( - key[..].into(), - rlp::decode::(&val[..]) - .expect("Decoded from trie which was encoded from the same type; qed") - .into(), + H256::from_slice(&key[..]), + BigEndianHash::from_uint( + &rlp::decode::(&val[..]) + .expect("Decoded from trie which was encoded from the same type; qed"), + ), ); } } @@ -1327,7 +1331,7 @@ impl State { if Self::update_account_cache(require, account, &self.db, accountdb.as_hash_db()) { return Ok(f(Some(account))); } else { - return Err(Box::new(TrieError::IncompleteDatabase(H256::from(a)))); + return Err(Box::new(TrieError::IncompleteDatabase(H256::from(*a)))); } } return Ok(f(None)); @@ -1340,7 +1344,7 @@ impl State { .accountdb .readonly(self.db.as_hash_db(), account.address_hash(a)); if !Self::update_account_cache(require, account, &self.db, accountdb.as_hash_db()) { - return Err(Box::new(TrieError::IncompleteDatabase(H256::from(a)))); + return Err(Box::new(TrieError::IncompleteDatabase(H256::from(*a)))); } } Ok(f(acc.map(|a| &*a))) @@ -1352,7 +1356,7 @@ impl State { let db = &self.db.as_hash_db(); let db = self.factories.trie.readonly(db, &self.root)?; let from_rlp = |b: &[u8]| Account::from_rlp(b).expect("decoding db value failed"); - let mut maybe_acc = db.get_with(a, from_rlp)?; + let mut maybe_acc = db.get_with(a.as_bytes(), from_rlp)?; if let Some(ref mut account) = maybe_acc.as_mut() { let accountdb = self .factories @@ -1364,7 +1368,7 @@ impl State { &self.db, accountdb.as_hash_db(), ) { - return Err(Box::new(TrieError::IncompleteDatabase(H256::from(a)))); + return Err(Box::new(TrieError::IncompleteDatabase(H256::from(*a)))); } } let r = f(maybe_acc.as_ref()); @@ -1406,7 +1410,7 @@ impl State { let db = self.factories.trie.readonly(db, &self.root)?; let from_rlp = |b: &[u8]| Account::from_rlp(b).expect("decoding db value failed"); - let maybe_acc = AccountEntry::new_clean(db.get_with(a, from_rlp)?); + let maybe_acc = AccountEntry::new_clean(db.get_with(a.as_bytes(), from_rlp)?); self.insert_cache(a, maybe_acc); } } @@ -1445,7 +1449,7 @@ impl State { &self.db, accountdb.as_hash_db(), ) { - return Err(Box::new(TrieError::IncompleteDatabase(H256::from(a)))); + return Err(Box::new(TrieError::IncompleteDatabase(H256::from(*a)))); } } @@ -1486,7 +1490,7 @@ impl State { }) }; let query = (&mut recorder, panicky_decoder); - trie.get_with(&account_key, query)? + trie.get_with(account_key.as_bytes(), query)? }; let account = maybe_account.unwrap_or_else(|| BasicAccount { balance: 0.into(), @@ -1516,9 +1520,9 @@ impl State { let db = &self.db.as_hash_db(); let trie = TrieDB::new(db, &self.root)?; let from_rlp = |b: &[u8]| Account::from_rlp(b).expect("decoding db value failed"); - let acc = match trie.get_with(&account_key, from_rlp)? { + let acc = match trie.get_with(account_key.as_bytes(), from_rlp)? { Some(acc) => acc, - None => return Ok((Vec::new(), H256::new())), + None => return Ok((Vec::new(), H256::default())), }; let account_db = self @@ -1570,8 +1574,8 @@ impl Clone for State { #[cfg(test)] mod tests { use super::*; - use ethereum_types::{Address, H256, U256}; - use ethkey::Secret; + use crypto::publickey::Secret; + use ethereum_types::{Address, BigEndianHash, H256, U256}; use evm::CallType; use hash::{keccak, KECCAK_NULL_RLP}; use machine::EthereumMachine; @@ -1622,7 +1626,7 @@ mod tests { trace_address: Default::default(), subtraces: 0, action: trace::Action::Create(trace::Create { - from: "9cce34f7ab185c7aba1b7c8140d620b4bda941d6".into(), + from: Address::from_str("9cce34f7ab185c7aba1b7c8140d620b4bda941d6").unwrap(), value: 100.into(), gas: 77412.into(), init: vec![ @@ -1685,7 +1689,7 @@ mod tests { let expected_trace = vec![FlatTrace { trace_address: Default::default(), action: trace::Action::Create(trace::Create { - from: "9cce34f7ab185c7aba1b7c8140d620b4bda941d6".into(), + from: Address::from_str("9cce34f7ab185c7aba1b7c8140d620b4bda941d6").unwrap(), value: 100.into(), gas: 78792.into(), init: vec![91, 96, 0, 86], @@ -1711,14 +1715,17 @@ mod tests { nonce: 0.into(), gas_price: 0.into(), gas: 100_000.into(), - action: Action::Call(0xa.into()), + action: Action::Call(Address::from_low_u64_be(0xa)), value: 100.into(), data: vec![], }) .sign(&secret(), None); state - .init_code(&0xa.into(), FromHex::from_hex("6000").unwrap()) + .init_code( + &Address::from_low_u64_be(0xa), + FromHex::from_hex("6000").unwrap(), + ) .unwrap(); state .add_balance(&t.sender(), &(100.into()), CleanupMode::NoEmpty) @@ -1727,8 +1734,8 @@ mod tests { let expected_trace = vec![FlatTrace { trace_address: Default::default(), action: trace::Action::Call(trace::Call { - from: "9cce34f7ab185c7aba1b7c8140d620b4bda941d6".into(), - to: 0xa.into(), + from: Address::from_str("9cce34f7ab185c7aba1b7c8140d620b4bda941d6").unwrap(), + to: Address::from_low_u64_be(0xa), value: 100.into(), gas: 79000.into(), input: vec![], @@ -1758,7 +1765,7 @@ mod tests { nonce: 0.into(), gas_price: 0.into(), gas: 100_000.into(), - action: Action::Call(0xa.into()), + action: Action::Call(Address::from_low_u64_be(0xa)), value: 100.into(), data: vec![], }) @@ -1771,8 +1778,8 @@ mod tests { let expected_trace = vec![FlatTrace { trace_address: Default::default(), action: trace::Action::Call(trace::Call { - from: "9cce34f7ab185c7aba1b7c8140d620b4bda941d6".into(), - to: 0xa.into(), + from: Address::from_str("9cce34f7ab185c7aba1b7c8140d620b4bda941d6").unwrap(), + to: Address::from_low_u64_be(0xa), value: 100.into(), gas: 79000.into(), input: vec![], @@ -1802,7 +1809,7 @@ mod tests { nonce: 0.into(), gas_price: 0.into(), gas: 100_000.into(), - action: Action::Call(0x1.into()), + action: Action::Call(Address::from_low_u64_be(0x1)), value: 0.into(), data: vec![], }) @@ -1813,8 +1820,8 @@ mod tests { let expected_trace = vec![FlatTrace { trace_address: Default::default(), action: trace::Action::Call(trace::Call { - from: "9cce34f7ab185c7aba1b7c8140d620b4bda941d6".into(), - to: "0000000000000000000000000000000000000001".into(), + from: Address::from_str("9cce34f7ab185c7aba1b7c8140d620b4bda941d6").unwrap(), + to: Address::from_str("0000000000000000000000000000000000000001").unwrap(), value: 0.into(), gas: 79_000.into(), input: vec![], @@ -1844,7 +1851,7 @@ mod tests { nonce: 0.into(), gas_price: 0.into(), gas: 100_000.into(), - action: Action::Call(0xa.into()), + action: Action::Call(Address::from_low_u64_be(0xa)), value: 0.into(), data: vec![], }) @@ -1852,7 +1859,7 @@ mod tests { state .init_code( - &0xa.into(), + &Address::from_low_u64_be(0xa), FromHex::from_hex("600060006000600060006001610be0f1").unwrap(), ) .unwrap(); @@ -1861,8 +1868,8 @@ mod tests { let expected_trace = vec![FlatTrace { trace_address: Default::default(), action: trace::Action::Call(trace::Call { - from: "9cce34f7ab185c7aba1b7c8140d620b4bda941d6".into(), - to: 0xa.into(), + from: Address::from_str("9cce34f7ab185c7aba1b7c8140d620b4bda941d6").unwrap(), + to: Address::from_low_u64_be(0xa), value: 0.into(), gas: 79000.into(), input: vec![], @@ -1892,7 +1899,7 @@ mod tests { nonce: 0.into(), gas_price: 0.into(), gas: 100_000.into(), - action: Action::Call(0xa.into()), + action: Action::Call(Address::from_low_u64_be(0xa)), value: 0.into(), data: vec![], }) @@ -1900,12 +1907,15 @@ mod tests { state .init_code( - &0xa.into(), + &Address::from_low_u64_be(0xa), FromHex::from_hex("60006000600060006000600b611000f2").unwrap(), ) .unwrap(); state - .init_code(&0xb.into(), FromHex::from_hex("6000").unwrap()) + .init_code( + &Address::from_low_u64_be(0xb), + FromHex::from_hex("6000").unwrap(), + ) .unwrap(); let result = state.apply(&info, &machine, &t, true).unwrap(); @@ -1914,8 +1924,8 @@ mod tests { trace_address: Default::default(), subtraces: 1, action: trace::Action::Call(trace::Call { - from: "9cce34f7ab185c7aba1b7c8140d620b4bda941d6".into(), - to: 0xa.into(), + from: Address::from_str("9cce34f7ab185c7aba1b7c8140d620b4bda941d6").unwrap(), + to: Address::from_low_u64_be(0xa), value: 0.into(), gas: 79000.into(), input: vec![], @@ -1930,8 +1940,8 @@ mod tests { trace_address: vec![0].into_iter().collect(), subtraces: 0, action: trace::Action::Call(trace::Call { - from: 0xa.into(), - to: 0xb.into(), + from: Address::from_low_u64_be(0xa), + to: Address::from_low_u64_be(0xb), value: 0.into(), gas: 4096.into(), input: vec![], @@ -1962,7 +1972,7 @@ mod tests { nonce: 0.into(), gas_price: 0.into(), gas: 100_000.into(), - action: Action::Call(0xa.into()), + action: Action::Call(Address::from_low_u64_be(0xa)), value: 0.into(), data: vec![], }) @@ -1970,13 +1980,13 @@ mod tests { state .init_code( - &0xa.into(), + &Address::from_low_u64_be(0xa), FromHex::from_hex("6000600060006000600b618000f4").unwrap(), ) .unwrap(); state .init_code( - &0xb.into(), + &Address::from_low_u64_be(0xb), FromHex::from_hex("60056000526001601ff3").unwrap(), ) .unwrap(); @@ -1987,8 +1997,8 @@ mod tests { trace_address: Default::default(), subtraces: 1, action: trace::Action::Call(trace::Call { - from: "9cce34f7ab185c7aba1b7c8140d620b4bda941d6".into(), - to: 0xa.into(), + from: Address::from_str("9cce34f7ab185c7aba1b7c8140d620b4bda941d6").unwrap(), + to: Address::from_low_u64_be(0xa), value: 0.into(), gas: 79000.into(), input: vec![], @@ -2003,8 +2013,8 @@ mod tests { trace_address: vec![0].into_iter().collect(), subtraces: 0, action: trace::Action::Call(trace::Call { - from: 0xa.into(), - to: 0xb.into(), + from: Address::from_low_u64_be(0xa), + to: Address::from_low_u64_be(0xb), value: 0.into(), gas: 32768.into(), input: vec![], @@ -2034,14 +2044,17 @@ mod tests { nonce: 0.into(), gas_price: 0.into(), gas: 100_000.into(), - action: Action::Call(0xa.into()), + action: Action::Call(Address::from_low_u64_be(0xa)), value: 100.into(), data: vec![], }) .sign(&secret(), None); state - .init_code(&0xa.into(), FromHex::from_hex("5b600056").unwrap()) + .init_code( + &Address::from_low_u64_be(0xa), + FromHex::from_hex("5b600056").unwrap(), + ) .unwrap(); state .add_balance(&t.sender(), &(100.into()), CleanupMode::NoEmpty) @@ -2050,8 +2063,8 @@ mod tests { let expected_trace = vec![FlatTrace { trace_address: Default::default(), action: trace::Action::Call(trace::Call { - from: "9cce34f7ab185c7aba1b7c8140d620b4bda941d6".into(), - to: 0xa.into(), + from: Address::from_str("9cce34f7ab185c7aba1b7c8140d620b4bda941d6").unwrap(), + to: Address::from_low_u64_be(0xa), value: 100.into(), gas: 79000.into(), input: vec![], @@ -2078,7 +2091,7 @@ mod tests { nonce: 0.into(), gas_price: 0.into(), gas: 100_000.into(), - action: Action::Call(0xa.into()), + action: Action::Call(Address::from_low_u64_be(0xa)), value: 100.into(), data: vec![], }) @@ -2086,12 +2099,15 @@ mod tests { state .init_code( - &0xa.into(), + &Address::from_low_u64_be(0xa), FromHex::from_hex("60006000600060006000600b602b5a03f1").unwrap(), ) .unwrap(); state - .init_code(&0xb.into(), FromHex::from_hex("6000").unwrap()) + .init_code( + &Address::from_low_u64_be(0xb), + FromHex::from_hex("6000").unwrap(), + ) .unwrap(); state .add_balance(&t.sender(), &(100.into()), CleanupMode::NoEmpty) @@ -2103,8 +2119,8 @@ mod tests { trace_address: Default::default(), subtraces: 1, action: trace::Action::Call(trace::Call { - from: "9cce34f7ab185c7aba1b7c8140d620b4bda941d6".into(), - to: 0xa.into(), + from: Address::from_str("9cce34f7ab185c7aba1b7c8140d620b4bda941d6").unwrap(), + to: Address::from_low_u64_be(0xa), value: 100.into(), gas: 79000.into(), input: vec![], @@ -2119,8 +2135,8 @@ mod tests { trace_address: vec![0].into_iter().collect(), subtraces: 0, action: trace::Action::Call(trace::Call { - from: 0xa.into(), - to: 0xb.into(), + from: Address::from_low_u64_be(0xa), + to: Address::from_low_u64_be(0xb), value: 0.into(), gas: 78934.into(), input: vec![], @@ -2150,7 +2166,7 @@ mod tests { nonce: 0.into(), gas_price: 0.into(), gas: 100_000.into(), - action: Action::Call(0xa.into()), + action: Action::Call(Address::from_low_u64_be(0xa)), value: 100.into(), data: vec![], }) @@ -2158,7 +2174,7 @@ mod tests { state .init_code( - &0xa.into(), + &Address::from_low_u64_be(0xa), FromHex::from_hex("60006000600060006045600b6000f1").unwrap(), ) .unwrap(); @@ -2171,8 +2187,8 @@ mod tests { trace_address: Default::default(), subtraces: 1, action: trace::Action::Call(trace::Call { - from: "9cce34f7ab185c7aba1b7c8140d620b4bda941d6".into(), - to: 0xa.into(), + from: Address::from_str("9cce34f7ab185c7aba1b7c8140d620b4bda941d6").unwrap(), + to: Address::from_low_u64_be(0xa), value: 100.into(), gas: 79000.into(), input: vec![], @@ -2187,8 +2203,8 @@ mod tests { trace_address: vec![0].into_iter().collect(), subtraces: 0, action: trace::Action::Call(trace::Call { - from: 0xa.into(), - to: 0xb.into(), + from: Address::from_low_u64_be(0xa), + to: Address::from_low_u64_be(0xb), value: 69.into(), gas: 2300.into(), input: vec![], @@ -2215,7 +2231,7 @@ mod tests { nonce: 0.into(), gas_price: 0.into(), gas: 100_000.into(), - action: Action::Call(0xa.into()), + action: Action::Call(Address::from_low_u64_be(0xa)), value: 100.into(), data: vec![], }) @@ -2223,7 +2239,7 @@ mod tests { state .init_code( - &0xa.into(), + &Address::from_low_u64_be(0xa), FromHex::from_hex("600060006000600060ff600b6000f1").unwrap(), ) .unwrap(); // not enough funds. @@ -2235,8 +2251,8 @@ mod tests { trace_address: Default::default(), subtraces: 0, action: trace::Action::Call(trace::Call { - from: "9cce34f7ab185c7aba1b7c8140d620b4bda941d6".into(), - to: 0xa.into(), + from: Address::from_str("9cce34f7ab185c7aba1b7c8140d620b4bda941d6").unwrap(), + to: Address::from_low_u64_be(0xa), value: 100.into(), gas: 79000.into(), input: vec![], @@ -2265,7 +2281,7 @@ mod tests { nonce: 0.into(), gas_price: 0.into(), gas: 100_000.into(), - action: Action::Call(0xa.into()), + action: Action::Call(Address::from_low_u64_be(0xa)), value: 100.into(), data: vec![], //600480600b6000396000f35b600056 }) @@ -2273,12 +2289,15 @@ mod tests { state .init_code( - &0xa.into(), + &Address::from_low_u64_be(0xa), FromHex::from_hex("60006000600060006000600b602b5a03f1").unwrap(), ) .unwrap(); state - .init_code(&0xb.into(), FromHex::from_hex("5b600056").unwrap()) + .init_code( + &Address::from_low_u64_be(0xb), + FromHex::from_hex("5b600056").unwrap(), + ) .unwrap(); state .add_balance(&t.sender(), &(100.into()), CleanupMode::NoEmpty) @@ -2289,8 +2308,8 @@ mod tests { trace_address: Default::default(), subtraces: 1, action: trace::Action::Call(trace::Call { - from: "9cce34f7ab185c7aba1b7c8140d620b4bda941d6".into(), - to: 0xa.into(), + from: Address::from_str("9cce34f7ab185c7aba1b7c8140d620b4bda941d6").unwrap(), + to: Address::from_low_u64_be(0xa), value: 100.into(), gas: 79000.into(), input: vec![], @@ -2305,8 +2324,8 @@ mod tests { trace_address: vec![0].into_iter().collect(), subtraces: 0, action: trace::Action::Call(trace::Call { - from: 0xa.into(), - to: 0xb.into(), + from: Address::from_low_u64_be(0xa), + to: Address::from_low_u64_be(0xb), value: 0.into(), gas: 78934.into(), input: vec![], @@ -2333,7 +2352,7 @@ mod tests { nonce: 0.into(), gas_price: 0.into(), gas: 100_000.into(), - action: Action::Call(0xa.into()), + action: Action::Call(Address::from_low_u64_be(0xa)), value: 100.into(), data: vec![], }) @@ -2341,18 +2360,21 @@ mod tests { state .init_code( - &0xa.into(), + &Address::from_low_u64_be(0xa), FromHex::from_hex("60006000600060006000600b602b5a03f1").unwrap(), ) .unwrap(); state .init_code( - &0xb.into(), + &Address::from_low_u64_be(0xb), FromHex::from_hex("60006000600060006000600c602b5a03f1").unwrap(), ) .unwrap(); state - .init_code(&0xc.into(), FromHex::from_hex("6000").unwrap()) + .init_code( + &Address::from_low_u64_be(0xc), + FromHex::from_hex("6000").unwrap(), + ) .unwrap(); state .add_balance(&t.sender(), &(100.into()), CleanupMode::NoEmpty) @@ -2363,8 +2385,8 @@ mod tests { trace_address: Default::default(), subtraces: 1, action: trace::Action::Call(trace::Call { - from: "9cce34f7ab185c7aba1b7c8140d620b4bda941d6".into(), - to: 0xa.into(), + from: Address::from_str("9cce34f7ab185c7aba1b7c8140d620b4bda941d6").unwrap(), + to: Address::from_low_u64_be(0xa), value: 100.into(), gas: 79000.into(), input: vec![], @@ -2379,8 +2401,8 @@ mod tests { trace_address: vec![0].into_iter().collect(), subtraces: 1, action: trace::Action::Call(trace::Call { - from: 0xa.into(), - to: 0xb.into(), + from: Address::from_low_u64_be(0xa), + to: Address::from_low_u64_be(0xb), value: 0.into(), gas: 78934.into(), input: vec![], @@ -2395,8 +2417,8 @@ mod tests { trace_address: vec![0, 0].into_iter().collect(), subtraces: 0, action: trace::Action::Call(trace::Call { - from: 0xb.into(), - to: 0xc.into(), + from: Address::from_low_u64_be(0xb), + to: Address::from_low_u64_be(0xc), value: 0.into(), gas: 78868.into(), input: vec![], @@ -2426,7 +2448,7 @@ mod tests { nonce: 0.into(), gas_price: 0.into(), gas: 100_000.into(), - action: Action::Call(0xa.into()), + action: Action::Call(Address::from_low_u64_be(0xa)), value: 100.into(), data: vec![], //600480600b6000396000f35b600056 }) @@ -2434,18 +2456,21 @@ mod tests { state .init_code( - &0xa.into(), + &Address::from_low_u64_be(0xa), FromHex::from_hex("60006000600060006000600b602b5a03f1").unwrap(), ) .unwrap(); state .init_code( - &0xb.into(), + &Address::from_low_u64_be(0xb), FromHex::from_hex("60006000600060006000600c602b5a03f1505b601256").unwrap(), ) .unwrap(); state - .init_code(&0xc.into(), FromHex::from_hex("6000").unwrap()) + .init_code( + &Address::from_low_u64_be(0xc), + FromHex::from_hex("6000").unwrap(), + ) .unwrap(); state .add_balance(&t.sender(), &(100.into()), CleanupMode::NoEmpty) @@ -2457,8 +2482,8 @@ mod tests { trace_address: Default::default(), subtraces: 1, action: trace::Action::Call(trace::Call { - from: "9cce34f7ab185c7aba1b7c8140d620b4bda941d6".into(), - to: 0xa.into(), + from: Address::from_str("9cce34f7ab185c7aba1b7c8140d620b4bda941d6").unwrap(), + to: Address::from_low_u64_be(0xa), value: 100.into(), gas: 79000.into(), input: vec![], @@ -2473,8 +2498,8 @@ mod tests { trace_address: vec![0].into_iter().collect(), subtraces: 1, action: trace::Action::Call(trace::Call { - from: 0xa.into(), - to: 0xb.into(), + from: Address::from_low_u64_be(0xa), + to: Address::from_low_u64_be(0xb), value: 0.into(), gas: 78934.into(), input: vec![], @@ -2486,8 +2511,8 @@ mod tests { trace_address: vec![0, 0].into_iter().collect(), subtraces: 0, action: trace::Action::Call(trace::Call { - from: 0xb.into(), - to: 0xc.into(), + from: Address::from_low_u64_be(0xb), + to: Address::from_low_u64_be(0xc), value: 0.into(), gas: 78868.into(), call_type: CallType::Call, @@ -2517,7 +2542,7 @@ mod tests { nonce: 0.into(), gas_price: 0.into(), gas: 100_000.into(), - action: Action::Call(0xa.into()), + action: Action::Call(Address::from_low_u64_be(0xa)), value: 100.into(), data: vec![], }) @@ -2525,12 +2550,16 @@ mod tests { state .init_code( - &0xa.into(), + &Address::from_low_u64_be(0xa), FromHex::from_hex("73000000000000000000000000000000000000000bff").unwrap(), ) .unwrap(); state - .add_balance(&0xa.into(), &50.into(), CleanupMode::NoEmpty) + .add_balance( + &Address::from_low_u64_be(0xa), + &50.into(), + CleanupMode::NoEmpty, + ) .unwrap(); state .add_balance(&t.sender(), &100.into(), CleanupMode::NoEmpty) @@ -2541,8 +2570,8 @@ mod tests { trace_address: Default::default(), subtraces: 1, action: trace::Action::Call(trace::Call { - from: "9cce34f7ab185c7aba1b7c8140d620b4bda941d6".into(), - to: 0xa.into(), + from: Address::from_str("9cce34f7ab185c7aba1b7c8140d620b4bda941d6").unwrap(), + to: Address::from_low_u64_be(0xa), value: 100.into(), gas: 79000.into(), input: vec![], @@ -2557,8 +2586,8 @@ mod tests { trace_address: vec![0].into_iter().collect(), subtraces: 0, action: trace::Action::Suicide(trace::Suicide { - address: 0xa.into(), - refund_address: 0xb.into(), + address: Address::from_low_u64_be(0xa), + refund_address: Address::from_low_u64_be(0xb), balance: 150.into(), }), result: trace::Res::None, @@ -2600,8 +2629,8 @@ mod tests { state .set_storage( &a, - H256::from(&U256::from(1u64)), - H256::from(&U256::from(69u64)), + BigEndianHash::from_uint(&U256::from(1u64)), + BigEndianHash::from_uint(&U256::from(69u64)), ) .unwrap(); state.commit().unwrap(); @@ -2610,8 +2639,9 @@ mod tests { let s = State::from_existing(db, root, U256::from(0u8), Default::default()).unwrap(); assert_eq!( - s.storage_at(&a, &H256::from(&U256::from(1u64))).unwrap(), - H256::from(&U256::from(69u64)) + s.storage_at(&a, &BigEndianHash::from_uint(&U256::from(1u64))) + .unwrap(), + BigEndianHash::from_uint(&U256::from(69u64)) ); } @@ -2717,7 +2747,7 @@ mod tests { fn alter_balance() { let mut state = get_temp_state(); let a = Address::zero(); - let b = 1u64.into(); + let b = Address::from_low_u64_be(1u64); state .add_balance(&a, &U256::from(69u64), CleanupMode::NoEmpty) .unwrap(); @@ -2775,7 +2805,8 @@ mod tests { state.commit().unwrap(); assert_eq!( *state.root(), - "0ce23f3c809de377b008a4a3ee94a0834aac8bec1f86e28ffe4fdb5a15b0c785".into() + H256::from_str("0ce23f3c809de377b008a4a3ee94a0834aac8bec1f86e28ffe4fdb5a15b0c785") + .unwrap() ); } @@ -2819,147 +2850,164 @@ mod tests { fn checkpoint_revert_to_get_storage_at() { let mut state = get_temp_state(); let a = Address::zero(); - let k = H256::from(U256::from(0)); + let k = BigEndianHash::from_uint(&U256::from(0)); let c0 = state.checkpoint(); let c1 = state.checkpoint(); - state.set_storage(&a, k, H256::from(U256::from(1))).unwrap(); + state + .set_storage(&a, k, BigEndianHash::from_uint(&U256::from(1))) + .unwrap(); assert_eq!( state.checkpoint_storage_at(c0, &a, &k).unwrap(), - Some(H256::from(U256::from(0))) + Some(BigEndianHash::from_uint(&U256::from(0))) ); assert_eq!( state.checkpoint_storage_at(c1, &a, &k).unwrap(), - Some(H256::from(U256::from(0))) + Some(BigEndianHash::from_uint(&U256::from(0))) + ); + assert_eq!( + state.storage_at(&a, &k).unwrap(), + BigEndianHash::from_uint(&U256::from(1)) ); - assert_eq!(state.storage_at(&a, &k).unwrap(), H256::from(U256::from(1))); state.revert_to_checkpoint(); // Revert to c1. assert_eq!( state.checkpoint_storage_at(c0, &a, &k).unwrap(), - Some(H256::from(U256::from(0))) + Some(BigEndianHash::from_uint(&U256::from(0))) + ); + assert_eq!( + state.storage_at(&a, &k).unwrap(), + BigEndianHash::from_uint(&U256::from(0)) ); - assert_eq!(state.storage_at(&a, &k).unwrap(), H256::from(U256::from(0))); } #[test] fn checkpoint_from_empty_get_storage_at() { let mut state = get_temp_state(); let a = Address::zero(); - let k = H256::from(U256::from(0)); - let k2 = H256::from(U256::from(1)); + let k = BigEndianHash::from_uint(&U256::from(0)); + let k2 = BigEndianHash::from_uint(&U256::from(1)); - assert_eq!(state.storage_at(&a, &k).unwrap(), H256::from(U256::from(0))); + assert_eq!( + state.storage_at(&a, &k).unwrap(), + BigEndianHash::from_uint(&U256::from(0)) + ); state.clear(); let c0 = state.checkpoint(); state.new_contract(&a, U256::zero(), U256::zero()).unwrap(); let c1 = state.checkpoint(); - state.set_storage(&a, k, H256::from(U256::from(1))).unwrap(); + state + .set_storage(&a, k, BigEndianHash::from_uint(&U256::from(1))) + .unwrap(); let c2 = state.checkpoint(); let c3 = state.checkpoint(); state - .set_storage(&a, k2, H256::from(U256::from(3))) + .set_storage(&a, k2, BigEndianHash::from_uint(&U256::from(3))) + .unwrap(); + state + .set_storage(&a, k, BigEndianHash::from_uint(&U256::from(3))) .unwrap(); - state.set_storage(&a, k, H256::from(U256::from(3))).unwrap(); let c4 = state.checkpoint(); - state.set_storage(&a, k, H256::from(U256::from(4))).unwrap(); + state + .set_storage(&a, k, BigEndianHash::from_uint(&U256::from(4))) + .unwrap(); let c5 = state.checkpoint(); assert_eq!( state.checkpoint_storage_at(c0, &a, &k).unwrap(), - Some(H256::from(U256::from(0))) + Some(BigEndianHash::from_uint(&U256::from(0))) ); assert_eq!( state.checkpoint_storage_at(c1, &a, &k).unwrap(), - Some(H256::from(U256::from(0))) + Some(BigEndianHash::from_uint(&U256::from(0))) ); assert_eq!( state.checkpoint_storage_at(c2, &a, &k).unwrap(), - Some(H256::from(U256::from(1))) + Some(BigEndianHash::from_uint(&U256::from(1))) ); assert_eq!( state.checkpoint_storage_at(c3, &a, &k).unwrap(), - Some(H256::from(U256::from(1))) + Some(BigEndianHash::from_uint(&U256::from(1))) ); assert_eq!( state.checkpoint_storage_at(c4, &a, &k).unwrap(), - Some(H256::from(U256::from(3))) + Some(BigEndianHash::from_uint(&U256::from(3))) ); assert_eq!( state.checkpoint_storage_at(c5, &a, &k).unwrap(), - Some(H256::from(U256::from(4))) + Some(BigEndianHash::from_uint(&U256::from(4))) ); state.discard_checkpoint(); // Commit/discard c5. assert_eq!( state.checkpoint_storage_at(c0, &a, &k).unwrap(), - Some(H256::from(U256::from(0))) + Some(BigEndianHash::from_uint(&U256::from(0))) ); assert_eq!( state.checkpoint_storage_at(c1, &a, &k).unwrap(), - Some(H256::from(U256::from(0))) + Some(BigEndianHash::from_uint(&U256::from(0))) ); assert_eq!( state.checkpoint_storage_at(c2, &a, &k).unwrap(), - Some(H256::from(U256::from(1))) + Some(BigEndianHash::from_uint(&U256::from(1))) ); assert_eq!( state.checkpoint_storage_at(c3, &a, &k).unwrap(), - Some(H256::from(U256::from(1))) + Some(BigEndianHash::from_uint(&U256::from(1))) ); assert_eq!( state.checkpoint_storage_at(c4, &a, &k).unwrap(), - Some(H256::from(U256::from(3))) + Some(BigEndianHash::from_uint(&U256::from(3))) ); state.revert_to_checkpoint(); // Revert to c4. assert_eq!( state.checkpoint_storage_at(c0, &a, &k).unwrap(), - Some(H256::from(U256::from(0))) + Some(BigEndianHash::from_uint(&U256::from(0))) ); assert_eq!( state.checkpoint_storage_at(c1, &a, &k).unwrap(), - Some(H256::from(U256::from(0))) + Some(BigEndianHash::from_uint(&U256::from(0))) ); assert_eq!( state.checkpoint_storage_at(c2, &a, &k).unwrap(), - Some(H256::from(U256::from(1))) + Some(BigEndianHash::from_uint(&U256::from(1))) ); assert_eq!( state.checkpoint_storage_at(c3, &a, &k).unwrap(), - Some(H256::from(U256::from(1))) + Some(BigEndianHash::from_uint(&U256::from(1))) ); state.discard_checkpoint(); // Commit/discard c3. assert_eq!( state.checkpoint_storage_at(c0, &a, &k).unwrap(), - Some(H256::from(U256::from(0))) + Some(BigEndianHash::from_uint(&U256::from(0))) ); assert_eq!( state.checkpoint_storage_at(c1, &a, &k).unwrap(), - Some(H256::from(U256::from(0))) + Some(BigEndianHash::from_uint(&U256::from(0))) ); assert_eq!( state.checkpoint_storage_at(c2, &a, &k).unwrap(), - Some(H256::from(U256::from(1))) + Some(BigEndianHash::from_uint(&U256::from(1))) ); state.revert_to_checkpoint(); // Revert to c2. assert_eq!( state.checkpoint_storage_at(c0, &a, &k).unwrap(), - Some(H256::from(U256::from(0))) + Some(BigEndianHash::from_uint(&U256::from(0))) ); assert_eq!( state.checkpoint_storage_at(c1, &a, &k).unwrap(), - Some(H256::from(U256::from(0))) + Some(BigEndianHash::from_uint(&U256::from(0))) ); state.discard_checkpoint(); // Commit/discard c1. assert_eq!( state.checkpoint_storage_at(c0, &a, &k).unwrap(), - Some(H256::from(U256::from(0))) + Some(BigEndianHash::from_uint(&U256::from(0))) ); } @@ -2967,18 +3015,18 @@ mod tests { fn checkpoint_get_storage_at() { let mut state = get_temp_state(); let a = Address::zero(); - let k = H256::from(U256::from(0)); - let k2 = H256::from(U256::from(1)); + let k = BigEndianHash::from_uint(&U256::from(0)); + let k2 = BigEndianHash::from_uint(&U256::from(1)); state - .set_storage(&a, k, H256::from(U256::from(0xffff))) + .set_storage(&a, k, BigEndianHash::from_uint(&U256::from(0xffff))) .unwrap(); state.commit().unwrap(); state.clear(); assert_eq!( state.storage_at(&a, &k).unwrap(), - H256::from(U256::from(0xffff)) + BigEndianHash::from_uint(&U256::from(0xffff)) ); state.clear(); @@ -2986,134 +3034,140 @@ mod tests { let c0 = state.checkpoint(); state.new_contract(&a, U256::zero(), U256::zero()).unwrap(); let c1 = state.checkpoint(); - state.set_storage(&a, k, H256::from(U256::from(1))).unwrap(); + state + .set_storage(&a, k, BigEndianHash::from_uint(&U256::from(1))) + .unwrap(); let c2 = state.checkpoint(); let c3 = state.checkpoint(); state - .set_storage(&a, k2, H256::from(U256::from(3))) + .set_storage(&a, k2, BigEndianHash::from_uint(&U256::from(3))) + .unwrap(); + state + .set_storage(&a, k, BigEndianHash::from_uint(&U256::from(3))) .unwrap(); - state.set_storage(&a, k, H256::from(U256::from(3))).unwrap(); let c4 = state.checkpoint(); - state.set_storage(&a, k, H256::from(U256::from(4))).unwrap(); + state + .set_storage(&a, k, BigEndianHash::from_uint(&U256::from(4))) + .unwrap(); let c5 = state.checkpoint(); assert_eq!( state.checkpoint_storage_at(cm1, &a, &k).unwrap(), - Some(H256::from(U256::from(0xffff))) + Some(BigEndianHash::from_uint(&U256::from(0xffff))) ); assert_eq!( state.checkpoint_storage_at(c0, &a, &k).unwrap(), - Some(H256::from(U256::from(0xffff))) + Some(BigEndianHash::from_uint(&U256::from(0xffff))) ); assert_eq!( state.checkpoint_storage_at(c1, &a, &k).unwrap(), - Some(H256::from(U256::from(0))) + Some(BigEndianHash::from_uint(&U256::from(0))) ); assert_eq!( state.checkpoint_storage_at(c2, &a, &k).unwrap(), - Some(H256::from(U256::from(1))) + Some(BigEndianHash::from_uint(&U256::from(1))) ); assert_eq!( state.checkpoint_storage_at(c3, &a, &k).unwrap(), - Some(H256::from(U256::from(1))) + Some(BigEndianHash::from_uint(&U256::from(1))) ); assert_eq!( state.checkpoint_storage_at(c4, &a, &k).unwrap(), - Some(H256::from(U256::from(3))) + Some(BigEndianHash::from_uint(&U256::from(3))) ); assert_eq!( state.checkpoint_storage_at(c5, &a, &k).unwrap(), - Some(H256::from(U256::from(4))) + Some(BigEndianHash::from_uint(&U256::from(4))) ); state.discard_checkpoint(); // Commit/discard c5. assert_eq!( state.checkpoint_storage_at(cm1, &a, &k).unwrap(), - Some(H256::from(U256::from(0xffff))) + Some(BigEndianHash::from_uint(&U256::from(0xffff))) ); assert_eq!( state.checkpoint_storage_at(c0, &a, &k).unwrap(), - Some(H256::from(U256::from(0xffff))) + Some(BigEndianHash::from_uint(&U256::from(0xffff))) ); assert_eq!( state.checkpoint_storage_at(c1, &a, &k).unwrap(), - Some(H256::from(U256::from(0))) + Some(BigEndianHash::from_uint(&U256::from(0))) ); assert_eq!( state.checkpoint_storage_at(c2, &a, &k).unwrap(), - Some(H256::from(U256::from(1))) + Some(BigEndianHash::from_uint(&U256::from(1))) ); assert_eq!( state.checkpoint_storage_at(c3, &a, &k).unwrap(), - Some(H256::from(U256::from(1))) + Some(BigEndianHash::from_uint(&U256::from(1))) ); assert_eq!( state.checkpoint_storage_at(c4, &a, &k).unwrap(), - Some(H256::from(U256::from(3))) + Some(BigEndianHash::from_uint(&U256::from(3))) ); state.revert_to_checkpoint(); // Revert to c4. assert_eq!( state.checkpoint_storage_at(cm1, &a, &k).unwrap(), - Some(H256::from(U256::from(0xffff))) + Some(BigEndianHash::from_uint(&U256::from(0xffff))) ); assert_eq!( state.checkpoint_storage_at(c0, &a, &k).unwrap(), - Some(H256::from(U256::from(0xffff))) + Some(BigEndianHash::from_uint(&U256::from(0xffff))) ); assert_eq!( state.checkpoint_storage_at(c1, &a, &k).unwrap(), - Some(H256::from(U256::from(0))) + Some(BigEndianHash::from_uint(&U256::from(0))) ); assert_eq!( state.checkpoint_storage_at(c2, &a, &k).unwrap(), - Some(H256::from(U256::from(1))) + Some(BigEndianHash::from_uint(&U256::from(1))) ); assert_eq!( state.checkpoint_storage_at(c3, &a, &k).unwrap(), - Some(H256::from(U256::from(1))) + Some(BigEndianHash::from_uint(&U256::from(1))) ); state.discard_checkpoint(); // Commit/discard c3. assert_eq!( state.checkpoint_storage_at(cm1, &a, &k).unwrap(), - Some(H256::from(U256::from(0xffff))) + Some(BigEndianHash::from_uint(&U256::from(0xffff))) ); assert_eq!( state.checkpoint_storage_at(c0, &a, &k).unwrap(), - Some(H256::from(U256::from(0xffff))) + Some(BigEndianHash::from_uint(&U256::from(0xffff))) ); assert_eq!( state.checkpoint_storage_at(c1, &a, &k).unwrap(), - Some(H256::from(U256::from(0))) + Some(BigEndianHash::from_uint(&U256::from(0))) ); assert_eq!( state.checkpoint_storage_at(c2, &a, &k).unwrap(), - Some(H256::from(U256::from(1))) + Some(BigEndianHash::from_uint(&U256::from(1))) ); state.revert_to_checkpoint(); // Revert to c2. assert_eq!( state.checkpoint_storage_at(cm1, &a, &k).unwrap(), - Some(H256::from(U256::from(0xffff))) + Some(BigEndianHash::from_uint(&U256::from(0xffff))) ); assert_eq!( state.checkpoint_storage_at(c0, &a, &k).unwrap(), - Some(H256::from(U256::from(0xffff))) + Some(BigEndianHash::from_uint(&U256::from(0xffff))) ); assert_eq!( state.checkpoint_storage_at(c1, &a, &k).unwrap(), - Some(H256::from(U256::from(0))) + Some(BigEndianHash::from_uint(&U256::from(0))) ); state.discard_checkpoint(); // Commit/discard c1. assert_eq!( state.checkpoint_storage_at(cm1, &a, &k).unwrap(), - Some(H256::from(U256::from(0xffff))) + Some(BigEndianHash::from_uint(&U256::from(0xffff))) ); assert_eq!( state.checkpoint_storage_at(c0, &a, &k).unwrap(), - Some(H256::from(U256::from(0xffff))) + Some(BigEndianHash::from_uint(&U256::from(0xffff))) ); } @@ -3121,22 +3175,30 @@ mod tests { fn kill_account_with_checkpoints() { let mut state = get_temp_state(); let a = Address::zero(); - let k = H256::from(U256::from(0)); + let k = BigEndianHash::from_uint(&U256::from(0)); state.checkpoint(); - state.set_storage(&a, k, H256::from(U256::from(1))).unwrap(); + state + .set_storage(&a, k, BigEndianHash::from_uint(&U256::from(1))) + .unwrap(); state.checkpoint(); state.kill_account(&a); - assert_eq!(state.storage_at(&a, &k).unwrap(), H256::from(U256::from(0))); + assert_eq!( + state.storage_at(&a, &k).unwrap(), + BigEndianHash::from_uint(&U256::from(0)) + ); state.revert_to_checkpoint(); - assert_eq!(state.storage_at(&a, &k).unwrap(), H256::from(U256::from(1))); + assert_eq!( + state.storage_at(&a, &k).unwrap(), + BigEndianHash::from_uint(&U256::from(1)) + ); } #[test] fn create_contract_fail() { let mut state = get_temp_state(); let orig_root = state.root().clone(); - let a: Address = 1000.into(); + let a = Address::from_low_u64_be(1000); state.checkpoint(); // c1 state.new_contract(&a, U256::zero(), U256::zero()).unwrap(); @@ -3158,11 +3220,11 @@ mod tests { #[test] fn create_contract_fail_previous_storage() { let mut state = get_temp_state(); - let a: Address = 1000.into(); - let k = H256::from(U256::from(0)); + let a = Address::from_low_u64_be(1000); + let k = BigEndianHash::from_uint(&U256::from(0)); state - .set_storage(&a, k, H256::from(U256::from(0xffff))) + .set_storage(&a, k, BigEndianHash::from_uint(&U256::from(0xffff))) .unwrap(); state.commit().unwrap(); state.clear(); @@ -3170,20 +3232,25 @@ mod tests { let orig_root = state.root().clone(); assert_eq!( state.storage_at(&a, &k).unwrap(), - H256::from(U256::from(0xffff)) + BigEndianHash::from_uint(&U256::from(0xffff)) ); state.clear(); state.checkpoint(); // c1 state.new_contract(&a, U256::zero(), U256::zero()).unwrap(); state.checkpoint(); // c2 - state.set_storage(&a, k, H256::from(U256::from(2))).unwrap(); + state + .set_storage(&a, k, BigEndianHash::from_uint(&U256::from(2))) + .unwrap(); state.revert_to_checkpoint(); // revert to c2 - assert_eq!(state.storage_at(&a, &k).unwrap(), H256::from(U256::from(0))); + assert_eq!( + state.storage_at(&a, &k).unwrap(), + BigEndianHash::from_uint(&U256::from(0)) + ); state.revert_to_checkpoint(); // revert to c1 assert_eq!( state.storage_at(&a, &k).unwrap(), - H256::from(U256::from(0xffff)) + BigEndianHash::from_uint(&U256::from(0xffff)) ); state.commit().unwrap(); @@ -3196,7 +3263,8 @@ mod tests { state.commit().unwrap(); assert_eq!( *state.root(), - "56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421".into() + H256::from_str("56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421") + .unwrap() ); } @@ -3204,27 +3272,31 @@ mod tests { fn should_not_panic_on_state_diff_with_storage() { let mut state = get_temp_state(); - let a: Address = 0xa.into(); + let a: Address = Address::from_low_u64_be(0xa); state.init_code(&a, b"abcdefg".to_vec()).unwrap(); state .add_balance(&a, &256.into(), CleanupMode::NoEmpty) .unwrap(); - state.set_storage(&a, 0xb.into(), 0xc.into()).unwrap(); + state + .set_storage(&a, H256::from_low_u64_be(0xb), H256::from_low_u64_be(0xc)) + .unwrap(); let mut new_state = state.clone(); - new_state.set_storage(&a, 0xb.into(), 0xd.into()).unwrap(); + new_state + .set_storage(&a, H256::from_low_u64_be(0xb), H256::from_low_u64_be(0xd)) + .unwrap(); new_state.diff_from(state).unwrap(); } #[test] fn should_kill_garbage() { - let a = 10.into(); - let b = 20.into(); - let c = 30.into(); - let d = 40.into(); - let e = 50.into(); - let x = 0.into(); + let a = Address::from_low_u64_be(10); + let b = Address::from_low_u64_be(20); + let c = Address::from_low_u64_be(30); + let d = Address::from_low_u64_be(40); + let e = Address::from_low_u64_be(50); + let x = Address::from_low_u64_be(0); let db = get_temp_state_db(); let (root, db) = { let mut state = State::new(db, U256::from(0), Default::default()); @@ -3287,7 +3359,7 @@ mod tests { fn should_trace_diff_suicided_accounts() { use pod_account; - let a = 10.into(); + let a = Address::from_low_u64_be(10); let db = get_temp_state_db(); let (root, db) = { let mut state = State::new(db, U256::from(0), Default::default()); @@ -3326,7 +3398,7 @@ mod tests { fn should_trace_diff_unmodified_storage() { use pod_account; - let a = 10.into(); + let a = Address::from_low_u64_be(10); let db = get_temp_state_db(); let (root, db) = { @@ -3334,8 +3406,8 @@ mod tests { state .set_storage( &a, - H256::from(&U256::from(1u64)), - H256::from(&U256::from(20u64)), + BigEndianHash::from_uint(&U256::from(1u64)), + BigEndianHash::from_uint(&U256::from(20u64)), ) .unwrap(); state.commit().unwrap(); @@ -3348,8 +3420,8 @@ mod tests { state .set_storage( &a, - H256::from(&U256::from(1u64)), - H256::from(&U256::from(100u64)), + BigEndianHash::from_uint(&U256::from(1u64)), + BigEndianHash::from_uint(&U256::from(100u64)), ) .unwrap(); @@ -3365,8 +3437,8 @@ mod tests { nonce: U256::zero(), code: Some(Default::default()), storage: vec![( - H256::from(&U256::from(1u64)), - H256::from(&U256::from(20u64)) + BigEndianHash::from_uint(&U256::from(1u64)), + BigEndianHash::from_uint(&U256::from(20u64)) )] .into_iter() .collect(), @@ -3376,8 +3448,8 @@ mod tests { nonce: U256::zero(), code: Some(Default::default()), storage: vec![( - H256::from(&U256::from(1u64)), - H256::from(&U256::from(100u64)) + BigEndianHash::from_uint(&U256::from(1u64)), + BigEndianHash::from_uint(&U256::from(100u64)) )] .into_iter() .collect(), @@ -3392,7 +3464,7 @@ mod tests { fn should_get_full_pod_storage_values() { use trie::{TrieFactory, TrieSpec}; - let a = 10.into(); + let a = Address::from_low_u64_be(10); let db = get_temp_state_db(); let factories = Factories { @@ -3412,23 +3484,27 @@ mod tests { .clone() }; - let storage_address = H256::from(&U256::from(1u64)); + let storage_address: H256 = BigEndianHash::from_uint(&U256::from(1u64)); let (root, db) = { let mut state = State::new(db, U256::from(0), factories.clone()); state - .set_storage(&a, storage_address.clone(), H256::from(&U256::from(20u64))) + .set_storage( + &a, + storage_address.clone(), + BigEndianHash::from_uint(&U256::from(20u64)), + ) .unwrap(); let dump = state.to_pod_full().unwrap(); assert_eq!( get_pod_state_val(&dump, &a, storage_address.clone()), - H256::from(&U256::from(20u64)) + BigEndianHash::from_uint(&U256::from(20u64)) ); state.commit().unwrap(); let dump = state.to_pod_full().unwrap(); assert_eq!( get_pod_state_val(&dump, &a, storage_address.clone()), - H256::from(&U256::from(20u64)) + BigEndianHash::from_uint(&U256::from(20u64)) ); state.drop() }; @@ -3437,24 +3513,32 @@ mod tests { let dump = state.to_pod_full().unwrap(); assert_eq!( get_pod_state_val(&dump, &a, storage_address.clone()), - H256::from(&U256::from(20u64)) + BigEndianHash::from_uint(&U256::from(20u64)) ); state - .set_storage(&a, storage_address.clone(), H256::from(&U256::from(21u64))) + .set_storage( + &a, + storage_address.clone(), + BigEndianHash::from_uint(&U256::from(21u64)), + ) .unwrap(); let dump = state.to_pod_full().unwrap(); assert_eq!( get_pod_state_val(&dump, &a, storage_address.clone()), - H256::from(&U256::from(21u64)) + BigEndianHash::from_uint(&U256::from(21u64)) ); state.commit().unwrap(); state - .set_storage(&a, storage_address.clone(), H256::from(&U256::from(0u64))) + .set_storage( + &a, + storage_address.clone(), + BigEndianHash::from_uint(&U256::from(0u64)), + ) .unwrap(); let dump = state.to_pod_full().unwrap(); assert_eq!( get_pod_state_val(&dump, &a, storage_address.clone()), - H256::from(&U256::from(0u64)) + BigEndianHash::from_uint(&U256::from(0u64)) ); } } diff --git a/crates/ethcore/src/state/substate.rs b/crates/ethcore/src/state/substate.rs index e2fe02483..a91dabbbe 100644 --- a/crates/ethcore/src/state/substate.rs +++ b/crates/ethcore/src/state/substate.rs @@ -88,6 +88,7 @@ impl Substate { #[cfg(test)] mod tests { use super::Substate; + use ethereum_types::Address; use types::log_entry::LogEntry; #[test] @@ -99,19 +100,23 @@ mod tests { #[test] fn accrue() { let mut sub_state = Substate::new(); - sub_state.contracts_created.push(1u64.into()); + sub_state + .contracts_created + .push(Address::from_low_u64_be(1u64)); sub_state.logs.push(LogEntry { - address: 1u64.into(), + address: Address::from_low_u64_be(1u64), topics: vec![], data: vec![], }); sub_state.sstore_clears_refund = (15000 * 5).into(); - sub_state.suicides.insert(10u64.into()); + sub_state.suicides.insert(Address::from_low_u64_be(10u64)); let mut sub_state_2 = Substate::new(); - sub_state_2.contracts_created.push(2u64.into()); + sub_state_2 + .contracts_created + .push(Address::from_low_u64_be(2u64)); sub_state_2.logs.push(LogEntry { - address: 1u64.into(), + address: Address::from_low_u64_be(1u64), topics: vec![], data: vec![], }); diff --git a/crates/ethcore/src/test_helpers.rs b/crates/ethcore/src/test_helpers.rs index 57652dd3d..13a145571 100644 --- a/crates/ethcore/src/test_helpers.rs +++ b/crates/ethcore/src/test_helpers.rs @@ -23,9 +23,9 @@ use blockchain::{ }; use blooms_db; use bytes::Bytes; +use crypto::publickey::KeyPair; use db::KeyValueDB; use ethereum_types::{Address, H256, U256}; -use ethkey::KeyPair; use evm::Factory as EvmFactory; use hash::keccak; use io::IoChannel; @@ -169,7 +169,7 @@ where let mut last_hashes = vec![]; let mut last_header = genesis_header.clone(); - let kp = KeyPair::from_secret_slice(&keccak("")).unwrap(); + let kp = KeyPair::from_secret_slice(keccak("").as_bytes()).unwrap(); let author = kp.address(); let mut n = 0; @@ -605,7 +605,7 @@ pub fn get_bad_state_dummy_block() -> Bytes { block_header.set_timestamp(40); block_header.set_number(1); block_header.set_parent_hash(test_spec.genesis_header().hash()); - block_header.set_state_root(0xbad.into()); + block_header.set_state_root(H256::from_low_u64_be(0xbad)); create_test_block(&block_header) } diff --git a/crates/ethcore/src/tests/client.rs b/crates/ethcore/src/tests/client.rs index a5f0b2d88..035bf0405 100644 --- a/crates/ethcore/src/tests/client.rs +++ b/crates/ethcore/src/tests/client.rs @@ -25,9 +25,9 @@ use client::{ }, Client, ClientConfig, ImportSealedBlock, PrepareOpenBlock, }; +use crypto::publickey::KeyPair; use ethereum; use ethereum_types::{Address, U256}; -use ethkey::KeyPair; use executive::{Executive, TransactOptions}; use hash::keccak; use io::IoChannel; diff --git a/crates/ethcore/src/tests/evm.rs b/crates/ethcore/src/tests/evm.rs index c3ba39d78..b8e1f5c21 100644 --- a/crates/ethcore/src/tests/evm.rs +++ b/crates/ethcore/src/tests/evm.rs @@ -43,7 +43,7 @@ fn test_blockhash_eip210(factory: Factory) { // populate state with 256 last hashes let mut state = get_temp_state_with_factory(factory); - let contract_address: Address = 0xf0.into(); + let contract_address = Address::from_low_u64_be(0xf0); state .init_code(&contract_address, (*blockhash_contract_code).clone()) .unwrap(); @@ -59,7 +59,7 @@ fn test_blockhash_eip210(factory: Factory) { value: ActionValue::Transfer(0.into()), code: Some(blockhash_contract_code.clone()), code_hash: Some(blockhash_contract_code_hash), - data: Some(H256::from(i - 1).to_vec()), + data: Some(H256::from_low_u64_be(i - 1).as_bytes().to_vec()), call_type: CallType::Call, params_type: ParamsType::Separate, access_list: AccessList::default(), @@ -74,10 +74,10 @@ fn test_blockhash_eip210(factory: Factory) { env_info.number = 256; let params = ActionParams { - code_address: Address::new(), - address: Address::new(), - sender: Address::new(), - origin: Address::new(), + code_address: Address::default(), + address: Address::default(), + sender: Address::default(), + origin: Address::default(), gas: 100000.into(), gas_price: 0.into(), value: ActionValue::Transfer(0.into()), @@ -93,10 +93,10 @@ fn test_blockhash_eip210(factory: Factory) { let mut substate = Substate::new(); let res = ex.call(params, &mut substate, &mut NoopTracer, &mut NoopVMTracer); let output = match res { - Ok(res) => H256::from(&res.return_data[..32]), + Ok(res) => H256::from_slice(&res.return_data[..32]), Err(e) => { panic!("Encountered error on getting last hash: {}", e); } }; - assert_eq!(output, 255.into()); + assert_eq!(output, H256::from_low_u64_be(255)); } diff --git a/crates/ethcore/src/tests/trace.rs b/crates/ethcore/src/tests/trace.rs index 3835a6a03..4cb92a2e3 100644 --- a/crates/ethcore/src/tests/trace.rs +++ b/crates/ethcore/src/tests/trace.rs @@ -18,13 +18,13 @@ use block::*; use client::{BlockChainClient, Client, ClientConfig, *}; +use crypto::publickey::KeyPair; use ethereum_types::{Address, U256}; -use ethkey::KeyPair; use hash::keccak; use io::*; use miner::Miner; use spec::*; -use std::sync::Arc; +use std::{str::FromStr, sync::Arc}; use test_helpers::{self, get_temp_state_db}; use trace::{trace::Action::Reward, LocalizedTrace, RewardType}; use types::{ @@ -73,7 +73,7 @@ fn can_trace_block_and_uncle_reward() { let mut last_header = genesis_header.clone(); last_hashes.push(last_header.hash()); - let kp = KeyPair::from_secret_slice(&keccak("")).unwrap(); + let kp = KeyPair::from_secret_slice(keccak("").as_bytes()).unwrap(); let author = kp.address(); // Add root block first @@ -187,7 +187,7 @@ fn can_trace_block_and_uncle_reward() { } let mut uncle = Header::new(); - let uncle_author: Address = "ef2d6d194084c2de36e0dabfce45d046b37d1106".into(); + let uncle_author = Address::from_str("ef2d6d194084c2de36e0dabfce45d046b37d1106").unwrap(); uncle.set_author(uncle_author); uncle.set_parent_hash(root_header.hash()); uncle.set_gas_limit(genesis_gas); diff --git a/crates/ethcore/src/trace/db.rs b/crates/ethcore/src/trace/db.rs index f0943649e..33ca541f2 100644 --- a/crates/ethcore/src/trace/db.rs +++ b/crates/ethcore/src/trace/db.rs @@ -20,8 +20,8 @@ use std::{collections::HashMap, sync::Arc}; use blockchain::BlockChainDB; use db::{self, cache_manager::CacheManager, CacheUpdatePolicy, Key, Readable, Writable}; use ethereum_types::{H256, H264}; -use heapsize::HeapSizeOf; use kvdb::DBTransaction; +use parity_util_mem::MallocSizeOfExt; use parking_lot::RwLock; use types::BlockNumber; @@ -43,8 +43,11 @@ impl Key for H256 { fn key(&self) -> H264 { let mut result = H264::default(); - result[0] = TraceDBIndex::BlockTraces as u8; - result[1..33].copy_from_slice(self); + { + let bytes = result.as_bytes_mut(); + bytes[0] = TraceDBIndex::BlockTraces as u8; + bytes[1..33].copy_from_slice(self.as_bytes()); + } result } } @@ -101,7 +104,7 @@ where } fn cache_size(&self) -> usize { - self.traces.read().heap_size_of_children() + self.traces.read().malloc_size_of() } /// Let the cache system know that a cacheable item has been used. @@ -123,7 +126,7 @@ where } traces.shrink_to_fit(); - traces.heap_size_of_children() + traces.malloc_size_of() }); } @@ -497,8 +500,8 @@ mod tests { trace_address: Default::default(), subtraces: 0, action: Action::Call(Call { - from: 1.into(), - to: 2.into(), + from: Address::from_low_u64_be(1), + to: Address::from_low_u64_be(2), value: 3.into(), gas: 4.into(), input: vec![], @@ -522,8 +525,8 @@ mod tests { trace_address: Default::default(), subtraces: 0, action: Action::Call(Call { - from: 1.into(), - to: 2.into(), + from: Address::from_low_u64_be(1), + to: Address::from_low_u64_be(2), value: 3.into(), gas: 4.into(), input: vec![], @@ -545,8 +548,8 @@ mod tests { ) -> LocalizedTrace { LocalizedTrace { action: Action::Call(Call { - from: Address::from(1), - to: Address::from(2), + from: Address::from_low_u64_be(1), + to: Address::from_low_u64_be(2), value: U256::from(3), gas: U256::from(4), input: vec![], @@ -567,10 +570,10 @@ mod tests { let db = new_db(); let mut config = Config::default(); config.enabled = true; - let block_0 = H256::from(0xa1); - let block_1 = H256::from(0xa2); - let tx_0 = H256::from(0xff); - let tx_1 = H256::from(0xaf); + let block_0 = H256::from_low_u64_be(0xa1); + let block_1 = H256::from_low_u64_be(0xa2); + let tx_0 = H256::from_low_u64_be(0xff); + let tx_1 = H256::from_low_u64_be(0xaf); let mut extras = Extras::default(); extras.block_hashes.insert(0, block_0.clone()); @@ -597,10 +600,10 @@ mod tests { let db = new_db(); let mut config = Config::default(); config.enabled = true; - let block_1 = H256::from(0xa1); - let block_2 = H256::from(0xa2); - let tx_1 = H256::from(0xff); - let tx_2 = H256::from(0xaf); + let block_1 = H256::from_low_u64_be(0xa1); + let block_2 = H256::from_low_u64_be(0xa2); + let tx_1 = H256::from_low_u64_be(0xff); + let tx_2 = H256::from_low_u64_be(0xaf); let mut extras = Extras::default(); extras.block_hashes.insert(0, H256::default()); @@ -620,7 +623,7 @@ mod tests { let filter = Filter { range: (1..1), - from_address: AddressesFilter::from(vec![Address::from(1)]), + from_address: AddressesFilter::from(vec![Address::from_low_u64_be(1)]), to_address: AddressesFilter::from(vec![]), }; @@ -639,7 +642,7 @@ mod tests { let filter = Filter { range: (1..2), - from_address: AddressesFilter::from(vec![Address::from(1)]), + from_address: AddressesFilter::from(vec![Address::from_low_u64_be(1)]), to_address: AddressesFilter::from(vec![]), }; @@ -706,8 +709,8 @@ mod tests { let db = new_db(); let mut config = Config::default(); let mut extras = Extras::default(); - let block_0 = H256::from(0xa1); - let tx_0 = H256::from(0xff); + let block_0 = H256::from_low_u64_be(0xa1); + let tx_0 = H256::from_low_u64_be(0xff); extras.block_hashes.insert(0, H256::default()); extras.transaction_hashes.insert(0, vec![]); @@ -742,7 +745,7 @@ mod tests { let db = new_db(); let mut config = Config::default(); let mut extras = Extras::default(); - let block_0 = H256::from(0xa1); + let block_0 = H256::from_low_u64_be(0xa1); extras.block_hashes.insert(0, block_0.clone()); extras.transaction_hashes.insert(0, vec![]); diff --git a/crates/ethcore/src/trace/types/error.rs b/crates/ethcore/src/trace/types/error.rs index 691e6cc39..01e636510 100644 --- a/crates/ethcore/src/trace/types/error.rs +++ b/crates/ethcore/src/trace/types/error.rs @@ -16,12 +16,13 @@ //! Trace errors. +use parity_util_mem::MallocSizeOf; use rlp::{Decodable, DecoderError, Encodable, Rlp, RlpStream}; use std::fmt; use vm::Error as VmError; /// Trace evm errors. -#[derive(Debug, PartialEq, Clone)] +#[derive(Debug, PartialEq, Clone, MallocSizeOf)] pub enum Error { /// `OutOfGas` is returned when transaction execution runs out of gas. OutOfGas, diff --git a/crates/ethcore/src/trace/types/filter.rs b/crates/ethcore/src/trace/types/filter.rs index 604981e4e..fe1bbf291 100644 --- a/crates/ethcore/src/trace/types/filter.rs +++ b/crates/ethcore/src/trace/types/filter.rs @@ -53,7 +53,7 @@ impl AddressesFilter { false => self .list .iter() - .map(|address| Bloom::from(BloomInput::Raw(address))) + .map(|address| Bloom::from(BloomInput::Raw(address.as_bytes()))) .collect(), } } @@ -69,7 +69,7 @@ impl AddressesFilter { .iter() .map(|address| { let mut bloom = bloom.clone(); - bloom.accrue(BloomInput::Raw(address)); + bloom.accrue(BloomInput::Raw(address.as_bytes())); bloom }) .collect::>() @@ -156,31 +156,31 @@ mod tests { fn single_trace_filter_bloom_possibility() { let filter = Filter { range: (0..0), - from_address: AddressesFilter::from(vec![Address::from(1)]), - to_address: AddressesFilter::from(vec![Address::from(2)]), + from_address: AddressesFilter::from(vec![Address::from_low_u64_be(1)]), + to_address: AddressesFilter::from(vec![Address::from_low_u64_be(2)]), }; let blooms = filter.bloom_possibilities(); assert_eq!(blooms.len(), 1); - assert!(blooms[0].contains_input(BloomInput::Raw(&Address::from(1)))); - assert!(blooms[0].contains_input(BloomInput::Raw(&Address::from(2)))); - assert!(!blooms[0].contains_input(BloomInput::Raw(&Address::from(3)))); + assert!(blooms[0].contains_input(BloomInput::Raw(Address::from_low_u64_be(1).as_bytes()))); + assert!(blooms[0].contains_input(BloomInput::Raw(Address::from_low_u64_be(2).as_bytes()))); + assert!(!blooms[0].contains_input(BloomInput::Raw(Address::from_low_u64_be(3).as_bytes()))); } #[test] fn only_from_trace_filter_bloom_possibility() { let filter = Filter { range: (0..0), - from_address: AddressesFilter::from(vec![Address::from(1)]), + from_address: AddressesFilter::from(vec![Address::from_low_u64_be(1)]), to_address: AddressesFilter::from(vec![]), }; let blooms = filter.bloom_possibilities(); assert_eq!(blooms.len(), 1); - assert!(blooms[0].contains_input(BloomInput::Raw(&Address::from(1)))); - assert!(!blooms[0].contains_input(BloomInput::Raw(&Address::from(2)))); + assert!(blooms[0].contains_input(BloomInput::Raw(Address::from_low_u64_be(1).as_bytes()))); + assert!(!blooms[0].contains_input(BloomInput::Raw(Address::from_low_u64_be(2).as_bytes()))); } #[test] @@ -188,59 +188,68 @@ mod tests { let filter = Filter { range: (0..0), from_address: AddressesFilter::from(vec![]), - to_address: AddressesFilter::from(vec![Address::from(1)]), + to_address: AddressesFilter::from(vec![Address::from_low_u64_be(1)]), }; let blooms = filter.bloom_possibilities(); assert_eq!(blooms.len(), 1); - assert!(blooms[0].contains_input(BloomInput::Raw(&Address::from(1)))); - assert!(!blooms[0].contains_input(BloomInput::Raw(&Address::from(2)))); + assert!(blooms[0].contains_input(BloomInput::Raw(Address::from_low_u64_be(1).as_bytes()))); + assert!(!blooms[0].contains_input(BloomInput::Raw(Address::from_low_u64_be(2).as_bytes()))); } #[test] fn multiple_trace_filter_bloom_possibility() { let filter = Filter { range: (0..0), - from_address: AddressesFilter::from(vec![Address::from(1), Address::from(3)]), - to_address: AddressesFilter::from(vec![Address::from(2), Address::from(4)]), + from_address: AddressesFilter::from(vec![ + Address::from_low_u64_be(1), + Address::from_low_u64_be(3), + ]), + to_address: AddressesFilter::from(vec![ + Address::from_low_u64_be(2), + Address::from_low_u64_be(4), + ]), }; let blooms = filter.bloom_possibilities(); assert_eq!(blooms.len(), 4); - assert!(blooms[0].contains_input(BloomInput::Raw(&Address::from(1)))); - assert!(blooms[0].contains_input(BloomInput::Raw(&Address::from(2)))); - assert!(!blooms[0].contains_input(BloomInput::Raw(&Address::from(3)))); - assert!(!blooms[0].contains_input(BloomInput::Raw(&Address::from(4)))); + assert!(blooms[0].contains_input(BloomInput::Raw(Address::from_low_u64_be(1).as_bytes()))); + assert!(blooms[0].contains_input(BloomInput::Raw(Address::from_low_u64_be(2).as_bytes()))); + assert!(!blooms[0].contains_input(BloomInput::Raw(Address::from_low_u64_be(3).as_bytes()))); + assert!(!blooms[0].contains_input(BloomInput::Raw(Address::from_low_u64_be(4).as_bytes()))); - assert!(blooms[1].contains_input(BloomInput::Raw(&Address::from(1)))); - assert!(blooms[1].contains_input(BloomInput::Raw(&Address::from(4)))); - assert!(!blooms[1].contains_input(BloomInput::Raw(&Address::from(2)))); - assert!(!blooms[1].contains_input(BloomInput::Raw(&Address::from(3)))); + assert!(blooms[1].contains_input(BloomInput::Raw(Address::from_low_u64_be(1).as_bytes()))); + assert!(blooms[1].contains_input(BloomInput::Raw(Address::from_low_u64_be(4).as_bytes()))); + assert!(!blooms[1].contains_input(BloomInput::Raw(Address::from_low_u64_be(2).as_bytes()))); + assert!(!blooms[1].contains_input(BloomInput::Raw(Address::from_low_u64_be(3).as_bytes()))); - assert!(blooms[2].contains_input(BloomInput::Raw(&Address::from(2)))); - assert!(blooms[2].contains_input(BloomInput::Raw(&Address::from(3)))); - assert!(!blooms[2].contains_input(BloomInput::Raw(&Address::from(1)))); - assert!(!blooms[2].contains_input(BloomInput::Raw(&Address::from(4)))); + assert!(blooms[2].contains_input(BloomInput::Raw(Address::from_low_u64_be(2).as_bytes()))); + assert!(blooms[2].contains_input(BloomInput::Raw(Address::from_low_u64_be(3).as_bytes()))); + assert!(!blooms[2].contains_input(BloomInput::Raw(Address::from_low_u64_be(1).as_bytes()))); + assert!(!blooms[2].contains_input(BloomInput::Raw(Address::from_low_u64_be(4).as_bytes()))); - assert!(blooms[3].contains_input(BloomInput::Raw(&Address::from(3)))); - assert!(blooms[3].contains_input(BloomInput::Raw(&Address::from(4)))); - assert!(!blooms[3].contains_input(BloomInput::Raw(&Address::from(1)))); - assert!(!blooms[3].contains_input(BloomInput::Raw(&Address::from(2)))); + assert!(blooms[3].contains_input(BloomInput::Raw(Address::from_low_u64_be(3).as_bytes()))); + assert!(blooms[3].contains_input(BloomInput::Raw(Address::from_low_u64_be(4).as_bytes()))); + assert!(!blooms[3].contains_input(BloomInput::Raw(Address::from_low_u64_be(1).as_bytes()))); + assert!(!blooms[3].contains_input(BloomInput::Raw(Address::from_low_u64_be(2).as_bytes()))); } #[test] fn filter_matches() { let f0 = Filter { range: (0..0), - from_address: AddressesFilter::from(vec![Address::from(1)]), + from_address: AddressesFilter::from(vec![Address::from_low_u64_be(1)]), to_address: AddressesFilter::from(vec![]), }; let f1 = Filter { range: (0..0), - from_address: AddressesFilter::from(vec![Address::from(3), Address::from(1)]), + from_address: AddressesFilter::from(vec![ + Address::from_low_u64_be(3), + Address::from_low_u64_be(1), + ]), to_address: AddressesFilter::from(vec![]), }; @@ -253,31 +262,37 @@ mod tests { let f3 = Filter { range: (0..0), from_address: AddressesFilter::from(vec![]), - to_address: AddressesFilter::from(vec![Address::from(2)]), + to_address: AddressesFilter::from(vec![Address::from_low_u64_be(2)]), }; let f4 = Filter { range: (0..0), from_address: AddressesFilter::from(vec![]), - to_address: AddressesFilter::from(vec![Address::from(2), Address::from(3)]), + to_address: AddressesFilter::from(vec![ + Address::from_low_u64_be(2), + Address::from_low_u64_be(3), + ]), }; let f5 = Filter { range: (0..0), - from_address: AddressesFilter::from(vec![Address::from(1)]), - to_address: AddressesFilter::from(vec![Address::from(2), Address::from(3)]), + from_address: AddressesFilter::from(vec![Address::from_low_u64_be(1)]), + to_address: AddressesFilter::from(vec![ + Address::from_low_u64_be(2), + Address::from_low_u64_be(3), + ]), }; let f6 = Filter { range: (0..0), - from_address: AddressesFilter::from(vec![Address::from(1)]), - to_address: AddressesFilter::from(vec![Address::from(4)]), + from_address: AddressesFilter::from(vec![Address::from_low_u64_be(1)]), + to_address: AddressesFilter::from(vec![Address::from_low_u64_be(4)]), }; let trace = FlatTrace { action: Action::Call(Call { - from: 1.into(), - to: 2.into(), + from: Address::from_low_u64_be(1), + to: Address::from_low_u64_be(2), value: 3.into(), gas: 4.into(), input: vec![0x5], @@ -298,7 +313,7 @@ mod tests { let trace = FlatTrace { action: Action::Create(Create { - from: 1.into(), + from: Address::from_low_u64_be(1), value: 3.into(), gas: 4.into(), init: vec![0x5], @@ -306,7 +321,7 @@ mod tests { result: Res::Create(CreateResult { gas_used: 10.into(), code: vec![], - address: 2.into(), + address: Address::from_low_u64_be(2), }), trace_address: vec![0].into_iter().collect(), subtraces: 0, @@ -322,8 +337,8 @@ mod tests { let trace = FlatTrace { action: Action::Suicide(Suicide { - address: 1.into(), - refund_address: 2.into(), + address: Address::from_low_u64_be(1), + refund_address: Address::from_low_u64_be(2), balance: 3.into(), }), result: Res::None, @@ -341,7 +356,7 @@ mod tests { let trace = FlatTrace { action: Action::Reward(Reward { - author: 2.into(), + author: Address::from_low_u64_be(2), value: 100.into(), reward_type: RewardType::Block, }), @@ -363,7 +378,7 @@ mod tests { fn filter_match_block_reward_fix_8070() { let f0 = Filter { range: (0..0), - from_address: vec![1.into()].into(), + from_address: vec![Address::from_low_u64_be(1)].into(), to_address: vec![].into(), }; @@ -376,12 +391,12 @@ mod tests { let f2 = Filter { range: (0..0), from_address: vec![].into(), - to_address: vec![2.into()].into(), + to_address: vec![Address::from_low_u64_be(2)].into(), }; let trace = FlatTrace { action: Action::Reward(Reward { - author: 2.into(), + author: Address::from_low_u64_be(2), value: 10.into(), reward_type: RewardType::Block, }), @@ -399,7 +414,7 @@ mod tests { fn filter_match_failed_contract_creation_fix_9822() { let f0 = Filter { range: (0..0), - from_address: vec![1.into()].into(), + from_address: vec![Address::from_low_u64_be(1)].into(), to_address: vec![].into(), }; @@ -412,12 +427,12 @@ mod tests { let f2 = Filter { range: (0..0), from_address: vec![].into(), - to_address: vec![2.into()].into(), + to_address: vec![Address::from_low_u64_be(2)].into(), }; let trace = FlatTrace { action: Action::Create(Create { - from: 1.into(), + from: Address::from_low_u64_be(1), gas: 4.into(), init: vec![0x5], value: 3.into(), diff --git a/crates/ethcore/src/trace/types/flat.rs b/crates/ethcore/src/trace/types/flat.rs index caf5b6be6..a165e2e91 100644 --- a/crates/ethcore/src/trace/types/flat.rs +++ b/crates/ethcore/src/trace/types/flat.rs @@ -18,16 +18,18 @@ use super::trace::{Action, Res}; use ethereum_types::Bloom; -use heapsize::HeapSizeOf; +use parity_util_mem::MallocSizeOf; use rlp::{Decodable, DecoderError, Encodable, Rlp, RlpStream}; /// Trace localized in vector of traces produced by a single transaction. /// /// Parent and children indexes refer to positions in this vector. -#[derive(Debug, PartialEq, Clone)] +#[derive(Debug, PartialEq, Clone, MallocSizeOf)] pub struct FlatTrace { + #[ignore_malloc_size_of = "ignored for performance reason"] /// Type of action performed by a transaction. pub action: Action, + #[ignore_malloc_size_of = "ignored for performance reason"] /// Result of this action. pub result: Res, /// Number of subtraces. @@ -45,12 +47,6 @@ impl FlatTrace { } } -impl HeapSizeOf for FlatTrace { - fn heap_size_of_children(&self) -> usize { - self.trace_address.heap_size_of_children() - } -} - impl Encodable for FlatTrace { fn rlp_append(&self, s: &mut RlpStream) { s.begin_list(4); @@ -76,7 +72,7 @@ impl Decodable for FlatTrace { } /// Represents all traces produced by a single transaction. -#[derive(Debug, PartialEq, Clone, RlpEncodableWrapper, RlpDecodableWrapper)] +#[derive(Debug, PartialEq, Clone, RlpEncodableWrapper, RlpDecodableWrapper, MallocSizeOf)] pub struct FlatTransactionTraces(Vec); impl From> for FlatTransactionTraces { @@ -85,12 +81,6 @@ impl From> for FlatTransactionTraces { } } -impl HeapSizeOf for FlatTransactionTraces { - fn heap_size_of_children(&self) -> usize { - self.0.heap_size_of_children() - } -} - impl FlatTransactionTraces { /// Returns bloom of all traces in the collection. pub fn bloom(&self) -> Bloom { @@ -107,15 +97,11 @@ impl Into> for FlatTransactionTraces { } /// Represents all traces produced by transactions in a single block. -#[derive(Debug, PartialEq, Clone, Default, RlpEncodableWrapper, RlpDecodableWrapper)] +#[derive( + Debug, PartialEq, Clone, Default, RlpEncodableWrapper, RlpDecodableWrapper, MallocSizeOf, +)] pub struct FlatBlockTraces(Vec); -impl HeapSizeOf for FlatBlockTraces { - fn heap_size_of_children(&self) -> usize { - self.0.heap_size_of_children() - } -} - impl From> for FlatBlockTraces { fn from(v: Vec) -> Self { FlatBlockTraces(v) diff --git a/crates/ethcore/src/trace/types/trace.rs b/crates/ethcore/src/trace/types/trace.rs index 28f7c3f72..62a1160dd 100644 --- a/crates/ethcore/src/trace/types/trace.rs +++ b/crates/ethcore/src/trace/types/trace.rs @@ -47,7 +47,7 @@ pub struct CreateResult { impl CreateResult { /// Returns bloom. pub fn bloom(&self) -> Bloom { - BloomInput::Raw(&self.address).into() + BloomInput::Raw(self.address.as_bytes()).into() } } @@ -96,8 +96,8 @@ impl Call { /// The bloom contains from and to addresses. pub fn bloom(&self) -> Bloom { let mut bloom = Bloom::default(); - bloom.accrue(BloomInput::Raw(&self.from)); - bloom.accrue(BloomInput::Raw(&self.to)); + bloom.accrue(BloomInput::Raw(self.from.as_bytes())); + bloom.accrue(BloomInput::Raw(self.to.as_bytes())); bloom } } @@ -130,7 +130,7 @@ impl Create { /// Returns bloom create action bloom. /// The bloom contains only from address. pub fn bloom(&self) -> Bloom { - BloomInput::Raw(&self.from).into() + BloomInput::Raw(self.from.as_bytes()).into() } } @@ -187,7 +187,7 @@ pub struct Reward { impl Reward { /// Return reward action bloom. pub fn bloom(&self) -> Bloom { - BloomInput::Raw(&self.author).into() + BloomInput::Raw(self.author.as_bytes()).into() } } @@ -227,8 +227,8 @@ impl Suicide { /// Return suicide action bloom. pub fn bloom(&self) -> Bloom { let mut bloom = Bloom::default(); - bloom.accrue(BloomInput::Raw(&self.address)); - bloom.accrue(BloomInput::Raw(&self.refund_address)); + bloom.accrue(BloomInput::Raw(self.address.as_bytes())); + bloom.accrue(BloomInput::Raw(self.refund_address.as_bytes())); bloom } } diff --git a/crates/ethcore/src/tx_filter.rs b/crates/ethcore/src/tx_filter.rs index 573fbbfbf..3bcc7df90 100644 --- a/crates/ethcore/src/tx_filter.rs +++ b/crates/ethcore/src/tx_filter.rs @@ -84,7 +84,7 @@ impl TransactionFilter { let mut contract_version_cache = self.contract_version_cache.lock(); let (tx_type, to) = match transaction.tx().action { - Action::Create => (tx_permissions::CREATE, Address::new()), + Action::Create => (tx_permissions::CREATE, Address::default()), Action::Call(address) => { if client .code_hash(&address, BlockId::Hash(*parent_hash)) @@ -173,12 +173,12 @@ impl TransactionFilter { mod test { use super::TransactionFilter; use client::{BlockChainClient, BlockId, Client, ClientConfig}; + use crypto::publickey::{KeyPair, Secret}; use ethereum_types::{Address, U256}; - use ethkey::{KeyPair, Secret}; use io::IoChannel; use miner::Miner; use spec::Spec; - use std::sync::Arc; + use std::{str::FromStr, sync::Arc}; use tempdir::TempDir; use test_helpers; use types::transaction::{Action, Transaction, TypedTransaction}; @@ -200,59 +200,66 @@ mod test { IoChannel::disconnected(), ) .unwrap(); - let key1 = KeyPair::from_secret(Secret::from( - "0000000000000000000000000000000000000000000000000000000000000001", - )) + let key1 = KeyPair::from_secret( + Secret::from_str("0000000000000000000000000000000000000000000000000000000000000001") + .unwrap(), + ) .unwrap(); - let key2 = KeyPair::from_secret(Secret::from( - "0000000000000000000000000000000000000000000000000000000000000002", - )) + let key2 = KeyPair::from_secret( + Secret::from_str("0000000000000000000000000000000000000000000000000000000000000002") + .unwrap(), + ) .unwrap(); - let key3 = KeyPair::from_secret(Secret::from( - "0000000000000000000000000000000000000000000000000000000000000003", - )) + let key3 = KeyPair::from_secret( + Secret::from_str("0000000000000000000000000000000000000000000000000000000000000003") + .unwrap(), + ) .unwrap(); - let key4 = KeyPair::from_secret(Secret::from( - "0000000000000000000000000000000000000000000000000000000000000004", - )) + let key4 = KeyPair::from_secret( + Secret::from_str("0000000000000000000000000000000000000000000000000000000000000004") + .unwrap(), + ) .unwrap(); - let key5 = KeyPair::from_secret(Secret::from( - "0000000000000000000000000000000000000000000000000000000000000005", - )) + let key5 = KeyPair::from_secret( + Secret::from_str("0000000000000000000000000000000000000000000000000000000000000005") + .unwrap(), + ) .unwrap(); - let key6 = KeyPair::from_secret(Secret::from( - "0000000000000000000000000000000000000000000000000000000000000006", - )) + let key6 = KeyPair::from_secret( + Secret::from_str("0000000000000000000000000000000000000000000000000000000000000006") + .unwrap(), + ) .unwrap(); - let key7 = KeyPair::from_secret(Secret::from( - "0000000000000000000000000000000000000000000000000000000000000007", - )) + let key7 = KeyPair::from_secret( + Secret::from_str("0000000000000000000000000000000000000000000000000000000000000007") + .unwrap(), + ) .unwrap(); let filter = TransactionFilter::from_params(spec.params()).unwrap(); let mut basic_tx = TypedTransaction::Legacy(Transaction::default()); basic_tx.tx_mut().action = - Action::Call(Address::from("d41c057fd1c78805aac12b0a94a405c0461a6fbb")); + Action::Call(Address::from_str("d41c057fd1c78805aac12b0a94a405c0461a6fbb").unwrap()); let create_tx = TypedTransaction::Legacy(Transaction::default()); let mut call_tx = TypedTransaction::Legacy(Transaction::default()); call_tx.tx_mut().action = - Action::Call(Address::from("0000000000000000000000000000000000000005")); + Action::Call(Address::from_str("0000000000000000000000000000000000000005").unwrap()); let mut basic_tx_with_ether_and_to_key7 = TypedTransaction::Legacy(Transaction::default()); basic_tx_with_ether_and_to_key7.tx_mut().action = - Action::Call(Address::from("d41c057fd1c78805aac12b0a94a405c0461a6fbb")); + Action::Call(Address::from_str("d41c057fd1c78805aac12b0a94a405c0461a6fbb").unwrap()); basic_tx_with_ether_and_to_key7.tx_mut().value = U256::from(123123); let mut call_tx_with_ether = TypedTransaction::Legacy(Transaction::default()); call_tx_with_ether.tx_mut().action = - Action::Call(Address::from("0000000000000000000000000000000000000005")); + Action::Call(Address::from_str("0000000000000000000000000000000000000005").unwrap()); call_tx_with_ether.tx_mut().value = U256::from(123123); let mut basic_tx_to_key6 = TypedTransaction::Legacy(Transaction::default()); basic_tx_to_key6.tx_mut().action = - Action::Call(Address::from("e57bfe9f44b819898f47bf37e5af72a0783e1141")); + Action::Call(Address::from_str("e57bfe9f44b819898f47bf37e5af72a0783e1141").unwrap()); let mut basic_tx_with_ether_and_to_key6 = TypedTransaction::Legacy(Transaction::default()); basic_tx_with_ether_and_to_key6.tx_mut().action = - Action::Call(Address::from("e57bfe9f44b819898f47bf37e5af72a0783e1141")); + Action::Call(Address::from_str("e57bfe9f44b819898f47bf37e5af72a0783e1141").unwrap()); basic_tx_with_ether_and_to_key6.tx_mut().value = U256::from(123123); let genesis = client.block_hash(BlockId::Latest).unwrap(); @@ -428,31 +435,35 @@ mod test { IoChannel::disconnected(), ) .unwrap(); - let key1 = KeyPair::from_secret(Secret::from( - "0000000000000000000000000000000000000000000000000000000000000001", - )) + let key1 = KeyPair::from_secret( + Secret::from_str("0000000000000000000000000000000000000000000000000000000000000001") + .unwrap(), + ) .unwrap(); - let key2 = KeyPair::from_secret(Secret::from( - "0000000000000000000000000000000000000000000000000000000000000002", - )) + let key2 = KeyPair::from_secret( + Secret::from_str("0000000000000000000000000000000000000000000000000000000000000002") + .unwrap(), + ) .unwrap(); - let key3 = KeyPair::from_secret(Secret::from( - "0000000000000000000000000000000000000000000000000000000000000003", - )) + let key3 = KeyPair::from_secret( + Secret::from_str("0000000000000000000000000000000000000000000000000000000000000003") + .unwrap(), + ) .unwrap(); - let key4 = KeyPair::from_secret(Secret::from( - "0000000000000000000000000000000000000000000000000000000000000004", - )) + let key4 = KeyPair::from_secret( + Secret::from_str("0000000000000000000000000000000000000000000000000000000000000004") + .unwrap(), + ) .unwrap(); let filter = TransactionFilter::from_params(spec.params()).unwrap(); let mut basic_tx = TypedTransaction::Legacy(Transaction::default()); basic_tx.tx_mut().action = - Action::Call(Address::from("000000000000000000000000000000000000032")); + Action::Call(Address::from_str("0000000000000000000000000000000000000032").unwrap()); let create_tx = TypedTransaction::Legacy(Transaction::default()); let mut call_tx = TypedTransaction::Legacy(Transaction::default()); call_tx.tx_mut().action = - Action::Call(Address::from("0000000000000000000000000000000000000005")); + Action::Call(Address::from_str("0000000000000000000000000000000000000005").unwrap()); let genesis = client.block_hash(BlockId::Latest).unwrap(); let block_number = 1; diff --git a/crates/ethcore/src/verification/queue/kind.rs b/crates/ethcore/src/verification/queue/kind.rs index 8bbcc46bd..af8f0e1ce 100644 --- a/crates/ethcore/src/verification/queue/kind.rs +++ b/crates/ethcore/src/verification/queue/kind.rs @@ -20,7 +20,7 @@ use engines::EthEngine; use error::Error; use ethereum_types::{H256, U256}; -use heapsize::HeapSizeOf; +use parity_util_mem::MallocSizeOf; pub use self::{blocks::Blocks, headers::Headers}; @@ -51,13 +51,13 @@ pub trait BlockLike { /// consistent. pub trait Kind: 'static + Sized + Send + Sync { /// The first stage: completely unverified. - type Input: Sized + Send + BlockLike + HeapSizeOf; + type Input: Sized + Send + BlockLike + MallocSizeOf; /// The second stage: partially verified. - type Unverified: Sized + Send + BlockLike + HeapSizeOf; + type Unverified: Sized + Send + BlockLike + MallocSizeOf; /// The third stage: completely verified. - type Verified: Sized + Send + BlockLike + HeapSizeOf; + type Verified: Sized + Send + BlockLike + MallocSizeOf; /// Attempt to create the `Unverified` item from the input. fn create( @@ -88,7 +88,7 @@ pub mod blocks { use bytes::Bytes; use ethereum_types::{H256, U256}; - use heapsize::HeapSizeOf; + use parity_util_mem::MallocSizeOf; /// A mode for verifying blocks. pub struct Blocks; @@ -135,7 +135,7 @@ pub mod blocks { } /// An unverified block. - #[derive(PartialEq, Debug)] + #[derive(PartialEq, Debug, MallocSizeOf)] pub struct Unverified { /// Unverified block header. pub header: Header, @@ -168,15 +168,6 @@ pub mod blocks { } } - impl HeapSizeOf for Unverified { - fn heap_size_of_children(&self) -> usize { - self.header.heap_size_of_children() - + self.transactions.heap_size_of_children() - + self.uncles.heap_size_of_children() - + self.bytes.heap_size_of_children() - } - } - impl BlockLike for Unverified { fn hash(&self) -> H256 { self.header.hash() diff --git a/crates/ethcore/src/verification/queue/mod.rs b/crates/ethcore/src/verification/queue/mod.rs index 2928ccc2e..e4202c564 100644 --- a/crates/ethcore/src/verification/queue/mod.rs +++ b/crates/ethcore/src/verification/queue/mod.rs @@ -22,9 +22,9 @@ use client::ClientIoMessage; use engines::EthEngine; use error::{BlockError, Error, ErrorKind, ImportErrorKind}; use ethereum_types::{H256, U256}; -use heapsize::HeapSizeOf; use io::*; use len_caching_lock::LenCachingMutex; +use parity_util_mem::{MallocSizeOf, MallocSizeOfExt}; use parking_lot::{Condvar, Mutex, RwLock}; use std::{ cmp, @@ -108,17 +108,12 @@ enum State { } /// An item which is in the process of being verified. +#[derive(MallocSizeOf)] pub struct Verifying { hash: H256, output: Option, } -impl HeapSizeOf for Verifying { - fn heap_size_of_children(&self) -> usize { - self.output.heap_size_of_children() - } -} - /// Status of items in the queue. pub enum Status { /// Currently queued. @@ -378,7 +373,7 @@ impl VerificationQueue { verification .sizes .unverified - .fetch_sub(item.heap_size_of_children(), AtomicOrdering::SeqCst); + .fetch_sub(item.malloc_size_of(), AtomicOrdering::SeqCst); verifying.push_back(Verifying { hash: item.hash(), output: None, @@ -397,10 +392,10 @@ impl VerificationQueue { if e.hash == hash { idx = Some(i); - verification.sizes.verifying.fetch_add( - verified.heap_size_of_children(), - AtomicOrdering::SeqCst, - ); + verification + .sizes + .verifying + .fetch_add(verified.malloc_size_of(), AtomicOrdering::SeqCst); e.output = Some(verified); break; } @@ -460,7 +455,7 @@ impl VerificationQueue { while let Some(output) = verifying.front_mut().and_then(|x| x.output.take()) { assert!(verifying.pop_front().is_some()); - let size = output.heap_size_of_children(); + let size = output.malloc_size_of(); removed_size += size; if bad.contains(&output.parent_hash()) { @@ -564,7 +559,7 @@ impl VerificationQueue { self.verification .sizes .unverified - .fetch_add(item.heap_size_of_children(), AtomicOrdering::SeqCst); + .fetch_add(item.malloc_size_of(), AtomicOrdering::SeqCst); //self.processing.write().insert(hash, item.difficulty()); { @@ -621,7 +616,7 @@ impl VerificationQueue { let mut removed_size = 0; for output in verified.drain(..) { if bad.contains(&output.parent_hash()) { - removed_size += output.heap_size_of_children(); + removed_size += output.malloc_size_of(); bad.insert(output.hash()); if let Some((difficulty, _)) = processing.remove(&output.hash()) { let mut td = self.total_difficulty.write(); @@ -663,7 +658,7 @@ impl VerificationQueue { let drained_size = result .iter() - .map(HeapSizeOf::heap_size_of_children) + .map(MallocSizeOfExt::malloc_size_of) .fold(0, |a, c| a + c); self.verification .sizes diff --git a/crates/ethcore/src/verification/verification.rs b/crates/ethcore/src/verification/verification.rs index 0cafaf841..f09cef8d3 100644 --- a/crates/ethcore/src/verification/verification.rs +++ b/crates/ethcore/src/verification/verification.rs @@ -28,7 +28,7 @@ use std::{ use bytes::Bytes; use hash::keccak; -use heapsize::HeapSizeOf; +use parity_util_mem::MallocSizeOf; use rlp::Rlp; use triehash::ordered_trie_root; use unexpected::{Mismatch, OutOfBounds}; @@ -44,6 +44,7 @@ use verification::queue::kind::blocks::Unverified; use time_utils::CheckedSystemTime; /// Preprocessed block data gathered in `verify_block_unordered` call +#[derive(MallocSizeOf)] pub struct PreverifiedBlock { /// Populated block header pub header: Header, @@ -55,14 +56,6 @@ pub struct PreverifiedBlock { pub bytes: Bytes, } -impl HeapSizeOf for PreverifiedBlock { - fn heap_size_of_children(&self) -> usize { - self.header.heap_size_of_children() - + self.transactions.heap_size_of_children() - + self.bytes.heap_size_of_children() - } -} - /// t_nb 4.0 Phase 1 quick block verification. Only does checks that are cheap. Operates on a single block pub fn verify_block_basic( block: &Unverified, @@ -524,10 +517,10 @@ mod tests { use super::*; use blockchain::{BlockDetails, BlockReceipts, TransactionAddress}; + use crypto::publickey::{Generator, Random}; use engines::EthEngine; use error::{BlockError::*, ErrorKind}; - use ethereum_types::{BloomRef, H256, U256}; - use ethkey::{Generator, Random}; + use ethereum_types::{Address, BloomRef, H256, U256}; use hash::keccak; use rlp; use spec::{CommonParams, Spec}; @@ -771,7 +764,7 @@ mod tests { good.set_timestamp(40); good.set_number(10); - let keypair = Random.generate().unwrap(); + let keypair = Random.generate(); let tr1 = TypedTransaction::Legacy(Transaction { action: Action::Create, @@ -794,7 +787,7 @@ mod tests { .sign(keypair.secret(), None); let tr3 = TypedTransaction::Legacy(Transaction { - action: Action::Call(0x0.into()), + action: Action::Call(Address::from_low_u64_be(0x0)), value: U256::from(0), data: Bytes::new(), gas: U256::from(30_000), @@ -871,7 +864,7 @@ mod tests { bad_header.set_transactions_root(eip86_transactions_root.clone()); bad_header.set_uncles_hash(good_uncles_hash.clone()); match basic_test(&create_test_block_with_data(&bad_header, &eip86_transactions, &good_uncles), engine) { - Err(Error(ErrorKind::Transaction(ref e), _)) if e == &::ethkey::Error::InvalidSignature.into() => (), + Err(Error(ErrorKind::Transaction(ref e), _)) if e == &crypto::publickey::Error::InvalidSignature.into() => (), e => panic!("Block verification failed.\nExpected: Transaction Error (Invalid Signature)\nGot: {:?}", e), } @@ -1102,8 +1095,8 @@ mod tests { #[test] fn dust_protection() { + use crypto::publickey::{Generator, Random}; use engines::NullEngine; - use ethkey::{Generator, Random}; use machine::EthereumMachine; use types::transaction::{Action, Transaction}; @@ -1114,7 +1107,7 @@ mod tests { let mut header = Header::default(); header.set_number(1); - let keypair = Random.generate().unwrap(); + let keypair = Random.generate(); let bad_transactions: Vec<_> = (0..3) .map(|i| { TypedTransaction::Legacy(Transaction { diff --git a/crates/ethcore/sync/Cargo.toml b/crates/ethcore/sync/Cargo.toml index 529537065..a449791a3 100644 --- a/crates/ethcore/sync/Cargo.toml +++ b/crates/ethcore/sync/Cargo.toml @@ -17,22 +17,23 @@ ethcore-network = { path = "../../net/network" } ethcore-network-devp2p = { path = "../../net/network-devp2p" } ethereum-forkid = "0.2" primitive_types07 = { package = "primitive-types", version = "0.7"} -ethereum-types = "0.4" +ethereum-types = "0.9.2" ethkey = { path = "../../accounts/ethkey" } ethstore = { path = "../../accounts/ethstore" } fastmap = { path = "../../util/fastmap" } hash-db = "0.11.0" -heapsize = "0.4" -keccak-hash = "0.1" +keccak-hash = "0.5.0" keccak-hasher = { path = "../../util/keccak-hasher" } kvdb = "0.1" log = "0.4" macros = { path = "../../util/macros" } parity-bytes = "0.1" +parity-crypto = { version = "0.6.2", features = [ "publickey" ] } +parity-util-mem = "0.7" parking_lot = "0.7" -rand = "0.4" -rlp = { version = "0.3.0", features = ["ethereum"] } -rlp04 = { package = "rlp", version = "0.4" } +rand = "0.7.3" +rand_xorshift = "0.2.0" +rlp = { version = "0.4.6" } trace-time = "0.1" triehash-ethereum = {version = "0.2", path = "../../util/triehash-ethereum" } stats = { path = "../../util/stats" } diff --git a/crates/ethcore/sync/src/api.rs b/crates/ethcore/sync/src/api.rs index e45196986..74c132a82 100644 --- a/crates/ethcore/sync/src/api.rs +++ b/crates/ethcore/sync/src/api.rs @@ -15,6 +15,7 @@ // along with OpenEthereum. If not, see . use bytes::Bytes; +use crypto::publickey::Secret; use devp2p::NetworkService; use network::{ client_version::ClientVersion, ConnectionFilter, Error, ErrorKind, @@ -38,7 +39,6 @@ use ethcore::{ snapshot::SnapshotService, }; use ethereum_types::{H256, H512, U256, U64}; -use ethkey::Secret; use io::TimerToken; use network::IpFilter; use parking_lot::{Mutex, RwLock}; diff --git a/crates/ethcore/sync/src/block_sync.rs b/crates/ethcore/sync/src/block_sync.rs index 44f33dd19..748e2199d 100644 --- a/crates/ethcore/sync/src/block_sync.rs +++ b/crates/ethcore/sync/src/block_sync.rs @@ -99,12 +99,6 @@ pub enum BlockDownloaderImportError { Useless, } -impl From for BlockDownloaderImportError { - fn from(_: rlp04::DecoderError) -> BlockDownloaderImportError { - BlockDownloaderImportError::Invalid - } -} - impl From for BlockDownloaderImportError { fn from(_: rlp::DecoderError) -> BlockDownloaderImportError { BlockDownloaderImportError::Invalid @@ -770,8 +764,8 @@ where #[cfg(test)] mod tests { use super::*; + use crypto::publickey::{Generator, Random}; use ethcore::{client::TestBlockChainClient, spec::Spec}; - use ethkey::{Generator, Random}; use hash::keccak; use parking_lot::RwLock; use rlp::{encode_list, RlpStream}; @@ -794,7 +788,7 @@ mod tests { } fn dummy_signed_tx() -> SignedTransaction { - let keypair = Random.generate().unwrap(); + let keypair = Random.generate(); TypedTransaction::Legacy(Transaction::default()).sign(keypair.secret(), None) } diff --git a/crates/ethcore/sync/src/blocks.rs b/crates/ethcore/sync/src/blocks.rs index a4e5b61d8..f5c9ad675 100644 --- a/crates/ethcore/sync/src/blocks.rs +++ b/crates/ethcore/sync/src/blocks.rs @@ -18,8 +18,8 @@ use bytes::Bytes; use ethcore::verification::queue::kind::blocks::Unverified; use ethereum_types::H256; use hash::{keccak, KECCAK_EMPTY_LIST_RLP, KECCAK_NULL_RLP}; -use heapsize::HeapSizeOf; use network; +use parity_util_mem::MallocSizeOf; use rlp::{DecoderError, Rlp, RlpStream}; use std::collections::{hash_map, BTreeMap, HashMap, HashSet}; use triehash_ethereum::ordered_trie_root; @@ -28,20 +28,14 @@ use types::{ transaction::{TypedTransaction, UnverifiedTransaction}, }; -known_heap_size!(0, HeaderId); +malloc_size_of_is_0!(HeaderId); -#[derive(PartialEq, Debug, Clone)] +#[derive(PartialEq, Debug, Clone, MallocSizeOf)] pub struct SyncHeader { pub bytes: Bytes, pub header: BlockHeader, } -impl HeapSizeOf for SyncHeader { - fn heap_size_of_children(&self) -> usize { - self.bytes.heap_size_of_children() + self.header.heap_size_of_children() - } -} - impl SyncHeader { pub fn from_rlp(bytes: Bytes) -> Result { let result = SyncHeader { @@ -53,6 +47,7 @@ impl SyncHeader { } } +#[derive(MallocSizeOf)] pub struct SyncBody { pub transactions_bytes: Bytes, pub transactions: Vec, @@ -86,16 +81,8 @@ impl SyncBody { } } -impl HeapSizeOf for SyncBody { - fn heap_size_of_children(&self) -> usize { - self.transactions_bytes.heap_size_of_children() - + self.transactions.heap_size_of_children() - + self.uncles_bytes.heap_size_of_children() - + self.uncles.heap_size_of_children() - } -} - /// Block data with optional body. +#[derive(MallocSizeOf)] struct SyncBlock { header: SyncHeader, body: Option, @@ -103,12 +90,6 @@ struct SyncBlock { receipts_root: H256, } -impl HeapSizeOf for SyncBlock { - fn heap_size_of_children(&self) -> usize { - self.header.heap_size_of_children() + self.body.heap_size_of_children() - } -} - fn unverified_from_sync(header: SyncHeader, body: Option) -> Unverified { let mut stream = RlpStream::new_list(3); stream.append_raw(&header.bytes, 1); @@ -588,7 +569,7 @@ impl BlockCollection { (None, receipt_root) } } else { - (None, H256::new()) + (None, H256::default()) }; self.parents.insert(*info.header.parent_hash(), hash); diff --git a/crates/ethcore/sync/src/chain/handler.rs b/crates/ethcore/sync/src/chain/handler.rs index a37eb862b..6938209b8 100644 --- a/crates/ethcore/sync/src/chain/handler.rs +++ b/crates/ethcore/sync/src/chain/handler.rs @@ -692,8 +692,10 @@ impl SyncHandler { .ok_or(rlp::DecoderError::RlpIsTooShort)? .as_val()?; let forkid_validation_error = { - let fork_id = rlp04::Rlp::new(r.as_raw()).val_at(5)?; - r_iter.next().ok_or(rlp::DecoderError::RlpIsTooShort)?; + let fork_id = r_iter + .next() + .ok_or(rlp::DecoderError::RlpIsTooShort)? + .as_val()?; sync.fork_filter .is_compatible(io.chain(), fork_id) .err() diff --git a/crates/ethcore/sync/src/chain/mod.rs b/crates/ethcore/sync/src/chain/mod.rs index bf6103a2b..4d04fe388 100644 --- a/crates/ethcore/sync/src/chain/mod.rs +++ b/crates/ethcore/sync/src/chain/mod.rs @@ -109,7 +109,7 @@ use fastmap::{H256FastMap, H256FastSet}; use hash::keccak; use network::{self, client_version::ClientVersion, PeerId}; use parking_lot::Mutex; -use rand::Rng; +use rand::{seq::SliceRandom, Rng}; use rlp::{DecoderError, RlpStream}; use snapshot::Snapshot; use std::{ @@ -136,7 +136,7 @@ use self::{ pub(crate) use self::supplier::SyncSupplier; use self::{propagator::SyncPropagator, requester::SyncRequester}; -known_heap_size!(0, PeerInfo); +malloc_size_of_is_0!(PeerInfo); /// Possible errors during packet's processing #[derive(Debug, Display)] @@ -380,15 +380,17 @@ impl PeerInfo { #[cfg(not(test))] pub mod random { use rand; - pub fn new() -> rand::ThreadRng { + pub fn new() -> rand::rngs::ThreadRng { rand::thread_rng() } } #[cfg(test)] pub mod random { - use rand::{self, SeedableRng}; - pub fn new() -> rand::XorShiftRng { - rand::XorShiftRng::from_seed([0, 1, 2, 3]) + use rand::SeedableRng; + use rand_xorshift::XorShiftRng; + const RNG_SEED: [u8; 16] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]; + pub fn new() -> XorShiftRng { + XorShiftRng::from_seed(RNG_SEED) } } @@ -630,7 +632,7 @@ impl ChainSync { let mut count = (peers.len() as f64).powf(0.5).round() as usize; count = cmp::min(count, MAX_PEERS_PROPAGATION); count = cmp::max(count, MIN_PEERS_PROPAGATION); - random::new().shuffle(&mut peers); + peers.shuffle(&mut random::new()); peers.truncate(count); peers } @@ -1029,8 +1031,9 @@ impl ChainSync { self.active_peers.len(), peers.len(), self.peers.len() ); - random::new().shuffle(&mut peers); // TODO (#646): sort by rating + peers.shuffle(&mut random::new()); // TODO (#646): sort by rating // prefer peers with higher protocol version + peers.sort_by(|&(_, ref v1), &(_, ref v2)| v1.cmp(v2)); for (peer_id, _) in peers { @@ -1297,7 +1300,7 @@ impl ChainSync { }; trace!(target: "sync", "Sending status to {}, protocol version {}", peer, protocol); - let mut packet = rlp04::RlpStream::new(); + let mut packet = RlpStream::new(); packet.begin_unbounded_list(); let chain = io.chain().chain_info(); packet.append(&(protocol as u32)); @@ -1310,7 +1313,7 @@ impl ChainSync { if warp_protocol { let manifest = io.snapshot_service().manifest(); let block_number = manifest.as_ref().map_or(0, |m| m.block_number); - let manifest_hash = manifest.map_or(H256::new(), |m| keccak(m.into_rlp())); + let manifest_hash = manifest.map_or(H256::default(), |m| keccak(m.into_rlp())); packet.append(&primitive_types07::H256(manifest_hash.0)); packet.append(&block_number); } @@ -1521,7 +1524,6 @@ pub mod tests { miner::{MinerService, PendingOrdering}, }; use ethereum_types::{Address, H256, U256}; - use ethkey; use network::PeerId; use parking_lot::RwLock; use rlp::{Rlp, RlpStream}; @@ -1558,7 +1560,7 @@ pub mod tests { let mut rlp = RlpStream::new_list(5); for _ in 0..5 { let mut hash_d_rlp = RlpStream::new_list(2); - let hash: H256 = H256::from(0u64); + let hash: H256 = H256::from_low_u64_be(0u64); let diff: U256 = U256::from(1u64); hash_d_rlp.append(&hash); hash_d_rlp.append(&diff); @@ -1720,7 +1722,7 @@ pub mod tests { #[test] fn should_add_transactions_to_queue() { fn sender(tx: &UnverifiedTransaction) -> Address { - ethkey::public_to_address(&tx.recover_public().unwrap()) + crypto::publickey::public_to_address(&tx.recover_public().unwrap()) } // given diff --git a/crates/ethcore/sync/src/chain/propagator.rs b/crates/ethcore/sync/src/chain/propagator.rs index de79c1207..1d814bca9 100644 --- a/crates/ethcore/sync/src/chain/propagator.rs +++ b/crates/ethcore/sync/src/chain/propagator.rs @@ -20,7 +20,7 @@ use bytes::Bytes; use ethereum_types::H256; use fastmap::H256FastSet; use network::{client_version::ClientCapabilities, PeerId}; -use rand::Rng; +use rand::RngCore; use rlp::RlpStream; use sync_io::SyncIo; use types::{blockchain_info::BlockChainInfo, transaction::SignedTransaction, BlockNumber}; @@ -249,7 +249,7 @@ impl SyncPropagator { pushed += 1; } } - packet.complete_unbounded_list(); + packet.finalize_unbounded_list(); (packet, to_send) }; diff --git a/crates/ethcore/sync/src/chain/supplier.rs b/crates/ethcore/sync/src/chain/supplier.rs index 3746819d5..9b667e921 100644 --- a/crates/ethcore/sync/src/chain/supplier.rs +++ b/crates/ethcore/sync/src/chain/supplier.rs @@ -421,7 +421,7 @@ mod test { use ethereum_types::H256; use parking_lot::RwLock; use rlp::{Rlp, RlpStream}; - use std::{collections::VecDeque, sync::RwLock as StdRwLock}; + use std::{collections::VecDeque, str::FromStr, sync::RwLock as StdRwLock}; use tests::{helpers::TestIo, snapshot::TestSnapshotService}; #[test] @@ -470,7 +470,7 @@ mod test { let ss = TestSnapshotService::new(); let io = TestIo::new(&mut client, &ss, &queue, None); - let unknown: H256 = H256::new(); + let unknown: H256 = H256::default(); let result = SyncSupplier::return_block_headers( &io, &Rlp::new(&make_hash_req(&unknown, 1, 0, false)), @@ -614,23 +614,27 @@ mod test { fn return_receipts() { let mut client = TestBlockChainClient::new(); let queue = RwLock::new(VecDeque::new()); - let sync = dummy_sync_with_peer(H256::new(), &client); + let sync = dummy_sync_with_peer(H256::default(), &client); let ss = TestSnapshotService::new(); let mut io = TestIo::new(&mut client, &ss, &queue, None); let mut receipt_list = RlpStream::new_list(4); - receipt_list.append(&H256::from( - "0000000000000000000000000000000000000000000000005555555555555555", - )); - receipt_list.append(&H256::from( - "ff00000000000000000000000000000000000000000000000000000000000000", - )); - receipt_list.append(&H256::from( - "fff0000000000000000000000000000000000000000000000000000000000000", - )); - receipt_list.append(&H256::from( - "aff0000000000000000000000000000000000000000000000000000000000000", - )); + receipt_list.append( + &H256::from_str("0000000000000000000000000000000000000000000000005555555555555555") + .unwrap(), + ); + receipt_list.append( + &H256::from_str("ff00000000000000000000000000000000000000000000000000000000000000") + .unwrap(), + ); + receipt_list.append( + &H256::from_str("fff0000000000000000000000000000000000000000000000000000000000000") + .unwrap(), + ); + receipt_list.append( + &H256::from_str("aff0000000000000000000000000000000000000000000000000000000000000") + .unwrap(), + ); let receipts_request = receipt_list.out(); // it returns rlp ONLY for hashes started with "f" diff --git a/crates/ethcore/sync/src/lib.rs b/crates/ethcore/sync/src/lib.rs index ff2bf8bb3..ea37d6982 100644 --- a/crates/ethcore/sync/src/lib.rs +++ b/crates/ethcore/sync/src/lib.rs @@ -34,11 +34,14 @@ extern crate ethstore; extern crate fastmap; extern crate keccak_hash as hash; extern crate parity_bytes as bytes; +extern crate parity_crypto as crypto; +#[macro_use] +extern crate parity_util_mem; extern crate parking_lot; extern crate primitive_types07; extern crate rand; +extern crate rand_xorshift; extern crate rlp; -extern crate rlp04; extern crate stats; extern crate triehash_ethereum; @@ -56,8 +59,6 @@ extern crate macros; #[macro_use] extern crate log; #[macro_use] -extern crate heapsize; -#[macro_use] extern crate trace_time; mod block_sync; diff --git a/crates/ethcore/sync/src/snapshot.rs b/crates/ethcore/sync/src/snapshot.rs index 72b90574d..b5f33081e 100644 --- a/crates/ethcore/sync/src/snapshot.rs +++ b/crates/ethcore/sync/src/snapshot.rs @@ -191,15 +191,19 @@ mod test { } fn test_manifest() -> (ManifestData, H256, Vec, Vec) { - let state_chunks: Vec = (0..20).map(|_| H256::random().to_vec()).collect(); - let block_chunks: Vec = (0..20).map(|_| H256::random().to_vec()).collect(); + let state_chunks: Vec = (0..20) + .map(|_| H256::random().as_bytes().to_vec()) + .collect(); + let block_chunks: Vec = (0..20) + .map(|_| H256::random().as_bytes().to_vec()) + .collect(); let manifest = ManifestData { version: 2, state_hashes: state_chunks.iter().map(|data| keccak(data)).collect(), block_hashes: block_chunks.iter().map(|data| keccak(data)).collect(), - state_root: H256::new(), + state_root: H256::default(), block_number: 42, - block_hash: H256::new(), + block_hash: H256::default(), }; let mhash = keccak(manifest.clone().into_rlp()); (manifest, mhash, state_chunks, block_chunks) @@ -222,7 +226,9 @@ mod test { let (manifest, mhash, state_chunks, block_chunks) = test_manifest(); snapshot.reset_to(&manifest, &mhash); assert_eq!(snapshot.done_chunks(), 0); - assert!(snapshot.validate_chunk(&H256::random().to_vec()).is_err()); + assert!(snapshot + .validate_chunk(&H256::random().as_bytes().to_vec()) + .is_err()); let requested: Vec = (0..40).map(|_| snapshot.needed_chunk().unwrap()).collect(); assert!(snapshot.needed_chunk().is_none()); diff --git a/crates/ethcore/sync/src/tests/consensus.rs b/crates/ethcore/sync/src/tests/consensus.rs index 6af66ec29..d3e949512 100644 --- a/crates/ethcore/sync/src/tests/consensus.rs +++ b/crates/ethcore/sync/src/tests/consensus.rs @@ -15,6 +15,7 @@ // along with OpenEthereum. If not, see . use super::helpers::*; +use crypto::publickey::{KeyPair, Secret}; use ethcore::{ client::{ChainInfo, ClientIoMessage}, engines, @@ -22,7 +23,6 @@ use ethcore::{ spec::Spec, }; use ethereum_types::{Address, U256}; -use ethkey::{KeyPair, Secret}; use hash::keccak; use io::{IoChannel, IoHandler}; use std::sync::Arc; @@ -44,8 +44,8 @@ fn new_tx(secret: &Secret, nonce: U256, chain_id: u64) -> PendingTransaction { #[test] fn authority_round() { - let s0 = KeyPair::from_secret_slice(&keccak("1")).unwrap(); - let s1 = KeyPair::from_secret_slice(&keccak("0")).unwrap(); + let s0 = KeyPair::from_secret_slice(keccak("1").as_bytes()).unwrap(); + let s1 = KeyPair::from_secret_slice(keccak("0").as_bytes()).unwrap(); let chain_id = Spec::new_test_round().chain_id(); let mut net = TestNet::with_spec(2, SyncConfig::default(), Spec::new_test_round); diff --git a/crates/ethcore/sync/src/tests/helpers.rs b/crates/ethcore/sync/src/tests/helpers.rs index 89eb22dd6..8d00714be 100644 --- a/crates/ethcore/sync/src/tests/helpers.rs +++ b/crates/ethcore/sync/src/tests/helpers.rs @@ -37,10 +37,7 @@ use network::{self, client_version::ClientVersion, PacketId, PeerId, ProtocolId, use parking_lot::RwLock; use std::{ collections::{HashMap, HashSet, VecDeque}, - sync::{ - Arc, RwLock as StdRwLock, RwLockReadGuard as StdRwLockReadGuard, - RwLockWriteGuard as StdRwLockWriteGuard, - }, + sync::{Arc, RwLock as StdRwLock}, }; use sync_io::SyncIo; use tests::snapshot::*; diff --git a/crates/ethcore/sync/src/tests/snapshot.rs b/crates/ethcore/sync/src/tests/snapshot.rs index 89f635b5f..9cc07c1b3 100644 --- a/crates/ethcore/sync/src/tests/snapshot.rs +++ b/crates/ethcore/sync/src/tests/snapshot.rs @@ -56,16 +56,16 @@ impl TestSnapshotService { let num_state_chunks = num_chunks / 2; let num_block_chunks = num_chunks - num_state_chunks; let state_chunks: Vec = (0..num_state_chunks) - .map(|_| H256::random().to_vec()) + .map(|_| H256::random().as_bytes().to_vec()) .collect(); let block_chunks: Vec = (0..num_block_chunks) - .map(|_| H256::random().to_vec()) + .map(|_| H256::random().as_bytes().to_vec()) .collect(); let manifest = ManifestData { version: 2, state_hashes: state_chunks.iter().map(|data| keccak(data)).collect(), block_hashes: block_chunks.iter().map(|data| keccak(data)).collect(), - state_root: H256::new(), + state_root: H256::default(), block_number: block_number, block_hash: block_hash, }; @@ -188,7 +188,7 @@ fn snapshot_sync() { let mut net = TestNet::new_with_config(5, config); let snapshot_service = Arc::new(TestSnapshotService::new_with_snapshot( 16, - H256::new(), + H256::default(), 500000, )); for i in 0..4 { diff --git a/crates/ethcore/sync/src/transactions_stats.rs b/crates/ethcore/sync/src/transactions_stats.rs index 989900ecb..44e47ec40 100644 --- a/crates/ethcore/sync/src/transactions_stats.rs +++ b/crates/ethcore/sync/src/transactions_stats.rs @@ -104,15 +104,16 @@ impl TransactionsStats { mod tests { use super::{Stats, TransactionsStats}; + use ethereum_types::{H256, H512}; use std::collections::{HashMap, HashSet}; #[test] fn should_keep_track_of_propagations() { // given let mut stats = TransactionsStats::default(); - let hash = 5.into(); - let enodeid1 = 2.into(); - let enodeid2 = 5.into(); + let hash = H256::from_low_u64_be(5); + let enodeid1 = H512::from_low_u64_be(2); + let enodeid2 = H512::from_low_u64_be(5); // when stats.propagated(&hash, Some(enodeid1), 5); @@ -137,8 +138,8 @@ mod tests { fn should_remove_hash_from_tracking() { // given let mut stats = TransactionsStats::default(); - let hash = 5.into(); - let enodeid1 = 5.into(); + let hash = H256::from_low_u64_be(5); + let enodeid1 = H512::from_low_u64_be(5); stats.propagated(&hash, Some(enodeid1), 10); // when diff --git a/crates/ethcore/types/Cargo.toml b/crates/ethcore/types/Cargo.toml index 9a16ddcb6..86c0d48ea 100644 --- a/crates/ethcore/types/Cargo.toml +++ b/crates/ethcore/types/Cargo.toml @@ -5,12 +5,12 @@ version = "0.1.0" authors = ["Parity Technologies "] [dependencies] -ethereum-types = "0.4" -ethkey = { path = "../../accounts/ethkey" } -heapsize = "0.4" -keccak-hash = "0.1" +ethereum-types = "0.9.2" +keccak-hash = "0.5.0" parity-bytes = "0.1" -rlp = { version = "0.3.0", features = ["ethereum"] } +parity-crypto = { version = "0.6.2", features = [ "publickey" ] } +parity-util-mem = "0.7" +rlp = { version = "0.4.6" } rlp_derive = { path = "../../util/rlp-derive" } unexpected = { path = "../../util/unexpected" } serde = "1.0" diff --git a/crates/ethcore/types/src/account_diff.rs b/crates/ethcore/types/src/account_diff.rs index 1144712c7..7ea690df1 100644 --- a/crates/ethcore/types/src/account_diff.rs +++ b/crates/ethcore/types/src/account_diff.rs @@ -120,17 +120,17 @@ impl AccountDiff { // TODO: refactor into something nicer. fn interpreted_hash(u: &H256) -> String { - if u <= &H256::from(0xffffffff) { + if u <= &H256::from_low_u64_be(0xffffffff) { format!( "{} = 0x{:x}", - U256::from(&**u).low_u32(), - U256::from(&**u).low_u32() + U256::from(u.as_bytes()).low_u32(), + U256::from(u.as_bytes()).low_u32() ) - } else if u <= &H256::from(u64::max_value()) { + } else if u <= &H256::from_low_u64_be(u64::max_value()) { format!( "{} = 0x{:x}", - U256::from(&**u).low_u64(), - U256::from(&**u).low_u64() + U256::from(u.as_bytes()).low_u64(), + U256::from(u.as_bytes()).low_u64() ) // } else if u <= &H256::from("0xffffffffffffffffffffffffffffffffffffffff") { // format!("@{}", Address::from(u)) diff --git a/crates/ethcore/types/src/encoded.rs b/crates/ethcore/types/src/encoded.rs index daf15eba0..f55074022 100644 --- a/crates/ethcore/types/src/encoded.rs +++ b/crates/ethcore/types/src/encoded.rs @@ -27,22 +27,16 @@ use block::Block as FullBlock; use ethereum_types::{Address, Bloom, H256, U256}; use hash::keccak; use header::Header as FullHeader; -use heapsize::HeapSizeOf; +use parity_util_mem::MallocSizeOf; use rlp::{self, Rlp, RlpStream}; use transaction::UnverifiedTransaction; use views::{self, BlockView, BodyView, HeaderView}; use BlockNumber; /// Owning header view. -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq, MallocSizeOf)] pub struct Header(Vec); -impl HeapSizeOf for Header { - fn heap_size_of_children(&self) -> usize { - self.0.heap_size_of_children() - } -} - impl Header { /// Create a new owning header view. /// Expects the data to be an RLP-encoded header -- any other case will likely lead to @@ -153,15 +147,9 @@ impl Header { } /// Owning block body view. -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq, MallocSizeOf)] pub struct Body(Vec); -impl HeapSizeOf for Body { - fn heap_size_of_children(&self) -> usize { - self.0.heap_size_of_children() - } -} - impl Body { /// Create a new owning block body view. The raw bytes passed in must be an rlp-encoded block /// body. @@ -246,15 +234,9 @@ impl Body { } /// Owning block view. -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq, MallocSizeOf)] pub struct Block(Vec); -impl HeapSizeOf for Block { - fn heap_size_of_children(&self) -> usize { - self.0.heap_size_of_children() - } -} - impl Block { /// Create a new owning block view. The raw bytes passed in must be an rlp-encoded block. pub fn new(raw: Vec) -> Self { diff --git a/crates/ethcore/types/src/filter.rs b/crates/ethcore/types/src/filter.rs index 84b8a3b64..822c2f7de 100644 --- a/crates/ethcore/types/src/filter.rs +++ b/crates/ethcore/types/src/filter.rs @@ -71,7 +71,7 @@ impl Filter { let blooms = match self.address { Some(ref addresses) if !addresses.is_empty() => addresses .iter() - .map(|ref address| Bloom::from(BloomInput::Raw(address))) + .map(|ref address| Bloom::from(BloomInput::Raw(address.as_bytes()))) .collect(), _ => vec![Bloom::default()], }; @@ -85,7 +85,7 @@ impl Filter { .into_iter() .map(|topic| { let mut b = bloom.clone(); - b.accrue(BloomInput::Raw(topic)); + b.accrue(BloomInput::Raw(topic.as_bytes())); b }) .collect::>() @@ -119,10 +119,11 @@ impl Filter { #[cfg(test)] mod tests { - use ethereum_types::Bloom; + use ethereum_types::{Bloom, H160, H256}; use filter::Filter; use ids::BlockId; use log_entry::LogEntry; + use std::str::FromStr; #[test] fn test_bloom_possibilities_none() { @@ -145,11 +146,15 @@ mod tests { let filter = Filter { from_block: BlockId::Earliest, to_block: BlockId::Latest, - address: Some(vec!["b372018f3be9e171df0581136b59d2faf73a7d5d".into()]), + address: Some(vec![H160::from_str( + "b372018f3be9e171df0581136b59d2faf73a7d5d", + ) + .unwrap()]), topics: vec![ - Some(vec![ - "ff74e91598aed6ae5d2fdcf8b24cd2c7be49a0808112a305069355b7160f23f9".into(), - ]), + Some(vec![H256::from_str( + "ff74e91598aed6ae5d2fdcf8b24cd2c7be49a0808112a305069355b7160f23f9", + ) + .unwrap()]), None, None, None, @@ -158,7 +163,7 @@ mod tests { }; let possibilities = filter.bloom_possibilities(); - assert_eq!(possibilities, vec!["00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000000000004000000004000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000000000000000".into()] as Vec); + assert_eq!(possibilities, vec![Bloom::from_str("00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000000000004000000004000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000000000000000").unwrap()] as Vec); } #[test] @@ -166,14 +171,19 @@ mod tests { let filter = Filter { from_block: BlockId::Earliest, to_block: BlockId::Latest, - address: Some(vec!["b372018f3be9e171df0581136b59d2faf73a7d5d".into()]), + address: Some(vec![H160::from_str( + "b372018f3be9e171df0581136b59d2faf73a7d5d", + ) + .unwrap()]), topics: vec![ - Some(vec![ - "ff74e91598aed6ae5d2fdcf8b24cd2c7be49a0808112a305069355b7160f23f9".into(), - ]), - Some(vec![ - "ff74e91598aed6ae5d2fdcf8b24cd2c7be49a0808112a305069355b7160f23f9".into(), - ]), + Some(vec![H256::from_str( + "ff74e91598aed6ae5d2fdcf8b24cd2c7be49a0808112a305069355b7160f23f9", + ) + .unwrap()]), + Some(vec![H256::from_str( + "ff74e91598aed6ae5d2fdcf8b24cd2c7be49a0808112a305069355b7160f23f9", + ) + .unwrap()]), None, None, ], @@ -181,7 +191,7 @@ mod tests { }; let possibilities = filter.bloom_possibilities(); - assert_eq!(possibilities, vec!["00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000000000004000000004000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000000000000000".into()] as Vec); + assert_eq!(possibilities, vec![Bloom::from_str("00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000000000004000000004000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000000000000000").unwrap()] as Vec); } #[test] @@ -190,21 +200,34 @@ mod tests { from_block: BlockId::Earliest, to_block: BlockId::Latest, address: Some(vec![ - "b372018f3be9e171df0581136b59d2faf73a7d5d".into(), - "b372018f3be9e171df0581136b59d2faf73a7d5d".into(), + H160::from_str("b372018f3be9e171df0581136b59d2faf73a7d5d").unwrap(), + H160::from_str("b372018f3be9e171df0581136b59d2faf73a7d5d").unwrap(), ]), topics: vec![ Some(vec![ - "ff74e91598aed6ae5d2fdcf8b24cd2c7be49a0808112a305069355b7160f23f9".into(), - "ff74e91598aed6ae5d2fdcf8b24cd2c7be49a0808112a305069355b7160f23f9".into(), + H256::from_str( + "ff74e91598aed6ae5d2fdcf8b24cd2c7be49a0808112a305069355b7160f23f9", + ) + .unwrap(), + H256::from_str( + "ff74e91598aed6ae5d2fdcf8b24cd2c7be49a0808112a305069355b7160f23f9", + ) + .unwrap(), ]), Some(vec![ - "ff74e91598aed6ae5d2fdcf8b24cd2c7be49a0808112a305069355b7160f23f9".into(), - "ff74e91598aed6ae5d2fdcf8b24cd2c7be49a0808112a305069355b7160f23f9".into(), - ]), - Some(vec![ - "ff74e91598aed6ae5d2fdcf8b24cd2c7be49a0808112a305069355b7160f23f9".into(), + H256::from_str( + "ff74e91598aed6ae5d2fdcf8b24cd2c7be49a0808112a305069355b7160f23f9", + ) + .unwrap(), + H256::from_str( + "ff74e91598aed6ae5d2fdcf8b24cd2c7be49a0808112a305069355b7160f23f9", + ) + .unwrap(), ]), + Some(vec![H256::from_str( + "ff74e91598aed6ae5d2fdcf8b24cd2c7be49a0808112a305069355b7160f23f9", + ) + .unwrap()]), None, ], limit: None, @@ -213,7 +236,7 @@ mod tests { // number of possibilites should be equal 2 * 2 * 2 * 1 = 8 let possibilities = filter.bloom_possibilities(); assert_eq!(possibilities.len(), 8); - assert_eq!(possibilities[0], Bloom::from("00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000000000004000000004000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000000000000000")); + assert_eq!(possibilities[0], Bloom::from_str("00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000000000004000000004000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000000000000000").unwrap()); } #[test] @@ -221,14 +244,19 @@ mod tests { let filter = Filter { from_block: BlockId::Earliest, to_block: BlockId::Latest, - address: Some(vec!["b372018f3be9e171df0581136b59d2faf73a7d5d".into()]), + address: Some(vec![H160::from_str( + "b372018f3be9e171df0581136b59d2faf73a7d5d", + ) + .unwrap()]), topics: vec![ - Some(vec![ - "ff74e91598aed6ae5d2fdcf8b24cd2c7be49a0808112a305069355b7160f23f9".into(), - ]), - Some(vec![ - "ff74e91598aed6ae5d2fdcf8b24cd2c7be49a0808112a305069355b7160f23fa".into(), - ]), + Some(vec![H256::from_str( + "ff74e91598aed6ae5d2fdcf8b24cd2c7be49a0808112a305069355b7160f23f9", + ) + .unwrap()]), + Some(vec![H256::from_str( + "ff74e91598aed6ae5d2fdcf8b24cd2c7be49a0808112a305069355b7160f23fa", + ) + .unwrap()]), None, None, ], @@ -236,28 +264,37 @@ mod tests { }; let entry0 = LogEntry { - address: "b372018f3be9e171df0581136b59d2faf73a7d5d".into(), + address: H160::from_str("b372018f3be9e171df0581136b59d2faf73a7d5d").unwrap(), topics: vec![ - "ff74e91598aed6ae5d2fdcf8b24cd2c7be49a0808112a305069355b7160f23f9".into(), - "ff74e91598aed6ae5d2fdcf8b24cd2c7be49a0808112a305069355b7160f23fa".into(), - "ff74e91598aed6ae5d2fdcf8b24cd2c7be49a0808112a305069355b7160f23f9".into(), + H256::from_str("ff74e91598aed6ae5d2fdcf8b24cd2c7be49a0808112a305069355b7160f23f9") + .unwrap(), + H256::from_str("ff74e91598aed6ae5d2fdcf8b24cd2c7be49a0808112a305069355b7160f23fa") + .unwrap(), + H256::from_str("ff74e91598aed6ae5d2fdcf8b24cd2c7be49a0808112a305069355b7160f23f9") + .unwrap(), ], data: vec![], }; let entry1 = LogEntry { - address: "b372018f3be9e171df0581136b59d2faf73a7d5e".into(), + address: H160::from_str("b372018f3be9e171df0581136b59d2faf73a7d5e").unwrap(), topics: vec![ - "ff74e91598aed6ae5d2fdcf8b24cd2c7be49a0808112a305069355b7160f23f9".into(), - "ff74e91598aed6ae5d2fdcf8b24cd2c7be49a0808112a305069355b7160f23fa".into(), - "ff74e91598aed6ae5d2fdcf8b24cd2c7be49a0808112a305069355b7160f23f9".into(), + H256::from_str("ff74e91598aed6ae5d2fdcf8b24cd2c7be49a0808112a305069355b7160f23f9") + .unwrap(), + H256::from_str("ff74e91598aed6ae5d2fdcf8b24cd2c7be49a0808112a305069355b7160f23fa") + .unwrap(), + H256::from_str("ff74e91598aed6ae5d2fdcf8b24cd2c7be49a0808112a305069355b7160f23f9") + .unwrap(), ], data: vec![], }; let entry2 = LogEntry { - address: "b372018f3be9e171df0581136b59d2faf73a7d5d".into(), - topics: vec!["ff74e91598aed6ae5d2fdcf8b24cd2c7be49a0808112a305069355b7160f23f9".into()], + address: H160::from_str("b372018f3be9e171df0581136b59d2faf73a7d5d").unwrap(), + topics: vec![H256::from_str( + "ff74e91598aed6ae5d2fdcf8b24cd2c7be49a0808112a305069355b7160f23f9", + ) + .unwrap()], data: vec![], }; diff --git a/crates/ethcore/types/src/header.rs b/crates/ethcore/types/src/header.rs index f53412bec..88c68e835 100644 --- a/crates/ethcore/types/src/header.rs +++ b/crates/ethcore/types/src/header.rs @@ -19,7 +19,7 @@ use bytes::Bytes; use ethereum_types::{Address, Bloom, H256, U256}; use hash::{keccak, KECCAK_EMPTY_LIST_RLP, KECCAK_NULL_RLP}; -use heapsize::HeapSizeOf; +use parity_util_mem::MallocSizeOf; use rlp::{Decodable, DecoderError, Encodable, Rlp, RlpStream}; use BlockNumber; @@ -49,7 +49,7 @@ pub struct ExtendedHeader { /// which is non-specific. /// /// Doesn't do all that much on its own. -#[derive(Debug, Clone, Eq)] +#[derive(Debug, Clone, Eq, MallocSizeOf)] pub struct Header { /// Parent hash. parent_hash: H256, @@ -393,12 +393,6 @@ impl Encodable for Header { } } -impl HeapSizeOf for Header { - fn heap_size_of_children(&self) -> usize { - self.extra_data.heap_size_of_children() + self.seal.heap_size_of_children() - } -} - impl ExtendedHeader { /// Returns combined difficulty of all ancestors together with the difficulty of this header. pub fn total_score(&self) -> U256 { diff --git a/crates/ethcore/types/src/lib.rs b/crates/ethcore/types/src/lib.rs index 5c99c105b..2eafc66ee 100644 --- a/crates/ethcore/types/src/lib.rs +++ b/crates/ethcore/types/src/lib.rs @@ -35,10 +35,10 @@ #![warn(unused_extern_crates)] extern crate ethereum_types; -extern crate ethkey; -extern crate heapsize; extern crate keccak_hash as hash; extern crate parity_bytes as bytes; +extern crate parity_crypto as crypto; +extern crate parity_util_mem; extern crate rlp; extern crate serde_repr; extern crate unexpected; diff --git a/crates/ethcore/types/src/log_entry.rs b/crates/ethcore/types/src/log_entry.rs index 129e78a92..8c72df15b 100644 --- a/crates/ethcore/types/src/log_entry.rs +++ b/crates/ethcore/types/src/log_entry.rs @@ -18,13 +18,13 @@ use bytes::Bytes; use ethereum_types::{Address, Bloom, BloomInput, H256}; -use heapsize::HeapSizeOf; +use parity_util_mem::MallocSizeOf; use std::ops::Deref; use BlockNumber; /// A record of execution for a `LOG` operation. -#[derive(Default, Debug, Clone, PartialEq, Eq, RlpEncodable, RlpDecodable)] +#[derive(Default, Debug, Clone, PartialEq, Eq, RlpEncodable, RlpDecodable, MallocSizeOf)] pub struct LogEntry { /// The address of the contract executing at the point of the `LOG` operation. pub address: Address, @@ -34,21 +34,16 @@ pub struct LogEntry { pub data: Bytes, } -impl HeapSizeOf for LogEntry { - fn heap_size_of_children(&self) -> usize { - self.topics.heap_size_of_children() + self.data.heap_size_of_children() - } -} - impl LogEntry { /// Calculates the bloom of this log entry. pub fn bloom(&self) -> Bloom { - self.topics - .iter() - .fold(Bloom::from(BloomInput::Raw(&self.address)), |mut b, t| { - b.accrue(BloomInput::Raw(t)); + self.topics.iter().fold( + Bloom::from(BloomInput::Raw(self.address.as_bytes())), + |mut b, t| { + b.accrue(BloomInput::Raw(t.as_bytes())); b - }) + }, + ) } } diff --git a/crates/ethcore/types/src/receipt.rs b/crates/ethcore/types/src/receipt.rs index 787c8f25f..2026081a8 100644 --- a/crates/ethcore/types/src/receipt.rs +++ b/crates/ethcore/types/src/receipt.rs @@ -18,7 +18,7 @@ use super::transaction::TypedTxId; use ethereum_types::{Address, Bloom, H160, H256, U256}; -use heapsize::HeapSizeOf; +use parity_util_mem::MallocSizeOf; use rlp::{DecoderError, Rlp, RlpStream}; use std::ops::{Deref, DerefMut}; @@ -26,7 +26,7 @@ use log_entry::{LocalizedLogEntry, LogEntry}; use BlockNumber; /// Transaction outcome store in the receipt. -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq, MallocSizeOf)] pub enum TransactionOutcome { /// Status and state root are unknown under EIP-98 rules. Unknown, @@ -37,7 +37,7 @@ pub enum TransactionOutcome { } /// Information describing execution of a transaction. -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq, MallocSizeOf)] pub struct LegacyReceipt { /// The total gas used in the block following execution of the transaction. pub gas_used: U256, @@ -106,7 +106,7 @@ impl LegacyReceipt { } } -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq, MallocSizeOf)] pub enum TypedReceipt { Legacy(LegacyReceipt), AccessList(LegacyReceipt), @@ -231,12 +231,6 @@ impl DerefMut for TypedReceipt { } } -impl HeapSizeOf for TypedReceipt { - fn heap_size_of_children(&self) -> usize { - self.receipt().logs.heap_size_of_children() - } -} - /// Receipt with additional info. #[derive(Debug, Clone, PartialEq)] pub struct RichReceipt { @@ -302,7 +296,9 @@ pub struct LocalizedReceipt { #[cfg(test)] mod tests { use super::{LegacyReceipt, TransactionOutcome, TypedReceipt, TypedTxId}; + use ethereum_types::{H160, H256}; use log_entry::LogEntry; + use std::str::FromStr; #[test] fn test_no_state_root() { @@ -313,7 +309,7 @@ mod tests { TransactionOutcome::Unknown, 0x40cae.into(), vec![LogEntry { - address: "dcf421d093428b096ca501a7cd1a740855a7976f".into(), + address: H160::from_str("dcf421d093428b096ca501a7cd1a740855a7976f").unwrap(), topics: vec![], data: vec![0u8; 32], }], @@ -329,11 +325,14 @@ mod tests { TypedTxId::Legacy, LegacyReceipt::new( TransactionOutcome::StateRoot( - "2f697d671e9ae4ee24a43c4b0d7e15f1cb4ba6de1561120d43b9a4e8c4a8a6ee".into(), + H256::from_str( + "2f697d671e9ae4ee24a43c4b0d7e15f1cb4ba6de1561120d43b9a4e8c4a8a6ee", + ) + .unwrap(), ), 0x40cae.into(), vec![LogEntry { - address: "dcf421d093428b096ca501a7cd1a740855a7976f".into(), + address: H160::from_str("dcf421d093428b096ca501a7cd1a740855a7976f").unwrap(), topics: vec![], data: vec![0u8; 32], }], @@ -352,11 +351,14 @@ mod tests { TypedTxId::AccessList, LegacyReceipt::new( TransactionOutcome::StateRoot( - "2f697d671e9ae4ee24a43c4b0d7e15f1cb4ba6de1561120d43b9a4e8c4a8a6ee".into(), + H256::from_str( + "2f697d671e9ae4ee24a43c4b0d7e15f1cb4ba6de1561120d43b9a4e8c4a8a6ee", + ) + .unwrap(), ), 0x40cae.into(), vec![LogEntry { - address: "dcf421d093428b096ca501a7cd1a740855a7976f".into(), + address: H160::from_str("dcf421d093428b096ca501a7cd1a740855a7976f").unwrap(), topics: vec![], data: vec![0u8; 32], }], @@ -377,7 +379,7 @@ mod tests { TransactionOutcome::StatusCode(0), 0x40cae.into(), vec![LogEntry { - address: "dcf421d093428b096ca501a7cd1a740855a7976f".into(), + address: H160::from_str("dcf421d093428b096ca501a7cd1a740855a7976f").unwrap(), topics: vec![], data: vec![0u8; 32], }], diff --git a/crates/ethcore/types/src/transaction/error.rs b/crates/ethcore/types/src/transaction/error.rs index c4813eba3..aa927c55e 100644 --- a/crates/ethcore/types/src/transaction/error.rs +++ b/crates/ethcore/types/src/transaction/error.rs @@ -17,7 +17,6 @@ use std::{error, fmt}; use ethereum_types::U256; -use ethkey; use rlp; use unexpected::OutOfBounds; @@ -88,8 +87,8 @@ pub enum Error { TransactionTypeNotEnabled, } -impl From for Error { - fn from(err: ethkey::Error) -> Self { +impl From for Error { + fn from(err: crypto::publickey::Error) -> Self { Error::InvalidSignature(format!("{}", err)) } } diff --git a/crates/ethcore/types/src/transaction/transaction.rs b/crates/ethcore/types/src/transaction/transaction.rs index 892795a6a..55a10506d 100644 --- a/crates/ethcore/types/src/transaction/transaction.rs +++ b/crates/ethcore/types/src/transaction/transaction.rs @@ -16,10 +16,10 @@ //! Transaction data structure. -use ethereum_types::{Address, H160, H256, U256}; -use ethkey::{self, public_to_address, recover, Public, Secret, Signature}; +use crypto::publickey::{self, public_to_address, recover, Public, Secret, Signature}; +use ethereum_types::{Address, BigEndianHash, H160, H256, U256}; use hash::keccak; -use heapsize::HeapSizeOf; +use parity_util_mem::MallocSizeOf; use rlp::{self, DecoderError, Rlp, RlpStream}; use std::ops::Deref; @@ -43,7 +43,7 @@ pub const SYSTEM_ADDRESS: Address = H160([ ]); /// Transaction action type. -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq, MallocSizeOf)] pub enum Action { /// Create creates new contract. Create, @@ -124,7 +124,7 @@ pub mod signature { /// A set of information describing an externally-originating message call /// or contract creation operation. -#[derive(Default, Debug, Clone, PartialEq, Eq)] +#[derive(Default, Debug, Clone, PartialEq, Eq, MallocSizeOf)] pub struct Transaction { /// Nonce. pub nonce: U256, @@ -229,13 +229,7 @@ impl Transaction { } } -impl HeapSizeOf for Transaction { - fn heap_size_of_children(&self) -> usize { - self.data.heap_size_of_children() - } -} - -#[derive(Debug, Clone, Eq, PartialEq)] +#[derive(Debug, Clone, Eq, PartialEq, MallocSizeOf)] pub struct AccessListTx { pub transaction: Transaction, //optional access list @@ -308,7 +302,7 @@ impl AccessListTx { }), chain_id, signature, - 0.into(), + H256::zero(), ) .compute_hash()) } @@ -368,7 +362,7 @@ impl AccessListTx { } } -#[derive(Debug, Clone, Eq, PartialEq)] +#[derive(Debug, Clone, Eq, PartialEq, MallocSizeOf)] pub enum TypedTransaction { Legacy(Transaction), // old legacy RLP encoded transaction AccessList(AccessListTx), // EIP-2930 Transaction with a list of addresses and storage keys that the transaction plans to access. @@ -393,7 +387,7 @@ impl TypedTransaction { /// Signs the transaction as coming from `sender`. pub fn sign(self, secret: &Secret, chain_id: Option) -> SignedTransaction { - let sig = ::ethkey::sign(secret, &self.signature_hash(chain_id)) + let sig = publickey::sign(secret, &self.signature_hash(chain_id)) .expect("data is valid and context has signing capabilities; qed"); SignedTransaction::new(self.with_signature(sig, chain_id)) .expect("secret is valid so it's recoverable") @@ -409,7 +403,7 @@ impl TypedTransaction { s: sig.s().into(), standard_v: sig.v().into(), }, - hash: 0.into(), + hash: H256::zero(), } .compute_hash() } @@ -425,7 +419,7 @@ impl TypedTransaction { s: U256::one(), standard_v: 4, }, - hash: 0.into(), + hash: H256::zero(), } .compute_hash(), sender: from, @@ -447,7 +441,7 @@ impl TypedTransaction { s: U256::zero(), standard_v: 0, }, - hash: 0.into(), + hash: H256::zero(), } .compute_hash(), sender: UNSIGNED_SENDER, @@ -466,7 +460,7 @@ impl TypedTransaction { s: U256::one(), standard_v: 0, }, - hash: 0.into(), + hash: H256::zero(), } .compute_hash() } @@ -567,17 +561,8 @@ impl TypedTransaction { } } -impl HeapSizeOf for TypedTransaction { - fn heap_size_of_children(&self) -> usize { - match self { - TypedTransaction::Legacy(legacy) => legacy.heap_size_of_children(), - TypedTransaction::AccessList(oal) => oal.tx().heap_size_of_children(), - } - } -} - /// Components that constitute transaction signature -#[derive(Debug, Clone, Eq, PartialEq)] +#[derive(Debug, Clone, Eq, PartialEq, MallocSizeOf)] pub struct SignatureComponents { /// The V field of the signature; the LS bit described which half of the curve our point falls /// in. It can be 0 or 1. @@ -606,7 +591,7 @@ impl SignatureComponents { } /// Signed transaction information without verified signature. -#[derive(Debug, Clone, Eq, PartialEq)] +#[derive(Debug, Clone, Eq, PartialEq, MallocSizeOf)] pub struct UnverifiedTransaction { /// Plain Transaction. unsigned: TypedTransaction, @@ -618,12 +603,6 @@ pub struct UnverifiedTransaction { hash: H256, } -impl HeapSizeOf for UnverifiedTransaction { - fn heap_size_of_children(&self) -> usize { - self.unsigned.heap_size_of_children() - } -} - impl Deref for UnverifiedTransaction { type Target = TypedTransaction; @@ -704,17 +683,15 @@ impl UnverifiedTransaction { /// Construct a signature object from the sig. pub fn signature(&self) -> Signature { - Signature::from_rsv( - &self.signature.r.into(), - &self.signature.s.into(), - self.standard_v(), - ) + let r: H256 = BigEndianHash::from_uint(&self.signature.r); + let s: H256 = BigEndianHash::from_uint(&self.signature.s); + Signature::from_rsv(&r, &s, self.standard_v()) } /// Checks whether the signature has a low 's' value. - pub fn check_low_s(&self) -> Result<(), ethkey::Error> { + pub fn check_low_s(&self) -> Result<(), publickey::Error> { if !self.signature().is_low_s() { - Err(ethkey::Error::InvalidSignature.into()) + Err(publickey::Error::InvalidSignature.into()) } else { Ok(()) } @@ -726,7 +703,7 @@ impl UnverifiedTransaction { } /// Recovers the public key of the sender. - pub fn recover_public(&self) -> Result { + pub fn recover_public(&self) -> Result { Ok(recover( &self.signature(), &self.unsigned.signature_hash(self.chain_id()), @@ -740,7 +717,7 @@ impl UnverifiedTransaction { chain_id: Option, ) -> Result<(), error::Error> { if self.is_unsigned() { - return Err(ethkey::Error::InvalidSignature.into()); + return Err(publickey::Error::InvalidSignature.into()); } if check_low_s { self.check_low_s()?; @@ -755,19 +732,13 @@ impl UnverifiedTransaction { } /// A `UnverifiedTransaction` with successfully recovered `sender`. -#[derive(Debug, Clone, Eq, PartialEq)] +#[derive(Debug, Clone, Eq, PartialEq, MallocSizeOf)] pub struct SignedTransaction { transaction: UnverifiedTransaction, sender: Address, public: Option, } -impl HeapSizeOf for SignedTransaction { - fn heap_size_of_children(&self) -> usize { - self.transaction.heap_size_of_children() - } -} - impl Deref for SignedTransaction { type Target = UnverifiedTransaction; fn deref(&self) -> &Self::Target { @@ -783,9 +754,9 @@ impl From for UnverifiedTransaction { impl SignedTransaction { // t_nb 5.3.1 Try to verify transaction and recover sender. - pub fn new(transaction: UnverifiedTransaction) -> Result { + pub fn new(transaction: UnverifiedTransaction) -> Result { if transaction.is_unsigned() { - return Err(ethkey::Error::InvalidSignature); + return Err(publickey::Error::InvalidSignature); } let public = transaction.recover_public()?; let sender = public_to_address(&public); @@ -903,8 +874,9 @@ impl From for PendingTransaction { #[cfg(test)] mod tests { use super::*; - use ethereum_types::U256; + use ethereum_types::{H160, U256}; use hash::keccak; + use std::str::FromStr; #[test] fn sender_test() { @@ -915,14 +887,17 @@ mod tests { assert_eq!(t.tx().gas_price, U256::from(0x01u64)); assert_eq!(t.tx().nonce, U256::from(0x00u64)); if let Action::Call(ref to) = t.tx().action { - assert_eq!(*to, "095e7baea6a6c7c4c2dfeb977efac326af552d87".into()); + assert_eq!( + *to, + H160::from_str("095e7baea6a6c7c4c2dfeb977efac326af552d87").unwrap() + ); } else { panic!(); } assert_eq!(t.tx().value, U256::from(0x0au64)); assert_eq!( public_to_address(&t.recover_public().unwrap()), - "0f65fe9276bc9a24ae7083ae28e2660ef72df99e".into() + H160::from_str("0f65fe9276bc9a24ae7083ae28e2660ef72df99e").unwrap() ); assert_eq!(t.chain_id(), None); } @@ -943,9 +918,9 @@ mod tests { #[test] fn signing_eip155_zero_chainid() { - use ethkey::{Generator, Random}; + use self::publickey::{Generator, Random}; - let key = Random.generate().unwrap(); + let key = Random.generate(); let t = TypedTransaction::Legacy(Transaction { action: Action::Create, nonce: U256::from(42), @@ -956,7 +931,7 @@ mod tests { }); let hash = t.signature_hash(Some(0)); - let sig = ::ethkey::sign(&key.secret(), &hash).unwrap(); + let sig = publickey::sign(&key.secret(), &hash).unwrap(); let u = t.with_signature(sig, Some(0)); assert!(SignedTransaction::new(u).is_ok()); @@ -964,9 +939,9 @@ mod tests { #[test] fn signing() { - use ethkey::{Generator, Random}; + use self::publickey::{Generator, Random}; - let key = Random.generate().unwrap(); + let key = Random.generate(); let t = TypedTransaction::Legacy(Transaction { action: Action::Create, nonce: U256::from(42), @@ -990,12 +965,12 @@ mod tests { value: U256::from(1), data: b"Hello!".to_vec(), }) - .fake_sign(Address::from(0x69)); - assert_eq!(Address::from(0x69), t.sender()); + .fake_sign(Address::from_low_u64_be(0x69)); + assert_eq!(Address::from_low_u64_be(0x69), t.sender()); assert_eq!(t.chain_id(), None); let t = t.clone(); - assert_eq!(Address::from(0x69), t.sender()); + assert_eq!(Address::from_low_u64_be(0x69), t.sender()); assert_eq!(t.chain_id(), None); } @@ -1018,15 +993,15 @@ mod tests { let res = SignedTransaction::new(t.transaction); match res { - Err(ethkey::Error::InvalidSignature) => {} + Err(publickey::Error::InvalidSignature) => {} _ => panic!("null signature should be rejected"), } } #[test] fn should_recover_from_chain_specific_signing() { - use ethkey::{Generator, Random}; - let key = Random.generate().unwrap(); + use self::publickey::{Generator, Random}; + let key = Random.generate(); let t = TypedTransaction::Legacy(Transaction { action: Action::Create, nonce: U256::from(42), @@ -1042,8 +1017,8 @@ mod tests { #[test] fn should_encode_decode_access_list_tx() { - use ethkey::{Generator, Random}; - let key = Random.generate().unwrap(); + use self::publickey::{Generator, Random}; + let key = Random.generate(); let t = TypedTransaction::AccessList(AccessListTx::new( Transaction { action: Action::Create, @@ -1054,8 +1029,11 @@ mod tests { data: b"Hello!".to_vec(), }, vec![ - (H160::from(10), vec![H256::from(102), H256::from(103)]), - (H160::from(400), vec![]), + ( + H160::from_low_u64_be(10), + vec![H256::from_low_u64_be(102), H256::from_low_u64_be(103)], + ), + (H160::from_low_u64_be(400), vec![]), ], )) .sign(&key.secret(), Some(69)); @@ -1116,19 +1094,19 @@ mod tests { let signed = TypedTransaction::decode(&FromHex::from_hex(tx_data).unwrap()) .expect("decoding tx data failed"); let signed = SignedTransaction::new(signed).unwrap(); - assert_eq!(signed.sender(), address.into()); + assert_eq!(signed.sender(), H160::from_str(address).unwrap()); println!("chainid: {:?}", signed.chain_id()); }; - test_vector("f864808504a817c800825208943535353535353535353535353535353535353535808025a0044852b2a670ade5407e78fb2863c51de9fcb96542a07186fe3aeda6bb8a116da0044852b2a670ade5407e78fb2863c51de9fcb96542a07186fe3aeda6bb8a116d", "0xf0f6f18bca1b28cd68e4357452947e021241e9ce"); - test_vector("f864018504a817c80182a410943535353535353535353535353535353535353535018025a0489efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bcaa0489efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6", "0x23ef145a395ea3fa3deb533b8a9e1b4c6c25d112"); - test_vector("f864028504a817c80282f618943535353535353535353535353535353535353535088025a02d7c5bef027816a800da1736444fb58a807ef4c9603b7848673f7e3a68eb14a5a02d7c5bef027816a800da1736444fb58a807ef4c9603b7848673f7e3a68eb14a5", "0x2e485e0c23b4c3c542628a5f672eeab0ad4888be"); - test_vector("f865038504a817c803830148209435353535353535353535353535353535353535351b8025a02a80e1ef1d7842f27f2e6be0972bb708b9a135c38860dbe73c27c3486c34f4e0a02a80e1ef1d7842f27f2e6be0972bb708b9a135c38860dbe73c27c3486c34f4de", "0x82a88539669a3fd524d669e858935de5e5410cf0"); - test_vector("f865048504a817c80483019a28943535353535353535353535353535353535353535408025a013600b294191fc92924bb3ce4b969c1e7e2bab8f4c93c3fc6d0a51733df3c063a013600b294191fc92924bb3ce4b969c1e7e2bab8f4c93c3fc6d0a51733df3c060", "0xf9358f2538fd5ccfeb848b64a96b743fcc930554"); - test_vector("f865058504a817c8058301ec309435353535353535353535353535353535353535357d8025a04eebf77a833b30520287ddd9478ff51abbdffa30aa90a8d655dba0e8a79ce0c1a04eebf77a833b30520287ddd9478ff51abbdffa30aa90a8d655dba0e8a79ce0c1", "0xa8f7aba377317440bc5b26198a363ad22af1f3a4"); - test_vector("f866068504a817c80683023e3894353535353535353535353535353535353535353581d88025a06455bf8ea6e7463a1046a0b52804526e119b4bf5136279614e0b1e8e296a4e2fa06455bf8ea6e7463a1046a0b52804526e119b4bf5136279614e0b1e8e296a4e2d", "0xf1f571dc362a0e5b2696b8e775f8491d3e50de35"); - test_vector("f867078504a817c807830290409435353535353535353535353535353535353535358201578025a052f1a9b320cab38e5da8a8f97989383aab0a49165fc91c737310e4f7e9821021a052f1a9b320cab38e5da8a8f97989383aab0a49165fc91c737310e4f7e9821021", "0xd37922162ab7cea97c97a87551ed02c9a38b7332"); - test_vector("f867088504a817c8088302e2489435353535353535353535353535353535353535358202008025a064b1702d9298fee62dfeccc57d322a463ad55ca201256d01f62b45b2e1c21c12a064b1702d9298fee62dfeccc57d322a463ad55ca201256d01f62b45b2e1c21c10", "0x9bddad43f934d313c2b79ca28a432dd2b7281029"); - test_vector("f867098504a817c809830334509435353535353535353535353535353535353535358202d98025a052f8f61201b2b11a78d6e866abc9c3db2ae8631fa656bfe5cb53668255367afba052f8f61201b2b11a78d6e866abc9c3db2ae8631fa656bfe5cb53668255367afb", "0x3c24d7329e92f84f08556ceb6df1cdb0104ca49f"); + test_vector("f864808504a817c800825208943535353535353535353535353535353535353535808025a0044852b2a670ade5407e78fb2863c51de9fcb96542a07186fe3aeda6bb8a116da0044852b2a670ade5407e78fb2863c51de9fcb96542a07186fe3aeda6bb8a116d", "f0f6f18bca1b28cd68e4357452947e021241e9ce"); + test_vector("f864018504a817c80182a410943535353535353535353535353535353535353535018025a0489efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bcaa0489efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6", "23ef145a395ea3fa3deb533b8a9e1b4c6c25d112"); + test_vector("f864028504a817c80282f618943535353535353535353535353535353535353535088025a02d7c5bef027816a800da1736444fb58a807ef4c9603b7848673f7e3a68eb14a5a02d7c5bef027816a800da1736444fb58a807ef4c9603b7848673f7e3a68eb14a5", "2e485e0c23b4c3c542628a5f672eeab0ad4888be"); + test_vector("f865038504a817c803830148209435353535353535353535353535353535353535351b8025a02a80e1ef1d7842f27f2e6be0972bb708b9a135c38860dbe73c27c3486c34f4e0a02a80e1ef1d7842f27f2e6be0972bb708b9a135c38860dbe73c27c3486c34f4de", "82a88539669a3fd524d669e858935de5e5410cf0"); + test_vector("f865048504a817c80483019a28943535353535353535353535353535353535353535408025a013600b294191fc92924bb3ce4b969c1e7e2bab8f4c93c3fc6d0a51733df3c063a013600b294191fc92924bb3ce4b969c1e7e2bab8f4c93c3fc6d0a51733df3c060", "f9358f2538fd5ccfeb848b64a96b743fcc930554"); + test_vector("f865058504a817c8058301ec309435353535353535353535353535353535353535357d8025a04eebf77a833b30520287ddd9478ff51abbdffa30aa90a8d655dba0e8a79ce0c1a04eebf77a833b30520287ddd9478ff51abbdffa30aa90a8d655dba0e8a79ce0c1", "a8f7aba377317440bc5b26198a363ad22af1f3a4"); + test_vector("f866068504a817c80683023e3894353535353535353535353535353535353535353581d88025a06455bf8ea6e7463a1046a0b52804526e119b4bf5136279614e0b1e8e296a4e2fa06455bf8ea6e7463a1046a0b52804526e119b4bf5136279614e0b1e8e296a4e2d", "f1f571dc362a0e5b2696b8e775f8491d3e50de35"); + test_vector("f867078504a817c807830290409435353535353535353535353535353535353535358201578025a052f1a9b320cab38e5da8a8f97989383aab0a49165fc91c737310e4f7e9821021a052f1a9b320cab38e5da8a8f97989383aab0a49165fc91c737310e4f7e9821021", "d37922162ab7cea97c97a87551ed02c9a38b7332"); + test_vector("f867088504a817c8088302e2489435353535353535353535353535353535353535358202008025a064b1702d9298fee62dfeccc57d322a463ad55ca201256d01f62b45b2e1c21c12a064b1702d9298fee62dfeccc57d322a463ad55ca201256d01f62b45b2e1c21c10", "9bddad43f934d313c2b79ca28a432dd2b7281029"); + test_vector("f867098504a817c809830334509435353535353535353535353535353535353535358202d98025a052f8f61201b2b11a78d6e866abc9c3db2ae8631fa656bfe5cb53668255367afba052f8f61201b2b11a78d6e866abc9c3db2ae8631fa656bfe5cb53668255367afb", "3c24d7329e92f84f08556ceb6df1cdb0104ca49f"); } } diff --git a/crates/ethcore/types/src/views/block.rs b/crates/ethcore/types/src/views/block.rs index 7b3b3e44d..1d7fbf345 100644 --- a/crates/ethcore/types/src/views/block.rs +++ b/crates/ethcore/types/src/views/block.rs @@ -201,7 +201,9 @@ impl<'a> BlockView<'a> { #[cfg(test)] mod tests { use super::BlockView; + use ethereum_types::H256; use rustc_hex::FromHex; + use std::str::FromStr; #[test] fn test_block_view() { @@ -211,7 +213,8 @@ mod tests { let view = view!(BlockView, &rlp); assert_eq!( view.hash(), - "2c9747e804293bd3f1a986484343f23bc88fd5be75dfe9d5c2860aff61e6f259".into() + H256::from_str("2c9747e804293bd3f1a986484343f23bc88fd5be75dfe9d5c2860aff61e6f259") + .unwrap() ); assert_eq!(view.transactions_count(), 1); assert_eq!(view.uncles_count(), 0); diff --git a/crates/ethcore/types/src/views/header.rs b/crates/ethcore/types/src/views/header.rs index e29713e37..a5ecd8e2e 100644 --- a/crates/ethcore/types/src/views/header.rs +++ b/crates/ethcore/types/src/views/header.rs @@ -145,8 +145,9 @@ impl<'a> HeaderView<'a> { #[cfg(test)] mod tests { use super::HeaderView; - use ethereum_types::Bloom; + use ethereum_types::{Bloom, H160, H256}; use rustc_hex::FromHex; + use std::str::FromStr; #[test] fn test_header_view() { @@ -160,31 +161,37 @@ mod tests { let view = view!(HeaderView, &rlp); assert_eq!( view.hash(), - "2c9747e804293bd3f1a986484343f23bc88fd5be75dfe9d5c2860aff61e6f259".into() + H256::from_str("2c9747e804293bd3f1a986484343f23bc88fd5be75dfe9d5c2860aff61e6f259") + .unwrap() ); assert_eq!( view.parent_hash(), - "d405da4e66f1445d455195229624e133f5baafe72b5cf7b3c36c12c8146e98b7".into() + H256::from_str("d405da4e66f1445d455195229624e133f5baafe72b5cf7b3c36c12c8146e98b7") + .unwrap() ); assert_eq!( view.uncles_hash(), - "1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347".into() + H256::from_str("1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347") + .unwrap() ); assert_eq!( view.author(), - "8888f1f195afa192cfee860698584c030f4c9db1".into() + H160::from_str("8888f1f195afa192cfee860698584c030f4c9db1").unwrap() ); assert_eq!( view.state_root(), - "5fb2b4bfdef7b314451cb138a534d225c922fc0e5fbe25e451142732c3e25c25".into() + H256::from_str("5fb2b4bfdef7b314451cb138a534d225c922fc0e5fbe25e451142732c3e25c25") + .unwrap() ); assert_eq!( view.transactions_root(), - "88d2ec6b9860aae1a2c3b299f72b6a5d70d7f7ba4722c78f2c49ba96273c2158".into() + H256::from_str("88d2ec6b9860aae1a2c3b299f72b6a5d70d7f7ba4722c78f2c49ba96273c2158") + .unwrap() ); assert_eq!( view.receipts_root(), - "07c6fdfa8eea7e86b81f5b0fc0f78f90cc19f4aa60d323151e0cac660199e9a1".into() + H256::from_str("07c6fdfa8eea7e86b81f5b0fc0f78f90cc19f4aa60d323151e0cac660199e9a1") + .unwrap() ); assert_eq!(view.log_bloom(), Bloom::default()); assert_eq!(view.difficulty(), 0x020080.into()); diff --git a/crates/ethjson/Cargo.toml b/crates/ethjson/Cargo.toml index b86f34f1d..819db5dbf 100644 --- a/crates/ethjson/Cargo.toml +++ b/crates/ethjson/Cargo.toml @@ -6,8 +6,8 @@ authors = ["Parity Technologies "] [dependencies] common-types = { path = "../ethcore/types", features = ["test-helpers"] } -ethkey = { path = "../accounts/ethkey" } -ethereum-types = "0.4" +parity-crypto = { version = "0.6.2", features = [ "publickey" ] } +ethereum-types = "0.9.2" rustc-hex = "1.0" serde = "1.0" serde_json = "1.0" diff --git a/crates/ethjson/src/hash.rs b/crates/ethjson/src/hash.rs index fc98dc3c6..c0b7d834b 100644 --- a/crates/ethjson/src/hash.rs +++ b/crates/ethjson/src/hash.rs @@ -19,7 +19,6 @@ use ethereum_types::{ Bloom as Hash2048, H160 as Hash160, H256 as Hash256, H520 as Hash520, H64 as Hash64, }; -use rustc_hex::ToHex; use serde::{ de::{Error, Visitor}, Deserialize, Deserializer, Serialize, Serializer, @@ -63,8 +62,8 @@ macro_rules! impl_hash { E: Error, { let value = match value.len() { - 0 => $inner::from(0), - 2 if value == "0x" => $inner::from(0), + 0 => $inner::from_low_u64_be(0), + 2 if value == "0x" => $inner::from_low_u64_be(0), _ if value.starts_with("0x") => { $inner::from_str(&value[2..]).map_err(|e| { Error::custom( @@ -99,9 +98,7 @@ macro_rules! impl_hash { where S: Serializer, { - let mut hex = "0x".to_owned(); - hex.push_str(&self.0.to_hex()); - serializer.serialize_str(&hex) + serializer.serialize_str(&format!("{:#x}", self.0)) } } }; @@ -127,7 +124,7 @@ mod test { assert_eq!( deserialized, vec![ - H256(ethereum_types::H256::from(0)), + H256(ethereum_types::H256::zero()), H256( ethereum_types::H256::from_str( "5a39ed1020c04d4d84539975b893a4e7c53eab6c2965db8bc3468093a31bc5ae" @@ -141,8 +138,8 @@ mod test { #[test] fn hash_into() { assert_eq!( - ethereum_types::H256::from(0), - H256(ethereum_types::H256::from(0)).into() + ethereum_types::H256::zero(), + H256(ethereum_types::H256::zero()).into() ); } } diff --git a/crates/ethjson/src/lib.rs b/crates/ethjson/src/lib.rs index f5a6d5f83..910175dfb 100644 --- a/crates/ethjson/src/lib.rs +++ b/crates/ethjson/src/lib.rs @@ -16,7 +16,7 @@ extern crate common_types as types; extern crate ethereum_types; -extern crate ethkey; +extern crate parity_crypto as crypto; extern crate rustc_hex; extern crate serde; extern crate serde_json; diff --git a/crates/ethjson/src/spec/authority_round.rs b/crates/ethjson/src/spec/authority_round.rs index 6a76855d1..45132d7b7 100644 --- a/crates/ethjson/src/spec/authority_round.rs +++ b/crates/ethjson/src/spec/authority_round.rs @@ -77,6 +77,7 @@ mod tests { use hash::Address; use serde_json; use spec::{authority_round::AuthorityRound, validator_set::ValidatorSet}; + use std::str::FromStr; use uint::Uint; #[test] @@ -99,9 +100,9 @@ mod tests { assert_eq!(deserialized.params.step_duration, Uint(U256::from(0x02))); assert_eq!( deserialized.params.validators, - ValidatorSet::List(vec![Address(H160::from( - "0xc6d9d2cd449a754c494264e1809c50e34d64562b" - ))]) + ValidatorSet::List(vec![Address( + H160::from_str("c6d9d2cd449a754c494264e1809c50e34d64562b").unwrap() + )]) ); assert_eq!(deserialized.params.start_step, Some(Uint(U256::from(24)))); assert_eq!(deserialized.params.immediate_transitions, None); @@ -138,9 +139,9 @@ mod tests { assert_eq!(deserialized.params.step_duration, Uint(U256::from(0x02))); assert_eq!( deserialized.params.validators, - ValidatorSet::Contract(Address(H160::from( - "0xc6d9d2cd449a754c494264e1809c50e34d64562b" - ))) + ValidatorSet::Contract(Address( + H160::from_str("c6d9d2cd449a754c494264e1809c50e34d64562b").unwrap() + )) ); let mut rewards: BTreeMap = BTreeMap::new(); rewards.insert(Uint(U256::from(0)), Uint(U256::from(5000000))); diff --git a/crates/ethjson/src/spec/basic_authority.rs b/crates/ethjson/src/spec/basic_authority.rs index 0f0ebc179..d744407a5 100644 --- a/crates/ethjson/src/spec/basic_authority.rs +++ b/crates/ethjson/src/spec/basic_authority.rs @@ -44,6 +44,7 @@ mod tests { use hash::Address; use serde_json; use spec::{basic_authority::BasicAuthority, validator_set::ValidatorSet}; + use std::str::FromStr; use uint::Uint; #[test] @@ -60,9 +61,9 @@ mod tests { let deserialized: BasicAuthority = serde_json::from_str(s).unwrap(); assert_eq!(deserialized.params.duration_limit, Uint(U256::from(0x0d))); - let vs = ValidatorSet::List(vec![Address(H160::from( - "0xc6d9d2cd449a754c494264e1809c50e34d64562b", - ))]); + let vs = ValidatorSet::List(vec![Address( + H160::from_str("c6d9d2cd449a754c494264e1809c50e34d64562b").unwrap(), + )]); assert_eq!(deserialized.params.validators, vs); } } diff --git a/crates/ethjson/src/spec/ethash.rs b/crates/ethjson/src/spec/ethash.rs index 6d2ec0d40..b7e8c0907 100644 --- a/crates/ethjson/src/spec/ethash.rs +++ b/crates/ethjson/src/spec/ethash.rs @@ -109,6 +109,7 @@ mod tests { use hash::Address; use serde_json; use spec::ethash::{BlockReward, Ethash, EthashParams}; + use std::str::FromStr; use uint::Uint; #[test] @@ -168,30 +169,70 @@ mod tests { block_reward_contract_code: None, block_reward_contract_transition: None, dao_hardfork_transition: Some(Uint(U256::from(0x08))), - dao_hardfork_beneficiary: Some(Address(H160::from( - "0xabcabcabcabcabcabcabcabcabcabcabcabcabca" - ))), + dao_hardfork_beneficiary: Some(Address( + H160::from_str("abcabcabcabcabcabcabcabcabcabcabcabcabca").unwrap() + )), dao_hardfork_accounts: Some(vec![ - Address(H160::from("0x304a554a310c7e546dfe434669c62820b7d83490")), - Address(H160::from("0x914d1b8b43e92723e64fd0a06f5bdb8dd9b10c79")), - Address(H160::from("0xfe24cdd8648121a43a7c86d289be4dd2951ed49f")), - Address(H160::from("0x17802f43a0137c506ba92291391a8a8f207f487d")), - Address(H160::from("0xb136707642a4ea12fb4bae820f03d2562ebff487")), - Address(H160::from("0xdbe9b615a3ae8709af8b93336ce9b477e4ac0940")), - Address(H160::from("0xf14c14075d6c4ed84b86798af0956deef67365b5")), - Address(H160::from("0xca544e5c4687d109611d0f8f928b53a25af72448")), - Address(H160::from("0xaeeb8ff27288bdabc0fa5ebb731b6f409507516c")), - Address(H160::from("0xcbb9d3703e651b0d496cdefb8b92c25aeb2171f7")), - Address(H160::from("0xaccc230e8a6e5be9160b8cdf2864dd2a001c28b6")), - Address(H160::from("0x2b3455ec7fedf16e646268bf88846bd7a2319bb2")), - Address(H160::from("0x4613f3bca5c44ea06337a9e439fbc6d42e501d0a")), - Address(H160::from("0xd343b217de44030afaa275f54d31a9317c7f441e")), - Address(H160::from("0x84ef4b2357079cd7a7c69fd7a37cd0609a679106")), - Address(H160::from("0xda2fef9e4a3230988ff17df2165440f37e8b1708")), - Address(H160::from("0xf4c64518ea10f995918a454158c6b61407ea345c")), - Address(H160::from("0x7602b46df5390e432ef1c307d4f2c9ff6d65cc97")), - Address(H160::from("0xbb9bc244d798123fde783fcc1c72d3bb8c189413")), - Address(H160::from("0x807640a13483f8ac783c557fcdf27be11ea4ac7a")), + Address( + H160::from_str("304a554a310c7e546dfe434669c62820b7d83490").unwrap() + ), + Address( + H160::from_str("914d1b8b43e92723e64fd0a06f5bdb8dd9b10c79").unwrap() + ), + Address( + H160::from_str("fe24cdd8648121a43a7c86d289be4dd2951ed49f").unwrap() + ), + Address( + H160::from_str("17802f43a0137c506ba92291391a8a8f207f487d").unwrap() + ), + Address( + H160::from_str("b136707642a4ea12fb4bae820f03d2562ebff487").unwrap() + ), + Address( + H160::from_str("dbe9b615a3ae8709af8b93336ce9b477e4ac0940").unwrap() + ), + Address( + H160::from_str("f14c14075d6c4ed84b86798af0956deef67365b5").unwrap() + ), + Address( + H160::from_str("ca544e5c4687d109611d0f8f928b53a25af72448").unwrap() + ), + Address( + H160::from_str("aeeb8ff27288bdabc0fa5ebb731b6f409507516c").unwrap() + ), + Address( + H160::from_str("cbb9d3703e651b0d496cdefb8b92c25aeb2171f7").unwrap() + ), + Address( + H160::from_str("accc230e8a6e5be9160b8cdf2864dd2a001c28b6").unwrap() + ), + Address( + H160::from_str("2b3455ec7fedf16e646268bf88846bd7a2319bb2").unwrap() + ), + Address( + H160::from_str("4613f3bca5c44ea06337a9e439fbc6d42e501d0a").unwrap() + ), + Address( + H160::from_str("d343b217de44030afaa275f54d31a9317c7f441e").unwrap() + ), + Address( + H160::from_str("84ef4b2357079cd7a7c69fd7a37cd0609a679106").unwrap() + ), + Address( + H160::from_str("da2fef9e4a3230988ff17df2165440f37e8b1708").unwrap() + ), + Address( + H160::from_str("f4c64518ea10f995918a454158c6b61407ea345c").unwrap() + ), + Address( + H160::from_str("7602b46df5390e432ef1c307d4f2c9ff6d65cc97").unwrap() + ), + Address( + H160::from_str("bb9bc244d798123fde783fcc1c72d3bb8c189413").unwrap() + ), + Address( + H160::from_str("807640a13483f8ac783c557fcdf27be11ea4ac7a").unwrap() + ), ]), difficulty_hardfork_transition: Some(Uint(U256::from(0x59d9))), difficulty_hardfork_bound_divisor: Some(Uint(U256::from(0x0200))), diff --git a/crates/ethjson/src/spec/genesis.rs b/crates/ethjson/src/spec/genesis.rs index 0cbcd6879..38445f123 100644 --- a/crates/ethjson/src/spec/genesis.rs +++ b/crates/ethjson/src/spec/genesis.rs @@ -83,29 +83,38 @@ mod tests { deserialized, Genesis { seal: Seal::Ethereum(Ethereum { - nonce: H64(Eth64::from("0x00006d6f7264656e")), - mix_hash: H256(Eth256::from( - "0x0000000000000000000000000000000000000000000000000000000000000000" - )) + nonce: H64(Eth64::from_str("00006d6f7264656e").unwrap()), + mix_hash: H256( + Eth256::from_str( + "0000000000000000000000000000000000000000000000000000000000000000" + ) + .unwrap() + ) }), difficulty: Uint(U256::from(0x400000000u64)), - author: Some(Address(H160::from( - "0x1000000000000000000000000000000000000001" - ))), + author: Some(Address( + H160::from_str("1000000000000000000000000000000000000001").unwrap() + )), timestamp: Some(Uint(U256::from(0x07))), - parent_hash: Some(H256(Eth256::from( - "0x9000000000000000000000000000000000000000000000000000000000000000" - ))), + parent_hash: Some(H256( + Eth256::from_str( + "9000000000000000000000000000000000000000000000000000000000000000" + ) + .unwrap() + )), gas_limit: Uint(U256::from(0x1388)), transactions_root: None, receipts_root: None, - state_root: Some(H256(Eth256::from( - "0xd7f8974fb5ac78d9ac099b9ad5018bedc2ce0a72dad1827a1709da30580f0544" - ))), + state_root: Some(H256( + Eth256::from_str( + "d7f8974fb5ac78d9ac099b9ad5018bedc2ce0a72dad1827a1709da30580f0544" + ) + .unwrap() + )), gas_used: None, extra_data: Some( Bytes::from_str( - "0x11bbe8db4e347b4e8c937c1c8370e4b5ed33adb3db69cbdb7a38e1e50b1b82fa" + "11bbe8db4e347b4e8c937c1c8370e4b5ed33adb3db69cbdb7a38e1e50b1b82fa" ) .unwrap() ), diff --git a/crates/ethjson/src/spec/seal.rs b/crates/ethjson/src/spec/seal.rs index 5bf894fdf..a53a1f07d 100644 --- a/crates/ethjson/src/spec/seal.rs +++ b/crates/ethjson/src/spec/seal.rs @@ -75,6 +75,7 @@ mod tests { use hash::*; use serde_json; use spec::{AuthorityRoundSeal, Ethereum, Seal, TendermintSeal}; + use std::str::FromStr; use uint::Uint; #[test] @@ -108,10 +109,13 @@ mod tests { assert_eq!( deserialized[0], Seal::Ethereum(Ethereum { - nonce: H64(Eth64::from("0x0000000000000042")), - mix_hash: H256(Eth256::from( - "0x1000000000000000000000000000000000000000000000000000000000000001" - )) + nonce: H64(Eth64::from_str("0000000000000042").unwrap()), + mix_hash: H256( + Eth256::from_str( + "1000000000000000000000000000000000000000000000000000000000000001" + ) + .unwrap() + ) }) ); @@ -128,14 +132,14 @@ mod tests { // [2] assert_eq!(deserialized[2], Seal::AuthorityRound(AuthorityRoundSeal { step: Uint(U256::from(0x0)), - signature: H520(Eth520::from("0x2000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002")) + signature: H520(Eth520::from_str("2000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002").unwrap()) })); // [3] assert_eq!(deserialized[3], Seal::Tendermint(TendermintSeal { round: Uint(U256::from(0x3)), - proposal: H520(Eth520::from("0x3000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003")), - precommits: vec![H520(Eth520::from("0x4000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004"))] + proposal: H520(Eth520::from_str("3000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003").unwrap()), + precommits: vec![H520(Eth520::from_str("4000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004").unwrap())] })); } } diff --git a/crates/ethjson/src/spec/validator_set.rs b/crates/ethjson/src/spec/validator_set.rs index 17c75162c..e41905082 100644 --- a/crates/ethjson/src/spec/validator_set.rs +++ b/crates/ethjson/src/spec/validator_set.rs @@ -41,6 +41,7 @@ mod tests { use hash::Address; use serde_json; use spec::validator_set::ValidatorSet; + use std::str::FromStr; use uint::Uint; #[test] @@ -64,21 +65,21 @@ mod tests { assert_eq!( deserialized[0], - ValidatorSet::List(vec![Address(H160::from( - "0xc6d9d2cd449a754c494264e1809c50e34d64562b" - ))]) + ValidatorSet::List(vec![Address( + H160::from_str("c6d9d2cd449a754c494264e1809c50e34d64562b").unwrap() + )]) ); assert_eq!( deserialized[1], - ValidatorSet::SafeContract(Address(H160::from( - "0xc6d9d2cd449a754c494264e1809c50e34d64562b" - ))) + ValidatorSet::SafeContract(Address( + H160::from_str("c6d9d2cd449a754c494264e1809c50e34d64562b").unwrap() + )) ); assert_eq!( deserialized[2], - ValidatorSet::Contract(Address(H160::from( - "0xc6d9d2cd449a754c494264e1809c50e34d64562b" - ))) + ValidatorSet::Contract(Address( + H160::from_str("c6d9d2cd449a754c494264e1809c50e34d64562b").unwrap() + )) ); match deserialized[3] { ValidatorSet::Multi(ref map) => { diff --git a/crates/ethjson/src/state/test.rs b/crates/ethjson/src/state/test.rs index 4411ff586..cc76fa101 100644 --- a/crates/ethjson/src/state/test.rs +++ b/crates/ethjson/src/state/test.rs @@ -17,7 +17,7 @@ //! General test deserialization. use bytes::Bytes; -use ethkey::Secret; +use crypto::publickey::Secret; use hash::{Address, H256}; use maybe::MaybeEmpty; use serde_json::{self, Error}; @@ -100,7 +100,10 @@ fn sign_with_secret(tx: TypedTransaction, secret: Option) -> SignedTrans impl MultiTransaction { /// Build transaction with given indexes. pub fn select(&self, indexes: &PostStateIndexes) -> SignedTransaction { - let secret = self.secret.clone().map(|s| Secret::from(s.0)); + let secret = self + .secret + .clone() + .map(|s| Secret::import_key(s.0.as_bytes()).expect("Expect signature to be valid")); let to: Option
= self.to.clone().into(); let transaction = Transaction { nonce: self.nonce.clone().into(), diff --git a/crates/ethjson/src/uint.rs b/crates/ethjson/src/uint.rs index 0df6131d6..fdcf4931a 100644 --- a/crates/ethjson/src/uint.rs +++ b/crates/ethjson/src/uint.rs @@ -35,19 +35,18 @@ impl Into for Uint { impl Into for Uint { fn into(self) -> u64 { - u64::from(self.0) + self.0.low_u64() } } impl Into for Uint { fn into(self) -> usize { - // TODO: clean it after util conversions refactored. - u64::from(self.0) as usize + self.0.low_u64() as usize } } impl Into for Uint { fn into(self) -> u8 { - u64::from(self.0) as u8 + self.0.low_u64() as u8 } } diff --git a/crates/net/network-devp2p/Cargo.toml b/crates/net/network-devp2p/Cargo.toml index 2b3873945..3db0434e3 100644 --- a/crates/net/network-devp2p/Cargo.toml +++ b/crates/net/network-devp2p/Cargo.toml @@ -10,7 +10,7 @@ authors = ["Parity Technologies "] log = "0.4" mio = "0.6.8" bytes = "0.4" -rand = "0.4" +rand = "0.7.3" tiny-keccak = "1.4" rust-crypto = "0.2.34" slab = "0.2" @@ -21,14 +21,14 @@ ansi_term = "0.10" rustc-hex = "1.0" ethcore-io = { path = "../../runtime/io", features = ["mio"] } parity-bytes = "0.1" -parity-crypto = "0.3.0" +parity-crypto = { version = "0.6.2", features = [ "publickey" ] } ethcore-network = { path = "../network" } -ethereum-types = "0.4" +ethereum-types = "0.9.2" ethkey = { path = "../../../crates/accounts/ethkey" } -rlp = { version = "0.3.0", features = ["ethereum"] } +rlp = { version = "0.4.6" } parity-path = "0.1" ipnetwork = "0.12.6" -keccak-hash = "0.1" +keccak-hash = "0.5.0" parity-snappy = "0.1" serde = "1.0" serde_json = "1.0" diff --git a/crates/net/network-devp2p/src/connection.rs b/crates/net/network-devp2p/src/connection.rs index 40dbd0487..16f22b77e 100644 --- a/crates/net/network-devp2p/src/connection.rs +++ b/crates/net/network-devp2p/src/connection.rs @@ -15,8 +15,11 @@ // along with OpenEthereum. If not, see . use bytes::{Buf, BufMut}; +use crypto::{ + aes::{AesCtr256, AesEcb256}, + publickey::Secret, +}; use ethereum_types::{H128, H256, H512}; -use ethkey::crypto; use handshake::Handshake; use hash::{keccak, write_keccak}; use io::{IoContext, StreamToken}; @@ -27,7 +30,6 @@ use mio::{ }; use network::{Error, ErrorKind}; use parity_bytes::*; -use rcrypto::{aessafe::*, blockmodes::*, buffer::*, symmetriccipher::*}; use rlp::{Rlp, RlpStream}; use std::{ collections::VecDeque, @@ -320,11 +322,11 @@ pub struct EncryptedConnection { /// Underlying tcp connection pub connection: Connection, /// Egress data encryptor - encoder: CtrMode, + encoder: AesCtr256, /// Ingress data decryptor - decoder: CtrMode, + decoder: AesCtr256, /// Ingress data decryptor - mac_encoder: EcbEncryptor>, + mac_encoder_key: Secret, /// MAC for egress data egress_mac: Keccak, /// MAC for ingress data @@ -337,36 +339,46 @@ pub struct EncryptedConnection { payload_len: usize, } +const NULL_IV: [u8; 16] = [0; 16]; impl EncryptedConnection { /// Create an encrypted connection out of the handshake. pub fn new(handshake: &mut Handshake) -> Result { - let shared = crypto::ecdh::agree(handshake.ecdhe.secret(), &handshake.remote_ephemeral)?; - let mut nonce_material = H512::new(); + let shared = parity_crypto::publickey::ecdh::agree( + handshake.ecdhe.secret(), + &handshake.remote_ephemeral, + )?; + let mut nonce_material = H512::default(); if handshake.originated { - handshake.remote_nonce.copy_to(&mut nonce_material[0..32]); - handshake.nonce.copy_to(&mut nonce_material[32..64]); + (&mut nonce_material[0..32]).copy_from_slice(handshake.remote_nonce.as_bytes()); + (&mut nonce_material[32..64]).copy_from_slice(handshake.nonce.as_bytes()); } else { - handshake.nonce.copy_to(&mut nonce_material[0..32]); - handshake.remote_nonce.copy_to(&mut nonce_material[32..64]); + (&mut nonce_material[0..32]).copy_from_slice(handshake.nonce.as_bytes()); + (&mut nonce_material[32..64]).copy_from_slice(handshake.remote_nonce.as_bytes()); } - let mut key_material = H512::new(); - shared.copy_to(&mut key_material[0..32]); + let mut key_material = H512::default(); + (&mut key_material[0..32]).copy_from_slice(shared.as_bytes()); write_keccak(&nonce_material, &mut key_material[32..64]); - keccak(&key_material).copy_to(&mut key_material[32..64]); - keccak(&key_material).copy_to(&mut key_material[32..64]); + let key_material_keccak = keccak(&key_material); + (&mut key_material[32..64]).copy_from_slice(key_material_keccak.as_bytes()); + let key_material_keccak = keccak(&key_material); + (&mut key_material[32..64]).copy_from_slice(key_material_keccak.as_bytes()); - let iv = vec![0u8; 16]; - let encoder = CtrMode::new(AesSafe256Encryptor::new(&key_material[32..64]), iv); - let iv = vec![0u8; 16]; - let decoder = CtrMode::new(AesSafe256Encryptor::new(&key_material[32..64]), iv); + // Using a 0 IV with CTR is fine as long as the same IV is never reused with the same key. + // This is the case here: ecdh creates a new secret which will be the symmetric key used + // only for this session the 0 IV is only use once with this secret, so we are in the case + // of same IV use for different key. + let encoder = AesCtr256::new(&key_material[32..64], &NULL_IV)?; + let decoder = AesCtr256::new(&key_material[32..64], &NULL_IV)?; - keccak(&key_material).copy_to(&mut key_material[32..64]); - let mac_encoder = - EcbEncryptor::new(AesSafe256Encryptor::new(&key_material[32..64]), NoPadding); + let key_material_keccak = keccak(&key_material); + (&mut key_material[32..64]).copy_from_slice(key_material_keccak.as_bytes()); + + let mac_encoder_key: Secret = Secret::copy_from_slice(&key_material[32..64]) + .expect("can create Secret from 32 bytes; qed"); let mut egress_mac = Keccak::new_keccak256(); let mut mac_material = H256::from_slice(&key_material[32..64]) ^ handshake.remote_nonce; - egress_mac.update(&mac_material); + egress_mac.update(mac_material.as_bytes()); egress_mac.update(if handshake.originated { &handshake.auth_cipher } else { @@ -375,7 +387,7 @@ impl EncryptedConnection { let mut ingress_mac = Keccak::new_keccak256(); mac_material = H256::from_slice(&key_material[32..64]) ^ handshake.nonce; - ingress_mac.update(&mac_material); + ingress_mac.update(mac_material.as_bytes()); ingress_mac.update(if handshake.originated { &handshake.ack_cipher } else { @@ -388,7 +400,7 @@ impl EncryptedConnection { connection, encoder, decoder, - mac_encoder, + mac_encoder_key, egress_mac, ingress_mac, read_state: EncryptedConnectionState::Header, @@ -408,86 +420,68 @@ impl EncryptedConnection { where Message: Send + Clone + Sync + 'static, { + const HEADER_LEN: usize = 16; let mut header = RlpStream::new(); let len = payload.len(); if len > MAX_PAYLOAD_SIZE { bail!(ErrorKind::OversizedPacket); } + header.append_raw(&[(len >> 16) as u8, (len >> 8) as u8, len as u8], 1); header.append_raw(&[0xc2u8, 0x80u8, 0x80u8], 1); - //TODO: get rid of vectors here - let mut header = header.out(); - let padding = (16 - (payload.len() % 16)) % 16; - header.resize(16, 0u8); + let padding = (16 - (len % 16)) % 16; - let mut packet = vec![0u8; 32 + payload.len() + padding + 16]; - self.encoder - .encrypt( - &mut RefReadBuffer::new(&header), - &mut RefWriteBuffer::new(&mut packet), - false, - ) - .expect("Invalid length or padding"); + let mut packet = vec![0u8; 16 + 16 + len + padding + 16]; + let mut header = header.out(); + header.resize(HEADER_LEN, 0u8); + &mut packet[..HEADER_LEN].copy_from_slice(&mut header); + self.encoder.encrypt(&mut packet[..HEADER_LEN])?; EncryptedConnection::update_mac( &mut self.egress_mac, - &mut self.mac_encoder, - &packet[0..16], - ); - self.egress_mac.clone().finalize(&mut packet[16..32]); - self.encoder - .encrypt( - &mut RefReadBuffer::new(payload), - &mut RefWriteBuffer::new(&mut packet[32..(32 + len)]), - padding == 0, - ) - .expect("Invalid length or padding"); + &self.mac_encoder_key, + &packet[..HEADER_LEN], + )?; + self.egress_mac + .clone() + .finalize(&mut packet[HEADER_LEN..32]); + &mut packet[32..32 + len].copy_from_slice(payload); + self.encoder.encrypt(&mut packet[32..32 + len])?; if padding != 0 { - let pad = [0u8; 16]; self.encoder - .encrypt( - &mut RefReadBuffer::new(&pad[0..padding]), - &mut RefWriteBuffer::new(&mut packet[(32 + len)..(32 + len + padding)]), - true, - ) - .expect("Invalid length or padding"); + .encrypt(&mut packet[(32 + len)..(32 + len + padding)])?; } self.egress_mac.update(&packet[32..(32 + len + padding)]); - EncryptedConnection::update_mac(&mut self.egress_mac, &mut self.mac_encoder, &[0u8; 0]); + EncryptedConnection::update_mac(&mut self.egress_mac, &self.mac_encoder_key, &[0u8; 0])?; self.egress_mac .clone() .finalize(&mut packet[(32 + len + padding)..]); self.connection.send(io, packet); + Ok(()) } /// Decrypt and authenticate an incoming packet header. Prepare for receiving payload. - fn read_header(&mut self, header: &[u8]) -> Result<(), Error> { + fn read_header(&mut self, mut header: Bytes) -> Result<(), Error> { if header.len() != ENCRYPTED_HEADER_LEN { return Err(ErrorKind::Auth.into()); } EncryptedConnection::update_mac( &mut self.ingress_mac, - &mut self.mac_encoder, + &self.mac_encoder_key, &header[0..16], - ); - let mac = &header[16..]; - let mut expected = H256::new(); - self.ingress_mac.clone().finalize(&mut expected); - if mac != &expected[0..16] { - return Err(ErrorKind::Auth.into()); + )?; + { + let mac = &header[16..]; + let mut expected = H256::zero(); + self.ingress_mac.clone().finalize(expected.as_bytes_mut()); + if mac != &expected[0..16] { + return Err(ErrorKind::Auth.into()); + } } + self.decoder.decrypt(&mut header[..16])?; - let mut hdec = H128::new(); - self.decoder - .decrypt( - &mut RefReadBuffer::new(&header[0..16]), - &mut RefWriteBuffer::new(&mut hdec), - false, - ) - .expect("Invalid length or padding"); - - let length = ((((hdec[0] as u32) << 8) + (hdec[1] as u32)) << 8) + (hdec[2] as u32); - let header_rlp = Rlp::new(&hdec[3..6]); + let length = ((((header[0] as u32) << 8) + (header[1] as u32)) << 8) + (header[2] as u32); + let header_rlp = Rlp::new(&header[3..6]); let protocol_id = header_rlp.val_at::(0)?; self.payload_len = length as usize; @@ -501,60 +495,40 @@ impl EncryptedConnection { } /// Decrypt and authenticate packet payload. - fn read_payload(&mut self, payload: &[u8]) -> Result { + fn read_payload(&mut self, mut payload: Bytes) -> Result { let padding = (16 - (self.payload_len % 16)) % 16; let full_length = self.payload_len + padding + 16; if payload.len() != full_length { return Err(ErrorKind::Auth.into()); } self.ingress_mac.update(&payload[0..payload.len() - 16]); - EncryptedConnection::update_mac(&mut self.ingress_mac, &mut self.mac_encoder, &[0u8; 0]); - let mac = &payload[(payload.len() - 16)..]; - let mut expected = H128::new(); - self.ingress_mac.clone().finalize(&mut expected); - if mac != &expected[..] { - return Err(ErrorKind::Auth.into()); - } + EncryptedConnection::update_mac(&mut self.ingress_mac, &self.mac_encoder_key, &[0u8; 0])?; - let mut packet = vec![0u8; self.payload_len]; + { + let mac = &payload[(payload.len() - 16)..]; + let mut expected = H128::default(); + self.ingress_mac.clone().finalize(expected.as_bytes_mut()); + if mac != &expected[..] { + return Err(ErrorKind::Auth.into()); + } + } self.decoder - .decrypt( - &mut RefReadBuffer::new(&payload[0..self.payload_len]), - &mut RefWriteBuffer::new(&mut packet), - false, - ) - .expect("Invalid length or padding"); - let mut pad_buf = [0u8; 16]; - self.decoder - .decrypt( - &mut RefReadBuffer::new(&payload[self.payload_len..(payload.len() - 16)]), - &mut RefWriteBuffer::new(&mut pad_buf), - false, - ) - .expect("Invalid length or padding"); + .decrypt(&mut payload[..self.payload_len + padding])?; + payload.truncate(self.payload_len); Ok(Packet { protocol: self.protocol_id, - data: packet, + data: payload, }) } /// Update MAC after reading or writing any data. - fn update_mac( - mac: &mut Keccak, - mac_encoder: &mut EcbEncryptor>, - seed: &[u8], - ) { - let mut prev = H128::new(); - mac.clone().finalize(&mut prev); - let mut enc = H128::new(); - mac_encoder - .encrypt( - &mut RefReadBuffer::new(&prev), - &mut RefWriteBuffer::new(&mut enc), - true, - ) - .expect("Error updating MAC"); - mac_encoder.reset(); + fn update_mac(mac: &mut Keccak, mac_encoder_key: &Secret, seed: &[u8]) -> Result<(), Error> { + let mut prev = H128::default(); + mac.clone().finalize(prev.as_bytes_mut()); + let mut enc = H128::default(); + &mut enc[..].copy_from_slice(prev.as_bytes()); + let mac_encoder = AesEcb256::new(mac_encoder_key.as_bytes())?; + mac_encoder.encrypt(enc.as_bytes_mut())?; enc = enc ^ if seed.is_empty() { @@ -562,7 +536,8 @@ impl EncryptedConnection { } else { H128::from_slice(seed) }; - mac.update(&enc); + mac.update(enc.as_bytes()); + Ok(()) } /// Readable IO handler. Tracker receive status and returns decoded packet if available. @@ -573,7 +548,7 @@ impl EncryptedConnection { io.clear_timer(self.connection.token)?; if let EncryptedConnectionState::Header = self.read_state { if let Some(data) = self.connection.readable()? { - self.read_header(&data)?; + self.read_header(data)?; io.register_timer(self.connection.token, RECEIVE_PAYLOAD)?; } }; @@ -582,7 +557,7 @@ impl EncryptedConnection { Some(data) => { self.read_state = EncryptedConnectionState::Header; self.connection.expect(ENCRYPTED_HEADER_LEN); - Ok(Some(self.read_payload(&data)?)) + Ok(Some(self.read_payload(data)?)) } None => Ok(None), } @@ -601,41 +576,6 @@ impl EncryptedConnection { } } -#[test] -pub fn test_encryption() { - use ethereum_types::{H128, H256}; - use std::str::FromStr; - let key = - H256::from_str("2212767d793a7a3d66f869ae324dd11bd17044b82c9f463b8a541a4d089efec5").unwrap(); - let before = H128::from_str("12532abaec065082a3cf1da7d0136f15").unwrap(); - let before2 = H128::from_str("7e99f682356fdfbc6b67a9562787b18a").unwrap(); - let after = H128::from_str("89464c6b04e7c99e555c81d3f7266a05").unwrap(); - let after2 = H128::from_str("85c070030589ef9c7a2879b3a8489316").unwrap(); - - let mut got = H128::new(); - - let mut encoder = EcbEncryptor::new(AesSafe256Encryptor::new(&key), NoPadding); - encoder - .encrypt( - &mut RefReadBuffer::new(&before), - &mut RefWriteBuffer::new(&mut got), - true, - ) - .unwrap(); - encoder.reset(); - assert_eq!(got, after); - got = H128::new(); - encoder - .encrypt( - &mut RefReadBuffer::new(&before2), - &mut RefWriteBuffer::new(&mut got), - true, - ) - .unwrap(); - encoder.reset(); - assert_eq!(got, after2); -} - #[cfg(test)] mod tests { use std::{ @@ -794,6 +734,32 @@ mod tests { IoContext::new(IoChannel::disconnected(), 0) } + #[test] + pub fn test_encryption() { + use ethereum_types::{H128, H256}; + use std::str::FromStr; + let key = + H256::from_str("2212767d793a7a3d66f869ae324dd11bd17044b82c9f463b8a541a4d089efec5") + .unwrap(); + let before = H128::from_str("12532abaec065082a3cf1da7d0136f15").unwrap(); + let before2 = H128::from_str("7e99f682356fdfbc6b67a9562787b18a").unwrap(); + let after = H128::from_str("89464c6b04e7c99e555c81d3f7266a05").unwrap(); + let after2 = H128::from_str("85c070030589ef9c7a2879b3a8489316").unwrap(); + + let mut got = H128::default(); + + let encoder = AesEcb256::new(key.as_bytes()).unwrap(); + got.as_bytes_mut().copy_from_slice(before.as_bytes()); + encoder.encrypt(got.as_bytes_mut()).unwrap(); + assert_eq!(got, after); + + let encoder = AesEcb256::new(key.as_bytes()).unwrap(); + got = H128::default(); + got.as_bytes_mut().copy_from_slice(&before2.as_bytes()); + encoder.encrypt(got.as_bytes_mut()).unwrap(); + assert_eq!(got, after2); + } + #[test] fn connection_expect() { let mut connection = TestConnection::new(); diff --git a/crates/net/network-devp2p/src/discovery.rs b/crates/net/network-devp2p/src/discovery.rs index 72f785a42..794e51f32 100644 --- a/crates/net/network-devp2p/src/discovery.rs +++ b/crates/net/network-devp2p/src/discovery.rs @@ -14,8 +14,8 @@ // You should have received a copy of the GNU General Public License // along with OpenEthereum. If not, see . +use crypto::publickey::{recover, sign, KeyPair, Secret}; use ethereum_types::{H256, H520}; -use ethkey::{recover, sign, KeyPair, Secret}; use hash::keccak; use lru_cache::LruCache; use network::{Error, ErrorKind, IpFilter}; @@ -199,7 +199,7 @@ impl<'a> Discovery<'a> { public_endpoint: public, discovery_initiated: false, discovery_round: None, - discovery_id: NodeId::new(), + discovery_id: NodeId::default(), discovery_nodes: HashSet::new(), node_buckets: (0..ADDRESS_BITS).map(|_| NodeBucket::new()).collect(), other_observed_nodes: LruCache::new(OBSERVED_NODES_MAX_SIZE), @@ -450,7 +450,7 @@ impl<'a> Discovery<'a> { payload: &[u8], ) -> Result { let packet = assemble_packet(packet_id, payload, &self.secret)?; - let hash = H256::from(&packet[0..32]); + let hash = H256::from_slice(&packet[0..32]); self.send_to(packet, address.clone()); Ok(hash) } @@ -531,7 +531,7 @@ impl<'a> Discovery<'a> { let packet_id = signed[0]; let rlp = Rlp::new(&signed[1..]); match packet_id { - PACKET_PING => self.on_ping(&rlp, &node_id, &from, &hash_signed), + PACKET_PING => self.on_ping(&rlp, &node_id, &from, hash_signed.as_bytes()), PACKET_PONG => self.on_pong(&rlp, &node_id, &from), PACKET_FIND_NODE => self.on_find_node(&rlp, &node_id, &from), PACKET_NEIGHBOURS => self.on_neighbours(&rlp, &node_id, &from), @@ -960,7 +960,7 @@ fn assemble_packet(packet_id: u8, bytes: &[u8], secret: &Secret) -> Result. use connection::Connection; +use crypto::publickey::{ecdh, ecies, recover, sign, Generator, KeyPair, Public, Random, Secret}; use ethereum_types::{H256, H520}; -use ethkey::{ - crypto::{ecdh, ecies}, - recover, sign, Generator, KeyPair, Public, Random, Secret, -}; use host::HostInfo; use io::{IoContext, StreamToken}; use mio::tcp::*; @@ -91,15 +88,15 @@ impl Handshake { id: if let Some(id) = id { *id } else { - NodeId::new() + NodeId::default() }, connection: Connection::new(token, socket), originated: false, state: HandshakeState::New, - ecdhe: Random.generate()?, + ecdhe: Random.generate(), nonce: *nonce, - remote_ephemeral: Public::new(), - remote_nonce: H256::new(), + remote_ephemeral: Public::default(), + remote_nonce: H256::default(), remote_version: PROTOCOL_VERSION, auth_cipher: Bytes::new(), ack_cipher: Bytes::new(), @@ -184,8 +181,8 @@ impl Handshake { remote_nonce: &[u8], remote_version: u64, ) -> Result<(), Error> { - self.id.clone_from_slice(remote_public); - self.remote_nonce.clone_from_slice(remote_nonce); + self.id = NodeId::from_slice(remote_public); + self.remote_nonce = H256::from_slice(remote_nonce); self.remote_version = remote_version; let shared = *ecdh::agree(host_secret, &self.id)?; let signature = H520::from_slice(sig); @@ -252,9 +249,9 @@ impl Handshake { let remote_version: u64 = rlp.val_at(3)?; self.set_auth( secret, - &signature, - &remote_public, - &remote_nonce, + signature.as_bytes(), + remote_public.as_bytes(), + remote_nonce.as_bytes(), remote_version, )?; self.write_ack_eip8(io)?; @@ -271,8 +268,8 @@ impl Handshake { self.ack_cipher = data.to_vec(); match ecies::decrypt(secret, &[], data) { Ok(ack) => { - self.remote_ephemeral.clone_from_slice(&ack[0..64]); - self.remote_nonce.clone_from_slice(&ack[64..(64 + 32)]); + self.remote_ephemeral = Public::from_slice(&ack[0..64]); + self.remote_nonce = H256::from_slice(&ack[64..(64 + 32)]); self.state = HandshakeState::StartSession; } Err(_) => { @@ -320,10 +317,7 @@ impl Handshake { rlp.append(&self.nonce); rlp.append(&PROTOCOL_VERSION); let mut encoded = rlp.out(); - encoded.resize( - encoded.len() + rand::thread_rng().gen_range::(100, 301), - 0, - ); + encoded.resize(encoded.len() + rand::thread_rng().gen_range(100, 301), 0); let len = (encoded.len() + ECIES_OVERHEAD) as u16; let prefix = len.to_be_bytes(); let message = ecies::encrypt(&self.id, &prefix, &encoded)?; @@ -347,8 +341,8 @@ impl Handshake { data[len - 1] = 0x0; let (epubk, rest) = data.split_at_mut(64); let (nonce, _) = rest.split_at_mut(32); - self.ecdhe.public().copy_to(epubk); - self.nonce.copy_to(nonce); + epubk.copy_from_slice(self.ecdhe.public().as_bytes()); + nonce.copy_from_slice(self.nonce.as_bytes()); } let message = ecies::encrypt(&self.id, &[], &data)?; self.ack_cipher = message.clone(); @@ -387,35 +381,38 @@ impl Handshake { #[cfg(test)] mod test { use super::*; - use ethereum_types::H256; - use ethkey::Public; + use crypto::publickey::Public; + use ethereum_types::{H256, H512}; use io::*; use mio::tcp::TcpStream; use rustc_hex::FromHex; + use std::str::FromStr; fn check_auth(h: &Handshake, version: u64) { - assert_eq!(h.id, "fda1cff674c90c9a197539fe3dfb53086ace64f83ed7c6eabec741f7f381cc803e52ab2cd55d5569bce4347107a310dfd5f88a010cd2ffd1005ca406f1842877".into()); + assert_eq!(h.id, H512::from_str("fda1cff674c90c9a197539fe3dfb53086ace64f83ed7c6eabec741f7f381cc803e52ab2cd55d5569bce4347107a310dfd5f88a010cd2ffd1005ca406f1842877").unwrap()); assert_eq!( h.remote_nonce, - "7e968bba13b6c50e2c4cd7f241cc0d64d1ac25c7f5952df231ac6a2bda8ee5d6".into() + H256::from_str("7e968bba13b6c50e2c4cd7f241cc0d64d1ac25c7f5952df231ac6a2bda8ee5d6") + .unwrap() ); - assert_eq!(h.remote_ephemeral, "654d1044b69c577a44e5f01a1209523adb4026e70c62d1c13a067acabc09d2667a49821a0ad4b634554d330a15a58fe61f8a8e0544b310c6de7b0c8da7528a8d".into()); + assert_eq!(h.remote_ephemeral, H512::from_str("654d1044b69c577a44e5f01a1209523adb4026e70c62d1c13a067acabc09d2667a49821a0ad4b634554d330a15a58fe61f8a8e0544b310c6de7b0c8da7528a8d").unwrap()); assert_eq!(h.remote_version, version); } fn check_ack(h: &Handshake, version: u64) { assert_eq!( h.remote_nonce, - "559aead08264d5795d3909718cdd05abd49572e84fe55590eef31a88a08fdffd".into() + H256::from_str("559aead08264d5795d3909718cdd05abd49572e84fe55590eef31a88a08fdffd") + .unwrap() ); - assert_eq!(h.remote_ephemeral, "b6d82fa3409da933dbf9cb0140c5dde89f4e64aec88d476af648880f4a10e1e49fe35ef3e69e93dd300b4797765a747c6384a6ecf5db9c2690398607a86181e4".into()); + assert_eq!(h.remote_ephemeral, H512::from_str("b6d82fa3409da933dbf9cb0140c5dde89f4e64aec88d476af648880f4a10e1e49fe35ef3e69e93dd300b4797765a747c6384a6ecf5db9c2690398607a86181e4").unwrap()); assert_eq!(h.remote_version, version); } fn create_handshake(to: Option<&Public>) -> Handshake { let addr = "127.0.0.1:50556".parse().unwrap(); let socket = TcpStream::connect(&addr).unwrap(); - let nonce = H256::new(); + let nonce = H256::default(); Handshake::new(0, to, socket, &nonce).unwrap() } @@ -515,7 +512,7 @@ mod test { #[test] fn test_handshake_ack_plain() { - let remote = "fda1cff674c90c9a197539fe3dfb53086ace64f83ed7c6eabec741f7f381cc803e52ab2cd55d5569bce4347107a310dfd5f88a010cd2ffd1005ca406f1842877".into(); + let remote = H512::from_str("fda1cff674c90c9a197539fe3dfb53086ace64f83ed7c6eabec741f7f381cc803e52ab2cd55d5569bce4347107a310dfd5f88a010cd2ffd1005ca406f1842877").unwrap(); let mut h = create_handshake(Some(&remote)); let secret = "49a7b37aa6f6645917e7b807e9d1c00d4fa71f18343b0d4122a4d2df64dd6fee" .parse() @@ -538,7 +535,7 @@ mod test { #[test] fn test_handshake_ack_eip8() { - let remote = "fda1cff674c90c9a197539fe3dfb53086ace64f83ed7c6eabec741f7f381cc803e52ab2cd55d5569bce4347107a310dfd5f88a010cd2ffd1005ca406f1842877".into(); + let remote = H512::from_str("fda1cff674c90c9a197539fe3dfb53086ace64f83ed7c6eabec741f7f381cc803e52ab2cd55d5569bce4347107a310dfd5f88a010cd2ffd1005ca406f1842877").unwrap(); let mut h = create_handshake(Some(&remote)); let secret = "49a7b37aa6f6645917e7b807e9d1c00d4fa71f18343b0d4122a4d2df64dd6fee" .parse() @@ -572,7 +569,7 @@ mod test { #[test] fn test_handshake_ack_eip8_2() { - let remote = "fda1cff674c90c9a197539fe3dfb53086ace64f83ed7c6eabec741f7f381cc803e52ab2cd55d5569bce4347107a310dfd5f88a010cd2ffd1005ca406f1842877".into(); + let remote = H512::from_str("fda1cff674c90c9a197539fe3dfb53086ace64f83ed7c6eabec741f7f381cc803e52ab2cd55d5569bce4347107a310dfd5f88a010cd2ffd1005ca406f1842877").unwrap(); let mut h = create_handshake(Some(&remote)); let secret = "49a7b37aa6f6645917e7b807e9d1c00d4fa71f18343b0d4122a4d2df64dd6fee" .parse() diff --git a/crates/net/network-devp2p/src/host.rs b/crates/net/network-devp2p/src/host.rs index 9ac7221d3..92191c115 100644 --- a/crates/net/network-devp2p/src/host.rs +++ b/crates/net/network-devp2p/src/host.rs @@ -14,8 +14,8 @@ // You should have received a copy of the GNU General Public License // along with OpenEthereum. If not, see . +use crypto::publickey::{Generator, KeyPair, Random, Secret}; use ethereum_types::H256; -use ethkey::{Generator, KeyPair, Random, Secret}; use hash::keccak; use mio::{deprecated::EventLoop, tcp::*, udp::*, *}; use rlp::{Encodable, RlpStream}; @@ -310,7 +310,7 @@ impl Host { .and_then(|ref p| load_key(Path::new(&p))) .map_or_else( || { - let key = Random.generate().expect("Error generating random key pair"); + let key = Random.generate(); if let Some(path) = config.config_path.clone() { save_key(Path::new(&path), key.secret()); } @@ -1457,7 +1457,7 @@ fn save_key(path: &Path, key: &Secret) { if let Err(e) = restrict_permissions_owner(path, true, false) { warn!(target: "network", "Failed to modify permissions of the file ({})", e); } - if let Err(e) = file.write(&key.hex().into_bytes()[2..]) { + if let Err(e) = file.write(&key.to_hex().into_bytes()) { warn!("Error writing key file: {:?}", e); } } diff --git a/crates/net/network-devp2p/src/node_table.rs b/crates/net/network-devp2p/src/node_table.rs index 03232e2ff..ef46e526f 100644 --- a/crates/net/network-devp2p/src/node_table.rs +++ b/crates/net/network-devp2p/src/node_table.rs @@ -18,7 +18,7 @@ use discovery::{NodeEntry, TableUpdates}; use ethereum_types::H512; use ip_utils::*; use network::{AllowIP, Error, ErrorKind, IpFilter}; -use rand::{self, Rng}; +use rand::seq::SliceRandom; use rlp::{DecoderError, Rlp, RlpStream}; use serde_json; use std::{ @@ -242,7 +242,7 @@ impl FromStr for Node { NodeEndpoint::from_str(&s[137..])?, ) } else { - (NodeId::new(), NodeEndpoint::from_str(s)?) + (NodeId::default(), NodeEndpoint::from_str(s)?) }; Ok(Node { @@ -351,7 +351,8 @@ impl NodeTable { a.time().cmp(&b.time()) }); - rand::thread_rng().shuffle(&mut unknown); + let mut rng = rand::thread_rng(); + unknown.shuffle(&mut rng); success.append(&mut unknown); success.append(&mut failures); diff --git a/crates/net/network-devp2p/tests/tests.rs b/crates/net/network-devp2p/tests/tests.rs index eec2aad78..ea501ad31 100644 --- a/crates/net/network-devp2p/tests/tests.rs +++ b/crates/net/network-devp2p/tests/tests.rs @@ -19,14 +19,14 @@ extern crate ethcore_io as io; extern crate ethcore_network; extern crate ethcore_network_devp2p; extern crate ethereum_types; -extern crate ethkey; extern crate parity_bytes; +extern crate parity_crypto as crypto; extern crate parking_lot; +use crypto::publickey::{Generator, Random}; use ethcore_network::*; use ethcore_network_devp2p::NetworkService; use ethereum_types::U64; -use ethkey::{Generator, Random}; use io::TimerToken; use parity_bytes::Bytes; use parking_lot::Mutex; @@ -136,7 +136,7 @@ fn net_start_stop() { #[test] fn net_disconnect() { - let key1 = Random.generate().unwrap(); + let key1 = Random.generate(); let mut config1 = NetworkConfiguration::new_local(); config1.use_secret = Some(key1.secret().clone()); config1.boot_nodes = vec![]; diff --git a/crates/net/network/Cargo.toml b/crates/net/network/Cargo.toml index 30827dee8..5cc8a560a 100644 --- a/crates/net/network/Cargo.toml +++ b/crates/net/network/Cargo.toml @@ -8,13 +8,13 @@ authors = ["Parity Technologies "] [dependencies] error-chain = { version = "0.12", default-features = false } -parity-crypto = "0.3.0" +parity-crypto = { version = "0.6.2", features = [ "publickey"] } ethcore-io = { path = "../../runtime/io" } -ethereum-types = "0.4" +ethereum-types = "0.9.2" ethkey = { path = "../../../crates/accounts/ethkey" } ipnetwork = "0.12.6" lazy_static = "1.0" -rlp = { version = "0.3.0", features = ["ethereum"] } +rlp = { version = "0.4.6" } libc = "0.2" parity-snappy = "0.1" semver = {version="0.9.0", features=["serde"]} diff --git a/crates/net/network/src/error.rs b/crates/net/network/src/error.rs index 041dee408..f37ebd6a8 100644 --- a/crates/net/network/src/error.rs +++ b/crates/net/network/src/error.rs @@ -19,7 +19,6 @@ #![allow(deprecated)] use crypto; -use ethkey; use io::IoError; use libc::{EMFILE, ENFILE}; use rlp; @@ -179,14 +178,14 @@ impl From for Error { } } -impl From for Error { - fn from(_err: ethkey::Error) -> Self { +impl From for Error { + fn from(_err: crypto::Error) -> Self { ErrorKind::Auth.into() } } -impl From for Error { - fn from(_err: ethkey::crypto::Error) -> Self { +impl From for Error { + fn from(_err: crypto::publickey::Error) -> Self { ErrorKind::Auth.into() } } @@ -217,7 +216,7 @@ fn test_errors() { _ => panic!("Unexpected error"), } - match *>::from(ethkey::crypto::Error::InvalidMessage) + match *>::from(crypto::publickey::Error::InvalidMessage) .kind() { ErrorKind::Auth => {} diff --git a/crates/net/network/src/lib.rs b/crates/net/network/src/lib.rs index 5c0f40a6a..dbf70ca01 100644 --- a/crates/net/network/src/lib.rs +++ b/crates/net/network/src/lib.rs @@ -50,8 +50,8 @@ pub use error::{DisconnectReason, Error, ErrorKind}; pub use io::TimerToken; use client_version::ClientVersion; +use crypto::publickey::Secret; use ethereum_types::{H512, U64}; -use ethkey::Secret; use ipnetwork::{IpNetwork, IpNetworkError}; use rlp::{Decodable, DecoderError, Rlp}; use std::{ diff --git a/crates/net/node-filter/Cargo.toml b/crates/net/node-filter/Cargo.toml index ca812ca19..4b23d2ef5 100644 --- a/crates/net/node-filter/Cargo.toml +++ b/crates/net/node-filter/Cargo.toml @@ -10,16 +10,16 @@ authors = ["Parity Technologies "] ethcore = { path = "../../ethcore"} ethcore-network = { path = "../network" } ethcore-network-devp2p = { path = "../network-devp2p" } -ethereum-types = "0.4" +ethereum-types = "0.9.2" log = "0.4" parking_lot = "0.7" -ethabi = "6.0" -ethabi-derive = "6.0" -ethabi-contract = "6.0" +ethabi = "12.0.0" +ethabi-derive = "12.0.0" +ethabi-contract = "11.0.0" lru-cache = "0.1" [dev-dependencies] ethcore = { path = "../../ethcore", features = ["test-helpers"] } kvdb-memorydb = "0.1" ethcore-io = { path = "../../runtime/io" } -tempdir = "0.3" \ No newline at end of file +tempdir = "0.3" diff --git a/crates/net/node-filter/src/lib.rs b/crates/net/node-filter/src/lib.rs index c32463b3e..6d72290a1 100644 --- a/crates/net/node-filter/src/lib.rs +++ b/crates/net/node-filter/src/lib.rs @@ -24,7 +24,6 @@ extern crate ethereum_types; extern crate lru_cache; extern crate parking_lot; -#[macro_use] extern crate ethabi_derive; #[macro_use] extern crate ethabi_contract; @@ -104,15 +103,19 @@ mod test { spec::Spec, test_helpers, }; + use ethereum_types::Address; use io::IoChannel; use network::{ConnectionDirection, ConnectionFilter, NodeId}; - use std::sync::{Arc, Weak}; + use std::{ + str::FromStr, + sync::{Arc, Weak}, + }; use tempdir::TempDir; /// Contract code: https://gist.github.com/arkpar/467dbcc73cbb85b0997a7a10ffa0695f #[test] fn node_filter() { - let contract_addr = "0000000000000000000000000000000000000005".into(); + let contract_addr = Address::from_str("0000000000000000000000000000000000000005").unwrap(); let data = include_bytes!("../res/node_filter.json"); let tempdir = TempDir::new("").unwrap(); let spec = Spec::load(&tempdir.path(), &data[..]).unwrap(); @@ -130,11 +133,11 @@ mod test { Arc::downgrade(&client) as Weak, contract_addr, ); - let self1: NodeId = "00000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000002".into(); - let self2: NodeId = "00000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000003".into(); - let node1: NodeId = "00000000000000000000000000000000000000000000000000000000000000110000000000000000000000000000000000000000000000000000000000000012".into(); - let node2: NodeId = "00000000000000000000000000000000000000000000000000000000000000210000000000000000000000000000000000000000000000000000000000000022".into(); - let nodex: NodeId = "77000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000".into(); + let self1 = NodeId::from_str("00000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000002").unwrap(); + let self2 = NodeId::from_str("00000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000003").unwrap(); + let node1 = NodeId::from_str("00000000000000000000000000000000000000000000000000000000000000110000000000000000000000000000000000000000000000000000000000000012").unwrap(); + let node2 = NodeId::from_str("00000000000000000000000000000000000000000000000000000000000000210000000000000000000000000000000000000000000000000000000000000022").unwrap(); + let nodex = NodeId::from_str("77000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000").unwrap(); assert!(filter.connection_allowed(&self1, &node1, ConnectionDirection::Inbound)); assert!(filter.connection_allowed(&self1, &nodex, ConnectionDirection::Inbound)); diff --git a/crates/rpc/Cargo.toml b/crates/rpc/Cargo.toml index 4b2d9bdef..13fc5deba 100644 --- a/crates/rpc/Cargo.toml +++ b/crates/rpc/Cargo.toml @@ -13,7 +13,8 @@ futures = "0.1.6" log = "0.4" order-stat = "0.1" parking_lot = "0.7" -rand = "0.4" +rand = "0.7.3" +rand_xorshift = "0.2.0" rustc-hex = "1.0" serde = "1.0" serde_derive = "1.0" @@ -39,19 +40,19 @@ ethcore-logger = { path = "../../bin/oe/logger" } ethcore-miner = { path = "../concensus/miner" } ethcore-network = { path = "../net/network" } ethcore-sync = { path = "../ethcore/sync" } -ethereum-types = "0.4" +ethereum-types = "0.9.2" parity-bytes = "0.1" -parity-crypto = "0.3.0" +parity-crypto = { version = "0.6.2", features = [ "publickey" ] } eip-712 = { path = "../util/EIP-712" } ethjson = { path = "../ethjson" } ethkey = { path = "../accounts/ethkey" } ethstore = { path = "../accounts/ethstore" } fetch = { path = "../net/fetch" } -keccak-hash = "0.1.2" +keccak-hash = "0.5.0" parity-runtime = { path = "../runtime/runtime" } parity-version = { path = "../util/version" } -rlp = { version = "0.3.0", features = ["ethereum"] } +rlp = { version = "0.4.6" } stats = { path = "../util/stats" } vm = { path = "../vm/vm" } diff --git a/crates/rpc/src/authcodes.rs b/crates/rpc/src/authcodes.rs index 12ec3dbb1..97240cae6 100644 --- a/crates/rpc/src/authcodes.rs +++ b/crates/rpc/src/authcodes.rs @@ -25,7 +25,7 @@ use std::{ use ethereum_types::H256; use hash::keccak; use itertools::Itertools; -use rand::{os::OsRng, Rng}; +use rand::{distributions::Alphanumeric, rngs::OsRng, Rng}; /// Providing current time in seconds pub trait TimeProvider { @@ -184,8 +184,11 @@ impl AuthCodes { /// Generates and returns a new code that can be used by `SignerUIs` pub fn generate_new(&mut self) -> io::Result { - let mut rng = OsRng::new()?; - let code = rng.gen_ascii_chars().take(TOKEN_LENGTH).collect::(); + let rng = OsRng; + let code = rng + .sample_iter(&Alphanumeric) + .take(TOKEN_LENGTH) + .collect::(); let readable_code = code .as_bytes() .chunks(4) diff --git a/crates/rpc/src/v1/extractors.rs b/crates/rpc/src/v1/extractors.rs index ef053fd6b..df32a4fc9 100644 --- a/crates/rpc/src/v1/extractors.rs +++ b/crates/rpc/src/v1/extractors.rs @@ -53,7 +53,7 @@ impl HttpMetaExtractor for RpcExtractor { impl ipc::MetaExtractor for RpcExtractor { fn extract(&self, req: &ipc::RequestContext) -> Metadata { Metadata { - origin: Origin::Ipc(req.session_id.into()), + origin: Origin::Ipc(H256::from_low_u64_be(req.session_id)), session: Some(Arc::new(Session::new(req.sender.clone()))), } } @@ -85,10 +85,14 @@ impl ws::MetaExtractor for WsExtractor { .and_then(|p| auth_token_hash(&path, p, true)); match authorization { Some(id) => Origin::Signer { session: id }, - None => Origin::Ws { session: id.into() }, + None => Origin::Ws { + session: H256::from_low_u64_be(id), + }, } } - None => Origin::Ws { session: id.into() }, + None => Origin::Ws { + session: H256::from_low_u64_be(id), + }, }; let session = Some(Arc::new(Session::new(req.sender()))); Metadata { origin, session } diff --git a/crates/rpc/src/v1/helpers/dispatch/mod.rs b/crates/rpc/src/v1/helpers/dispatch/mod.rs index d211e35d4..3d64e4906 100644 --- a/crates/rpc/src/v1/helpers/dispatch/mod.rs +++ b/crates/rpc/src/v1/helpers/dispatch/mod.rs @@ -86,9 +86,10 @@ pub use v1::helpers::nonce::Reservations; use std::{fmt::Debug, ops::Deref, sync::Arc}; use bytes::Bytes; +use crypto::publickey::Signature; use ethcore::{client::BlockChainClient, miner::MinerService}; use ethereum_types::{Address, H256, H520, U256}; -use ethkey::{Password, Signature}; +use ethkey::Password; use hash::keccak; use types::transaction::{PendingTransaction, SignedTransaction}; diff --git a/crates/rpc/src/v1/helpers/dispatch/signing.rs b/crates/rpc/src/v1/helpers/dispatch/signing.rs index 3ff004d34..43704a6b0 100644 --- a/crates/rpc/src/v1/helpers/dispatch/signing.rs +++ b/crates/rpc/src/v1/helpers/dispatch/signing.rs @@ -18,9 +18,8 @@ use std::sync::Arc; use accounts::AccountProvider; use bytes::Bytes; -use crypto::DEFAULT_MAC; +use crypto::{publickey::Signature, DEFAULT_MAC}; use ethereum_types::{Address, H256, U256}; -use ethkey::Signature; use jsonrpc_core::{Error, ErrorCode}; use types::transaction::{ AccessListTx, Action, SignedTransaction, Transaction, TypedTransaction, TypedTxId, diff --git a/crates/rpc/src/v1/helpers/engine_signer.rs b/crates/rpc/src/v1/helpers/engine_signer.rs index bcd9ca9ba..365ddae6a 100644 --- a/crates/rpc/src/v1/helpers/engine_signer.rs +++ b/crates/rpc/src/v1/helpers/engine_signer.rs @@ -17,7 +17,8 @@ use std::sync::Arc; use accounts::AccountProvider; -use ethkey::{self, Address, Password}; +use crypto::publickey::{self, Address}; +use ethkey::Password; /// An implementation of EngineSigner using internal account management. pub struct EngineSigner { @@ -38,13 +39,13 @@ impl EngineSigner { } impl ethcore::engines::EngineSigner for EngineSigner { - fn sign(&self, message: ethkey::Message) -> Result { + fn sign(&self, message: publickey::Message) -> Result { match self .accounts .sign(self.address, Some(self.password.clone()), message) { Ok(ok) => Ok(ok), - Err(_e) => Err(ethkey::Error::InvalidSecret), + Err(e) => Err(publickey::Error::Custom(e.to_string())), } } diff --git a/crates/rpc/src/v1/helpers/external_signer/signing_queue.rs b/crates/rpc/src/v1/helpers/external_signer/signing_queue.rs index e7c031938..6954c2772 100644 --- a/crates/rpc/src/v1/helpers/external_signer/signing_queue.rs +++ b/crates/rpc/src/v1/helpers/external_signer/signing_queue.rs @@ -242,7 +242,7 @@ impl SigningQueue for ConfirmationsQueue { #[cfg(test)] mod test { - use ethereum_types::{Address, U256}; + use ethereum_types::{Address, H256, U256}; use jsonrpc_core::futures::Future; use parking_lot::Mutex; use std::sync::Arc; @@ -257,9 +257,9 @@ mod test { fn request() -> ConfirmationPayload { ConfirmationPayload::SendTransaction(FilledTransactionRequest { transaction_type: Default::default(), - from: Address::from(1), + from: Address::from_low_u64_be(1), used_default_from: false, - to: Some(Address::from(2)), + to: Some(Address::from_low_u64_be(2)), gas_price: 0.into(), gas: 10_000.into(), value: 10_000_000.into(), @@ -279,13 +279,20 @@ mod test { // when let (id, future) = queue.add_request(request, Default::default()).unwrap(); let sender = queue.take(&id).unwrap(); - queue.request_confirmed(sender, Ok(ConfirmationResponse::SendTransaction(1.into()))); + queue.request_confirmed( + sender, + Ok(ConfirmationResponse::SendTransaction( + H256::from_low_u64_be(1), + )), + ); // then let confirmation = future.wait().unwrap(); assert_eq!( confirmation, - Ok(ConfirmationResponse::SendTransaction(1.into())) + Ok(ConfirmationResponse::SendTransaction( + H256::from_low_u64_be(1) + )) ); } diff --git a/crates/rpc/src/v1/helpers/secretstore.rs b/crates/rpc/src/v1/helpers/secretstore.rs index ed24d83ca..35df73247 100644 --- a/crates/rpc/src/v1/helpers/secretstore.rs +++ b/crates/rpc/src/v1/helpers/secretstore.rs @@ -15,11 +15,10 @@ // along with OpenEthereum. If not, see . use bytes::Bytes; -use crypto; +use crypto::publickey::{self, ec_math_utils, Generator, Public, Random, Secret}; use ethereum_types::{H256, H512}; -use ethkey::{self, math, Generator, Public, Random, Secret}; use jsonrpc_core::Error; -use rand::{OsRng, Rng}; +use rand::{rngs::OsRng, RngCore}; use std::collections::BTreeSet; use tiny_keccak::Keccak; use v1::{helpers::errors, types::EncryptedDocumentKey}; @@ -33,17 +32,17 @@ pub fn generate_document_key( server_key_public: Public, ) -> Result { // generate random plain document key - let document_key = Random.generate().map_err(errors::encryption)?; + let document_key = Random.generate(); // encrypt document key using server key let (common_point, encrypted_point) = encrypt_secret(document_key.public(), &server_key_public)?; // ..and now encrypt document key with account public - let encrypted_key = ethkey::crypto::ecies::encrypt( + let encrypted_key = publickey::ecies::encrypt( &account_public, &crypto::DEFAULT_MAC, - document_key.public(), + document_key.public().as_bytes(), ) .map_err(errors::encryption)?; @@ -104,7 +103,7 @@ pub fn decrypt_document_with_shadow( encrypted_document: Bytes, ) -> Result { let key = decrypt_with_shadow_coefficients(decrypted_secret, common_point, shadows)?; - decrypt_document(key.to_vec(), encrypted_document) + decrypt_document(key.as_bytes().to_vec(), encrypted_document) } /// Calculate Keccak(ordered servers set) @@ -132,7 +131,7 @@ fn into_document_key(key: Bytes) -> Result { fn initialization_vector() -> [u8; INIT_VEC_LEN] { let mut result = [0u8; INIT_VEC_LEN]; - let mut rng = OsRng::new().unwrap(); + let mut rng = OsRng; rng.fill_bytes(&mut result); result } @@ -149,9 +148,10 @@ fn decrypt_with_shadow_coefficients( .map_err(errors::encryption)?; } - math::public_mul_secret(&mut common_shadow_point, &shadow_coefficients_sum) + ec_math_utils::public_mul_secret(&mut common_shadow_point, &shadow_coefficients_sum) + .map_err(errors::encryption)?; + ec_math_utils::public_add(&mut decrypted_shadow, &common_shadow_point) .map_err(errors::encryption)?; - math::public_add(&mut decrypted_shadow, &common_shadow_point).map_err(errors::encryption)?; Ok(decrypted_shadow) } @@ -159,16 +159,18 @@ fn encrypt_secret(secret: &Public, joint_public: &Public) -> Result<(Public, Pub // TODO: it is copypaste of `encrypt_secret` from secret_store/src/key_server_cluster/math.rs // use shared version from SS math library, when it'll be available - let key_pair = Random.generate().map_err(errors::encryption)?; + let key_pair = Random.generate(); // k * T - let mut common_point = math::generation_point(); - math::public_mul_secret(&mut common_point, key_pair.secret()).map_err(errors::encryption)?; + let mut common_point = ec_math_utils::generation_point(); + ec_math_utils::public_mul_secret(&mut common_point, key_pair.secret()) + .map_err(errors::encryption)?; // M + k * y let mut encrypted_point = joint_public.clone(); - math::public_mul_secret(&mut encrypted_point, key_pair.secret()).map_err(errors::encryption)?; - math::public_add(&mut encrypted_point, secret).map_err(errors::encryption)?; + ec_math_utils::public_mul_secret(&mut encrypted_point, key_pair.secret()) + .map_err(errors::encryption)?; + ec_math_utils::public_add(&mut encrypted_point, secret).map_err(errors::encryption)?; Ok((common_point, encrypted_point)) } diff --git a/crates/rpc/src/v1/helpers/signature.rs b/crates/rpc/src/v1/helpers/signature.rs index ce71b9f2d..c7844aac3 100644 --- a/crates/rpc/src/v1/helpers/signature.rs +++ b/crates/rpc/src/v1/helpers/signature.rs @@ -14,8 +14,8 @@ // You should have received a copy of the GNU General Public License // along with OpenEthereum. If not, see . +use crypto::publickey::{public_to_address, recover, Signature}; use ethereum_types::{H256, U64}; -use ethkey::{public_to_address, recover, Signature}; use hash::keccak; use jsonrpc_core::Result; use v1::{ @@ -59,8 +59,8 @@ pub fn verify_signature( #[cfg(test)] mod tests { use super::*; + use crypto::publickey::{self, Generator}; use ethereum_types::{H160, U64}; - use ethkey::Generator; pub fn add_chain_replay_protection(v: u64, chain_id: Option) -> u64 { v + if let Some(n) = chain_id { @@ -88,9 +88,9 @@ mod tests { } else { keccak(data) }; - let account = ethkey::Random.generate().unwrap(); + let account = publickey::Random.generate(); let address = account.address(); - let sig = ethkey::sign(account.secret(), &hash).unwrap(); + let sig = publickey::sign(account.secret(), &hash).unwrap(); let (r, s, v) = (sig.r(), sig.s(), sig.v()); let v = add_chain_replay_protection(v as u64, signing_chain_id); let (r_buf, s_buf) = { diff --git a/crates/rpc/src/v1/helpers/subscribers.rs b/crates/rpc/src/v1/helpers/subscribers.rs index b428d7fbc..2dac203a4 100644 --- a/crates/rpc/src/v1/helpers/subscribers.rs +++ b/crates/rpc/src/v1/helpers/subscribers.rs @@ -21,7 +21,6 @@ use jsonrpc_pubsub::{ typed::{Sink, Subscriber}, SubscriptionId, }; -use rand::{Rng, StdRng}; use std::{collections::HashMap, ops, str}; #[derive(Debug, Clone, Hash, Eq, PartialEq)] @@ -44,34 +43,44 @@ impl Id { } } -#[derive(Clone)] +#[cfg(not(test))] +mod random { + use rand::rngs::OsRng; + pub type Rng = rand::rngs::OsRng; + pub fn new() -> Rng { + OsRng + } +} + +#[cfg(test)] +mod random { + extern crate rand_xorshift; + use self::rand_xorshift::XorShiftRng; + use rand::SeedableRng; + const RNG_SEED: [u8; 16] = [0u8; 16]; + pub type Rng = XorShiftRng; + pub fn new() -> Rng { + Rng::from_seed(RNG_SEED) + } +} + pub struct Subscribers { - rand: StdRng, + rand: random::Rng, subscriptions: HashMap, } impl Default for Subscribers { fn default() -> Self { Subscribers { - rand: StdRng::new().expect("Valid random source is required."), + rand: random::new(), subscriptions: HashMap::new(), } } } impl Subscribers { - /// Create a new Subscribers with given random source. - #[cfg(test)] - pub fn new_test() -> Self { - Subscribers { - rand: ::rand::SeedableRng::from_seed([0usize].as_ref()), - subscriptions: HashMap::new(), - } - } - fn next_id(&mut self) -> Id { - let mut data = H64::default(); - self.rand.fill_bytes(&mut data.0); + let data = H64::random_using(&mut self.rand); Id(data) } diff --git a/crates/rpc/src/v1/helpers/subscription_manager.rs b/crates/rpc/src/v1/helpers/subscription_manager.rs index 2bf525b9b..5fa45ee7d 100644 --- a/crates/rpc/src/v1/helpers/subscription_manager.rs +++ b/crates/rpc/src/v1/helpers/subscription_manager.rs @@ -66,7 +66,7 @@ impl> GenericPollManager { #[cfg(test)] pub fn new_test(rpc: MetaIoHandler) -> Self { let mut manager = Self::new(rpc); - manager.subscribers = Subscribers::new_test(); + manager.subscribers = Subscribers::default(); manager } @@ -187,7 +187,7 @@ mod tests { let mut el = Runtime::new().unwrap(); let mut poll_manager = poll_manager(); let (id, rx) = poll_manager.subscribe(Default::default(), "hello".into(), Params::None); - assert_eq!(id, SubscriptionId::String("0x416d77337e24399d".into())); + assert_eq!(id, SubscriptionId::String("0x43ca64edf03768e1".into())); // then poll_manager.tick().wait().unwrap(); diff --git a/crates/rpc/src/v1/impls/eth.rs b/crates/rpc/src/v1/impls/eth.rs index aa6529380..3c59a151a 100644 --- a/crates/rpc/src/v1/impls/eth.rs +++ b/crates/rpc/src/v1/impls/eth.rs @@ -22,7 +22,7 @@ use std::{ time::{Duration, Instant, SystemTime, UNIX_EPOCH}, }; -use ethereum_types::{Address, H160, H256, H64, U256, U64}; +use ethereum_types::{Address, BigEndianHash, H160, H256, H64, U256, U64}; use parking_lot::Mutex; use ethash::{self, SeedHashCompute}; @@ -637,7 +637,7 @@ where fn author(&self) -> Result { let miner = self.miner.authoring_params().author; - if miner == 0.into() { + if miner.is_zero() { (self.accounts)() .first() .cloned() @@ -732,8 +732,8 @@ where let key2: H256 = storage_index; self.client.prove_storage(key1, keccak(key2), id).map( |(storage_proof, storage_value)| StorageProof { - key: key2.into(), - value: storage_value.into(), + key: key2.into_uint(), + value: storage_value.into_uint(), proof: storage_proof.into_iter().map(Bytes::new).collect(), }, ) @@ -755,10 +755,11 @@ where let num = num.unwrap_or_default(); try_bf!(check_known(&*self.client, num.clone())); - let res = match self - .client - .storage_at(&address, &H256::from(position), self.get_state(num)) - { + let res = match self.client.storage_at( + &address, + &BigEndianHash::from_uint(&position), + self.get_state(num), + ) { Some(s) => Ok(s), None => Err(errors::state_pruned()), }; diff --git a/crates/rpc/src/v1/impls/eth_pubsub.rs b/crates/rpc/src/v1/impls/eth_pubsub.rs index c8199d463..7bf41bee7 100644 --- a/crates/rpc/src/v1/impls/eth_pubsub.rs +++ b/crates/rpc/src/v1/impls/eth_pubsub.rs @@ -79,9 +79,9 @@ impl EthPubSubClient { #[cfg(test)] pub fn new_test(client: Arc, executor: Executor) -> Self { let client = Self::new(client, executor); - *client.heads_subscribers.write() = Subscribers::new_test(); - *client.logs_subscribers.write() = Subscribers::new_test(); - *client.transactions_subscribers.write() = Subscribers::new_test(); + *client.heads_subscribers.write() = Subscribers::default(); + *client.logs_subscribers.write() = Subscribers::default(); + *client.transactions_subscribers.write() = Subscribers::default(); client } diff --git a/crates/rpc/src/v1/impls/parity.rs b/crates/rpc/src/v1/impls/parity.rs index 3c1c9c762..2a4bc3e32 100644 --- a/crates/rpc/src/v1/impls/parity.rs +++ b/crates/rpc/src/v1/impls/parity.rs @@ -17,7 +17,7 @@ //! Parity-specific rpc implementation. use std::{collections::BTreeMap, str::FromStr, sync::Arc}; -use crypto::DEFAULT_MAC; +use crypto::{publickey::ecies, DEFAULT_MAC}; use ethcore::{ client::{BlockChainClient, Call, StateClient}, miner::{self, MinerService}, @@ -26,7 +26,7 @@ use ethcore::{ }; use ethcore_logger::RotatingLogger; use ethereum_types::{Address, H160, H256, H512, H64, U256, U64}; -use ethkey::{crypto::ecies, Brain, Generator}; +use ethkey::Brain; use ethstore::random_phrase; use jsonrpc_core::{futures::future, BoxFuture, Result}; use stats::PrometheusMetrics; @@ -213,10 +213,7 @@ where } fn phrase_to_address(&self, phrase: String) -> Result { - Ok(Brain::new(phrase) - .generate() - .expect("Brain::generate always returns Ok; qed") - .address()) + Ok(Brain::new(phrase).generate().address()) } fn list_accounts( diff --git a/crates/rpc/src/v1/impls/parity_accounts.rs b/crates/rpc/src/v1/impls/parity_accounts.rs index 053a8dd71..151c3f12a 100644 --- a/crates/rpc/src/v1/impls/parity_accounts.rs +++ b/crates/rpc/src/v1/impls/parity_accounts.rs @@ -24,8 +24,9 @@ use std::{ }; use accounts::AccountProvider; +use crypto::publickey::Secret; use ethereum_types::{Address, H160, H256, H520}; -use ethkey::{Brain, Generator, Password, Secret}; +use ethkey::{Brain, Password}; use ethstore::KeyFile; use jsonrpc_core::Result; use v1::{ @@ -139,7 +140,7 @@ impl ParityAccounts for ParityAccountsClient { fn new_account_from_phrase(&self, phrase: String, pass: Password) -> Result { self.deprecation_notice("parity_newAccountFromPhrase"); - let brain = Brain::new(phrase).generate().unwrap(); + let brain = Brain::new(phrase).generate(); self.accounts .insert_account(brain.secret().clone(), &pass) .map(Into::into) @@ -157,7 +158,7 @@ impl ParityAccounts for ParityAccountsClient { fn new_account_from_secret(&self, secret: H256, pass: Password) -> Result { self.deprecation_notice("parity_newAccountFromSecret"); - let secret = Secret::from_unsafe_slice(&secret.0) + let secret = Secret::import_key(&secret.0) .map_err(|e| errors::account("Could not create account.", e))?; self.accounts .insert_account(secret, &pass) diff --git a/crates/rpc/src/v1/impls/parity_set.rs b/crates/rpc/src/v1/impls/parity_set.rs index 21489d034..62c1d801c 100644 --- a/crates/rpc/src/v1/impls/parity_set.rs +++ b/crates/rpc/src/v1/impls/parity_set.rs @@ -23,7 +23,6 @@ use ethcore::{ miner::{self, MinerService}, }; use ethereum_types::{H160, H256, U256}; -use ethkey; use fetch::{self, Fetch}; use hash::keccak_buffer; use sync::ManageNetwork; @@ -150,7 +149,7 @@ where } fn set_engine_signer_secret(&self, secret: H256) -> Result { - let keypair = ethkey::KeyPair::from_secret(secret.into()) + let keypair = crypto::publickey::KeyPair::from_secret(secret.into()) .map_err(|e| errors::account("Invalid secret", e))?; self.miner.set_author(miner::Author::Sealer( ethcore::engines::signer::from_keypair(keypair), diff --git a/crates/rpc/src/v1/impls/personal.rs b/crates/rpc/src/v1/impls/personal.rs index ce03eebdf..813790333 100644 --- a/crates/rpc/src/v1/impls/personal.rs +++ b/crates/rpc/src/v1/impls/personal.rs @@ -19,9 +19,9 @@ use std::sync::Arc; use accounts::AccountProvider; use bytes::Bytes; +use crypto::publickey::{public_to_address, recover, Signature}; use eip_712::{hash_structured_data, EIP712}; use ethereum_types::{Address, H160, H256, H520, U128}; -use ethkey::{public_to_address, recover, Signature}; use types::transaction::{PendingTransaction, SignedTransaction}; use jsonrpc_core::{ @@ -282,7 +282,7 @@ impl Personal for PersonalClient { fn ec_recover(&self, data: RpcBytes, signature: H520) -> BoxFuture { let signature: H520 = signature.into(); - let signature = Signature::from_electrum(&signature); + let signature = Signature::from_electrum(signature.as_bytes()); let data: Bytes = data.into(); let hash = eth_data_hash(data); diff --git a/crates/rpc/src/v1/impls/secretstore.rs b/crates/rpc/src/v1/impls/secretstore.rs index 8844fd62b..9c219e875 100644 --- a/crates/rpc/src/v1/impls/secretstore.rs +++ b/crates/rpc/src/v1/impls/secretstore.rs @@ -19,9 +19,8 @@ use std::{collections::BTreeSet, sync::Arc}; use accounts::AccountProvider; -use crypto::DEFAULT_MAC; +use crypto::{publickey::Secret, DEFAULT_MAC}; use ethereum_types::{H160, H256, H512}; -use ethkey::Secret; use ethkey::Password; use jsonrpc_core::Result; @@ -59,9 +58,8 @@ impl SecretStoreClient { /// Decrypt secret key using account' private key fn decrypt_secret(&self, address: H160, password: Password, key: Bytes) -> Result { - self.decrypt_key(address, password, key).and_then(|s| { - Secret::from_unsafe_slice(&s).map_err(|e| errors::account("invalid secret", e)) - }) + self.decrypt_key(address, password, key) + .and_then(|s| Secret::import_key(&s).map_err(|e| errors::account("invalid secret", e))) } } diff --git a/crates/rpc/src/v1/impls/signer.rs b/crates/rpc/src/v1/impls/signer.rs index 049ed2ab6..33a1f653e 100644 --- a/crates/rpc/src/v1/impls/signer.rs +++ b/crates/rpc/src/v1/impls/signer.rs @@ -18,8 +18,8 @@ use std::sync::Arc; -use ethereum_types::U256; -use ethkey; +use crypto::publickey; +use ethereum_types::{H520, U256}; use parity_runtime::Executor; use parking_lot::Mutex; use types::transaction::{PendingTransaction, SignedTransaction, TypedTransaction}; @@ -289,11 +289,11 @@ impl Signer for SignerClient { } ConfirmationPayload::EthSignMessage(address, data) => { let expected_hash = eth_data_hash(data); - let signature = ethkey::Signature::from_electrum(&bytes.0); - match ethkey::verify_address(&address, &signature, &expected_hash) { - Ok(true) => { - Ok(ConfirmationResponse::Signature(bytes.0.as_slice().into())) - } + let signature = publickey::Signature::from_electrum(&bytes.0); + match publickey::verify_address(&address, &signature, &expected_hash) { + Ok(true) => Ok(ConfirmationResponse::Signature(H520::from_slice( + bytes.0.as_slice(), + ))), Ok(false) => Err(errors::invalid_params( "Sender address does not match the signature.", (), @@ -304,11 +304,11 @@ impl Signer for SignerClient { } } ConfirmationPayload::SignMessage(address, hash) => { - let signature = ethkey::Signature::from_electrum(&bytes.0); - match ethkey::verify_address(&address, &signature, &hash) { - Ok(true) => { - Ok(ConfirmationResponse::Signature(bytes.0.as_slice().into())) - } + let signature = publickey::Signature::from_electrum(&bytes.0); + match publickey::verify_address(&address, &signature, &hash) { + Ok(true) => Ok(ConfirmationResponse::Signature(H520::from_slice( + bytes.0.as_slice(), + ))), Ok(false) => Err(errors::invalid_params( "Sender address does not match the signature.", (), diff --git a/crates/rpc/src/v1/tests/eth.rs b/crates/rpc/src/v1/tests/eth.rs index a3999f431..620c22c0a 100644 --- a/crates/rpc/src/v1/tests/eth.rs +++ b/crates/rpc/src/v1/tests/eth.rs @@ -571,7 +571,7 @@ fn starting_nonce_test() { let tester = EthTester::from_spec( Spec::load(&env::temp_dir(), POSITIVE_NONCE_SPEC).expect("invalid chain spec"), ); - let address = Address::from(10); + let address = Address::from_low_u64_be(10); let sample = tester .handler diff --git a/crates/rpc/src/v1/tests/helpers/sync_provider.rs b/crates/rpc/src/v1/tests/helpers/sync_provider.rs index c0e87b893..2d56808b2 100644 --- a/crates/rpc/src/v1/tests/helpers/sync_provider.rs +++ b/crates/rpc/src/v1/tests/helpers/sync_provider.rs @@ -16,7 +16,7 @@ //! Test implementation of SyncProvider. -use ethereum_types::H256; +use ethereum_types::{H256, H512}; use network::client_version::ClientVersion; use parking_lot::RwLock; use stats::{PrometheusMetrics, PrometheusRegistry}; @@ -88,7 +88,7 @@ impl SyncProvider for TestSyncProvider { eth_info: Some(EthProtocolInfo { version: 63, difficulty: Some(40.into()), - head: 50.into(), + head: H256::from_low_u64_be(50), }), }, PeerInfo { @@ -100,7 +100,7 @@ impl SyncProvider for TestSyncProvider { eth_info: Some(EthProtocolInfo { version: 65, difficulty: None, - head: 60.into(), + head: H256::from_low_u64_be(60), }), }, ] @@ -112,16 +112,16 @@ impl SyncProvider for TestSyncProvider { fn transactions_stats(&self) -> BTreeMap { map![ - 1.into() => TransactionStats { + H256::from_low_u64_be(1) => TransactionStats { first_seen: 10, propagated_to: map![ - 128.into() => 16 + H512::from_low_u64_be(128) => 16 ], }, - 5.into() => TransactionStats { + H256::from_low_u64_be(5) => TransactionStats { first_seen: 16, propagated_to: map![ - 16.into() => 1 + H512::from_low_u64_be(16) => 1 ], } ] diff --git a/crates/rpc/src/v1/tests/mocked/eth.rs b/crates/rpc/src/v1/tests/mocked/eth.rs index 00ea5c6c2..5b712054e 100644 --- a/crates/rpc/src/v1/tests/mocked/eth.rs +++ b/crates/rpc/src/v1/tests/mocked/eth.rs @@ -223,15 +223,15 @@ fn rpc_eth_chain_id() { fn rpc_eth_hashrate() { let tester = EthTester::default(); tester.hashrates.lock().insert( - H256::from(0), + H256::from_low_u64_be(0), (Instant::now() + Duration::from_secs(2), U256::from(0xfffa)), ); tester.hashrates.lock().insert( - H256::from(0), + H256::from_low_u64_be(0), (Instant::now() + Duration::from_secs(2), U256::from(0xfffb)), ); tester.hashrates.lock().insert( - H256::from(1), + H256::from_low_u64_be(1), (Instant::now() + Duration::from_secs(2), U256::from(0x1)), ); @@ -302,10 +302,16 @@ fn rpc_eth_logs() { #[test] fn rpc_eth_logs_error() { + fn h256_from_digit_be(d: u8) -> H256 { + let mut bytes = [0u8; 32]; + bytes[0] = d; + H256(bytes) + } + let tester = EthTester::default(); tester .client - .set_error_on_logs(Some(BlockId::Hash(H256::from([5u8].as_ref())))); + .set_error_on_logs(Some(BlockId::Hash(h256_from_digit_be(5)))); let request = r#"{"jsonrpc": "2.0", "method": "eth_getLogs", "params": [{"limit":1,"blockHash":"0x0000000000000000000000000000000000000000000000000000000000000000"}], "id": 1}"#; let response = r#"{"jsonrpc":"2.0","error":{"code":-32000,"message":"One of the blocks specified in filter (fromBlock, toBlock or blockHash) cannot be found","data":"0x0500000000000000000000000000000000000000000000000000000000000000"},"id":1}"#; assert_eq!( @@ -457,9 +463,10 @@ fn rpc_eth_submit_hashrate() { tester .hashrates .lock() - .get(&H256::from( - "0x59daa26581d0acd1fce254fb7e85952f4c09d0915afd33d3886cd914bc7d283c" - )) + .get( + &H256::from_str("59daa26581d0acd1fce254fb7e85952f4c09d0915afd33d3886cd914bc7d283c") + .unwrap() + ) .cloned() .unwrap() .1, @@ -536,10 +543,10 @@ fn rpc_eth_accounts() { let address = tester.accounts_provider.new_account(&"".into()).unwrap(); tester .accounts_provider - .set_address_name(1.into(), "1".into()); + .set_address_name(Address::from_low_u64_be(1), "1".into()); tester .accounts_provider - .set_address_name(10.into(), "10".into()); + .set_address_name(Address::from_low_u64_be(10), "10".into()); // with current policy it should return the account let request = r#"{"jsonrpc": "2.0", "method": "eth_accounts", "params": [], "id": 1}"#; @@ -569,7 +576,9 @@ fn rpc_eth_block_number() { #[test] fn rpc_eth_balance() { let tester = EthTester::default(); - tester.client.set_balance(Address::from(1), U256::from(5)); + tester + .client + .set_balance(Address::from_low_u64_be(1), U256::from(5)); let request = r#"{ "jsonrpc": "2.0", @@ -588,7 +597,9 @@ fn rpc_eth_balance() { #[test] fn rpc_eth_balance_pending() { let tester = EthTester::default(); - tester.client.set_balance(Address::from(1), U256::from(5)); + tester + .client + .set_balance(Address::from_low_u64_be(1), U256::from(5)); let request = r#"{ "jsonrpc": "2.0", @@ -608,9 +619,11 @@ fn rpc_eth_balance_pending() { #[test] fn rpc_eth_storage_at() { let tester = EthTester::default(); - tester - .client - .set_storage(Address::from(1), H256::from(4), H256::from(7)); + tester.client.set_storage( + Address::from_low_u64_be(1), + H256::from_low_u64_be(4), + H256::from_low_u64_be(7), + ); let request = r#"{ "jsonrpc": "2.0", @@ -755,7 +768,9 @@ fn rpc_eth_uncle_count_by_block_number() { #[test] fn rpc_eth_code() { let tester = EthTester::default(); - tester.client.set_code(Address::from(1), vec![0xff, 0x21]); + tester + .client + .set_code(Address::from_low_u64_be(1), vec![0xff, 0x21]); let request = r#"{ "jsonrpc": "2.0", @@ -1162,13 +1177,13 @@ fn rpc_eth_transaction_receipt() { ) .unwrap(), block_number: 0x4510c, - transaction_hash: H256::new(), + transaction_hash: H256::default(), transaction_index: 0, transaction_log_index: 0, log_index: 1, }], - log_bloom: 0.into(), - outcome: TransactionOutcome::StateRoot(0.into()), + log_bloom: Bloom::zero(), + outcome: TransactionOutcome::StateRoot(H256::zero()), }; let hash = diff --git a/crates/rpc/src/v1/tests/mocked/eth_pubsub.rs b/crates/rpc/src/v1/tests/mocked/eth_pubsub.rs index 0e5c6bbba..e19768c27 100644 --- a/crates/rpc/src/v1/tests/mocked/eth_pubsub.rs +++ b/crates/rpc/src/v1/tests/mocked/eth_pubsub.rs @@ -29,6 +29,7 @@ use v1::{EthPubSub, EthPubSubClient, Metadata}; use ethcore::client::{ ChainNotify, ChainRoute, ChainRouteType, EachBlockWith, NewBlocks, TestBlockChainClient, }; +use ethereum_types::{Address, H256}; use parity_runtime::Runtime; const DURATION_ZERO: Duration = Duration::from_millis(0); @@ -58,7 +59,7 @@ fn should_subscribe_to_new_heads() { // Subscribe let request = r#"{"jsonrpc": "2.0", "method": "eth_subscribe", "params": ["newHeads"], "id": 1}"#; - let response = r#"{"jsonrpc":"2.0","result":"0x416d77337e24399d","id":1}"#; + let response = r#"{"jsonrpc":"2.0","result":"0x43ca64edf03768e1","id":1}"#; assert_eq!( io.handle_request_sync(request, metadata.clone()), Some(response.to_owned()) @@ -75,7 +76,7 @@ fn should_subscribe_to_new_heads() { true, )); let (res, receiver) = receiver.into_future().wait().unwrap(); - let response = r#"{"jsonrpc":"2.0","method":"eth_subscription","params":{"result":{"author":"0x0000000000000000000000000000000000000000","difficulty":"0x1","extraData":"0x","gasLimit":"0xf4240","gasUsed":"0x0","hash":"0x3457d2fa2e3dd33c78ac681cf542e429becf718859053448748383af67e23218","logsBloom":"0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000","miner":"0x0000000000000000000000000000000000000000","number":"0x1","parentHash":"0x0cd786a2425d16f152c658316c423e6ce1181e15c3295826d7c9904cba9ce303","receiptsRoot":"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421","sealFields":[],"sha3Uncles":"0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347","size":"0x1c9","stateRoot":"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421","timestamp":"0x0","transactionsRoot":"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421"},"subscription":"0x416d77337e24399d"}}"#; + let response = r#"{"jsonrpc":"2.0","method":"eth_subscription","params":{"result":{"author":"0x0000000000000000000000000000000000000000","difficulty":"0x1","extraData":"0x","gasLimit":"0xf4240","gasUsed":"0x0","hash":"0x3457d2fa2e3dd33c78ac681cf542e429becf718859053448748383af67e23218","logsBloom":"0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000","miner":"0x0000000000000000000000000000000000000000","number":"0x1","parentHash":"0x0cd786a2425d16f152c658316c423e6ce1181e15c3295826d7c9904cba9ce303","receiptsRoot":"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421","sealFields":[],"sha3Uncles":"0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347","size":"0x1c9","stateRoot":"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421","timestamp":"0x0","transactionsRoot":"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421"},"subscription":"0x43ca64edf03768e1"}}"#; assert_eq!(res, Some(response.into())); // Notify about two blocks @@ -94,14 +95,14 @@ fn should_subscribe_to_new_heads() { // Receive both let (res, receiver) = receiver.into_future().wait().unwrap(); - let response = r#"{"jsonrpc":"2.0","method":"eth_subscription","params":{"result":{"author":"0x0000000000000000000000000000000000000000","difficulty":"0x2","extraData":"0x","gasLimit":"0xf4240","gasUsed":"0x0","hash":"0x44e5ecf454ea99af9d8a8f2ca0daba96964c90de05db7a78f59b84ae9e749706","logsBloom":"0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000","miner":"0x0000000000000000000000000000000000000000","number":"0x2","parentHash":"0x3457d2fa2e3dd33c78ac681cf542e429becf718859053448748383af67e23218","receiptsRoot":"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421","sealFields":[],"sha3Uncles":"0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347","size":"0x1c9","stateRoot":"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421","timestamp":"0x0","transactionsRoot":"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421"},"subscription":"0x416d77337e24399d"}}"#; + let response = r#"{"jsonrpc":"2.0","method":"eth_subscription","params":{"result":{"author":"0x0000000000000000000000000000000000000000","difficulty":"0x2","extraData":"0x","gasLimit":"0xf4240","gasUsed":"0x0","hash":"0x44e5ecf454ea99af9d8a8f2ca0daba96964c90de05db7a78f59b84ae9e749706","logsBloom":"0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000","miner":"0x0000000000000000000000000000000000000000","number":"0x2","parentHash":"0x3457d2fa2e3dd33c78ac681cf542e429becf718859053448748383af67e23218","receiptsRoot":"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421","sealFields":[],"sha3Uncles":"0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347","size":"0x1c9","stateRoot":"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421","timestamp":"0x0","transactionsRoot":"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421"},"subscription":"0x43ca64edf03768e1"}}"#; assert_eq!(res, Some(response.into())); let (res, receiver) = receiver.into_future().wait().unwrap(); - let response = r#"{"jsonrpc":"2.0","method":"eth_subscription","params":{"result":{"author":"0x0000000000000000000000000000000000000000","difficulty":"0x3","extraData":"0x","gasLimit":"0xf4240","gasUsed":"0x0","hash":"0xdf04a98bb0c6fa8441bd429822f65a46d0cb553f6bcef602b973e65c81497f8e","logsBloom":"0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000","miner":"0x0000000000000000000000000000000000000000","number":"0x3","parentHash":"0x44e5ecf454ea99af9d8a8f2ca0daba96964c90de05db7a78f59b84ae9e749706","receiptsRoot":"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421","sealFields":[],"sha3Uncles":"0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347","size":"0x1c9","stateRoot":"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421","timestamp":"0x0","transactionsRoot":"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421"},"subscription":"0x416d77337e24399d"}}"#; + let response = r#"{"jsonrpc":"2.0","method":"eth_subscription","params":{"result":{"author":"0x0000000000000000000000000000000000000000","difficulty":"0x3","extraData":"0x","gasLimit":"0xf4240","gasUsed":"0x0","hash":"0xdf04a98bb0c6fa8441bd429822f65a46d0cb553f6bcef602b973e65c81497f8e","logsBloom":"0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000","miner":"0x0000000000000000000000000000000000000000","number":"0x3","parentHash":"0x44e5ecf454ea99af9d8a8f2ca0daba96964c90de05db7a78f59b84ae9e749706","receiptsRoot":"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421","sealFields":[],"sha3Uncles":"0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347","size":"0x1c9","stateRoot":"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421","timestamp":"0x0","transactionsRoot":"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421"},"subscription":"0x43ca64edf03768e1"}}"#; assert_eq!(res, Some(response.into())); // And unsubscribe - let request = r#"{"jsonrpc": "2.0", "method": "eth_unsubscribe", "params": ["0x416d77337e24399d"], "id": 1}"#; + let request = r#"{"jsonrpc": "2.0", "method": "eth_unsubscribe", "params": ["0x43ca64edf03768e1"], "id": 1}"#; let response = r#"{"jsonrpc":"2.0","result":true,"id":1}"#; assert_eq!( io.handle_request_sync(request, metadata), @@ -130,8 +131,13 @@ fn should_subscribe_to_logs() { let tx_hash = block.transactions()[0].hash(); client.set_logs(vec![LocalizedLogEntry { entry: LogEntry { - address: 5.into(), - topics: vec![1.into(), 2.into(), 0.into(), 0.into()], + address: Address::from_low_u64_be(5), + topics: vec![ + H256::from_low_u64_be(1), + H256::from_low_u64_be(2), + H256::from_low_u64_be(0), + H256::from_low_u64_be(0), + ], data: vec![], }, block_hash: h1, @@ -156,7 +162,7 @@ fn should_subscribe_to_logs() { // Subscribe let request = r#"{"jsonrpc": "2.0", "method": "eth_subscribe", "params": ["logs", {}], "id": 1}"#; - let response = r#"{"jsonrpc":"2.0","result":"0x416d77337e24399d","id":1}"#; + let response = r#"{"jsonrpc":"2.0","result":"0x43ca64edf03768e1","id":1}"#; assert_eq!( io.handle_request_sync(request, metadata.clone()), Some(response.to_owned()) @@ -175,7 +181,7 @@ fn should_subscribe_to_logs() { let (res, receiver) = receiver.into_future().wait().unwrap(); let response = r#"{"jsonrpc":"2.0","method":"eth_subscription","params":{"result":{"address":"0x0000000000000000000000000000000000000005","blockHash":"0x3457d2fa2e3dd33c78ac681cf542e429becf718859053448748383af67e23218","blockNumber":"0x1","data":"0x","logIndex":"0x0","removed":false,"topics":["0x0000000000000000000000000000000000000000000000000000000000000001","0x0000000000000000000000000000000000000000000000000000000000000002","0x0000000000000000000000000000000000000000000000000000000000000000","0x0000000000000000000000000000000000000000000000000000000000000000"],"transactionHash":""#.to_owned() + &format!("0x{:x}", tx_hash) - + r#"","transactionIndex":"0x0","transactionLogIndex":"0x0","type":"mined"},"subscription":"0x416d77337e24399d"}}"#; + + r#"","transactionIndex":"0x0","transactionLogIndex":"0x0","type":"mined"},"subscription":"0x43ca64edf03768e1"}}"#; assert_eq!(res, Some(response.into())); // Check notifications (retracted) @@ -191,11 +197,11 @@ fn should_subscribe_to_logs() { let (res, receiver) = receiver.into_future().wait().unwrap(); let response = r#"{"jsonrpc":"2.0","method":"eth_subscription","params":{"result":{"address":"0x0000000000000000000000000000000000000005","blockHash":"0x3457d2fa2e3dd33c78ac681cf542e429becf718859053448748383af67e23218","blockNumber":"0x1","data":"0x","logIndex":"0x0","removed":true,"topics":["0x0000000000000000000000000000000000000000000000000000000000000001","0x0000000000000000000000000000000000000000000000000000000000000002","0x0000000000000000000000000000000000000000000000000000000000000000","0x0000000000000000000000000000000000000000000000000000000000000000"],"transactionHash":""#.to_owned() + &format!("0x{:x}", tx_hash) - + r#"","transactionIndex":"0x0","transactionLogIndex":"0x0","type":"removed"},"subscription":"0x416d77337e24399d"}}"#; + + r#"","transactionIndex":"0x0","transactionLogIndex":"0x0","type":"removed"},"subscription":"0x43ca64edf03768e1"}}"#; assert_eq!(res, Some(response.into())); // And unsubscribe - let request = r#"{"jsonrpc": "2.0", "method": "eth_unsubscribe", "params": ["0x416d77337e24399d"], "id": 1}"#; + let request = r#"{"jsonrpc": "2.0", "method": "eth_unsubscribe", "params": ["0x43ca64edf03768e1"], "id": 1}"#; let response = r#"{"jsonrpc":"2.0","result":true,"id":1}"#; assert_eq!( io.handle_request_sync(request, metadata), @@ -233,25 +239,25 @@ fn should_subscribe_to_pending_transactions() { // Subscribe let request = r#"{"jsonrpc": "2.0", "method": "eth_subscribe", "params": ["newPendingTransactions"], "id": 1}"#; - let response = r#"{"jsonrpc":"2.0","result":"0x416d77337e24399d","id":1}"#; + let response = r#"{"jsonrpc":"2.0","result":"0x43ca64edf03768e1","id":1}"#; assert_eq!( io.handle_request_sync(request, metadata.clone()), Some(response.to_owned()) ); // Send new transactions - handler.notify_new_transactions(&[5.into(), 7.into()]); + handler.notify_new_transactions(&[H256::from_low_u64_be(5), H256::from_low_u64_be(7)]); let (res, receiver) = receiver.into_future().wait().unwrap(); - let response = r#"{"jsonrpc":"2.0","method":"eth_subscription","params":{"result":"0x0000000000000000000000000000000000000000000000000000000000000005","subscription":"0x416d77337e24399d"}}"#; + let response = r#"{"jsonrpc":"2.0","method":"eth_subscription","params":{"result":"0x0000000000000000000000000000000000000000000000000000000000000005","subscription":"0x43ca64edf03768e1"}}"#; assert_eq!(res, Some(response.into())); let (res, receiver) = receiver.into_future().wait().unwrap(); - let response = r#"{"jsonrpc":"2.0","method":"eth_subscription","params":{"result":"0x0000000000000000000000000000000000000000000000000000000000000007","subscription":"0x416d77337e24399d"}}"#; + let response = r#"{"jsonrpc":"2.0","method":"eth_subscription","params":{"result":"0x0000000000000000000000000000000000000000000000000000000000000007","subscription":"0x43ca64edf03768e1"}}"#; assert_eq!(res, Some(response.into())); // And unsubscribe - let request = r#"{"jsonrpc": "2.0", "method": "eth_unsubscribe", "params": ["0x416d77337e24399d"], "id": 1}"#; + let request = r#"{"jsonrpc": "2.0", "method": "eth_unsubscribe", "params": ["0x43ca64edf03768e1"], "id": 1}"#; let response = r#"{"jsonrpc":"2.0","result":true,"id":1}"#; assert_eq!( io.handle_request_sync(request, metadata), diff --git a/crates/rpc/src/v1/tests/mocked/parity.rs b/crates/rpc/src/v1/tests/mocked/parity.rs index ea1b7c31a..49cd95a1d 100644 --- a/crates/rpc/src/v1/tests/mocked/parity.rs +++ b/crates/rpc/src/v1/tests/mocked/parity.rs @@ -14,10 +14,10 @@ // You should have received a copy of the GNU General Public License // along with OpenEthereum. If not, see . +use crypto::publickey::{Generator, Random}; use ethcore::client::{Executed, TestBlockChainClient, TransactionId}; use ethcore_logger::RotatingLogger; -use ethereum_types::{Address, H256, U256}; -use ethstore::ethkey::{Generator, Random}; +use ethereum_types::{Address, BigEndianHash, Bloom, H256, U256}; use miner::pool::local_transactions::Status as LocalTransactionStatus; use std::sync::Arc; use sync::ManageNetwork; @@ -294,7 +294,7 @@ fn rpc_parity_pending_transactions() { fn rpc_parity_encrypt() { let deps = Dependencies::new(); let io = deps.default_client(); - let key = format!("{:x}", Random.generate().unwrap().public()); + let key = format!("{:x}", Random.generate().public()); let request = r#"{"jsonrpc": "2.0", "method": "parity_encryptMessage", "params":["0x"# .to_owned() @@ -382,16 +382,16 @@ fn rpc_parity_local_transactions() { data: vec![1, 2, 3], nonce: 0.into(), }) - .fake_sign(3.into()); + .fake_sign(Address::from_low_u64_be(3)); let tx = Arc::new(::miner::pool::VerifiedTransaction::from_pending_block_transaction(tx)); - deps.miner - .local_transactions - .lock() - .insert(10.into(), LocalTransactionStatus::Pending(tx.clone())); - deps.miner - .local_transactions - .lock() - .insert(15.into(), LocalTransactionStatus::Pending(tx.clone())); + deps.miner.local_transactions.lock().insert( + H256::from_low_u64_be(10), + LocalTransactionStatus::Pending(tx.clone()), + ); + deps.miner.local_transactions.lock().insert( + H256::from_low_u64_be(15), + LocalTransactionStatus::Pending(tx.clone()), + ); let request = r#"{"jsonrpc": "2.0", "method": "parity_localTransactions", "params":[], "id": 1}"#; @@ -406,7 +406,7 @@ fn rpc_parity_chain_status() { let io = deps.default_client(); *deps.client.ancient_block.write() = Some((H256::default(), 5)); - *deps.client.first_block.write() = Some((H256::from(U256::from(1234)), 3333)); + *deps.client.first_block.write() = Some((BigEndianHash::from_uint(&U256::from(1234)), 3333)); let request = r#"{"jsonrpc": "2.0", "method": "parity_chainStatus", "params":[], "id": 1}"#; let response = r#"{"jsonrpc":"2.0","result":{"blockGap":["0x6","0xd05"]},"id":1}"#; @@ -467,21 +467,21 @@ fn rpc_parity_call() { fn rpc_parity_block_receipts() { let deps = Dependencies::new(); deps.client.receipts.write().insert( - TransactionId::Hash(1.into()), + TransactionId::Hash(H256::from_low_u64_be(1)), LocalizedReceipt { - transaction_hash: 1.into(), + transaction_hash: H256::from_low_u64_be(1), transaction_type: TypedTxId::Legacy, transaction_index: 0, - block_hash: 3.into(), + block_hash: H256::from_low_u64_be(3), block_number: 0, cumulative_gas_used: 21_000.into(), gas_used: 21_000.into(), contract_address: None, logs: vec![], - log_bloom: 1.into(), + log_bloom: Bloom::from_low_u64_be(1), outcome: TransactionOutcome::Unknown, to: None, - from: 9.into(), + from: Address::from_low_u64_be(9), }, ); let io = deps.default_client(); diff --git a/crates/rpc/src/v1/tests/mocked/parity_accounts.rs b/crates/rpc/src/v1/tests/mocked/parity_accounts.rs index 78cd70d39..c154a577b 100644 --- a/crates/rpc/src/v1/tests/mocked/parity_accounts.rs +++ b/crates/rpc/src/v1/tests/mocked/parity_accounts.rs @@ -14,7 +14,7 @@ // You should have received a copy of the GNU General Public License // along with OpenEthereum. If not, see . -use std::sync::Arc; +use std::{str::FromStr, sync::Arc}; use accounts::{AccountProvider, AccountProviderSettings}; use ethereum_types::Address; @@ -76,7 +76,9 @@ fn rpc_parity_accounts_info() { assert_eq!(accounts.len(), 1); let address = accounts[0]; - tester.accounts.set_address_name(1.into(), "XX".into()); + tester + .accounts + .set_address_name(Address::from_low_u64_be(1), "XX".into()); tester .accounts .set_account_name(address.clone(), "Test".into()) @@ -645,7 +647,7 @@ fn should_import_wallet() { let account_meta = tester .accounts - .account_meta("0x00bac56a8a27232baa044c03f43bf3648c961735".into()) + .account_meta(Address::from_str("00bac56a8a27232baa044c03f43bf3648c961735").unwrap()) .unwrap(); let account_uuid: String = account_meta.uuid.unwrap().into(); diff --git a/crates/rpc/src/v1/tests/mocked/parity_set.rs b/crates/rpc/src/v1/tests/mocked/parity_set.rs index bea2000a3..2384f9248 100644 --- a/crates/rpc/src/v1/tests/mocked/parity_set.rs +++ b/crates/rpc/src/v1/tests/mocked/parity_set.rs @@ -191,11 +191,11 @@ fn rpc_parity_remove_transaction() { nonce: 1.into(), gas_price: 0x9184e72a000u64.into(), gas: 0x76c0.into(), - action: Action::Call(5.into()), + action: Action::Call(Address::from_low_u64_be(5)), value: 0x9184e72au64.into(), data: vec![], }); - let signed = tx.fake_sign(2.into()); + let signed = tx.fake_sign(Address::from_low_u64_be(2)); let hash = signed.hash(); let request = r#"{"jsonrpc": "2.0", "method": "parity_removeTransaction", "params":[""# diff --git a/crates/rpc/src/v1/tests/mocked/personal.rs b/crates/rpc/src/v1/tests/mocked/personal.rs index 3a7743220..eeaefed8f 100644 --- a/crates/rpc/src/v1/tests/mocked/personal.rs +++ b/crates/rpc/src/v1/tests/mocked/personal.rs @@ -18,6 +18,7 @@ use std::{str::FromStr, sync::Arc}; use accounts::AccountProvider; use bytes::ToPretty; +use crypto::publickey::Secret; use ethcore::client::TestBlockChainClient; use ethereum_types::{Address, H520, U256}; use hash::keccak; @@ -26,7 +27,6 @@ use parity_runtime::Runtime; use parking_lot::Mutex; use types::transaction::{Action, Transaction, TypedTransaction}; -use ethkey::Secret; use serde_json::to_value; use v1::{ helpers::{ @@ -392,6 +392,7 @@ fn ec_recover_invalid_signature() { fn should_unlock_account_permanently() { let tester = setup(); let address = tester.accounts.new_account(&"password123".into()).unwrap(); + let message = [1u8; 32].into(); let request = r#"{ "jsonrpc": "2.0", @@ -412,10 +413,7 @@ fn should_unlock_account_permanently() { Some(response.into()) ); assert!( - tester - .accounts - .sign(address, None, Default::default()) - .is_ok(), + tester.accounts.sign(address, None, message).is_ok(), "Should unlock account." ); } @@ -446,7 +444,7 @@ fn sign_eip191_with_validator() { }"#; let with_validator = to_value(PresignedTransaction { validator: address.into(), - data: keccak("hello world").to_vec().into(), + data: keccak("hello world").as_bytes().to_vec().into(), }) .unwrap(); let result = eip191::hash_message(EIP191Version::PresignedTransaction, with_validator).unwrap(); diff --git a/crates/rpc/src/v1/tests/mocked/pubsub.rs b/crates/rpc/src/v1/tests/mocked/pubsub.rs index cf144a21b..5e05c254f 100644 --- a/crates/rpc/src/v1/tests/mocked/pubsub.rs +++ b/crates/rpc/src/v1/tests/mocked/pubsub.rs @@ -57,7 +57,7 @@ fn should_subscribe_to_a_method() { // Subscribe let request = r#"{"jsonrpc": "2.0", "method": "parity_subscribe", "params": ["hello", []], "id": 1}"#; - let response = r#"{"jsonrpc":"2.0","result":"0x416d77337e24399d","id":1}"#; + let response = r#"{"jsonrpc":"2.0","result":"0x43ca64edf03768e1","id":1}"#; assert_eq!( io.handle_request_sync(request, metadata.clone()), Some(response.to_owned()) @@ -65,15 +65,15 @@ fn should_subscribe_to_a_method() { // Check notifications let (res, receiver) = receiver.into_future().wait().unwrap(); - let response = r#"{"jsonrpc":"2.0","method":"parity_subscription","params":{"result":"hello","subscription":"0x416d77337e24399d"}}"#; + let response = r#"{"jsonrpc":"2.0","method":"parity_subscription","params":{"result":"hello","subscription":"0x43ca64edf03768e1"}}"#; assert_eq!(res, Some(response.into())); let (res, receiver) = receiver.into_future().wait().unwrap(); - let response = r#"{"jsonrpc":"2.0","method":"parity_subscription","params":{"result":"world","subscription":"0x416d77337e24399d"}}"#; + let response = r#"{"jsonrpc":"2.0","method":"parity_subscription","params":{"result":"world","subscription":"0x43ca64edf03768e1"}}"#; assert_eq!(res, Some(response.into())); // And unsubscribe - let request = r#"{"jsonrpc": "2.0", "method": "parity_unsubscribe", "params": ["0x416d77337e24399d"], "id": 1}"#; + let request = r#"{"jsonrpc": "2.0", "method": "parity_unsubscribe", "params": ["0x43ca64edf03768e1"], "id": 1}"#; let response = r#"{"jsonrpc":"2.0","result":true,"id":1}"#; assert_eq!( io.handle_request_sync(request, metadata), diff --git a/crates/rpc/src/v1/tests/mocked/secretstore.rs b/crates/rpc/src/v1/tests/mocked/secretstore.rs index 2b702823c..76dbbce50 100644 --- a/crates/rpc/src/v1/tests/mocked/secretstore.rs +++ b/crates/rpc/src/v1/tests/mocked/secretstore.rs @@ -17,9 +17,11 @@ use std::sync::Arc; use accounts::AccountProvider; -use crypto::DEFAULT_MAC; +use crypto::{ + publickey::{verify_public, KeyPair, Signature}, + DEFAULT_MAC, +}; use ethereum_types::H256; -use ethkey::{verify_public, KeyPair, Signature}; use jsonrpc_core::{IoHandler, Success}; use serde_json; diff --git a/crates/rpc/src/v1/tests/mocked/signer.rs b/crates/rpc/src/v1/tests/mocked/signer.rs index 58dc1232f..759659fff 100644 --- a/crates/rpc/src/v1/tests/mocked/signer.rs +++ b/crates/rpc/src/v1/tests/mocked/signer.rs @@ -92,7 +92,7 @@ fn should_return_list_of_items_to_confirm() { .add_request( ConfirmationPayload::SendTransaction(FilledTransactionRequest { transaction_type: Default::default(), - from: Address::from(1), + from: Address::from_low_u64_be(1), used_default_from: false, to: Some(Address::from_str("d46e8dd67c5d32be8058bb8eb970870f07244567").unwrap()), gas_price: U256::from(10_000), @@ -109,7 +109,7 @@ fn should_return_list_of_items_to_confirm() { let _sign_future = tester .signer .add_request( - ConfirmationPayload::EthSignMessage(1.into(), vec![5].into()), + ConfirmationPayload::EthSignMessage(Address::from_low_u64_be(1), vec![5].into()), Origin::Unknown, ) .unwrap(); @@ -139,7 +139,7 @@ fn should_reject_transaction_from_queue_without_dispatching() { .add_request( ConfirmationPayload::SendTransaction(FilledTransactionRequest { transaction_type: Default::default(), - from: Address::from(1), + from: Address::from_low_u64_be(1), used_default_from: false, to: Some(Address::from_str("d46e8dd67c5d32be8058bb8eb970870f07244567").unwrap()), gas_price: U256::from(10_000), @@ -177,7 +177,7 @@ fn should_not_remove_transaction_if_password_is_invalid() { .add_request( ConfirmationPayload::SendTransaction(FilledTransactionRequest { transaction_type: Default::default(), - from: Address::from(1), + from: Address::from_low_u64_be(1), used_default_from: false, to: Some(Address::from_str("d46e8dd67c5d32be8058bb8eb970870f07244567").unwrap()), gas_price: U256::from(10_000), @@ -213,7 +213,7 @@ fn should_not_remove_sign_if_password_is_invalid() { let _confirmation_future = tester .signer .add_request( - ConfirmationPayload::EthSignMessage(0.into(), vec![5].into()), + ConfirmationPayload::EthSignMessage(Address::from_low_u64_be(0), vec![5].into()), Origin::Unknown, ) .unwrap(); @@ -308,7 +308,7 @@ fn should_alter_the_sender_and_nonce() { .add_request( ConfirmationPayload::SendTransaction(FilledTransactionRequest { transaction_type: Default::default(), - from: 0.into(), + from: Address::from_low_u64_be(0), used_default_from: false, to: Some(recipient), gas_price: U256::from(10_000), diff --git a/crates/rpc/src/v1/tests/mocked/signing.rs b/crates/rpc/src/v1/tests/mocked/signing.rs index dd7ae5a9b..f8a675bee 100644 --- a/crates/rpc/src/v1/tests/mocked/signing.rs +++ b/crates/rpc/src/v1/tests/mocked/signing.rs @@ -32,10 +32,9 @@ use v1::{ use accounts::AccountProvider; use bytes::ToPretty; +use crypto::publickey::{Generator, Random, Secret}; use ethcore::client::TestBlockChainClient; -use ethereum_types::{Address, U256}; -use ethkey::Secret; -use ethstore::ethkey::{Generator, Random}; +use ethereum_types::{Address, H256, H520, U256}; use parity_runtime::{Executor, Runtime}; use parking_lot::Mutex; use serde_json; @@ -156,7 +155,10 @@ fn should_add_sign_to_queue() { if signer.requests().len() == 1 { // respond let sender = signer.take(&1.into()).unwrap(); - signer.request_confirmed(sender, Ok(ConfirmationResponse::Signature(0.into()))); + signer.request_confirmed( + sender, + Ok(ConfirmationResponse::Signature(H520::from_low_u64_be(0))), + ); break; } ::std::thread::sleep(Duration::from_millis(100)) @@ -250,9 +252,10 @@ fn should_check_status_of_request_when_its_resolved() { }"#; tester.io.handle_request_sync(&request).expect("Sent"); let sender = tester.signer.take(&1.into()).unwrap(); - tester - .signer - .request_confirmed(sender, Ok(ConfirmationResponse::Signature(1.into()))); + tester.signer.request_confirmed( + sender, + Ok(ConfirmationResponse::Signature(H520::from_low_u64_be(1))), + ); // This is not ideal, but we need to give futures some time to be executed, and they need to run in a separate thread thread::sleep(Duration::from_millis(20)); @@ -343,7 +346,12 @@ fn should_add_transaction_to_queue() { if signer.requests().len() == 1 { // respond let sender = signer.take(&1.into()).unwrap(); - signer.request_confirmed(sender, Ok(ConfirmationResponse::SendTransaction(0.into()))); + signer.request_confirmed( + sender, + Ok(ConfirmationResponse::SendTransaction( + H256::from_low_u64_be(0), + )), + ); break; } ::std::thread::sleep(Duration::from_millis(100)) @@ -549,7 +557,7 @@ fn should_decrypt_message_if_account_is_unlocked() { fn should_add_decryption_to_the_queue() { // given let tester = eth_signing(); - let acc = Random.generate().unwrap(); + let acc = Random.generate(); assert_eq!(tester.signer.requests().len(), 0); // when @@ -592,7 +600,7 @@ fn should_add_decryption_to_the_queue() { fn should_compose_transaction() { // given let tester = eth_signing(); - let acc = Random.generate().unwrap(); + let acc = Random.generate(); assert_eq!(tester.signer.requests().len(), 0); let from = format!("{:x}", acc.address()); diff --git a/crates/rpc/src/v1/tests/mocked/signing_unsafe.rs b/crates/rpc/src/v1/tests/mocked/signing_unsafe.rs index 088c95b83..fd9b51700 100644 --- a/crates/rpc/src/v1/tests/mocked/signing_unsafe.rs +++ b/crates/rpc/src/v1/tests/mocked/signing_unsafe.rs @@ -256,7 +256,7 @@ fn rpc_eth_send_transaction_with_bad_to() { "id": 1 }"#; - let response = r#"{"jsonrpc":"2.0","error":{"code":-32602,"message":"Invalid params: prefix is missing."},"id":1}"#; + let response = r#"{"jsonrpc":"2.0","error":{"code":-32602,"message":"Invalid params: 0x prefix is missing."},"id":1}"#; assert_eq!( tester.io.handle_request_sync(&request), diff --git a/crates/rpc/src/v1/tests/mocked/traces.rs b/crates/rpc/src/v1/tests/mocked/traces.rs index 34b0a2896..f9363da5b 100644 --- a/crates/rpc/src/v1/tests/mocked/traces.rs +++ b/crates/rpc/src/v1/tests/mocked/traces.rs @@ -24,6 +24,7 @@ use ethcore::{ LocalizedTrace, }, }; +use ethereum_types::{Address, H256}; use vm::CallType; @@ -40,8 +41,8 @@ fn io() -> Tester { let client = Arc::new(TestBlockChainClient::new()); *client.traces.write() = Some(vec![LocalizedTrace { action: Action::Call(Call { - from: 0xf.into(), - to: 0x10.into(), + from: Address::from_low_u64_be(0xf), + to: Address::from_low_u64_be(0x10), value: 0x1.into(), gas: 0x100.into(), input: vec![1, 2, 3], @@ -51,9 +52,9 @@ fn io() -> Tester { subtraces: 0, trace_address: vec![0], transaction_number: Some(0), - transaction_hash: Some(5.into()), + transaction_hash: Some(H256::from_low_u64_be(5)), block_number: 10, - block_hash: 10.into(), + block_hash: H256::from_low_u64_be(10), }]); *client.execution_result.write() = Some(Ok(Executed { exception: None, diff --git a/crates/rpc/src/v1/types/call_request.rs b/crates/rpc/src/v1/types/call_request.rs index 609686040..37a79c9b2 100644 --- a/crates/rpc/src/v1/types/call_request.rs +++ b/crates/rpc/src/v1/types/call_request.rs @@ -88,8 +88,8 @@ mod tests { deserialized, CallRequest { transaction_type: Default::default(), - from: Some(H160::from(1)), - to: Some(H160::from(2)), + from: Some(H160::from_low_u64_be(1)), + to: Some(H160::from_low_u64_be(2)), gas_price: Some(U256::from(1)), gas: Some(U256::from(2)), value: Some(U256::from(3)), @@ -134,7 +134,7 @@ mod tests { deserialized, CallRequest { transaction_type: Default::default(), - from: Some(H160::from(1)), + from: Some(H160::from_low_u64_be(1)), to: None, gas_price: None, gas: None, diff --git a/crates/rpc/src/v1/types/confirmations.rs b/crates/rpc/src/v1/types/confirmations.rs index b489f354c..152821335 100644 --- a/crates/rpc/src/v1/types/confirmations.rs +++ b/crates/rpc/src/v1/types/confirmations.rs @@ -302,7 +302,7 @@ where #[cfg(test)] mod tests { use super::*; - use ethereum_types::{H256, U256}; + use ethereum_types::{Address, H256, U256}; use serde_json; use std::str::FromStr; use v1::{helpers, types::TransactionCondition}; @@ -312,7 +312,10 @@ mod tests { // given let request = helpers::ConfirmationRequest { id: 15.into(), - payload: helpers::ConfirmationPayload::EthSignMessage(1.into(), vec![5].into()), + payload: helpers::ConfirmationPayload::EthSignMessage( + Address::from_low_u64_be(1), + vec![5].into(), + ), origin: Origin::Rpc("test service".into()), }; @@ -332,7 +335,7 @@ mod tests { payload: helpers::ConfirmationPayload::SendTransaction( helpers::FilledTransactionRequest { transaction_type: Default::default(), - from: 0.into(), + from: Address::from_low_u64_be(0), used_default_from: false, to: None, gas: 15_000.into(), @@ -344,7 +347,9 @@ mod tests { access_list: None, }, ), - origin: Origin::Signer { session: 5.into() }, + origin: Origin::Signer { + session: H256::from_low_u64_be(5), + }, }; // when @@ -363,7 +368,7 @@ mod tests { payload: helpers::ConfirmationPayload::SignTransaction( helpers::FilledTransactionRequest { transaction_type: Default::default(), - from: 0.into(), + from: Address::from_low_u64_be(0), used_default_from: false, to: None, gas: 15_000.into(), @@ -391,7 +396,10 @@ mod tests { // given let request = helpers::ConfirmationRequest { id: 15.into(), - payload: helpers::ConfirmationPayload::Decrypt(10.into(), vec![1, 2, 3].into()), + payload: helpers::ConfirmationPayload::Decrypt( + Address::from_low_u64_be(10), + vec![1, 2, 3].into(), + ), origin: Default::default(), }; @@ -423,7 +431,7 @@ mod tests { assert_eq!( res1, TransactionModification { - sender: Some(10.into()), + sender: Some(Address::from_low_u64_be(10)), gas_price: Some(U256::from_str("0ba43b7400").unwrap()), gas: None, condition: Some(Some(TransactionCondition::Number(0x42))), diff --git a/crates/rpc/src/v1/types/eth_types.rs b/crates/rpc/src/v1/types/eth_types.rs index f048cf814..32cee8387 100644 --- a/crates/rpc/src/v1/types/eth_types.rs +++ b/crates/rpc/src/v1/types/eth_types.rs @@ -18,10 +18,10 @@ fn should_serialize_u256() { #[test] fn should_serialize_h256() { - let serialized1 = serde_json::to_string(&H256::from(0)).unwrap(); - let serialized2 = serde_json::to_string(&H256::from(1)).unwrap(); - let serialized3 = serde_json::to_string(&H256::from(16)).unwrap(); - let serialized4 = serde_json::to_string(&H256::from(256)).unwrap(); + let serialized1 = serde_json::to_string(&H256::from_low_u64_be(0)).unwrap(); + let serialized2 = serde_json::to_string(&H256::from_low_u64_be(1)).unwrap(); + let serialized3 = serde_json::to_string(&H256::from_low_u64_be(16)).unwrap(); + let serialized4 = serde_json::to_string(&H256::from_low_u64_be(256)).unwrap(); assert_eq!( serialized1, @@ -109,7 +109,7 @@ fn should_deserialize_h256() { ) .unwrap(); - assert_eq!(deserialized1, 0.into()); - assert_eq!(deserialized2, 1.into()); - assert_eq!(deserialized3, 256.into()); + assert_eq!(deserialized1, H256::from_low_u64_be(0)); + assert_eq!(deserialized2, H256::from_low_u64_be(1)); + assert_eq!(deserialized3, H256::from_low_u64_be(256)); } diff --git a/crates/rpc/src/v1/types/filter.rs b/crates/rpc/src/v1/types/filter.rs index 07c841c32..7e610e184 100644 --- a/crates/rpc/src/v1/types/filter.rs +++ b/crates/rpc/src/v1/types/filter.rs @@ -238,7 +238,10 @@ mod tests { topics: Some(vec![ VariadicValue::Null, VariadicValue::Single( - "000000000000000000000000a94f5374fce5edbc8e2a8697c15331677e6ebf0b".into(), + H256::from_str( + "000000000000000000000000a94f5374fce5edbc8e2a8697c15331677e6ebf0b", + ) + .unwrap(), ), VariadicValue::Null, ]), @@ -254,9 +257,10 @@ mod tests { address: Some(vec![]), topics: vec![ None, - Some(vec![ - "000000000000000000000000a94f5374fce5edbc8e2a8697c15331677e6ebf0b".into() - ]), + Some(vec![H256::from_str( + "000000000000000000000000a94f5374fce5edbc8e2a8697c15331677e6ebf0b" + ) + .unwrap()]), None, None, ], diff --git a/crates/rpc/src/v1/types/provenance.rs b/crates/rpc/src/v1/types/provenance.rs index 5311cc400..5352cdc44 100644 --- a/crates/rpc/src/v1/types/provenance.rs +++ b/crates/rpc/src/v1/types/provenance.rs @@ -66,16 +66,21 @@ impl fmt::Display for Origin { #[cfg(test)] mod tests { use super::Origin; + use ethereum_types::H256; use serde_json; #[test] fn should_serialize_origin() { // given let o1 = Origin::Rpc("test service".into()); - let o3 = Origin::Ipc(5.into()); - let o4 = Origin::Signer { session: 10.into() }; + let o3 = Origin::Ipc(H256::from_low_u64_be(5)); + let o4 = Origin::Signer { + session: H256::from_low_u64_be(10), + }; let o5 = Origin::Unknown; - let o6 = Origin::Ws { session: 5.into() }; + let o6 = Origin::Ws { + session: H256::from_low_u64_be(5), + }; // when let res1 = serde_json::to_string(&o1).unwrap(); diff --git a/crates/rpc/src/v1/types/receipt.rs b/crates/rpc/src/v1/types/receipt.rs index dd083aabe..7a21d0800 100644 --- a/crates/rpc/src/v1/types/receipt.rs +++ b/crates/rpc/src/v1/types/receipt.rs @@ -140,6 +140,7 @@ impl From for Receipt { #[cfg(test)] mod tests { + use ethereum_types::{Bloom, H256}; use serde_json; use types::transaction::TypedTxId; use v1::types::{Log, Receipt}; @@ -152,7 +153,7 @@ mod tests { from: None, to: None, transaction_type: TypedTxId::AccessList.to_U64_option_id(), - transaction_hash: Some(0.into()), + transaction_hash: Some(H256::zero()), transaction_index: Some(0.into()), block_hash: Some( "ed76641c68a1c641aee09a94b3b471f4dc0316efe5ac19cf488e2674cf8d05b5" @@ -180,15 +181,15 @@ mod tests { .unwrap(), ), block_number: Some(0x4510c.into()), - transaction_hash: Some(0.into()), + transaction_hash: Some(H256::zero()), transaction_index: Some(0.into()), transaction_log_index: None, log_index: Some(1.into()), log_type: "mined".into(), removed: false, }], - logs_bloom: 15.into(), - state_root: Some(10.into()), + logs_bloom: Bloom::from_low_u64_be(15), + state_root: Some(H256::from_low_u64_be(10)), status_code: Some(1u64.into()), }; diff --git a/crates/rpc/src/v1/types/secretstore.rs b/crates/rpc/src/v1/types/secretstore.rs index b73d4c1d3..bf77ca0a0 100644 --- a/crates/rpc/src/v1/types/secretstore.rs +++ b/crates/rpc/src/v1/types/secretstore.rs @@ -32,13 +32,14 @@ pub struct EncryptedDocumentKey { #[cfg(test)] mod tests { use super::EncryptedDocumentKey; + use ethereum_types::H512; use serde_json; #[test] fn test_serialize_encrypted_document_key() { let initial = EncryptedDocumentKey { - common_point: 1.into(), - encrypted_point: 2.into(), + common_point: H512::from_low_u64_be(1), + encrypted_point: H512::from_low_u64_be(2), encrypted_key: vec![3].into(), }; @@ -49,8 +50,8 @@ mod tests { ); let deserialized: EncryptedDocumentKey = serde_json::from_str(&serialized).unwrap(); - assert_eq!(deserialized.common_point, 1.into()); - assert_eq!(deserialized.encrypted_point, 2.into()); + assert_eq!(deserialized.common_point, H512::from_low_u64_be(1)); + assert_eq!(deserialized.encrypted_point, H512::from_low_u64_be(2)); assert_eq!(deserialized.encrypted_key, vec![3].into()); } } diff --git a/crates/rpc/src/v1/types/sync.rs b/crates/rpc/src/v1/types/sync.rs index 0563b557a..7254ef960 100644 --- a/crates/rpc/src/v1/types/sync.rs +++ b/crates/rpc/src/v1/types/sync.rs @@ -175,6 +175,7 @@ pub struct ChainStatus { #[cfg(test)] mod tests { use super::{ChainStatus, Peers, SyncInfo, SyncStatus, TransactionStats}; + use ethereum_types::H512; use serde_json; use std::collections::BTreeMap; @@ -229,7 +230,7 @@ mod tests { let stats = TransactionStats { first_seen: 100, propagated_to: map![ - 10.into() => 50 + H512::from_low_u64_be(10) => 50 ], }; diff --git a/crates/rpc/src/v1/types/trace.rs b/crates/rpc/src/v1/types/trace.rs index e4595879b..7e055c542 100644 --- a/crates/rpc/src/v1/types/trace.rs +++ b/crates/rpc/src/v1/types/trace.rs @@ -679,6 +679,7 @@ impl From<(H256, Executed)> for TraceResultsWithTransactionHash { mod tests { use super::*; use ethcore::trace::TraceError; + use ethereum_types::{Address, H256}; use serde_json; use std::collections::BTreeMap; use v1::types::Bytes; @@ -702,8 +703,8 @@ mod tests { fn test_trace_call_serialize() { let t = LocalizedTrace { action: Action::Call(Call { - from: 4.into(), - to: 5.into(), + from: Address::from_low_u64_be(4), + to: Address::from_low_u64_be(5), value: 6.into(), gas: 7.into(), input: Bytes::new(vec![0x12, 0x34]), @@ -716,9 +717,9 @@ mod tests { trace_address: vec![10], subtraces: 1, transaction_position: Some(11), - transaction_hash: Some(12.into()), + transaction_hash: Some(H256::from_low_u64_be(12)), block_number: 13, - block_hash: 14.into(), + block_hash: H256::from_low_u64_be(14), }; let serialized = serde_json::to_string(&t).unwrap(); assert_eq!( @@ -731,8 +732,8 @@ mod tests { fn test_trace_failed_call_serialize() { let t = LocalizedTrace { action: Action::Call(Call { - from: 4.into(), - to: 5.into(), + from: Address::from_low_u64_be(4), + to: Address::from_low_u64_be(5), value: 6.into(), gas: 7.into(), input: Bytes::new(vec![0x12, 0x34]), @@ -742,9 +743,9 @@ mod tests { trace_address: vec![10], subtraces: 1, transaction_position: Some(11), - transaction_hash: Some(12.into()), + transaction_hash: Some(H256::from_low_u64_be(12)), block_number: 13, - block_hash: 14.into(), + block_hash: H256::from_low_u64_be(14), }; let serialized = serde_json::to_string(&t).unwrap(); assert_eq!( @@ -757,7 +758,7 @@ mod tests { fn test_trace_create_serialize() { let t = LocalizedTrace { action: Action::Create(Create { - from: 4.into(), + from: Address::from_low_u64_be(4), value: 6.into(), gas: 7.into(), init: Bytes::new(vec![0x12, 0x34]), @@ -765,14 +766,14 @@ mod tests { result: Res::Create(CreateResult { gas_used: 8.into(), code: vec![0x56, 0x78].into(), - address: 0xff.into(), + address: Address::from_low_u64_be(0xff), }), trace_address: vec![10], subtraces: 1, transaction_position: Some(11), - transaction_hash: Some(12.into()), + transaction_hash: Some(H256::from_low_u64_be(12)), block_number: 13, - block_hash: 14.into(), + block_hash: H256::from_low_u64_be(14), }; let serialized = serde_json::to_string(&t).unwrap(); assert_eq!( @@ -785,7 +786,7 @@ mod tests { fn test_trace_failed_create_serialize() { let t = LocalizedTrace { action: Action::Create(Create { - from: 4.into(), + from: Address::from_low_u64_be(4), value: 6.into(), gas: 7.into(), init: Bytes::new(vec![0x12, 0x34]), @@ -794,9 +795,9 @@ mod tests { trace_address: vec![10], subtraces: 1, transaction_position: Some(11), - transaction_hash: Some(12.into()), + transaction_hash: Some(H256::from_low_u64_be(12)), block_number: 13, - block_hash: 14.into(), + block_hash: H256::from_low_u64_be(14), }; let serialized = serde_json::to_string(&t).unwrap(); assert_eq!( @@ -809,17 +810,17 @@ mod tests { fn test_trace_suicide_serialize() { let t = LocalizedTrace { action: Action::Suicide(Suicide { - address: 4.into(), - refund_address: 6.into(), + address: Address::from_low_u64_be(4), + refund_address: Address::from_low_u64_be(6), balance: 7.into(), }), result: Res::None, trace_address: vec![10], subtraces: 1, transaction_position: Some(11), - transaction_hash: Some(12.into()), + transaction_hash: Some(H256::from_low_u64_be(12)), block_number: 13, - block_hash: 14.into(), + block_hash: H256::from_low_u64_be(14), }; let serialized = serde_json::to_string(&t).unwrap(); assert_eq!( @@ -832,7 +833,7 @@ mod tests { fn test_trace_reward_serialize() { let t = LocalizedTrace { action: Action::Reward(Reward { - author: 4.into(), + author: Address::from_low_u64_be(4), value: 6.into(), reward_type: RewardType::Block, }), @@ -842,7 +843,7 @@ mod tests { transaction_position: None, transaction_hash: None, block_number: 13, - block_hash: 14.into(), + block_hash: H256::from_low_u64_be(14), }; let serialized = serde_json::to_string(&t).unwrap(); assert_eq!( @@ -904,15 +905,15 @@ mod tests { #[test] fn test_statediff_serialize() { let t = StateDiff(map![ - 42.into() => AccountDiff { + Address::from_low_u64_be(42) => AccountDiff { balance: Diff::Same, nonce: Diff::Born(1.into()), code: Diff::Same, storage: map![ - 42.into() => Diff::Same + H256::from_low_u64_be(42) => Diff::Same ] }, - 69.into() => AccountDiff { + Address::from_low_u64_be(69) => AccountDiff { balance: Diff::Same, nonce: Diff::Changed(ChangedType { from: 1.into(), to: 0.into() }), code: Diff::Died(vec![96].into()), diff --git a/crates/rpc/src/v1/types/trace_filter.rs b/crates/rpc/src/v1/types/trace_filter.rs index 50b3ea47f..7c61c78a3 100644 --- a/crates/rpc/src/v1/types/trace_filter.rs +++ b/crates/rpc/src/v1/types/trace_filter.rs @@ -106,8 +106,8 @@ mod tests { TraceFilter { from_block: Some(BlockNumber::Latest), to_block: Some(BlockNumber::Latest), - from_address: Some(vec![Address::from(3).into()]), - to_address: Some(vec![Address::from(5).into()]), + from_address: Some(vec![Address::from_low_u64_be(3).into()]), + to_address: Some(vec![Address::from_low_u64_be(5).into()]), after: 50.into(), count: 100.into(), } diff --git a/crates/rpc/src/v1/types/transaction.rs b/crates/rpc/src/v1/types/transaction.rs index 14f7608e7..f84a8951e 100644 --- a/crates/rpc/src/v1/types/transaction.rs +++ b/crates/rpc/src/v1/types/transaction.rs @@ -317,6 +317,7 @@ impl LocalTransactionStatus { #[cfg(test)] mod tests { use super::{LocalTransactionStatus, Transaction}; + use ethereum_types::H256; use serde_json; use types::transaction::TypedTxId; use v1::types::AccessListItem; @@ -343,7 +344,11 @@ mod tests { let status5 = LocalTransactionStatus::Invalid(Transaction::default()); let status6 = LocalTransactionStatus::Rejected(Transaction::default(), "Just because".into()); - let status7 = LocalTransactionStatus::Replaced(Transaction::default(), 5.into(), 10.into()); + let status7 = LocalTransactionStatus::Replaced( + Transaction::default(), + 5.into(), + H256::from_low_u64_be(10), + ); assert_eq!( serde_json::to_string(&status1).unwrap(), diff --git a/crates/rpc/src/v1/types/transaction_request.rs b/crates/rpc/src/v1/types/transaction_request.rs index 8aab53876..77d0282b2 100644 --- a/crates/rpc/src/v1/types/transaction_request.rs +++ b/crates/rpc/src/v1/types/transaction_request.rs @@ -178,8 +178,8 @@ mod tests { deserialized, TransactionRequest { transaction_type: Default::default(), - from: Some(H160::from(1)), - to: Some(H160::from(2)), + from: Some(H160::from_low_u64_be(1)), + to: Some(H160::from_low_u64_be(2)), gas_price: Some(U256::from(1)), gas: Some(U256::from(2)), value: Some(U256::from(3)), @@ -226,7 +226,7 @@ mod tests { deserialized, TransactionRequest { transaction_type: Default::default(), - from: Some(H160::from(1).into()), + from: Some(H160::from_low_u64_be(1).into()), to: None, gas_price: None, gas: None, diff --git a/crates/util/EIP-712/Cargo.toml b/crates/util/EIP-712/Cargo.toml index 3d6320b03..48428a0b7 100644 --- a/crates/util/EIP-712/Cargo.toml +++ b/crates/util/EIP-712/Cargo.toml @@ -14,9 +14,9 @@ edition = "2018" serde_derive = "1.0" serde = "1.0" serde_json = "1.0" -ethabi = "6.0" -keccak-hash = "0.1" -ethereum-types = "0.4" +ethabi = "12.0.0" +keccak-hash = "0.5.0" +ethereum-types = "0.9.2" failure = "0.1.7" itertools = "0.7" lazy_static = "1.1" diff --git a/crates/util/EIP-712/src/encode.rs b/crates/util/EIP-712/src/encode.rs index 09d6caef9..a63f8300c 100644 --- a/crates/util/EIP-712/src/encode.rs +++ b/crates/util/EIP-712/src/encode.rs @@ -134,8 +134,7 @@ fn encode_data( items.append(&mut encoded); } - // keccak(items).as_ref().to_vec() - keccak(items).to_vec() + keccak(items).as_ref().to_vec() } Type::Custom(ref ident) if message_types.get(&*ident).is_some() => { @@ -152,8 +151,7 @@ fn encode_data( tokens.append(&mut encoded); } - // keccak(tokens).as_ref().to_vec() - keccak(tokens).to_vec() + keccak(tokens).as_ref().to_vec() } Type::Bytes => { @@ -164,8 +162,7 @@ fn encode_data( let bytes = (&string[2..]) .from_hex::>() .map_err(|err| ErrorKind::HexParseError(format!("{}", err)))?; - // let bytes = keccak(&bytes).as_ref().to_vec(); - let bytes = keccak(&bytes).to_vec(); + let bytes = keccak(&bytes).as_ref().to_vec(); encode(&[EthAbiToken::FixedBytes(bytes)]) } @@ -184,8 +181,7 @@ fn encode_data( Type::String => { let value = value.as_str().ok_or(serde_error("string", field_name))?; - // let hash = keccak(value).as_ref().to_vec(); - let hash = keccak(value).to_vec(); + let hash = keccak(value).as_ref().to_vec(); encode(&[EthAbiToken::FixedBytes(hash)]) } diff --git a/crates/util/cli-signer/Cargo.toml b/crates/util/cli-signer/Cargo.toml index afc3352ca..83fe9c0c2 100644 --- a/crates/util/cli-signer/Cargo.toml +++ b/crates/util/cli-signer/Cargo.toml @@ -7,7 +7,7 @@ version = "1.4.0" authors = ["Parity "] [dependencies] -ethereum-types = "0.4" +ethereum-types = "0.9.2" futures = "0.1" rpassword = "1.0" parity-rpc = { path = "../../rpc" } diff --git a/crates/util/cli-signer/rpc-client/Cargo.toml b/crates/util/cli-signer/rpc-client/Cargo.toml index 19d2c61a8..fe54b5fcc 100644 --- a/crates/util/cli-signer/rpc-client/Cargo.toml +++ b/crates/util/cli-signer/rpc-client/Cargo.toml @@ -7,7 +7,7 @@ version = "1.4.0" authors = ["Parity "] [dependencies] -ethereum-types = "0.4" +ethereum-types = "0.9.2" futures = "0.1" log = "0.4" serde = "1.0" @@ -18,4 +18,4 @@ parking_lot = "0.9" jsonrpc-core = "15.0.0" jsonrpc-ws-server = "15.0.0" parity-rpc = { path = "../../../rpc" } -keccak-hash = "0.1" +keccak-hash = "0.5.0" diff --git a/crates/util/dir/Cargo.toml b/crates/util/dir/Cargo.toml index 449805c38..bfa27f23e 100644 --- a/crates/util/dir/Cargo.toml +++ b/crates/util/dir/Cargo.toml @@ -5,7 +5,7 @@ authors = ["Parity Technologies "] license = "GPL3" [dependencies] -ethereum-types = "0.4" +ethereum-types = "0.9.2" journaldb = { path = "../../db/journaldb" } app_dirs = { git = "https://github.com/openethereum/app-dirs-rs" } home = "0.3" diff --git a/crates/util/dir/src/lib.rs b/crates/util/dir/src/lib.rs index 05d8b7b22..f105014b4 100644 --- a/crates/util/dir/src/lib.rs +++ b/crates/util/dir/src/lib.rs @@ -188,9 +188,10 @@ impl DatabaseDirectories { /// Base DB directory for the given fork. // TODO: remove in 1.7 pub fn legacy_fork_path(&self) -> PathBuf { + let gh = H64::from_slice(&self.genesis_hash.as_bytes()[20..28]); Path::new(&self.legacy_path).join(format!( "{:x}{}", - H64::from(self.genesis_hash), + gh, self.fork_name .as_ref() .map(|f| format!("-{}", f)) @@ -212,9 +213,8 @@ impl DatabaseDirectories { /// DB root path, named after genesis hash pub fn db_root_path(&self) -> PathBuf { - self.spec_root_path() - .join("db") - .join(format!("{:x}", H64::from(self.genesis_hash))) + let gh = H64::from_slice(&self.genesis_hash.as_bytes()[20..28]); + self.spec_root_path().join("db").join(format!("{:x}", gh)) } /// DB path diff --git a/crates/util/fastmap/Cargo.toml b/crates/util/fastmap/Cargo.toml index 371eebe97..6ca397d77 100644 --- a/crates/util/fastmap/Cargo.toml +++ b/crates/util/fastmap/Cargo.toml @@ -6,5 +6,5 @@ description = "Specialized version of `HashMap` with H256 keys and fast hashing license = "GPL-3.0" [dependencies] -ethereum-types = "0.4" +ethereum-types = "0.9.2" plain_hasher = "0.2" diff --git a/crates/util/fastmap/src/lib.rs b/crates/util/fastmap/src/lib.rs index cc7929b01..cc39591e1 100644 --- a/crates/util/fastmap/src/lib.rs +++ b/crates/util/fastmap/src/lib.rs @@ -38,6 +38,6 @@ mod tests { #[test] fn test_works() { let mut h = H256FastMap::default(); - h.insert(H256::from(123), "abc"); + h.insert(H256::from_low_u64_be(123), "abc"); } } diff --git a/crates/util/keccak-hasher/Cargo.toml b/crates/util/keccak-hasher/Cargo.toml index edeecda83..ba3af0d3d 100644 --- a/crates/util/keccak-hasher/Cargo.toml +++ b/crates/util/keccak-hasher/Cargo.toml @@ -6,7 +6,7 @@ description = "Keccak-256 implementation of the Hasher trait" license = "GPL-3.0" [dependencies] -ethereum-types = "0.4" +ethereum-types = "0.9.2" tiny-keccak = "1.4.2" hash-db = "0.11.0" plain_hasher = "0.2" diff --git a/crates/util/memory-cache/Cargo.toml b/crates/util/memory-cache/Cargo.toml index f2b612463..213772857 100644 --- a/crates/util/memory-cache/Cargo.toml +++ b/crates/util/memory-cache/Cargo.toml @@ -6,5 +6,5 @@ description = "An LRU-cache which operates on memory used" license = "GPL3" [dependencies] -heapsize = "0.4" +parity-util-mem = "0.7" lru-cache = "0.1" diff --git a/crates/util/memory-cache/src/lib.rs b/crates/util/memory-cache/src/lib.rs index bfa260c74..1f401671d 100644 --- a/crates/util/memory-cache/src/lib.rs +++ b/crates/util/memory-cache/src/lib.rs @@ -18,29 +18,29 @@ //! crate. // TODO: push changes upstream in a clean way. -extern crate heapsize; extern crate lru_cache; +extern crate parity_util_mem; -use heapsize::HeapSizeOf; use lru_cache::LruCache; +use parity_util_mem::{MallocSizeOf, MallocSizeOfExt}; use std::hash::Hash; const INITIAL_CAPACITY: usize = 4; /// An LRU-cache which operates on memory used. -pub struct MemoryLruCache { +pub struct MemoryLruCache { inner: LruCache, cur_size: usize, max_size: usize, } // amount of memory used when the item will be put on the heap. -fn heap_size_of(val: &T) -> usize { - ::std::mem::size_of::() + val.heap_size_of_children() +fn heap_size_of(val: &T) -> usize { + ::std::mem::size_of::() + val.malloc_size_of() } -impl MemoryLruCache { +impl MemoryLruCache { /// Create a new cache with a maximum size in bytes. pub fn new(max_size: usize) -> Self { MemoryLruCache { diff --git a/crates/util/rlp-compress/Cargo.toml b/crates/util/rlp-compress/Cargo.toml index 4bd34bce1..e16c5b3de 100644 --- a/crates/util/rlp-compress/Cargo.toml +++ b/crates/util/rlp-compress/Cargo.toml @@ -4,6 +4,6 @@ version = "0.1.0" authors = ["Parity Technologies "] [dependencies] -rlp = { version = "0.3.0", features = ["ethereum"] } +rlp = { version = "0.4.6" } elastic-array = "0.10" lazy_static = "1.0" diff --git a/crates/util/rlp-derive/Cargo.toml b/crates/util/rlp-derive/Cargo.toml index 2087f7524..d843d75a5 100644 --- a/crates/util/rlp-derive/Cargo.toml +++ b/crates/util/rlp-derive/Cargo.toml @@ -13,4 +13,4 @@ quote = "0.6" proc-macro2 = "0.4" [dev-dependencies] -rlp = { version = "0.3.0", features = ["ethereum"] } +rlp = { version = "0.4.6" } diff --git a/crates/util/triehash-ethereum/Cargo.toml b/crates/util/triehash-ethereum/Cargo.toml index 5b6364297..929baf1d2 100644 --- a/crates/util/triehash-ethereum/Cargo.toml +++ b/crates/util/triehash-ethereum/Cargo.toml @@ -6,6 +6,6 @@ description = "Trie-root helpers, ethereum style" license = "GPL-3.0" [dependencies] -triehash = { version = "0.4.0", features = ["ethereum"] } -ethereum-types = "0.4" +triehash = { version = "0.5.0" } +ethereum-types = "0.9.2" keccak-hasher = { path = "../keccak-hasher" } diff --git a/crates/util/triehash-ethereum/src/lib.rs b/crates/util/triehash-ethereum/src/lib.rs index 0409d0432..029f59f79 100644 --- a/crates/util/triehash-ethereum/src/lib.rs +++ b/crates/util/triehash-ethereum/src/lib.rs @@ -55,7 +55,9 @@ where #[cfg(test)] mod tests { use super::{ordered_trie_root, sec_trie_root, trie_root}; + use ethereum_types::H256; use keccak_hasher::KeccakHasher; + use std::str::FromStr; use triehash; #[test] @@ -65,7 +67,8 @@ mod tests { b"A", b"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" as &[u8] )]), - "d23786fb4a010da3ce639d66d5e904a11dbc02746d1ce25029e53290cabf28ab".into() + H256::from_str("d23786fb4a010da3ce639d66d5e904a11dbc02746d1ce25029e53290cabf28ab") + .unwrap() ); } diff --git a/crates/util/version/Cargo.toml b/crates/util/version/Cargo.toml index 7fdef2e3b..2c0db378e 100644 --- a/crates/util/version/Cargo.toml +++ b/crates/util/version/Cargo.toml @@ -9,7 +9,7 @@ build = "build.rs" [dependencies] parity-bytes = "0.1" -rlp = { version = "0.3.0", features = ["ethereum"] } +rlp = { version = "0.4.6" } target_info = "0.1" [build-dependencies] diff --git a/crates/vm/builtin/Cargo.toml b/crates/vm/builtin/Cargo.toml index 540d179b0..45167eb96 100644 --- a/crates/vm/builtin/Cargo.toml +++ b/crates/vm/builtin/Cargo.toml @@ -9,15 +9,15 @@ edition = "2018" bn = { git = "https://github.com/paritytech/bn", default-features = false } byteorder = "1.3.2" eip-152 = { path = "../../util/EIP-152" } -ethereum-types = "0.4" +ethereum-types = "0.9.2" ethjson = { path = "../../ethjson" } ethkey = { path = "../../accounts/ethkey" } -keccak-hash = "0.1.0" +keccak-hash = "0.5.0" log = "0.4" macros = { path = "../../util/macros" } num = { version = "0.1", default-features = false, features = ["bigint"] } parity-bytes = "0.1" -parity-crypto = "0.4.0" +parity-crypto = { version = "0.6.2", features = [ "publickey" ] } eth_pairings = { git = "https://github.com/matter-labs/eip1962.git", default-features = false, features = ["eip_2537"], rev = "ece6cbabc41948db4200e41f0bfdab7ab94c7af8" } [dev-dependencies] diff --git a/crates/vm/builtin/src/lib.rs b/crates/vm/builtin/src/lib.rs index 5ba924772..3583c2d69 100644 --- a/crates/vm/builtin/src/lib.rs +++ b/crates/vm/builtin/src/lib.rs @@ -35,12 +35,14 @@ use eth_pairings::public_interface::eip2537::{ }; use ethereum_types::{H256, U256}; use ethjson; -use ethkey::{recover as ec_recover, Signature}; use keccak_hash::keccak; use log::{trace, warn}; use num::{BigUint, One, Zero}; use parity_bytes::BytesRef; -use parity_crypto::digest; +use parity_crypto::{ + digest, + publickey::{recover_allowing_all_zero_message, Signature, ZeroesAllowedMessage}, +}; /// Native implementation of a built-in contract. pub trait Implementation: Send + Sync { @@ -192,7 +194,7 @@ impl ModexpPricer { reader .read_exact(&mut buf[..]) .expect("reading from zero-extended memory cannot fail; qed"); - U256::from(H256::from_slice(&buf[..])) + U256::from_big_endian(&buf[..]) }; let base_len_u256 = read_len(); let exp_len_u256 = read_len(); @@ -210,7 +212,7 @@ impl ModexpPricer { reader .read_exact(&mut buf[(32 - len)..]) .expect("reading from zero-extended memory cannot fail; qed"); - U256::from(H256::from_slice(&buf[..])) + U256::from_big_endian(&buf[..]) }; (base_len_u256, exp_len_u256, exp_low, mod_len_u256) @@ -829,10 +831,16 @@ impl Implementation for EcRecover { let s = Signature::from_rsv(&r, &s, bit); if s.is_valid() { - if let Ok(p) = ec_recover(&s, &hash) { + // The builtin allows/requires all-zero messages to be valid to + // recover the public key. Use of such messages is disallowed in + // `rust-secp256k1` and this is a workaround for that. It is not an + // openethereum-level error to fail here; instead we return all + // zeroes and let the caller interpret that outcome. + let recovery_message = ZeroesAllowedMessage(hash); + if let Ok(p) = recover_allowing_all_zero_message(&s, recovery_message) { let r = keccak(p); output.write(0, &[0; 12]); - output.write(12, &r[12..r.len()]); + output.write(12, &r.as_bytes()[12..]); } } diff --git a/crates/vm/call-contract/Cargo.toml b/crates/vm/call-contract/Cargo.toml index 08066e988..da5606487 100644 --- a/crates/vm/call-contract/Cargo.toml +++ b/crates/vm/call-contract/Cargo.toml @@ -8,5 +8,5 @@ edition = "2018" [dependencies] types = { path = "../../ethcore/types", package = "common-types" } -ethereum-types = "0.4" +ethereum-types = "0.9.2" bytes = { version = "0.1", package = "parity-bytes" } diff --git a/crates/vm/evm/Cargo.toml b/crates/vm/evm/Cargo.toml index e59bf7e6d..d79bf5f87 100644 --- a/crates/vm/evm/Cargo.toml +++ b/crates/vm/evm/Cargo.toml @@ -7,12 +7,12 @@ authors = ["Parity Technologies "] [dependencies] bit-set = "0.4" parity-bytes = "0.1" -ethereum-types = "0.4" -heapsize = "0.4" +ethereum-types = "0.9.2" lazy_static = "1.0" log = "0.4" vm = { path = "../vm" } -keccak-hash = "0.1" +keccak-hash = "0.5.0" +parity-util-mem = "0.7" parking_lot = "0.7" memory-cache = { path = "../../util/memory-cache" } ethcore-builtin = { path = "../builtin" } diff --git a/crates/vm/evm/benches/basic.rs b/crates/vm/evm/benches/basic.rs index f6b7fa472..4d2d8e4a6 100644 --- a/crates/vm/evm/benches/basic.rs +++ b/crates/vm/evm/benches/basic.rs @@ -21,7 +21,6 @@ extern crate criterion; extern crate bit_set; extern crate ethereum_types; extern crate evm; -extern crate heapsize; extern crate keccak_hash as hash; extern crate memory_cache; extern crate parity_bytes as bytes; diff --git a/crates/vm/evm/src/interpreter/gasometer.rs b/crates/vm/evm/src/interpreter/gasometer.rs index 8a710069e..aec51b4ec 100644 --- a/crates/vm/evm/src/interpreter/gasometer.rs +++ b/crates/vm/evm/src/interpreter/gasometer.rs @@ -15,7 +15,7 @@ // along with OpenEthereum. If not, see . use super::u256_to_address; -use ethereum_types::{Address, H256, U256}; +use ethereum_types::{Address, BigEndianHash, U256}; use std::cmp; use super::stack::VecStack; @@ -139,14 +139,14 @@ impl Gasometer { if schedule.eip1706 && self.current_gas <= Gas::from(schedule.call_stipend) { return Err(vm::Error::OutOfGas); } - let key = H256::from(stack.peek(0)); + let key = BigEndianHash::from_uint(stack.peek(0)); let newval = stack.peek(1); - let val = U256::from(&*ext.storage_at(&key)?); + let val = ext.storage_at(&key)?.into_uint(); let is_cold = !ext.al_contains_storage_key(current_address, &key); let gas = if schedule.eip1283 { - let orig = U256::from(&*ext.initial_storage_at(&key)?); + let orig = ext.initial_storage_at(&key)?.into_uint(); calculate_eip1283_eip2929_sstore_gas(schedule, is_cold, &orig, &val, &newval) } else { if val.is_zero() && !newval.is_zero() { @@ -161,7 +161,7 @@ impl Gasometer { Request::Gas(gas.into()) } instructions::SLOAD => { - let key = H256::from(stack.peek(0)); + let key = BigEndianHash::from_uint(stack.peek(0)); let gas = if ext.al_is_enabled() { if ext.al_contains_storage_key(current_address, &key) { schedule.warm_storage_read_cost diff --git a/crates/vm/evm/src/interpreter/mod.rs b/crates/vm/evm/src/interpreter/mod.rs index 418c3572a..302013f5e 100644 --- a/crates/vm/evm/src/interpreter/mod.rs +++ b/crates/vm/evm/src/interpreter/mod.rs @@ -24,7 +24,7 @@ mod shared_cache; mod stack; use bytes::Bytes; -use ethereum_types::{Address, H256, U256}; +use ethereum_types::{Address, BigEndianHash, H256, U256}; use hash::keccak; use num_bigint::BigUint; use std::{cmp, marker::PhantomData, mem, sync::Arc}; @@ -694,7 +694,7 @@ impl Interpreter { let address_scheme = match instruction { instructions::CREATE => CreateContractAddress::FromSenderAndNonce, instructions::CREATE2 => CreateContractAddress::FromSenderSaltAndCodeHash( - self.stack.pop_back().into(), + BigEndianHash::from_uint(&self.stack.pop_back()), ), _ => unreachable!("instruction can only be CREATE/CREATE2 checked above; qed"), }; @@ -940,7 +940,7 @@ impl Interpreter { .stack .pop_n(no_of_topics) .iter() - .map(H256::from) + .map(BigEndianHash::from_uint) .collect(); ext.log(topics, self.mem.read_slice(offset, size))?; } @@ -1003,23 +1003,23 @@ impl Interpreter { let offset = self.stack.pop_back(); let size = self.stack.pop_back(); let k = keccak(self.mem.read_slice(offset, size)); - self.stack.push(U256::from(&*k)); + self.stack.push(k.into_uint()); } instructions::SLOAD => { - let key = H256::from(&self.stack.pop_back()); - let word = U256::from(&*ext.storage_at(&key)?); + let key = BigEndianHash::from_uint(&self.stack.pop_back()); + let word = ext.storage_at(&key)?.into_uint(); self.stack.push(word); ext.al_insert_storage_key(self.params.address, key); } instructions::SSTORE => { - let key = H256::from(&self.stack.pop_back()); + let key = BigEndianHash::from_uint(&self.stack.pop_back()); let val = self.stack.pop_back(); - let current_val = U256::from(&*ext.storage_at(&key)?); + let current_val = ext.storage_at(&key)?.into_uint(); // Increase refund for clear if ext.schedule().eip1283 { - let original_val = U256::from(&*ext.initial_storage_at(&key)?); + let original_val = ext.initial_storage_at(&key)?.into_uint(); gasometer::handle_eip1283_sstore_clears_refund( ext, &original_val, @@ -1032,7 +1032,7 @@ impl Interpreter { ext.add_sstore_refund(sstore_clears_schedule); } } - ext.set_storage(key, H256::from(&val))?; + ext.set_storage(key, BigEndianHash::from_uint(&val))?; ext.al_insert_storage_key(self.params.address, key); } instructions::PC => { @@ -1099,7 +1099,7 @@ impl Interpreter { let hash = ext.extcodehash(&address)?.unwrap_or_else(H256::zero); ext.al_insert_address(address); - self.stack.push(U256::from(hash)); + self.stack.push(hash.into_uint()); } instructions::CALLDATACOPY => { Self::copy_data_to_memory( @@ -1142,7 +1142,7 @@ impl Interpreter { instructions::BLOCKHASH => { let block_number = self.stack.pop_back(); let block_hash = ext.blockhash(&block_number); - self.stack.push(U256::from(&*block_hash)); + self.stack.push(block_hash.into_uint()); } instructions::COINBASE => { self.stack @@ -1528,16 +1528,18 @@ fn set_sign(value: U256, sign: bool) -> U256 { #[inline] fn u256_to_address(value: &U256) -> Address { - Address::from(H256::from(value)) + let addr: H256 = BigEndianHash::from_uint(value); + Address::from(addr) } #[inline] fn address_to_u256(value: Address) -> U256 { - U256::from(&*H256::from(value)) + H256::from(value).into_uint() } #[cfg(test)] mod tests { + use ethereum_types::Address; use factory::Factory; use rustc_hex::FromHex; use std::sync::Arc; @@ -1557,13 +1559,14 @@ mod tests { let code = "7feeffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff006000527faaffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffaa6020526000620f120660406000601773945304eb96065b2a98b57a48a06ae28d285a71b56101f4f1600055".from_hex().unwrap(); let mut params = ActionParams::default(); - params.address = 5.into(); + params.address = Address::from_low_u64_be(5); params.gas = 300_000.into(); params.gas_price = 1.into(); params.value = ActionValue::Transfer(100_000.into()); params.code = Some(Arc::new(code)); let mut ext = FakeExt::new(); - ext.balances.insert(5.into(), 1_000_000_000.into()); + ext.balances + .insert(Address::from_low_u64_be(5), 1_000_000_000.into()); ext.tracing = true; let gas_left = { @@ -1580,12 +1583,13 @@ mod tests { let code = "6001600160000360003e00".from_hex().unwrap(); let mut params = ActionParams::default(); - params.address = 5.into(); + params.address = Address::from_low_u64_be(5); params.gas = 300_000.into(); params.gas_price = 1.into(); params.code = Some(Arc::new(code)); let mut ext = FakeExt::new_byzantium(); - ext.balances.insert(5.into(), 1_000_000_000.into()); + ext.balances + .insert(Address::from_low_u64_be(5), 1_000_000_000.into()); ext.tracing = true; let err = { diff --git a/crates/vm/evm/src/interpreter/shared_cache.rs b/crates/vm/evm/src/interpreter/shared_cache.rs index 459bb1a90..cc25ff464 100644 --- a/crates/vm/evm/src/interpreter/shared_cache.rs +++ b/crates/vm/evm/src/interpreter/shared_cache.rs @@ -18,36 +18,29 @@ use super::super::instructions::{self, Instruction}; use bit_set::BitSet; use ethereum_types::H256; use hash::KECCAK_EMPTY; -use heapsize::HeapSizeOf; use memory_cache::MemoryLruCache; +use parity_util_mem::{MallocSizeOf, MallocSizeOfOps}; use parking_lot::Mutex; use std::sync::Arc; const DEFAULT_CACHE_SIZE: usize = 4 * 1024 * 1024; -// stub for a HeapSizeOf implementation. #[derive(Clone)] struct Bits(Arc); -impl HeapSizeOf for Bits { - fn heap_size_of_children(&self) -> usize { +impl MallocSizeOf for Bits { + fn size_of(&self, _ops: &mut MallocSizeOfOps) -> usize { // dealing in bits here self.0.capacity() * 8 } } -#[derive(Clone)] +#[derive(MallocSizeOf, Clone)] struct CacheItem { jump_destination: Bits, sub_entrypoint: Bits, } -impl HeapSizeOf for CacheItem { - fn heap_size_of_children(&self) -> usize { - self.jump_destination.heap_size_of_children() + self.sub_entrypoint.heap_size_of_children() - } -} - /// Global cache for EVM interpreter pub struct SharedCache { jump_destinations: Mutex>, diff --git a/crates/vm/evm/src/lib.rs b/crates/vm/evm/src/lib.rs index 144cbf895..66431fa3d 100644 --- a/crates/vm/evm/src/lib.rs +++ b/crates/vm/evm/src/lib.rs @@ -19,11 +19,11 @@ extern crate bit_set; extern crate ethcore_builtin as builtin; extern crate ethereum_types; -extern crate heapsize; extern crate keccak_hash as hash; extern crate memory_cache; extern crate num_bigint; extern crate parity_bytes as bytes; +extern crate parity_util_mem; extern crate parking_lot; extern crate vm; diff --git a/crates/vm/evm/src/tests.rs b/crates/vm/evm/src/tests.rs index 14fa06941..32daa37e1 100644 --- a/crates/vm/evm/src/tests.rs +++ b/crates/vm/evm/src/tests.rs @@ -334,7 +334,7 @@ fn test_blockhash(factory: super::Factory) { }; assert_eq!(gas_left, U256::from(79_974)); - assert_eq!(ext.store.get(&H256::new()).unwrap(), &blockhash); + assert_eq!(ext.store.get(&H256::default()).unwrap(), &blockhash); } evm_test! {test_calldataload: test_calldataload_int} @@ -1207,8 +1207,8 @@ evm_test! {test_calls: test_calls_int} fn test_calls(factory: super::Factory) { let code = "600054602d57600160005560006000600060006050610998610100f160006000600060006050610998610100f25b".from_hex().unwrap(); - let address = Address::from(0x155); - let code_address = Address::from(0x998); + let address = Address::from_low_u64_be(0x155); + let code_address = Address::from_low_u64_be(0x998); let mut params = ActionParams::default(); params.gas = U256::from(150_000); params.code = Some(Arc::new(code)); @@ -1259,7 +1259,7 @@ evm_test! {test_create_in_staticcall: test_create_in_staticcall_int} fn test_create_in_staticcall(factory: super::Factory) { let code = "600060006064f000".from_hex().unwrap(); - let address = Address::from(0x155); + let address = Address::from_low_u64_be(0x155); let mut params = ActionParams::default(); params.gas = U256::from(100_000); params.code = Some(Arc::new(code)); @@ -1579,12 +1579,12 @@ fn test_access_list_ext_at_precompiles(factory: super::Factory) { params.gas = U256::from(8653); params.code = Some(Arc::new(code)); let mut ext = FakeExt::new_berlin( - Address::from("0x0000000000000000000000000000000000000000"), - Address::from("0x000000000000000000000000636F6E7472616374"), + Address::from_str("0000000000000000000000000000000000000000").unwrap(), + Address::from_str("000000000000000000000000636F6E7472616374").unwrap(), &[ - Address::from("0x0000000000000000000000000000000000000001"), - Address::from("0x0000000000000000000000000000000000000002"), - Address::from("0x0000000000000000000000000000000000000003"), + Address::from_str("0000000000000000000000000000000000000001").unwrap(), + Address::from_str("0000000000000000000000000000000000000002").unwrap(), + Address::from_str("0000000000000000000000000000000000000003").unwrap(), ], ); let gas_left = { @@ -1603,8 +1603,8 @@ fn test_access_list_extcodecopy_twice(factory: super::Factory) { params.gas = U256::from(2835); params.code = Some(Arc::new(code)); let mut ext = FakeExt::new_berlin( - Address::from("0x0000000000000000000000000000000000000000"), - Address::from("0x000000000000000000000000636F6E7472616374"), + Address::from_str("0000000000000000000000000000000000000000").unwrap(), + Address::from_str("000000000000000000000000636F6E7472616374").unwrap(), &[], ); let gas_left = { @@ -1629,8 +1629,8 @@ fn test_access_list_sload_sstore(factory: super::Factory) { params.gas = U256::from(44529); params.code = Some(Arc::new(code)); let mut ext = FakeExt::new_berlin( - Address::from("0x0000000000000000000000000000000000000000"), - Address::from("0x000000000000000000000000636F6E7472616374"), + Address::from_str("0000000000000000000000000000000000000000").unwrap(), + Address::from_str("000000000000000000000000636F6E7472616374").unwrap(), &[], ); let gas_left = { @@ -1649,9 +1649,9 @@ fn test_access_list_cheap_expensive_cheap(factory: super::Factory) { params.gas = U256::from(2869); params.code = Some(Arc::new(code)); let mut ext = FakeExt::new_berlin( - Address::from("0x0000000000000000000000000000000000000000"), - Address::from("0x000000000000000000000000636F6E7472616374"), - &[Address::from("0x0000000000000000000000000000000000000004")], + Address::from_str("0000000000000000000000000000000000000000").unwrap(), + Address::from_str("000000000000000000000000636F6E7472616374").unwrap(), + &[Address::from_str("0000000000000000000000000000000000000004").unwrap()], ); let gas_left = { let vm = factory.create(params, ext.schedule(), ext.depth()); @@ -1705,7 +1705,7 @@ fn assert_set_contains(set: &HashSet, val: fn assert_store(ext: &FakeExt, pos: u64, val: &str) { assert_eq!( - ext.store.get(&H256::from(pos)).unwrap(), + ext.store.get(&H256::from_low_u64_be(pos)).unwrap(), &H256::from_str(val).unwrap() ); } diff --git a/crates/vm/vm/Cargo.toml b/crates/vm/vm/Cargo.toml index 70a7056b3..ece0197c4 100644 --- a/crates/vm/vm/Cargo.toml +++ b/crates/vm/vm/Cargo.toml @@ -6,8 +6,8 @@ authors = ["Parity Technologies "] [dependencies] parity-bytes = "0.1" -ethereum-types = "0.4" +ethereum-types = "0.9.2" patricia-trie-ethereum = { path = "../../db/patricia-trie-ethereum" } ethjson = { path = "../../ethjson" } -rlp = { version = "0.3.0", features = ["ethereum"] } -keccak-hash = "0.1" +rlp = { version = "0.4.6" } +keccak-hash = "0.5.0" diff --git a/crates/vm/vm/src/access_list.rs b/crates/vm/vm/src/access_list.rs index 3d3545604..aa6c71f9a 100644 --- a/crates/vm/vm/src/access_list.rs +++ b/crates/vm/vm/src/access_list.rs @@ -182,12 +182,16 @@ mod tests { #[test] fn default_disabled_accesslist_does_nothing() { let mut access_list = AccessList::default(); - access_list.insert_address(Address::from(1)); - access_list.insert_storage_key(Address::from(2), H256::from(3)); - assert_eq!(false, access_list.contains_address(&Address::from(1))); + access_list.insert_address(Address::from_low_u64_be(1)); + access_list.insert_storage_key(Address::from_low_u64_be(2), H256::from_low_u64_be(3)); assert_eq!( false, - access_list.contains_storage_key(&Address::from(2), &H256::from(3)) + access_list.contains_address(&Address::from_low_u64_be(1)) + ); + assert_eq!( + false, + access_list + .contains_storage_key(&Address::from_low_u64_be(2), &H256::from_low_u64_be(3)) ); } @@ -196,12 +200,16 @@ mod tests { let mut access_list = AccessList::default(); access_list.enable(); assert_eq!(true, access_list.is_enabled()); - access_list.insert_address(Address::from(1)); - access_list.insert_storage_key(Address::from(2), H256::from(3)); - assert_eq!(true, access_list.contains_address(&Address::from(1))); + access_list.insert_address(Address::from_low_u64_be(1)); + access_list.insert_storage_key(Address::from_low_u64_be(2), H256::from_low_u64_be(3)); assert_eq!( true, - access_list.contains_storage_key(&Address::from(2), &H256::from(3)) + access_list.contains_address(&Address::from_low_u64_be(1)) + ); + assert_eq!( + true, + access_list + .contains_storage_key(&Address::from_low_u64_be(2), &H256::from_low_u64_be(3)) ); } @@ -210,51 +218,74 @@ mod tests { let mut access_list = AccessList::default(); access_list.enable(); assert_eq!(true, access_list.is_enabled()); - access_list.insert_address(Address::from(1)); - access_list.insert_storage_key(Address::from(2), H256::from(3)); + access_list.insert_address(Address::from_low_u64_be(1)); + access_list.insert_storage_key(Address::from_low_u64_be(2), H256::from_low_u64_be(3)); let access_list_call = access_list.clone(); - assert_eq!(true, access_list_call.contains_address(&Address::from(1))); assert_eq!( true, - access_list_call.contains_storage_key(&Address::from(2), &H256::from(3)) + access_list_call.contains_address(&Address::from_low_u64_be(1)) + ); + assert_eq!( + true, + access_list_call + .contains_storage_key(&Address::from_low_u64_be(2), &H256::from_low_u64_be(3)) + ); + access_list.insert_address(Address::from_low_u64_be(4)); + assert_eq!( + true, + access_list_call.contains_address(&Address::from_low_u64_be(4)) ); - access_list.insert_address(Address::from(4)); - assert_eq!(true, access_list_call.contains_address(&Address::from(4))); - assert_eq!(true, access_list.contains_address(&Address::from(4))); + assert_eq!( + true, + access_list.contains_address(&Address::from_low_u64_be(4)) + ); } #[test] fn cloned_accesslist_rollbacks_in_parent() { let mut access_list = AccessList::default(); access_list.enable(); assert_eq!(true, access_list.is_enabled()); - access_list.insert_address(Address::from(1)); - access_list.insert_storage_key(Address::from(2), H256::from(3)); + access_list.insert_address(Address::from_low_u64_be(1)); + access_list.insert_storage_key(Address::from_low_u64_be(2), H256::from_low_u64_be(3)); let mut access_list_call = access_list.clone(); - access_list_call.insert_address(Address::from(1)); - access_list_call.insert_storage_key(Address::from(2), H256::from(3)); - access_list_call.insert_address(Address::from(4)); + access_list_call.insert_address(Address::from_low_u64_be(1)); + access_list_call.insert_storage_key(Address::from_low_u64_be(2), H256::from_low_u64_be(3)); + access_list_call.insert_address(Address::from_low_u64_be(4)); let mut access_list_call_call = access_list.clone(); - access_list_call_call.insert_address(Address::from(1)); - access_list_call_call.insert_storage_key(Address::from(2), H256::from(3)); - access_list_call_call.insert_address(Address::from(5)); - access_list_call_call.insert_storage_key(Address::from(6), H256::from(7)); + access_list_call_call.insert_address(Address::from_low_u64_be(1)); + access_list_call_call + .insert_storage_key(Address::from_low_u64_be(2), H256::from_low_u64_be(3)); + access_list_call_call.insert_address(Address::from_low_u64_be(5)); + access_list_call_call + .insert_storage_key(Address::from_low_u64_be(6), H256::from_low_u64_be(7)); access_list_call.rollback(); - assert_eq!(true, access_list.contains_address(&Address::from(1))); - assert_eq!(false, access_list.contains_address(&Address::from(4))); - assert_eq!(false, access_list.contains_address(&Address::from(5))); assert_eq!( true, - access_list.contains_storage_key(&Address::from(2), &H256::from(3)) + access_list.contains_address(&Address::from_low_u64_be(1)) ); assert_eq!( false, - access_list.contains_storage_key(&Address::from(6), &H256::from(7)) + access_list.contains_address(&Address::from_low_u64_be(4)) + ); + assert_eq!( + false, + access_list.contains_address(&Address::from_low_u64_be(5)) + ); + assert_eq!( + true, + access_list + .contains_storage_key(&Address::from_low_u64_be(2), &H256::from_low_u64_be(3)) + ); + assert_eq!( + false, + access_list + .contains_storage_key(&Address::from_low_u64_be(6), &H256::from_low_u64_be(7)) ); } } diff --git a/crates/vm/vm/src/action_params.rs b/crates/vm/vm/src/action_params.rs index b9aaf38bc..f2076e6e0 100644 --- a/crates/vm/vm/src/action_params.rs +++ b/crates/vm/vm/src/action_params.rs @@ -98,11 +98,11 @@ impl Default for ActionParams { /// Returns default ActionParams initialized with zeros fn default() -> ActionParams { ActionParams { - code_address: Address::new(), + code_address: Address::default(), code_hash: Some(KECCAK_EMPTY), - address: Address::new(), - sender: Address::new(), - origin: Address::new(), + address: Address::default(), + sender: Address::default(), + origin: Address::default(), gas: U256::zero(), gas_price: U256::zero(), value: ActionValue::Transfer(U256::zero()), @@ -119,7 +119,7 @@ impl From for ActionParams { fn from(t: ethjson::vm::Transaction) -> Self { let address: Address = t.address.into(); ActionParams { - code_address: Address::new(), + code_address: Address::default(), code_hash: Some(keccak(&*t.code)), address: address, sender: t.sender.into(), diff --git a/crates/vm/vm/src/tests.rs b/crates/vm/vm/src/tests.rs index 6bcb46fd2..11daf4be9 100644 --- a/crates/vm/vm/src/tests.rs +++ b/crates/vm/vm/src/tests.rs @@ -145,11 +145,11 @@ impl FakeExt { impl Ext for FakeExt { fn initial_storage_at(&self, _key: &H256) -> Result { - Ok(H256::new()) + Ok(H256::default()) } fn storage_at(&self, key: &H256) -> Result { - Ok(self.store.get(key).unwrap_or(&H256::new()).clone()) + Ok(self.store.get(key).unwrap_or(&H256::default()).clone()) } fn set_storage(&mut self, key: H256, value: H256) -> Result<()> { @@ -174,7 +174,10 @@ impl Ext for FakeExt { } fn blockhash(&mut self, number: &U256) -> H256 { - self.blockhashes.get(number).unwrap_or(&H256::new()).clone() + self.blockhashes + .get(number) + .unwrap_or(&H256::default()) + .clone() } fn create( diff --git a/crates/vm/wasm/Cargo.toml b/crates/vm/wasm/Cargo.toml index e724a6a4c..2b1bafca2 100644 --- a/crates/vm/wasm/Cargo.toml +++ b/crates/vm/wasm/Cargo.toml @@ -6,7 +6,7 @@ authors = ["Parity Technologies "] [dependencies] byteorder = "1.0" -ethereum-types = "0.4" +ethereum-types = "0.9.2" log = "0.4" parity-wasm = "0.31" libc = "0.2" diff --git a/crates/vm/wasm/src/runtime.rs b/crates/vm/wasm/src/runtime.rs index 386ae577b..b4de3f77c 100644 --- a/crates/vm/wasm/src/runtime.rs +++ b/crates/vm/wasm/src/runtime.rs @@ -15,7 +15,7 @@ // along with OpenEthereum. If not, see . use super::panic_payload; -use ethereum_types::{Address, H256, U256}; +use ethereum_types::{Address, BigEndianHash, H256, U256}; use std::cmp; use vm::{self, CallType}; use wasmi::{ @@ -171,7 +171,7 @@ impl<'a> Runtime<'a> { let mut buf = [0u8; 32]; self.memory.get_into(ptr, &mut buf[..])?; - Ok(H256::from(&buf[..])) + Ok(H256::from_slice(&buf[..])) } /// Loads 160-bit hash (Ethereum address) from the specified sandboxed memory pointer @@ -179,7 +179,7 @@ impl<'a> Runtime<'a> { let mut buf = [0u8; 20]; self.memory.get_into(ptr, &mut buf[..])?; - Ok(Address::from(&buf[..])) + Ok(Address::from_slice(&buf[..])) } /// Loads 256-bit integer represented with bigendian from the specified sandboxed memory pointer @@ -275,7 +275,7 @@ impl<'a> Runtime<'a> { self.adjusted_charge(|schedule| schedule.sload_gas as u64)?; - self.memory.set(val_ptr as u32, &*val)?; + self.memory.set(val_ptr as u32, val.as_bytes())?; Ok(()) } @@ -532,14 +532,14 @@ impl<'a> Runtime<'a> { fn return_address_ptr(&mut self, ptr: u32, val: Address) -> Result<()> { self.charge(|schedule| schedule.wasm().static_address as u64)?; - self.memory.set(ptr, &*val)?; + self.memory.set(ptr, val.as_bytes())?; Ok(()) } fn return_u256_ptr(&mut self, ptr: u32, val: U256) -> Result<()> { - let value: H256 = val.into(); + let value: H256 = BigEndianHash::from_uint(&val); self.charge(|schedule| schedule.wasm().static_u256 as u64)?; - self.memory.set(ptr, &*value)?; + self.memory.set(ptr, value.as_bytes())?; Ok(()) } @@ -573,7 +573,7 @@ impl<'a> Runtime<'a> { .expect("Trap is false; trap error will not happen; qed") { vm::ContractCreateResult::Created(address, gas_left) => { - self.memory.set(result_ptr, &*address)?; + self.memory.set(result_ptr, address.as_bytes())?; self.gas_counter = self.gas_limit - // this cannot overflow, since initial gas is in [0..u64::max) range, // and gas_left cannot be bigger @@ -646,7 +646,7 @@ impl<'a> Runtime<'a> { trace!(target: "wasm", "runtime: CREATE2"); let endowment = self.u256_at(args.nth_checked(0)?)?; trace!(target: "wasm", " val: {:?}", endowment); - let salt: H256 = self.u256_at(args.nth_checked(1)?)?.into(); + let salt: H256 = BigEndianHash::from_uint(&self.u256_at(args.nth_checked(1)?)?); trace!(target: "wasm", " salt: {:?}", salt); let code_ptr: u32 = args.nth_checked(2)?; trace!(target: "wasm", " code_ptr: {:?}", code_ptr); @@ -704,7 +704,7 @@ impl<'a> Runtime<'a> { pub fn blockhash(&mut self, args: RuntimeArgs) -> Result<()> { self.adjusted_charge(|schedule| schedule.blockhash_gas as u64)?; let hash = self.ext.blockhash(&U256::from(args.nth_checked::(0)?)); - self.memory.set(args.nth_checked(1)?, &*hash)?; + self.memory.set(args.nth_checked(1)?, hash.as_bytes())?; Ok(()) } @@ -794,7 +794,7 @@ impl<'a> Runtime<'a> { *topics.get_mut(i as usize) .expect("topics is resized to `topic_count`, i is in 0..topic count iterator, get_mut uses i as an indexer, get_mut cannot fail; qed") - = H256::from(&self.memory.get(offset, 32)?[..]); + = H256::from_slice(&self.memory.get(offset, 32)?[..]); } self.ext .log(topics, &self.memory.get(data_ptr, data_len as usize)?)