diff --git a/.github/workflows/build_image_ghcr.yml b/.github/workflows/build_image_ghcr.yml index a8df54934..49032aef4 100644 --- a/.github/workflows/build_image_ghcr.yml +++ b/.github/workflows/build_image_ghcr.yml @@ -2,7 +2,7 @@ name: Build ghcr.io image on: push: - branches: [ 'main', '*docker*', '*dev*' ] + branches: [ 'main', '*dev*', '*alpha*', '*beta*', '*rc*' ] tags: workflow_dispatch: inputs: @@ -103,7 +103,7 @@ jobs: - name: Modify the Axon image of in devtools/chain/docker-compose.yml env: AXON_IMAGE: "${{ needs.build-amd64-image-to-ghcr.outputs.image_name }}:${{ needs.build-amd64-image-to-ghcr.outputs.image_tag }}" - uses: mikefarah/yq@v4.40.3 + uses: mikefarah/yq@v4.40.4 with: cmd: yq -i '.services.axon.image = "${{ env.AXON_IMAGE }}"' 'devtools/chain/docker-compose.yml' diff --git a/CHANGELOG.md b/CHANGELOG.md index 9ad4b5023..4c4caa24e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,6 @@ # CHANGELOG -## Unreleased (v0.3.0-dev) +## v0.3.0-beta ### BREAKING CHANGES * refactor!: remove the limitation of set ckb related info ([\#1517](https://github.com/axonweb3/axon/pull/1517)) @@ -11,10 +11,8 @@ ### FEATURES -- Migrate axon-tools to axon repo in - ([\#1519](https://github.com/axonweb3/axon/pull/1519)) and ([\#1545](https://github.com/axonweb3/axon/pull/1545)) -- Add no-std feature of axon-tools, using use ckb-blst for riscv64 - ([\#1532](https://github.com/axonweb3/axon/pull/1532)) and ([\#1563](https://github.com/axonweb3/axon/pull/1563)) +* Migrate axon-tools to axon repo ([\#1519](https://github.com/axonweb3/axon/pull/1519), [\#1545](https://github.com/axonweb3/axon/pull/1545)) +* Add no-std feature of axon-tools, using use ckb-blst for riscv64 (([\#1532](https://github.com/axonweb3/axon/pull/1532)), [\#1563](https://github.com/axonweb3/axon/pull/1563)) * feat: add `eth_getProof` JSON RPC API ([\#1540](https://github.com/axonweb3/axon/pull/1540), [\#1549](https://github.com/axonweb3/axon/pull/1549), [\#1564](https://github.com/axonweb3/axon/pull/1564), [\#1571](https://github.com/axonweb3/axon/pull/1571)) * feat: add `ckb_blake2b` precompile contract ([\#1555](https://github.com/axonweb3/axon/pull/1555)) * feat: add ckb mbt proof verify precompile contract ([\#1578](https://github.com/axonweb3/axon/pull/1578)) @@ -23,39 +21,36 @@ ### BUG FIXES -- Fix value of gas in JSON RPC Transaction should be gas limit - ([\#1530](https://github.com/axonweb3/axon/pull/1530)) +* Fix value of gas in JSON RPC Transaction should be gas limit ([\#1530](https://github.com/axonweb3/axon/pull/1530)) * fix: check mempool when call `eth_getTransactionByHash` ([\#1526](https://github.com/axonweb3/axon/pull/1526)) * fix: use a same default value for `max_payload_size` ([\#1548](https://github.com/axonweb3/axon/pull/1548)) * fix: rlp decode of `SignedTransction` with interoperation signature ([\#1533](https://github.com/axonweb3/axon/pull/1533)) * fix: get genesis block proposal may panic ([\#1554](https://github.com/axonweb3/axon/pull/1554)) * fix: field `chainId` should be acceptable for `eth_estimateGas` ([\#1601](https://github.com/axonweb3/axon/pull/1601)) -* fix: enable estimation mode for query apis ([\#1603](https://github.com/axonweb3/axon/pull/1603)) * fix: get pending tx count by number ([\#1605](https://github.com/axonweb3/axon/pull/1605)) * fix: duplicated calculation in `eth_estimateGas` ([\#1599](https://github.com/axonweb3/axon/pull/1599), [\#1609](https://github.com/axonweb3/axon/pull/1609)) - +* fix: gas limit too low error ([\#1625](https://github.com/axonweb3/axon/pull/1625)) ### CODE REFACTORS -- Add more details for JSON RPC errors ([\#1495](https://github.com/axonweb3/axon/pull/1495)) -- Remove the limitation of set CKB related info in system contract ([\#1517](https://github.com/axonweb3/axon/pull/1517)) +* Add more details for JSON RPC errors ([\#1495](https://github.com/axonweb3/axon/pull/1495)) +* Remove the limitation of set CKB related info in system contract ([\#1517](https://github.com/axonweb3/axon/pull/1517)) * Remove empty crates ([\#1521](https://github.com/axonweb3/axon/pull/1521)) -- Enhance readability of output logs and errors ([\#1528](https://github.com/axonweb3/axon/pull/1528)) -- Change default db cache size ([\#1531](https://github.com/axonweb3/axon/pull/1531)) +* Enhance readability of output logs and errors ([\#1528](https://github.com/axonweb3/axon/pull/1528)) +* Change default db cache size ([\#1531](https://github.com/axonweb3/axon/pull/1531)) * config(blockscan): update the env variables of Axon's explorer ([\#1550](https://github.com/axonweb3/axon/pull/1550)) * Refactor fn is_hardfork_enabled ([\#1538](https://github.com/axonweb3/axon/pull/1538)) * Remove duplicated code to protect ([\#1556](https://github.com/axonweb3/axon/pull/1556)) * Update CkbType.sol and ImageCell.sol for consistent ABI output with json file in ([\#1558](https://github.com/axonweb3/axon/pull/1558), [\#1567](https://github.com/axonweb3/axon/pull/1567)) -* ci: refactor OpenZeppelin tests and entry_workflow.yml ([\#1610](https://github.com/axonweb3/axon/pull/1610)) - +* refactor: rename Proof.block_hash serde to proposal_hash ([\#1618](https://github.com/axonweb3/axon/pull/1618)) +* refactor: forbid call eth_getStorageAt to system contract accounts ([\#1619](https://github.com/axonweb3/axon/pull/1619)) +* refactor: change estimate gas calculation logic ([\#1603](https://github.com/axonweb3/axon/pull/1603), [\#1626](https://github.com/axonweb3/axon/pull/1626)) ### CHORE * ci: adjust CI after migrating the test projects ([\#1513](https://github.com/axonweb3/axon/pull/1513)) * chore: make blst portable ([\#1520](https://github.com/axonweb3/axon/pull/1520)) * ci: run unit tests in separate processes ([\#1559](https://github.com/axonweb3/axon/pull/1559)) - - -**Full Changelog**: https://github.com/axonweb3/axon/compare/v0.2.0-beta.2...v0.3.0-dev +* ci: refactor OpenZeppelin tests and entry_workflow.yml ([\#1610](https://github.com/axonweb3/axon/pull/1610)) ## v0.2.0-beta.2 diff --git a/Cargo.lock b/Cargo.lock index 11c9030fa..7a375eab7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -227,7 +227,7 @@ checksum = "bc00ceb34980c03614e35a3a4e218276a0a824e911d07651cd0d858a51e8c0f0" dependencies = [ "proc-macro2", "quote", - "syn 2.0.38", + "syn 2.0.39", ] [[package]] @@ -272,7 +272,7 @@ checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" [[package]] name = "axon" -version = "0.3.0-alpha" +version = "0.3.0-beta" dependencies = [ "axon-protocol", "clap 4.4.6", @@ -518,7 +518,7 @@ dependencies = [ "regex", "rustc-hash", "shlex", - "syn 2.0.38", + "syn 2.0.39", "which", ] @@ -1469,7 +1469,7 @@ dependencies = [ "heck", "proc-macro2", "quote", - "syn 2.0.38", + "syn 2.0.39", ] [[package]] @@ -1902,7 +1902,7 @@ dependencies = [ "hasher", "lazy_static", "log", - "lru 0.12.0", + "lru 0.12.1", "molecule", "parking_lot 0.12.1", "revm", @@ -2073,7 +2073,7 @@ dependencies = [ "futures", "lazy_static", "log", - "lru 0.12.0", + "lru 0.12.1", "num-traits", "parking_lot 0.12.1", ] @@ -2382,7 +2382,7 @@ checksum = "67e77553c4162a157adbf834ebae5b415acbecbeafc7a74b0e886657506a7611" dependencies = [ "proc-macro2", "quote", - "syn 2.0.38", + "syn 2.0.39", ] [[package]] @@ -3001,7 +3001,7 @@ dependencies = [ "reqwest", "serde", "serde_json", - "syn 2.0.38", + "syn 2.0.39", "toml 0.7.3", "walkdir", ] @@ -3019,7 +3019,7 @@ dependencies = [ "proc-macro2", "quote", "serde_json", - "syn 2.0.38", + "syn 2.0.39", ] [[package]] @@ -3045,7 +3045,7 @@ dependencies = [ "serde", "serde_json", "strum", - "syn 2.0.38", + "syn 2.0.39", "tempfile", "thiserror", "tiny-keccak", @@ -3483,7 +3483,7 @@ checksum = "89ca545a94061b6365f2c7355b4b32bd20df3ff95f02da9329b34ccc3bd6ee72" dependencies = [ "proc-macro2", "quote", - "syn 2.0.38", + "syn 2.0.39", ] [[package]] @@ -4198,9 +4198,9 @@ dependencies = [ [[package]] name = "jsonrpsee" -version = "0.20.1" +version = "0.20.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ad9b31183a8bcbe843e32ca8554ad2936633548d95a7bb6a8e14c767dea6b05" +checksum = "affdc52f7596ccb2d7645231fc6163bb314630c989b64998f3699a28b4d5d4dc" dependencies = [ "jsonrpsee-core", "jsonrpsee-proc-macros", @@ -4212,9 +4212,9 @@ dependencies = [ [[package]] name = "jsonrpsee-core" -version = "0.20.1" +version = "0.20.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "35dc957af59ce98373bcdde0c1698060ca6c2d2e9ae357b459c7158b6df33330" +checksum = "da2327ba8df2fdbd5e897e2b5ed25ce7f299d345b9736b6828814c3dbd1fd47b" dependencies = [ "anyhow", "async-trait", @@ -4235,9 +4235,9 @@ dependencies = [ [[package]] name = "jsonrpsee-proc-macros" -version = "0.20.1" +version = "0.20.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cef91b1017a4edb63f65239381c18de39f88d0e0760ab626d806e196f7f51477" +checksum = "29110019693a4fa2dbda04876499d098fa16d70eba06b1e6e2b3f1b251419515" dependencies = [ "heck", "proc-macro-crate", @@ -4248,9 +4248,9 @@ dependencies = [ [[package]] name = "jsonrpsee-server" -version = "0.20.1" +version = "0.20.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "24f4e2f3d223d810e363fb8b5616ec4c6254243ee7f452d05ac281cdc9cf76b2" +checksum = "82c39a00449c9ef3f50b84fc00fc4acba20ef8f559f07902244abf4c15c5ab9c" dependencies = [ "futures-util", "http", @@ -4271,9 +4271,9 @@ dependencies = [ [[package]] name = "jsonrpsee-types" -version = "0.20.1" +version = "0.20.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa9e25aec855b2a7d3ed90fded6c41e8c3fb72b63f071e1be3f0004eba19b625" +checksum = "5be0be325642e850ed0bdff426674d2e66b2b7117c9be23a7caef68a2902b7d9" dependencies = [ "anyhow", "beef", @@ -4351,9 +4351,9 @@ checksum = "830d08ce1d1d941e6b30645f1a0eb5643013d835ce3779a5fc208261dbe10f55" [[package]] name = "libc" -version = "0.2.147" +version = "0.2.150" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b4668fb0ea861c1df094127ac5f1da3409a82116a4ba74fca2e58ef927159bb3" +checksum = "89d92a4743f9a61002fae18374ed11e7973f530cb3a3255fb354818118b2203c" [[package]] name = "libloading" @@ -4468,9 +4468,9 @@ dependencies = [ [[package]] name = "lru" -version = "0.12.0" +version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1efa59af2ddfad1854ae27d75009d538d0998b4b2fd47083e743ac1a10e46c60" +checksum = "2994eeba8ed550fd9b47a0b38f0242bc3344e496483c6180b69139cc2fa5d1d7" dependencies = [ "hashbrown 0.14.0", ] @@ -4612,14 +4612,13 @@ dependencies = [ [[package]] name = "mio" -version = "0.8.6" +version = "0.8.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b9d9a46eff5b4ff64b45a9e316a6d1e0bc719ef429cbec4dc630684212bfdf9" +checksum = "3dce281c5e46beae905d4de1870d8b1509a9142b62eedf18b443b011ca8343d0" dependencies = [ "libc", - "log", "wasi 0.11.0+wasi-snapshot-preview1", - "windows-sys 0.45.0", + "windows-sys 0.48.0", ] [[package]] @@ -4856,7 +4855,7 @@ dependencies = [ "proc-macro-crate", "proc-macro2", "quote", - "syn 2.0.38", + "syn 2.0.39", ] [[package]] @@ -4986,7 +4985,7 @@ checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.38", + "syn 2.0.39", ] [[package]] @@ -5182,7 +5181,7 @@ dependencies = [ "libc", "redox_syscall 0.3.5", "smallvec", - "windows-targets 0.48.0", + "windows-targets", ] [[package]] @@ -5368,7 +5367,7 @@ checksum = "39407670928234ebc5e6e580247dd567ad73a3578460c5990f9503df207e8f07" dependencies = [ "proc-macro2", "quote", - "syn 2.0.38", + "syn 2.0.39", ] [[package]] @@ -5497,7 +5496,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ae005bd773ab59b4725093fd7df83fd7892f7d8eafb48dbd7de6e024e4215f9d" dependencies = [ "proc-macro2", - "syn 2.0.38", + "syn 2.0.39", ] [[package]] @@ -5579,9 +5578,9 @@ checksum = "dc375e1527247fe1a97d8b7156678dfe7c1af2fc075c9a4db3690ecd2a148068" [[package]] name = "proc-macro2" -version = "1.0.69" +version = "1.0.70" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "134c189feb4956b20f6f547d2cf727d4c0fe06722b20a0eec87ed445a97f92da" +checksum = "39278fbbf5fb4f646ce651690877f89d1c5811a3d4acb27700c1cb3cdb78fd3b" dependencies = [ "unicode-ident", ] @@ -6453,9 +6452,9 @@ dependencies = [ [[package]] name = "semver" -version = "1.0.18" +version = "1.0.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b0293b4b29daaf487284529cc2f5675b8e57c61f70167ba415a463651fd6a918" +checksum = "836fa6a3e1e547f9a2c4040802ec865b5d85f4014efe00555d7090a3dcaa1090" dependencies = [ "serde", ] @@ -6474,9 +6473,9 @@ checksum = "cd0b0ec5f1c1ca621c432a25813d8d60c88abe6d3e08a3eb9cf37d97a0fe3d73" [[package]] name = "serde" -version = "1.0.188" +version = "1.0.193" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf9e0fcba69a370eed61bcf2b728575f726b50b55cba78064753d708ddc7549e" +checksum = "25dd9975e68d0cb5aa1120c288333fc98731bd1dd12f561e468ea4728c042b89" dependencies = [ "serde_derive", ] @@ -6493,13 +6492,13 @@ dependencies = [ [[package]] name = "serde_derive" -version = "1.0.188" +version = "1.0.193" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4eca7ac642d82aa35b60049a6eccb4be6be75e599bd2e9adb5f875a737654af2" +checksum = "43576ca501357b9b071ac53cdc7da8ef0cbd9493d8df094cd821777ea6e894d3" dependencies = [ "proc-macro2", "quote", - "syn 2.0.38", + "syn 2.0.39", ] [[package]] @@ -6711,9 +6710,9 @@ dependencies = [ [[package]] name = "socket2" -version = "0.5.3" +version = "0.5.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2538b18701741680e0322a2302176d3253a35388e2e62f172f64f4f16605f877" +checksum = "7b5fac59a5cb5dd637972e5fca70daf0523c9067fcdc4842f053dae04a18f8e9" dependencies = [ "libc", "windows-sys 0.48.0", @@ -6844,7 +6843,7 @@ dependencies = [ "proc-macro2", "quote", "rustversion", - "syn 2.0.38", + "syn 2.0.39", ] [[package]] @@ -6956,9 +6955,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.38" +version = "2.0.39" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e96b79aaa137db8f61e26363a0c9b47d8b4ec75da28b7d1d614c2303e232408b" +checksum = "23e78b90f2fcf45d3e842032ce32e3f2d1545ba6636271dcbf24fa306d87be7a" dependencies = [ "proc-macro2", "quote", @@ -7137,22 +7136,22 @@ checksum = "222a222a5bfe1bba4a77b45ec488a741b3cb8872e5e499451fd7d0129c9c7c3d" [[package]] name = "thiserror" -version = "1.0.49" +version = "1.0.50" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1177e8c6d7ede7afde3585fd2513e611227efd6481bd78d2e82ba1ce16557ed4" +checksum = "f9a7210f5c9a7156bb50aa36aed4c95afb51df0df00713949448cf9e97d382d2" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl" -version = "1.0.49" +version = "1.0.50" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "10712f02019e9288794769fba95cd6847df9874d49d871d062172f9dd41bc4cc" +checksum = "266b2e40bc00e5a6c09c3584011e08b06f123c00362c92b975ba9843aaaa14b8" dependencies = [ "proc-macro2", "quote", - "syn 2.0.38", + "syn 2.0.39", ] [[package]] @@ -7279,9 +7278,9 @@ checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" [[package]] name = "tokio" -version = "1.33.0" +version = "1.34.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4f38200e3ef7995e5ef13baec2f432a6da0aa9ac495b2c0e8f3b7eec2c92d653" +checksum = "d0c014766411e834f7af5b8f4cf46257aab4036ca95e9d2c144a10f59ad6f5b9" dependencies = [ "backtrace", "bytes", @@ -7291,20 +7290,20 @@ dependencies = [ "parking_lot 0.12.1", "pin-project-lite", "signal-hook-registry", - "socket2 0.5.3", + "socket2 0.5.5", "tokio-macros", "windows-sys 0.48.0", ] [[package]] name = "tokio-macros" -version = "2.1.0" +version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "630bdcf245f78637c13ec01ffae6187cca34625e8c63150d424b59e55af2675e" +checksum = "5b8a1e28f2deaa14e508979454cb3a223b10b938b45af148bc0986de36f1923b" dependencies = [ "proc-macro2", "quote", - "syn 2.0.38", + "syn 2.0.39", ] [[package]] @@ -7517,7 +7516,7 @@ checksum = "0f57e3ca2a01450b1a921183a9c9cbfda207fd822cef4ccb00a65402cbba7a74" dependencies = [ "proc-macro2", "quote", - "syn 2.0.38", + "syn 2.0.39", ] [[package]] @@ -8017,7 +8016,7 @@ version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e686886bc078bc1b0b600cac0147aadb815089b6e4da64016cbd754b6342700f" dependencies = [ - "windows-targets 0.48.0", + "windows-targets", ] [[package]] @@ -8035,37 +8034,13 @@ dependencies = [ "windows_x86_64_msvc 0.42.2", ] -[[package]] -name = "windows-sys" -version = "0.45.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "75283be5efb2831d37ea142365f009c02ec203cd29a3ebecbc093d52315b66d0" -dependencies = [ - "windows-targets 0.42.2", -] - [[package]] name = "windows-sys" version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" dependencies = [ - "windows-targets 0.48.0", -] - -[[package]] -name = "windows-targets" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e5180c00cd44c9b1c88adb3693291f1cd93605ded80c250a75d472756b4d071" -dependencies = [ - "windows_aarch64_gnullvm 0.42.2", - "windows_aarch64_msvc 0.42.2", - "windows_i686_gnu 0.42.2", - "windows_i686_msvc 0.42.2", - "windows_x86_64_gnu 0.42.2", - "windows_x86_64_gnullvm 0.42.2", - "windows_x86_64_msvc 0.42.2", + "windows-targets", ] [[package]] @@ -8272,7 +8247,7 @@ checksum = "ce36e65b0d2999d2aafac989fb249189a141aee1f53c612c1f37d72631959f69" dependencies = [ "proc-macro2", "quote", - "syn 2.0.38", + "syn 2.0.39", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 5ed3c0b5c..d9fc2b537 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "axon" -version = "0.3.0-alpha" +version = "0.3.0-beta" authors = ["Nervos Dev "] edition = "2021" repository = "https://github.com/axonweb3/axon" diff --git a/common/config-parser/src/types/spec.rs b/common/config-parser/src/types/spec.rs index 310ad6668..2b8971c94 100644 --- a/common/config-parser/src/types/spec.rs +++ b/common/config-parser/src/types/spec.rs @@ -12,7 +12,8 @@ use common_crypto::Secp256k1RecoverablePrivateKey; use protocol::{ codec::{decode_256bits_key, deserialize_address}, types::{ - HardforkInfoInner, Header, Key256Bits, Metadata, H160, H256, RLP_EMPTY_LIST, RLP_NULL, U256, + HardforkInfoInner, Header, Key256Bits, Metadata, H160, H256, RLP_EMPTY_LIST, RLP_NULL, + U256, U64, }, }; @@ -36,7 +37,7 @@ pub struct ChainSpec { pub struct Genesis { pub timestamp: u64, pub hardforks: Vec, - pub base_fee_per_gas: U256, + pub base_fee_per_gas: U64, pub chain_id: u64, } diff --git a/core/api/src/adapter.rs b/core/api/src/adapter.rs index 1a19a5189..a169918d8 100644 --- a/core/api/src/adapter.rs +++ b/core/api/src/adapter.rs @@ -7,10 +7,11 @@ use protocol::trie::Trie as _; use protocol::types::{ Account, BigEndianHash, Block, BlockNumber, Bytes, CkbRelatedInfo, EthAccountProof, EthStorageProof, ExecutorContext, HardforkInfo, HardforkInfoInner, Hash, Header, Hex, Metadata, - Proposal, Receipt, SignedTransaction, TxResp, H160, H256, MAX_BLOCK_GAS_LIMIT, NIL_DATA, - RLP_NULL, U256, + Proposal, Receipt, SignedTransaction, TxResp, H160, H256, NIL_DATA, RLP_NULL, U256, U64, +}; +use protocol::{ + async_trait, codec::ProtocolCodec, constants::MAX_BLOCK_GAS_LIMIT, trie, ProtocolResult, }; -use protocol::{async_trait, codec::ProtocolCodec, trie, ProtocolResult}; use core_executor::{ system_contract::metadata::MetadataHandle, AxonExecutor, AxonExecutorReadOnlyAdapter, MPTTrie, @@ -193,8 +194,8 @@ where _ctx: Context, from: Option, to: Option, - gas_price: Option, - gas_limit: Option, + gas_price: Option, + gas_limit: Option, value: U256, data: Vec, estimate: bool, @@ -203,7 +204,9 @@ where ) -> ProtocolResult { let mut exec_ctx = ExecutorContext::from(mock_header); exec_ctx.origin = from.unwrap_or_default(); - exec_ctx.gas_price = gas_price.unwrap_or_else(U256::one); + exec_ctx.gas_price = gas_price + .map(|p| U256::from(p.low_u64())) + .unwrap_or_else(U256::one); let backend = AxonExecutorReadOnlyAdapter::from_root( state_root, @@ -212,7 +215,7 @@ where exec_ctx, )?; let gas_limit = gas_limit - .map(|gas| gas.as_u64()) + .map(|gas| gas.low_u64()) .unwrap_or(MAX_BLOCK_GAS_LIMIT); Ok(AxonExecutor.call(&backend, gas_limit, from, to, value, data, estimate)) diff --git a/core/api/src/jsonrpc/error.rs b/core/api/src/jsonrpc/error.rs index 6738d7463..ba0701cef 100644 --- a/core/api/src/jsonrpc/error.rs +++ b/core/api/src/jsonrpc/error.rs @@ -27,8 +27,6 @@ pub enum RpcError { GasLimitIsTooLow, #[display(fmt = "Gas limit is too large")] GasLimitIsTooLarge, - #[display(fmt = "Gas limit is zero")] - GasLimitIsZero, #[display(fmt = "Transaction is not signed")] TransactionIsNotSigned, #[display(fmt = "Cannot get latest block")] @@ -78,7 +76,6 @@ impl RpcError { RpcError::GasPriceIsTooLarge => -40007, RpcError::GasLimitIsTooLow => -40008, RpcError::GasLimitIsTooLarge => -40009, - RpcError::GasLimitIsZero => -40010, RpcError::TransactionIsNotSigned => -40011, RpcError::CannotGetLatestBlock => -40013, RpcError::InvalidBlockHash => -40014, @@ -116,7 +113,6 @@ impl From for ErrorObjectOwned { RpcError::GasPriceIsTooLarge => ErrorObject::owned(err_code, err, none_data), RpcError::GasLimitIsTooLow => ErrorObject::owned(err_code, err, none_data), RpcError::GasLimitIsTooLarge => ErrorObject::owned(err_code, err, none_data), - RpcError::GasLimitIsZero => ErrorObject::owned(err_code, err, none_data), RpcError::TransactionIsNotSigned => ErrorObject::owned(err_code, err, none_data), RpcError::CannotGetLatestBlock => ErrorObject::owned(err_code, err, none_data), RpcError::InvalidBlockHash => ErrorObject::owned(err_code, err, none_data), diff --git a/core/api/src/jsonrpc/impl/axon.rs b/core/api/src/jsonrpc/impl/axon.rs index 4e654b486..098a5c941 100644 --- a/core/api/src/jsonrpc/impl/axon.rs +++ b/core/api/src/jsonrpc/impl/axon.rs @@ -30,7 +30,7 @@ impl AxonRpcServer for AxonRpcImpl { BlockId::Hash(hash) => self.adapter.get_block_by_hash(Context::new(), hash).await, BlockId::Num(num) => { self.adapter - .get_block_by_number(Context::new(), Some(num.as_u64())) + .get_block_by_number(Context::new(), Some(num.low_u64())) .await } BlockId::Latest => self.adapter.get_block_by_number(Context::new(), None).await, @@ -52,7 +52,7 @@ impl AxonRpcServer for AxonRpcImpl { async fn get_metadata_by_number(&self, block_number: U256) -> RpcResult { let ret = self .adapter - .get_metadata_by_number(Context::new(), Some(block_number.as_u64())) + .get_metadata_by_number(Context::new(), Some(block_number.low_u64())) .await .map_err(|e| RpcError::Internal(e.to_string()))?; diff --git a/core/api/src/jsonrpc/impl/filter.rs b/core/api/src/jsonrpc/impl/filter.rs index 67f0849b7..bd9e72771 100644 --- a/core/api/src/jsonrpc/impl/filter.rs +++ b/core/api/src/jsonrpc/impl/filter.rs @@ -204,7 +204,7 @@ where match from { BlockId::Num(n) => { - if n.as_u64() < header.number { + if n.low_u64() < header.number { filter.from_block = Some(BlockId::Num(U64::from(header.number + 1))); } } @@ -302,7 +302,7 @@ where let (start, end) = { let convert = |id: &BlockId| -> BlockNumber { match id { - BlockId::Num(n) => n.as_u64(), + BlockId::Num(n) => n.low_u64(), BlockId::Earliest => 0, _ => latest_number, } diff --git a/core/api/src/jsonrpc/impl/web3.rs b/core/api/src/jsonrpc/impl/web3.rs index 8746cf40c..79361f87b 100644 --- a/core/api/src/jsonrpc/impl/web3.rs +++ b/core/api/src/jsonrpc/impl/web3.rs @@ -4,15 +4,17 @@ use jsonrpsee::core::RpcResult; use common_apm::metrics_rpc; use core_executor::is_system_contract_address_format; +use protocol::constants::{ + BASE_FEE_PER_GAS, MAX_FEE_HISTORY, MAX_GAS_LIMIT, MAX_GAS_PRICE, MEMPOOL_REFRESH_TIMEOUT, + MIN_TRANSACTION_GAS_LIMIT, +}; use protocol::traits::{APIAdapter, Context}; use protocol::types::{ Block, BlockNumber, Bytes, EthAccountProof, Hash, Header, Hex, Proposal, Receipt, - SignedTransaction, TxResp, UnverifiedTransaction, BASE_FEE_PER_GAS, H160, H256, - MAX_FEE_HISTORY, MAX_RPC_GAS_CAP, MIN_TRANSACTION_GAS_LIMIT, U256, U64, + SignedTransaction, TxResp, UnverifiedTransaction, H160, H256, U256, U64, }; use protocol::{ async_trait, codec::ProtocolCodec, lazy::PROTOCOL_VERSION, tokio::time::sleep, ProtocolResult, - MEMPOOL_REFRESH_TIMEOUT, }; use crate::jsonrpc::web3_types::{ @@ -27,7 +29,7 @@ pub(crate) const MAX_LOG_NUM: usize = 10000; pub struct Web3RpcImpl { adapter: Arc, - max_gas_cap: U256, + max_gas_cap: U64, log_filter_max_block_range: u64, } @@ -92,10 +94,10 @@ impl Web3RpcImpl { async fn calculate_rewards( &self, block_number: u64, - base_fee_par_gas: U256, + base_fee_par_gas: U64, txs: Vec, reward_percentiles: Vec, - reward: &mut Vec>, + reward: &mut Vec>, ) -> Result<(), RpcError> { let receipts = self .adapter @@ -103,17 +105,17 @@ impl Web3RpcImpl { .await .map_err(|e| RpcError::Internal(e.to_string()))?; - let effective_priority_fees: Vec = receipts + let effective_priority_fees: Vec = receipts .iter() .map(|receipt| { receipt .as_ref() .map(|r| r.used_gas.saturating_sub(base_fee_par_gas)) - .unwrap_or(U256::zero()) + .unwrap_or(U64::zero()) }) .collect(); - let reward_vec: Vec = reward_percentiles + let reward_vec: Vec = reward_percentiles .iter() .map(|percentile| { let index = @@ -121,7 +123,7 @@ impl Web3RpcImpl { effective_priority_fees .get(index) .cloned() - .unwrap_or(U256::zero()) + .unwrap_or(U64::zero()) }) .collect(); @@ -135,7 +137,7 @@ impl Web3RpcImpl { height: Option, block_count: U256, reward_percentiles: &Option>, - ) -> Result<(u64, Vec, Vec, Vec>), RpcError> { + ) -> Result<(u64, Vec, Vec, Vec>), RpcError> { let latest_block = self .adapter .get_block_by_number(Context::new(), height) @@ -148,9 +150,9 @@ impl Web3RpcImpl { .saturating_sub(block_count.as_u64()) .saturating_add(1); - let mut bash_fee_per_gases: Vec = Vec::new(); + let mut bash_fee_per_gases: Vec = Vec::new(); let mut gas_used_ratios: Vec = Vec::new(); - let mut reward: Vec> = Vec::new(); + let mut reward: Vec> = Vec::new(); for i in oldest_block_number..=latest_block_number { let block = match self @@ -198,11 +200,11 @@ impl Web3RpcServer for Web3RpcImpl { let gas_price = utx.unsigned.gas_price(); - if gas_price == U256::zero() { + if gas_price == U64::zero() { return Err(RpcError::GasPriceIsZero.into()); } - if gas_price >= U256::from(u64::MAX) { + if gas_price > MAX_GAS_PRICE { return Err(RpcError::GasPriceIsTooLarge.into()); } @@ -414,12 +416,12 @@ impl Web3RpcServer for Web3RpcImpl { #[metrics_rpc("eth_call")] async fn call(&self, req: Web3CallRequest, block_id: Option) -> RpcResult { - if req.gas_price.unwrap_or_default() > U256::from(u64::MAX) { + if req.gas.unwrap_or_default() > MAX_GAS_LIMIT.into() { return Err(RpcError::GasLimitIsTooLarge.into()); } - if req.gas.unwrap_or_default() > U256::from(MAX_RPC_GAS_CAP) { - return Err(RpcError::GasLimitIsTooLarge.into()); + if req.gas_price.unwrap_or_default() > MAX_GAS_PRICE { + return Err(RpcError::GasPriceIsTooLarge.into()); } if let Some(call_addr) = req.to { @@ -451,15 +453,17 @@ impl Web3RpcServer for Web3RpcImpl { #[metrics_rpc("eth_estimateGas")] async fn estimate_gas(&self, req: Web3CallRequest, number: Option) -> RpcResult { if let Some(gas_limit) = req.gas.as_ref() { - if gas_limit == &U256::zero() { - return Err(RpcError::GasPriceIsZero.into()); + if gas_limit < &(MIN_TRANSACTION_GAS_LIMIT.into()) { + return Err(RpcError::GasLimitIsTooLow.into()); } } - if let Some(price) = req.gas_price.as_ref() { - if price >= &U256::from(u64::MAX) { - return Err(RpcError::GasPriceIsTooLarge.into()); - } + if req.gas.unwrap_or_default() > MAX_GAS_LIMIT.into() { + return Err(RpcError::GasLimitIsTooLarge.into()); + } + + if req.gas_price.unwrap_or_default() > MAX_GAS_PRICE { + return Err(RpcError::GasPriceIsTooLarge.into()); } if let Some(call_addr) = req.to { @@ -469,7 +473,7 @@ impl Web3RpcServer for Web3RpcImpl { } let num = match number { - Some(BlockId::Num(n)) => Some(n.as_u64()), + Some(BlockId::Num(n)) => Some(n.low_u64()), _ => None, }; let data_bytes = req @@ -688,7 +692,7 @@ impl Web3RpcServer for Web3RpcImpl { let (start, end) = { let convert = |id: BlockId| -> BlockNumber { match id { - BlockId::Num(n) => n.as_u64(), + BlockId::Num(n) => n.low_u64(), BlockId::Earliest => 0, _ => latest_number, } @@ -780,7 +784,7 @@ impl Web3RpcServer for Web3RpcImpl { match newest_block { BlockId::Num(number) => { let (oldest_block_number, bash_fee_per_gases, gas_used_ratios, reward) = self - .inner_fee_history(number.as_u64().into(), blocks_count, &reward_percentiles) + .inner_fee_history(number.low_u64().into(), blocks_count, &reward_percentiles) .await?; match reward_percentiles { @@ -861,7 +865,7 @@ impl Web3RpcServer for Web3RpcImpl { gas_used_ratio, })); } - let mut reward: Vec> = Vec::new(); + let mut reward: Vec> = Vec::new(); self.calculate_rewards( first_block.header.number, first_block.header.base_fee_per_gas, @@ -969,6 +973,10 @@ impl Web3RpcServer for Web3RpcImpl { position: U256, block_id: Option, ) -> RpcResult { + if is_system_contract_address_format(&address) { + return Err(RpcError::CallSystemContract.into()); + } + let number = self.get_block_number_by_id(block_id).await?; let header = self @@ -1064,9 +1072,9 @@ fn check_reward_percentiles(reward_percentiles: &Option>) -> RpcResult< // Calculates the gas used ratio for the block. fn calculate_gas_used_ratio(block: &Block) -> f64 { - (block.header.gas_limit != U256::zero()) + (block.header.gas_limit != U64::zero()) .then(|| { - block.header.gas_used.as_u64() as f64 / block.header.gas_limit.as_u64() as f64 * 100f64 + block.header.gas_used.low_u64() as f64 / block.header.gas_limit.as_u64() as f64 * 100f64 }) .unwrap_or(0f64) } @@ -1075,14 +1083,14 @@ fn calculate_gas_used_ratio(block: &Block) -> f64 { // vector. fn calculate_effective_priority_fees_index( percentile: &f64, - effective_priority_fees: &Vec, + effective_priority_fees: &Vec, ) -> usize { ((percentile * effective_priority_fees.len() as f64 / 100f64).floor() as usize) .saturating_sub(1) } // Get the base fee per gas for the next block. -fn next_block_base_fee_per_gas() -> U256 { +fn next_block_base_fee_per_gas() -> U64 { BASE_FEE_PER_GAS.into() } diff --git a/core/api/src/jsonrpc/web3_types.rs b/core/api/src/jsonrpc/web3_types.rs index 8d3efb611..07ed454a0 100644 --- a/core/api/src/jsonrpc/web3_types.rs +++ b/core/api/src/jsonrpc/web3_types.rs @@ -49,26 +49,26 @@ impl RichTransactionOrHash { pub struct Web3Transaction { #[serde(rename = "type")] pub type_: Option, - pub block_number: Option, + pub block_number: Option, pub block_hash: Option, pub hash: Hash, - pub nonce: U256, - pub transaction_index: Option, + pub nonce: U64, + pub transaction_index: Option, pub from: H160, pub to: Option, pub value: U256, - pub gas: U256, - pub gas_price: U256, + pub gas: U64, + pub gas_price: U64, #[serde(skip_serializing_if = "Option::is_none")] - pub max_fee_per_gas: Option, + pub max_fee_per_gas: Option, #[serde(skip_serializing_if = "Option::is_none")] - pub max_priority_fee_per_gas: Option, + pub max_priority_fee_per_gas: Option, pub raw: Hex, pub input: Hex, pub public_key: Option, #[serde(skip_serializing_if = "Option::is_none")] pub access_list: Option, - pub chain_id: Option, + pub chain_id: Option, #[serde(skip_serializing_if = "Option::is_none")] pub standard_v: Option, pub v: U256, @@ -107,7 +107,7 @@ impl From for Web3Transaction { gas: *stx.transaction.unsigned.gas_limit(), gas_price: stx.transaction.unsigned.gas_price(), max_fee_per_gas: if is_eip1559 { - Some(U256::from(MAX_PRIORITY_FEE_PER_GAS)) + Some(U64::from(MAX_PRIORITY_FEE_PER_GAS)) } else { None }, @@ -162,15 +162,15 @@ pub struct Web3Receipt { pub block_number: U256, pub block_hash: H256, pub contract_address: Option, - pub cumulative_gas_used: U256, - pub effective_gas_price: U256, + pub cumulative_gas_used: U64, + pub effective_gas_price: U64, pub from: H160, - pub gas_used: U256, + pub gas_used: U64, pub logs: Vec, pub logs_bloom: Bloom, #[serde(rename = "root")] pub state_root: Hash, - pub status: U256, + pub status: U64, pub to: Option, pub transaction_hash: Hash, pub transaction_index: Option, @@ -243,16 +243,16 @@ pub struct Web3Block { pub state_root: H256, pub transactions_root: H256, pub receipts_root: H256, - pub number: U256, - pub gas_used: U256, - pub gas_limit: U256, + pub number: U64, + pub gas_used: U64, + pub gas_limit: U64, pub extra_data: Hex, pub logs_bloom: Option, pub timestamp: U256, pub difficulty: U256, pub total_difficulty: Option, pub seal_fields: Vec, - pub base_fee_per_gas: U256, + pub base_fee_per_gas: U64, pub uncles: Vec, pub transactions: Vec, pub size: Option, @@ -308,10 +308,10 @@ pub struct Web3CallRequest { pub from: Option, pub to: Option, #[serde(skip_serializing_if = "Option::is_none")] - pub gas_price: Option, + pub gas_price: Option, #[serde(skip_serializing_if = "Option::is_none")] - pub max_fee_per_gas: Option, - pub gas: Option, + pub max_fee_per_gas: Option, + pub gas: Option, pub value: Option, pub data: Option, pub nonce: Option, @@ -335,7 +335,7 @@ pub enum BlockId { impl From for Option { fn from(id: BlockId) -> Self { match id { - BlockId::Num(num) => Some(num.as_u64()), + BlockId::Num(num) => Some(num.low_u64()), BlockId::Earliest => Some(0), _ => None, } @@ -727,13 +727,13 @@ pub struct FeeHistoryWithReward { /// This includes the next block after the newest of the returned range, /// because this value can be derived from the newest block. Zeroes are /// returned for pre-EIP-1559 blocks. - pub base_fee_per_gas: Vec, + pub base_fee_per_gas: Vec, /// An array of block gas used ratios. These are calculated as the ratio /// of `gasUsed` and `gasLimit`. pub gas_used_ratio: Vec, /// An (optional) array of effective priority fee per gas data points from a /// single block. All zeroes are returned if the block is empty. - pub reward: Vec>, + pub reward: Vec>, } /// Response type for `eth_feeHistory` RPC call with parameter REWARDPERCENTILES @@ -747,7 +747,7 @@ pub struct FeeHistoryWithoutReward { /// This includes the next block after the newest of the returned range, /// because this value can be derived from the newest block. Zeroes are /// returned for pre-EIP-1559 blocks. - pub base_fee_per_gas: Vec, + pub base_fee_per_gas: Vec, /// An array of block gas used ratios. These are calculated as the ratio /// of `gasUsed` and `gasLimit`. pub gas_used_ratio: Vec, @@ -769,8 +769,8 @@ pub struct FeeHistoryEmpty { pub struct Web3Header { pub difficulty: U256, pub extra_data: Hex, - pub gas_limit: U256, - pub gas_used: U256, + pub gas_limit: U64, + pub gas_used: U64, pub logs_bloom: Option, pub miner: H160, pub nonce: U256, diff --git a/core/consensus/src/engine.rs b/core/consensus/src/engine.rs index e87deaf31..37c7a2869 100644 --- a/core/consensus/src/engine.rs +++ b/core/consensus/src/engine.rs @@ -21,11 +21,11 @@ use protocol::constants::endpoints::{ END_GOSSIP_AGGREGATED_VOTE, END_GOSSIP_SIGNED_CHOKE, END_GOSSIP_SIGNED_PROPOSAL, END_GOSSIP_SIGNED_VOTE, }; +use protocol::constants::{BASE_FEE_PER_GAS, MAX_BLOCK_GAS_LIMIT}; use protocol::traits::{ConsensusAdapter, Context, MessageTarget, NodeInfo}; use protocol::types::{ Block, BlockVersion, Bytes, ExecResp, ExtraData, Hash, Hex, Metadata, Proof, Proposal, - SignedTransaction, ValidatorExtend, VecDisplayHelper, BASE_FEE_PER_GAS, MAX_BLOCK_GAS_LIMIT, - RLP_NULL, + SignedTransaction, ValidatorExtend, VecDisplayHelper, RLP_NULL, }; use protocol::{ async_trait, codec::ProtocolCodec, tokio::sync::Mutex as AsyncMutex, types::HardforkInfoInner, @@ -742,7 +742,7 @@ impl ConsensusEngine { ctx, resp.state_root, MAX_BLOCK_GAS_LIMIT, - last_status.max_tx_size.as_u64(), + last_status.max_tx_size.low_u64(), ); if block.header.number != proof.number { diff --git a/core/consensus/src/tests/mod.rs b/core/consensus/src/tests/mod.rs index 8d9c9efdc..f718ce35c 100644 --- a/core/consensus/src/tests/mod.rs +++ b/core/consensus/src/tests/mod.rs @@ -14,7 +14,7 @@ use protocol::{ Address, Block, BlockNumber, Bytes, Eip1559Transaction, ExecResp, Hash, Hasher, Header, Hex, MerkleRoot, Metadata, Proof, Proposal, Public, Receipt, SignatureComponents, SignedTransaction, TransactionAction, UnsignedTransaction, UnverifiedTransaction, - Validator, H160, H256, U256, + Validator, H160, H256, U256, U64, }, ProtocolResult, }; @@ -109,10 +109,10 @@ fn gen_tx(sender: H160, addr: H160, value: u64, data: Vec) -> SignedTransact SignedTransaction { transaction: UnverifiedTransaction { unsigned: UnsignedTransaction::Eip1559(Eip1559Transaction { - nonce: U256::default(), - max_priority_fee_per_gas: U256::default(), - gas_price: U256::default(), - gas_limit: U256::from_str("0x1000000000").unwrap(), + nonce: U64::default(), + max_priority_fee_per_gas: U64::default(), + gas_price: U64::default(), + gas_limit: U64::from_str("0x1000000000").unwrap(), action: TransactionAction::Call(addr), value: value.into(), data: data.into(), diff --git a/core/executor/benches/mock.rs b/core/executor/benches/mock.rs index 55eb25ae9..24a40d05b 100644 --- a/core/executor/benches/mock.rs +++ b/core/executor/benches/mock.rs @@ -9,7 +9,7 @@ use protocol::{ types::{ public_to_address, Account, Address, Bytes, Eip1559Transaction, ExecutorContext, Public, SignedTransaction, TransactionAction, UnsignedTransaction, UnverifiedTransaction, H160, - H512, NIL_DATA, RLP_NULL, U256, + H512, NIL_DATA, RLP_NULL, U256, U64, }, }; @@ -76,7 +76,7 @@ pub fn mock_transactions(n: usize) -> Vec { ) }; let raw_tx = Eip1559Transaction { - nonce: U256::zero(), + nonce: U64::zero(), max_priority_fee_per_gas: 1u64.into(), gas_price: 1u64.into(), gas_limit: 10_000_000u64.into(), diff --git a/core/executor/benches/revm_adapter.rs b/core/executor/benches/revm_adapter.rs index e758de640..86199b4d0 100644 --- a/core/executor/benches/revm_adapter.rs +++ b/core/executor/benches/revm_adapter.rs @@ -52,7 +52,7 @@ where let raw = raw.unwrap(); Ok(Some(Account::decode(raw).map(|a| AccountInfo { balance: U256(a.balance.0), - nonce: a.nonce.as_u64(), + nonce: a.nonce.low_u64(), code_hash: a.code_hash, code: None, })?)) @@ -101,11 +101,11 @@ where fn block_hash(&mut self, number: U256) -> Result { let current_number = self.exec_ctx.block_number; - if number.as_u64() > current_number.as_u64() { + if number.low_u64() > current_number.low_u64() { return Ok(H256::default()); } - let number = number.as_u64(); + let number = number.low_u64(); let res = blocking_async!(self, storage, get_block, Context::new(), number) .map(|b| b.hash()) .unwrap_or_default(); @@ -299,7 +299,7 @@ where .nonce; set_revm( evm, - tx.transaction.unsigned.gas_limit().as_u64(), + tx.transaction.unsigned.gas_limit().low_u64(), Some(tx.sender), tx.transaction.unsigned.to(), *tx.transaction.unsigned.value(), @@ -324,7 +324,7 @@ where exit_reason: evm::ExitReason::Succeed(ExitSucceed::Returned), ret, gas_used: res.gas_used, - remain_gas: tx.transaction.unsigned.gas_limit().as_u64() - res.gas_used, + remain_gas: tx.transaction.unsigned.gas_limit().low_u64() - res.gas_used, fee_cost: res.gas_used.into(), // todo logs: vec![], diff --git a/core/executor/src/adapter/backend/apply.rs b/core/executor/src/adapter/backend/apply.rs index ef5c364ad..73d8dda79 100644 --- a/core/executor/src/adapter/backend/apply.rs +++ b/core/executor/src/adapter/backend/apply.rs @@ -9,6 +9,7 @@ use protocol::traits::{ use protocol::trie::Trie; use protocol::types::{ Account, Bytes, ExecutorContext, Hasher, Log, MerkleRoot, H160, H256, NIL_DATA, RLP_NULL, U256, + U64, }; use protocol::{codec::ProtocolCodec, trie, ProtocolResult}; @@ -114,8 +115,8 @@ where self.inner.exec_ctx.origin = origin; } - fn set_gas_price(&mut self, gas_price: U256) { - self.inner.exec_ctx.gas_price = gas_price; + fn set_gas_price(&mut self, gas_price: U64) { + self.inner.exec_ctx.gas_price = gas_price.low_u64().into(); } fn take_logs(&mut self) -> Vec { diff --git a/core/executor/src/adapter/backend/read_only.rs b/core/executor/src/adapter/backend/read_only.rs index 1c41e626c..0ef57d6f4 100644 --- a/core/executor/src/adapter/backend/read_only.rs +++ b/core/executor/src/adapter/backend/read_only.rs @@ -78,7 +78,7 @@ where return H256::default(); } - let number = number.as_u64(); + let number = number.low_u64(); blocking_async!(self, get_storage, get_block, Context::new(), number) .map(|b| b.hash()) .unwrap_or_default() @@ -97,11 +97,11 @@ where } fn block_gas_limit(&self) -> U256 { - self.exec_ctx.block_gas_limit + U256::from(self.exec_ctx.block_gas_limit.low_u64()) } fn block_base_fee_per_gas(&self) -> U256 { - self.exec_ctx.block_base_fee_per_gas + U256::from(self.exec_ctx.block_base_fee_per_gas.low_u64()) } fn chain_id(&self) -> U256 { diff --git a/core/executor/src/debugger/create2.rs b/core/executor/src/debugger/create2.rs index e8dfce91c..a11ea0c72 100644 --- a/core/executor/src/debugger/create2.rs +++ b/core/executor/src/debugger/create2.rs @@ -1,9 +1,9 @@ use protocol::traits::Backend; use protocol::types::{ LegacyTransaction, SignedTransaction, TransactionAction, UnsignedTransaction, - UnverifiedTransaction, H160, H256, MAX_BLOCK_GAS_LIMIT, U256, + UnverifiedTransaction, H160, H256, U256, U64, }; -use protocol::{codec::hex_decode, tokio}; +use protocol::{codec::hex_decode, constants::MAX_BLOCK_GAS_LIMIT, tokio}; use crate::debugger::EvmDebugger; @@ -29,10 +29,10 @@ async fn test_create2_gas() { let gas_used = resp.tx_resp[0].gas_used; let after_balance = debugger.backend(1).basic(sender).balance; - assert_eq!(gas_used * 8, (init_balance - after_balance).as_u64()); + assert_eq!(gas_used * 8, (init_balance - after_balance).low_u64()); } -fn mock_create2_tx(nonce: U256, sender: H160) -> SignedTransaction { +fn mock_create2_tx(nonce: U64, sender: H160) -> SignedTransaction { let tx = LegacyTransaction { nonce, gas_price: 8u64.into(), diff --git a/core/executor/src/debugger/mod.rs b/core/executor/src/debugger/mod.rs index 70ac9038d..b863ad4a1 100644 --- a/core/executor/src/debugger/mod.rs +++ b/core/executor/src/debugger/mod.rs @@ -6,13 +6,12 @@ use std::time::{SystemTime, UNIX_EPOCH}; use evm::tracing::{Event, EventListener}; -use protocol::codec::ProtocolCodec; use protocol::traits::Backend; -use protocol::trie::Trie as _; use protocol::types::{ Account, Eip1559Transaction, ExecResp, ExecutorContext, Hash, Hasher, SignedTransaction, - UnsignedTransaction, UnverifiedTransaction, H160, H256, NIL_DATA, RLP_NULL, U256, + UnsignedTransaction, UnverifiedTransaction, H160, H256, NIL_DATA, RLP_NULL, U256, U64, }; +use protocol::{codec::ProtocolCodec, trie::Trie as _}; use core_db::RocksAdapter; use core_storage::ImplStorage; @@ -95,8 +94,8 @@ impl EvmDebugger { .unwrap() } - fn nonce(&self, addr: H160) -> U256 { - self.backend(0).basic(addr).nonce + fn nonce(&self, addr: H160) -> U64 { + self.backend(0).basic(addr).nonce.low_u64().into() } } diff --git a/core/executor/src/debugger/uniswap2.rs b/core/executor/src/debugger/uniswap2.rs index 8d9e45769..aa94f3ad1 100644 --- a/core/executor/src/debugger/uniswap2.rs +++ b/core/executor/src/debugger/uniswap2.rs @@ -6,7 +6,7 @@ use evm::{ExitReason, ExitSucceed}; use protocol::codec::hex_decode; use protocol::tokio; -use protocol::types::{Bytes, TransactionAction, H160}; +use protocol::types::{Bytes, TransactionAction, H160, U64}; ethabi_contract::use_contract!(factory, "res/factory.abi"); ethabi_contract::use_contract!(router, "res/router.abi"); @@ -35,9 +35,9 @@ fn read_code(path: &str) -> String { fn construct_tx(action: TransactionAction, value: U256, data: Vec) -> Eip1559Transaction { Eip1559Transaction { - nonce: U256::default(), - max_priority_fee_per_gas: U256::default(), - gas_price: U256::default(), + nonce: U64::default(), + max_priority_fee_per_gas: U64::default(), + gas_price: U64::default(), gas_limit: 10000000000u64.into(), action, value, diff --git a/core/executor/src/lib.rs b/core/executor/src/lib.rs index 0c07dfc5d..9c4a803d5 100644 --- a/core/executor/src/lib.rs +++ b/core/executor/src/lib.rs @@ -71,15 +71,10 @@ impl Executor for AxonExecutor { to: Option, value: U256, data: Vec, - estimate: bool, + is_estimate: bool, ) -> TxResp { self.init_local_system_contract_roots(backend); - let config = { - let mut config = self.config(); - // whether run the gasometer in estimate mode or not - config.estimate = estimate; - config - }; + let config = self.config(); let metadata = StackSubstateMetadata::new(gas_limit, &config); let state = MemoryStackState::new(metadata, backend); let precompiles = build_precompile_set(); @@ -99,6 +94,12 @@ impl Executor for AxonExecutor { }; let used_gas = executor.used_gas(); + let used_gas = if is_estimate { + // The estimate gas coef is 1.25 + (used_gas / 4) + used_gas + } else { + used_gas + }; TxResp { exit_reason: exit, @@ -300,9 +301,14 @@ impl AxonExecutor { ) -> TxResp { // Deduct pre-pay gas let sender = tx.sender; + // The `Backend` trait is imply in + // `core/executor/src/adapter/backend/read_only.rs`. The `gas_price` is never + // larger than u64::MAX. let tx_gas_price = adapter.gas_price(); - let gas_limit = tx.transaction.unsigned.gas_limit(); - let prepay_gas = tx_gas_price * gas_limit; + let gas_limit = tx.transaction.unsigned.gas_limit().low_u64(); + // The overflow check is done in the `check_authorization` function + // of`core/mempool/src/adapter/mod.rs`. + let prepay_gas = tx_gas_price * U256::from(gas_limit); let mut account = adapter.get_account(&sender); let old_nonce = account.nonce; @@ -310,7 +316,7 @@ impl AxonExecutor { account.balance = account.balance.saturating_sub(prepay_gas); adapter.save_account(&sender, &account); - let metadata = StackSubstateMetadata::new(gas_limit.as_u64(), config); + let metadata = StackSubstateMetadata::new(gas_limit, config); let mut executor = StackExecutor::new_with_precompiles( MemoryStackState::new(metadata, adapter), config, @@ -331,14 +337,14 @@ impl AxonExecutor { *addr, *tx.transaction.unsigned.value(), tx.transaction.unsigned.data().to_vec(), - gas_limit.as_u64(), + gas_limit, access_list, ), TransactionAction::Create => executor.transact_create( tx.sender, *tx.transaction.unsigned.value(), tx.transaction.unsigned.data().to_vec(), - gas_limit.as_u64(), + gas_limit, access_list, ), }; @@ -364,9 +370,7 @@ impl AxonExecutor { // Add remain gas if remained_gas != 0 { - let remain_gas = U256::from(remained_gas) - .checked_mul(tx_gas_price) - .unwrap_or_else(U256::max_value); + let remain_gas = U256::from(remained_gas) * tx_gas_price; account.balance = account .balance .checked_add(remain_gas) @@ -380,9 +384,8 @@ impl AxonExecutor { ret: res, remain_gas: remained_gas, gas_used: used_gas, - fee_cost: tx_gas_price - .checked_mul(used_gas.into()) - .unwrap_or(U256::max_value()), + fee_cost: tx_gas_price * U256::from(used_gas), /* used_gas must le transaction + * gas_limit */ logs: vec![], code_address: code_addr, removed: false, diff --git a/core/executor/src/system_contract/utils.rs b/core/executor/src/system_contract/utils.rs index 37bacbe28..48d89bd42 100644 --- a/core/executor/src/system_contract/utils.rs +++ b/core/executor/src/system_contract/utils.rs @@ -1,7 +1,7 @@ use evm::ExitSucceed; use protocol::types::{ - Apply, ApplyBackend, Backend, ExitReason, ExitRevert, TxResp, H160, H256, U256, + Apply, ApplyBackend, Backend, ExitReason, ExitRevert, TxResp, H160, H256, U256, U64, }; use crate::system_contract::{ @@ -10,11 +10,11 @@ use crate::system_contract::{ }; use crate::{CURRENT_HEADER_CELL_ROOT, CURRENT_METADATA_ROOT}; -pub fn revert_resp(gas_limit: U256) -> TxResp { +pub fn revert_resp(gas_limit: U64) -> TxResp { TxResp { exit_reason: ExitReason::Revert(ExitRevert::Reverted), ret: vec![], - gas_used: (gas_limit - 1).as_u64(), + gas_used: (gas_limit - 1).low_u64(), remain_gas: 1u64, fee_cost: U256::one(), logs: vec![], @@ -23,12 +23,12 @@ pub fn revert_resp(gas_limit: U256) -> TxResp { } } -pub fn succeed_resp(gas_limit: U256) -> TxResp { +pub fn succeed_resp(gas_limit: U64) -> TxResp { TxResp { exit_reason: ExitReason::Succeed(ExitSucceed::Stopped), ret: vec![], gas_used: 0u64, - remain_gas: gas_limit.as_u64(), + remain_gas: gas_limit.low_u64(), fee_cost: U256::zero(), logs: vec![], code_address: None, diff --git a/core/executor/src/tests/mod.rs b/core/executor/src/tests/mod.rs index 1c7271fde..c39b55d44 100644 --- a/core/executor/src/tests/mod.rs +++ b/core/executor/src/tests/mod.rs @@ -10,7 +10,7 @@ use evm::Config; use protocol::types::{ Bytes, Eip1559Transaction, ExecutorContext, ExitReason, ExitSucceed, Public, SignatureComponents, SignedTransaction, TransactionAction, UnsignedTransaction, - UnverifiedTransaction, H160, H256, U256, + UnverifiedTransaction, H160, H256, U256, U64, }; use protocol::{codec::hex_decode, tokio, traits::Executor, trie::MemoryDB}; @@ -24,7 +24,7 @@ fn exec_adapter() -> AxonExecutorApplyAdapter, Memory let storage = ImplStorage::new(Arc::new(MemoryAdapter::new()), 20); let ctx = ExecutorContext { block_gas_limit: u32::MAX.into(), - block_base_fee_per_gas: U256::one(), + block_base_fee_per_gas: U64::one(), ..Default::default() }; @@ -50,10 +50,10 @@ fn gen_tx(sender: H160, addr: H160, value: u64, data: Vec) -> SignedTransact SignedTransaction { transaction: UnverifiedTransaction { unsigned: UnsignedTransaction::Eip1559(Eip1559Transaction { - nonce: U256::default(), - max_priority_fee_per_gas: U256::default(), - gas_price: U256::default(), - gas_limit: U256::from_str("0x1000000000").unwrap(), + nonce: U64::default(), + max_priority_fee_per_gas: U64::default(), + gas_price: U64::default(), + gas_limit: U64::from_str("0x1000000000").unwrap(), action: TransactionAction::Call(addr), value: value.into(), data: data.into(), diff --git a/core/mempool/benches/mock.rs b/core/mempool/benches/mock.rs index 4822c524c..7318161ad 100644 --- a/core/mempool/benches/mock.rs +++ b/core/mempool/benches/mock.rs @@ -12,7 +12,7 @@ use protocol::traits::{Context, MemPool, MemPoolAdapter}; use protocol::types::{ public_to_address, recover_intact_pub_key, Bytes, Eip1559Transaction, Hash, PackedTxHashes, Public, SignedTransaction, TransactionAction, UnsignedTransaction, UnverifiedTransaction, H160, - H256, U256, + H256, U256, U64, }; use protocol::{async_trait, tokio, ProtocolResult}; @@ -71,8 +71,8 @@ impl MemPoolAdapter for HashMemPoolAdapter { &self, _ctx: Context, _tx: &SignedTransaction, - ) -> ProtocolResult { - Ok(U256::zero()) + ) -> ProtocolResult { + Ok(U64::zero()) } async fn check_transaction(&self, _ctx: Context, tx: &SignedTransaction) -> ProtocolResult<()> { @@ -135,9 +135,9 @@ pub async fn default_mempool() -> MemPoolImpl { pub fn mock_transaction(nonce: u64, is_call_system_script: bool) -> Eip1559Transaction { Eip1559Transaction { nonce: nonce.into(), - gas_limit: U256::one(), - max_priority_fee_per_gas: U256::one(), - gas_price: U256::one(), + gas_limit: U64::one(), + max_priority_fee_per_gas: U64::one(), + gas_price: U64::one(), action: if is_call_system_script { TransactionAction::Call(NATIVE_TOKEN_ISSUE_ADDRESS) } else { diff --git a/core/mempool/src/adapter/mod.rs b/core/mempool/src/adapter/mod.rs index ede5e6750..866faa5c9 100644 --- a/core/mempool/src/adapter/mod.rs +++ b/core/mempool/src/adapter/mod.rs @@ -17,12 +17,13 @@ use protocol::traits::{ }; use protocol::types::{ recover_intact_pub_key, Backend, BatchSignedTxs, CellDepWithPubKey, Hash, MerkleRoot, - SignedTransaction, H160, U256, + SignedTransaction, H160, U256, U64, }; use protocol::{ async_trait, codec::ProtocolCodec, constants::endpoints::{END_GOSSIP_NEW_TXS, RPC_PULL_TXS}, + constants::MAX_GAS_PRICE, tokio, trie, Display, ProtocolError, ProtocolErrorKind, ProtocolResult, }; @@ -120,7 +121,7 @@ pub struct DefaultMemPoolAdapter { storage: Arc, trie_db: Arc, - addr_nonce: DashMap, + addr_nonce: DashMap, gas_limit: AtomicU64, max_tx_size: AtomicUsize, chain_id: u64, @@ -183,13 +184,13 @@ where &self, ctx: Context, stx: &SignedTransaction, - ) -> ProtocolResult { + ) -> ProtocolResult { let addr = &stx.sender; let block = self.storage.get_latest_block(ctx.clone()).await?; let root = self.executor_backend(ctx).await?.get_metadata_root(); if MetadataHandle::new(root).is_validator(block.header.number + 1, *addr)? { - return Ok(U256::zero()); + return Ok(U64::zero()); } Err(MemPoolError::CheckAuthorization { @@ -243,8 +244,8 @@ where fn verify_gas_price(&self, stx: &SignedTransaction) -> ProtocolResult<()> { let gas_price = stx.transaction.unsigned.gas_price(); - if gas_price == U256::zero() || gas_price >= U256::from(u64::MAX) { - return Err(MemPoolError::InvalidGasPrice(gas_price).into()); + if gas_price == U64::zero() || gas_price >= MAX_GAS_PRICE { + return Err(MemPoolError::InvalidGasPrice(gas_price.low_u64()).into()); } Ok(()) @@ -252,7 +253,7 @@ where fn verify_gas_limit(&self, ctx: Context, stx: &SignedTransaction) -> ProtocolResult<()> { let gas_limit_tx = stx.transaction.unsigned.gas_limit(); - if gas_limit_tx > &U256::from(self.gas_limit.load(Ordering::Acquire)) { + if gas_limit_tx > &U64::from(self.gas_limit.load(Ordering::Acquire)) { if ctx.is_network_origin_txs() { self.network.report( ctx, @@ -264,7 +265,7 @@ where } return Err(MemPoolError::ExceedGasLimit { tx_hash: stx.transaction.hash, - gas_limit_tx: gas_limit_tx.as_u64(), + gas_limit_tx: gas_limit_tx.low_u64(), gas_limit_config: self.gas_limit.load(Ordering::Acquire), } .into()); @@ -371,7 +372,7 @@ where &self, ctx: Context, tx: &SignedTransaction, - ) -> ProtocolResult { + ) -> ProtocolResult { if is_call_system_script(tx.transaction.unsigned.action())? { return self.check_system_script_tx_authorization(ctx, tx).await; } @@ -380,11 +381,11 @@ where if let Some(res) = self.addr_nonce.get(addr) { if tx.transaction.unsigned.nonce() < &res.value().0 { return Err(MemPoolError::InvalidNonce { - current: res.value().0.as_u64(), - tx_nonce: tx.transaction.unsigned.nonce().as_u64(), + current: res.value().0.low_u64(), + tx_nonce: tx.transaction.unsigned.nonce().low_u64(), } .into()); - } else if res.value().1 < tx.transaction.unsigned.may_cost() { + } else if res.value().1 < tx.transaction.unsigned.may_cost()? { return Err(MemPoolError::ExceedBalance { tx_hash: tx.transaction.hash, account_balance: res.value().1, @@ -399,17 +400,17 @@ where let backend = self.executor_backend(ctx).await?; let account = backend.basic(*addr); self.addr_nonce - .insert(*addr, (account.nonce, account.balance)); + .insert(*addr, (account.nonce.low_u64().into(), account.balance)); - if &account.nonce > tx.transaction.unsigned.nonce() { + if account.nonce.low_u64() > tx.transaction.unsigned.nonce().low_u64() { return Err(MemPoolError::InvalidNonce { current: account.nonce.as_u64(), - tx_nonce: tx.transaction.unsigned.nonce().as_u64(), + tx_nonce: tx.transaction.unsigned.nonce().low_u64(), } .into()); } - if account.balance < tx.transaction.unsigned.may_cost() { + if account.balance < tx.transaction.unsigned.may_cost()? { return Err(MemPoolError::ExceedBalance { tx_hash: tx.transaction.hash, account_balance: account.balance, @@ -418,7 +419,7 @@ where .into()); } - Ok(tx.transaction.unsigned.nonce() - account.nonce) + Ok(tx.transaction.unsigned.nonce() - account.nonce.low_u64()) } async fn check_transaction(&self, ctx: Context, stx: &SignedTransaction) -> ProtocolResult<()> { diff --git a/core/mempool/src/lib.rs b/core/mempool/src/lib.rs index 8286890b4..308ee73f6 100644 --- a/core/mempool/src/lib.rs +++ b/core/mempool/src/lib.rs @@ -17,7 +17,9 @@ use futures::future::try_join_all; use common_apm::Instant; use protocol::traits::{Context, MemPool, MemPoolAdapter}; -use protocol::types::{BlockNumber, Hash, PackedTxHashes, SignedTransaction, H160, H256, U256}; +use protocol::types::{ + BlockNumber, Hash, PackedTxHashes, SignedTransaction, H160, H256, U256, U64, +}; use protocol::{async_trait, tokio, Display, ProtocolError, ProtocolErrorKind, ProtocolResult}; use core_executor::is_call_system_script; @@ -87,7 +89,7 @@ where self.adapter .check_storage_exist(ctx.clone(), &stx.transaction.hash) .await?; - self.pool.insert(stx, true, U256::zero()) + self.pool.insert(stx, true, U64::zero()) } async fn insert_tx( @@ -134,7 +136,7 @@ where &self, ctx: Context, txs: Vec, - ) -> ProtocolResult> { + ) -> ProtocolResult> { let inst = Instant::now(); let len = txs.len(); @@ -155,20 +157,21 @@ where }) .collect::>>>(); - let res: Vec = try_join_all(futs) + let res: Vec = try_join_all(futs) .await .map_err(|e| { log::error!("[mempool] verify batch txs error {:?}", e); MemPoolError::VerifyBatchTransactions })? .into_iter() - .collect::, ProtocolError>>()?; + .collect::, ProtocolError>>()?; log::info!( "[mempool] verify txs done, size {} cost {:?}", len, inst.elapsed() ); + Ok(res) } @@ -369,11 +372,11 @@ pub enum MemPoolError { ExceedBalance { tx_hash: Hash, account_balance: U256, - tx_gas_limit: U256, + tx_gas_limit: U64, }, #[display(fmt = "Invalid gas price {:?}", _0)] - InvalidGasPrice(U256), + InvalidGasPrice(u64), #[display( fmt = "Tx: {:?} exceeds size limit, now: {}, limit: {} Bytes", diff --git a/core/mempool/src/pool.rs b/core/mempool/src/pool.rs index c61177a38..69606d844 100644 --- a/core/mempool/src/pool.rs +++ b/core/mempool/src/pool.rs @@ -10,8 +10,10 @@ use dashmap::DashMap; use parking_lot::{Mutex, RwLock}; use protocol::tokio::{self, time::sleep}; -use protocol::types::{BlockNumber, Bytes, Hash, PackedTxHashes, SignedTransaction, H160, U256}; -use protocol::{ProtocolResult, MEMPOOL_REFRESH_TIMEOUT}; +use protocol::types::{ + BlockNumber, Bytes, Hash, PackedTxHashes, SignedTransaction, H160, U256, U64, +}; +use protocol::{constants::MEMPOOL_REFRESH_TIMEOUT, ProtocolResult}; use crate::tx_wrapper::{PendingQueue, TxPtr, TxWrapper}; use crate::MemPoolError; @@ -23,7 +25,7 @@ pub struct PriorityPool { // the replace by fee function. pending_queue: Arc>, // The transactions in this queue have not been processed yet and cannot be packaged. - co_queue: Arc>, + co_queue: Arc>, // Transactions in this queue will be packaged into blocks real_queue: Arc>>, // Record all transactions in the transaction pool @@ -110,7 +112,7 @@ impl PriorityPool { &self, stx: SignedTransaction, check_limit: bool, - check_nonce: U256, + check_nonce: U64, ) -> ProtocolResult<()> { if let Err(n) = self .stock_len @@ -249,7 +251,7 @@ impl PriorityPool { let mut q = self.real_queue.lock(); let mut timeout_gap = self.timeout_gap.lock(); - let mut remove_tip_nonce: HashMap = HashMap::new(); + let mut remove_tip_nonce: HashMap = HashMap::new(); for hash in hashes { if let Some((_, ptr)) = self.tx_map.remove(hash) { match remove_tip_nonce.entry(ptr.sender()) { diff --git a/core/mempool/src/tests/mod.rs b/core/mempool/src/tests/mod.rs index 3b217959b..1d940a9b6 100644 --- a/core/mempool/src/tests/mod.rs +++ b/core/mempool/src/tests/mod.rs @@ -14,7 +14,7 @@ use protocol::traits::{Context, MemPool, MemPoolAdapter}; use protocol::types::{ public_to_address, recover_intact_pub_key, Bytes, Eip1559Transaction, Hash, PackedTxHashes, Public, SignedTransaction, TransactionAction, UnsignedTransaction, UnverifiedTransaction, H160, - H256, U256, + H256, U256, U64, }; use protocol::{async_trait, tokio, ProtocolResult}; @@ -72,8 +72,8 @@ impl MemPoolAdapter for HashMemPoolAdapter { &self, _ctx: Context, _tx: &SignedTransaction, - ) -> ProtocolResult { - Ok(U256::zero()) + ) -> ProtocolResult { + Ok(U64::zero()) } async fn check_transaction(&self, _ctx: Context, tx: &SignedTransaction) -> ProtocolResult<()> { @@ -254,9 +254,9 @@ async fn exec_get_full_txs( fn mock_transaction(nonce: u64, is_call_system_script: bool) -> Eip1559Transaction { Eip1559Transaction { nonce: nonce.into(), - gas_limit: U256::one(), - max_priority_fee_per_gas: U256::one(), - gas_price: U256::one(), + gas_limit: U64::one(), + max_priority_fee_per_gas: U64::one(), + gas_price: U64::one(), action: if is_call_system_script { TransactionAction::Call(NATIVE_TOKEN_ISSUE_ADDRESS) } else { diff --git a/core/mempool/src/tx_wrapper.rs b/core/mempool/src/tx_wrapper.rs index 3d3c9ce9e..08c358c23 100644 --- a/core/mempool/src/tx_wrapper.rs +++ b/core/mempool/src/tx_wrapper.rs @@ -4,7 +4,7 @@ use std::ops::Bound::{Included, Unbounded}; use std::sync::atomic::{AtomicU8, Ordering as AtomicOrdering}; use std::sync::Arc; -use protocol::types::{Hash, SignedTransaction, H160, U256}; +use protocol::types::{Hash, SignedTransaction, H160, U64}; pub type TxPtr = Arc; @@ -54,7 +54,7 @@ impl TxWrapper { self.tx.transaction.hash } - pub fn nonce(&self) -> &U256 { + pub fn nonce(&self) -> &U64 { self.tx.transaction.unsigned.nonce() } @@ -62,7 +62,7 @@ impl TxWrapper { self.tx.sender } - pub fn gas_price(&self) -> U256 { + pub fn gas_price(&self) -> U64 { self.tx.transaction.unsigned.gas_price() } @@ -89,15 +89,15 @@ impl TxWrapper { #[derive(Default)] pub struct PendingQueue { - queue: BTreeMap, + queue: BTreeMap, // already insert to package list tip nonce - pop_tip_nonce: U256, - current_tip_nonce: U256, + pop_tip_nonce: U64, + current_tip_nonce: U64, need_remove: bool, } impl PendingQueue { - pub fn insert(&mut self, tx: TxPtr, nonce_diff: U256) -> bool { + pub fn insert(&mut self, tx: TxPtr, nonce_diff: U64) -> bool { let nonce = *tx.nonce(); let current_tip = nonce - nonce_diff; if self.current_tip_nonce > nonce { @@ -155,7 +155,7 @@ impl PendingQueue { self.queue.retain(|_, v| !v.is_dropped()); } - pub fn set_drop_by_nonce_tip(&mut self, nonce: U256) { + pub fn set_drop_by_nonce_tip(&mut self, nonce: U64) { for (_, v) in self.queue.range((Included(0.into()), Included(nonce))) { v.set_dropped(); } diff --git a/core/network/src/peer_manager/peer_store/peer_store_impl.rs b/core/network/src/peer_manager/peer_store/peer_store_impl.rs index 24b798af0..4640b94d6 100644 --- a/core/network/src/peer_manager/peer_store/peer_store_impl.rs +++ b/core/network/src/peer_manager/peer_store/peer_store_impl.rs @@ -21,10 +21,6 @@ use crate::{ }; /// Peer store -/// -/// | -- choose to identify --| --- choose to feeler --- | -- delete -- -/// | | 1 | 2 | 3 | 4 | 5 | 6 | 7 | More than seven -/// days | #[derive(Default)] pub struct PeerStore { addr_manager: Manager, diff --git a/core/run/src/components/chain_spec.rs b/core/run/src/components/chain_spec.rs index 0d0bf34b5..502de57df 100644 --- a/core/run/src/components/chain_spec.rs +++ b/core/run/src/components/chain_spec.rs @@ -1,7 +1,8 @@ use common_config_parser::types::spec::ChainSpec; +use protocol::constants::BASE_FEE_PER_GAS; use protocol::types::{ - Block, Eip1559Transaction, RichBlock, TransactionAction, UnsignedTransaction, BASE_FEE_PER_GAS, + Block, Eip1559Transaction, RichBlock, TransactionAction, UnsignedTransaction, }; pub(crate) trait ChainSpecExt { diff --git a/core/run/src/lib.rs b/core/run/src/lib.rs index 55c779d40..f536c9ffd 100644 --- a/core/run/src/lib.rs +++ b/core/run/src/lib.rs @@ -345,7 +345,7 @@ where Arc::clone(storage), Arc::clone(trie_db), current_header.chain_id, - current_header.gas_limit.as_u64(), + current_header.gas_limit.low_u64(), config.pool_size as usize, config.broadcast_txs_size, config.broadcast_txs_interval, diff --git a/devtools/axon-tools/src/proof.rs b/devtools/axon-tools/src/proof.rs index 75ac46257..2c7d79670 100644 --- a/devtools/axon-tools/src/proof.rs +++ b/devtools/axon-tools/src/proof.rs @@ -50,15 +50,15 @@ pub fn verify_proof( } .rlp_bytes(); - if keccak_256(&raw_proposal) != proof.block_hash.0 { + if keccak_256(&raw_proposal) != proof.proposal_hash.0 { return Err(Error::InvalidProofBlockHash); } let vote = Vote { - height: proof.number, - round: proof.round, - vote_type: 2u8, - block_hash: Bytes::from(proof.block_hash.0.to_vec()), + height: proof.number, + round: proof.round, + vote_type: 2u8, + proposal_hash: Bytes::from(proof.proposal_hash.0.to_vec()), }; let hash_vote = keccak_256(rlp::encode(&vote).as_ref()); diff --git a/devtools/axon-tools/src/rlp_codec.rs b/devtools/axon-tools/src/rlp_codec.rs index bf820cce7..91da088f6 100644 --- a/devtools/axon-tools/src/rlp_codec.rs +++ b/devtools/axon-tools/src/rlp_codec.rs @@ -26,7 +26,7 @@ impl Encodable for Vote { .append(&self.height) .append(&self.round) .append(&vote_type) - .append(&self.block_hash.to_vec()); + .append(&self.proposal_hash.to_vec()); } } @@ -42,7 +42,7 @@ impl Encodable for Proposal { .append(&self.signed_txs_hash) .append(&self.timestamp) .append(&self.number) - .append(&self.gas_limit.as_u64()) + .append(&self.gas_limit.low_u64()) .append_list(&self.extra_data) .append(&self.proof) .append(&self.call_system_script_count) diff --git a/devtools/axon-tools/src/tests/block.json b/devtools/axon-tools/src/tests/block.json index f0c60095f..7016d9702 100644 --- a/devtools/axon-tools/src/tests/block.json +++ b/devtools/axon-tools/src/tests/block.json @@ -17,7 +17,7 @@ "proof": { "number": "0xe7c2", "round": "0x0", - "block_hash": "0x734f6e28a7caf9df326c21d8c57b89034ed02f782a11d04d18284b7aa4de43f0", + "proposal_hash": "0x734f6e28a7caf9df326c21d8c57b89034ed02f782a11d04d18284b7aa4de43f0", "signature": "0x933be0cd674477473bd68a55a53511a652fbcecfa4cafaa244d0b55ca3f6a7f296d50a2744337365fd6407d737cc389f054b70b3c82ee27a1669a43cc344ba7ad42a7cc663faa63190a739dc1c6a1a5d80d45f5903f42d118fc5e4d695cc4815", "bitmap": "0xb0" }, diff --git a/devtools/axon-tools/src/tests/proof.json b/devtools/axon-tools/src/tests/proof.json index 795e672bc..f3d15cb66 100644 --- a/devtools/axon-tools/src/tests/proof.json +++ b/devtools/axon-tools/src/tests/proof.json @@ -1,7 +1,7 @@ { "number": "0xe7c3", "round": "0x0", - "block_hash": "0x6e48fa2d2002453abd9b51e4ac0342abb1f027b8272d6e27ce79a630b3f26673", + "proposal_hash": "0x6e48fa2d2002453abd9b51e4ac0342abb1f027b8272d6e27ce79a630b3f26673", "signature": "0xb3e8e27db04baec18c04bc0b8ffe7fdbf2b5f7d6ef243c8be02bfd75defee32f1c0ff73a9fa67fee24630d2da5aa70f111ba41c0212be5d91b95f3bb84e5c0406b4742cca8c8f8362c07024fd8081d16875b01f43c6aa11c60b196af8c671a9b", "bitmap": "0x70" } diff --git a/devtools/axon-tools/src/tests/verify_proof.rs b/devtools/axon-tools/src/tests/verify_proof.rs index deb64858c..3a1e69f9d 100644 --- a/devtools/axon-tools/src/tests/verify_proof.rs +++ b/devtools/axon-tools/src/tests/verify_proof.rs @@ -5,7 +5,7 @@ use crate::types::{Block, BlockVersion, Metadata, Proof, Proposal, ValidatorExte #[cfg(feature = "proof")] use bytes::Bytes; #[cfg(feature = "proof")] -use ethereum_types::{H160, H256, U256}; +use ethereum_types::{H160, H256, U64}; #[cfg(feature = "proof")] use rlp::Encodable; #[cfg(feature = "proof")] @@ -29,15 +29,15 @@ fn test_proposal() { signed_txs_hash: H256::from([5u8; 32]), timestamp: 0, number: 100, - gas_limit: U256::from(6), + gas_limit: U64::from(6), extra_data: Vec::new(), - base_fee_per_gas: U256::from(7), + base_fee_per_gas: U64::from(7), proof: Proof { - number: 0, - round: 1, - block_hash: H256::from([1u8; 32]), - signature: Bytes::from("1234"), - bitmap: Bytes::from("abcd"), + number: 0, + round: 1, + proposal_hash: H256::from([1u8; 32]), + signature: Bytes::from("1234"), + bitmap: Bytes::from("abcd"), }, chain_id: 1000, call_system_script_count: 1, diff --git a/devtools/axon-tools/src/types.rs b/devtools/axon-tools/src/types.rs index e6bf0a7a1..11e6fc76f 100644 --- a/devtools/axon-tools/src/types.rs +++ b/devtools/axon-tools/src/types.rs @@ -12,7 +12,7 @@ use alloc::vec; use alloc::vec::Vec; use bytes::{Bytes, BytesMut}; use core::cmp::Ordering; -use ethereum_types::{Bloom, H160, H256, U256}; +use ethereum_types::{Bloom, H160, H256, U64}; #[cfg(feature = "impl-serde")] use serde::{Deserialize, Serialize}; @@ -209,13 +209,13 @@ pub struct Header { ) )] pub number: BlockNumber, - pub gas_used: U256, - pub gas_limit: U256, + pub gas_used: U64, + pub gas_limit: U64, /// Extra data for the block header /// The first index of extra_data is used to store hardfork information: /// `HardforkInfoInner` pub extra_data: Vec, - pub base_fee_per_gas: U256, + pub base_fee_per_gas: U64, pub proof: Proof, #[cfg_attr( all(feature = "impl-serde", feature = "std"), @@ -270,9 +270,9 @@ pub struct Proposal { serde(deserialize_with = "decode::deserialize_hex_u64") )] pub number: BlockNumber, - pub gas_limit: U256, + pub gas_limit: U64, pub extra_data: Vec, - pub base_fee_per_gas: U256, + pub base_fee_per_gas: U64, pub proof: Proof, #[cfg_attr( all(feature = "impl-serde", feature = "std"), @@ -301,7 +301,8 @@ pub struct Proof { deserialize_with = "decode::deserialize_hex_u64" ) )] - pub number: u64, + pub number: u64, + #[cfg_attr( all(feature = "impl-serde", feature = "std"), serde( @@ -309,8 +310,10 @@ pub struct Proof { deserialize_with = "decode::deserialize_hex_u64" ) )] - pub round: u64, - pub block_hash: Hash, + pub round: u64, + + pub proposal_hash: Hash, + #[cfg_attr( all(feature = "impl-serde", feature = "std"), serde( @@ -318,7 +321,8 @@ pub struct Proof { deserialize_with = "faster_hex::withpfx_lowercase::deserialize" ) )] - pub signature: Bytes, + pub signature: Bytes, + #[cfg_attr( all(feature = "impl-serde", feature = "std"), serde( @@ -326,7 +330,7 @@ pub struct Proof { deserialize_with = "faster_hex::withpfx_lowercase::deserialize" ) )] - pub bitmap: Bytes, + pub bitmap: Bytes, } #[cfg(feature = "proof")] @@ -360,10 +364,10 @@ impl core::cmp::Ord for Validator { #[cfg_attr(doc_cfg, doc(cfg(feature = "proof")))] #[cfg_attr(feature = "impl-serde", derive(serde::Serialize, serde::Deserialize))] pub struct Vote { - pub height: u64, - pub round: u64, - pub vote_type: u8, - pub block_hash: Bytes, + pub height: u64, + pub round: u64, + pub vote_type: u8, + pub proposal_hash: Bytes, } #[cfg(test)] @@ -371,10 +375,10 @@ pub struct Vote { impl Vote { fn random() -> Self { Self { - height: rand::random(), - round: rand::random(), - vote_type: 2, - block_hash: tests::random_bytes(32), + height: rand::random(), + round: rand::random(), + vote_type: 2, + proposal_hash: tests::random_bytes(32), } } } @@ -445,42 +449,49 @@ pub struct ConsensusConfig { all(feature = "impl-serde", feature = "std"), serde(deserialize_with = "decode::deserialize_hex_u64") )] - pub gas_limit: u64, + pub gas_limit: u64, + #[cfg_attr( all(feature = "impl-serde", feature = "std"), serde(deserialize_with = "decode::deserialize_hex_u64") )] - pub interval: u64, + pub interval: u64, + #[cfg_attr( all(feature = "impl-serde", feature = "std"), serde(deserialize_with = "decode::deserialize_hex_u64") )] - pub propose_ratio: u64, + pub propose_ratio: u64, + #[cfg_attr( all(feature = "impl-serde", feature = "std"), serde(deserialize_with = "decode::deserialize_hex_u64") )] - pub prevote_ratio: u64, + pub prevote_ratio: u64, + #[cfg_attr( all(feature = "impl-serde", feature = "std"), serde(deserialize_with = "decode::deserialize_hex_u64") )] pub precommit_ratio: u64, + #[cfg_attr( all(feature = "impl-serde", feature = "std"), serde(deserialize_with = "decode::deserialize_hex_u64") )] - pub brake_ratio: u64, + pub brake_ratio: u64, + #[cfg_attr( all(feature = "impl-serde", feature = "std"), serde(deserialize_with = "decode::deserialize_hex_u64") )] - pub tx_num_limit: u64, + pub tx_num_limit: u64, + #[cfg_attr( all(feature = "impl-serde", feature = "std"), serde(deserialize_with = "decode::deserialize_hex_u64") )] - pub max_tx_size: u64, + pub max_tx_size: u64, } #[derive(Clone, Debug, PartialEq, Eq)] @@ -733,6 +744,6 @@ mod tests { let decoded: overlord::types::Vote = rlp::decode(&raw).unwrap(); assert_eq!(vote.height, decoded.height); assert_eq!(vote.round, decoded.round); - assert_eq!(vote.block_hash, decoded.block_hash); + assert_eq!(vote.proposal_hash, decoded.block_hash); } } diff --git a/protocol/Cargo.toml b/protocol/Cargo.toml index db9374b6a..36d263548 100644 --- a/protocol/Cargo.toml +++ b/protocol/Cargo.toml @@ -36,7 +36,7 @@ rlp = "0.5" rlp-derive = "0.1" serde = { version = "1.0", features = ["derive"] } thiserror = "1.0" -tokio = { version = "1.33", features = ["full"] } +tokio = { version = "1.34", features = ["full"] } trie = { package = "cita_trie", version = "5.0" } zeroize = "1.6.0" diff --git a/protocol/src/codec/block.rs b/protocol/src/codec/block.rs index c2368fee7..f19d856ed 100644 --- a/protocol/src/codec/block.rs +++ b/protocol/src/codec/block.rs @@ -3,8 +3,8 @@ use std::error::Error; use overlord::Codec; use rlp::{Decodable, DecoderError, Encodable, Rlp, RlpStream}; -use crate::types::{BlockVersion, Bytes, Proposal, BASE_FEE_PER_GAS}; -use crate::{codec::error::CodecError, lazy::CHAIN_ID, ProtocolError}; +use crate::types::{BlockVersion, Bytes, Proposal}; +use crate::{codec::error::CodecError, constants::BASE_FEE_PER_GAS, lazy::CHAIN_ID, ProtocolError}; impl Encodable for BlockVersion { fn rlp_append(&self, s: &mut RlpStream) { @@ -32,7 +32,7 @@ impl Encodable for Proposal { .append(&self.signed_txs_hash) .append(&self.timestamp) .append(&self.number) - .append(&self.gas_limit.as_u64()) + .append(&self.gas_limit.low_u64()) .append_list(&self.extra_data) .append(&self.proof) .append(&self.call_system_script_count) diff --git a/protocol/src/codec/transaction.rs b/protocol/src/codec/transaction.rs index 9659b5a5d..513a84135 100644 --- a/protocol/src/codec/transaction.rs +++ b/protocol/src/codec/transaction.rs @@ -370,7 +370,7 @@ mod tests { use common_crypto::secp256k1_recover; use crate::codec::hex_decode; - use crate::types::{Public, SignatureS, Witness, H160, U256}; + use crate::types::{Public, SignatureS, Witness, H160, U256, U64}; #[test] fn test_legacy_decode() { @@ -379,9 +379,9 @@ mod tests { assert!(tx.check_hash().is_ok()); assert!(tx.unsigned.data().is_empty()); - assert_eq!(*tx.unsigned.gas_limit(), U256::from(0x5208u64)); - assert_eq!(tx.unsigned.gas_price(), U256::from(0x01u64)); - assert_eq!(*tx.unsigned.nonce(), U256::from(0x00u64)); + assert_eq!(*tx.unsigned.gas_limit(), U64::from(0x5208u64)); + assert_eq!(tx.unsigned.gas_price(), U64::from(0x01u64)); + assert_eq!(*tx.unsigned.nonce(), U64::from(0x00u64)); assert_eq!( tx.unsigned.to().unwrap(), H160::from_slice(&hex_decode("095e7baea6a6c7c4c2dfeb977efac326af552d87").unwrap()) @@ -401,9 +401,9 @@ mod tests { let tx = UnverifiedTransaction::decode(&Rlp::new(&bytes)).unwrap(); assert!(tx.unsigned.data().is_empty()); - assert_eq!(*tx.unsigned.gas_limit(), U256::from(0x5208u64)); - assert_eq!(tx.unsigned.gas_price(), U256::from(0x01u64)); - assert_eq!(*tx.unsigned.nonce(), U256::from(0x00u64)); + assert_eq!(*tx.unsigned.gas_limit(), U64::from(0x5208u64)); + assert_eq!(tx.unsigned.gas_price(), U64::from(0x01u64)); + assert_eq!(*tx.unsigned.nonce(), U64::from(0x00u64)); assert_eq!( tx.unsigned.to().unwrap(), H160::from_slice(&hex_decode("095e7baea6a6c7c4c2dfeb977efac326af552d87").unwrap()) @@ -422,9 +422,9 @@ mod tests { let tx = UnverifiedTransaction::decode(&Rlp::new(&bytes)).unwrap(); assert!(tx.unsigned.data().is_empty()); - assert_eq!(*tx.unsigned.gas_limit(), U256::from(0x5208u64)); - assert_eq!(tx.unsigned.gas_price(), U256::from(0x02540be400u64)); - assert_eq!(*tx.unsigned.nonce(), U256::from(0x05u64)); + assert_eq!(*tx.unsigned.gas_limit(), U64::from(0x5208u64)); + assert_eq!(tx.unsigned.gas_price(), U64::from(0x02540be400u64)); + assert_eq!(*tx.unsigned.nonce(), U64::from(0x05u64)); assert_eq!( tx.unsigned.to().unwrap(), H160::from_slice(&hex_decode("f386573563c3a75dbbd269fce9782620826ddac2").unwrap()) @@ -443,9 +443,9 @@ mod tests { let bytes = hex_decode("0xf90a388085174876e800830c35008080b909e5608060405234801561001057600080fd5b506109c5806100206000396000f3fe608060405234801561001057600080fd5b50600436106100a5576000357c010000000000000000000000000000000000000000000000000000000090048063a41e7d5111610078578063a41e7d51146101d4578063aabbb8ca1461020a578063b705676514610236578063f712f3e814610280576100a5565b806329965a1d146100aa5780633d584063146100e25780635df8122f1461012457806365ba36c114610152575b600080fd5b6100e0600480360360608110156100c057600080fd5b50600160a060020a038135811691602081013591604090910135166102b6565b005b610108600480360360208110156100f857600080fd5b5035600160a060020a0316610570565b60408051600160a060020a039092168252519081900360200190f35b6100e06004803603604081101561013a57600080fd5b50600160a060020a03813581169160200135166105bc565b6101c26004803603602081101561016857600080fd5b81019060208101813564010000000081111561018357600080fd5b82018360208201111561019557600080fd5b803590602001918460018302840111640100000000831117156101b757600080fd5b5090925090506106b3565b60408051918252519081900360200190f35b6100e0600480360360408110156101ea57600080fd5b508035600160a060020a03169060200135600160e060020a0319166106ee565b6101086004803603604081101561022057600080fd5b50600160a060020a038135169060200135610778565b61026c6004803603604081101561024c57600080fd5b508035600160a060020a03169060200135600160e060020a0319166107ef565b604080519115158252519081900360200190f35b61026c6004803603604081101561029657600080fd5b508035600160a060020a03169060200135600160e060020a0319166108aa565b6000600160a060020a038416156102cd57836102cf565b335b9050336102db82610570565b600160a060020a031614610339576040805160e560020a62461bcd02815260206004820152600f60248201527f4e6f7420746865206d616e616765720000000000000000000000000000000000604482015290519081900360640190fd5b6103428361092a565b15610397576040805160e560020a62461bcd02815260206004820152601a60248201527f4d757374206e6f7420626520616e204552433136352068617368000000000000604482015290519081900360640190fd5b600160a060020a038216158015906103b85750600160a060020a0382163314155b156104ff5760405160200180807f455243313832305f4143434550545f4d4147494300000000000000000000000081525060140190506040516020818303038152906040528051906020012082600160a060020a031663249cb3fa85846040518363ffffffff167c01000000000000000000000000000000000000000000000000000000000281526004018083815260200182600160a060020a0316600160a060020a031681526020019250505060206040518083038186803b15801561047e57600080fd5b505afa158015610492573d6000803e3d6000fd5b505050506040513d60208110156104a857600080fd5b5051146104ff576040805160e560020a62461bcd02815260206004820181905260248201527f446f6573206e6f7420696d706c656d656e742074686520696e74657266616365604482015290519081900360640190fd5b600160a060020a03818116600081815260208181526040808320888452909152808220805473ffffffffffffffffffffffffffffffffffffffff19169487169485179055518692917f93baa6efbd2244243bfee6ce4cfdd1d04fc4c0e9a786abd3a41313bd352db15391a450505050565b600160a060020a03818116600090815260016020526040812054909116151561059a5750806105b7565b50600160a060020a03808216600090815260016020526040902054165b919050565b336105c683610570565b600160a060020a031614610624576040805160e560020a62461bcd02815260206004820152600f60248201527f4e6f7420746865206d616e616765720000000000000000000000000000000000604482015290519081900360640190fd5b81600160a060020a031681600160a060020a0316146106435780610646565b60005b600160a060020a03838116600081815260016020526040808220805473ffffffffffffffffffffffffffffffffffffffff19169585169590951790945592519184169290917f605c2dbf762e5f7d60a546d42e7205dcb1b011ebc62a61736a57c9089d3a43509190a35050565b600082826040516020018083838082843780830192505050925050506040516020818303038152906040528051906020012090505b92915050565b6106f882826107ef565b610703576000610705565b815b600160a060020a03928316600081815260208181526040808320600160e060020a031996909616808452958252808320805473ffffffffffffffffffffffffffffffffffffffff19169590971694909417909555908152600284528181209281529190925220805460ff19166001179055565b600080600160a060020a038416156107905783610792565b335b905061079d8361092a565b156107c357826107ad82826108aa565b6107b85760006107ba565b815b925050506106e8565b600160a060020a0390811660009081526020818152604080832086845290915290205416905092915050565b6000808061081d857f01ffc9a70000000000000000000000000000000000000000000000000000000061094c565b909250905081158061082d575080155b1561083d576000925050506106e8565b61084f85600160e060020a031961094c565b909250905081158061086057508015155b15610870576000925050506106e8565b61087a858561094c565b909250905060018214801561088f5750806001145b1561089f576001925050506106e8565b506000949350505050565b600160a060020a0382166000908152600260209081526040808320600160e060020a03198516845290915281205460ff1615156108f2576108eb83836107ef565b90506106e8565b50600160a060020a03808316600081815260208181526040808320600160e060020a0319871684529091529020549091161492915050565b7bffffffffffffffffffffffffffffffffffffffffffffffffffffffff161590565b6040517f01ffc9a7000000000000000000000000000000000000000000000000000000008082526004820183905260009182919060208160248189617530fa90519096909550935050505056fea165627a7a72305820377f4a2d4301ede9949f163f319021a6e9c687c292a5e2b2c4734c126b524e6c00291ba01820182018201820182018201820182018201820182018201820182018201820a01820182018201820182018201820182018201820182018201820182018201820").unwrap(); let tx = UnverifiedTransaction::decode(&Rlp::new(&bytes)).unwrap(); - assert_eq!(*tx.unsigned.gas_limit(), U256::from(0x0c3500u64)); - assert_eq!(tx.unsigned.gas_price(), U256::from(0x174876e800u64)); - assert_eq!(*tx.unsigned.nonce(), U256::from(0x00u64)); + assert_eq!(*tx.unsigned.gas_limit(), U64::from(0x0c3500u64)); + assert_eq!(tx.unsigned.gas_price(), U64::from(0x174876e800u64)); + assert_eq!(*tx.unsigned.nonce(), U64::from(0x00u64)); assert_eq!( tx.unsigned.data(), hex_decode("608060405234801561001057600080fd5b506109c5806100206000396000f3fe608060405234801561001057600080fd5b50600436106100a5576000357c010000000000000000000000000000000000000000000000000000000090048063a41e7d5111610078578063a41e7d51146101d4578063aabbb8ca1461020a578063b705676514610236578063f712f3e814610280576100a5565b806329965a1d146100aa5780633d584063146100e25780635df8122f1461012457806365ba36c114610152575b600080fd5b6100e0600480360360608110156100c057600080fd5b50600160a060020a038135811691602081013591604090910135166102b6565b005b610108600480360360208110156100f857600080fd5b5035600160a060020a0316610570565b60408051600160a060020a039092168252519081900360200190f35b6100e06004803603604081101561013a57600080fd5b50600160a060020a03813581169160200135166105bc565b6101c26004803603602081101561016857600080fd5b81019060208101813564010000000081111561018357600080fd5b82018360208201111561019557600080fd5b803590602001918460018302840111640100000000831117156101b757600080fd5b5090925090506106b3565b60408051918252519081900360200190f35b6100e0600480360360408110156101ea57600080fd5b508035600160a060020a03169060200135600160e060020a0319166106ee565b6101086004803603604081101561022057600080fd5b50600160a060020a038135169060200135610778565b61026c6004803603604081101561024c57600080fd5b508035600160a060020a03169060200135600160e060020a0319166107ef565b604080519115158252519081900360200190f35b61026c6004803603604081101561029657600080fd5b508035600160a060020a03169060200135600160e060020a0319166108aa565b6000600160a060020a038416156102cd57836102cf565b335b9050336102db82610570565b600160a060020a031614610339576040805160e560020a62461bcd02815260206004820152600f60248201527f4e6f7420746865206d616e616765720000000000000000000000000000000000604482015290519081900360640190fd5b6103428361092a565b15610397576040805160e560020a62461bcd02815260206004820152601a60248201527f4d757374206e6f7420626520616e204552433136352068617368000000000000604482015290519081900360640190fd5b600160a060020a038216158015906103b85750600160a060020a0382163314155b156104ff5760405160200180807f455243313832305f4143434550545f4d4147494300000000000000000000000081525060140190506040516020818303038152906040528051906020012082600160a060020a031663249cb3fa85846040518363ffffffff167c01000000000000000000000000000000000000000000000000000000000281526004018083815260200182600160a060020a0316600160a060020a031681526020019250505060206040518083038186803b15801561047e57600080fd5b505afa158015610492573d6000803e3d6000fd5b505050506040513d60208110156104a857600080fd5b5051146104ff576040805160e560020a62461bcd02815260206004820181905260248201527f446f6573206e6f7420696d706c656d656e742074686520696e74657266616365604482015290519081900360640190fd5b600160a060020a03818116600081815260208181526040808320888452909152808220805473ffffffffffffffffffffffffffffffffffffffff19169487169485179055518692917f93baa6efbd2244243bfee6ce4cfdd1d04fc4c0e9a786abd3a41313bd352db15391a450505050565b600160a060020a03818116600090815260016020526040812054909116151561059a5750806105b7565b50600160a060020a03808216600090815260016020526040902054165b919050565b336105c683610570565b600160a060020a031614610624576040805160e560020a62461bcd02815260206004820152600f60248201527f4e6f7420746865206d616e616765720000000000000000000000000000000000604482015290519081900360640190fd5b81600160a060020a031681600160a060020a0316146106435780610646565b60005b600160a060020a03838116600081815260016020526040808220805473ffffffffffffffffffffffffffffffffffffffff19169585169590951790945592519184169290917f605c2dbf762e5f7d60a546d42e7205dcb1b011ebc62a61736a57c9089d3a43509190a35050565b600082826040516020018083838082843780830192505050925050506040516020818303038152906040528051906020012090505b92915050565b6106f882826107ef565b610703576000610705565b815b600160a060020a03928316600081815260208181526040808320600160e060020a031996909616808452958252808320805473ffffffffffffffffffffffffffffffffffffffff19169590971694909417909555908152600284528181209281529190925220805460ff19166001179055565b600080600160a060020a038416156107905783610792565b335b905061079d8361092a565b156107c357826107ad82826108aa565b6107b85760006107ba565b815b925050506106e8565b600160a060020a0390811660009081526020818152604080832086845290915290205416905092915050565b6000808061081d857f01ffc9a70000000000000000000000000000000000000000000000000000000061094c565b909250905081158061082d575080155b1561083d576000925050506106e8565b61084f85600160e060020a031961094c565b909250905081158061086057508015155b15610870576000925050506106e8565b61087a858561094c565b909250905060018214801561088f5750806001145b1561089f576001925050506106e8565b506000949350505050565b600160a060020a0382166000908152600260209081526040808320600160e060020a03198516845290915281205460ff1615156108f2576108eb83836107ef565b90506106e8565b50600160a060020a03808316600081815260208181526040808320600160e060020a0319871684529091529020549091161492915050565b7bffffffffffffffffffffffffffffffffffffffffffffffffffffffff161590565b6040517f01ffc9a7000000000000000000000000000000000000000000000000000000008082526004820183905260009182919060208160248189617530fa90519096909550935050505056fea165627a7a72305820377f4a2d4301ede9949f163f319021a6e9c687c292a5e2b2c4734c126b524e6c0029").unwrap() diff --git a/protocol/src/constants/configs.rs b/protocol/src/constants/configs.rs new file mode 100644 index 000000000..c09edd2ac --- /dev/null +++ b/protocol/src/constants/configs.rs @@ -0,0 +1,20 @@ +use crate::types::U64; + +/// There is not a standard for the maximum gas limit, as long as the account +/// balance can pay the `gas_limit * gas_price`. For reduce some useless +/// calculation, `30_000_000` is large enough to cover the transaction usage. +pub const MAX_GAS_LIMIT: u64 = 30_000_000; +/// According to [go-ethereum](https://github.com/ethereum/go-ethereum/blob/be65b47/eth/gasprice/gasprice.go#L38), +/// the maximum gas price is 500 Gwei. +pub const MAX_GAS_PRICE: U64 = U64([500 * GWEI]); +pub const MIN_TRANSACTION_GAS_LIMIT: u64 = 21_000; +/// The mempool refresh timeout is 50 milliseconds. +pub const MEMPOOL_REFRESH_TIMEOUT: u64 = 50; +pub const MAX_BLOCK_GAS_LIMIT: u64 = 30_000_000; +// MAX_FEE_HISTORY is the maximum number of blocks that can be retrieved for a +// fee history request. Between 1 and 1024 blocks can be requested in a single +// query. reference: https://docs.infura.io/infura/networks/ethereum/json-rpc-methods/eth_feehistory/ +pub const MAX_FEE_HISTORY: u64 = 1024; +pub const BASE_FEE_PER_GAS: u64 = 0x539; + +const GWEI: u64 = 1_000_000_000; diff --git a/protocol/src/constants/mod.rs b/protocol/src/constants/mod.rs index c4b360f4b..8c5992f31 100644 --- a/protocol/src/constants/mod.rs +++ b/protocol/src/constants/mod.rs @@ -1 +1,4 @@ +mod configs; pub mod endpoints; + +pub use configs::*; diff --git a/protocol/src/lib.rs b/protocol/src/lib.rs index 9bf7d0963..ad1dcd379 100644 --- a/protocol/src/lib.rs +++ b/protocol/src/lib.rs @@ -12,8 +12,6 @@ pub use { trie, }; -pub const MEMPOOL_REFRESH_TIMEOUT: u64 = 50; - #[derive(Copy, Clone, Debug)] pub enum ProtocolErrorKind { // traits diff --git a/protocol/src/traits/api.rs b/protocol/src/traits/api.rs index 0964a1dfc..ae1334710 100644 --- a/protocol/src/traits/api.rs +++ b/protocol/src/traits/api.rs @@ -1,7 +1,7 @@ use crate::types::{ Account, Block, BlockNumber, Bytes, CkbRelatedInfo, EthAccountProof, HardforkInfo, HardforkInfoInner, Hash, Header, Metadata, Proposal, Receipt, SignedTransaction, TxResp, H160, - H256, U256, + H256, U256, U64, }; use crate::{async_trait, traits::Context, ProtocolResult}; @@ -79,8 +79,8 @@ pub trait APIAdapter: Send + Sync { ctx: Context, from: Option, to: Option, - gas_price: Option, - gas_limit: Option, + gas_price: Option, + gas_limit: Option, value: U256, data: Vec, estimate: bool, diff --git a/protocol/src/traits/executor.rs b/protocol/src/traits/executor.rs index f46790d4e..44940f20b 100644 --- a/protocol/src/traits/executor.rs +++ b/protocol/src/traits/executor.rs @@ -2,7 +2,7 @@ pub use evm::backend::{ApplyBackend, Backend, MemoryBackend}; use crate::types::{ Account, Bytes, ExecResp, ExecutorContext, Log, MerkleRoot, SignedTransaction, TxResp, - ValidatorExtend, H160, U256, + ValidatorExtend, H160, U256, U64, }; pub trait ExecutorReadOnlyAdapter: Backend { @@ -16,7 +16,7 @@ pub trait ExecutorReadOnlyAdapter: Backend { pub trait ExecutorAdapter: ExecutorReadOnlyAdapter + ApplyBackend { fn set_origin(&mut self, origin: H160); - fn set_gas_price(&mut self, gas_price: U256); + fn set_gas_price(&mut self, gas_price: U64); fn save_account(&mut self, address: &H160, account: &Account); @@ -65,7 +65,7 @@ impl<'a> ExecutorAdapter for MemoryBackend<'a> { unreachable!() } - fn set_gas_price(&mut self, _gas_price: U256) { + fn set_gas_price(&mut self, _gas_price: U64) { unreachable!() } diff --git a/protocol/src/traits/mempool.rs b/protocol/src/traits/mempool.rs index 9c77c1c9d..c0ddfc89e 100644 --- a/protocol/src/traits/mempool.rs +++ b/protocol/src/traits/mempool.rs @@ -1,4 +1,6 @@ -use crate::types::{BlockNumber, Hash, MerkleRoot, PackedTxHashes, SignedTransaction, H160, U256}; +use crate::types::{ + BlockNumber, Hash, MerkleRoot, PackedTxHashes, SignedTransaction, H160, U256, U64, +}; use crate::{async_trait, traits::Context, ProtocolResult}; #[async_trait] @@ -65,7 +67,7 @@ pub trait MemPoolAdapter: Send + Sync { &self, ctx: Context, tx: &SignedTransaction, - ) -> ProtocolResult; + ) -> ProtocolResult; async fn check_transaction(&self, ctx: Context, tx: &SignedTransaction) -> ProtocolResult<()>; diff --git a/protocol/src/types/block.rs b/protocol/src/types/block.rs index 4dfbd7f0b..95d68f1c0 100644 --- a/protocol/src/types/block.rs +++ b/protocol/src/types/block.rs @@ -7,20 +7,12 @@ use serde::{Deserialize, Serialize}; use crate::codec::serialize_uint; use crate::types::{ logs_bloom, Bloom, BloomInput, Bytes, ExecResp, Hash, Hasher, Log, MerkleRoot, Receipt, - SignedTransaction, VecDisplayHelper, H160, U256, + SignedTransaction, VecDisplayHelper, H160, U64, }; use crate::{codec::ProtocolCodec, types::TypesError}; pub type BlockNumber = u64; -pub const MAX_BLOCK_GAS_LIMIT: u64 = 30_000_000; -// MAX_FEE_HISTORY is the maximum number of blocks that can be retrieved for a -// fee history request. Between 1 and 1024 blocks can be requested in a single -// query. reference: https://docs.infura.io/infura/networks/ethereum/json-rpc-methods/eth_feehistory/ -pub const MAX_FEE_HISTORY: u64 = 1024; -pub const MAX_RPC_GAS_CAP: u64 = 50_000_000; -pub const BASE_FEE_PER_GAS: u64 = 0x539; - #[derive(Serialize, Deserialize, Default, Copy, Clone, Debug, PartialEq, Eq, Display)] pub enum BlockVersion { #[default] @@ -81,9 +73,9 @@ pub struct Proposal { pub timestamp: u64, #[cfg_attr(feature = "hex-serialize", serde(serialize_with = "serialize_uint"))] pub number: BlockNumber, - pub gas_limit: U256, + pub gas_limit: U64, pub extra_data: Vec, - pub base_fee_per_gas: U256, + pub base_fee_per_gas: U64, pub proof: Proof, #[cfg_attr(feature = "hex-serialize", serde(serialize_with = "serialize_uint"))] pub chain_id: u64, @@ -217,7 +209,7 @@ impl Block { block_hash: self.hash(), tx_index: idx as u32, state_root: self.header.state_root, - used_gas: U256::from(res.gas_used), + used_gas: U64::from(res.gas_used), logs_bloom: logs_bloom(res.logs.iter()), logs: res.logs.clone(), log_index, @@ -286,13 +278,13 @@ pub struct Header { pub timestamp: u64, #[cfg_attr(feature = "hex-serialize", serde(serialize_with = "serialize_uint"))] pub number: BlockNumber, - pub gas_used: U256, - pub gas_limit: U256, + pub gas_used: U64, + pub gas_limit: U64, /// Extra data for the block header /// The first index of extra_data is used to store hardfork information: /// `HardforkInfoInner` pub extra_data: Vec, - pub base_fee_per_gas: U256, + pub base_fee_per_gas: U64, pub proof: Proof, #[cfg_attr(feature = "hex-serialize", serde(serialize_with = "serialize_uint"))] pub call_system_script_count: u32, @@ -359,6 +351,7 @@ pub struct Proof { pub number: u64, #[cfg_attr(feature = "hex-serialize", serde(serialize_with = "serialize_uint"))] pub round: u64, + #[serde(rename = "proposal_hash")] pub block_hash: Hash, #[cfg_attr( feature = "hex-serialize", diff --git a/protocol/src/types/executor.rs b/protocol/src/types/executor.rs index 9328ef81c..59895b56a 100644 --- a/protocol/src/types/executor.rs +++ b/protocol/src/types/executor.rs @@ -6,7 +6,7 @@ use rlp_derive::{RlpDecodable, RlpEncodable}; use serde::{Deserialize, Serialize}; use crate::types::{ - Bloom, ExtraData, Hash, Hasher, Header, MerkleRoot, Proposal, H160, H256, U256, + Bloom, ExtraData, Hash, Hasher, Header, MerkleRoot, Proposal, H160, H256, U256, U64, }; use super::Hex; @@ -56,8 +56,8 @@ pub struct ExecutorContext { pub chain_id: U256, pub origin: H160, pub gas_price: U256, - pub block_gas_limit: U256, - pub block_base_fee_per_gas: U256, + pub block_gas_limit: U64, + pub block_base_fee_per_gas: U64, pub extra_data: Vec, } diff --git a/protocol/src/types/mod.rs b/protocol/src/types/mod.rs index 1b8fcbce1..34530cf77 100644 --- a/protocol/src/types/mod.rs +++ b/protocol/src/types/mod.rs @@ -87,6 +87,9 @@ pub enum TypesError { #[display(fmt = "Decode interoperation signature R error {:?}", _0)] DecodeInteroperationSigR(rlp::DecoderError), + + #[display(fmt = "Prepay gas is too large")] + PrepayGasIsTooLarge, } impl Error for TypesError {} diff --git a/protocol/src/types/primitive.rs b/protocol/src/types/primitive.rs index eaa1ce78e..5196108e2 100644 --- a/protocol/src/types/primitive.rs +++ b/protocol/src/types/primitive.rs @@ -174,7 +174,6 @@ impl<'de> Deserialize<'de> for Hex { } /// A 256 bits bytes used for sensitive data, such as private keys. -/// /// It's implemented a `Drop` handler which erase its memory when it dropped. /// This ensures that sensitive data is securely erased from memory when it is /// no longer needed. diff --git a/protocol/src/types/receipt.rs b/protocol/src/types/receipt.rs index 4e57289b8..62019dd30 100644 --- a/protocol/src/types/receipt.rs +++ b/protocol/src/types/receipt.rs @@ -1,7 +1,7 @@ pub use ethereum::Log; pub use ethereum_types::BloomInput; -use crate::types::{Bloom, ExitReason, ExitSucceed, Hash, MerkleRoot, H160, U256}; +use crate::types::{Bloom, ExitReason, ExitSucceed, Hash, MerkleRoot, H160, U64}; #[derive(Clone, Debug, PartialEq, Eq)] pub struct Receipt { @@ -10,7 +10,7 @@ pub struct Receipt { pub block_hash: Hash, pub tx_index: u32, pub state_root: MerkleRoot, - pub used_gas: U256, + pub used_gas: U64, pub logs_bloom: Bloom, pub logs: Vec, pub log_index: u32, @@ -41,10 +41,10 @@ impl Default for Receipt { } impl Receipt { - pub fn status(&self) -> U256 { + pub fn status(&self) -> U64 { match self.ret { - ExitReason::Succeed(_) => U256::one(), - _ => U256::zero(), + ExitReason::Succeed(_) => U64::one(), + _ => U64::zero(), } } } diff --git a/protocol/src/types/transaction.rs b/protocol/src/types/transaction.rs index 563ff0ff1..20d2c06b9 100644 --- a/protocol/src/types/transaction.rs +++ b/protocol/src/types/transaction.rs @@ -9,12 +9,11 @@ use common_crypto::secp256k1_recover; use crate::types::{ Bloom, Bytes, BytesMut, CellDepWithPubKey, ExitReason, Hash, Hasher, Public, TxResp, - TypesError, H160, H256, H520, U256, + TypesError, H160, H256, H520, U256, U64, }; use crate::ProtocolResult; pub const MAX_PRIORITY_FEE_PER_GAS: u64 = 1_337; -pub const MIN_TRANSACTION_GAS_LIMIT: u64 = 21_000; #[derive(Serialize, Deserialize, Clone, Debug, Hash, PartialEq, Eq)] pub enum UnsignedTransaction { @@ -32,14 +31,16 @@ impl UnsignedTransaction { } } - pub fn may_cost(&self) -> U256 { - if let Some(res) = self.gas_price().checked_mul(*self.gas_limit()) { - return res + pub fn may_cost(&self) -> ProtocolResult { + if let Some(res) = U256::from(self.gas_price().low_u64()) + .checked_mul(U256::from(self.gas_limit().low_u64())) + { + return Ok(res .checked_add(*self.value()) - .unwrap_or_else(U256::max_value); + .unwrap_or_else(U256::max_value)); } - U256::max_value() + Err(TypesError::PrepayGasIsTooLarge.into()) } pub fn is_legacy(&self) -> bool { @@ -74,7 +75,7 @@ impl UnsignedTransaction { } } - pub fn gas_price(&self) -> U256 { + pub fn gas_price(&self) -> U64 { match self { UnsignedTransaction::Legacy(tx) => tx.gas_price, UnsignedTransaction::Eip2930(tx) => tx.gas_price, @@ -82,7 +83,7 @@ impl UnsignedTransaction { } } - pub fn max_priority_fee_per_gas(&self) -> &U256 { + pub fn max_priority_fee_per_gas(&self) -> &U64 { match self { UnsignedTransaction::Legacy(tx) => &tx.gas_price, UnsignedTransaction::Eip2930(tx) => &tx.gas_price, @@ -135,7 +136,7 @@ impl UnsignedTransaction { } } - pub fn gas_limit(&self) -> &U256 { + pub fn gas_limit(&self) -> &U64 { match self { UnsignedTransaction::Legacy(tx) => &tx.gas_limit, UnsignedTransaction::Eip2930(tx) => &tx.gas_limit, @@ -143,7 +144,7 @@ impl UnsignedTransaction { } } - pub fn nonce(&self) -> &U256 { + pub fn nonce(&self) -> &U64 { match self { UnsignedTransaction::Legacy(tx) => &tx.nonce, UnsignedTransaction::Eip2930(tx) => &tx.nonce, @@ -170,9 +171,11 @@ impl UnsignedTransaction { #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] pub struct LegacyTransaction { - pub nonce: U256, - pub gas_price: U256, - pub gas_limit: U256, + /// According to [EIP-2681](https://eips.ethereum.org/EIPS/eip-2681), + /// limit account nonce to 2^64-1. + pub nonce: U64, + pub gas_price: U64, + pub gas_limit: U64, pub action: TransactionAction, pub value: U256, pub data: Bytes, @@ -202,9 +205,11 @@ impl LegacyTransaction { #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] pub struct Eip2930Transaction { - pub nonce: U256, - pub gas_price: U256, - pub gas_limit: U256, + /// According to [EIP-2681](https://eips.ethereum.org/EIPS/eip-2681), + /// limit account nonce to 2^64-1. + pub nonce: U64, + pub gas_price: U64, + pub gas_limit: U64, pub action: TransactionAction, pub value: U256, pub data: Bytes, @@ -239,10 +244,10 @@ impl Eip2930Transaction { #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] pub struct Eip1559Transaction { - pub nonce: U256, - pub max_priority_fee_per_gas: U256, - pub gas_price: U256, - pub gas_limit: U256, + pub nonce: U64, + pub max_priority_fee_per_gas: U64, + pub gas_price: U64, + pub gas_limit: U64, pub action: TransactionAction, pub value: U256, pub data: Bytes, diff --git a/tests/e2e/src/eth_call.test.js b/tests/e2e/src/eth_call.test.js index 8b04eb8d2..feb31f9f6 100644 --- a/tests/e2e/src/eth_call.test.js +++ b/tests/e2e/src/eth_call.test.js @@ -235,7 +235,7 @@ describe("eth_call", () => { await param1.type(testDataInfo.accountAddress); await param2.type(testDataInfo.contractAddress); await param3.type("0x210000"); - await param4.type("0xfffffffffff"); + await param4.type("0xffff"); await param5.type("0x0"); await param6.type("0x06fdde03"); await param7.type("latest"); @@ -264,7 +264,7 @@ describe("eth_call", () => { await param1.type(testDataInfo.contractAddress); await param2.type(testDataInfo.contractAddress); await param3.type("0x210000"); - await param4.type("0xfffffffffff"); + await param4.type("0xffff"); await param5.type("0x0"); await param6.type("0x06fdde03"); await param7.type("latest"); @@ -293,7 +293,7 @@ describe("eth_call", () => { await param1.type(testDataInfo.contractAddress); await param2.type("0x63010dD4c3164dd0D73eCB518972916161fBACd9"); await param3.type("0x210000"); - await param4.type("0xfffffffffff"); + await param4.type("0xffff"); await param5.type("0x0"); await param6.type("0x06fdde03"); await param7.type("latest"); @@ -322,7 +322,7 @@ describe("eth_call", () => { await param1.type("0x735EaC8A5f3F197799f2FEaEbc0F6B3F6e4c345D"); await param2.type(testDataInfo.contractAddress); await param3.type("0x210000"); - await param4.type("0xfffffffffff"); + await param4.type("0xffff"); await param5.type("0x0"); await param6.type("0x06fdde03"); await param7.type("latest");