From f7457d2bc2815f8e1b459d111962c65d1ce0565f Mon Sep 17 00:00:00 2001 From: Eason Gao Date: Thu, 21 Sep 2023 14:24:20 +0800 Subject: [PATCH] chore: bump jsonrpsee and ckb related crates version (#1438) * chore: bump ckb related crates and jsonrpsee version * format some code * bump ckb-vm version * fix e2e test --- Cargo.lock | 270 ++++++++++-------- common/apm-derive/Cargo.toml | 2 +- common/config-parser/src/lib.rs | 6 +- common/config-parser/src/types/spec.rs | 6 +- core/api/Cargo.toml | 8 +- core/api/src/jsonrpc/error.rs | 153 ++++++++-- core/api/src/jsonrpc/impl/axon.rs | 28 +- core/api/src/jsonrpc/impl/ckb_light_client.rs | 8 +- core/api/src/jsonrpc/impl/filter.rs | 43 ++- core/api/src/jsonrpc/impl/web3.rs | 174 +++++------ core/api/src/jsonrpc/mod.rs | 16 +- core/api/src/jsonrpc/ws_subscription.rs | 84 +++--- core/db/src/rocks.rs | 1 - core/executor/Cargo.toml | 8 +- .../src/precompiles/verify_by_ckb_vm.rs | 2 +- core/executor/src/system_contract/mod.rs | 18 +- core/interoperation/Cargo.toml | 13 +- core/interoperation/src/lib.rs | 42 ++- core/mempool/Cargo.toml | 4 +- core/mempool/src/adapter/mod.rs | 2 +- core/rpc-client/Cargo.toml | 6 +- core/storage/src/lib.rs | 3 +- protocol/Cargo.toml | 18 +- protocol/src/traits/interoperation.rs | 11 +- protocol/src/traits/mod.rs | 4 +- tests/e2e/src/eth_getStorageAt.test.js | 2 +- 26 files changed, 543 insertions(+), 389 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 9c420246e..7a2a42583 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -90,15 +90,6 @@ dependencies = [ "version_check", ] -[[package]] -name = "aho-corasick" -version = "0.7.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc936419f96fa211c1b9166887b38e5e40b19958e5b895be7c1f93adec7071ac" -dependencies = [ - "memchr", -] - [[package]] name = "aho-corasick" version = "1.0.1" @@ -233,7 +224,7 @@ checksum = "bc00ceb34980c03614e35a3a4e218276a0a824e911d07651cd0d858a51e8c0f0" dependencies = [ "proc-macro2", "quote", - "syn 2.0.32", + "syn 2.0.37", ] [[package]] @@ -544,9 +535,9 @@ dependencies = [ [[package]] name = "blake2b-ref" -version = "0.2.1" +version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "95916998c798756098a4eb1b3f2cd510659705a9817bf203d61abd30fbec3e7b" +checksum = "294d17c72e0ba59fad763caa112368d0672083779cdebbb97164f4bb4c1e339a" [[package]] name = "blake2b-rs" @@ -607,16 +598,6 @@ dependencies = [ "sha2 0.9.9", ] -[[package]] -name = "bstr" -version = "1.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3d4260bcc2e8fc9df1eac4919a720effeb63a3f0952f5bf4944adfa18897f09" -dependencies = [ - "memchr", - "serde", -] - [[package]] name = "bumpalo" version = "3.12.2" @@ -885,9 +866,9 @@ dependencies = [ [[package]] name = "ckb-chain-spec" -version = "0.108.0" +version = "0.111.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e78df45446aaa86b06a77b8b145cffa79950e7ede293cebcd114a62e74c29dbf" +checksum = "dbd58081d4ac4f08d068b52c5a07f0b379d93aad0dfa8344c6890429a9b73c2b" dependencies = [ "ckb-constant", "ckb-crypto", @@ -907,24 +888,24 @@ dependencies = [ [[package]] name = "ckb-channel" -version = "0.108.0" +version = "0.111.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "920f26cc48cadcaf6f7bcc3960fde9f9f355633b6361da8ef31e1e1c00fc8858" +checksum = "701e6829c3dcbae46dd2442de63d080046480a6c2bb4951dbf419ad092459402" dependencies = [ "crossbeam-channel", ] [[package]] name = "ckb-constant" -version = "0.108.0" +version = "0.111.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "302566408e5b296663ac5e8245bf71824ca2c7c2ef19a57fcc15939dd66527e9" +checksum = "9d5c980d4724770f72a37bceffa26ea64dd914891e45e856e2a3792fdb4a5a18" [[package]] name = "ckb-crypto" -version = "0.108.0" +version = "0.111.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aac31177b0a8bf3acd563c042775e40494e437b2bbbae96ac2473eec3a4da95d" +checksum = "df80db694e42b64a5774ae551daff3c8310cd99bb528643dbe0dd409abb298e7" dependencies = [ "ckb-fixed-hash", "faster-hex 0.6.1", @@ -936,9 +917,9 @@ dependencies = [ [[package]] name = "ckb-dao-utils" -version = "0.108.0" +version = "0.111.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1929c9627923fe1d22151361d74f5a5aa0dda77016d020307a54486eae11cb3c" +checksum = "5e158ce5a4e9d1fcd08d9dee87332474572c629c6273cca0aea80ba24892a403" dependencies = [ "byteorder", "ckb-error", @@ -947,9 +928,9 @@ dependencies = [ [[package]] name = "ckb-error" -version = "0.108.0" +version = "0.111.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "446a519d8a847d97f1c8ece739dc1748751a9a2179249c96c45cced0825a7aa5" +checksum = "34cfd733cabcb4262ee679c02733864b13c8fa879e3aabc078fe0ec727cd95d6" dependencies = [ "anyhow", "ckb-occupied-capacity", @@ -959,9 +940,9 @@ dependencies = [ [[package]] name = "ckb-fixed-hash" -version = "0.108.0" +version = "0.111.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "00cbbc455b23748b32e06d16628a03e30d56ffa057f17093fdf5b42d4fb6c879" +checksum = "3b1dfab045fffa31cae9680d73e1f09833ca1abfb807dc4b9544739c94c23fd0" dependencies = [ "ckb-fixed-hash-core", "ckb-fixed-hash-macros", @@ -969,9 +950,9 @@ dependencies = [ [[package]] name = "ckb-fixed-hash-core" -version = "0.108.0" +version = "0.111.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf4e644a4e026625b4be5a04cdf6c02043080e79feaf77d9cdbb2f0e6553f751" +checksum = "bdd1727a6ecd4d0bcab604cb1ef707fe92e939fa6e9a438f9f25bf05208cb080" dependencies = [ "faster-hex 0.6.1", "serde", @@ -980,9 +961,9 @@ dependencies = [ [[package]] name = "ckb-fixed-hash-macros" -version = "0.108.0" +version = "0.111.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e1cfc980ef88c217825172eb46df269f47890f5e78a38214416f13b3bd17a4b4" +checksum = "7b5da34c32585c35715fcde4e3a1dd3b0346d7af43506c5e51c613f01483e4f9" dependencies = [ "ckb-fixed-hash-core", "proc-macro2", @@ -990,11 +971,26 @@ dependencies = [ "syn 1.0.109", ] +[[package]] +name = "ckb-gen-types" +version = "0.111.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a3bc54ca99b09e1eb5fc6c49bb1156644ce57fce9c6f52b5c13110b9a3143f7e" +dependencies = [ + "cfg-if 1.0.0", + "ckb-error", + "ckb-fixed-hash", + "ckb-hash", + "ckb-occupied-capacity", + "molecule", + "numext-fixed-uint", +] + [[package]] name = "ckb-hash" -version = "0.108.0" +version = "0.111.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "53d9b683e89ae4ffdd5aaf4172eab00b6bbe7ea24e2abf77d3eb850ba36e8983" +checksum = "8c88e5e2d6454be488fa5cf8b49175879353c6af969ff210dd6416f315b53120" dependencies = [ "blake2b-ref", "blake2b-rs", @@ -1002,9 +998,9 @@ dependencies = [ [[package]] name = "ckb-jsonrpc-types" -version = "0.108.0" +version = "0.111.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac087657eaf964e729f40b3c929d3dac74a2cd8bb38d5e588756e2495711f810" +checksum = "d789a71538da07871c11aecbd28d6c632bb426bdfeed5fc2fa1b455e31152468" dependencies = [ "ckb-types", "faster-hex 0.6.1", @@ -1028,9 +1024,9 @@ dependencies = [ [[package]] name = "ckb-logger" -version = "0.108.0" +version = "0.111.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "911c4695ddf82f78da8f514b359092bbe231f58c2669c93b1cfc9a2030b125bb" +checksum = "939fa09ca3534248d3d452552546f016fc7e11346644fbc5b55d2ad38d3e80e7" dependencies = [ "log", ] @@ -1044,11 +1040,23 @@ dependencies = [ "cfg-if 1.0.0", ] +[[package]] +name = "ckb-mock-tx-types" +version = "0.111.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dcd5b156c36f03ad6053e174e26a874088c8e9098c3a2e80ec93dc9831ecfac3" +dependencies = [ + "ckb-jsonrpc-types", + "ckb-traits", + "ckb-types", + "serde", +] + [[package]] name = "ckb-occupied-capacity" -version = "0.108.0" +version = "0.111.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2d2a1dd0d4ba5dafba1e30d437c1148b20f42edb76b6794323e05bda626754eb" +checksum = "358ad364465a5a359575642c12952ba8735a148382789d65ddd5231cd21899fc" dependencies = [ "ckb-occupied-capacity-core", "ckb-occupied-capacity-macros", @@ -1056,18 +1064,18 @@ dependencies = [ [[package]] name = "ckb-occupied-capacity-core" -version = "0.108.0" +version = "0.111.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ebba3d564098a84c83f4740e1dce48a5e2da759becdb47e3c7965f0808e6e92" +checksum = "de2dc06db98f8a995cb7145bc56dbd17bb0c8ab2e59a07aaa40f2c956c2451dd" dependencies = [ "serde", ] [[package]] name = "ckb-occupied-capacity-macros" -version = "0.108.0" +version = "0.111.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce6321bba85cdf9724029d8c906851dd4a90906869b42f9100b16645a1261d4c" +checksum = "b1709e0f101026c4ef29b1593692e480b03cdb4e0dace1e348494c6554d50d35" dependencies = [ "ckb-occupied-capacity-core", "quote", @@ -1076,9 +1084,9 @@ dependencies = [ [[package]] name = "ckb-pow" -version = "0.108.0" +version = "0.111.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a9167b427f42874e68e20e6946d5211709979ff1d86c0061a71c2f6a6aa17659" +checksum = "481e76388993d7e6e0dd797e8532c60398901787e28d0638ca114254257b8813" dependencies = [ "byteorder", "ckb-hash", @@ -1090,9 +1098,9 @@ dependencies = [ [[package]] name = "ckb-rational" -version = "0.108.0" +version = "0.111.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a2519249f8d47fa758d3fb3cf3049327c69ce0f2acd79d61427482c8661d3dbd" +checksum = "bd3959391a4fb05d6a2578aa8db75732ada1ce381fb34d6eeaf09d395702e63c" dependencies = [ "numext-fixed-uint", "serde", @@ -1100,9 +1108,9 @@ dependencies = [ [[package]] name = "ckb-resource" -version = "0.108.0" +version = "0.111.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a3abddc968d7f1e70584ab04180c347380a44acbe0b60e26cc96208ec8885279" +checksum = "03222b0613cf3f55cb181471d7a84879b6fba5e920e2e1c7ba2c2315614bd387" dependencies = [ "ckb-system-scripts", "ckb-types", @@ -1126,9 +1134,9 @@ dependencies = [ [[package]] name = "ckb-script" -version = "0.108.0" +version = "0.111.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "12b4754a2f0ccea5ea1934822bd18a3a66c46344d8c3872cb20ffdcf0851fab9" +checksum = "8c9075ad901eae97925f491b6be675d7b19bf7b10eaa94a88f6e8070c0cd00ba" dependencies = [ "byteorder", "ckb-chain-spec", @@ -1144,23 +1152,27 @@ dependencies = [ [[package]] name = "ckb-sdk" -version = "2.5.0" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b201220ac5762353f9313fbbc3c4cee2a6a924c16c17df51517644991575cc1" +checksum = "9ded3042867b04f20456f17a1f752f2604a24659f3aeec1928917d9ee6b659d4" dependencies = [ "anyhow", "bech32 0.8.1", "bitflags", "bytes", + "ckb-chain-spec", "ckb-crypto", "ckb-dao-utils", "ckb-hash", "ckb-jsonrpc-types", + "ckb-mock-tx-types", "ckb-resource", "ckb-script", "ckb-traits", "ckb-types", "dashmap", + "derive-getters", + "dyn-clone", "enum-repr-derive", "futures", "jsonrpc-core", @@ -1195,40 +1207,44 @@ dependencies = [ [[package]] name = "ckb-traits" -version = "0.108.0" +version = "0.111.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e9d5827f20a396dfb785398db484fe50de93d76c02e1e32287832604a9dda91" +checksum = "ca049aba2cb2d1208c6044accb497b17290ad56de629f6a4b95eded67a43fd40" dependencies = [ "ckb-types", ] [[package]] name = "ckb-types" -version = "0.108.0" +version = "0.111.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c22b3b1ca8f88a8f48e2f73321c0605281c9c6f1e1c4d651c6138265c22291e" +checksum = "b6ec737e4957418bbd0f4091e8565a89bbd8f6fc37a20360820e44d1f1e44e58" dependencies = [ "bit-vec", "bytes", "ckb-channel", + "ckb-constant", "ckb-error", "ckb-fixed-hash", + "ckb-gen-types", "ckb-hash", "ckb-merkle-mountain-range", "ckb-occupied-capacity", "ckb-rational", "derive_more", + "golomb-coded-set", "merkle-cbt", "molecule", "numext-fixed-uint", "once_cell", + "paste", ] [[package]] name = "ckb-util" -version = "0.108.0" +version = "0.111.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "03d165c6958601dfbfa4cd00c9263ecfb013b4ccb6d9e1d3187bfa62801abc7d" +checksum = "011b907b18aa706fc224a1309f14eadd9cc14c42cf2258ca3010d1324bc20f10" dependencies = [ "linked-hash-map", "once_cell", @@ -1238,9 +1254,9 @@ dependencies = [ [[package]] name = "ckb-vm" -version = "0.22.2" +version = "0.24.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1223acc8054ce96f91c5d99d4942898d0bdadd618c3b14f1acd3e67212991d8e" +checksum = "0cc004a826b9bc9319ffae0b8415690e1b5f1482266d55fbd43843aa40ddcd63" dependencies = [ "byteorder", "bytes", @@ -1256,9 +1272,12 @@ dependencies = [ [[package]] name = "ckb-vm-definitions" -version = "0.22.2" +version = "0.24.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4af800ae2b6c54b70efa398dab015a09a52eeac2dd1ac3ad32c9bbe224974225" +checksum = "c4ced3ff9d79b53d93c106720f6c1f855694290e33581850e05c859500eee83f" +dependencies = [ + "paste", +] [[package]] name = "clang-sys" @@ -1348,7 +1367,7 @@ dependencies = [ "heck", "proc-macro2", "quote", - "syn 2.0.32", + "syn 2.0.37", ] [[package]] @@ -1776,6 +1795,7 @@ dependencies = [ "axon-protocol", "cardano-message-signing", "cardano-serialization-lib", + "ckb-chain-spec", "ckb-error", "ckb-jsonrpc-types", "ckb-script", @@ -2155,6 +2175,17 @@ dependencies = [ "syn 1.0.109", ] +[[package]] +name = "derive-getters" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0122f262bf9c9a367829da84f808d9fb128c10ef283bbe7b0922a77cf07b2747" +dependencies = [ + "proc-macro2", + "quote", + "syn 1.0.109", +] + [[package]] name = "derive_more" version = "0.99.17" @@ -2650,7 +2681,7 @@ dependencies = [ "reqwest", "serde", "serde_json", - "syn 2.0.32", + "syn 2.0.37", "tokio", "toml 0.7.3", "url", @@ -2670,7 +2701,7 @@ dependencies = [ "proc-macro2", "quote", "serde_json", - "syn 2.0.32", + "syn 2.0.37", ] [[package]] @@ -2697,7 +2728,7 @@ dependencies = [ "serde", "serde_json", "strum 0.24.1", - "syn 2.0.32", + "syn 2.0.37", "tempfile", "thiserror", "tiny-keccak", @@ -3130,7 +3161,7 @@ checksum = "89ca545a94061b6365f2c7355b4b32bd20df3ff95f02da9329b34ccc3bd6ee72" dependencies = [ "proc-macro2", "quote", - "syn 2.0.32", + "syn 2.0.37", ] [[package]] @@ -3241,19 +3272,6 @@ version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d2fabcfbdc87f4758337ca535fb41a6d701b65693ce38287d856d1674551ec9b" -[[package]] -name = "globset" -version = "0.4.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "029d74589adefde59de1a0c4f4732695c32805624aec7b68d91503d4dba79afc" -dependencies = [ - "aho-corasick 0.7.20", - "bstr", - "fnv", - "log", - "regex", -] - [[package]] name = "gloo-timers" version = "0.2.6" @@ -3298,6 +3316,15 @@ dependencies = [ "scroll", ] +[[package]] +name = "golomb-coded-set" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c7076c0cd6257d84b785b0f22c36443dd47a5e86a1256d7ef82c8cb88ea9a7e" +dependencies = [ + "siphasher", +] + [[package]] name = "group" version = "0.13.0" @@ -3809,30 +3836,28 @@ dependencies = [ [[package]] name = "jsonrpsee" -version = "0.16.2" +version = "0.20.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7d291e3a5818a2384645fd9756362e6d89cf0541b0b916fa7702ea4a9833608e" +checksum = "9ad9b31183a8bcbe843e32ca8554ad2936633548d95a7bb6a8e14c767dea6b05" dependencies = [ "jsonrpsee-core", "jsonrpsee-proc-macros", "jsonrpsee-server", "jsonrpsee-types", + "tokio", "tracing", ] [[package]] name = "jsonrpsee-core" -version = "0.16.2" +version = "0.20.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a4e70b4439a751a5de7dd5ed55eacff78ebf4ffe0fc009cb1ebb11417f5b536b" +checksum = "35dc957af59ce98373bcdde0c1698060ca6c2d2e9ae357b459c7158b6df33330" dependencies = [ "anyhow", - "arrayvec", "async-trait", "beef", - "futures-channel", "futures-util", - "globset", "hyper", "jsonrpsee-types", "parking_lot 0.12.1", @@ -3848,9 +3873,9 @@ dependencies = [ [[package]] name = "jsonrpsee-proc-macros" -version = "0.16.2" +version = "0.20.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "baa6da1e4199c10d7b1d0a6e5e8bd8e55f351163b6f4b3cbb044672a69bd4c1c" +checksum = "cef91b1017a4edb63f65239381c18de39f88d0e0760ab626d806e196f7f51477" dependencies = [ "heck", "proc-macro-crate", @@ -3861,19 +3886,20 @@ dependencies = [ [[package]] name = "jsonrpsee-server" -version = "0.16.2" +version = "0.20.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fb69dad85df79527c019659a992498d03f8495390496da2f07e6c24c2b356fc" +checksum = "24f4e2f3d223d810e363fb8b5616ec4c6254243ee7f452d05ac281cdc9cf76b2" dependencies = [ - "futures-channel", "futures-util", "http", "hyper", "jsonrpsee-core", "jsonrpsee-types", + "route-recognizer", "serde", "serde_json", "soketto", + "thiserror", "tokio", "tokio-stream", "tokio-util", @@ -3883,9 +3909,9 @@ dependencies = [ [[package]] name = "jsonrpsee-types" -version = "0.16.2" +version = "0.20.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5bd522fe1ce3702fd94812965d7bb7a3364b1c9aba743944c5a00529aae80f8c" +checksum = "fa9e25aec855b2a7d3ed90fded6c41e8c3fb72b63f071e1be3f0004eba19b625" dependencies = [ "anyhow", "beef", @@ -4192,9 +4218,9 @@ dependencies = [ [[package]] name = "molecule" -version = "0.7.3" +version = "0.7.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "edc8276c02a006bddad7d1c28c1a88f30421e1b5f0ba0ca96ceb8077c7d20c01" +checksum = "d4fd9767ab5e5f2ea40f71ff4c8bdb633c50509052e093c2fdd0e390a749dfa3" dependencies = [ "bytes", "cfg-if 1.0.0", @@ -4424,7 +4450,7 @@ dependencies = [ "proc-macro-crate", "proc-macro2", "quote", - "syn 2.0.32", + "syn 2.0.37", ] [[package]] @@ -4554,7 +4580,7 @@ checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.32", + "syn 2.0.37", ] [[package]] @@ -4936,7 +4962,7 @@ checksum = "39407670928234ebc5e6e580247dd567ad73a3578460c5990f9503df207e8f07" dependencies = [ "proc-macro2", "quote", - "syn 2.0.32", + "syn 2.0.37", ] [[package]] @@ -5065,7 +5091,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "617feabb81566b593beb4886fb8c1f38064169dae4dccad0e3220160c3b37203" dependencies = [ "proc-macro2", - "syn 2.0.32", + "syn 2.0.37", ] [[package]] @@ -5475,7 +5501,7 @@ version = "1.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "af83e617f331cc6ae2da5443c602dfa5af81e517212d9d611a5b3ba1777b5370" dependencies = [ - "aho-corasick 1.0.1", + "aho-corasick", "memchr", "regex-syntax 0.7.1", ] @@ -5625,6 +5651,12 @@ dependencies = [ "syn 1.0.109", ] +[[package]] +name = "route-recognizer" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "afab94fb28594581f62d981211a9a4d53cc8130bbcbbb89a0440d9b8e81a7746" + [[package]] name = "rug" version = "1.19.2" @@ -5999,7 +6031,7 @@ checksum = "4eca7ac642d82aa35b60049a6eccb4be6be75e599bd2e9adb5f875a737654af2" dependencies = [ "proc-macro2", "quote", - "syn 2.0.32", + "syn 2.0.37", ] [[package]] @@ -6335,7 +6367,7 @@ dependencies = [ "proc-macro2", "quote", "rustversion", - "syn 2.0.32", + "syn 2.0.37", ] [[package]] @@ -6424,9 +6456,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.32" +version = "2.0.37" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "239814284fd6f1a4ffe4ca893952cdd93c224b6a1571c9a9eadd670295c0c9e2" +checksum = "7303ef2c05cd654186cb250d29049a24840ca25d2747c25c0381c8d9e2f582e8" dependencies = [ "proc-macro2", "quote", @@ -6591,7 +6623,7 @@ checksum = "49922ecae66cc8a249b77e68d1d0623c1b2c514f0060c27cdc68bd62a1219d35" dependencies = [ "proc-macro2", "quote", - "syn 2.0.32", + "syn 2.0.37", ] [[package]] @@ -6743,7 +6775,7 @@ checksum = "630bdcf245f78637c13ec01ffae6187cca34625e8c63150d424b59e55af2675e" dependencies = [ "proc-macro2", "quote", - "syn 2.0.32", + "syn 2.0.37", ] [[package]] @@ -6915,7 +6947,7 @@ checksum = "0f57e3ca2a01450b1a921183a9c9cbfda207fd822cef4ccb00a65402cbba7a74" dependencies = [ "proc-macro2", "quote", - "syn 2.0.32", + "syn 2.0.37", ] [[package]] @@ -7586,7 +7618,7 @@ checksum = "ce36e65b0d2999d2aafac989fb249189a141aee1f53c612c1f37d72631959f69" dependencies = [ "proc-macro2", "quote", - "syn 2.0.32", + "syn 2.0.37", ] [[package]] diff --git a/common/apm-derive/Cargo.toml b/common/apm-derive/Cargo.toml index 49943b37f..712f31c70 100644 --- a/common/apm-derive/Cargo.toml +++ b/common/apm-derive/Cargo.toml @@ -17,7 +17,7 @@ syn = { version = "1.0", features = ["full"] } [dev-dependencies] async-trait = "0.1" common-apm = { path = "../apm" } -jsonrpsee = { version = "0.16", features = ["macros"] } +jsonrpsee = { version = "0.20", features = ["macros"] } log = "0.4" protocol = { path = "../../protocol", package = "axon-protocol" } diff --git a/common/config-parser/src/lib.rs b/common/config-parser/src/lib.rs index b1c593b89..1bfd8bca5 100644 --- a/common/config-parser/src/lib.rs +++ b/common/config-parser/src/lib.rs @@ -1,11 +1,7 @@ pub mod types; use serde::de; -use std::error; -use std::fmt; -use std::fs; -use std::io; -use std::path::Path; +use std::{error, fmt, fs, io, path::Path}; /// Parse a config from reader. pub fn parse_reader(r: &mut R) -> Result { diff --git a/common/config-parser/src/types/spec.rs b/common/config-parser/src/types/spec.rs index 58212728f..f8330909e 100644 --- a/common/config-parser/src/types/spec.rs +++ b/common/config-parser/src/types/spec.rs @@ -8,9 +8,10 @@ use std::{ use clap::{ builder::{StringValueParser, TypedValueParser, ValueParserFactory}, - Args, + Args, ValueEnum, }; use serde::{Deserialize, Serialize}; +use strum_macros::EnumIter; use common_crypto::Secp256k1RecoverablePrivateKey; use protocol::{ @@ -275,9 +276,6 @@ impl Genesis { } } -use clap::ValueEnum; -use strum_macros::EnumIter; - #[derive(Clone, Debug, Deserialize, Args)] pub struct HardforkInput { #[arg( diff --git a/core/api/Cargo.toml b/core/api/Cargo.toml index d1022b22c..8dd5f832b 100644 --- a/core/api/Cargo.toml +++ b/core/api/Cargo.toml @@ -7,10 +7,10 @@ edition = "2021" [dependencies] # async-graphql = { version = "3.0", features = ["tracing"] } beef = "0.5" -ckb-jsonrpc-types = "0.108" -ckb-traits = "0.108" -ckb-types = "0.108" -jsonrpsee = { version = "0.16", features = ["macros", "server"] } +ckb-jsonrpc-types = "0.111" +ckb-traits = "0.111" +ckb-types = "0.111" +jsonrpsee = { version = "0.20", features = ["macros", "server"] } log = "0.4" parking_lot = "0.12" pprof = { version = "0.11", features = ["prost-codec"], optional = true } diff --git a/core/api/src/jsonrpc/error.rs b/core/api/src/jsonrpc/error.rs index 0820e0268..3ac820882 100644 --- a/core/api/src/jsonrpc/error.rs +++ b/core/api/src/jsonrpc/error.rs @@ -1,41 +1,152 @@ -use jsonrpsee::core::Error; -use jsonrpsee::types::error::{CallError, ErrorObject}; +use jsonrpsee::types::{error::ErrorObject, ErrorObjectOwned}; -use protocol::codec::hex_encode; use protocol::types::{ExitReason, TxResp}; +use protocol::{codec::hex_encode, Display}; use core_executor::decode_revert_msg; -const EXEC_ERROR: i32 = -32015; +use crate::jsonrpc::web3_types::BlockId; -#[derive(Clone, Debug)] +#[derive(Clone, Display, Debug)] pub enum RpcError { + #[display(fmt = "Decode interoperation signature r error")] + DecodeInteroperationSigR(String), + #[display(fmt = "Decode interoperation signature s error")] + DecodeInteroperationSigS(String), + #[display(fmt = "Invalid address source")] + InvalidAddressSource, + #[display(fmt = "Missing dummy input cell")] + MissingDummyInputCell, + #[display(fmt = "Cannot find image cell")] + CannotFindImageCell, + #[display(fmt = "Gas price is zero")] + GasPriceIsZero, + #[display(fmt = "Gas price is too large")] + GasPriceIsTooLarge, + #[display(fmt = "Gas limit is less than 21000")] + 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 receipt by hash")] + CannotGetReceiptByHash, + #[display(fmt = "Cannot get latest block")] + CannotGetLatestBlock, + #[display(fmt = "Invalid block hash")] + InvalidBlockHash, + #[display(fmt = "Invalid from block number {}", _0)] + InvalidFromBlockNumber(u64), + #[display(fmt = "Invalid block range from {} to {} limit to {}", _0, _1, _2)] + InvalidBlockRange(u64, u64, u64), + #[display(fmt = "Invalid newest block {:?}", _0)] + InvalidNewestBlock(BlockId), + #[display(fmt = "Invalid position {}", _0)] + InvalidPosition(u64), + #[display(fmt = "Cannot find the block")] + CannotFindBlock, + #[display(fmt = "Invalid reward percentiles {} {}", _0, _1)] + InvalidRewardPercentiles(f64, f64), + #[display(fmt = "Invalid from block number and to block number union")] + InvalidFromBlockAndToBlockUnion, + #[display(fmt = "Invalid filter id {}", _0)] + CannotFindFilterId(u64), + + #[display(fmt = "CKB-VM error {}", "decode_revert_msg(&_0.ret)")] VM(TxResp), + #[display(fmt = "Internal error")] + Internal(String), } -impl From for Error { +impl From for String { fn from(err: RpcError) -> Self { - match err { - RpcError::VM(resp) => vm_err(resp), + err.to_string() + } +} + +impl RpcError { + fn code(&self) -> i32 { + match self { + RpcError::DecodeInteroperationSigR(_) => -40001, + RpcError::DecodeInteroperationSigS(_) => -40002, + RpcError::InvalidAddressSource => -40003, + RpcError::MissingDummyInputCell => -40004, + RpcError::CannotFindImageCell => -40005, + RpcError::GasPriceIsZero => -40006, + RpcError::GasPriceIsTooLarge => -40007, + RpcError::GasLimitIsTooLow => -40008, + RpcError::GasLimitIsTooLarge => -40009, + RpcError::GasLimitIsZero => -40010, + RpcError::TransactionIsNotSigned => -40011, + RpcError::CannotGetReceiptByHash => -40012, + RpcError::CannotGetLatestBlock => -40013, + RpcError::InvalidBlockHash => -40014, + RpcError::InvalidFromBlockNumber(_) => -40015, + RpcError::InvalidBlockRange(_, _, _) => -40016, + RpcError::InvalidNewestBlock(_) => -40017, + RpcError::InvalidPosition(_) => -40018, + RpcError::CannotFindBlock => -40019, + RpcError::InvalidRewardPercentiles(_, _) => -40020, + RpcError::InvalidFromBlockAndToBlockUnion => -40021, + RpcError::CannotFindFilterId(_) => -40022, + + RpcError::VM(_) => -49998, + RpcError::Internal(_) => -49999, } } } -pub fn vm_err(resp: TxResp) -> Error { - let data = match resp.exit_reason { +impl From for ErrorObjectOwned { + fn from(err: RpcError) -> Self { + let none_data: Option = None; + let err_code = err.code(); + match &err { + RpcError::DecodeInteroperationSigR(msg) => { + ErrorObject::owned(err_code, err.clone(), Some(msg)) + } + RpcError::DecodeInteroperationSigS(msg) => { + ErrorObject::owned(err_code, err.clone(), Some(msg)) + } + RpcError::InvalidAddressSource => ErrorObject::owned(err_code, err, none_data), + RpcError::MissingDummyInputCell => ErrorObject::owned(err_code, err, none_data), + RpcError::CannotFindImageCell => ErrorObject::owned(err_code, err, none_data), + RpcError::GasPriceIsZero => ErrorObject::owned(err_code, err, none_data), + 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::CannotGetReceiptByHash => 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), + RpcError::InvalidFromBlockNumber(_) => ErrorObject::owned(err_code, err, none_data), + RpcError::InvalidBlockRange(_, _, _) => ErrorObject::owned(err_code, err, none_data), + RpcError::InvalidNewestBlock(_) => ErrorObject::owned(err_code, err, none_data), + RpcError::InvalidPosition(_) => ErrorObject::owned(err_code, err, none_data), + RpcError::CannotFindBlock => ErrorObject::owned(err_code, err, none_data), + RpcError::InvalidRewardPercentiles(_, _) => { + ErrorObject::owned(err_code, err, none_data) + } + RpcError::InvalidFromBlockAndToBlockUnion => { + ErrorObject::owned(err_code, err, none_data) + } + RpcError::CannotFindFilterId(_) => ErrorObject::owned(err_code, err, none_data), + + RpcError::VM(resp) => { + ErrorObject::owned(err_code, err.clone(), Some(vm_err(resp.clone()))) + } + RpcError::Internal(msg) => ErrorObject::owned(err_code, err.clone(), Some(msg)), + } + } +} + +pub fn vm_err(resp: TxResp) -> String { + match resp.exit_reason { ExitReason::Revert(_) => format!("0x{}", hex_encode(&resp.ret),), ExitReason::Error(err) => format!("{:?}", err), ExitReason::Fatal(fatal) => format!("{:?}", fatal), _ => unreachable!(), - }; - - into_rpc_err(ErrorObject::owned( - EXEC_ERROR, - decode_revert_msg(&resp.ret), - Some(data), - )) -} - -fn into_rpc_err(obj: ErrorObject<'static>) -> Error { - CallError::Custom(obj).into() + } } diff --git a/core/api/src/jsonrpc/impl/axon.rs b/core/api/src/jsonrpc/impl/axon.rs index e8815eb19..f3be59282 100644 --- a/core/api/src/jsonrpc/impl/axon.rs +++ b/core/api/src/jsonrpc/impl/axon.rs @@ -1,6 +1,6 @@ use std::{collections::HashMap, sync::Arc}; -use jsonrpsee::core::Error; +use jsonrpsee::{core::RpcResult, types::error::ErrorCode}; use strum::IntoEnumIterator; use common_config_parser::types::spec::HardforkName; @@ -11,7 +11,7 @@ use protocol::types::{ }; use crate::jsonrpc::web3_types::{BlockId, HardforkStatus}; -use crate::jsonrpc::{AxonRpcServer, RpcResult}; +use crate::jsonrpc::{error::RpcError, AxonRpcServer}; pub struct AxonRpcImpl { adapter: Arc, @@ -34,9 +34,9 @@ impl AxonRpcServer for AxonRpcImpl { .await } BlockId::Latest => self.adapter.get_block_by_number(Context::new(), None).await, - _ => return Err(Error::InvalidRequestId), + _ => return Err(ErrorCode::InvalidRequest.into()), } - .map_err(|e| Error::Custom(e.to_string()))?; + .map_err(|e| RpcError::Internal(e.to_string()))?; Ok(ret) } @@ -54,7 +54,7 @@ impl AxonRpcServer for AxonRpcImpl { .adapter .get_metadata_by_number(Context::new(), Some(block_number.as_u64())) .await - .map_err(|e| Error::Custom(e.to_string()))?; + .map_err(|e| RpcError::Internal(e.to_string()))?; Ok(ret) } @@ -65,14 +65,14 @@ impl AxonRpcServer for AxonRpcImpl { .adapter .get_block_by_number(Context::new(), Some(block_number - 1)) .await - .map_err(|e| Error::Custom(e.to_string()))? - .ok_or_else(|| Error::Custom("prev block not found".to_string()))?; + .map_err(|e| RpcError::Internal(e.to_string()))? + .ok_or_else(|| RpcError::Internal("prev block not found".to_string()))?; let block = self .adapter .get_block_by_number(Context::new(), Some(block_number)) .await - .map_err(|e| Error::Custom(e.to_string()))? - .ok_or_else(|| Error::Custom("block not found".to_string()))?; + .map_err(|e| RpcError::Internal(e.to_string()))? + .ok_or_else(|| RpcError::Internal("block not found".to_string()))?; Ok(Proposal::new_with_state_root( &block.header, @@ -86,7 +86,7 @@ impl AxonRpcServer for AxonRpcImpl { .adapter .get_metadata_by_number(Context::new(), None) .await - .map_err(|e| Error::Custom(e.to_string()))?; + .map_err(|e| RpcError::Internal(e.to_string()))?; Ok(ret) } @@ -96,7 +96,7 @@ impl AxonRpcServer for AxonRpcImpl { .adapter .get_ckb_related_info(Context::new()) .await - .map_err(|e| Error::Custom(e.to_string()))?; + .map_err(|e| RpcError::Internal(e.to_string()))?; Ok(ret) } @@ -106,19 +106,19 @@ impl AxonRpcServer for AxonRpcImpl { .adapter .hardfork_info(Context::new()) .await - .map_err(|e| Error::Custom(e.to_string()))?; + .map_err(|e| RpcError::Internal(e.to_string()))?; let proposal = self .adapter .hardfork_proposal(Context::new()) .await - .map_err(|e| Error::Custom(e.to_string()))?; + .map_err(|e| RpcError::Internal(e.to_string()))?; let current_number = self .adapter .get_block_header_by_number(Default::default(), None) .await - .map_err(|e| Error::Custom(e.to_string()))? + .map_err(|e| RpcError::Internal(e.to_string()))? .unwrap() .number; diff --git a/core/api/src/jsonrpc/impl/ckb_light_client.rs b/core/api/src/jsonrpc/impl/ckb_light_client.rs index 8236dea32..8f7807f4a 100644 --- a/core/api/src/jsonrpc/impl/ckb_light_client.rs +++ b/core/api/src/jsonrpc/impl/ckb_light_client.rs @@ -4,13 +4,13 @@ use ckb_jsonrpc_types::{CellData, CellInfo, HeaderView as CkbHeaderView, JsonByt use ckb_traits::HeaderProvider; use ckb_types::core::cell::{CellProvider, CellStatus}; use ckb_types::{packed, prelude::Pack}; +use jsonrpsee::core::RpcResult; use core_executor::DataProvider; -use jsonrpsee::core::Error; use protocol::traits::{APIAdapter, Context}; use protocol::{async_trait, ckb_blake2b_256, types::H256}; -use crate::jsonrpc::{CkbLightClientRpcServer, RpcResult}; +use crate::jsonrpc::{error::RpcError, CkbLightClientRpcServer}; #[derive(Clone, Debug)] pub struct CkbLightClientRpcImpl { @@ -24,7 +24,7 @@ impl CkbLightClientRpcServer for CkbLightClientRp .adapter .get_image_cell_root(Context::new()) .await - .map_err(|e| Error::Custom(e.to_string()))?; + .map_err(|e| RpcError::Internal(e.to_string()))?; Ok(DataProvider::new(root) .get_header(&(hash.0.pack())) .map(Into::into)) @@ -40,7 +40,7 @@ impl CkbLightClientRpcServer for CkbLightClientRp .adapter .get_image_cell_root(Context::new()) .await - .map_err(|e| Error::Custom(e.to_string()))?; + .map_err(|e| RpcError::Internal(e.to_string()))?; match DataProvider::new(root).cell(&out_point, false) { CellStatus::Live(c) => { diff --git a/core/api/src/jsonrpc/impl/filter.rs b/core/api/src/jsonrpc/impl/filter.rs index 2eef99155..67f0849b7 100644 --- a/core/api/src/jsonrpc/impl/filter.rs +++ b/core/api/src/jsonrpc/impl/filter.rs @@ -2,18 +2,17 @@ use std::collections::HashMap; use std::sync::Arc; use std::time::{Duration, Instant}; -use jsonrpsee::core::Error; +use jsonrpsee::core::RpcResult; use serde::{Deserialize, Serialize}; -use protocol::async_trait; -use protocol::rand::prelude::*; use protocol::tokio::sync::mpsc::{channel, Receiver, Sender}; use protocol::tokio::{self, select, sync::oneshot, time::interval}; use protocol::traits::{APIAdapter, Context}; use protocol::types::{BlockNumber, Hash, Receipt, H160, H256, U256, U64}; +use protocol::{async_trait, rand::prelude::*}; use crate::jsonrpc::web3_types::{BlockId, FilterChanges, RawLoggerFilter, Web3Log}; -use crate::jsonrpc::{r#impl::from_receipt_to_web3_log, RpcResult, Web3FilterServer}; +use crate::jsonrpc::{error::RpcError, r#impl::from_receipt_to_web3_log, Web3FilterServer}; pub fn filter_module( adapter: Arc, @@ -62,13 +61,11 @@ pub struct AxonWeb3RpcFilter { impl Web3FilterServer for AxonWeb3RpcFilter { async fn new_filter(&self, filter: RawLoggerFilter) -> RpcResult { if let Some(BlockId::Pending) = filter.from_block { - return Err(Error::Custom( - "Invalid from_block and to_block union".to_string(), - )); + return Err(RpcError::InvalidFromBlockAndToBlockUnion.into()); } match filter.to_block { Some(BlockId::Earliest) | Some(BlockId::Num(U64([0]))) => { - return Err(Error::Custom("Invalid to_block".to_string())) + return Err(RpcError::Internal("Invalid to_block".to_string()).into()) } _ => (), } @@ -77,7 +74,7 @@ impl Web3FilterServer for AxonWeb3RpcFilter { self.sender .send(Command::NewLogs((filter.into(), tx))) .await - .map_err(|e| Error::Custom(e.to_string()))?; + .map_err(|e| RpcError::Internal(e.to_string()))?; Ok(rx.await.unwrap()) } @@ -88,7 +85,7 @@ impl Web3FilterServer for AxonWeb3RpcFilter { self.sender .send(Command::NewBlocks(tx)) .await - .map_err(|e| Error::Custom(e.to_string()))?; + .map_err(|e| RpcError::Internal(e.to_string()))?; Ok(rx.await.unwrap()) } @@ -99,7 +96,7 @@ impl Web3FilterServer for AxonWeb3RpcFilter { self.sender .send(Command::FilterRequest((id, tx))) .await - .map_err(|e| Error::Custom(e.to_string()))?; + .map_err(|e| RpcError::Internal(e.to_string()))?; rx.await.unwrap() } @@ -110,7 +107,7 @@ impl Web3FilterServer for AxonWeb3RpcFilter { self.sender .send(Command::FilterRequest((id, tx))) .await - .map_err(|e| Error::Custom(e.to_string()))?; + .map_err(|e| RpcError::Internal(e.to_string()))?; rx.await.unwrap() } @@ -121,7 +118,7 @@ impl Web3FilterServer for AxonWeb3RpcFilter { self.sender .send(Command::Uninstall((id, tx))) .await - .map_err(|e| Error::Custom(e.to_string()))?; + .map_err(|e| RpcError::Internal(e.to_string()))?; Ok(rx.await.unwrap()) } @@ -249,10 +246,7 @@ where sender.send(res).unwrap() } else { sender - .send(Err(Error::Custom(format!( - "Can't find this filter id: {}", - id - )))) + .send(Err(RpcError::CannotFindFilterId(id.as_u64()).into())) .unwrap() } } @@ -301,7 +295,7 @@ where .adapter .get_block_by_number(Context::new(), None) .await - .map_err(|e| Error::Custom(e.to_string()))? + .map_err(|e| RpcError::Internal(e.to_string()))? .unwrap(); let latest_number = latest_block.header.number; @@ -335,10 +329,9 @@ where return Ok(Vec::new()); } if end.saturating_sub(start) > self.log_filter_max_block_range { - return Err(Error::Custom(format!( - "Invalid block range {:?} to {:?}, limit to {:?}", - start, end, self.log_filter_max_block_range - ))); + return Err( + RpcError::InvalidBlockRange(start, end, self.log_filter_max_block_range).into(), + ); } let extend_logs = |logs: &mut Vec, receipts: Vec>| { for (index, receipt) in receipts.into_iter().flatten().enumerate() { @@ -361,13 +354,13 @@ where .adapter .get_block_by_number(Context::new(), Some(n)) .await - .map_err(|e| Error::Custom(e.to_string()))? + .map_err(|e| RpcError::Internal(e.to_string()))? .unwrap(); let receipts = self .adapter .get_receipts_by_hashes(Context::new(), block.header.number, &block.tx_hashes) .await - .map_err(|e| Error::Custom(e.to_string()))?; + .map_err(|e| RpcError::Internal(e.to_string()))?; extend_logs(&mut all_logs, receipts); } @@ -382,7 +375,7 @@ where &latest_block.tx_hashes, ) .await - .map_err(|e| Error::Custom(e.to_string()))?; + .map_err(|e| RpcError::Internal(e.to_string()))?; extend_logs(&mut all_logs, receipts); } diff --git a/core/api/src/jsonrpc/impl/web3.rs b/core/api/src/jsonrpc/impl/web3.rs index f43c27bbc..bbe325ea4 100644 --- a/core/api/src/jsonrpc/impl/web3.rs +++ b/core/api/src/jsonrpc/impl/web3.rs @@ -2,7 +2,7 @@ use std::sync::Arc; use ckb_types::core::cell::{CellProvider, CellStatus}; use ckb_types::prelude::Entity; -use jsonrpsee::core::Error; +use jsonrpsee::core::RpcResult; use common_apm::metrics_rpc; use protocol::traits::{APIAdapter, Context, Interoperation}; @@ -25,7 +25,7 @@ use crate::jsonrpc::web3_types::{ RichTransactionOrHash, Web3Block, Web3CallRequest, Web3FeeHistory, Web3Filter, Web3Log, Web3Receipt, Web3Transaction, }; -use crate::jsonrpc::{error::RpcError, RpcResult, Web3RpcServer}; +use crate::jsonrpc::{error::RpcError, Web3RpcServer}; use crate::APIError; pub(crate) const MAX_LOG_NUM: usize = 10000; @@ -48,13 +48,13 @@ impl Web3RpcImpl { async fn get_block_number_by_id( &self, block_id: Option, - ) -> Result, Error> { + ) -> Result, RpcError> { match block_id { Some(BlockId::Hash(ref hash)) => Ok(self .adapter .get_block_number_by_hash(Context::new(), *hash) .await - .map_err(|e| Error::Custom(e.to_string()))?), + .map_err(|e| RpcError::Internal(e.to_string()))?), _ => Ok(block_id.unwrap_or_default().into()), } } @@ -99,12 +99,12 @@ impl Web3RpcImpl { txs: Vec, reward_percentiles: Vec, reward: &mut Vec>, - ) -> Result<(), Error> { + ) -> Result<(), RpcError> { let receipts = self .adapter .get_receipts_by_hashes(Context::new(), block_number, &txs) .await - .map_err(|e| Error::Custom(e.to_string()))?; + .map_err(|e| RpcError::Internal(e.to_string()))?; let effective_priority_fees: Vec = receipts .iter() @@ -138,13 +138,13 @@ impl Web3RpcImpl { height: Option, block_count: U256, reward_percentiles: &Option>, - ) -> Result<(u64, Vec, Vec, Vec>), Error> { + ) -> Result<(u64, Vec, Vec, Vec>), RpcError> { let latest_block = self .adapter .get_block_by_number(Context::new(), height) .await - .map_err(|e| Error::Custom(e.to_string()))? - .ok_or_else(|| Error::Custom("Latest block not found".to_string()))?; + .map_err(|e| RpcError::Internal(e.to_string()))? + .ok_or(RpcError::CannotGetLatestBlock)?; let latest_block_number = latest_block.header.number; let oldest_block_number = latest_block_number @@ -199,14 +199,16 @@ impl Web3RpcImpl { // Call CKB-VM mode if signature.r[0] == 0 { let r = rlp::decode::(&signature.r[1..]) - .map_err(|e| Error::Custom(e.to_string()))?; + .map_err(|e| RpcError::DecodeInteroperationSigR(e.to_string()))?; return Ok(Hasher::digest(&r.pub_key).into()); } // Verify by CKB-VM mode - let r = SignatureR::decode(&signature.r).map_err(|e| Error::Custom(e.to_string()))?; - let s = SignatureS::decode(&signature.s).map_err(|e| Error::Custom(e.to_string()))?; + let r = SignatureR::decode(&signature.r) + .map_err(|e| RpcError::DecodeInteroperationSigR(e.to_string()))?; + let s = SignatureS::decode(&signature.s) + .map_err(|e| RpcError::DecodeInteroperationSigS(e.to_string()))?; let address_source = r.address_source(); let ckb_tx_view = @@ -216,7 +218,7 @@ impl Web3RpcImpl { let input = ckb_tx_view .inputs() .get(address_source.index as usize) - .ok_or(Error::Custom("Invalid address source".to_string()))?; + .ok_or(RpcError::InvalidAddressSource)?; log::debug!("[mempool]: verify interoperation tx sender \ntx view \n{:?}\ndummy input\n {:?}\naddress source\n{:?}\n", ckb_tx_view, dummy_input, address_source); @@ -226,9 +228,7 @@ impl Web3RpcImpl { if let Some(cell) = dummy_input { if address_source.type_ == 1 && cell.type_script.is_none() { - return Err(Error::Custom( - "Invalid address source in dummy input mode".to_string(), - )); + return Err(RpcError::InvalidAddressSource.into()); } let script_hash = if address_source.type_ == 0 { @@ -240,7 +240,7 @@ impl Web3RpcImpl { return Ok(Hasher::digest(script_hash).into()); } - return Err(Error::Custom("No dummy input cell".to_string())); + return Err(RpcError::MissingDummyInputCell.into()); } // Reality input mode @@ -248,7 +248,7 @@ impl Web3RpcImpl { .adapter .get_image_cell_root(Context::new()) .await - .map_err(|e| Error::Custom(e.to_string()))?; + .map_err(|e| RpcError::Internal(e.to_string()))?; match DataProvider::new(root).cell(&input.previous_output(), true) { CellStatus::Live(cell) => { let script_hash = if address_source.type_ == 0 { @@ -256,12 +256,12 @@ impl Web3RpcImpl { } else if let Some(type_script) = cell.cell_output.type_().to_opt() { ckb_blake2b_256(type_script.as_slice()) } else { - return Err(Error::Custom("Invalid address source".to_string())); + return Err(RpcError::InvalidAddressSource.into()); }; Ok(Hasher::digest(script_hash).into()) } - _ => Err(Error::Custom("Cannot find input cell in ICSC".to_string())), + _ => Err(RpcError::CannotFindImageCell.into()), } } } @@ -271,35 +271,30 @@ impl Web3RpcServer for Web3RpcImpl { #[metrics_rpc("eth_sendRawTransaction")] async fn send_raw_transaction(&self, tx: Hex) -> RpcResult { let utx = UnverifiedTransaction::decode(&tx.as_bytes()) - .map_err(|e| Error::Custom(e.to_string()))?; + .map_err(|e| RpcError::Internal(e.to_string()))?; let gas_price = utx.unsigned.gas_price(); if gas_price == U256::zero() { - return Err(Error::Custom( - "The transaction gas price is zero".to_string(), - )); + return Err(RpcError::GasPriceIsZero.into()); } if gas_price >= U256::from(u64::MAX) { - return Err(Error::Custom("The gas price is too large".to_string())); + return Err(RpcError::GasPriceIsTooLarge.into()); } let gas_limit = *utx.unsigned.gas_limit(); if gas_limit < MIN_TRANSACTION_GAS_LIMIT.into() { - return Err(Error::Custom( - "The transaction gas limit less than 21000".to_string(), - )); + return Err(RpcError::GasLimitIsTooLow.into()); } if gas_limit > self.max_gas_cap { - return Err(Error::Custom( - "The transaction gas limit is too large".to_string(), - )); + return Err(RpcError::GasLimitIsTooLarge.into()); } - utx.check_hash().map_err(|e| Error::Custom(e.to_string()))?; + utx.check_hash() + .map_err(|e| RpcError::Internal(e.to_string()))?; let interoperation_sender = if let Some(sig) = utx.signature.as_ref() { if sig.is_eth_sig() { @@ -308,17 +303,17 @@ impl Web3RpcServer for Web3RpcImpl { Some(self.extract_interoperation_tx_sender(&utx, sig).await?) } } else { - return Err(Error::Custom("The transaction is not signed".to_string())); + return Err(RpcError::TransactionIsNotSigned.into()); }; let stx = SignedTransaction::from_unverified(utx, interoperation_sender) - .map_err(|e| Error::Custom(e.to_string()))?; + .map_err(|e| RpcError::Internal(e.to_string()))?; let hash = stx.transaction.hash; self.adapter .insert_signed_txs(Context::new(), stx) .await - .map_err(|e| Error::Custom(e.to_string()))?; + .map_err(|e| RpcError::Internal(e.to_string()))?; Ok(hash) } @@ -329,21 +324,18 @@ impl Web3RpcServer for Web3RpcImpl { .adapter .get_transaction_by_hash(Context::new(), hash) .await - .map_err(|e| Error::Custom(e.to_string()))?; + .map_err(|e| RpcError::Internal(e.to_string()))?; if let Some(stx) = res { if let Some(receipt) = self .adapter .get_receipt_by_tx_hash(Context::new(), hash) .await - .map_err(|e| Error::Custom(e.to_string()))? + .map_err(|e| RpcError::Internal(e.to_string()))? { Ok(Some((stx, receipt).into())) } else { - Err(Error::Custom(format!( - "can not get receipt by hash {:?}", - hash - ))) + Err(RpcError::CannotGetReceiptByHash.into()) } } else { Ok(None) @@ -360,7 +352,7 @@ impl Web3RpcServer for Web3RpcImpl { .adapter .get_block_by_number(Context::new(), number.into()) .await - .map_err(|e| Error::Custom(e.to_string()))?; + .map_err(|e| RpcError::Internal(e.to_string()))?; match block { Some(b) => { @@ -375,7 +367,7 @@ impl Web3RpcServer for Web3RpcImpl { .adapter .get_transaction_by_hash(Context::new(), tx.get_hash()) .await - .map_err(|e| Error::Custom(e.to_string()))? + .map_err(|e| RpcError::Internal(e.to_string()))? .unwrap(); txs.push(RichTransactionOrHash::Rich( @@ -405,7 +397,7 @@ impl Web3RpcServer for Web3RpcImpl { .adapter .get_block_by_hash(Context::new(), hash) .await - .map_err(|e| Error::Custom(e.to_string()))?; + .map_err(|e| RpcError::Internal(e.to_string()))?; match block { Some(b) => { @@ -420,7 +412,7 @@ impl Web3RpcServer for Web3RpcImpl { .adapter .get_transaction_by_hash(Context::new(), tx.get_hash()) .await - .map_err(|e| Error::Custom(e.to_string()))? + .map_err(|e| RpcError::Internal(e.to_string()))? .unwrap(); txs.push(RichTransactionOrHash::Rich( @@ -452,7 +444,7 @@ impl Web3RpcServer for Web3RpcImpl { .adapter .get_pending_tx_count(Context::new(), address) .await - .map_err(|e| Error::Custom(e.to_string()))?; + .map_err(|e| RpcError::Internal(e.to_string()))?; Ok(self .adapter .get_account(Context::new(), address, BlockId::Pending.into()) @@ -465,7 +457,7 @@ impl Web3RpcServer for Web3RpcImpl { .adapter .get_block_number_by_hash(Context::new(), *hash) .await - .map_err(|e| Error::Custom(e.to_string()))?; + .map_err(|e| RpcError::Internal(e.to_string()))?; Ok(self .adapter .get_account(Context::new(), address, number) @@ -487,9 +479,9 @@ impl Web3RpcServer for Web3RpcImpl { self.adapter .get_block_header_by_number(Context::new(), None) .await - .map_err(|e| Error::Custom(e.to_string()))? + .map_err(|e| RpcError::Internal(e.to_string()))? .map(|h| U256::from(h.number)) - .ok_or_else(|| Error::Custom("Cannot get latest block header".to_string())) + .ok_or_else(|| RpcError::CannotGetLatestBlock.into()) } #[metrics_rpc("eth_getBalance")] @@ -506,11 +498,11 @@ 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) { - return Err(Error::Custom("The gas price is too large".to_string())); + return Err(RpcError::GasLimitIsTooLarge.into()); } if req.gas.unwrap_or_default() > U256::from(MAX_RPC_GAS_CAP) { - return Err(Error::Custom("The gas limit is too large".to_string())); + return Err(RpcError::GasLimitIsTooLarge.into()); } let number = self.get_block_number_by_id(block_id).await?; @@ -523,7 +515,7 @@ impl Web3RpcServer for Web3RpcImpl { let resp = self .call_evm(req, data_bytes, number) .await - .map_err(|e| Error::Custom(e.to_string()))?; + .map_err(|e| RpcError::Internal(e.to_string()))?; if resp.exit_reason.is_succeed() { let call_hex_result = Hex::encode(resp.ret); @@ -537,13 +529,13 @@ impl Web3RpcServer for Web3RpcImpl { 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(Error::Custom("Failed: Gas cannot be zero".to_string())); + return Err(RpcError::GasPriceIsZero.into()); } } if let Some(price) = req.gas_price.as_ref() { if price >= &U256::from(u64::MAX) { - return Err(Error::Custom("Failed: Gas price too high".to_string())); + return Err(RpcError::GasPriceIsTooLarge.into()); } } @@ -559,7 +551,7 @@ impl Web3RpcServer for Web3RpcImpl { let resp = self .call_evm(req, data_bytes, num) .await - .map_err(|e| Error::Custom(e.to_string()))?; + .map_err(|e| RpcError::Internal(e.to_string()))?; if resp.exit_reason.is_succeed() { return Ok(resp.gas_used.into()); @@ -576,13 +568,13 @@ impl Web3RpcServer for Web3RpcImpl { .adapter .get_account(Context::new(), address, number) .await - .map_err(|e| Error::Custom(e.to_string()))?; + .map_err(|e| RpcError::Internal(e.to_string()))?; let code_result = self .adapter .get_code_by_hash(Context::new(), &account.code_hash) .await - .map_err(|e| Error::Custom(e.to_string()))?; + .map_err(|e| RpcError::Internal(e.to_string()))?; if let Some(code_bytes) = code_result { Ok(Hex::encode(code_bytes)) } else { @@ -596,7 +588,7 @@ impl Web3RpcServer for Web3RpcImpl { .adapter .get_block_by_number(Context::new(), number.into()) .await - .map_err(|e| Error::Custom(e.to_string()))?; + .map_err(|e| RpcError::Internal(e.to_string()))?; let count = match block { Some(bc) => bc.tx_hashes.len(), _ => 0, @@ -611,14 +603,14 @@ impl Web3RpcServer for Web3RpcImpl { .adapter .get_transaction_by_hash(ctx.clone(), hash) .await - .map_err(|e| Error::Custom(e.to_string()))?; + .map_err(|e| RpcError::Internal(e.to_string()))?; if let Some(stx) = res { if let Some(receipt) = self .adapter .get_receipt_by_tx_hash(ctx, hash) .await - .map_err(|e| Error::Custom(e.to_string()))? + .map_err(|e| RpcError::Internal(e.to_string()))? { return Ok(Some(Web3Receipt::new(receipt, stx))); } @@ -632,7 +624,7 @@ impl Web3RpcServer for Web3RpcImpl { self.adapter .peer_count(Context::new()) .await - .map_err(|e| Error::Custom(e.to_string())) + .map_err(|e| RpcError::Internal(e.to_string()).into()) } #[metrics_rpc("eth_gasPrice")] @@ -690,7 +682,7 @@ impl Web3RpcServer for Web3RpcImpl { match adapter .get_block_by_hash(Context::new(), hash) .await - .map_err(|e| Error::Custom(e.to_string()))? + .map_err(|e| RpcError::Internal(e.to_string()))? { Some(block) => { let receipts = adapter @@ -700,22 +692,18 @@ impl Web3RpcServer for Web3RpcImpl { &block.tx_hashes, ) .await - .map_err(|e| Error::Custom(e.to_string()))?; + .map_err(|e| RpcError::Internal(e.to_string()))?; extend_logs(logs, receipts, early_return); Ok(()) } - None => Err(Error::Custom(format!( - "Invalid block hash - {}", - hash - ))), + None => Err(RpcError::InvalidBlockHash.into()), } } BlockPosition::Num(n) => { let block = adapter .get_block_by_number(Context::new(), Some(n)) .await - .map_err(|e| Error::Custom(e.to_string()))? + .map_err(|e| RpcError::Internal(e.to_string()))? .unwrap(); let receipts = adapter .get_receipts_by_hashes( @@ -724,7 +712,7 @@ impl Web3RpcServer for Web3RpcImpl { &block.tx_hashes, ) .await - .map_err(|e| Error::Custom(e.to_string()))?; + .map_err(|e| RpcError::Internal(e.to_string()))?; extend_logs(logs, receipts, early_return); Ok(()) @@ -737,7 +725,7 @@ impl Web3RpcServer for Web3RpcImpl { &block.tx_hashes, ) .await - .map_err(|e| Error::Custom(e.to_string()))?; + .map_err(|e| RpcError::Internal(e.to_string()))?; extend_logs(logs, receipts, early_return); Ok(()) @@ -765,7 +753,7 @@ impl Web3RpcServer for Web3RpcImpl { .adapter .get_block_by_number(Context::new(), None) .await - .map_err(|e| Error::Custom(e.to_string()))? + .map_err(|e| RpcError::Internal(e.to_string()))? .unwrap(); let latest_number = latest_block.header.number; let (start, end) = { @@ -787,14 +775,16 @@ impl Web3RpcServer for Web3RpcImpl { }; if start > latest_number { - return Err(Error::Custom(format!("Invalid from_block {}", start))); + return Err(RpcError::InvalidFromBlockNumber(start).into()); } if end.saturating_sub(start) > self.log_filter_max_block_range { - return Err(Error::Custom(format!( - "Invalid block range {:?} to {:?}, limit to {:?}", - start, end, self.log_filter_max_block_range - ))); + return Err(RpcError::InvalidBlockRange( + start, + end, + self.log_filter_max_block_range, + ) + .into()); } let mut visiter_last_block = false; @@ -920,7 +910,7 @@ impl Web3RpcServer for Web3RpcImpl { .adapter .get_block_by_number(Context::new(), Some(0)) .await - .map_err(|e| Error::Custom(e.to_string()))? + .map_err(|e| RpcError::Internal(e.to_string()))? .unwrap(); let base_fee_per_gas = vec![ first_block.header.base_fee_per_gas, @@ -960,12 +950,7 @@ impl Web3RpcServer for Web3RpcImpl { } } } - _ => { - return Err(Error::Custom(format!( - "Invalid parameter newest_block {:?}", - newest_block - ))) - } + _ => return Err(RpcError::InvalidNewestBlock(newest_block).into()), } } @@ -980,7 +965,7 @@ impl Web3RpcServer for Web3RpcImpl { .adapter .get_block_by_hash(Context::new(), hash) .await - .map_err(|e| Error::Custom(e.to_string()))? + .map_err(|e| RpcError::Internal(e.to_string()))? .map(|b| U256::from(b.tx_hashes.len())) .unwrap_or_default()) } @@ -992,7 +977,7 @@ impl Web3RpcServer for Web3RpcImpl { position: U256, ) -> RpcResult> { if position > U256::from(usize::MAX) { - return Err(Error::Custom(format!("invalid position: {}", position))); + return Err(RpcError::InvalidPosition(position.as_u64()).into()); } let mut raw = [0u8; 32]; @@ -1006,7 +991,7 @@ impl Web3RpcServer for Web3RpcImpl { .adapter .get_block_by_hash(Context::new(), hash) .await - .map_err(|e| Error::Custom(e.to_string()))?; + .map_err(|e| RpcError::Internal(e.to_string()))?; if let Some(block) = block { if let Some(tx_hash) = block.tx_hashes.get(index) { @@ -1023,7 +1008,7 @@ impl Web3RpcServer for Web3RpcImpl { position: U256, ) -> RpcResult> { if position > U256::from(usize::MAX) { - return Err(Error::Custom(format!("invalid position: {}", position))); + return Err(RpcError::InvalidPosition(position.as_u64()).into()); } let mut raw = [0u8; 32]; @@ -1038,7 +1023,7 @@ impl Web3RpcServer for Web3RpcImpl { .adapter .get_block_by_number(Context::new(), number.into()) .await - .map_err(|e| Error::Custom(e.to_string()))?; + .map_err(|e| RpcError::Internal(e.to_string()))?; if let Some(block) = block { if let Some(tx_hash) = block.tx_hashes.get(index) { @@ -1061,8 +1046,8 @@ impl Web3RpcServer for Web3RpcImpl { .adapter .get_block_by_number(Context::new(), number) .await - .map_err(|e| Error::Custom(e.to_string()))? - .ok_or_else(|| Error::Custom("Can't find this block".to_string()))?; + .map_err(|e| RpcError::Internal(e.to_string()))? + .ok_or(RpcError::CannotFindBlock)?; let value = self .adapter .get_storage_at(Context::new(), address, position, block.header.state_root) @@ -1118,12 +1103,7 @@ fn check_reward_percentiles(reward_percentiles: &Option>) -> RpcResult< .find(|(_, window)| window[0] >= window[1] || window[0] < 0.0 || window[0] > 100.0) .map(|(_, vec)| vec) }) - .map(|vec| { - Err(Error::Custom(format!( - "Invalid parameter reward_percentiles: {} {}", - vec[0], vec[1] - ))) - }) + .map(|vec| Err(RpcError::InvalidRewardPercentiles(vec[0], vec[1]).into())) .unwrap_or(Ok(())) } diff --git a/core/api/src/jsonrpc/mod.rs b/core/api/src/jsonrpc/mod.rs index c0df87e14..4cd07046b 100644 --- a/core/api/src/jsonrpc/mod.rs +++ b/core/api/src/jsonrpc/mod.rs @@ -7,7 +7,7 @@ use std::{collections::HashMap, sync::Arc}; use ckb_jsonrpc_types::{CellInfo, HeaderView as CkbHeaderView, OutPoint}; use jsonrpsee::server::{ServerBuilder, ServerHandle}; -use jsonrpsee::{core::Error, proc_macros::rpc}; +use jsonrpsee::{core::RpcResult, proc_macros::rpc}; use common_config_parser::types::{spec::HardforkName, Config}; use protocol::traits::APIAdapter; @@ -25,8 +25,6 @@ use crate::APIError; use self::web3_types::BlockCount; -type RpcResult = Result; - #[rpc(server)] pub trait Web3Rpc { /// Sends signed transaction, returning its hash. @@ -279,11 +277,7 @@ pub async fn run_jsonrpc_server( .await .map_err(|e| APIError::HttpServer(e.to_string()))?; - ret.0 = Some( - server - .start(rpc.clone()) - .map_err(|e| APIError::HttpServer(e.to_string()))?, - ); + ret.0 = Some(server.start(rpc.clone())); } if let Some(addr) = config.rpc.ws_listening_address { @@ -299,11 +293,7 @@ pub async fn run_jsonrpc_server( rpc.merge(ws_subscription_module(adapter).await).unwrap(); - ret.1 = Some( - server - .start(rpc) - .map_err(|e| APIError::WebSocketServer(e.to_string()))?, - ) + ret.1 = Some(server.start(rpc)) } Ok(ret) diff --git a/core/api/src/jsonrpc/ws_subscription.rs b/core/api/src/jsonrpc/ws_subscription.rs index 1765d6ded..46b197ad6 100644 --- a/core/api/src/jsonrpc/ws_subscription.rs +++ b/core/api/src/jsonrpc/ws_subscription.rs @@ -1,5 +1,4 @@ use std::{ - io, sync::{ atomic::{AtomicU64, Ordering}, Arc, @@ -7,23 +6,18 @@ use std::{ time::Duration, }; -use jsonrpsee::{ - core::Error, - server::{IdProvider, RpcModule, SubscriptionSink}, - types::{error::CallError, params::Params, SubscriptionId}, +use jsonrpsee::server::{ + IdProvider, IntoSubscriptionCloseResponse, PendingSubscriptionSink, RpcModule, + SubscriptionMessage, SubscriptionSink, }; +use jsonrpsee::types::{error::ErrorCode, params::Params, ErrorObjectOwned, SubscriptionId}; use serde::{Deserialize, Serialize}; use core_consensus::SYNC_STATUS; -use protocol::{ - tokio::{ - self, select, - sync::mpsc::{channel, Receiver, Sender}, - time::interval, - }, - traits::{APIAdapter, Context}, - types::{BigEndianHash, Hash, Hex, H160, H256, U256}, -}; +use protocol::tokio::sync::mpsc::{channel, Receiver, Sender}; +use protocol::tokio::{self, select, time::interval}; +use protocol::traits::{APIAdapter, Context}; +use protocol::types::{BigEndianHash, Hash, Hex, H160, H256, U256}; use crate::jsonrpc::{ r#impl::from_receipt_to_web3_log, @@ -45,27 +39,36 @@ where "eth_subscribe", "eth_subscription", "eth_unsubscribe", - |params, mut sink, ctx| match Type::try_from(params) { - Ok(typ) => { - sink.accept()?; - let raw_hub = RawHub { typ, sink }; - - tokio::spawn(async move { - let _ignore = ctx.send(raw_hub).await; - }); - Ok(()) - } - Err(e) => { - let e: Error = e.into(); - let _ = sink.reject(e); - Ok(()) - } - }, + subscription_callback, ) .unwrap(); rpc } +async fn subscription_callback( + params: Params<'static>, + sink: PendingSubscriptionSink, + ctx: Arc>, +) -> impl IntoSubscriptionCloseResponse { + match Type::try_from(params) { + Ok(type_) => { + let raw_hub = RawHub { + typ: type_, + sink: sink.accept().await?, + }; + + tokio::spawn(async move { + let _ignore = ctx.send(raw_hub).await; + }); + Ok(()) + } + Err(e) => { + sink.reject(e).await; + Ok(()) + } + } +} + pub struct Subscription { log_hubs: Vec>, header_hubs: Vec>, @@ -128,24 +131,29 @@ where log_vec.push((block.header.number, block.tx_hashes)); let web3_header = Web3Header::from(block.header); + let msg = SubscriptionMessage::from_json(&web3_header).unwrap(); + for hub in self.header_hubs.iter_mut() { - let _ignore = hub.sink.send(&web3_header); + let _ignore = hub.sink.send(msg.clone()); } } let latest_web3_header = Web3Header::from(latest_block.header); + let msg = SubscriptionMessage::from_json(&latest_web3_header).unwrap(); + for hub in self.header_hubs.iter_mut() { - let _ignore = hub.sink.send(&latest_web3_header); + let _ignore = hub.sink.send(msg.clone()); } } // Send all sync status if !self.sync_hubs.is_empty() { let web3_sync_state: Web3SyncStatus = { SYNC_STATUS.read().clone().into() }; + let msg = SubscriptionMessage::from_json(&web3_sync_state).unwrap(); for hub in self.sync_hubs.iter_mut() { // unbound sender can ignore it's return - let _ignore = hub.sink.send(&web3_sync_state); + let _ignore = hub.sink.send(msg.clone()); } } @@ -188,8 +196,9 @@ where ); for log in logs.drain(..) { + let msg = SubscriptionMessage::from_json(&log).unwrap(); // unbound sender can ignore it's return - let _ignore = hub.sink.send(&log); + let _ignore = hub.sink.send(msg); } } index += log_len; @@ -236,7 +245,7 @@ enum Type { } impl<'a> TryFrom> for Type { - type Error = CallError; + type Error = ErrorObjectOwned; fn try_from(value: Params<'a>) -> Result { let mut iter = value.sequence(); @@ -250,10 +259,7 @@ impl<'a> TryFrom> for Type { let filter: RawLoggerFilter = iter.next()?; Ok(Type::Logs(filter.into())) } - _ => Err(CallError::from_std_error(io::Error::new( - io::ErrorKind::InvalidData, - format!("invalid method: {}", method), - ))), + _ => Err(ErrorCode::MethodNotFound.into()), } } } diff --git a/core/db/src/rocks.rs b/core/db/src/rocks.rs index 9eef95663..e22241058 100644 --- a/core/db/src/rocks.rs +++ b/core/db/src/rocks.rs @@ -295,7 +295,6 @@ impl From for ProtocolError { } } -// column family "c0" is reserved for store version const C_VERSION: &str = "c0"; const C_BLOCKS: &str = "c1"; const C_BLOCK_HEADER: &str = "c2"; diff --git a/core/executor/Cargo.toml b/core/executor/Cargo.toml index f83aadd0d..b98bb0e56 100644 --- a/core/executor/Cargo.toml +++ b/core/executor/Cargo.toml @@ -8,8 +8,8 @@ version = "0.1.0" arc-swap = "1.6" az = "1.2" bn = { package = "substrate-bn", version = "0.6" } -ckb-traits = "0.108" -ckb-types = "0.108" +ckb-traits = "0.111" +ckb-types = "0.111" common-apm = { path = "../../common/apm" } common-config-parser = { path = "../../common/config-parser" } common-crypto = { path = "../../common/crypto" } @@ -36,8 +36,8 @@ thiserror = "1.0" [dev-dependencies] bytemuck = "1.13" -ckb-jsonrpc-types = "0.108" -ckb-types = "0.108" +ckb-jsonrpc-types = "0.111" +ckb-types = "0.111" common-crypto = { path = "../../common/crypto" } core-rpc-client = { path = "../rpc-client" } core-storage = { path = "../storage" } diff --git a/core/executor/src/precompiles/verify_by_ckb_vm.rs b/core/executor/src/precompiles/verify_by_ckb_vm.rs index 35e1a799f..d2ccc31ca 100644 --- a/core/executor/src/precompiles/verify_by_ckb_vm.rs +++ b/core/executor/src/precompiles/verify_by_ckb_vm.rs @@ -30,7 +30,7 @@ impl PrecompileContract for CkbVM { if let Some(gas) = gas_limit { let res = InteroperationImpl::verify_by_ckb_vm( Default::default(), - &DataProvider::new(CURRENT_HEADER_CELL_ROOT.with(|r| *r.borrow())), + DataProvider::new(CURRENT_HEADER_CELL_ROOT.with(|r| *r.borrow())), &InteroperationImpl::dummy_transaction( SignatureR::new_by_ref( payload.cell_deps(), diff --git a/core/executor/src/system_contract/mod.rs b/core/executor/src/system_contract/mod.rs index 141c86f6f..fc3a85bbb 100644 --- a/core/executor/src/system_contract/mod.rs +++ b/core/executor/src/system_contract/mod.rs @@ -19,7 +19,7 @@ pub use crate::system_contract::native_token::{ use std::sync::Arc; -use ckb_traits::{CellDataProvider, HeaderProvider}; +use ckb_traits::{CellDataProvider, ExtensionProvider, HeaderProvider}; use ckb_types::core::cell::{CellProvider, CellStatus}; use ckb_types::core::{HeaderBuilder, HeaderView}; use ckb_types::{packed, prelude::*}; @@ -27,8 +27,9 @@ use evm::backend::ApplyBackend; use parking_lot::RwLock; use rocksdb::DB; +use protocol::ckb_blake2b_256; +use protocol::traits::{CkbDataProvider, ExecutorAdapter}; use protocol::types::{Bytes, Hasher, SignedTransaction, TxResp, H160, H256}; -use protocol::{ckb_blake2b_256, traits::ExecutorAdapter}; use crate::adapter::RocksTrieDB; use crate::system_contract::{ @@ -236,6 +237,19 @@ impl HeaderProvider for DataProvider { } } +impl ExtensionProvider for DataProvider { + fn get_block_extension(&self, hash: &packed::Byte32) -> Option { + let block_hash = hash.unpack(); + CkbHeaderReader + .get_header_by_block_hash(self.root, &H256(block_hash.0)) + .ok() + .flatten() + .map(|h| h.extension.pack()) + } +} + +impl CkbDataProvider for DataProvider {} + impl DataProvider { pub fn new(root: H256) -> Self { DataProvider { root } diff --git a/core/interoperation/Cargo.toml b/core/interoperation/Cargo.toml index 40574f3fa..5de4c51cd 100644 --- a/core/interoperation/Cargo.toml +++ b/core/interoperation/Cargo.toml @@ -7,11 +7,12 @@ edition = "2021" [dependencies] arc-swap = "1.5" -ckb-error = "0.108" -ckb-script = "0.108" -ckb-traits = "0.108" -ckb-types = "0.108" -ckb-vm = { version = "0.22.2", features = ["asm"] } +ckb-chain-spec = "0.111" +ckb-error = "0.111" +ckb-script = "0.111" +ckb-traits = "0.111" +ckb-types = "0.111" +ckb-vm = { version = "=0.24.6", features = ["asm"] } lazy_static = "1.4" log = "0.4" @@ -20,7 +21,7 @@ protocol = { path = "../../protocol", package = "axon-protocol", default-feature [dev-dependencies] cardano-serialization-lib = "7.0" cardano-message-signing = { git = "https://github.com/ashuralyk/message-signing", branch = "rust" } -ckb-jsonrpc-types = "0.108" +ckb-jsonrpc-types = "0.111" ed25519-dalek = "1.0" ethers-core = "2.0" serde_json = "1.0" diff --git a/core/interoperation/src/lib.rs b/core/interoperation/src/lib.rs index 6159872b9..0d38e3c69 100644 --- a/core/interoperation/src/lib.rs +++ b/core/interoperation/src/lib.rs @@ -3,16 +3,17 @@ mod tests; pub mod utils; -use std::error::Error; +use std::{error::Error, sync::Arc}; -use ckb_script::TransactionScriptsVerifier; -use ckb_traits::{CellDataProvider, HeaderProvider}; -use ckb_types::core::{cell::CellProvider, Cycle, TransactionView}; -use ckb_types::packed; +use ckb_chain_spec::consensus::Consensus; +use ckb_script::{TransactionScriptsVerifier, TxVerifyEnv}; +use ckb_traits::CellDataProvider; +use ckb_types::core::{Cycle, HeaderBuilder, TransactionView}; +use ckb_types::{packed, prelude::Pack}; use ckb_vm::machine::{asm::AsmCoreMachine, DefaultMachineBuilder, SupportMachine, VERSION1}; use ckb_vm::{Error as VMError, ISA_B, ISA_IMC, ISA_MOP}; -use protocol::traits::{Context, Interoperation}; +use protocol::traits::{CkbDataProvider, Context, Interoperation}; use protocol::types::{Bytes, CellDep, CellWithData, OutPoint, VMResp}; use protocol::{Display, ProtocolError, ProtocolErrorKind, ProtocolResult}; @@ -21,6 +22,11 @@ use crate::utils::resolve_transaction; const ISA: u8 = ISA_IMC | ISA_B | ISA_MOP; const GAS_TO_CYCLE_COEF: u64 = 6_000; +// The following information is from CKB block [10976708](https://explorer.nervos.org/block/10976708) +// which is CKB2023 disabled. +const CKB2023_DISABLED_NUMBER: u64 = 10_976_708; +const CKB2023_DISABLED_EPOCH: u64 = 0x53c007f0020c8; + pub const fn gas_to_cycle(gas: u64) -> u64 { gas * GAS_TO_CYCLE_COEF } @@ -74,17 +80,33 @@ impl Interoperation for InteroperationImpl { }) } - fn verify_by_ckb_vm( + /// Todo: After CKB2023 is enabled, a hardfork is needed to support the new + /// VM version and syscalls. + fn verify_by_ckb_vm( _ctx: Context, - data_loader: &DL, + data_loader: DL, mocked_tx: &TransactionView, dummy_input: Option, max_cycles: u64, ) -> ProtocolResult { - let rtx = resolve_transaction(data_loader, mocked_tx, dummy_input)?; + let rtx = Arc::new(resolve_transaction(&data_loader, mocked_tx, dummy_input)?); log::debug!("[mempool]: Verify by ckb vm tx {:?}", rtx); - TransactionScriptsVerifier::new(&rtx, data_loader) + // The consensus and tx_env arguments are used for judge if the VM version2 and + // syscalls3 are enabled. Due to only the hardfork field in consensus and the + // epoch field in tx_env is used, the provided arguments only need to fill these + // fields correctly. + let (ckb_spec, ckb2023_disabled_env) = ( + Arc::new(Consensus::default()), + Arc::new(TxVerifyEnv::new_commit( + &HeaderBuilder::default() + .number(CKB2023_DISABLED_NUMBER.pack()) + .epoch(CKB2023_DISABLED_EPOCH.pack()) + .build(), + )), + ); + + TransactionScriptsVerifier::new(rtx, data_loader, ckb_spec, ckb2023_disabled_env) .verify(max_cycles) .map_err(|e| InteroperationError::Ckb(e).into()) } diff --git a/core/mempool/Cargo.toml b/core/mempool/Cargo.toml index cd9debfac..dd224975a 100644 --- a/core/mempool/Cargo.toml +++ b/core/mempool/Cargo.toml @@ -5,10 +5,10 @@ edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] -ckb-types = "0.108" +ckb-types = "0.111" crossbeam-queue = "0.3" dashmap = { version = "5.5", features = ["rayon"] } -futures = { version = "0.3", features = [ "async-await" ] } +futures = { version = "0.3", features = ["async-await"] } log = "0.4" parking_lot = "0.12" rlp = "0.5" diff --git a/core/mempool/src/adapter/mod.rs b/core/mempool/src/adapter/mod.rs index 11519d86f..e5dcdda6a 100644 --- a/core/mempool/src/adapter/mod.rs +++ b/core/mempool/src/adapter/mod.rs @@ -319,7 +319,7 @@ where InteroperationImpl::verify_by_ckb_vm( Default::default(), - &DataProvider::new(root), + DataProvider::new(root), &InteroperationImpl::dummy_transaction( r.clone(), s, diff --git a/core/rpc-client/Cargo.toml b/core/rpc-client/Cargo.toml index f7bbf11f6..75e332dcf 100644 --- a/core/rpc-client/Cargo.toml +++ b/core/rpc-client/Cargo.toml @@ -5,9 +5,9 @@ edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] -ckb-jsonrpc-types = "0.108" -ckb-sdk = "2.5" -ckb-types = "0.108" +ckb-jsonrpc-types = "0.111" +ckb-sdk = "3.0" +ckb-types = "0.111" futures = "0.3" jsonrpc-core = "18.0" reqwest = { version = "0.11", features = ["json"] } diff --git a/core/storage/src/lib.rs b/core/storage/src/lib.rs index f4eb7d2b1..f4a697d17 100644 --- a/core/storage/src/lib.rs +++ b/core/storage/src/lib.rs @@ -26,13 +26,12 @@ use protocol::types::{ use protocol::{ async_trait, tokio, Display, From, ProtocolError, ProtocolErrorKind, ProtocolResult, }; -use schema::HardforkSchema; use crate::cache::StorageCache; use crate::hash_key::{BlockKey, CommonHashKey, CommonPrefix}; use crate::schema::{ BlockHashNumberSchema, BlockHeaderSchema, BlockSchema, EvmCodeAddressSchema, EvmCodeSchema, - LatestBlockSchema, LatestProofSchema, ReceiptBytesSchema, ReceiptSchema, + HardforkSchema, LatestBlockSchema, LatestProofSchema, ReceiptBytesSchema, ReceiptSchema, TransactionBytesSchema, TransactionSchema, TxHashNumberSchema, }; diff --git a/protocol/Cargo.toml b/protocol/Cargo.toml index 8c4960bcf..c97f02a80 100644 --- a/protocol/Cargo.toml +++ b/protocol/Cargo.toml @@ -9,15 +9,21 @@ arc-swap = "1.6" async-trait = "0.1" bincode = "1.3" bytes = { version = "1.5", features = ["serde"] } -ckb-hash = "0.108" -ckb-jsonrpc-types = "0.108" -ckb-sdk = "2.5" -ckb-traits = "0.108" -ckb-types = "0.108" +ckb-hash = "0.111" +ckb-jsonrpc-types = "0.111" +ckb-sdk = "3.0" +ckb-traits = "0.111" +ckb-types = "0.111" creep = "0.2" derive_more = "0.99" ethereum = { version = "0.14", features = ["with-codec", "with-serde"] } -ethereum-types = { version = "0.14", features = ["arbitrary", "codec", "rlp", "serialize", "std"] } +ethereum-types = { version = "0.14", features = [ + "arbitrary", + "codec", + "rlp", + "serialize", + "std", +] } ethers-core = "2.0" evm = { version = "0.37", features = ["with-serde"] } faster-hex = "0.8" diff --git a/protocol/src/traits/interoperation.rs b/protocol/src/traits/interoperation.rs index ba54d3570..72b38d151 100644 --- a/protocol/src/traits/interoperation.rs +++ b/protocol/src/traits/interoperation.rs @@ -1,4 +1,4 @@ -use ckb_traits::{CellDataProvider, HeaderProvider}; +use ckb_traits::{CellDataProvider, ExtensionProvider, HeaderProvider}; use ckb_types::core::{cell::CellProvider, Cycle, TransactionView}; use ckb_types::{packed, prelude::*}; @@ -24,6 +24,11 @@ const fn signature_hash_cell_bytes() -> u64 { 32 + 32 + 1 + 8 } +pub trait CkbDataProvider: + Clone + CellDataProvider + CellProvider + HeaderProvider + ExtensionProvider +{ +} + pub trait Interoperation: Sync + Send { fn call_ckb_vm( ctx: Context, @@ -33,9 +38,9 @@ pub trait Interoperation: Sync + Send { max_cycles: u64, ) -> ProtocolResult; - fn verify_by_ckb_vm( + fn verify_by_ckb_vm( ctx: Context, - data_loader: &DL, + data_loader: DL, mocked_tx: &TransactionView, dummy_input: Option, max_cycles: u64, diff --git a/protocol/src/traits/mod.rs b/protocol/src/traits/mod.rs index 9251d43f6..e300de5e1 100644 --- a/protocol/src/traits/mod.rs +++ b/protocol/src/traits/mod.rs @@ -15,7 +15,9 @@ pub use consensus::{ }; pub use creep::{Cloneable, Context}; pub use executor::{ApplyBackend, Backend, Executor, ExecutorAdapter, ExecutorReadOnlyAdapter}; -pub use interoperation::{Interoperation, BYTE_SHANNONS, SIGNATURE_HASH_CELL_OCCUPIED_CAPACITY}; +pub use interoperation::{ + CkbDataProvider, Interoperation, BYTE_SHANNONS, SIGNATURE_HASH_CELL_OCCUPIED_CAPACITY, +}; pub use mempool::{MemPool, MemPoolAdapter}; pub use network::{ Gossip, MessageCodec, MessageHandler, Network, PeerTag, PeerTrust, Priority, Rpc, TrustFeedback, diff --git a/tests/e2e/src/eth_getStorageAt.test.js b/tests/e2e/src/eth_getStorageAt.test.js index 94439ab05..6a4c79343 100644 --- a/tests/e2e/src/eth_getStorageAt.test.js +++ b/tests/e2e/src/eth_getStorageAt.test.js @@ -92,7 +92,7 @@ describe("eth_getStorageAt", () => { await param1.type(testDataInfo.contractAddress); await param2.type("0x02"); await param3.type("0xffffffffff"); - await goto.check(page, "Can't find this block"); + await goto.check(page, "Cannot find the block"); }); /**