diff --git a/.all-contributorsrc b/.all-contributorsrc index 01327b5c2..c7ab131dc 100644 --- a/.all-contributorsrc +++ b/.all-contributorsrc @@ -7,7 +7,7 @@ "README.md", "README-CN.md" ], - "imageSize": 100, + "imageSize": 50, "commit": true, "commitConvention": "none", "contributors": [ @@ -498,5 +498,5 @@ ] } ], - "contributorsPerLine": 7 + "contributorsPerLine": 9 } diff --git a/.circleci/config.yml b/.circleci/config.yml index 4d509c73c..1a43b851d 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -107,7 +107,7 @@ alias: - &job-default docker: - - image: cita/cita-build:ubuntu-18.04-20190429 + - image: cita/cita-build:ubuntu-18.04-20190515 working_directory: ~/cita-build resource_class: xlarge @@ -145,9 +145,7 @@ jobs: - restore_cache: *restore-security-audit-cache - run: name: Check Security Audit - command: | - echo "Add it back when bump protobuf to `v2.6.0`." - # make security_audit + command: make security_audit - save_cache: *save-security-audit-cache "Check Contracts": @@ -220,20 +218,27 @@ jobs: HASH_ALGO: sm3hash CRYPTO_ALGO: sm2 - "Integrate Test Part-1": + "Basic Test": <<: *job-default steps: - restore_cache: *restore-source-codes-cache - restore_cache: *restore-release-cache - run: *after-restore-release-cache - run: - name: Basic Integrate Test + name: Basic Test command: ./tests/integrate_test/cita_basic.sh + + "Basic Tls Test": + <<: *job-default + steps: + - restore_cache: *restore-source-codes-cache + - restore_cache: *restore-release-cache + - run: *after-restore-release-cache - run: - name: Basic Tls Integrate Test - command: ./tests/integrate_test/cita_tls_basic.sh + name: Basic Tls Test + command: ./tests/integrate_test/cita_basic.sh --enable_tls - "Integrate Test Part-2": + "JSON-RPC Mock Test in Charge Mode": <<: *job-default steps: - restore_cache: *restore-source-codes-cache @@ -247,18 +252,63 @@ jobs: command: | echo "We should add it back later." # ./tests/integrate_test/cita_jsonrpc_schema_mock.sh charge + + "JSON-RPC Mock Test in Quota Mode": + <<: *job-default + steps: + - restore_cache: *restore-source-codes-cache + - restore_cache: *restore-release-cache + - run: *after-restore-release-cache + - run: + name: JSON-RPC Mock Test in Quota Mode + command: ./tests/integrate_test/cita_jsonrpc_schema_mock.sh quota + + "Test Transfer Value in Charge Mode": + <<: *job-default + steps: + - restore_cache: *restore-source-codes-cache + - restore_cache: *restore-release-cache + - run: *after-restore-release-cache - run: name: Test Transfer Value in Charge Mode command: ./tests/integrate_test/cita_charge_mode.sh + + "Test Executor Process SignProposal/BlockWithProof": + <<: *job-default + steps: + - restore_cache: *restore-source-codes-cache + - restore_cache: *restore-release-cache + - run: *after-restore-release-cache - run: name: Test Executor Process SignProposal/BlockWithProof command: ./tests/integrate_test/box_executor_test.sh + + "Test Snapshot Taking And Restoring": + <<: *job-default + steps: + - restore_cache: *restore-source-codes-cache + - restore_cache: *restore-release-cache + - run: *after-restore-release-cache - run: name: Test Snapshot Taking And Restoring command: ./tests/integrate_test/cita_snapshot_test.sh + + "Test Amend": + <<: *job-default + steps: + - restore_cache: *restore-source-codes-cache + - restore_cache: *restore-release-cache + - run: *after-restore-release-cache - run: name: Test Amend command: ./tests/integrate_test/cita_amend_test.sh + + "Test Executor Process Invalid Proof": + <<: *job-default + steps: + - restore_cache: *restore-source-codes-cache + - restore_cache: *restore-release-cache + - run: *after-restore-release-cache - run: name: Test Executor Process Invalid Proof command: ./tests/integrate_test/cita_bft_resend.sh @@ -372,12 +422,32 @@ workflows: requires: - "Release" - - "Integrate Test Part-1": + - "Basic Test": + requires: + - "Release" + - "Basic Tls Test": + requires: + - "Release" + + - "JSON-RPC Mock Test in Charge Mode": + requires: + - "Release" + - "JSON-RPC Mock Test in Quota Mode": requires: - "Release" - - "Integrate Test Part-2": + - "Test Transfer Value in Charge Mode": requires: - "Release" + - "Test Snapshot Taking And Restoring": + requires: + - "Release" + - "Test Amend": + requires: + - "Release" + - "Test Executor Process Invalid Proof": + requires: + - "Release" + - "Discovery Test for network": requires: - "Release" @@ -406,8 +476,14 @@ workflows: - "Passed": requires: - - "Integrate Test Part-1" - - "Integrate Test Part-2" + - "Basic Test" + - "Basic Tls Test" + - "JSON-RPC Mock Test in Charge Mode" + - "JSON-RPC Mock Test in Quota Mode" + - "Test Transfer Value in Charge Mode" + - "Test Snapshot Taking And Restoring" + - "Test Amend" + - "Test Executor Process Invalid Proof" - "Discovery Test for network" - "Byzantine Test in Quota Mode" - "Byzantine Test in Charge Mode" diff --git a/.gitmodules b/.gitmodules index d1f45a686..6b3480962 100644 --- a/.gitmodules +++ b/.gitmodules @@ -10,8 +10,8 @@ path = scripts/txtool/txtool/proto url = https://github.com/cryptape/cita-proto.git branch = master -[submodule "scripts/contracts/tests/contracts"] - path = scripts/contracts/tests/contracts +[submodule "tests/contracts"] + path = tests/contracts url = https://github.com/cryptape/test-contracts.git branch = master [submodule "scripts/contracts/interaction"] diff --git a/.travis.yml b/.travis.yml index f8495607f..9bf9c0405 100644 --- a/.travis.yml +++ b/.travis.yml @@ -11,13 +11,19 @@ services: git: depth: 1 stages: + - CheckShell - Release - IntegrateTest before_install: - - docker pull cita/cita-build:ubuntu-18.04-20190429 + - docker pull cita/cita-build:ubuntu-18.04-20190515 jobs: include: + - stage: CheckShell + script: + # Fail if any of these files have warnings + - shellcheck scripts/*.sh env.sh + - stage: Release name: Release for Integrate Test language: node_js @@ -84,6 +90,9 @@ jobs: - <<: *stage-contract-test-sha3-secp256k1 name: Unit Quota Management script: npm run-script unit_qm + - <<: *stage-contract-test-sha3-secp256k1 + name: Unit Quota + script: npm run-script unit_quota - <<: *stage-contract-test-sha3-secp256k1 name: Unit Abi script: npm run-script abi @@ -99,6 +108,9 @@ jobs: - <<: *stage-contract-test-sha3-secp256k1 name: Unit Uint8 script: npm run-script uint8 + - <<: *stage-contract-test-sha3-secp256k1 + name: Unit VersionManager + script: npm run-script unit_vm - <<: *stage-contract-test-sha3-secp256k1 name: Unit Node @@ -152,3 +164,17 @@ jobs: - ./bin/cita start test-chain/0 script: - npm run-script auto_exec + + - <<: *stage-contract-test-sha3-secp256k1 + name: Integrate Lifetime + install: + - cd $TRAVIS_BUILD_DIR/target/install + - ./bin/cita create + --nodes "127.0.0.1:4100" + --contract_arguments "SysConfig.economicalModel=1 PriceManager.quotaPrice=1" + --super_admin "0x4b5ae4567ad5d9fb92bc9afd6a657e6fa13a2523" + --init_token 0x1000000 + - ./bin/cita setup test-chain/0 + - ./bin/cita start test-chain/0 + script: + - npm run-script lifetime diff --git a/CHANGELOG.md b/CHANGELOG.md index ab84ff6ff..f617907cc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,48 @@ All notable changes to this project will be documented in this file. And this pr ## [Unreleased] +### Framework + +- [Optimization] Bump Rust toolchain to `1.34.2`. [@kaikai1024] +- [Optimization] Use Rust 2018 edition. [@kaikai1024] [@ouwenkg] +- [Optimization] Use `cita-logger` crate. [@kaikai1024] + +### Network + +- [Fix] Fix the bug that save wrong session. [@leeyr338] +- [Fix] Should not unwrap on handle_remote_msg. [@leeyr338] +- [Fix] Fix the operation of repeated peer key. [@jerry-yu] +- [Feature] Add retransfer message for P2P network. [@jerry-yu] + +### System Contracts + +- [Fix] Fix the import path. [@ouwenkg] +- [Optimization] Use `protocol version` instead of version. [@kaikai1024] +- [Optimization] Rename `emergency brake` to `emergency intervention`. [@kaikai1024] + +### Tools + +- [Refactor] Rewrite the tool of creating genesis using Rust. [@ouwenkg] + +### Test + +- [Refactor] Refactor scripts of integrate test. [@kaikai1024] +- [Optimization] Add quota unit test in travisCI. [@ouwenkg] + +### Scripts + +- [Fix] Node path should not consider bin path. [@rainchen] +- [Refactor] Refactor the `cita.sh` script. [@kaikai1024] +- [Fix] Fix amend help info and latest version. [@leeyr338] +- [Optimization] Rename `config_example` to `default_config`. [@kaikai1024] + +### Doc + +- [Doc] Add file naming style doc. [@kaikai1024] +- [Doc] New CITA contents structure of CITAHub-Docs. [@kaikai1024] [@zhouyun-zoe] [@ouwenkg] [@leeyr338] [@wuyuyue] +- [Doc] Add wiki about RocksDB. [@leeyr338] +- [Doc] Update the description about `getTransactionCount`. [@ouwenkg] + ## [v0.24.1] - 2019-06-14 Fix the issue about memory leak in cita-executor. @@ -854,6 +896,7 @@ Release the first version of CITA. [@leeyr338]: https://github.com/leeyr338 [@luqz]: https://github.com/luqz [@ouwenkg]: https://github.com/ouwenkg +[@rainchen]: https://github.com/rainchen [@rev-chaos]: https://github.com/rev-chaos [@rink1969]: https://github.com/rink1969 [@u2]: https://github.com/u2 diff --git a/Cargo.lock b/Cargo.lock index 9db567f23..26dc596ca 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -86,7 +86,7 @@ name = "ansi_term" version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -112,6 +112,16 @@ dependencies = [ "nodrop 0.1.12 (registry+https://github.com/rust-lang/crates.io-index)", ] +[[package]] +name = "attohttpc" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "http 0.1.17 (registry+https://github.com/rust-lang/crates.io-index)", + "log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)", + "url 1.7.1 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "atty" version = "0.2.11" @@ -119,13 +129,13 @@ source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "libc 0.2.46 (registry+https://github.com/rust-lang/crates.io-index)", "termion 1.5.1 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "authority_manage" version = "0.1.0" -source = "git+https://github.com/cryptape/cita-common.git?branch=develop#73402b55138919f85b50b066f2e5c1f8b32e6b3c" +source = "git+https://github.com/cryptape/cita-common.git?branch=develop#b948764c71c656943506317505868bbde95bc3f3" dependencies = [ "bincode 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)", "cita-types 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", @@ -159,7 +169,7 @@ dependencies = [ "cfg-if 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)", "libc 0.2.46 (registry+https://github.com/rust-lang/crates.io-index)", "rustc-demangle 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -212,7 +222,7 @@ dependencies = [ "cexpr 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)", "cfg-if 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)", "clang-sys 0.23.0 (registry+https://github.com/rust-lang/crates.io-index)", - "clap 2.32.0 (registry+https://github.com/rust-lang/crates.io-index)", + "clap 2.33.0 (registry+https://github.com/rust-lang/crates.io-index)", "env_logger 0.5.13 (registry+https://github.com/rust-lang/crates.io-index)", "lazy_static 1.3.0 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)", @@ -260,7 +270,7 @@ dependencies = [ [[package]] name = "blake2b" version = "0.1.0" -source = "git+https://github.com/cryptape/cita-common.git?branch=develop#73402b55138919f85b50b066f2e5c1f8b32e6b3c" +source = "git+https://github.com/cryptape/cita-common.git?branch=develop#b948764c71c656943506317505868bbde95bc3f3" dependencies = [ "cc 1.0.26 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -310,17 +320,17 @@ dependencies = [ ] [[package]] -name = "box_executor" +name = "box-executor" version = "0.1.0" dependencies = [ "bincode 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)", "cita-crypto 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", + "cita-logger 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", "cita-types 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", - "clap 2.32.0 (registry+https://github.com/rust-lang/crates.io-index)", + "clap 2.33.0 (registry+https://github.com/rust-lang/crates.io-index)", "dotenv 0.13.0 (registry+https://github.com/rust-lang/crates.io-index)", "hashable 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "libproto 0.6.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", - "logger 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "proof 0.6.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "pubsub 0.6.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "rlp 0.2.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", @@ -393,12 +403,12 @@ version = "0.1.0" dependencies = [ "bincode 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)", "cita-crypto 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", + "cita-logger 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", "cita-types 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", - "clap 2.32.0 (registry+https://github.com/rust-lang/crates.io-index)", + "clap 2.33.0 (registry+https://github.com/rust-lang/crates.io-index)", "dotenv 0.13.0 (registry+https://github.com/rust-lang/crates.io-index)", "hashable 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "libproto 0.6.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", - "logger 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "proof 0.6.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "pubsub 0.6.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "rlp 0.2.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", @@ -409,19 +419,19 @@ dependencies = [ ] [[package]] -name = "chain_performance_by_mq" +name = "chain-performance-by-mq" version = "0.1.0" dependencies = [ "bincode 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)", "cita-crypto 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", + "cita-logger 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", "cita-types 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", - "clap 2.32.0 (registry+https://github.com/rust-lang/crates.io-index)", + "clap 2.33.0 (registry+https://github.com/rust-lang/crates.io-index)", "common-types 0.1.0", "cpuprofiler 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)", "dotenv 0.13.0 (registry+https://github.com/rust-lang/crates.io-index)", "hashable 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "libproto 0.6.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", - "logger 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "proof 0.6.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "pubsub 0.6.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "rustc-serialize 0.3.24 (registry+https://github.com/rust-lang/crates.io-index)", @@ -445,8 +455,9 @@ version = "0.1.0" dependencies = [ "cita-crypto 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "cita-directories 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", + "cita-logger 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", "cita-types 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", - "clap 2.32.0 (registry+https://github.com/rust-lang/crates.io-index)", + "clap 2.33.0 (registry+https://github.com/rust-lang/crates.io-index)", "core 0.1.0", "cpuprofiler 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)", "db 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", @@ -455,14 +466,13 @@ dependencies = [ "hashable 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "jsonrpc-types 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "libproto 0.6.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", - "logger 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "lru 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)", "pubsub 0.6.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "quickcheck 0.7.2 (registry+https://github.com/rust-lang/crates.io-index)", "rayon 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.89 (registry+https://github.com/rust-lang/crates.io-index)", "serde_derive 1.0.89 (registry+https://github.com/rust-lang/crates.io-index)", - "serde_json 1.0.32 (registry+https://github.com/rust-lang/crates.io-index)", + "serde_json 1.0.39 (registry+https://github.com/rust-lang/crates.io-index)", "tempdir 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", "tempfile 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "tx_pool 0.6.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", @@ -478,14 +488,14 @@ dependencies = [ "bincode 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)", "cita-crypto 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "cita-directories 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", + "cita-logger 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", "cita-types 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", - "clap 2.32.0 (registry+https://github.com/rust-lang/crates.io-index)", + "clap 2.33.0 (registry+https://github.com/rust-lang/crates.io-index)", "cpuprofiler 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)", "dotenv 0.13.0 (registry+https://github.com/rust-lang/crates.io-index)", "engine 0.6.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "hashable 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "libproto 0.6.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", - "logger 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "lru-cache 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", "min-max-heap 1.2.2 (registry+https://github.com/rust-lang/crates.io-index)", "ntp 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", @@ -504,8 +514,9 @@ version = "0.6.0" dependencies = [ "byteorder 1.3.1 (registry+https://github.com/rust-lang/crates.io-index)", "cita-directories 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", + "cita-logger 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", "cita-types 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", - "clap 2.32.0 (registry+https://github.com/rust-lang/crates.io-index)", + "clap 2.33.0 (registry+https://github.com/rust-lang/crates.io-index)", "common-types 0.1.0", "core 0.1.0", "db 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", @@ -513,17 +524,16 @@ dependencies = [ "error 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "jsonrpc-types 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "libproto 0.6.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", - "logger 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "proof 0.6.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "pubsub 0.6.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", - "serde_json 1.0.32 (registry+https://github.com/rust-lang/crates.io-index)", + "serde_json 1.0.39 (registry+https://github.com/rust-lang/crates.io-index)", "util 0.6.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", ] [[package]] name = "cita-crypto" version = "0.1.0" -source = "git+https://github.com/cryptape/cita-common.git?branch=develop#73402b55138919f85b50b066f2e5c1f8b32e6b3c" +source = "git+https://github.com/cryptape/cita-common.git?branch=develop#b948764c71c656943506317505868bbde95bc3f3" dependencies = [ "cita-crypto-trait 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "cita-ed25519 0.6.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", @@ -534,7 +544,7 @@ dependencies = [ [[package]] name = "cita-crypto-trait" version = "0.1.0" -source = "git+https://github.com/cryptape/cita-common.git?branch=develop#73402b55138919f85b50b066f2e5c1f8b32e6b3c" +source = "git+https://github.com/cryptape/cita-common.git?branch=develop#b948764c71c656943506317505868bbde95bc3f3" dependencies = [ "cita-types 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", ] @@ -542,7 +552,7 @@ dependencies = [ [[package]] name = "cita-directories" version = "0.1.0" -source = "git+https://github.com/cryptape/cita-common.git?branch=develop#73402b55138919f85b50b066f2e5c1f8b32e6b3c" +source = "git+https://github.com/cryptape/cita-common.git?branch=develop#b948764c71c656943506317505868bbde95bc3f3" dependencies = [ "uuid 0.7.1 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -550,7 +560,7 @@ dependencies = [ [[package]] name = "cita-ed25519" version = "0.6.0" -source = "git+https://github.com/cryptape/cita-common.git?branch=develop#73402b55138919f85b50b066f2e5c1f8b32e6b3c" +source = "git+https://github.com/cryptape/cita-common.git?branch=develop#b948764c71c656943506317505868bbde95bc3f3" dependencies = [ "bincode 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)", "cita-crypto-trait 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", @@ -570,8 +580,9 @@ dependencies = [ "cita-crypto 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "cita-directories 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "cita-ed25519 0.6.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", + "cita-logger 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", "cita-types 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", - "clap 2.32.0 (registry+https://github.com/rust-lang/crates.io-index)", + "clap 2.33.0 (registry+https://github.com/rust-lang/crates.io-index)", "common-types 0.1.0", "core-executor 0.1.0", "crossbeam-channel 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)", @@ -583,12 +594,11 @@ dependencies = [ "hashable 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "jsonrpc-types 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "libproto 0.6.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", - "logger 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "proof 0.6.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "pubsub 0.6.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "serde 1.0.89 (registry+https://github.com/rust-lang/crates.io-index)", "serde_derive 1.0.89 (registry+https://github.com/rust-lang/crates.io-index)", - "serde_json 1.0.32 (registry+https://github.com/rust-lang/crates.io-index)", + "serde_json 1.0.39 (registry+https://github.com/rust-lang/crates.io-index)", "tempdir 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", "util 0.6.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", ] @@ -597,9 +607,9 @@ dependencies = [ name = "cita-forever" version = "0.1.0" dependencies = [ - "clap 2.32.0 (registry+https://github.com/rust-lang/crates.io-index)", + "cita-logger 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "clap 2.33.0 (registry+https://github.com/rust-lang/crates.io-index)", "crossbeam-channel 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)", - "logger 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "serde 1.0.89 (registry+https://github.com/rust-lang/crates.io-index)", "serde_derive 1.0.89 (registry+https://github.com/rust-lang/crates.io-index)", "util 0.6.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", @@ -610,25 +620,25 @@ name = "cita-jsonrpc" version = "0.1.0" dependencies = [ "bytes 0.4.12 (registry+https://github.com/rust-lang/crates.io-index)", - "clap 2.32.0 (registry+https://github.com/rust-lang/crates.io-index)", + "cita-logger 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "clap 2.33.0 (registry+https://github.com/rust-lang/crates.io-index)", "cpuprofiler 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)", "dotenv 0.13.0 (registry+https://github.com/rust-lang/crates.io-index)", "error 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "futures 0.1.25 (registry+https://github.com/rust-lang/crates.io-index)", - "http 0.1.13 (registry+https://github.com/rust-lang/crates.io-index)", + "http 0.1.17 (registry+https://github.com/rust-lang/crates.io-index)", "httparse 1.3.3 (registry+https://github.com/rust-lang/crates.io-index)", "hyper 0.12.16 (registry+https://github.com/rust-lang/crates.io-index)", "jsonrpc-proto 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "jsonrpc-types 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "libc 0.2.46 (registry+https://github.com/rust-lang/crates.io-index)", "libproto 0.6.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", - "logger 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "net2 0.2.33 (registry+https://github.com/rust-lang/crates.io-index)", "num_cpus 1.8.0 (registry+https://github.com/rust-lang/crates.io-index)", "pubsub 0.6.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "serde 1.0.89 (registry+https://github.com/rust-lang/crates.io-index)", "serde_derive 1.0.89 (registry+https://github.com/rust-lang/crates.io-index)", - "serde_json 1.0.32 (registry+https://github.com/rust-lang/crates.io-index)", + "serde_json 1.0.39 (registry+https://github.com/rust-lang/crates.io-index)", "threadpool 1.7.1 (registry+https://github.com/rust-lang/crates.io-index)", "time 0.1.40 (registry+https://github.com/rust-lang/crates.io-index)", "tokio 0.1.16 (registry+https://github.com/rust-lang/crates.io-index)", @@ -642,10 +652,23 @@ dependencies = [ "ws 0.7.9 (registry+https://github.com/rust-lang/crates.io-index)", ] +[[package]] +name = "cita-logger" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "chrono 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)", + "crossbeam-channel 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.46 (registry+https://github.com/rust-lang/crates.io-index)", + "log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)", + "log4rs 0.8.1 (registry+https://github.com/rust-lang/crates.io-index)", + "signal-hook 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "cita-merklehash" version = "0.1.0" -source = "git+https://github.com/cryptape/cita-common.git?branch=develop#73402b55138919f85b50b066f2e5c1f8b32e6b3c" +source = "git+https://github.com/cryptape/cita-common.git?branch=develop#b948764c71c656943506317505868bbde95bc3f3" dependencies = [ "cita-types 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "hashable 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", @@ -660,22 +683,22 @@ version = "0.6.0" dependencies = [ "byteorder 1.3.1 (registry+https://github.com/rust-lang/crates.io-index)", "bytes 0.4.12 (registry+https://github.com/rust-lang/crates.io-index)", + "cita-logger 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", "cita-types 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", - "clap 2.32.0 (registry+https://github.com/rust-lang/crates.io-index)", + "clap 2.33.0 (registry+https://github.com/rust-lang/crates.io-index)", "dotenv 0.13.0 (registry+https://github.com/rust-lang/crates.io-index)", "fnv 1.0.6 (registry+https://github.com/rust-lang/crates.io-index)", "futures 0.1.25 (registry+https://github.com/rust-lang/crates.io-index)", "jsonrpc-types 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "libproto 0.6.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", - "logger 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "notify 4.0.10 (registry+https://github.com/rust-lang/crates.io-index)", "pubsub 0.6.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "rand 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.89 (registry+https://github.com/rust-lang/crates.io-index)", "serde_derive 1.0.89 (registry+https://github.com/rust-lang/crates.io-index)", - "serde_json 1.0.32 (registry+https://github.com/rust-lang/crates.io-index)", + "serde_json 1.0.39 (registry+https://github.com/rust-lang/crates.io-index)", "tempfile 3.0.7 (registry+https://github.com/rust-lang/crates.io-index)", - "tentacle 0.2.0-alpha.14 (registry+https://github.com/rust-lang/crates.io-index)", + "tentacle 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", "tentacle-discovery 0.2.4 (registry+https://github.com/rust-lang/crates.io-index)", "tokio 0.1.16 (registry+https://github.com/rust-lang/crates.io-index)", "util 0.6.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", @@ -686,26 +709,26 @@ name = "cita-relayer-parser" version = "0.1.0" dependencies = [ "cita-crypto 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", + "cita-logger 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", "cita-types 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", - "clap 2.32.0 (registry+https://github.com/rust-lang/crates.io-index)", + "clap 2.33.0 (registry+https://github.com/rust-lang/crates.io-index)", "core 0.1.0", "ethabi 4.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "futures 0.1.25 (registry+https://github.com/rust-lang/crates.io-index)", "hyper 0.11.22 (git+https://github.com/cryptape/hyper.git?branch=reuse_port)", "jsonrpc-types 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "libproto 0.6.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", - "logger 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "parking_lot 0.6.4 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.89 (registry+https://github.com/rust-lang/crates.io-index)", "serde_derive 1.0.89 (registry+https://github.com/rust-lang/crates.io-index)", - "serde_json 1.0.32 (registry+https://github.com/rust-lang/crates.io-index)", + "serde_json 1.0.39 (registry+https://github.com/rust-lang/crates.io-index)", "tokio-core 0.1.17 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "cita-secp256k1" version = "0.6.0" -source = "git+https://github.com/cryptape/cita-common.git?branch=develop#73402b55138919f85b50b066f2e5c1f8b32e6b3c" +source = "git+https://github.com/cryptape/cita-common.git?branch=develop#b948764c71c656943506317505868bbde95bc3f3" dependencies = [ "bincode 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)", "cita-crypto-trait 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", @@ -722,7 +745,7 @@ dependencies = [ [[package]] name = "cita-sm2" version = "0.1.0" -source = "git+https://github.com/cryptape/cita-common.git?branch=develop#73402b55138919f85b50b066f2e5c1f8b32e6b3c" +source = "git+https://github.com/cryptape/cita-common.git?branch=develop#b948764c71c656943506317505868bbde95bc3f3" dependencies = [ "cita-crypto-trait 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "cita-types 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", @@ -736,7 +759,7 @@ dependencies = [ [[package]] name = "cita-types" version = "0.1.0" -source = "git+https://github.com/cryptape/cita-common.git?branch=develop#73402b55138919f85b50b066f2e5c1f8b32e6b3c" +source = "git+https://github.com/cryptape/cita-common.git?branch=develop#b948764c71c656943506317505868bbde95bc3f3" dependencies = [ "ethereum-types 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)", "plain_hasher 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", @@ -754,14 +777,14 @@ dependencies = [ [[package]] name = "clap" -version = "2.32.0" +version = "2.33.0" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "ansi_term 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)", "atty 0.2.11 (registry+https://github.com/rust-lang/crates.io-index)", "bitflags 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)", - "strsim 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)", - "textwrap 0.10.0 (registry+https://github.com/rust-lang/crates.io-index)", + "strsim 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)", + "textwrap 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)", "unicode-width 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)", "vec_map 0.8.1 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -788,13 +811,13 @@ version = "0.1.0" dependencies = [ "bloomchain 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "cita-crypto 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", + "cita-logger 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", "cita-types 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "db 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "hashable 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "jsonrpc-types 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "lazy_static 0.2.11 (registry+https://github.com/rust-lang/crates.io-index)", "libproto 0.6.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", - "logger 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "proof 0.6.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "rlp 0.2.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "rlp_derive 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", @@ -811,11 +834,11 @@ dependencies = [ "bincode 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)", "chrono 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)", "cita-crypto 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", + "cita-logger 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", "cita-types 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", - "clap 2.32.0 (registry+https://github.com/rust-lang/crates.io-index)", + "clap 2.33.0 (registry+https://github.com/rust-lang/crates.io-index)", "hashable 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "libproto 0.6.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", - "logger 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "proof 0.6.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "pubsub 0.6.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "serde 1.0.89 (registry+https://github.com/rust-lang/crates.io-index)", @@ -844,6 +867,7 @@ dependencies = [ "byteorder 1.3.1 (registry+https://github.com/rust-lang/crates.io-index)", "cita-crypto 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "cita-ed25519 0.6.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", + "cita-logger 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", "cita-merklehash 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "cita-secp256k1 0.6.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "cita-types 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", @@ -855,7 +879,6 @@ dependencies = [ "jsonrpc-types 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "lazy_static 0.2.11 (registry+https://github.com/rust-lang/crates.io-index)", "libproto 0.6.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", - "logger 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "lru-cache 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", "proof 0.6.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "pubsub 0.6.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", @@ -882,6 +905,7 @@ dependencies = [ "cita-crypto 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "cita-crypto-trait 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "cita-ed25519 0.6.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", + "cita-logger 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", "cita-merklehash 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "cita-secp256k1 0.6.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "cita-types 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", @@ -897,11 +921,11 @@ dependencies = [ "evm 0.1.0", "grpc 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)", "hashable 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", + "hex 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)", "jsonrpc-types 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "largest-remainder-method 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", "lazy_static 0.2.11 (registry+https://github.com/rust-lang/crates.io-index)", "libproto 0.6.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", - "logger 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "lru-cache 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", "num 0.1.42 (registry+https://github.com/rust-lang/crates.io-index)", "proof 0.6.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", @@ -913,7 +937,7 @@ dependencies = [ "rustc-serialize 0.3.24 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.89 (registry+https://github.com/rust-lang/crates.io-index)", "serde_derive 1.0.89 (registry+https://github.com/rust-lang/crates.io-index)", - "serde_json 1.0.32 (registry+https://github.com/rust-lang/crates.io-index)", + "serde_json 1.0.39 (registry+https://github.com/rust-lang/crates.io-index)", "snappy 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "tempdir 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", "time 0.1.40 (registry+https://github.com/rust-lang/crates.io-index)", @@ -940,7 +964,26 @@ dependencies = [ ] [[package]] -name = "create_key_addr" +name = "create-genesis" +version = "0.1.0" +dependencies = [ + "clap 2.33.0 (registry+https://github.com/rust-lang/crates.io-index)", + "core-executor 0.1.0", + "ethabi 7.0.0 (registry+https://github.com/rust-lang/crates.io-index)", + "ethereum-types 0.5.2 (registry+https://github.com/rust-lang/crates.io-index)", + "evm 0.1.0", + "hex 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)", + "json 0.11.14 (registry+https://github.com/rust-lang/crates.io-index)", + "libproto 0.6.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", + "libsecp256k1 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)", + "serde 1.0.89 (registry+https://github.com/rust-lang/crates.io-index)", + "serde_json 1.0.39 (registry+https://github.com/rust-lang/crates.io-index)", + "serde_yaml 0.8.6 (registry+https://github.com/rust-lang/crates.io-index)", + "tiny-keccak 1.4.2 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "create-key-addr" version = "0.1.0" dependencies = [ "cita-crypto 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", @@ -1063,6 +1106,11 @@ name = "crunchy" version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" +[[package]] +name = "crunchy" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" + [[package]] name = "crypto-mac" version = "0.4.0" @@ -1101,7 +1149,7 @@ dependencies = [ "openssl-sys 0.9.39 (registry+https://github.com/rust-lang/crates.io-index)", "pkg-config 0.3.14 (registry+https://github.com/rust-lang/crates.io-index)", "vcpkg 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -1117,14 +1165,14 @@ source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "db" version = "0.1.0" -source = "git+https://github.com/cryptape/cita-common.git?branch=develop#73402b55138919f85b50b066f2e5c1f8b32e6b3c" +source = "git+https://github.com/cryptape/cita-common.git?branch=develop#b948764c71c656943506317505868bbde95bc3f3" dependencies = [ + "cita-logger 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", "cita-types 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "elastic-array 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)", "hashable 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "heapsize 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)", "itertools 0.5.10 (registry+https://github.com/rust-lang/crates.io-index)", - "logger 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "parity-rocksdb 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)", "regex 1.0.5 (registry+https://github.com/rust-lang/crates.io-index)", "rlp 0.2.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", @@ -1187,7 +1235,7 @@ dependencies = [ [[package]] name = "engine" version = "0.6.0" -source = "git+https://github.com/cryptape/cita-common.git?branch=develop#73402b55138919f85b50b066f2e5c1f8b32e6b3c" +source = "git+https://github.com/cryptape/cita-common.git?branch=develop#b948764c71c656943506317505868bbde95bc3f3" dependencies = [ "cita-crypto 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "cita-types 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", @@ -1250,7 +1298,7 @@ dependencies = [ [[package]] name = "error" version = "0.1.0" -source = "git+https://github.com/cryptape/cita-common.git?branch=develop#73402b55138919f85b50b066f2e5c1f8b32e6b3c" +source = "git+https://github.com/cryptape/cita-common.git?branch=develop#b948764c71c656943506317505868bbde95bc3f3" [[package]] name = "error-chain" @@ -1273,6 +1321,14 @@ name = "error-chain" version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" +[[package]] +name = "error-chain" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "version_check 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "ethabi" version = "4.2.0" @@ -1282,7 +1338,21 @@ dependencies = [ "rustc-hex 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.89 (registry+https://github.com/rust-lang/crates.io-index)", "serde_derive 1.0.89 (registry+https://github.com/rust-lang/crates.io-index)", - "serde_json 1.0.32 (registry+https://github.com/rust-lang/crates.io-index)", + "serde_json 1.0.39 (registry+https://github.com/rust-lang/crates.io-index)", + "tiny-keccak 1.4.2 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "ethabi" +version = "7.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "error-chain 0.12.1 (registry+https://github.com/rust-lang/crates.io-index)", + "ethereum-types 0.5.2 (registry+https://github.com/rust-lang/crates.io-index)", + "rustc-hex 2.0.1 (registry+https://github.com/rust-lang/crates.io-index)", + "serde 1.0.89 (registry+https://github.com/rust-lang/crates.io-index)", + "serde_derive 1.0.89 (registry+https://github.com/rust-lang/crates.io-index)", + "serde_json 1.0.39 (registry+https://github.com/rust-lang/crates.io-index)", "tiny-keccak 1.4.2 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -1308,10 +1378,22 @@ dependencies = [ "tiny-keccak 1.4.2 (registry+https://github.com/rust-lang/crates.io-index)", ] +[[package]] +name = "ethbloom" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "crunchy 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)", + "fixed-hash 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)", + "impl-rlp 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", + "impl-serde 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", + "tiny-keccak 1.4.2 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "ethcore-bloom-journal" version = "0.1.0" -source = "git+https://github.com/cryptape/cita-common.git?branch=develop#73402b55138919f85b50b066f2e5c1f8b32e6b3c" +source = "git+https://github.com/cryptape/cita-common.git?branch=develop#b948764c71c656943506317505868bbde95bc3f3" dependencies = [ "siphasher 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -1343,6 +1425,19 @@ dependencies = [ "uint 0.4.1 (registry+https://github.com/rust-lang/crates.io-index)", ] +[[package]] +name = "ethereum-types" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "crunchy 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)", + "ethbloom 0.6.4 (registry+https://github.com/rust-lang/crates.io-index)", + "ethereum-types-serialize 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)", + "fixed-hash 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)", + "serde 1.0.89 (registry+https://github.com/rust-lang/crates.io-index)", + "uint 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "ethereum-types-serialize" version = "0.2.2" @@ -1356,12 +1451,12 @@ name = "evm" version = "0.1.0" dependencies = [ "bit-set 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", + "cita-logger 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", "cita-types 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "common-types 0.1.0", "db 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "hashable 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "lazy_static 0.2.11 (registry+https://github.com/rust-lang/crates.io-index)", - "logger 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "rlp 0.2.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "rustc-hex 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", "util 0.6.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", @@ -1413,6 +1508,18 @@ dependencies = [ "rustc-hex 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", ] +[[package]] +name = "fixed-hash" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "byteorder 1.3.1 (registry+https://github.com/rust-lang/crates.io-index)", + "heapsize 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)", + "rand 0.5.5 (registry+https://github.com/rust-lang/crates.io-index)", + "rustc-hex 2.0.1 (registry+https://github.com/rust-lang/crates.io-index)", + "static_assertions 0.2.5 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "flatbuffers" version = "0.6.0" @@ -1450,7 +1557,7 @@ version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "libc 0.2.46 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -1564,7 +1671,7 @@ dependencies = [ "futures-cpupool 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)", "httpbis 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)", - "protobuf 2.1.1 (registry+https://github.com/rust-lang/crates.io-index)", + "protobuf 2.6.2 (registry+https://github.com/rust-lang/crates.io-index)", "tls-api 0.1.20 (registry+https://github.com/rust-lang/crates.io-index)", "tls-api-stub 0.1.20 (registry+https://github.com/rust-lang/crates.io-index)", "tokio-core 0.1.17 (registry+https://github.com/rust-lang/crates.io-index)", @@ -1581,7 +1688,7 @@ dependencies = [ "bytes 0.4.12 (registry+https://github.com/rust-lang/crates.io-index)", "fnv 1.0.6 (registry+https://github.com/rust-lang/crates.io-index)", "futures 0.1.25 (registry+https://github.com/rust-lang/crates.io-index)", - "http 0.1.13 (registry+https://github.com/rust-lang/crates.io-index)", + "http 0.1.17 (registry+https://github.com/rust-lang/crates.io-index)", "indexmap 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)", "slab 0.4.1 (registry+https://github.com/rust-lang/crates.io-index)", @@ -1592,7 +1699,7 @@ dependencies = [ [[package]] name = "hashable" version = "0.1.0" -source = "git+https://github.com/cryptape/cita-common.git?branch=develop#73402b55138919f85b50b066f2e5c1f8b32e6b3c" +source = "git+https://github.com/cryptape/cita-common.git?branch=develop#b948764c71c656943506317505868bbde95bc3f3" dependencies = [ "blake2b 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "cita-types 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", @@ -1605,7 +1712,7 @@ name = "heapsize" version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -1644,7 +1751,7 @@ dependencies = [ [[package]] name = "http" -version = "0.1.13" +version = "0.1.17" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "bytes 0.4.12 (registry+https://github.com/rust-lang/crates.io-index)", @@ -1719,7 +1826,7 @@ dependencies = [ "futures 0.1.25 (registry+https://github.com/rust-lang/crates.io-index)", "futures-cpupool 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)", "h2 0.1.14 (registry+https://github.com/rust-lang/crates.io-index)", - "http 0.1.13 (registry+https://github.com/rust-lang/crates.io-index)", + "http 0.1.17 (registry+https://github.com/rust-lang/crates.io-index)", "httparse 1.3.3 (registry+https://github.com/rust-lang/crates.io-index)", "iovec 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", "itoa 0.4.3 (registry+https://github.com/rust-lang/crates.io-index)", @@ -1746,6 +1853,36 @@ dependencies = [ "unicode-normalization 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)", ] +[[package]] +name = "igd" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "attohttpc 0.4.1 (registry+https://github.com/rust-lang/crates.io-index)", + "bytes 0.4.12 (registry+https://github.com/rust-lang/crates.io-index)", + "http 0.1.17 (registry+https://github.com/rust-lang/crates.io-index)", + "log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)", + "rand 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)", + "url 1.7.1 (registry+https://github.com/rust-lang/crates.io-index)", + "xmltree 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "impl-rlp" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "rlp 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "impl-serde" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "serde 1.0.89 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "indexmap" version = "1.0.2" @@ -1791,27 +1928,32 @@ name = "itoa" version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" +[[package]] +name = "json" +version = "0.11.14" +source = "registry+https://github.com/rust-lang/crates.io-index" + [[package]] name = "jsonrpc-proto" version = "0.1.0" -source = "git+https://github.com/cryptape/cita-common.git?branch=develop#73402b55138919f85b50b066f2e5c1f8b32e6b3c" +source = "git+https://github.com/cryptape/cita-common.git?branch=develop#b948764c71c656943506317505868bbde95bc3f3" dependencies = [ "bincode 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)", + "cita-logger 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", "cita-types 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "jsonrpc-types 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "libproto 0.6.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", - "logger 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "proof 0.6.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "rustc-serialize 0.3.24 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.89 (registry+https://github.com/rust-lang/crates.io-index)", - "serde_json 1.0.32 (registry+https://github.com/rust-lang/crates.io-index)", + "serde_json 1.0.39 (registry+https://github.com/rust-lang/crates.io-index)", "uuid 0.7.1 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "jsonrpc-types" version = "0.1.0" -source = "git+https://github.com/cryptape/cita-common.git?branch=develop#73402b55138919f85b50b066f2e5c1f8b32e6b3c" +source = "git+https://github.com/cryptape/cita-common.git?branch=develop#b948764c71c656943506317505868bbde95bc3f3" dependencies = [ "bincode 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)", "cita-types 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", @@ -1819,13 +1961,13 @@ dependencies = [ "rustc-serialize 0.3.24 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.89 (registry+https://github.com/rust-lang/crates.io-index)", "serde_derive 1.0.89 (registry+https://github.com/rust-lang/crates.io-index)", - "serde_json 1.0.32 (registry+https://github.com/rust-lang/crates.io-index)", + "serde_json 1.0.39 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "jsonrpc-types-internals" version = "0.1.0" -source = "git+https://github.com/cryptape/cita-common.git?branch=develop#73402b55138919f85b50b066f2e5c1f8b32e6b3c" +source = "git+https://github.com/cryptape/cita-common.git?branch=develop#b948764c71c656943506317505868bbde95bc3f3" dependencies = [ "proc-macro2 0.4.20 (registry+https://github.com/rust-lang/crates.io-index)", "quote 0.6.8 (registry+https://github.com/rust-lang/crates.io-index)", @@ -1901,21 +2043,21 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "cc 1.0.26 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "libproto" version = "0.6.0" -source = "git+https://github.com/cryptape/cita-common.git?branch=develop#73402b55138919f85b50b066f2e5c1f8b32e6b3c" +source = "git+https://github.com/cryptape/cita-common.git?branch=develop#b948764c71c656943506317505868bbde95bc3f3" dependencies = [ "cita-crypto 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", + "cita-logger 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", "cita-merklehash 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "cita-types 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "grpc 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)", "hashable 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", - "logger 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", - "protobuf 2.1.1 (registry+https://github.com/rust-lang/crates.io-index)", + "protobuf 2.6.2 (registry+https://github.com/rust-lang/crates.io-index)", "rlp 0.2.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "rustc-serialize 0.3.24 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.89 (registry+https://github.com/rust-lang/crates.io-index)", @@ -2053,24 +2195,11 @@ dependencies = [ "serde 1.0.89 (registry+https://github.com/rust-lang/crates.io-index)", "serde-value 0.5.2 (registry+https://github.com/rust-lang/crates.io-index)", "serde_derive 1.0.89 (registry+https://github.com/rust-lang/crates.io-index)", - "serde_json 1.0.32 (registry+https://github.com/rust-lang/crates.io-index)", + "serde_json 1.0.39 (registry+https://github.com/rust-lang/crates.io-index)", "serde_yaml 0.8.6 (registry+https://github.com/rust-lang/crates.io-index)", "thread-id 3.3.0 (registry+https://github.com/rust-lang/crates.io-index)", "typemap 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "logger" -version = "0.1.0" -source = "git+https://github.com/cryptape/cita-common.git?branch=develop#73402b55138919f85b50b066f2e5c1f8b32e6b3c" -dependencies = [ - "chrono 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)", - "crossbeam-channel 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)", - "libc 0.2.46 (registry+https://github.com/rust-lang/crates.io-index)", - "log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)", - "log4rs 0.8.1 (registry+https://github.com/rust-lang/crates.io-index)", - "signal-hook 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -2239,7 +2368,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "cfg-if 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)", "libc 0.2.46 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -2270,7 +2399,7 @@ dependencies = [ "mio 0.6.16 (registry+https://github.com/rust-lang/crates.io-index)", "mio-extras 2.0.5 (registry+https://github.com/rust-lang/crates.io-index)", "walkdir 2.2.7 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -2426,10 +2555,10 @@ dependencies = [ [[package]] name = "panic_hook" version = "0.0.1" -source = "git+https://github.com/cryptape/cita-common.git?branch=develop#73402b55138919f85b50b066f2e5c1f8b32e6b3c" +source = "git+https://github.com/cryptape/cita-common.git?branch=develop#b948764c71c656943506317505868bbde95bc3f3" dependencies = [ "backtrace 0.3.9 (registry+https://github.com/rust-lang/crates.io-index)", - "logger 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", + "cita-logger 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -2508,7 +2637,7 @@ dependencies = [ "rand 0.5.5 (registry+https://github.com/rust-lang/crates.io-index)", "rustc_version 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)", "smallvec 0.6.5 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -2553,7 +2682,7 @@ dependencies = [ [[package]] name = "proof" version = "0.6.0" -source = "git+https://github.com/cryptape/cita-common.git?branch=develop#73402b55138919f85b50b066f2e5c1f8b32e6b3c" +source = "git+https://github.com/cryptape/cita-common.git?branch=develop#b948764c71c656943506317505868bbde95bc3f3" dependencies = [ "bincode 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)", "cita-crypto 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", @@ -2567,7 +2696,7 @@ dependencies = [ [[package]] name = "protobuf" -version = "2.1.1" +version = "2.6.2" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "bytes 0.4.12 (registry+https://github.com/rust-lang/crates.io-index)", @@ -2576,7 +2705,7 @@ dependencies = [ [[package]] name = "pubsub" version = "0.6.0" -source = "git+https://github.com/cryptape/cita-common.git?branch=develop#73402b55138919f85b50b066f2e5c1f8b32e6b3c" +source = "git+https://github.com/cryptape/cita-common.git?branch=develop#b948764c71c656943506317505868bbde95bc3f3" dependencies = [ "dotenv 0.13.0 (registry+https://github.com/rust-lang/crates.io-index)", "pubsub_kafka 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", @@ -2587,19 +2716,19 @@ dependencies = [ [[package]] name = "pubsub_kafka" version = "0.1.0" -source = "git+https://github.com/cryptape/cita-common.git?branch=develop#73402b55138919f85b50b066f2e5c1f8b32e6b3c" +source = "git+https://github.com/cryptape/cita-common.git?branch=develop#b948764c71c656943506317505868bbde95bc3f3" dependencies = [ + "cita-logger 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", "crossbeam-channel 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)", "futures 0.1.25 (registry+https://github.com/rust-lang/crates.io-index)", "futures-cpupool 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)", - "logger 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "rdkafka 0.12.0 (git+https://github.com/fede1024/rust-rdkafka.git?rev=84d4062)", ] [[package]] name = "pubsub_rabbitmq" version = "0.1.0" -source = "git+https://github.com/cryptape/cita-common.git?branch=develop#73402b55138919f85b50b066f2e5c1f8b32e6b3c" +source = "git+https://github.com/cryptape/cita-common.git?branch=develop#b948764c71c656943506317505868bbde95bc3f3" dependencies = [ "amqp 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", "crossbeam-channel 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)", @@ -2608,10 +2737,10 @@ dependencies = [ [[package]] name = "pubsub_zeromq" version = "0.1.0" -source = "git+https://github.com/cryptape/cita-common.git?branch=develop#73402b55138919f85b50b066f2e5c1f8b32e6b3c" +source = "git+https://github.com/cryptape/cita-common.git?branch=develop#b948764c71c656943506317505868bbde95bc3f3" dependencies = [ + "cita-logger 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", "crossbeam-channel 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)", - "logger 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "zmq 0.8.2 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -2679,7 +2808,7 @@ dependencies = [ "libc 0.2.46 (registry+https://github.com/rust-lang/crates.io-index)", "rand_core 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", "rdrand 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -2691,7 +2820,7 @@ dependencies = [ "fuchsia-zircon 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)", "libc 0.2.46 (registry+https://github.com/rust-lang/crates.io-index)", "rand_core 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -2709,7 +2838,7 @@ dependencies = [ "rand_os 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", "rand_pcg 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", "rand_xorshift 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -2765,7 +2894,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "libc 0.2.46 (registry+https://github.com/rust-lang/crates.io-index)", "rand_core 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -2778,7 +2907,7 @@ dependencies = [ "libc 0.2.46 (registry+https://github.com/rust-lang/crates.io-index)", "rand_core 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", "rdrand 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -2831,7 +2960,7 @@ dependencies = [ "rdkafka-sys 0.11.0-1 (git+https://github.com/fede1024/rust-rdkafka.git?rev=84d4062)", "serde 1.0.89 (registry+https://github.com/rust-lang/crates.io-index)", "serde_derive 1.0.89 (registry+https://github.com/rust-lang/crates.io-index)", - "serde_json 1.0.32 (registry+https://github.com/rust-lang/crates.io-index)", + "serde_json 1.0.39 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -2916,7 +3045,7 @@ name = "remove_dir_all" version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -2934,7 +3063,7 @@ dependencies = [ [[package]] name = "rlp" version = "0.2.0" -source = "git+https://github.com/cryptape/cita-common.git?branch=develop#73402b55138919f85b50b066f2e5c1f8b32e6b3c" +source = "git+https://github.com/cryptape/cita-common.git?branch=develop#b948764c71c656943506317505868bbde95bc3f3" dependencies = [ "byteorder 1.3.1 (registry+https://github.com/rust-lang/crates.io-index)", "cita-types 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", @@ -2943,10 +3072,19 @@ dependencies = [ "rustc-hex 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", ] +[[package]] +name = "rlp" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "byteorder 1.3.1 (registry+https://github.com/rust-lang/crates.io-index)", + "rustc-hex 2.0.1 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "rlp_derive" version = "0.1.0" -source = "git+https://github.com/cryptape/cita-common.git?branch=develop#73402b55138919f85b50b066f2e5c1f8b32e6b3c" +source = "git+https://github.com/cryptape/cita-common.git?branch=develop#b948764c71c656943506317505868bbde95bc3f3" dependencies = [ "quote 0.3.15 (registry+https://github.com/rust-lang/crates.io-index)", "syn 0.11.11 (registry+https://github.com/rust-lang/crates.io-index)", @@ -3046,6 +3184,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" name = "serde" version = "1.0.89" source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "serde_derive 1.0.89 (registry+https://github.com/rust-lang/crates.io-index)", +] [[package]] name = "serde-value" @@ -3068,7 +3209,7 @@ dependencies = [ [[package]] name = "serde_json" -version = "1.0.32" +version = "1.0.39" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "itoa 0.4.3 (registry+https://github.com/rust-lang/crates.io-index)", @@ -3159,21 +3300,21 @@ dependencies = [ [[package]] name = "snappy" version = "0.1.0" -source = "git+https://github.com/cryptape/cita-common.git?branch=develop#73402b55138919f85b50b066f2e5c1f8b32e6b3c" +source = "git+https://github.com/cryptape/cita-common.git?branch=develop#b948764c71c656943506317505868bbde95bc3f3" dependencies = [ "libc 0.2.46 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] -name = "snapshot_tool" +name = "snapshot-tool" version = "0.2.0" dependencies = [ - "clap 2.32.0 (registry+https://github.com/rust-lang/crates.io-index)", + "cita-logger 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "clap 2.33.0 (registry+https://github.com/rust-lang/crates.io-index)", "dotenv 0.13.0 (registry+https://github.com/rust-lang/crates.io-index)", "error 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "fs2 0.4.3 (registry+https://github.com/rust-lang/crates.io-index)", "libproto 0.6.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", - "logger 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "pubsub 0.6.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "util 0.6.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", ] @@ -3199,7 +3340,7 @@ version = "1.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] -name = "state_test" +name = "state-test" version = "0.1.0" dependencies = [ "core-executor 0.1.0", @@ -3212,10 +3353,15 @@ dependencies = [ "log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.89 (registry+https://github.com/rust-lang/crates.io-index)", "serde_derive 1.0.89 (registry+https://github.com/rust-lang/crates.io-index)", - "serde_json 1.0.32 (registry+https://github.com/rust-lang/crates.io-index)", + "serde_json 1.0.39 (registry+https://github.com/rust-lang/crates.io-index)", "tiny-keccak 1.4.2 (registry+https://github.com/rust-lang/crates.io-index)", ] +[[package]] +name = "static_assertions" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" + [[package]] name = "static_merkle_tree" version = "0.1.1" @@ -3236,7 +3382,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "strsim" -version = "0.7.0" +version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] @@ -3324,24 +3470,27 @@ dependencies = [ "rand 0.6.5 (registry+https://github.com/rust-lang/crates.io-index)", "redox_syscall 0.1.40 (registry+https://github.com/rust-lang/crates.io-index)", "remove_dir_all 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "tentacle" -version = "0.2.0-alpha.14" +version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "bytes 0.4.12 (registry+https://github.com/rust-lang/crates.io-index)", "flatbuffers 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)", "flatbuffers-verifier 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "futures 0.1.25 (registry+https://github.com/rust-lang/crates.io-index)", + "igd 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.46 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)", "parity-multiaddr 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", "tentacle-secio 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)", "tokio 0.1.16 (registry+https://github.com/rust-lang/crates.io-index)", "tokio-threadpool 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)", - "tokio-yamux 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)", + "tokio-yamux 0.1.12 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -3357,7 +3506,7 @@ dependencies = [ "futures 0.1.25 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)", "rand 0.6.5 (registry+https://github.com/rust-lang/crates.io-index)", - "tentacle 0.2.0-alpha.14 (registry+https://github.com/rust-lang/crates.io-index)", + "tentacle 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", "tokio 0.1.16 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -3405,7 +3554,7 @@ dependencies = [ [[package]] name = "textwrap" -version = "0.10.0" +version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "unicode-width 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)", @@ -3427,7 +3576,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "libc 0.2.46 (registry+https://github.com/rust-lang/crates.io-index)", "redox_syscall 0.1.40 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -3461,7 +3610,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "libc 0.2.46 (registry+https://github.com/rust-lang/crates.io-index)", "redox_syscall 0.1.40 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -3732,7 +3881,7 @@ dependencies = [ [[package]] name = "tokio-yamux" -version = "0.1.10" +version = "0.1.12" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "byteorder 1.3.1 (registry+https://github.com/rust-lang/crates.io-index)", @@ -3784,7 +3933,7 @@ dependencies = [ [[package]] name = "tx_pool" version = "0.6.0" -source = "git+https://github.com/cryptape/cita-common.git?branch=develop#73402b55138919f85b50b066f2e5c1f8b32e6b3c" +source = "git+https://github.com/cryptape/cita-common.git?branch=develop#b948764c71c656943506317505868bbde95bc3f3" dependencies = [ "cita-crypto 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", "cita-types 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", @@ -3832,6 +3981,17 @@ dependencies = [ "rustc-hex 2.0.1 (registry+https://github.com/rust-lang/crates.io-index)", ] +[[package]] +name = "uint" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "byteorder 1.3.1 (registry+https://github.com/rust-lang/crates.io-index)", + "crunchy 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)", + "heapsize 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)", + "rustc-hex 2.0.1 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "unicase" version = "2.2.0" @@ -3926,7 +4086,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "util" version = "0.6.0" -source = "git+https://github.com/cryptape/cita-common.git?branch=develop#73402b55138919f85b50b066f2e5c1f8b32e6b3c" +source = "git+https://github.com/cryptape/cita-common.git?branch=develop#b948764c71c656943506317505868bbde95bc3f3" dependencies = [ "ansi_term 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)", "cita-types 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)", @@ -3979,7 +4139,7 @@ version = "2.2.7" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "same-file 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", "winapi-util 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -4008,7 +4168,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "winapi" -version = "0.3.6" +version = "0.3.7" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", @@ -4030,7 +4190,7 @@ name = "winapi-util" version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -4043,7 +4203,7 @@ name = "wincolor" version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", "winapi-util 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -4073,6 +4233,22 @@ dependencies = [ "winapi-build 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", ] +[[package]] +name = "xml-rs" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "bitflags 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "xmltree" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "xml-rs 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "yaml-rust" version = "0.4.2" @@ -4137,6 +4313,7 @@ dependencies = [ "checksum arc-swap 0.3.4 (registry+https://github.com/rust-lang/crates.io-index)" = "af192669a9f44d2fb63c691a04183c8e12428f34041449270b08c0456587f5a5" "checksum arrayref 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)" = "0d382e583f07208808f6b1249e60848879ba3543f57c32277bf52d69c2f0f0ee" "checksum arrayvec 0.4.7 (registry+https://github.com/rust-lang/crates.io-index)" = "a1e964f9e24d588183fcb43503abda40d288c8657dfc27311516ce2f05675aef" +"checksum attohttpc 0.4.1 (registry+https://github.com/rust-lang/crates.io-index)" = "eaf0ec4b0e00f61ee75556ca027485b7b354f4a714d88cc03f4468abd9378c86" "checksum atty 0.2.11 (registry+https://github.com/rust-lang/crates.io-index)" = "9a7d5b8723950951411ee34d271d99dddcc2035a16ab25310ea2c8cfd4369652" "checksum authority_manage 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)" = "" "checksum autocfg 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "a6d640bee2da49f60a4068a7fae53acde8982514ab7bae8b8cea9e88cbcfd799" @@ -4173,12 +4350,13 @@ dependencies = [ "checksum cita-crypto-trait 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)" = "" "checksum cita-directories 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)" = "" "checksum cita-ed25519 0.6.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)" = "" +"checksum cita-logger 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "5c0fccf6b33be6ab71808f2b5bb36206acef2eee9f5d0d29f87b81327242b521" "checksum cita-merklehash 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)" = "" "checksum cita-secp256k1 0.6.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)" = "" "checksum cita-sm2 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)" = "" "checksum cita-types 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)" = "" "checksum clang-sys 0.23.0 (registry+https://github.com/rust-lang/crates.io-index)" = "d7f7c04e52c35222fffcc3a115b5daf5f7e2bfb71c13c4e2321afe1fc71859c2" -"checksum clap 2.32.0 (registry+https://github.com/rust-lang/crates.io-index)" = "b957d88f4b6a63b9d70d5f454ac8011819c6efa7727858f458ab71c756ce2d3e" +"checksum clap 2.33.0 (registry+https://github.com/rust-lang/crates.io-index)" = "5067f5bb2d80ef5d68b4c87db81601f0b75bca627bc2ef76b141d7b846a3c6d9" "checksum cloudabi 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)" = "ddfc5b9aa5d4507acaf872de71051dfd0e309860e88966e1051e462a077aac4f" "checksum cmake 0.1.35 (registry+https://github.com/rust-lang/crates.io-index)" = "6ec65ee4f9c9d16f335091d23693457ed4928657ba4982289d7fafee03bc614a" "checksum constant_time_eq 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)" = "8ff012e225ce166d4422e0e78419d901719760f62ae2b7969ca6b564d1b54a9e" @@ -4198,6 +4376,7 @@ dependencies = [ "checksum crossbeam-utils 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)" = "677d453a17e8bd2b913fa38e8b9cf04bcdbb5be790aa294f2389661d72036015" "checksum crossbeam-utils 0.6.5 (registry+https://github.com/rust-lang/crates.io-index)" = "f8306fcef4a7b563b76b7dd949ca48f52bc1141aa067d2ea09565f3e2652aa5c" "checksum crunchy 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)" = "a2f4a431c5c9f662e1200b7c7f02c34e91361150e382089a8f2dec3ba680cbda" +"checksum crunchy 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "7a81dae078cea95a014a339291cec439d2f232ebe854a9d672b796c6afafa9b7" "checksum crypto-mac 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "779015233ac67d65098614aec748ac1c756ab6677fa2e14cf8b37c08dfed1198" "checksum crypto-mac 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "4434400df11d95d556bac068ddfedd482915eb18fe8bea89bc80b6e4b1c179e5" "checksum ctr 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "044f882973b245404e90c90e7e42e8ee8d7a64edfd7adf83d684fb97e8e2c1b6" @@ -4221,19 +4400,24 @@ dependencies = [ "checksum error 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)" = "" "checksum error-chain 0.10.0 (registry+https://github.com/rust-lang/crates.io-index)" = "d9435d864e017c3c6afeac1654189b06cdb491cf2ff73dbf0d73b0f292f42ff8" "checksum error-chain 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ff511d5dc435d703f4971bc399647c9bc38e20cb41452e3b9feb4765419ed3f3" +"checksum error-chain 0.12.1 (registry+https://github.com/rust-lang/crates.io-index)" = "3ab49e9dcb602294bc42f9a7dfc9bc6e936fca4418ea300dbfb84fe16de0b7d9" "checksum error-chain 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)" = "bd5c82c815138e278b8dcdeffc49f27ea6ffb528403e9dea4194f2e3dd40b143" "checksum ethabi 4.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "0c49de42ee3e3e4734bd847d015e7c55b7855ab978800795c4f032772573d077" +"checksum ethabi 7.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "be9a03ff8f3d495d9b73d59fd166acc91d0fd81779911b0b8b4c87b6024a670a" "checksum ethbloom 0.2.5 (registry+https://github.com/rust-lang/crates.io-index)" = "3d1d93b56bf23b8d38c71e4a5360607fc8e91d402ec20a7e90f4e896cfd21d2b" "checksum ethbloom 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)" = "1a93a43ce2e9f09071449da36bfa7a1b20b950ee344b6904ff23de493b03b386" +"checksum ethbloom 0.6.4 (registry+https://github.com/rust-lang/crates.io-index)" = "3932e82d64d347a045208924002930dc105a138995ccdc1479d0f05f0359f17c" "checksum ethcore-bloom-journal 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)" = "" "checksum ethereum-types 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)" = "9c48729b8aea8aedb12cf4cb2e5cef439fdfe2dda4a89e47eeebd15778ef53b6" "checksum ethereum-types 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)" = "6e742184dc63a01c8ea0637369f8faa27c40f537949908a237f95c05e68d2c96" +"checksum ethereum-types 0.5.2 (registry+https://github.com/rust-lang/crates.io-index)" = "b054df51e53f253837ea422681215b42823c02824bde982699d0dceecf6165a1" "checksum ethereum-types-serialize 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "1873d77b32bc1891a79dad925f2acbc318ee942b38b9110f9dbc5fbeffcea350" "checksum failure 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)" = "795bd83d3abeb9220f257e597aa0080a508b27533824adf336529648f6abf7e2" "checksum failure_derive 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)" = "ea1063915fd7ef4309e222a5a07cf9c319fb9c7836b1f89b85458672dbb127e1" "checksum fake-simd 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "e88a8acf291dafb59c2d96e8f59828f3838bb1a70398823ade51a84de6a6deed" "checksum filetime 0.2.5 (registry+https://github.com/rust-lang/crates.io-index)" = "2f8c63033fcba1f51ef744505b3cad42510432b904c062afa67ad7ece008429d" "checksum fixed-hash 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "0d5ec8112f00ea8a483e04748a85522184418fd1cf02890b626d8fc28683f7de" +"checksum fixed-hash 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)" = "d1a683d1234507e4f3bf2736eeddf0de1dc65996dc0164d57eba0a74bcf29489" "checksum flatbuffers 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)" = "2fc1af59fd8248b59beb048d614a869ce211315c195f5412334e47f5b7e22726" "checksum flatbuffers-verifier 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "fb67f9057183996c00b19cd934f9e79f09aecf7c29e4424cf262288f5a2a84ae" "checksum flate2 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)" = "3b0c7353385f92079524de3b7116cf99d73947c08a7472774e9b3b04bff3b901" @@ -4260,19 +4444,23 @@ dependencies = [ "checksum hmac 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)" = "7a13f4163aa0c5ca1be584aace0e2212b2e41be5478218d4f657f5f778b2ae2a" "checksum hmac 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "f127a908633569f208325f86f71255d3363c79721d7f9fe31cd5569908819771" "checksum hmac-drbg 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "4fe727d41d2eec0a6574d887914347e5ff96a3b87177817e2a9820c5c87fecc2" -"checksum http 0.1.13 (registry+https://github.com/rust-lang/crates.io-index)" = "24f58e8c2d8e886055c3ead7b28793e1455270b5fb39650984c224bc538ba581" +"checksum http 0.1.17 (registry+https://github.com/rust-lang/crates.io-index)" = "eed324f0f0daf6ec10c474f150505af2c143f251722bf9dbd1261bd1f2ee2c1a" "checksum httparse 1.3.3 (registry+https://github.com/rust-lang/crates.io-index)" = "e8734b0cfd3bc3e101ec59100e101c2eecd19282202e87808b3037b442777a83" "checksum httpbis 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "7689cfa896b2a71da4f16206af167542b75d242b6906313e53857972a92d5614" "checksum humantime 1.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "0484fda3e7007f2a4a0d9c3a703ca38c71c54c55602ce4660c419fd32e188c9e" "checksum hyper 0.11.22 (git+https://github.com/cryptape/hyper.git?branch=reuse_port)" = "" "checksum hyper 0.12.16 (registry+https://github.com/rust-lang/crates.io-index)" = "0aeedb8ca5f0f96be00f84073c6d0d5f962ecad020ef543dff99a7c12717a60e" "checksum idna 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)" = "38f09e0f0b1fb55fdee1f17470ad800da77af5186a1a76c026b679358b7e844e" +"checksum igd 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)" = "96f0f346ff76d5143011b2de50fbe72c3e521304868dfbd0d781b4f262a75dd5" +"checksum impl-rlp 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "f39b9963cf5f12fcc4ae4b30a6927ed67d6b4ea4cbe7d17a41131163b401303b" +"checksum impl-serde 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "7d26be4b97d738552ea423f76c4f681012ff06c3fa36fa968656b3679f60b4a1" "checksum indexmap 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)" = "7e81a7c05f79578dbc15793d8b619db9ba32b4577003ef3af1a91c416798c58d" "checksum inotify 0.6.1 (registry+https://github.com/rust-lang/crates.io-index)" = "40b54539f3910d6f84fbf9a643efd6e3aa6e4f001426c0329576128255994718" "checksum inotify-sys 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)" = "e74a1aa87c59aeff6ef2cc2fa62d41bc43f54952f55652656b18a02fd5e356c0" "checksum iovec 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "dbe6e417e7d0975db6512b90796e8ce223145ac4e33c377e4a42882a0e88bb08" "checksum itertools 0.5.10 (registry+https://github.com/rust-lang/crates.io-index)" = "4833d6978da405305126af4ac88569b5d71ff758581ce5a987dbfa3755f694fc" "checksum itoa 0.4.3 (registry+https://github.com/rust-lang/crates.io-index)" = "1306f3464951f30e30d12373d31c79fbd52d236e5e896fd92f96ec7babbbe60b" +"checksum json 0.11.14 (registry+https://github.com/rust-lang/crates.io-index)" = "01d7903059b22f1f09ced2fb9562507e3556a953caa2f835c64ab022bb6148c2" "checksum jsonrpc-proto 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)" = "" "checksum jsonrpc-types 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)" = "" "checksum jsonrpc-types-internals 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)" = "" @@ -4300,7 +4488,6 @@ dependencies = [ "checksum log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)" = "c84ec4b527950aa83a329754b01dbe3f58361d1c5efacd1f6d68c494d08a17c6" "checksum log-mdc 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "a94d21414c1f4a51209ad204c1776a3d0765002c76c6abcb602a6f09f1e881c7" "checksum log4rs 0.8.1 (registry+https://github.com/rust-lang/crates.io-index)" = "25e0fc8737a634116a2deb38d821e4400ed16ce9dcb0d628a978d399260f5902" -"checksum logger 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)" = "" "checksum lru 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)" = "5fb41c1934bda881f2ab7ad8afa2ec25b8e0453563bfb09854bf3c319b1c96c3" "checksum lru-cache 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "4d06ff7ff06f729ce5f4e227876cb88d10bc59cd4ae1e09fbb2bde15c850dc21" "checksum lz4-sys 1.8.2 (registry+https://github.com/rust-lang/crates.io-index)" = "a41fe7bc4964530eb26cf243b6ca0348a5d67949957840fe6489d5322a3ce937" @@ -4355,7 +4542,7 @@ dependencies = [ "checksum proc-macro2 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)" = "77997c53ae6edd6d187fec07ec41b207063b5ee6f33680e9fa86d405cdd313d4" "checksum proc-macro2 0.4.20 (registry+https://github.com/rust-lang/crates.io-index)" = "3d7b7eaaa90b4a90a932a9ea6666c95a389e424eff347f0f793979289429feee" "checksum proof 0.6.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)" = "" -"checksum protobuf 2.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "56c363dfc36e450457f4fa05a91d8c3f0fed00fc21142b4ce2cb7b525675eaeb" +"checksum protobuf 2.6.2 (registry+https://github.com/rust-lang/crates.io-index)" = "7e9076cae823584ab4d8fab3a111658d1232faf106611dc8378161b7d062b628" "checksum pubsub 0.6.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)" = "" "checksum pubsub_kafka 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)" = "" "checksum pubsub_rabbitmq 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)" = "" @@ -4395,6 +4582,7 @@ dependencies = [ "checksum remove_dir_all 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)" = "3488ba1b9a2084d38645c4c08276a1752dcbf2c7130d74f1569681ad5d2799c5" "checksum ring 0.14.5 (registry+https://github.com/rust-lang/crates.io-index)" = "148fc853f6d85f53f5f315d46701eaacc565cdfb3cb1959730c96e81e7e49999" "checksum rlp 0.2.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)" = "" +"checksum rlp 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "3b0d56c1450bfbef1181fdeb78b902dc1d23178de77c23d705317508e03d1b7c" "checksum rlp_derive 0.1.0 (git+https://github.com/cryptape/cita-common.git?branch=develop)" = "" "checksum rust-crypto 0.2.36 (registry+https://github.com/rust-lang/crates.io-index)" = "f76d05d3993fd5f4af9434e8e436db163a12a9d40e1a58a726f27a01dfd12a2a" "checksum rustc-demangle 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)" = "bcfe5b13211b4d78e5c2cadfebd7769197d95c639c35a50057eb4c05de811395" @@ -4413,7 +4601,7 @@ dependencies = [ "checksum serde 1.0.89 (registry+https://github.com/rust-lang/crates.io-index)" = "92514fb95f900c9b5126e32d020f5c6d40564c27a5ea6d1d7d9f157a96623560" "checksum serde-value 0.5.2 (registry+https://github.com/rust-lang/crates.io-index)" = "52903ade2290cbd61a0937a66a268f26cebf246e3ddd7964a8babb297111fb0d" "checksum serde_derive 1.0.89 (registry+https://github.com/rust-lang/crates.io-index)" = "bb6eabf4b5914e88e24eea240bb7c9f9a2cbc1bbbe8d961d381975ec3c6b806c" -"checksum serde_json 1.0.32 (registry+https://github.com/rust-lang/crates.io-index)" = "43344e7ce05d0d8280c5940cabb4964bea626aa58b1ec0e8c73fa2a8512a38ce" +"checksum serde_json 1.0.39 (registry+https://github.com/rust-lang/crates.io-index)" = "5a23aa71d4a4d43fdbfaac00eff68ba8a06a51759a89ac3304323e800c4dd40d" "checksum serde_yaml 0.8.6 (registry+https://github.com/rust-lang/crates.io-index)" = "980f5cc4e92ba24ba471b6a7b3df17d5b7b2c16fb1900a1aa0a79062320b16c4" "checksum sha1 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)" = "2579985fda508104f7587689507983eadd6a6e84dd35d6d115361f530916fa0d" "checksum sha2 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)" = "7d963c78ce367df26d7ea8b8cc655c651b42e8a1e584e869c1e17dae3ccb116a" @@ -4428,10 +4616,11 @@ dependencies = [ "checksum sodiumoxide 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "71c0682b4406fa25d621b19d2e70b5f6c8627e39b4b7ce0e24b2ef05d0fbe1ca" "checksum spin 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)" = "44363f6f51401c34e7be73db0db371c04705d35efbe9f7d6082e03a921a32c55" "checksum stable_deref_trait 1.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "dba1a27d3efae4351c8051072d619e3ade2820635c3958d826bfea39d59b54c8" +"checksum static_assertions 0.2.5 (registry+https://github.com/rust-lang/crates.io-index)" = "c19be23126415861cb3a23e501d34a708f7f9b2183c5252d690941c2e69199d5" "checksum static_merkle_tree 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "f8c6d128ce6eff23dd4a2df63c61a96f729455cf776911917eed1a4c92155f9f" "checksum stream-cipher 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "8861bc80f649f5b4c9bd38b696ae9af74499d479dbfb327f0607de6b326a36bc" "checksum string 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "98998cced76115b1da46f63388b909d118a37ae0be0f82ad35773d4a4bc9d18d" -"checksum strsim 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "bb4f380125926a99e52bc279241539c018323fab05ad6368b56f93d9369ff550" +"checksum strsim 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)" = "8ea5119cdb4c55b55d432abb513a0429384878c15dde60cc77b1c99de1a95a6a" "checksum subtle 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "2d67a5a62ba6e01cb2192ff309324cb4875d0c451d55fe2319433abe7a05a8ee" "checksum syn 0.11.11 (registry+https://github.com/rust-lang/crates.io-index)" = "d3b891b9015c88c576343b9b3e41c2c11a51c219ef067b264bd9c8aa9b441dad" "checksum syn 0.14.9 (registry+https://github.com/rust-lang/crates.io-index)" = "261ae9ecaa397c42b960649561949d69311f08eeaea86a65696e6e46517cf741" @@ -4441,12 +4630,12 @@ dependencies = [ "checksum tempdir 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)" = "15f2b5fb00ccdf689e0149d1b1b3c03fead81c2b37735d812fa8bddbbf41b6d8" "checksum tempfile 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "11ce2fe9db64b842314052e2421ac61a73ce41b898dc8e3750398b219c5fc1e0" "checksum tempfile 3.0.7 (registry+https://github.com/rust-lang/crates.io-index)" = "b86c784c88d98c801132806dadd3819ed29d8600836c4088e855cdf3e178ed8a" -"checksum tentacle 0.2.0-alpha.14 (registry+https://github.com/rust-lang/crates.io-index)" = "047295b0c9f01be1790d8c94f722c81ab59788e6576d3b2c5c95d44700bfce8d" +"checksum tentacle 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "8dcddd2761682b538db6c0d20723a031d6beeac74d73656e5e9b54ff6cd25bed" "checksum tentacle-discovery 0.2.4 (registry+https://github.com/rust-lang/crates.io-index)" = "48f049945da9545ef3208a10a28a33ca64e9672dab762ad28cfc861262f9a770" "checksum tentacle-secio 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)" = "1f7e6cfc62a132bec2b68c0827dcbfbe7b54744783aeaf15219acaeb8e07e8cd" "checksum termcolor 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)" = "4096add70612622289f2fdcdbd5086dc81c1e2675e6ae58d6c4f62a16c6d7f2f" "checksum termion 1.5.1 (registry+https://github.com/rust-lang/crates.io-index)" = "689a3bdfaab439fd92bc87df5c4c78417d3cbe537487274e9b0b2dce76e92096" -"checksum textwrap 0.10.0 (registry+https://github.com/rust-lang/crates.io-index)" = "307686869c93e71f94da64286f9a9524c0f308a9e1c87a583de8e9c9039ad3f6" +"checksum textwrap 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)" = "d326610f408c7a4eb6f51c37c330e496b08506c9457c9d34287ecc38809fb060" "checksum thread-id 2.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "a9539db560102d1cef46b8b78ce737ff0bb64e7e18d35b2a5688f7d097d0ff03" "checksum thread-id 3.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "c7fbf4c9d56b320106cd64fd024dadfa0be7cb4706725fc44a7d7ce952d820c1" "checksum thread_local 0.2.7 (registry+https://github.com/rust-lang/crates.io-index)" = "8576dbbfcaef9641452d5cf0df9b0e7eeab7694956dd33bb61515fb8f18cfdd5" @@ -4475,7 +4664,7 @@ dependencies = [ "checksum tokio-udp 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "da941144b816d0dcda4db3a1ba87596e4df5e860a72b70783fe435891f80601c" "checksum tokio-uds 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)" = "65ae5d255ce739e8537221ed2942e0445f4b3b813daebac1c0050ddaaa3587f9" "checksum tokio-uds 0.2.5 (registry+https://github.com/rust-lang/crates.io-index)" = "037ffc3ba0e12a0ab4aca92e5234e0dedeb48fddf6ccd260f1f150a36a9f2445" -"checksum tokio-yamux 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)" = "a6b5045fcdbb9cfe770bf5a1453f28115e23023949327607ab6e78a55a23630d" +"checksum tokio-yamux 0.1.12 (registry+https://github.com/rust-lang/crates.io-index)" = "2e8787adfb7b3a984b1093478895b304d7094d4de4e919655c6b0378e921f3df" "checksum toml 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "736b60249cb25337bc196faa43ee12c705e426f3d55c214d73a4e7be06f92cb4" "checksum toml 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)" = "4a2ecc31b0351ea18b3fe11274b8db6e4d82bce861bbb22e6dbed40417902c65" "checksum traitobject 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "efd1f82c56340fdf16f2a953d7bda4f8fdffba13d93b00844c25572110b26079" @@ -4488,6 +4677,7 @@ dependencies = [ "checksum ucd-util 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "fd2be2d6639d0f8fe6cdda291ad456e23629558d466e2789d2c3e9892bda285d" "checksum uint 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "38051a96565903d81c9a9210ce11076b2218f3b352926baa1f5f6abbdfce8273" "checksum uint 0.4.1 (registry+https://github.com/rust-lang/crates.io-index)" = "754ba11732b9161b94c41798e5197e5e75388d012f760c42adb5000353e98646" +"checksum uint 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)" = "082df6964410f6aa929a61ddfafc997e4f32c62c22490e439ac351cec827f436" "checksum unicase 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "9d3218ea14b4edcaccfa0df0a64a3792a2c32cc706f1b336e48867f9d3147f90" "checksum unicode-bidi 0.3.4 (registry+https://github.com/rust-lang/crates.io-index)" = "49f2bd0c6468a8230e1db229cff8029217cf623c767ea5d60bfbd42729ea54d5" "checksum unicode-normalization 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)" = "6a0180bc61fc5a987082bfa111f4cc95c4caff7f9799f3e46df09163a937aa25" @@ -4512,7 +4702,7 @@ dependencies = [ "checksum want 0.0.6 (registry+https://github.com/rust-lang/crates.io-index)" = "797464475f30ddb8830cc529aaaae648d581f99e2036a928877dfde027ddf6b3" "checksum which 1.0.5 (registry+https://github.com/rust-lang/crates.io-index)" = "e84a603e7e0b1ce1aa1ee2b109c7be00155ce52df5081590d1ffb93f4f515cb2" "checksum winapi 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)" = "167dc9d6949a9b857f3451275e911c3f44255842c1f7a76f33c55103a909087a" -"checksum winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)" = "92c1eb33641e276cfa214a0522acad57be5c56b10cb348b3c5117db75f3ac4b0" +"checksum winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)" = "f10e386af2b13e47c89e7236a7a14a086791a2b88ebad6df9bf42040195cf770" "checksum winapi-build 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "2d315eee3b34aca4797b2da6b13ed88266e6d612562a0c46390af8299fc699bc" "checksum winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" "checksum winapi-util 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "afc5508759c5bf4285e61feb862b6083c8480aec864fa17a81fdec6f69b461ab" @@ -4520,6 +4710,8 @@ dependencies = [ "checksum wincolor 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)" = "561ed901ae465d6185fa7864d63fbd5720d0ef718366c9a4dc83cf6170d7e9ba" "checksum ws 0.7.9 (registry+https://github.com/rust-lang/crates.io-index)" = "329d3e6dd450a9c5c73024e1047f0be7e24121a68484eb0b5368977bee3cf8c3" "checksum ws2_32-sys 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "d59cefebd0c892fa2dd6de581e937301d8552cb44489cdff035c6187cb63fa5e" +"checksum xml-rs 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "3c1cb601d29fe2c2ac60a2b2e5e293994d87a1f6fa9687a31a15270f909be9c2" +"checksum xmltree 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ff8eaee9d17062850f1e6163b509947969242990ee59a35801af437abe041e70" "checksum yaml-rust 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)" = "95acf0db5515d07da9965ec0e0ba6cc2d825e2caeb7303b66ca441729801254e" "checksum yasna 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)" = "3a31ff5b5f5fcc70c5da4fcbdcbd91d541bb95b0b2517a3ca5cdc49fd3692cbb" "checksum zktx 0.0.1 (git+https://github.com/cryptape/zktx.git)" = "" diff --git a/Cargo.toml b/Cargo.toml index 4357df88a..3210453b2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -6,14 +6,15 @@ members = ["cita-auth" ,"cita-network" ,"cita-executor" ,"cita-forever" -,"tools/create_key_addr" -,"tools/snapshot_tool" +,"tools/create-key-addr" +,"tools/snapshot-tool" +,"tools/create-genesis" ,"tools/relayer-parser" ,"tests/chain-executor-mock" ,"tests/consensus-mock" -,"tests/chain_performance_by_mq" -,"tests/box_executor" -,"tests/json_test" +,"tests/chain-performance-by-mq" +,"tests/box-executor" +,"tests/json-test" ] [profile.bench] diff --git a/README-CN.md b/README-CN.md index bf6792242..22c27816c 100644 --- a/README-CN.md +++ b/README-CN.md @@ -88,7 +88,7 @@ GPLv3 license ## 权益归属 - + 秘猿科技团队 :heart: @@ -102,7 +102,74 @@ Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/d -
kaikai
kaikai

💻
zhangyaning
zhangyaning

💻
Boyu Yang
Boyu Yang

💻
zhiwei
zhiwei

💻
漂流
漂流

💻
AsceticBear
AsceticBear

💻
yubo
yubo

💻
zhouyun-zoe
zhouyun-zoe

📖
Bicheng Gao
Bicheng Gao

💻
lhf
lhf

💻
LinFeng Qian
LinFeng Qian

💻
keroro
keroro

💻
Yaorong
Yaorong

💻
suyanlong
suyanlong

💻
Chen Yu
Chen Yu

💻
zhangsoledad
zhangsoledad

💻
hezhengjun
hezhengjun

💻
zeroqn
zeroqn

💻
urugang
urugang

💻
Jiang Jinyang
Jiang Jinyang

💻
Jan Xie
Jan Xie

💻
Sun Lei
Sun Lei

💻
hyl
hyl

💻
Terry Tai
Terry Tai

💻
Ke Wang
Ke Wang

💻
Mohanson
Mohanson

💻
quanzhan lu
quanzhan lu

💻
duanyytop
duanyytop

💻
clearloop
clearloop

💻
nokodemion
nokodemion

💻
Rain Chen
Rain Chen

💻
Daogang Tang
Daogang Tang

💻
xianliang jiang
xianliang jiang

🐛
Nov
Nov

💻
Rai Yang
Rai Yang

💻
Wenchao Hu
Wenchao Hu

💻
kaiyu
kaiyu

💻
James Chen
James Chen

💻
rev-chaos
rev-chaos

💻
Eason Gao
Eason Gao

💻
Eric Zhang
Eric Zhang

💻
Jun Jiang
Jun Jiang

💻
PRIEWIENV
PRIEWIENV

💻
The Gitter Badger
The Gitter Badger

💻
CL
CL

💻
programmer-liu
programmer-liu

💻
Jiayu Ye
Jiayu Ye

💻
liyanzi
liyanzi

🐛
JiaYi
JiaYi

📖
Timmy Zhang
Timmy Zhang

🤔
Wu Yuyue
Wu Yuyue

📖
xiangmeiLu
xiangmeiLu

📖
mingxiaowu
mingxiaowu

🐛
wangfh666
wangfh666

🐛
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
kaikai
kaikai

💻
zhangyaning
zhangyaning

💻
Boyu Yang
Boyu Yang

💻
zhiwei
zhiwei

💻
漂流
漂流

💻
AsceticBear
AsceticBear

💻
yubo
yubo

💻
zhouyun-zoe
zhouyun-zoe

📖
Bicheng Gao
Bicheng Gao

💻
lhf
lhf

💻
LinFeng Qian
LinFeng Qian

💻
keroro
keroro

💻
Yaorong
Yaorong

💻
suyanlong
suyanlong

💻
Chen Yu
Chen Yu

💻
zhangsoledad
zhangsoledad

💻
hezhengjun
hezhengjun

💻
zeroqn
zeroqn

💻
urugang
urugang

💻
Jiang Jinyang
Jiang Jinyang

💻
Jan Xie
Jan Xie

💻
Sun Lei
Sun Lei

💻
hyl
hyl

💻
Terry Tai
Terry Tai

💻
Ke Wang
Ke Wang

💻
Mohanson
Mohanson

💻
quanzhan lu
quanzhan lu

💻
duanyytop
duanyytop

💻
clearloop
clearloop

💻
nokodemion
nokodemion

💻
Rain Chen
Rain Chen

💻
Daogang Tang
Daogang Tang

💻
xianliang jiang
xianliang jiang

🐛
Nov
Nov

💻
Rai Yang
Rai Yang

💻
Wenchao Hu
Wenchao Hu

💻
kaiyu
kaiyu

💻
James Chen
James Chen

💻
rev-chaos
rev-chaos

💻
Eason Gao
Eason Gao

💻
Eric Zhang
Eric Zhang

💻
Jun Jiang
Jun Jiang

💻
PRIEWIENV
PRIEWIENV

💻
The Gitter Badger
The Gitter Badger

💻
CL
CL

💻
programmer-liu
programmer-liu

💻
Jiayu Ye
Jiayu Ye

💻
liyanzi
liyanzi

🐛
JiaYi
JiaYi

📖
Timmy Zhang
Timmy Zhang

🤔
Wu Yuyue
Wu Yuyue

📖
xiangmeiLu
xiangmeiLu

📖
mingxiaowu
mingxiaowu

🐛
wangfh666
wangfh666

🐛
diff --git a/README.md b/README.md index e13a0828e..5f6c31c67 100644 --- a/README.md +++ b/README.md @@ -70,7 +70,7 @@ CITA is currently under the GPLv3 license. See the LICENSE file for details. ## Credits - + CITA is created by Cryptape team with :heart:. @@ -84,7 +84,74 @@ Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/d -
kaikai
kaikai

💻
zhangyaning
zhangyaning

💻
Boyu Yang
Boyu Yang

💻
zhiwei
zhiwei

💻
漂流
漂流

💻
AsceticBear
AsceticBear

💻
yubo
yubo

💻
zhouyun-zoe
zhouyun-zoe

📖
Bicheng Gao
Bicheng Gao

💻
lhf
lhf

💻
LinFeng Qian
LinFeng Qian

💻
keroro
keroro

💻
Yaorong
Yaorong

💻
suyanlong
suyanlong

💻
Chen Yu
Chen Yu

💻
zhangsoledad
zhangsoledad

💻
hezhengjun
hezhengjun

💻
zeroqn
zeroqn

💻
urugang
urugang

💻
Jiang Jinyang
Jiang Jinyang

💻
Jan Xie
Jan Xie

💻
Sun Lei
Sun Lei

💻
hyl
hyl

💻
Terry Tai
Terry Tai

💻
Ke Wang
Ke Wang

💻
Mohanson
Mohanson

💻
quanzhan lu
quanzhan lu

💻
duanyytop
duanyytop

💻
clearloop
clearloop

💻
nokodemion
nokodemion

💻
Rain Chen
Rain Chen

💻
Daogang Tang
Daogang Tang

💻
xianliang jiang
xianliang jiang

🐛
Nov
Nov

💻
Rai Yang
Rai Yang

💻
Wenchao Hu
Wenchao Hu

💻
kaiyu
kaiyu

💻
James Chen
James Chen

💻
rev-chaos
rev-chaos

💻
Eason Gao
Eason Gao

💻
Eric Zhang
Eric Zhang

💻
Jun Jiang
Jun Jiang

💻
PRIEWIENV
PRIEWIENV

💻
The Gitter Badger
The Gitter Badger

💻
CL
CL

💻
programmer-liu
programmer-liu

💻
Jiayu Ye
Jiayu Ye

💻
liyanzi
liyanzi

🐛
JiaYi
JiaYi

📖
Timmy Zhang
Timmy Zhang

🤔
Wu Yuyue
Wu Yuyue

📖
xiangmeiLu
xiangmeiLu

📖
mingxiaowu
mingxiaowu

🐛
wangfh666
wangfh666

🐛
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
kaikai
kaikai

💻
zhangyaning
zhangyaning

💻
Boyu Yang
Boyu Yang

💻
zhiwei
zhiwei

💻
漂流
漂流

💻
AsceticBear
AsceticBear

💻
yubo
yubo

💻
zhouyun-zoe
zhouyun-zoe

📖
Bicheng Gao
Bicheng Gao

💻
lhf
lhf

💻
LinFeng Qian
LinFeng Qian

💻
keroro
keroro

💻
Yaorong
Yaorong

💻
suyanlong
suyanlong

💻
Chen Yu
Chen Yu

💻
zhangsoledad
zhangsoledad

💻
hezhengjun
hezhengjun

💻
zeroqn
zeroqn

💻
urugang
urugang

💻
Jiang Jinyang
Jiang Jinyang

💻
Jan Xie
Jan Xie

💻
Sun Lei
Sun Lei

💻
hyl
hyl

💻
Terry Tai
Terry Tai

💻
Ke Wang
Ke Wang

💻
Mohanson
Mohanson

💻
quanzhan lu
quanzhan lu

💻
duanyytop
duanyytop

💻
clearloop
clearloop

💻
nokodemion
nokodemion

💻
Rain Chen
Rain Chen

💻
Daogang Tang
Daogang Tang

💻
xianliang jiang
xianliang jiang

🐛
Nov
Nov

💻
Rai Yang
Rai Yang

💻
Wenchao Hu
Wenchao Hu

💻
kaiyu
kaiyu

💻
James Chen
James Chen

💻
rev-chaos
rev-chaos

💻
Eason Gao
Eason Gao

💻
Eric Zhang
Eric Zhang

💻
Jun Jiang
Jun Jiang

💻
PRIEWIENV
PRIEWIENV

💻
The Gitter Badger
The Gitter Badger

💻
CL
CL

💻
programmer-liu
programmer-liu

💻
Jiayu Ye
Jiayu Ye

💻
liyanzi
liyanzi

🐛
JiaYi
JiaYi

📖
Timmy Zhang
Timmy Zhang

🤔
Wu Yuyue
Wu Yuyue

📖
xiangmeiLu
xiangmeiLu

📖
mingxiaowu
mingxiaowu

🐛
wangfh666
wangfh666

🐛
diff --git a/cita-auth/Cargo.toml b/cita-auth/Cargo.toml index 1ceaa6aa9..47abcd2fb 100644 --- a/cita-auth/Cargo.toml +++ b/cita-auth/Cargo.toml @@ -2,6 +2,7 @@ name = "cita-auth" version = "0.1.0" authors = ["Cryptape Technologies "] +edition = "2018" [dependencies] clap = "2" @@ -10,12 +11,12 @@ cpuprofiler = "0.0.3" serde = "1.0" serde_derive = "1.0" serde_json = "1.0" +cita-logger = "0.1.0" cita-types = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } cita-directories = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } util = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } error = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } pubsub = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } -logger = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } libproto = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } cita-crypto = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } tx_pool = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } diff --git a/cita-auth/build.rs b/cita-auth/build.rs index a0533082a..0b73a9c9c 100644 --- a/cita-auth/build.rs +++ b/cita-auth/build.rs @@ -1,5 +1,5 @@ // CITA -// Copyright 2016-2018 Cryptape Technologies LLC. +// Copyright 2016-2019 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public diff --git a/cita-auth/src/batch_forward.rs b/cita-auth/src/batch_forward.rs index 56e6dbc06..890c7f7fe 100644 --- a/cita-auth/src/batch_forward.rs +++ b/cita-auth/src/batch_forward.rs @@ -1,5 +1,5 @@ // CITA -// Copyright 2016-2017 Cryptape Technologies LLC. +// Copyright 2016-2019 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public diff --git a/cita-auth/src/block_txn.rs b/cita-auth/src/block_txn.rs index 7ed6c85e4..81185f7b0 100644 --- a/cita-auth/src/block_txn.rs +++ b/cita-auth/src/block_txn.rs @@ -1,5 +1,5 @@ // CITA -// Copyright 2016-2018 Cryptape Technologies LLC. +// Copyright 2016-2019 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public @@ -15,9 +15,9 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . +use crate::handler::verify_tx_sig; +use crate::hashable::Hashable; use cita_types::H256; -use handler::verify_tx_sig; -use hashable::Hashable; use libproto::TryInto; use libproto::{BlockTxn, GetBlockTxn, Origin, SignedTransaction}; use rayon::iter::{IndexedParallelIterator, IntoParallelIterator, ParallelIterator}; diff --git a/cita-auth/src/block_verify.rs b/cita-auth/src/block_verify.rs index 625cf64c8..0a6d1c46a 100644 --- a/cita-auth/src/block_verify.rs +++ b/cita-auth/src/block_verify.rs @@ -1,5 +1,5 @@ // CITA -// Copyright 2016-2018 Cryptape Technologies LLC. +// Copyright 2016-2019 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public @@ -79,7 +79,7 @@ impl<'a> BlockVerify<'a> { unimplemented!(); } - pub fn verify_emergency_brake() -> bool { + pub fn verify_emergency_intervention() -> bool { unimplemented!() } } diff --git a/cita-auth/src/config.rs b/cita-auth/src/config.rs index 2e68b8e89..f017e771e 100644 --- a/cita-auth/src/config.rs +++ b/cita-auth/src/config.rs @@ -1,5 +1,5 @@ // CITA -// Copyright 2016-2017 Cryptape Technologies LLC. +// Copyright 2016-2019 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public diff --git a/cita-auth/src/dispatcher.rs b/cita-auth/src/dispatcher.rs index fcbc2acf6..ee22acfe9 100644 --- a/cita-auth/src/dispatcher.rs +++ b/cita-auth/src/dispatcher.rs @@ -1,5 +1,5 @@ // CITA -// Copyright 2016-2018 Cryptape Technologies LLC. +// Copyright 2016-2019 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public @@ -15,9 +15,10 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . +use crate::handler::SysConfigInfo; +use crate::txwal::TxWal; use cita_types::traits::LowerHex; use cita_types::{Address, H256}; -use handler::SysConfigInfo; use libproto::blockchain::{AccountGasLimit, BlockBody, BlockTxs, SignedTransaction}; use libproto::router::{MsgType, RoutingKey, SubModules}; use libproto::Message; @@ -28,7 +29,6 @@ use std::collections::HashSet; use std::convert::Into; use std::thread; use tx_pool; -use txwal::TxWal; pub struct Dispatcher { txs_pool: RefCell, diff --git a/cita-auth/src/handler.rs b/cita-auth/src/handler.rs index 162605594..31fbdd398 100644 --- a/cita-auth/src/handler.rs +++ b/cita-auth/src/handler.rs @@ -1,5 +1,5 @@ // CITA -// Copyright 2016-2018 Cryptape Technologies LLC. +// Copyright 2016-2019 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public @@ -15,14 +15,15 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . -use block_txn::{BlockTxnMessage, BlockTxnReq}; -use block_verify::BlockVerify; +use crate::block_txn::{BlockTxnMessage, BlockTxnReq}; +use crate::block_verify::BlockVerify; +use crate::dispatcher::Dispatcher; +use crate::history::HistoryHeights; +use crate::transaction_verify::Error; use cita_types::traits::LowerHex; use cita_types::{clean_0x, Address, H256, U256}; use crypto::{pubkey_to_address, PubKey, Sign, Signature, SIGNATURE_BYTES_LEN}; -use dispatcher::Dispatcher; use error::ErrorCode; -use history::HistoryHeights; use jsonrpc_types::rpc_types::TxResponse; use libproto::auth::{Miscellaneous, MiscellaneousReq}; use libproto::blockchain::{AccountGasLimit, SignedTransaction}; @@ -42,7 +43,6 @@ use std::collections::{HashMap, HashSet}; use std::convert::Into; use std::str::FromStr; use std::time::Duration; -use transaction_verify::Error; use util::BLOCKLIMIT; const TX_OK: &str = "OK"; diff --git a/cita-auth/src/history.rs b/cita-auth/src/history.rs index 19a4cfb61..331370d3f 100644 --- a/cita-auth/src/history.rs +++ b/cita-auth/src/history.rs @@ -1,5 +1,5 @@ // CITA -// Copyright 2016-2018 Cryptape Technologies LLC. +// Copyright 2016-2019 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public diff --git a/cita-auth/src/main.rs b/cita-auth/src/main.rs index fa2830da9..5de961cd1 100644 --- a/cita-auth/src/main.rs +++ b/cita-auth/src/main.rs @@ -1,5 +1,5 @@ // CITA -// Copyright 2016-2017 Cryptape Technologies LLC. +// Copyright 2016-2019 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public @@ -69,35 +69,22 @@ //! extern crate cita_crypto as crypto; -extern crate cita_directories; -extern crate cita_types; -extern crate clap; extern crate core as chain_core; -extern crate cpuprofiler; -extern crate dotenv; -extern crate error; -extern crate jsonrpc_types; #[macro_use] extern crate libproto; #[macro_use] -extern crate logger; -extern crate lru; -extern crate pubsub; +extern crate cita_logger as logger; #[cfg(test)] #[macro_use] extern crate quickcheck; -extern crate rayon; #[macro_use] extern crate serde_derive; -extern crate serde_json; #[cfg(test)] extern crate tempfile; -extern crate tx_pool; #[macro_use] extern crate util; extern crate db as cita_db; extern crate hashable; -extern crate uuid; use batch_forward::BatchForward; use clap::App; diff --git a/cita-auth/src/transaction_verify.rs b/cita-auth/src/transaction_verify.rs index 97c6d1b73..8912c4f1c 100644 --- a/cita-auth/src/transaction_verify.rs +++ b/cita-auth/src/transaction_verify.rs @@ -1,5 +1,5 @@ // CITA -// Copyright 2016-2018 Cryptape Technologies LLC. +// Copyright 2016-2019 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public diff --git a/cita-auth/src/txwal.rs b/cita-auth/src/txwal.rs index 32aacd0d6..53248539e 100644 --- a/cita-auth/src/txwal.rs +++ b/cita-auth/src/txwal.rs @@ -1,5 +1,5 @@ // CITA -// Copyright 2016-2018 Cryptape Technologies LLC. +// Copyright 2016-2019 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public diff --git a/cita-bft b/cita-bft index 7041bda10..72cf820cc 160000 --- a/cita-bft +++ b/cita-bft @@ -1 +1 @@ -Subproject commit 7041bda10499e88e7646f5df707b8058c09c9c67 +Subproject commit 72cf820cc057bf5b3860cdf5e41a1cd6b9030989 diff --git a/cita-chain/Cargo.toml b/cita-chain/Cargo.toml index d37ead0a8..0b1c92a10 100644 --- a/cita-chain/Cargo.toml +++ b/cita-chain/Cargo.toml @@ -3,19 +3,20 @@ description = "CITA node." name = "cita-chain" version = "0.6.0" authors = ["Cryptape Technologies "] +edition = "2018" [dependencies] dotenv = "0.13.0" clap = "2" byteorder = { version = "1", default-features = false } serde_json = "1.0" +cita-logger = "0.1.0" cita-types = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } libproto = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } pubsub = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } cita-directories = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } util = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } error = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } -logger = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } jsonrpc-types = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } core = { path = "./core" } common-types = { path = "./types" } diff --git a/cita-chain/build.rs b/cita-chain/build.rs index 13f56792b..d3ee509ce 100644 --- a/cita-chain/build.rs +++ b/cita-chain/build.rs @@ -1,5 +1,3 @@ -extern crate util; - use std::env; use util::build_info::gen_build_info; diff --git a/cita-chain/core/Cargo.toml b/cita-chain/core/Cargo.toml index 099a6d636..ea0f94ef7 100644 --- a/cita-chain/core/Cargo.toml +++ b/cita-chain/core/Cargo.toml @@ -2,6 +2,7 @@ name = "core" version = "0.1.0" authors = ["Cryptape Technologies ", "Parity Technologies "] +edition = "2018" [dependencies] byteorder = { version = "1", default-features = false } @@ -15,8 +16,8 @@ bit-set = "0.4" time = "0.1" crossbeam = "0.2" transient-hashmap = "0.4.0" +cita-logger = "0.1.0" libproto = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } -logger = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } cita-ed25519 = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } cita-secp256k1 = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } cita-types = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } @@ -37,7 +38,7 @@ pubsub = { git = "https://github.com/cryptape/cita-common.git", branch = "develo rand = "0.3" cpuprofiler = "0.0.3" tempdir = "0.3.7" -logger = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } +cita-logger = "0.1.0" [features] default = ["secp256k1", "sha3hash"] diff --git a/cita-chain/core/src/env_info.rs b/cita-chain/core/src/env_info.rs index d3dd80b69..f19178efb 100644 --- a/cita-chain/core/src/env_info.rs +++ b/cita-chain/core/src/env_info.rs @@ -14,12 +14,9 @@ // You should have received a copy of the GNU General Public License // along with Parity. If not, see . -// use std::cmp; - +use crate::header::BlockNumber; use cita_types::{Address, H256, U256}; -use header::BlockNumber; use std::sync::Arc; -// use ethjson; /// Simple vector of hashes, should be at most 256 items large, can be smaller if being used /// for a block whose number is less than 257. @@ -42,6 +39,7 @@ pub struct EnvInfo { pub last_hashes: Arc, /// The quota used. pub quota_used: U256, + /// The account quota limit pub account_quota_limit: U256, } @@ -60,42 +58,10 @@ impl Default for EnvInfo { } } -// impl From for EnvInfo { -// fn from(e: ethjson::vm::Env) -> Self { -// let number = e.number.into(); -// EnvInfo { -// number: number, -// author: e.author.into(), -// difficulty: e.difficulty.into(), -// quota_limit: e.quota_limit.into(), -// timestamp: e.timestamp.into(), -// last_hashes: Arc::new((1..cmp::min(number + 1, 257)).map(|i| format!("{}", number - i).as_bytes().crypt_hash()).collect()), -// quota_used: U256::default(), -// } -// } -// } - #[cfg(test)] mod tests { use super::*; - // #[test] - // fn it_serializes_form_json() { - // let env_info = EnvInfo::from(ethjson::vm::Env { - // author: ethjson::hash::Address(Address::from_str("000000f00000000f000000000000f00000000f00").unwrap()), - // number: ethjson::uint::Uint(U256::from(1_112_339)), - // difficulty: ethjson::uint::Uint(U256::from(50_000)), - // quota_limit: ethjson::uint::Uint(U256::from(40_000)), - // timestamp: ethjson::uint::Uint(U256::from(1_100)) - // }); - - // assert_eq!(env_info.number, 1112339); - // assert_eq!(env_info.author, Address::from_str("000000f00000000f000000000000f00000000f00").unwrap()); - // assert_eq!(env_info.quota_limit, 40000.into()); - // assert_eq!(env_info.difficulty, 50000.into()); - // assert_eq!(env_info.quota_used, 0.into()); - // } - #[test] fn it_can_be_created_as_default() { let default_env_info = EnvInfo::default(); diff --git a/cita-chain/core/src/error.rs b/cita-chain/core/src/error.rs index deb22f612..541889999 100644 --- a/cita-chain/core/src/error.rs +++ b/cita-chain/core/src/error.rs @@ -16,14 +16,14 @@ //! General error types for use in ethcore. -use basic_types::LogBloom; +use crate::basic_types::LogBloom; use cita_ed25519::Error as EthkeyError; -use cita_db::TrieError; +use crate::cita_db::TrieError; +use crate::header::BlockNumber; +use crate::snapshot::error::Error as SnapshotError; use cita_types::{H256, U256, U512}; -use header::BlockNumber; use snappy; -use snapshot::error::Error as SnapshotError; use std::fmt; use util::*; diff --git a/cita-chain/core/src/filters/eth_filter.rs b/cita-chain/core/src/filters/eth_filter.rs index cd1d8ec53..68bdc04b1 100644 --- a/cita-chain/core/src/filters/eth_filter.rs +++ b/cita-chain/core/src/filters/eth_filter.rs @@ -15,11 +15,11 @@ // along with Parity. If not, see . use super::{limit_logs, PollFilter, PollId}; +use crate::libchain::chain::Chain; +use crate::types::filter::Filter as EthcoreFilter; +use crate::types::ids::BlockId; use cita_types::H256; use jsonrpc_types::rpc_types::{Filter, FilterChanges, Log}; -use libchain::chain::Chain; -use types::filter::Filter as EthcoreFilter; -use types::ids::BlockId; pub trait EthFilter { fn new_filter(&self, filter: Filter) -> PollId; diff --git a/cita-chain/core/src/lib.rs b/cita-chain/core/src/lib.rs index 75c560054..54be60040 100644 --- a/cita-chain/core/src/lib.rs +++ b/cita-chain/core/src/lib.rs @@ -1,5 +1,5 @@ // CITA -// Copyright 2016-2017 Cryptape Technologies LLC. +// Copyright 2016-2019 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public @@ -19,7 +19,7 @@ extern crate byteorder; #[macro_use] extern crate libproto; #[macro_use] -extern crate logger; +extern crate cita_logger as logger; extern crate cita_merklehash; extern crate hashable; extern crate lru_cache; @@ -55,10 +55,8 @@ pub mod env_info; #[macro_use] pub mod error; - pub mod filters; pub mod libchain; pub mod snapshot; - -pub use cita_db::journaldb; -pub use types::*; +pub use crate::cita_db::journaldb; +pub use crate::types::*; diff --git a/cita-chain/core/src/libchain/chain.rs b/cita-chain/core/src/libchain/chain.rs index fc921dade..7908664ac 100644 --- a/cita-chain/core/src/libchain/chain.rs +++ b/cita-chain/core/src/libchain/chain.rs @@ -1,5 +1,5 @@ // CITA -// Copyright 2016-2018 Cryptape Technologies LLC. +// Copyright 2016-2019 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public @@ -15,49 +15,49 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . -use basic_types::{LogBloom, LogBloomGroup}; -use bloomchain::group::{ +use crate::basic_types::{LogBloom, LogBloomGroup}; +use crate::bloomchain::group::{ BloomGroup, BloomGroupChain, BloomGroupDatabase, GroupPosition as BloomGroupPosition, }; -use bloomchain::{Bloom, Config as BloomChainConfig, Number as BloomChainNumber}; +use crate::bloomchain::{Bloom, Config as BloomChainConfig, Number as BloomChainNumber}; +use crate::db; +use crate::db::*; pub use byteorder::{BigEndian, ByteOrder}; -use db; -use db::*; -use filters::{PollFilter, PollManager}; -use header::*; -use libchain::cache::CacheSize; -use libchain::status::Status; +use crate::filters::{PollFilter, PollManager}; +use crate::header::*; +use crate::libchain::cache::CacheSize; +use crate::libchain::status::Status; +pub use crate::types::block::*; +use crate::types::extras::*; use libproto::blockchain::{ AccountGasLimit as ProtoAccountGasLimit, Proof as ProtoProof, ProofType, RichStatus as ProtoRichStatus, StateSignal, }; -pub use types::block::*; -use types::extras::*; -use cita_db::kvdb::*; +use crate::cita_db::kvdb::*; +use crate::header::Header; +use crate::receipt::{LocalizedReceipt, Receipt}; +use crate::types::cache_manager::CacheManager; +use crate::types::filter::Filter; +use crate::types::ids::{BlockId, TransactionId}; +use crate::types::log_entry::{LocalizedLogEntry, LogEntry}; +use crate::types::transaction::{Action, SignedTransaction}; use cita_merklehash; use cita_types::traits::LowerHex; use cita_types::{Address, H256, U256}; use hashable::Hashable; -use header::Header; use libproto::executor::ExecutedResult; use libproto::router::{MsgType, RoutingKey, SubModules}; use libproto::TryInto; use libproto::{BlockTxHashes, FullTransaction, Message}; use proof::BftProof; use pubsub::channel::Sender; -use receipt::{LocalizedReceipt, Receipt}; use rlp::{self, Encodable}; use std::collections::{BTreeMap, HashMap, HashSet}; use std::convert::Into; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::Arc; -use types::cache_manager::CacheManager; -use types::filter::Filter; -use types::ids::{BlockId, TransactionId}; -use types::log_entry::{LocalizedLogEntry, LogEntry}; -use types::transaction::{Action, SignedTransaction}; use util::HeapSizeOf; use util::{Mutex, RwLock}; diff --git a/cita-chain/core/src/libchain/mod.rs b/cita-chain/core/src/libchain/mod.rs index b9c0d5ddd..d57620aa9 100644 --- a/cita-chain/core/src/libchain/mod.rs +++ b/cita-chain/core/src/libchain/mod.rs @@ -1,5 +1,5 @@ // CITA -// Copyright 2016-2017 Cryptape Technologies LLC. +// Copyright 2016-2019 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public @@ -19,5 +19,5 @@ pub mod cache; pub mod chain; pub mod rich_status; pub mod status; -pub use cita_db::journaldb; -pub use types::block::*; +pub use crate::cita_db::journaldb; +pub use crate::types::block::*; diff --git a/cita-chain/core/src/libchain/rich_status.rs b/cita-chain/core/src/libchain/rich_status.rs index 4fab0ca09..19ea1cd4d 100644 --- a/cita-chain/core/src/libchain/rich_status.rs +++ b/cita-chain/core/src/libchain/rich_status.rs @@ -1,5 +1,5 @@ // CITA -// Copyright 2016-2017 Cryptape Technologies LLC. +// Copyright 2016-2019 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public diff --git a/cita-chain/core/src/libchain/status.rs b/cita-chain/core/src/libchain/status.rs index 9b77dc19f..012198fcb 100644 --- a/cita-chain/core/src/libchain/status.rs +++ b/cita-chain/core/src/libchain/status.rs @@ -1,5 +1,5 @@ // CITA -// Copyright 2016-2017 Cryptape Technologies LLC. +// Copyright 2016-2019 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public diff --git a/cita-chain/core/src/snapshot/error.rs b/cita-chain/core/src/snapshot/error.rs index 2b607ef75..6d0988a47 100644 --- a/cita-chain/core/src/snapshot/error.rs +++ b/cita-chain/core/src/snapshot/error.rs @@ -18,9 +18,9 @@ use std::fmt; -use types::ids::BlockId; +use crate::types::ids::BlockId; -use cita_db::trie::TrieError; +use crate::cita_db::trie::TrieError; use cita_types::H256; use rlp::DecoderError; use snappy::SnappyError; diff --git a/cita-chain/core/src/snapshot/io.rs b/cita-chain/core/src/snapshot/io.rs index 16c2591ca..f0c44f832 100644 --- a/cita-chain/core/src/snapshot/io.rs +++ b/cita-chain/core/src/snapshot/io.rs @@ -185,7 +185,7 @@ impl PackedReader { /// Create a new `PackedReader` for the file at the given path. /// This will fail if any io errors are encountered or the file /// is not a valid packed snapshot. - pub fn create(path: &Path) -> Result, ::error::Error> { + pub fn create(path: &Path) -> Result, crate::error::Error> { let mut file = File::open(path)?; let file_len = file.metadata()?.len(); if file_len < 8 { @@ -270,7 +270,7 @@ pub struct LooseReader { impl LooseReader { /// Create a new `LooseReader` which will read the manifest and chunk data from /// the given directory. - pub fn create(mut dir: PathBuf) -> Result { + pub fn create(mut dir: PathBuf) -> Result { let mut manifest_buf = Vec::new(); dir.push("MANIFEST"); diff --git a/cita-chain/core/src/snapshot/mod.rs b/cita-chain/core/src/snapshot/mod.rs index 085789879..e81ef3785 100644 --- a/cita-chain/core/src/snapshot/mod.rs +++ b/cita-chain/core/src/snapshot/mod.rs @@ -28,7 +28,7 @@ const PREFERRED_CHUNK_SIZE: usize = 4 * 1024 * 1024; // Snappy::decompressed_len estimation may sometimes yield results greater // than PREFERRED_CHUNK_SIZE so allow some threshold here. //const MAX_CHUNK_SIZE: usize = PREFERRED_CHUNK_SIZE / 4 * 5; -use header::Header; +use crate::header::Header; use cita_types::H256; use rlp::{DecoderError, Encodable, RlpStream, UntrustedRlp}; @@ -37,31 +37,33 @@ use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::Arc; use std::time::Duration; -use cita_db::kvdb::{DBTransaction, KeyValueDB}; +use crate::cita_db::kvdb::{DBTransaction, KeyValueDB}; use hashable::Hashable; use snappy; use util::{Bytes, Mutex, BLOCKLIMIT}; -use basic_types::{LogBloom, LogBloomGroup}; -use bloomchain::group::BloomGroupChain; -use bloomchain::{Bloom, Number as BloomChainNumber}; +use crate::basic_types::{LogBloom, LogBloomGroup}; +use crate::bloomchain::group::BloomGroupChain; +use crate::bloomchain::{Bloom, Number as BloomChainNumber}; pub use self::error::Error; use self::io::SnapshotReader; use self::io::SnapshotWriter; use self::service::{Service, SnapshotService}; use super::header::BlockNumber; -use db::{CacheUpdatePolicy, Writable, COL_BODIES, COL_EXTRA, COL_HEADERS}; +use crate::db::{CacheUpdatePolicy, Writable, COL_BODIES, COL_EXTRA, COL_HEADERS}; -use types::ids::BlockId; +use crate::types::ids::BlockId; -use libchain::chain::Chain; -use types::block::{Block, BlockBody}; -use types::extras::{BlockReceipts, CurrentHash, CurrentHeight, CurrentProof, LogGroupPosition}; +use crate::libchain::chain::Chain; +use crate::types::block::{Block, BlockBody}; +use crate::types::extras::{ + BlockReceipts, CurrentHash, CurrentHeight, CurrentProof, LogGroupPosition, +}; use libproto::Proof; -use receipt::Receipt; +use crate::receipt::Receipt; //#[cfg(test)] //mod tests; @@ -443,7 +445,11 @@ impl BlockRebuilder { } /// Feed an uncompressed state chunk into the rebuilder. - pub fn feed(&mut self, chunk: &[u8], abort_flag: &AtomicBool) -> Result<(), ::error::Error> { + pub fn feed( + &mut self, + chunk: &[u8], + abort_flag: &AtomicBool, + ) -> Result<(), crate::error::Error> { let rlp = UntrustedRlp::new(chunk); let item_count = rlp.item_count()?; let num_blocks = (item_count - 2) as u64; @@ -684,7 +690,7 @@ impl BlockRebuilder { } /// Glue together any disconnected chunks and check that the chain is complete. - fn finalize(&self) -> Result<(), ::error::Error> { + fn finalize(&self) -> Result<(), crate::error::Error> { let mut batch = self.db.transaction(); let genesis_block = self diff --git a/cita-chain/core/src/snapshot/service.rs b/cita-chain/core/src/snapshot/service.rs index e422238b0..2118f64ce 100644 --- a/cita-chain/core/src/snapshot/service.rs +++ b/cita-chain/core/src/snapshot/service.rs @@ -27,18 +27,18 @@ use std::usize::MAX; use super::io::{LooseReader, LooseWriter, SnapshotReader, SnapshotWriter}; use super::{BlockRebuilder, ManifestData, RestorationStatus}; +use crate::error::Error; use cita_types::H256; -use error::Error; -use cita_db::kvdb::{Database, DatabaseConfig}; +use crate::cita_db::kvdb::{Database, DatabaseConfig}; use snappy; use util::Bytes; use util::UtilError; use util::{Mutex, RwLock, RwLockReadGuard}; -use libchain::chain::{get_chain, get_chain_body_height, Chain}; +use crate::libchain::chain::{get_chain, get_chain_body_height, Chain}; -use filters::PollManager; +use crate::filters::PollManager; /// External database restoration handler pub trait DatabaseRestore: Send + Sync { diff --git a/cita-chain/src/block_processor.rs b/cita-chain/src/block_processor.rs index 330e43837..4ca7dfd7e 100644 --- a/cita-chain/src/block_processor.rs +++ b/cita-chain/src/block_processor.rs @@ -1,5 +1,5 @@ // CITA -// Copyright 2016-2017 Cryptape Technologies LLC. +// Copyright 2016-2019 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public diff --git a/cita-chain/src/forward.rs b/cita-chain/src/forward.rs index 1b43acfd4..d82074f2d 100644 --- a/cita-chain/src/forward.rs +++ b/cita-chain/src/forward.rs @@ -1,5 +1,5 @@ // CITA -// Copyright 2016-2017 Cryptape Technologies LLC. +// Copyright 2016-2019 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public @@ -15,6 +15,8 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . +use crate::types::filter::Filter; +use crate::types::ids::BlockId; use cita_types::H256; use core::filters::eth_filter::EthFilter; use core::libchain::chain::{BlockInQueue, Chain}; @@ -41,10 +43,8 @@ use std::sync::atomic::Ordering; use std::sync::Arc; use std::thread; use std::time::Duration; -use types::filter::Filter; -use types::ids::BlockId; -use cita_db::kvdb::DatabaseConfig; +use crate::cita_db::kvdb::DatabaseConfig; use cita_directories::DataPath; use core::db; use std::fs::File; diff --git a/cita-chain/src/main.rs b/cita-chain/src/main.rs index afa080b51..56ec6733d 100644 --- a/cita-chain/src/main.rs +++ b/cita-chain/src/main.rs @@ -1,5 +1,5 @@ // CITA -// Copyright 2016-2017 Cryptape Technologies LLC. +// Copyright 2016-2019 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public @@ -66,36 +66,25 @@ //! [`Chain`]: ../core/libchain/chain/struct.Chain.html //! -extern crate byteorder; -extern crate cita_types; -extern crate clap; extern crate common_types as types; -extern crate core; -extern crate dotenv; -extern crate error; -extern crate jsonrpc_types; #[macro_use] extern crate libproto; #[macro_use] -extern crate logger; -extern crate proof; -extern crate pubsub; -extern crate serde_json; +extern crate cita_logger as logger; #[macro_use] extern crate util; -extern crate cita_directories; extern crate db as cita_db; mod block_processor; mod forward; -use block_processor::BlockProcessor; -use cita_db::kvdb::{Database, DatabaseConfig}; +use crate::block_processor::BlockProcessor; +use crate::cita_db::kvdb::{Database, DatabaseConfig}; +use crate::forward::Forward; use cita_directories::DataPath; use clap::App; use core::db; use core::libchain; -use forward::Forward; use libproto::router::{MsgType, RoutingKey, SubModules}; use pubsub::{channel, start_pubsub}; use std::sync::Arc; diff --git a/cita-chain/types/Cargo.toml b/cita-chain/types/Cargo.toml index 9d3e07ef9..31ce19a8f 100644 --- a/cita-chain/types/Cargo.toml +++ b/cita-chain/types/Cargo.toml @@ -3,6 +3,7 @@ name = "common-types" description = "Common types used throughout the codebase" version = "0.1.0" authors = ["Cryptape Technologies "] +edition = "2018" [dependencies] rlp = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } @@ -18,7 +19,7 @@ serde_derive = "1.0" bloomchain = "0.2" lazy_static = "0.2" time = "0.1" -logger = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } +cita-logger = "0.1.0" proof = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } db = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } diff --git a/cita-chain/types/src/basic_types.rs b/cita-chain/types/src/basic_types.rs index d184c32aa..853571df5 100644 --- a/cita-chain/types/src/basic_types.rs +++ b/cita-chain/types/src/basic_types.rs @@ -17,9 +17,9 @@ //! Ethcore basic typenames. /// Type for a 2048-bit log-bloom, as used by our blocks. -pub use log_entry::LogBloom; +pub use crate::log_entry::LogBloom; -pub use log_blooms::LogBloomGroup; +pub use crate::log_blooms::LogBloomGroup; /// Constant 2048-bit datum for 0. Often used as a default. lazy_static! { diff --git a/cita-chain/types/src/block.rs b/cita-chain/types/src/block.rs index 7a32a955b..3d2c8055c 100644 --- a/cita-chain/types/src/block.rs +++ b/cita-chain/types/src/block.rs @@ -15,10 +15,10 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . -use header::{Header, OpenHeader}; +use crate::header::{Header, OpenHeader}; +use crate::extras::TransactionAddress; use cita_types::H256; -use extras::TransactionAddress; use std::collections::HashMap; use libproto::blockchain::{ @@ -27,7 +27,7 @@ use libproto::blockchain::{ use rlp::*; use std::ops::{Deref, DerefMut}; -use transaction::SignedTransaction; +use crate::transaction::SignedTransaction; use util::HeapSizeOf; #[derive(Default, Debug, Clone, PartialEq)] diff --git a/cita-chain/types/src/db.rs b/cita-chain/types/src/db.rs index c008bd411..37d72f023 100644 --- a/cita-chain/types/src/db.rs +++ b/cita-chain/types/src/db.rs @@ -16,7 +16,7 @@ //! Database utilities and definitions. -use cita_db::{DBTransaction, KeyValueDB}; +use crate::cita_db::{DBTransaction, KeyValueDB}; use rlp::{decode, encode, Decodable, Encodable}; use std::collections::HashMap; use std::hash::Hash; diff --git a/cita-chain/types/src/extras.rs b/cita-chain/types/src/extras.rs index d7bab597c..9782c6914 100644 --- a/cita-chain/types/src/extras.rs +++ b/cita-chain/types/src/extras.rs @@ -16,14 +16,14 @@ //! Blockchain DB extras. -use basic_types::LogBloomGroup; -use block::BlockBody; +use crate::basic_types::LogBloomGroup; +use crate::block::BlockBody; +use crate::db::Key; +use crate::header::{BlockNumber, Header}; +use crate::receipt::Receipt; use bloomchain::group::GroupPosition; use cita_types::{H256, H264}; -use db::Key; -use header::{BlockNumber, Header}; use libproto::blockchain::Proof; -use receipt::Receipt; use rlp::*; use std::ops::{Deref, Index}; use util::*; diff --git a/cita-chain/types/src/filter.rs b/cita-chain/types/src/filter.rs index c1efeb994..033f34b4c 100644 --- a/cita-chain/types/src/filter.rs +++ b/cita-chain/types/src/filter.rs @@ -16,11 +16,11 @@ //! Blockchain filter +use crate::ids::BlockId; +use crate::log_entry::{LogBloom, LogEntry}; use cita_types::traits::BloomTools; use cita_types::{Address, H256}; -use ids::BlockId; use jsonrpc_types::rpc_types::{Filter as RpcFilter, VariadicValue}; -use log_entry::{LogBloom, LogEntry}; /// Blockchain Filter. #[derive(Debug, PartialEq)] @@ -159,9 +159,9 @@ impl From for Filter { #[cfg(test)] mod tests { - use filter::Filter; - use ids::BlockId; - use log_entry::{LogBloom, LogEntry}; + use crate::filter::Filter; + use crate::ids::BlockId; + use crate::log_entry::{LogBloom, LogEntry}; #[test] fn test_bloom_possibilities_none() { diff --git a/cita-chain/types/src/header.rs b/cita-chain/types/src/header.rs index b3ea97945..706edb14f 100644 --- a/cita-chain/types/src/header.rs +++ b/cita-chain/types/src/header.rs @@ -17,7 +17,7 @@ //! Block header. -use basic_types::{LogBloom, ZERO_LOGBLOOM}; +use crate::basic_types::{LogBloom, ZERO_LOGBLOOM}; use cita_types::{Address, H256, U256}; use libproto::blockchain::{ Block as ProtoBlock, BlockHeader as ProtoBlockHeader, Proof as ProtoProof, ProofType, @@ -29,9 +29,9 @@ use std::cmp; use std::ops::{Deref, DerefMut}; use time::get_time; +pub use crate::BlockNumber; use hashable::{Hashable, HASH_NULL_RLP}; use util::{Bytes, HeapSizeOf}; -pub use BlockNumber; #[derive(Debug, Clone, Eq)] pub struct OpenHeader { diff --git a/cita-chain/types/src/ids.rs b/cita-chain/types/src/ids.rs index 6ddf1b408..0b92316ec 100644 --- a/cita-chain/types/src/ids.rs +++ b/cita-chain/types/src/ids.rs @@ -16,9 +16,9 @@ //! Unique identifiers. +use crate::BlockNumber; use cita_types::H256; use jsonrpc_types::rpc_types::{BlockNumber as RpcBlockNumber, BlockTag}; -use BlockNumber; /// Uniquely identifies block. #[derive(Debug, PartialEq, Copy, Clone, Hash, Eq)] diff --git a/cita-chain/types/src/lib.rs b/cita-chain/types/src/lib.rs index 972f21568..a446c9c85 100644 --- a/cita-chain/types/src/lib.rs +++ b/cita-chain/types/src/lib.rs @@ -1,5 +1,5 @@ // CITA -// Copyright 2016-2017 Cryptape Technologies LLC. +// Copyright 2016-2019 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public @@ -16,23 +16,15 @@ // along with this program. If not, see . extern crate cita_crypto as crypto; -extern crate cita_types; -extern crate hashable; -extern crate jsonrpc_types; -extern crate libproto; -extern crate rlp; #[macro_use] extern crate rlp_derive; #[macro_use] extern crate serde_derive; -extern crate util; #[macro_use] extern crate lazy_static; -extern crate time; #[macro_use] -extern crate logger; +extern crate cita_logger as logger; extern crate db as cita_db; -extern crate proof; pub extern crate bloomchain; diff --git a/cita-chain/types/src/log_blooms.rs b/cita-chain/types/src/log_blooms.rs index 41c020e43..21087926a 100644 --- a/cita-chain/types/src/log_blooms.rs +++ b/cita-chain/types/src/log_blooms.rs @@ -16,9 +16,9 @@ //! Bridge between bloomchain crate types and cita LogBloom. +use crate::log_entry::LogBloom; use bloomchain::group::BloomGroup; use bloomchain::Bloom; -use log_entry::LogBloom; use rlp::*; use util::HeapSizeOf; diff --git a/cita-chain/types/src/log_entry.rs b/cita-chain/types/src/log_entry.rs index 0973a0436..0cfc4c409 100644 --- a/cita-chain/types/src/log_entry.rs +++ b/cita-chain/types/src/log_entry.rs @@ -16,6 +16,7 @@ //! Log entry type definition. +use crate::BlockNumber; use cita_types::traits::BloomTools; use cita_types::{Address, Bloom, H256}; use jsonrpc_types::rpc_types::Log as RpcLog; @@ -23,7 +24,6 @@ use libproto::executor::LogEntry as ProtoLogEntry; use rlp::*; use std::ops::Deref; use util::{Bytes, HeapSizeOf}; -use BlockNumber; pub type LogBloom = Bloom; diff --git a/cita-chain/types/src/receipt.rs b/cita-chain/types/src/receipt.rs index cfbd7a152..8d7a5d0ee 100644 --- a/cita-chain/types/src/receipt.rs +++ b/cita-chain/types/src/receipt.rs @@ -16,17 +16,17 @@ //! Receipt +use crate::log_entry::{LocalizedLogEntry, LogBloom, LogEntry}; +use crate::BlockNumber; use cita_types::traits::LowerHex; use cita_types::{Address, H256, U256}; use jsonrpc_types::rpc_types::Receipt as RpcReceipt; use libproto::executor::{ Receipt as ProtoReceipt, ReceiptError as ProtoReceiptError, ReceiptErrorWithOption, StateRoot, }; -use log_entry::{LocalizedLogEntry, LogBloom, LogEntry}; use rlp::*; use std::str::FromStr; use util::{Bytes, HeapSizeOf}; -use BlockNumber; #[derive(Serialize, Deserialize, Debug, PartialEq, Clone, Copy, Eq)] pub enum ReceiptError { @@ -385,7 +385,7 @@ impl Into for LocalizedReceipt { #[cfg(test)] mod tests { use super::*; - use log_entry::LogEntry; + use crate::log_entry::LogEntry; #[test] fn test_no_state_root() { diff --git a/cita-chain/types/src/reserved_addresses.rs b/cita-chain/types/src/reserved_addresses.rs index 40289104d..7b80bc51e 100644 --- a/cita-chain/types/src/reserved_addresses.rs +++ b/cita-chain/types/src/reserved_addresses.rs @@ -1,5 +1,5 @@ // CITA -// Copyright 2016-2018 Cryptape Technologies LLC. +// Copyright 2016-2019 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public @@ -103,7 +103,7 @@ pub const GROUP_CREATOR: &str = "ffffffffffffffffffffffffffffffffff02000b"; pub const ADMIN: &str = "ffffffffffffffffffffffffffffffffff02000c"; pub const ROLE_AUTH: &str = "ffffffffffffffffffffffffffffffffff02000d"; pub const BATCH_TX: &str = "ffffffffffffffffffffffffffffffffff02000e"; -pub const EMERGENCY_BRAKE: &str = "ffffffffffffffffffffffffffffffffff02000f"; +pub const EMERGENCY_INTERVENTION: &str = "ffffffffffffffffffffffffffffffffff02000f"; pub const PRICE_MANAGEMENT: &str = "ffffffffffffffffffffffffffffffffff020010"; pub const VERSION_MANAGEMENT: &str = "ffffffffffffffffffffffffffffffffff020011"; pub const ALL_GROUPS: &str = "ffffffffffffffffffffffffffffffffff020012"; @@ -130,7 +130,7 @@ pub const PERMISSION_UPDATE_NODE: &str = "ffffffffffffffffffffffffffffffffff0210 pub const PERMISSION_ACCOUNT_QUOTA: &str = "ffffffffffffffffffffffffffffffffff021023"; pub const PERMISSION_BLOCK_QUOTA: &str = "ffffffffffffffffffffffffffffffffff021024"; pub const PERMISSION_BATCH_TX: &str = "ffffffffffffffffffffffffffffffffff021025"; -pub const PERMISSION_EMERGENCY_BRAKE: &str = "ffffffffffffffffffffffffffffffffff021026"; +pub const PERMISSION_EMERGENCY_INTERVENTION: &str = "ffffffffffffffffffffffffffffffffff021026"; pub const PERMISSION_QUOTA_PRICE: &str = "ffffffffffffffffffffffffffffffffff021027"; pub const PERMISSION_VERSION: &str = "ffffffffffffffffffffffffffffffffff021028"; diff --git a/cita-chain/types/src/state_diff.rs b/cita-chain/types/src/state_diff.rs index 9d7f4a4b7..6202f9cb8 100644 --- a/cita-chain/types/src/state_diff.rs +++ b/cita-chain/types/src/state_diff.rs @@ -16,7 +16,7 @@ //! State diff module. -use account_diff::*; +use crate::account_diff::*; use cita_types::Address; use std::collections::BTreeMap; use std::fmt; diff --git a/cita-chain/types/src/transaction.rs b/cita-chain/types/src/transaction.rs index b9a94c8a9..0f2ebbc03 100644 --- a/cita-chain/types/src/transaction.rs +++ b/cita-chain/types/src/transaction.rs @@ -15,21 +15,21 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . -use cita_types::traits::LowerHex; -use cita_types::{clean_0x, Address, H256, U256}; -use crypto::{ +use crate::crypto::{ pubkey_to_address, PubKey, Signature, HASH_BYTES_LEN, PUBKEY_BYTES_LEN, SIGNATURE_BYTES_LEN, }; +use crate::reserved_addresses::{ABI_ADDRESS, AMEND_ADDRESS, GO_CONTRACT, STORE_ADDRESS}; +use crate::BlockNumber; +use cita_types::traits::LowerHex; +use cita_types::{clean_0x, Address, H256, U256}; use libproto::blockchain::{ Crypto as ProtoCrypto, SignedTransaction as ProtoSignedTransaction, Transaction as ProtoTransaction, UnverifiedTransaction as ProtoUnverifiedTransaction, }; -use reserved_addresses::{ABI_ADDRESS, AMEND_ADDRESS, GO_CONTRACT, STORE_ADDRESS}; use rlp::*; use std::ops::{Deref, DerefMut}; use std::str::FromStr; use util::{Bytes, HeapSizeOf}; -use BlockNumber; #[derive(Debug, PartialEq, Clone)] pub enum Error { diff --git a/cita-executor/Cargo.toml b/cita-executor/Cargo.toml index 6138034fc..7ee943bc5 100644 --- a/cita-executor/Cargo.toml +++ b/cita-executor/Cargo.toml @@ -2,6 +2,7 @@ name = "cita-executor" version = "0.1.0" authors = ["Cryptape Technologies "] +edition = "2018" [dependencies] dotenv = "0.13.0" @@ -11,11 +12,11 @@ crossbeam-channel = "0.2" serde_json = "1.0" serde_derive = "1.0" grpc = "0.5.0" +cita-logger = "0.1.0" cita-types = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } cita-directories = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } hashable = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } util = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } -logger = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } pubsub = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } libproto = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } error = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } diff --git a/cita-executor/build.rs b/cita-executor/build.rs index a0533082a..14aad7c92 100644 --- a/cita-executor/build.rs +++ b/cita-executor/build.rs @@ -1,5 +1,5 @@ // CITA -// Copyright 2016-2018 Cryptape Technologies LLC. +// Copyright 2016-2019 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public @@ -15,10 +15,7 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . -extern crate util; - use std::env; - use util::build_info::gen_build_info; fn main() { diff --git a/cita-executor/core/Cargo.toml b/cita-executor/core/Cargo.toml index 09afa732e..c136610e4 100644 --- a/cita-executor/core/Cargo.toml +++ b/cita-executor/core/Cargo.toml @@ -2,11 +2,12 @@ name = "core-executor" version = "0.1.0" authors = ["Parity Technologies ", "Cryptape Technologies "] +edition = "2018" [dependencies] +cita-logger = "0.1.0" libproto = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } byteorder = { version = "1", default-features = false } -logger = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } cita-merklehash = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } snappy = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } hashable = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } @@ -28,6 +29,7 @@ rust-crypto = "0.2.34" num = "0.1" rand = "0.3" time = "0.1" +hex = "0.3" crossbeam = "0.2" crossbeam-channel = "0.2" transient-hashmap = "0.4.0" diff --git a/cita-executor/core/src/account_db.rs b/cita-executor/core/src/account_db.rs index a71393767..fc96650a5 100644 --- a/cita-executor/core/src/account_db.rs +++ b/cita-executor/core/src/account_db.rs @@ -16,7 +16,7 @@ //! DB backend wrapper for Account trie -use cita_db::{DBValue, HashDB}; +use crate::cita_db::{DBValue, HashDB}; use cita_types::{Address, H256}; use hashable::{Hashable, HASH_NULL_RLP}; use rlp::NULL_RLP; diff --git a/cita-executor/core/src/authentication.rs b/cita-executor/core/src/authentication.rs index 42250b184..0fe94543f 100644 --- a/cita-executor/core/src/authentication.rs +++ b/cita-executor/core/src/authentication.rs @@ -15,14 +15,14 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . +use crate::contracts::solc::{permission_management::contains_resource, Resource}; +use crate::executed::ExecutionError; +use crate::libexecutor::sys_config::CheckOptions; +use crate::types::reserved_addresses; +use crate::types::transaction::{Action, SignedTransaction}; use cita_types::{Address, H160}; -use contracts::solc::{permission_management::contains_resource, Resource}; -use executed::ExecutionError; -use libexecutor::sys_config::CheckOptions; use std::collections::HashMap; use std::str::FromStr; -use types::reserved_addresses; -use types::transaction::{Action, SignedTransaction}; /// Check the sender's permission #[allow(unknown_lints, clippy::implicit_hasher)] // TODO clippy diff --git a/cita-executor/core/src/benches/executor.rs b/cita-executor/core/src/benches/executor.rs index 892a98516..c4cce0b07 100644 --- a/cita-executor/core/src/benches/executor.rs +++ b/cita-executor/core/src/benches/executor.rs @@ -1,5 +1,5 @@ // CITA -// Copyright 2016-2018 Cryptape Technologies LLC. +// Copyright 2016-2019 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public @@ -34,7 +34,7 @@ fn generate_block(executor: &Executor, txs: u32) -> OpenBlock { #[bench] fn test_block_with_10000_tx(b: &mut Bencher) { // One block with 10000 tx bench test takes 271.51ms - let mut executor = helpers::init_executor(vec![]); + let mut executor = helpers::init_executor(); let block = generate_block(&executor, 10000); b.iter(|| { @@ -45,7 +45,7 @@ fn test_block_with_10000_tx(b: &mut Bencher) { #[bench] fn test_block_with_30000_tx(b: &mut Bencher) { // One block with 30000 tx bench test takes 886.39ms - let mut executor = helpers::init_executor(vec![]); + let mut executor = helpers::init_executor(); let block = generate_block(&executor, 30000); b.iter(|| { @@ -56,7 +56,7 @@ fn test_block_with_30000_tx(b: &mut Bencher) { #[bench] fn test_block_with_50000_tx(b: &mut Bencher) { // One block with 50000 tx bench test takes 1424.51ms - let mut executor = helpers::init_executor(vec![]); + let mut executor = helpers::init_executor(); let block = generate_block(&executor, 50000); b.iter(|| { @@ -67,7 +67,7 @@ fn test_block_with_50000_tx(b: &mut Bencher) { #[bench] fn test_block_with_10000_tx_write_db(b: &mut Bencher) { // One block with 10000 tx bench test takes 1551.8ms - let mut executor = helpers::init_executor(vec![]); + let mut executor = helpers::init_executor(); let block = generate_block(&executor, 10000); b.iter(|| { diff --git a/cita-executor/core/src/benches/mod.rs b/cita-executor/core/src/benches/mod.rs index 457064991..0db48a3da 100644 --- a/cita-executor/core/src/benches/mod.rs +++ b/cita-executor/core/src/benches/mod.rs @@ -1,5 +1,5 @@ // CITA -// Copyright 2016-2018 Cryptape Technologies LLC. +// Copyright 2016-2019 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public diff --git a/cita-executor/core/src/builtin.rs b/cita-executor/core/src/builtin.rs index 22c74cf5a..e03081a9d 100644 --- a/cita-executor/core/src/builtin.rs +++ b/cita-executor/core/src/builtin.rs @@ -14,6 +14,7 @@ // You should have received a copy of the GNU General Public License // along with Parity. If not, see . +use crate::spec; use cita_crypto_trait::Sign; use cita_ed25519::{Message as ED_Message, Signature as ED_Signature}; use cita_secp256k1::Signature; @@ -22,7 +23,6 @@ use crypto::digest::Digest; use crypto::ripemd160::Ripemd160 as Ripemd160Digest; use crypto::sha2::Sha256 as Sha256Digest; use hashable::Hashable; -use spec; use std::cmp::min; use util::BytesRef; @@ -206,10 +206,10 @@ mod tests { extern crate rustc_serialize; use super::{ethereum_builtin, Builtin, Linear, Pricer}; + use crate::spec; use cita_crypto_trait::{CreateKey, Sign}; use cita_ed25519::{pubkey_to_address as ED_pubkey_to_address, KeyPair, Signature}; use cita_types::{H256, U256}; - use spec; use util::BytesRef; #[test] diff --git a/cita-executor/core/src/contracts/grpc/contract.rs b/cita-executor/core/src/contracts/grpc/contract.rs index 62cb8ad5f..b741fcad3 100644 --- a/cita-executor/core/src/contracts/grpc/contract.rs +++ b/cita-executor/core/src/contracts/grpc/contract.rs @@ -1,5 +1,5 @@ // CITA -// Copyright 2016-2018 Cryptape Technologies LLC. +// Copyright 2016-2019 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public @@ -15,19 +15,19 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . +use crate::contracts::grpc::{contract_state::ConnectInfo, grpc_vm::CallEvmImpl}; +use crate::state::backend::Backend as StateBackend; +use crate::state::State; +use crate::types::reserved_addresses; use cita_types::traits::LowerHex; use cita_types::Address; -use contracts::grpc::{contract_state::ConnectInfo, grpc_vm::CallEvmImpl}; use evm::action_params::ActionParams; use evm::env_info::EnvInfo; use grpc::Result as GrpcResult; use libproto::citacode::{ ActionParams as ProtoActionParams, EnvInfo as ProtoEnvInfo, InvokeRequest, InvokeResponse, }; -use state::backend::Backend as StateBackend; -use state::State; use std::str::FromStr; -use types::reserved_addresses; lazy_static! { static ref CONTRACT_CREATION_ADDRESS: Address = diff --git a/cita-executor/core/src/contracts/grpc/contract_state.rs b/cita-executor/core/src/contracts/grpc/contract_state.rs index d45e18b2b..65efa3e2b 100644 --- a/cita-executor/core/src/contracts/grpc/contract_state.rs +++ b/cita-executor/core/src/contracts/grpc/contract_state.rs @@ -1,5 +1,5 @@ // CITA -// Copyright 2016-2018 Cryptape Technologies LLC. +// Copyright 2016-2019 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public @@ -15,8 +15,8 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . +use crate::db::Key; use cita_types::{Address, H160}; -use db::Key; use rlp::*; use std::str::FromStr; use util::*; diff --git a/cita-executor/core/src/contracts/grpc/grpc_vm.rs b/cita-executor/core/src/contracts/grpc/grpc_vm.rs index 11296aa76..495281d9e 100644 --- a/cita-executor/core/src/contracts/grpc/grpc_vm.rs +++ b/cita-executor/core/src/contracts/grpc/grpc_vm.rs @@ -1,5 +1,5 @@ // CITA -// Copyright 2016-2018 Cryptape Technologies LLC. +// Copyright 2016-2019 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public @@ -15,28 +15,28 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . -use authentication::check_permission; +use crate::authentication::check_permission; +use crate::db::{self as db, Writable}; +use crate::error::{Error, ExecutionError}; +use crate::libexecutor::sys_config::BlockSysConfig; use cita_types::traits::LowerHex; use cita_types::{Address, H256, U256}; -use db::{self as db, Writable}; -use error::{Error, ExecutionError}; use grpc::Result as GrpcResult; -use libexecutor::sys_config::BlockSysConfig; -use contracts::grpc::{ +use crate::contracts::grpc::{ contract_state::{ConnectInfo, ContractState}, service_registry, }; -use libexecutor::executor::Executor; +use crate::libexecutor::executor::Executor; +use crate::log_entry::LogEntry; +use crate::receipt::Receipt; +use crate::state::backend::Backend as StateBackend; +use crate::state::State; +use crate::types::transaction::{Action, SignedTransaction}; use libproto::citacode::{ActionParams, EnvInfo, InvokeRequest, InvokeResponse}; use libproto::citacode_grpc::{CitacodeService, CitacodeServiceClient}; -use log_entry::LogEntry; -use receipt::Receipt; -use state::backend::Backend as StateBackend; -use state::State; use std::error::Error as StdError; use std::str::FromStr; -use types::transaction::{Action, SignedTransaction}; use util::Bytes; pub fn extract_logs_from_response(sender: Address, response: &InvokeResponse) -> Vec { diff --git a/cita-executor/core/src/contracts/grpc/grpc_vm_adapter.rs b/cita-executor/core/src/contracts/grpc/grpc_vm_adapter.rs index c15096afa..7650cee2f 100644 --- a/cita-executor/core/src/contracts/grpc/grpc_vm_adapter.rs +++ b/cita-executor/core/src/contracts/grpc/grpc_vm_adapter.rs @@ -1,5 +1,5 @@ // CITA -// Copyright 2016-2018 Cryptape Technologies LLC. +// Copyright 2016-2019 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public @@ -15,17 +15,17 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . +use crate::contracts::grpc::service_registry; +use crate::libexecutor::command; +use crate::types::ids::BlockId; use cita_types::{Address, H256, U256}; -use contracts::grpc::service_registry; use crossbeam_channel::{Receiver, Sender}; use grpc::Server; -use libexecutor::command; use libproto::executor::{LoadRequest, LoadResponse, RegisterRequest, RegisterResponse}; use libproto::executor_grpc::{ExecutorService, ExecutorServiceServer}; use std::str::FromStr; use std::thread; use std::time::Duration; -use types::ids::BlockId; pub struct ExecutorServiceImpl { command_req_sender: Sender, @@ -33,7 +33,6 @@ pub struct ExecutorServiceImpl { } impl ExecutorService for ExecutorServiceImpl { - // add code here fn register( &self, _o: ::grpc::RequestOptions, diff --git a/cita-executor/core/src/contracts/grpc/mod.rs b/cita-executor/core/src/contracts/grpc/mod.rs index 4ddf5d3e3..796f2a246 100644 --- a/cita-executor/core/src/contracts/grpc/mod.rs +++ b/cita-executor/core/src/contracts/grpc/mod.rs @@ -1,5 +1,5 @@ // CITA -// Copyright 2016-2018 Cryptape Technologies LLC. +// Copyright 2016-2019 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public diff --git a/cita-executor/core/src/contracts/grpc/service_registry.rs b/cita-executor/core/src/contracts/grpc/service_registry.rs index a185e6a4f..118ef1ac1 100644 --- a/cita-executor/core/src/contracts/grpc/service_registry.rs +++ b/cita-executor/core/src/contracts/grpc/service_registry.rs @@ -1,5 +1,5 @@ // CITA -// Copyright 2016-2018 Cryptape Technologies LLC. +// Copyright 2016-2019 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public @@ -15,9 +15,9 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . +use crate::contracts::grpc::contract_state::ContractState; use cita_types::traits::LowerHex; use cita_types::Address; -use contracts::grpc::contract_state::ContractState; use std::collections::HashMap; use std::sync::Mutex; use util::RwLock; diff --git a/cita-executor/core/src/contracts/grpc/storage.rs b/cita-executor/core/src/contracts/grpc/storage.rs index 21a1115d7..d567d67d4 100644 --- a/cita-executor/core/src/contracts/grpc/storage.rs +++ b/cita-executor/core/src/contracts/grpc/storage.rs @@ -1,5 +1,5 @@ // CITA -// Copyright 2016-2018 Cryptape Technologies LLC. +// Copyright 2016-2019 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public @@ -15,10 +15,10 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . -use cita_db::trie; +use crate::cita_db::trie; +use crate::state::backend::Backend; +use crate::state::State; use cita_types::{Address, H256, U256}; -use state::backend::Backend; -use state::State; pub fn set_storage( state: &mut State, diff --git a/cita-executor/core/src/contracts/native/crosschain_verify.rs b/cita-executor/core/src/contracts/native/crosschain_verify.rs index 191294ff1..40e131c6d 100644 --- a/cita-executor/core/src/contracts/native/crosschain_verify.rs +++ b/cita-executor/core/src/contracts/native/crosschain_verify.rs @@ -15,15 +15,17 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . +use crate::contracts::{ + native::factory::Contract, solc::ChainManagement, tools::method as method_tools, +}; +use crate::state::StateProof; use cita_types::{Address, H256, U256}; -use contracts::{native::factory::Contract, solc::ChainManagement, tools::method as method_tools}; use core::header::Header; use core::libchain::chain::TxProof; use ethabi; use evm::action_params::ActionParams; use evm::storage::Map; use evm::{Error, Ext, GasLeft, ReturnData}; -use state::StateProof; lazy_static! { static ref VERIFY_TRANSACTION_FUNC: u32 = diff --git a/cita-executor/core/src/contracts/native/factory.rs b/cita-executor/core/src/contracts/native/factory.rs index 5219fe297..e41e5abb0 100644 --- a/cita-executor/core/src/contracts/native/factory.rs +++ b/cita-executor/core/src/contracts/native/factory.rs @@ -15,12 +15,12 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . +use crate::types::reserved_addresses; use cita_types::Address; use evm::action_params::ActionParams; use evm::{self, Ext, GasLeft}; use std::collections::HashMap; use std::str::FromStr; -use types::reserved_addresses; //////////////////////////////////////////////////////////////////////////////// pub type Signature = u32; diff --git a/cita-executor/core/src/contracts/native/storage.rs b/cita-executor/core/src/contracts/native/storage.rs index 60597c2ac..0147224c4 100644 --- a/cita-executor/core/src/contracts/native/storage.rs +++ b/cita-executor/core/src/contracts/native/storage.rs @@ -18,14 +18,14 @@ use self::bincode::internal::serialize_into; use self::bincode::Infinite; use super::factory::{Contract, Factory}; +use crate::contracts::tools::method as method_tools; +use crate::types::reserved_addresses; use bincode; use cita_types::{Address, H256, U256}; -use contracts::tools::method as method_tools; use evm; use evm::fake_tests::FakeExt; use std::io::Write; use std::str::FromStr; -use types::reserved_addresses; use byteorder::BigEndian; use evm::action_params::ActionParams; diff --git a/cita-executor/core/src/contracts/solc/admin.rs b/cita-executor/core/src/contracts/solc/admin.rs new file mode 100644 index 000000000..49b1348ec --- /dev/null +++ b/cita-executor/core/src/contracts/solc/admin.rs @@ -0,0 +1,68 @@ +// CITA +// Copyright 2016-2019 Cryptape Technologies LLC. + +// This program is free software: you can redistribute it +// and/or modify it under the terms of the GNU General Public +// License as published by the Free Software Foundation, +// either version 3 of the License, or (at your option) any +// later version. + +// This program is distributed in the hope that it will be +// useful, but WITHOUT ANY WARRANTY; without even the implied +// warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +// PURPOSE. See the GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . + +//! Get Admin Info + +use super::ContractCallExt; +use crate::contracts::tools::{decode as decode_tools, method as method_tools}; +use crate::libexecutor::executor::Executor; +use crate::types::ids::BlockId; +use crate::types::reserved_addresses; +use cita_types::Address; +use std::str::FromStr; + +lazy_static! { + static ref GET_ADMIN: Vec = method_tools::encode_to_vec(b"admin()"); + static ref CONTRACT_ADDRESS: Address = Address::from_str(reserved_addresses::ADMIN).unwrap(); +} + +pub struct Admin<'a> { + executor: &'a Executor, +} + +impl<'a> Admin<'a> { + pub fn new(executor: &'a Executor) -> Self { + Admin { executor } + } + + /// Get Admin + pub fn get_admin(&self, block_id: BlockId) -> Option
{ + self.executor + .call_method(&*CONTRACT_ADDRESS, &*GET_ADMIN.as_slice(), None, block_id) + .ok() + .and_then(|output| decode_tools::to_address(&output)) + } +} + +#[cfg(test)] +mod tests { + use super::Admin; + use crate::tests::helpers::init_executor; + use crate::types::ids::BlockId; + use cita_types::Address; + + #[test] + fn test_admin() { + let executor = init_executor(); + let admin = Admin::new(&executor); + let addr = admin.get_admin(BlockId::Pending).unwrap(); + assert_eq!( + addr, + Address::from("0x4b5ae4567ad5d9fb92bc9afd6a657e6fa13a2523") + ); + } +} diff --git a/cita-executor/core/src/contracts/solc/chain_manager.rs b/cita-executor/core/src/contracts/solc/chain_manager.rs index fe5fefb35..37d75ee8b 100644 --- a/cita-executor/core/src/contracts/solc/chain_manager.rs +++ b/cita-executor/core/src/contracts/solc/chain_manager.rs @@ -17,12 +17,12 @@ //! Chain manager. +use crate::contracts::tools::{decode as decode_tools, method as method_tools}; +use crate::types::reserved_addresses; use cita_types::{Address, H160, H256, U256}; -use contracts::tools::{decode as decode_tools, method as method_tools}; use evm::call_type::CallType; use evm::ext::{Ext, MessageCallResult}; use std::str::FromStr; -use types::reserved_addresses; const CHAIN_ID: &[u8] = &*b"getChainId()"; const AUTHORITIES: &[u8] = &*b"getAuthorities(uint256)"; diff --git a/cita-executor/core/src/contracts/solc/emergency_brake.rs b/cita-executor/core/src/contracts/solc/emergency_intervention.rs similarity index 66% rename from cita-executor/core/src/contracts/solc/emergency_brake.rs rename to cita-executor/core/src/contracts/solc/emergency_intervention.rs index 32ff319eb..211a5c4dc 100644 --- a/cita-executor/core/src/contracts/solc/emergency_brake.rs +++ b/cita-executor/core/src/contracts/solc/emergency_intervention.rs @@ -1,5 +1,5 @@ // CITA -// Copyright 2016-2018 Cryptape Technologies LLC. +// Copyright 2016-2019 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public @@ -15,33 +15,33 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . -//! Emergency Break +//! Emergency Intervention use std::str::FromStr; use super::ContractCallExt; -use contracts::tools::method as method_tools; -use libexecutor::executor::Executor; +use crate::contracts::tools::method as method_tools; +use crate::libexecutor::executor::Executor; +use crate::types::ids::BlockId; +use crate::types::reserved_addresses; use cita_types::Address; use ethabi::{decode, ParamType}; -use types::ids::BlockId; -use types::reserved_addresses; lazy_static! { static ref STATE_HASH: Vec = method_tools::encode_to_vec(b"state()"); static ref CONTRACT_ADDRESS: Address = - Address::from_str(reserved_addresses::EMERGENCY_BRAKE).unwrap(); + Address::from_str(reserved_addresses::EMERGENCY_INTERVENTION).unwrap(); } /// Configuration items from system contract -pub struct EmergencyBrake<'a> { +pub struct EmergencyIntervention<'a> { executor: &'a Executor, } -impl<'a> EmergencyBrake<'a> { +impl<'a> EmergencyIntervention<'a> { pub fn new(executor: &'a Executor) -> Self { - EmergencyBrake { executor } + EmergencyIntervention { executor } } pub fn state(&self, block_id: BlockId) -> Option { @@ -55,22 +55,22 @@ impl<'a> EmergencyBrake<'a> { } pub fn default_state() -> bool { - info!("Use default emergency break state."); + info!("Use default emergency intervention state."); false } } #[cfg(test)] mod tests { - use super::EmergencyBrake; - use tests::helpers::init_executor; - use types::ids::BlockId; + use super::EmergencyIntervention; + use crate::tests::helpers::init_executor; + use crate::types::ids::BlockId; #[test] fn test_state() { - let executor = init_executor(vec![]); - let emergency_brake = EmergencyBrake::new(&executor); - let state = emergency_brake.state(BlockId::Pending).unwrap(); + let executor = init_executor(); + let emergency_intervention = EmergencyIntervention::new(&executor); + let state = emergency_intervention.state(BlockId::Pending).unwrap(); assert_eq!(state, false); } } diff --git a/cita-executor/core/src/contracts/solc/mod.rs b/cita-executor/core/src/contracts/solc/mod.rs index 3c9478dae..f6a4fae51 100644 --- a/cita-executor/core/src/contracts/solc/mod.rs +++ b/cita-executor/core/src/contracts/solc/mod.rs @@ -1,5 +1,5 @@ // CITA -// Copyright 2016-2017 Cryptape Technologies LLC. +// Copyright 2016-2019 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public @@ -17,8 +17,9 @@ //! System contracts. +pub mod admin; pub mod chain_manager; -pub mod emergency_brake; +pub mod emergency_intervention; pub mod node_manager; pub mod permission_management; pub mod price_manager; @@ -28,7 +29,7 @@ pub mod user_management; pub mod version_management; pub use self::chain_manager::ChainManagement; -pub use self::emergency_brake::EmergencyBrake; +pub use self::emergency_intervention::EmergencyIntervention; pub use self::node_manager::NodeManager; pub use self::permission_management::{PermissionManagement, Resource}; pub use self::price_manager::PriceManagement; @@ -37,11 +38,11 @@ pub use self::sys_config::SysConfig; pub use self::user_management::UserManagement; pub use self::version_management::VersionManager; +use crate::libexecutor::call_request::CallRequest; +use crate::libexecutor::command::Commander; +use crate::libexecutor::executor::Executor; +use crate::types::ids::BlockId; use cita_types::Address; -use libexecutor::call_request::CallRequest; -use libexecutor::command::Commander; -use libexecutor::executor::Executor; -use types::ids::BlockId; use util::Bytes; /// Extend `Executor` with some methods related to contract diff --git a/cita-executor/core/src/contracts/solc/node_manager.rs b/cita-executor/core/src/contracts/solc/node_manager.rs index 8e2644125..fb24b0340 100644 --- a/cita-executor/core/src/contracts/solc/node_manager.rs +++ b/cita-executor/core/src/contracts/solc/node_manager.rs @@ -1,5 +1,5 @@ // CITA -// Copyright 2016-2017 Cryptape Technologies LLC. +// Copyright 2016-2019 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public @@ -18,16 +18,16 @@ //! Node manager. use super::ContractCallExt; +use crate::contracts::tools::{decode as decode_tools, method as method_tools}; +use crate::libexecutor::economical_model::EconomicalModel; +use crate::libexecutor::executor::Executor; +use crate::types::ids::BlockId; +use crate::types::reserved_addresses; use cita_types::{Address, H160}; -use contracts::tools::{decode as decode_tools, method as method_tools}; use largest_remainder_method::apportion; -use libexecutor::economical_model::EconomicalModel; -use libexecutor::executor::Executor; use rand::{Rng, SeedableRng, StdRng}; use std::iter; use std::str::FromStr; -use types::ids::BlockId; -use types::reserved_addresses; const LIST_NODE: &[u8] = &*b"listNode()"; const LIST_STAKE: &[u8] = &*b"listStake()"; @@ -134,41 +134,8 @@ impl<'a> NodeManager<'a> { #[cfg(test)] mod tests { - extern crate logger; - - use super::{party_seats, shuffle, NodeManager}; - use cita_types::H160; - use std::str::FromStr; - use tests::helpers::init_executor; - use types::ids::BlockId; - - #[test] - fn test_node_manager_contract() { - let executor = init_executor(vec![ - ( - "NodeManager.nodes", - concat!( - "0x50ad2b9d6946d9c75ae978534043e3021ee1bfb1,", - "0xeeb3a71c4046f63a941013f826fccc503be26b77,", - "0xa2bbb65d4f8c3ada29f7471abe416e18061127f3,", - "0x72eb1e258c9cdccebb7b62930a35cfb6ef4cd24b" - ), - ), - ("NodeManager.stakes", "1,1,1,1"), - ]); - let node_manager = NodeManager::new(&executor, executor.genesis_header().timestamp()); - let nodes = node_manager.nodes(BlockId::Pending).unwrap(); - - assert_eq!( - nodes, - vec![ - H160::from_str("50ad2b9d6946d9c75ae978534043e3021ee1bfb1").unwrap(), - H160::from_str("eeb3a71c4046f63a941013f826fccc503be26b77").unwrap(), - H160::from_str("a2bbb65d4f8c3ada29f7471abe416e18061127f3").unwrap(), - H160::from_str("72eb1e258c9cdccebb7b62930a35cfb6ef4cd24b").unwrap(), - ] - ) - } + extern crate cita_logger as logger; + use super::{party_seats, shuffle}; #[test] fn test_party_seats() { diff --git a/cita-executor/core/src/contracts/solc/permission_management.rs b/cita-executor/core/src/contracts/solc/permission_management.rs index 6b6e2f980..120b91e56 100644 --- a/cita-executor/core/src/contracts/solc/permission_management.rs +++ b/cita-executor/core/src/contracts/solc/permission_management.rs @@ -1,5 +1,5 @@ // CITA -// Copyright 2016-2017 Cryptape Technologies LLC. +// Copyright 2016-2019 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public @@ -17,19 +17,19 @@ //! Permission management. use super::ContractCallExt; +use crate::contracts::tools::{decode as decode_tools, method as method_tools}; +use crate::libexecutor::executor::Executor; +use crate::types::ids::BlockId; +use crate::types::reserved_addresses; use cita_types::{Address, H160, H256}; -use contracts::tools::{decode as decode_tools, method as method_tools}; -use libexecutor::executor::Executor; use std::collections::HashMap; use std::str::FromStr; -use types::ids::BlockId; -use types::reserved_addresses; const ALLACCOUNTS: &[u8] = &*b"queryAllAccounts()"; const PERMISSIONS: &[u8] = &*b"queryPermissions(address)"; const RESOURCES: &[u8] = &*b"queryResource()"; #[cfg(test)] -const DEFAULT_SUPER_ADEMIN: &str = "4b5ae4567ad5d9fb92bc9afd6a657e6fa1300000"; +const DEFAULT_SUPER_ADEMIN: &str = "4b5ae4567ad5d9fb92bc9afd6a657e6fa13a2523"; lazy_static! { static ref ALLACCOUNTS_HASH: Vec = method_tools::encode_to_vec(ALLACCOUNTS); @@ -182,17 +182,17 @@ pub fn contains_resource( #[cfg(test)] mod tests { - extern crate logger; + extern crate cita_logger as logger; use super::contains_resource; use super::{PermissionManagement, Resource, DEFAULT_SUPER_ADEMIN}; + use crate::contracts::tools::method as method_tools; + use crate::tests::helpers::init_executor; + use crate::types::ids::BlockId; + use crate::types::reserved_addresses; use cita_types::{Address, H160, H256}; - use contracts::tools::method as method_tools; use std::collections::HashMap; use std::str::FromStr; - use tests::helpers::init_executor; - use types::ids::BlockId; - use types::reserved_addresses; const NEW_PERMISSION: &[u8] = &*b"newPermission(bytes32,address[],bytes4[])"; const DELETE_PERMISSION: &[u8] = &*b"deletePermission(address)"; @@ -227,6 +227,7 @@ mod tests { const SET_STATE: &[u8] = &*b"setState(bool)"; const SET_QUOTA_PRICE: &[u8] = &*b"setQuotaPrice(uint256)"; const SET_VERSION: &[u8] = &*b"setVersion(uint32)"; + const SET_PROTOCOL_VERSION: &[u8] = &*b"setProtocolVersion(uint32)"; #[test] fn test_contains_resource() { @@ -280,10 +281,7 @@ mod tests { #[test] fn test_solc() { - let executor = init_executor(vec![( - "Authorization.superAdmin", - &format!("0x{}", DEFAULT_SUPER_ADEMIN), - )]); + let executor = init_executor(); // Test all_accounts let permission_management = PermissionManagement::new(&executor); @@ -329,7 +327,7 @@ mod tests { Address::from_str(reserved_addresses::PERMISSION_ACCOUNT_QUOTA).unwrap(), Address::from_str(reserved_addresses::PERMISSION_BLOCK_QUOTA).unwrap(), Address::from_str(reserved_addresses::PERMISSION_BATCH_TX).unwrap(), - Address::from_str(reserved_addresses::PERMISSION_EMERGENCY_BRAKE).unwrap(), + Address::from_str(reserved_addresses::PERMISSION_EMERGENCY_INTERVENTION).unwrap(), Address::from_str(reserved_addresses::PERMISSION_QUOTA_PRICE).unwrap(), Address::from_str(reserved_addresses::PERMISSION_VERSION).unwrap(), ]; @@ -496,9 +494,9 @@ mod tests { cont: H160::from_str(reserved_addresses::BATCH_TX).unwrap(), func: method_tools::encode_to_vec(MULTI_TXS), }, - // emergencyBrake + // emergencyIntervention Resource { - cont: H160::from_str(reserved_addresses::EMERGENCY_BRAKE).unwrap(), + cont: H160::from_str(reserved_addresses::EMERGENCY_INTERVENTION).unwrap(), func: method_tools::encode_to_vec(SET_STATE), }, // quotaPrice @@ -506,11 +504,16 @@ mod tests { cont: H160::from_str(reserved_addresses::PRICE_MANAGEMENT).unwrap(), func: method_tools::encode_to_vec(SET_QUOTA_PRICE), }, - // version + // setVersion(Will deprecated) Resource { cont: H160::from_str(reserved_addresses::VERSION_MANAGEMENT).unwrap(), func: method_tools::encode_to_vec(SET_VERSION), }, + // setProtocolVersion + Resource { + cont: H160::from_str(reserved_addresses::VERSION_MANAGEMENT).unwrap(), + func: method_tools::encode_to_vec(SET_PROTOCOL_VERSION), + }, ]; expected_resources.sort(); @@ -519,7 +522,7 @@ mod tests { #[test] fn test_resources() { - let executor = init_executor(vec![]); + let executor = init_executor(); let permission = Address::from_str(reserved_addresses::PERMISSION_NEW_PERMISSION).unwrap(); // Test resources diff --git a/cita-executor/core/src/contracts/solc/price_manager.rs b/cita-executor/core/src/contracts/solc/price_manager.rs index fca0b9eb8..030d50b7c 100644 --- a/cita-executor/core/src/contracts/solc/price_manager.rs +++ b/cita-executor/core/src/contracts/solc/price_manager.rs @@ -18,12 +18,12 @@ //! Quota Price Management use super::ContractCallExt; +use crate::contracts::tools::{decode as decode_tools, method as method_tools}; +use crate::libexecutor::executor::Executor; +use crate::types::ids::BlockId; +use crate::types::reserved_addresses; use cita_types::{Address, U256}; -use contracts::tools::{decode as decode_tools, method as method_tools}; -use libexecutor::executor::Executor; use std::str::FromStr; -use types::ids::BlockId; -use types::reserved_addresses; lazy_static! { static ref GET_QUOTA_PRICE: Vec = method_tools::encode_to_vec(b"getQuotaPrice()"); @@ -63,13 +63,13 @@ impl<'a> PriceManagement<'a> { #[cfg(test)] mod tests { use super::PriceManagement; + use crate::tests::helpers::init_executor; + use crate::types::ids::BlockId; use cita_types::U256; - use tests::helpers::init_executor; - use types::ids::BlockId; #[test] - fn test_state() { - let executor = init_executor(vec![]); + fn test_quota_price() { + let executor = init_executor(); let price_management = PriceManagement::new(&executor); let price = price_management.quota_price(BlockId::Pending).unwrap(); assert_eq!(price, U256::from(100_0000)); diff --git a/cita-executor/core/src/contracts/solc/quota_manager.rs b/cita-executor/core/src/contracts/solc/quota_manager.rs index 57df815d6..f97ca05f4 100644 --- a/cita-executor/core/src/contracts/solc/quota_manager.rs +++ b/cita-executor/core/src/contracts/solc/quota_manager.rs @@ -1,5 +1,5 @@ // CITA -// Copyright 2016-2018 Cryptape Technologies LLC. +// Copyright 2016-2019 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public @@ -18,15 +18,15 @@ //! Quota manager. use super::ContractCallExt; +use crate::contracts::tools::{decode as decode_tools, method as method_tools}; +use crate::libexecutor::executor::Executor; +use crate::types::ids::BlockId; +use crate::types::reserved_addresses; use cita_types::traits::LowerHex; use cita_types::{Address, H160}; -use contracts::tools::{decode as decode_tools, method as method_tools}; -use libexecutor::executor::Executor; use libproto::blockchain::AccountGasLimit as ProtoAccountQuotaLimit; use std::collections::HashMap; use std::str::FromStr; -use types::ids::BlockId; -use types::reserved_addresses; const QUOTAS: &[u8] = &*b"getQuotas()"; const ACCOUNTS: &[u8] = &*b"getAccounts()"; @@ -195,37 +195,29 @@ impl<'a> QuotaManager<'a> { #[cfg(test)] mod tests { - extern crate logger; + extern crate cita_logger as logger; use super::{QuotaManager, AQL_VALUE, AUTO_EXEC_QL_VALUE, BQL_VALUE}; + use crate::tests::helpers::init_executor; + use crate::types::ids::BlockId; use cita_types::H160; use std::str::FromStr; - use tests::helpers::init_executor; - use types::ids::BlockId; #[test] fn test_users() { - let executor = init_executor(vec![ - (( - "QuotaManager.admin", - "0xd3f1a71d1d8f073f4e725f57bbe14d67da22f888", - )), - ]); - println!("init executor finish"); + let executor = init_executor(); let quota_management = QuotaManager::new(&executor); let users = quota_management.users(BlockId::Pending).unwrap(); assert_eq!( users, - vec![H160::from_str("d3f1a71d1d8f073f4e725f57bbe14d67da22f888").unwrap()] + vec![H160::from_str("4b5ae4567ad5d9fb92bc9afd6a657e6fa13a2523").unwrap()] ); } #[test] fn test_quota() { - let executor = init_executor(vec![]); - println!("init executor finish"); - + let executor = init_executor(); let quota_management = QuotaManager::new(&executor); // Test quota diff --git a/cita-executor/core/src/contracts/solc/sys_config.rs b/cita-executor/core/src/contracts/solc/sys_config.rs index d2dc7f2b7..a30fd8a16 100644 --- a/cita-executor/core/src/contracts/solc/sys_config.rs +++ b/cita-executor/core/src/contracts/solc/sys_config.rs @@ -1,5 +1,5 @@ // CITA -// Copyright 2016-2018 Cryptape Technologies LLC. +// Copyright 2016-2019 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public @@ -20,15 +20,15 @@ use std::str::FromStr; use super::ContractCallExt; +use crate::contracts::solc::version_management::VersionManager; +use crate::contracts::tools::method as method_tools; +use crate::libexecutor::economical_model::EconomicalModel; +use crate::libexecutor::executor::Executor; +use crate::types::ids::BlockId; +use crate::types::reserved_addresses; use cita_types::{Address, H256, U256}; -use contracts::solc::version_management::VersionManager; -use contracts::tools::method as method_tools; use ethabi::{decode, ParamType, Token}; -use libexecutor::economical_model::EconomicalModel; -use libexecutor::executor::Executor; use num::FromPrimitive; -use types::ids::BlockId; -use types::reserved_addresses; lazy_static! { static ref DELAY_BLOCK_NUMBER: Vec = method_tools::encode_to_vec(b"getDelayBlockNumber()"); @@ -341,50 +341,30 @@ impl<'a> SysConfig<'a> { } pub fn default_auto_exec() -> bool { - error!("Use the default autoEXEC."); + info!("Use the default autoEXEC."); false } } #[cfg(test)] mod tests { - extern crate logger; + extern crate cita_logger as logger; use super::{EconomicalModel, SysConfig, TokenInfo}; + use crate::tests::helpers::init_executor; + use crate::types::ids::BlockId; use cita_types::Address; use std::str::FromStr; - use tests::helpers::init_executor; - use types::ids::BlockId; #[test] fn test_delay_block_number() { - let executor = init_executor(vec![ - ("SysConfig.delayBlockNumber", "2"), - ("SysConfig.checkCallPermission", "false"), - ("SysConfig.checkSendTxPermission", "false"), - ("SysConfig.checkCreateContractPermission", "false"), - ("SysConfig.checkQuota", "true"), - ("SysConfig.checkFeeBackPlatform", "true"), - ( - "SysConfig.chainOwner", - "0x0000000000000000000000000000000000000000", - ), - ("SysConfig.chainName", "test-chain"), - ("SysConfig.chainId", "123"), - ("SysConfig.operator", "test-operator"), - ("SysConfig.website", "https://www.cryptape.com"), - ("SysConfig.blockInterval", "3006"), - ("SysConfig.economicalModel", "1"), - ("SysConfig.name", "name"), - ("SysConfig.symbol", "symbol"), - ("SysConfig.avatar", "avatar"), - ]); + let executor = init_executor(); let config = SysConfig::new(&executor); // Test delay block number let number = config.delay_block_number(BlockId::Pending).unwrap(); - assert_eq!(number, 2); + assert_eq!(number, 1); // Test call permission_check let check_call_permission = config.call_permission_check(BlockId::Pending).unwrap(); @@ -406,7 +386,7 @@ mod tests { // Test fee_back_platform_check let check_fee_back_platform = config.fee_back_platform_check(BlockId::Pending).unwrap(); - assert_eq!(check_fee_back_platform, true); + assert_eq!(check_fee_back_platform, false); // Test chain_owner let value = config.chain_owner(BlockId::Pending).unwrap(); @@ -421,7 +401,7 @@ mod tests { // Test chain_id let value = config.chain_id(BlockId::Pending).unwrap(); - assert_eq!(value, 123); + assert_eq!(value, 1); // Test operator let value = config.operator(BlockId::Pending).unwrap(); @@ -429,24 +409,24 @@ mod tests { // Test website let value = config.website(BlockId::Pending).unwrap(); - assert_eq!(value, "https://www.cryptape.com"); + assert_eq!(value, "https://www.example.com"); // Test block_interval let value = config.block_interval(BlockId::Pending).unwrap(); - assert_eq!(value, 3006); + assert_eq!(value, 3000); // Test economical_model let value = config.economical_model(BlockId::Pending).unwrap(); - assert_eq!(value, EconomicalModel::Charge); + assert_eq!(value, EconomicalModel::Quota); // Test token info let value = config.token_info(BlockId::Pending).unwrap(); assert_eq!( value, TokenInfo { - name: "name".to_owned(), - symbol: "symbol".to_owned(), - avatar: "avatar".to_owned() + name: "CITA Test Token".to_owned(), + symbol: "CTT".to_owned(), + avatar: "https://cdn.cryptape.com/icon_cita.png".to_owned() } ); diff --git a/cita-executor/core/src/contracts/solc/user_management.rs b/cita-executor/core/src/contracts/solc/user_management.rs index 8f2ae3977..783616283 100644 --- a/cita-executor/core/src/contracts/solc/user_management.rs +++ b/cita-executor/core/src/contracts/solc/user_management.rs @@ -1,5 +1,5 @@ // CITA -// Copyright 2016-2018 Cryptape Technologies LLC. +// Copyright 2016-2019 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public @@ -17,13 +17,13 @@ //! User management. use super::ContractCallExt; +use crate::contracts::tools::{decode as decode_tools, method as method_tools}; +use crate::libexecutor::executor::Executor; +use crate::types::ids::BlockId; +use crate::types::reserved_addresses; use cita_types::{Address, H160}; -use contracts::tools::{decode as decode_tools, method as method_tools}; -use libexecutor::executor::Executor; use std::collections::HashMap; use std::str::FromStr; -use types::ids::BlockId; -use types::reserved_addresses; const ALLGROUPS: &[u8] = &*b"queryGroups()"; const ACCOUNTS: &[u8] = &*b"queryAccounts()"; @@ -96,18 +96,18 @@ impl<'a> UserManagement<'a> { #[cfg(test)] mod tests { - extern crate logger; + extern crate cita_logger as logger; use super::UserManagement; + use crate::tests::helpers::init_executor; + use crate::types::ids::BlockId; + use crate::types::reserved_addresses; use cita_types::{Address, H160}; use std::str::FromStr; - use tests::helpers::init_executor; - use types::ids::BlockId; - use types::reserved_addresses; #[test] fn test_all_groups() { - let executor = init_executor(vec![]); + let executor = init_executor(); let user_management = UserManagement::new(&executor); let all_groups: Vec
= user_management.all_groups(BlockId::Pending).unwrap(); @@ -117,48 +117,4 @@ mod tests { vec![H160::from_str(reserved_addresses::GROUP).unwrap()] ); } - - #[test] - fn test_accounts() { - let executor = init_executor(vec![( - "Group.accounts", - concat!( - "0x4b5ae4567ad5d9fb92bc9afd6a657e6fa13a2523,", - "0xd3f1a71d1d8f073f4e725f57bbe14d67da22f888,", - "0x9dcd6b234e2772c5451fd4ccf7582f4283140697" - ), - )]); - let user_management = UserManagement::new(&executor); - - // Test accounts - let accounts: Vec
= user_management - .accounts( - &H160::from_str("ffffffffffffffffffffffffffffffffff020009").unwrap(), - BlockId::Pending, - ) - .unwrap(); - - assert_eq!( - accounts, - vec![ - Address::from_str("4b5ae4567ad5d9fb92bc9afd6a657e6fa13a2523").unwrap(), - Address::from_str("d3f1a71d1d8f073f4e725f57bbe14d67da22f888").unwrap(), - Address::from_str("9dcd6b234e2772c5451fd4ccf7582f4283140697").unwrap(), - ] - ); - - // Test group accounts - let root = H160::from_str(reserved_addresses::GROUP).unwrap(); - - let group_accounts = user_management.load_group_accounts(BlockId::Pending); - assert_eq!(group_accounts.contains_key(&root), true); - assert_eq!( - *group_accounts.get(&root).unwrap(), - vec![ - Address::from_str("4b5ae4567ad5d9fb92bc9afd6a657e6fa13a2523").unwrap(), - Address::from_str("d3f1a71d1d8f073f4e725f57bbe14d67da22f888").unwrap(), - Address::from_str("9dcd6b234e2772c5451fd4ccf7582f4283140697").unwrap(), - ] - ); - } } diff --git a/cita-executor/core/src/contracts/solc/version_management.rs b/cita-executor/core/src/contracts/solc/version_management.rs index 0379cd2ef..701807406 100644 --- a/cita-executor/core/src/contracts/solc/version_management.rs +++ b/cita-executor/core/src/contracts/solc/version_management.rs @@ -1,5 +1,5 @@ // CITA -// Copyright 2016-2018 Cryptape Technologies LLC. +// Copyright 2016-2019 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public @@ -20,16 +20,18 @@ use std::str::FromStr; use super::ContractCallExt; -use contracts::tools::method as method_tools; -use libexecutor::executor::Executor; +use crate::contracts::tools::method as method_tools; +use crate::libexecutor::executor::Executor; +use crate::types::ids::BlockId; +use crate::types::reserved_addresses; use cita_types::Address; use cita_types::H256; use ethabi::{decode, ParamType}; -use types::ids::BlockId; -use types::reserved_addresses; lazy_static! { + // Will use `getProtocolVersion` at next version after `v0.25.0`. + // And the `getVersion` will be *Deprecated*. static ref VERSION_HASH: Vec = method_tools::encode_to_vec(b"getVersion()"); static ref CONTRACT_ADDRESS: Address = Address::from_str(reserved_addresses::VERSION_MANAGEMENT).unwrap(); @@ -70,12 +72,12 @@ impl<'a> VersionManager<'a> { #[cfg(test)] mod tests { use super::VersionManager; - use tests::helpers::init_executor; - use types::ids::BlockId; + use crate::tests::helpers::init_executor; + use crate::types::ids::BlockId; #[test] - fn test_state() { - let executor = init_executor(vec![]); + fn test_get_version() { + let executor = init_executor(); let version_management = VersionManager::new(&executor); let version = version_management.get_version(BlockId::Pending).unwrap(); assert_eq!(version, 2); diff --git a/cita-executor/core/src/contracts/tools/decode.rs b/cita-executor/core/src/contracts/tools/decode.rs index c45fed7e3..f08fe9213 100644 --- a/cita-executor/core/src/contracts/tools/decode.rs +++ b/cita-executor/core/src/contracts/tools/decode.rs @@ -15,8 +15,8 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . +use crate::contracts::solc::permission_management::Resource; use cita_types::{Address, H256, U256}; -use contracts::solc::permission_management::Resource; use ethabi::{decode, ParamType, Token}; /// Parse solidity return data `address[]` to rust `Vec
` @@ -86,6 +86,14 @@ pub fn to_u256(output: &[u8]) -> Option { .map(U256::from) } +/// Parse solidity return data `Address` to rust `Address` +pub fn to_address(output: &[u8]) -> Option
{ + decode(&[ParamType::Address], output) + .ok() + .and_then(|decoded| decoded.first().cloned()) + .and_then(Token::to_address) + .map(Address::from) +} /// Parse solidity return data `uint256` to rust `u64` pub fn to_u64(output: &[u8]) -> Option { to_u256(output).map(|x| x.low_u64()) diff --git a/cita-executor/core/src/engines/mod.rs b/cita-executor/core/src/engines/mod.rs index 4a73aef9e..0303331d9 100644 --- a/cita-executor/core/src/engines/mod.rs +++ b/cita-executor/core/src/engines/mod.rs @@ -1,5 +1,5 @@ // CITA -// Copyright 2016-2018 Cryptape Technologies LLC. +// Copyright 2016-2019 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public @@ -15,14 +15,14 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . -use builtin::Builtin; +use crate::builtin::Builtin; +use crate::header::BlockNumber; +use crate::spec::Builtin as SpecBuiltin; +use crate::types::reserved_addresses; use cita_types::Address; -use header::BlockNumber; use serde_json; -use spec::Builtin as SpecBuiltin; use std::collections::BTreeMap; use std::str::FromStr; -use types::reserved_addresses; mod null_engine; pub use self::null_engine::NullEngine; diff --git a/cita-executor/core/src/engines/null_engine.rs b/cita-executor/core/src/engines/null_engine.rs index 28a4103b1..ce46b3581 100644 --- a/cita-executor/core/src/engines/null_engine.rs +++ b/cita-executor/core/src/engines/null_engine.rs @@ -14,9 +14,9 @@ // You should have received a copy of the GNU General Public License // along with Parity. If not, see . -use builtin::Builtin; +use crate::builtin::Builtin; +use crate::engines::Engine; use cita_types::Address; -use engines::Engine; use std::collections::BTreeMap; /// An engine which does not provide any consensus mechanism and does not seal blocks. diff --git a/cita-executor/core/src/error.rs b/cita-executor/core/src/error.rs index 24b09c40b..370811db3 100644 --- a/cita-executor/core/src/error.rs +++ b/cita-executor/core/src/error.rs @@ -16,15 +16,15 @@ //! General error types for use in ethcore. -use basic_types::LogBloom; +use crate::basic_types::LogBloom; use cita_ed25519::Error as EthkeyError; use cita_types::{H256, U256}; -use cita_db::TrieError; -pub use executed::{CallError, ExecutionError}; -use header::BlockNumber; +use crate::cita_db::TrieError; +pub use crate::executed::{CallError, ExecutionError}; +use crate::header::BlockNumber; +use crate::snapshot::Error as SnapshotError; use snappy; -use snapshot::Error as SnapshotError; use std::fmt; use util::*; diff --git a/cita-executor/core/src/executed.rs b/cita-executor/core/src/executed.rs index 831284759..f32d95c03 100644 --- a/cita-executor/core/src/executed.rs +++ b/cita-executor/core/src/executed.rs @@ -16,14 +16,14 @@ //! Transaction execution format module. -use cita_db::trie; +use crate::cita_db::trie; +use crate::receipt::ReceiptError; +use crate::trace::{FlatTrace, VMTrace}; +use crate::types::log_entry::LogEntry; +use crate::types::state_diff::StateDiff; use cita_types::{Address, U256, U512}; use evm; -use receipt::ReceiptError; use std::fmt; -use trace::{FlatTrace, VMTrace}; -use types::log_entry::LogEntry; -use types::state_diff::StateDiff; use util::Bytes; /// Transaction execution receipt. diff --git a/cita-executor/core/src/executive.rs b/cita-executor/core/src/executive.rs index 5e487b5b9..63e7d942e 100644 --- a/cita-executor/core/src/executive.rs +++ b/cita-executor/core/src/executive.rs @@ -16,10 +16,9 @@ //! Transaction Execution environment. -use authentication::check_permission; -use builtin::Builtin; -use cita_types::{Address, H160, H256, U256, U512}; -use contracts::{ +use crate::authentication::check_permission; +use crate::builtin::Builtin; +use crate::contracts::{ grpc::{ self, contract::{ @@ -30,30 +29,31 @@ use contracts::{ }, native::factory::{Contract as NativeContract, Factory as NativeFactory}, }; +use crate::engines::Engine; +use crate::error::ExecutionError; +pub use crate::executed::{Executed, ExecutionResult}; +use crate::externalities::*; +use crate::libexecutor::economical_model::EconomicalModel; +use crate::libexecutor::sys_config::BlockSysConfig; +use crate::state::backend::Backend as StateBackend; +use crate::state::{State, Substate}; +use crate::trace::{ + ExecutiveTracer, ExecutiveVMTracer, FlatTrace, NoopTracer, NoopVMTracer, Tracer, VMTrace, + VMTracer, +}; +use crate::types::reserved_addresses; +use crate::types::transaction::{Action, SignedTransaction}; +use cita_types::{Address, H160, H256, U256, U512}; use crossbeam; -use engines::Engine; -use error::ExecutionError; use evm::action_params::{ActionParams, ActionValue}; use evm::call_type::CallType; use evm::env_info::EnvInfo; use evm::{self, Factory, FinalizationResult, Finalize, ReturnData, Schedule}; -pub use executed::{Executed, ExecutionResult}; -use externalities::*; use hashable::{Hashable, HASH_EMPTY}; -use libexecutor::economical_model::EconomicalModel; -use libexecutor::sys_config::BlockSysConfig; -use state::backend::Backend as StateBackend; -use state::{State, Substate}; use std::cmp; use std::error::Error; use std::str::FromStr; use std::sync::Arc; -use trace::{ - ExecutiveTracer, ExecutiveVMTracer, FlatTrace, NoopTracer, NoopVMTracer, Tracer, VMTrace, - VMTracer, -}; -use types::reserved_addresses; -use types::transaction::{Action, SignedTransaction}; use util::*; /// Roughly estimate what stack size each level of evm depth will use @@ -1210,27 +1210,27 @@ impl<'a, B: 'a + StateBackend> Executive<'a, B> { #[cfg(test)] mod tests { - extern crate logger; + extern crate cita_logger as logger; extern crate rustc_hex; //////////////////////////////////////////////////////////////////////////////// use self::rustc_hex::FromHex; use super::*; + use crate::engines::NullEngine; + use crate::libexecutor::sys_config::BlockSysConfig; + use crate::state::Substate; + use crate::tests::helpers::*; + use crate::trace::{ExecutiveTracer, ExecutiveVMTracer}; + use crate::types::transaction::Transaction; use cita_crypto::{CreateKey, KeyPair}; use cita_types::{Address, H256, U256}; - use engines::NullEngine; use evm::action_params::{ActionParams, ActionValue}; use evm::env_info::EnvInfo; use evm::Schedule; use evm::{Factory, VMType}; - use libexecutor::sys_config::BlockSysConfig; - use state::Substate; use std::ops::Deref; use std::str::FromStr; use std::sync::Arc; - use tests::helpers::*; - use trace::{ExecutiveTracer, ExecutiveVMTracer}; - use types::transaction::Transaction; #[test] fn test_transfer_for_store() { diff --git a/cita-executor/core/src/externalities.rs b/cita-executor/core/src/externalities.rs index ffdda4b2d..429abed21 100644 --- a/cita-executor/core/src/externalities.rs +++ b/cita-executor/core/src/externalities.rs @@ -18,9 +18,15 @@ //////////////////////////////////////////////////////////////////////////////// +use crate::contracts::native::factory::Factory as NativeFactory; +use crate::engines::Engine; +use crate::executive::*; +use crate::libexecutor::economical_model::EconomicalModel; +use crate::state::backend::Backend as StateBackend; +use crate::state::State; +use crate::substate::Substate; +use crate::trace::{Tracer, VMTracer}; use cita_types::{Address, H256, U256}; -use contracts::native::factory::Factory as NativeFactory; -use engines::Engine; use evm::action_params::{ActionParams, ActionValue}; use evm::call_type::CallType; use evm::env_info::EnvInfo; @@ -28,15 +34,9 @@ use evm::{ self, ContractCreateResult, Factory, FinalizationResult, MessageCallResult, ReturnData, Schedule, }; -use executive::*; use hashable::Hashable; -use libexecutor::economical_model::EconomicalModel; -use state::backend::Backend as StateBackend; -use state::State; use std::cmp; use std::sync::Arc; -use substate::Substate; -use trace::{Tracer, VMTracer}; use util::*; /// Policy for handling output data on `RETURN` opcode. @@ -401,7 +401,7 @@ where } fn log(&mut self, topics: Vec, data: &[u8]) -> evm::Result<()> { - use log_entry::LogEntry; + use crate::log_entry::LogEntry; if self.static_flag { return Err(evm::Error::MutableCallInStaticContext); diff --git a/cita-executor/core/src/factory.rs b/cita-executor/core/src/factory.rs index 3389794de..576febae8 100644 --- a/cita-executor/core/src/factory.rs +++ b/cita-executor/core/src/factory.rs @@ -14,9 +14,9 @@ // You should have received a copy of the GNU General Public License // along with Parity. If not, see . -use account_db::Factory as AccountFactory; -use cita_db::trie::TrieFactory; -use contracts::native::factory::Factory as NativeFactory; +use crate::account_db::Factory as AccountFactory; +use crate::cita_db::trie::TrieFactory; +use crate::contracts::native::factory::Factory as NativeFactory; use evm::Factory as EvmFactory; /// Collection of factories. diff --git a/cita-executor/core/src/lib.rs b/cita-executor/core/src/lib.rs index a6491abc1..fa86c4566 100644 --- a/cita-executor/core/src/lib.rs +++ b/cita-executor/core/src/lib.rs @@ -1,5 +1,5 @@ // CITA -// Copyright 2016-2018 Cryptape Technologies LLC. +// Copyright 2016-2019 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public @@ -21,7 +21,7 @@ extern crate cita_crypto_trait; extern crate libproto; extern crate snappy; #[macro_use] -extern crate logger; +extern crate cita_logger as logger; extern crate lru_cache; extern crate proof; extern crate rlp; @@ -97,7 +97,7 @@ pub mod snapshot; mod spec; -pub use cita_db::journaldb; +pub use crate::cita_db::journaldb; +pub use crate::factory::*; +pub use crate::types::*; pub use evm::Error; -pub use factory::*; -pub use types::*; diff --git a/cita-executor/core/src/libexecutor/auto_exec.rs b/cita-executor/core/src/libexecutor/auto_exec.rs index 862476d13..fabe60507 100644 --- a/cita-executor/core/src/libexecutor/auto_exec.rs +++ b/cita-executor/core/src/libexecutor/auto_exec.rs @@ -1,5 +1,5 @@ // CITA -// Copyright 2016-2018 Cryptape Technologies LLC. +// Copyright 2016-2019 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public @@ -15,23 +15,23 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . +use crate::contracts::native::factory::Factory as NativeFactory; +use crate::contracts::tools::method as method_tools; +use crate::engines::NullEngine; +use crate::externalities::{Externalities, OriginInfo, OutputPolicy}; +use crate::libexecutor::economical_model::EconomicalModel; +use crate::state::State; +use crate::state::Substate; +use crate::state_db::StateDB; +use crate::trace::Tracer; +use crate::trace::{NoopTracer, NoopVMTracer}; +use crate::types::reserved_addresses; use cita_types::{Address, H160, U256}; -use contracts::native::factory::Factory as NativeFactory; -use contracts::tools::method as method_tools; -use engines::NullEngine; use evm::action_params::{ActionParams, ActionValue}; use evm::call_type::CallType; use evm::env_info::EnvInfo; use evm::{Factory, Finalize, VMType}; -use externalities::{Externalities, OriginInfo, OutputPolicy}; -use libexecutor::economical_model::EconomicalModel; -use state::State; -use state::Substate; -use state_db::StateDB; use std::str::FromStr; -use trace::Tracer; -use trace::{NoopTracer, NoopVMTracer}; -use types::reserved_addresses; use util::BytesRef; const AUTO_EXEC: &[u8] = &*b"autoExec()"; diff --git a/cita-executor/core/src/libexecutor/blacklist.rs b/cita-executor/core/src/libexecutor/blacklist.rs index ff6c462c0..267b9abf3 100644 --- a/cita-executor/core/src/libexecutor/blacklist.rs +++ b/cita-executor/core/src/libexecutor/blacklist.rs @@ -1,5 +1,5 @@ // CITA -// Copyright 2016-2017 Cryptape Technologies LLC. +// Copyright 2016-2019 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public diff --git a/cita-executor/core/src/libexecutor/block.rs b/cita-executor/core/src/libexecutor/block.rs index a332f6ab1..c508f3216 100644 --- a/cita-executor/core/src/libexecutor/block.rs +++ b/cita-executor/core/src/libexecutor/block.rs @@ -15,27 +15,27 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . -use basic_types::LogBloom; +use crate::basic_types::LogBloom; +use crate::engines::Engine; +use crate::error::Error; +use crate::factory::Factories; +use crate::libexecutor::auto_exec::auto_exec; +use crate::libexecutor::sys_config::BlockSysConfig; +use crate::receipt::Receipt; +use crate::state::State; +use crate::state_db::StateDB; +use crate::trace::FlatTrace; +pub use crate::types::block::{Block, BlockBody, OpenBlock}; +use crate::types::transaction::SignedTransaction; use cita_merklehash; use cita_types::{Address, H256, U256}; -use engines::Engine; -use error::Error; use evm::env_info::{EnvInfo, LastHashes}; -use factory::Factories; use hashable::Hashable; -use libexecutor::auto_exec::auto_exec; -use libexecutor::sys_config::BlockSysConfig; use libproto::executor::{ExecutedInfo, ReceiptWithOption}; -use receipt::Receipt; use rlp::*; -use state::State; -use state_db::StateDB; use std::collections::HashMap; use std::ops::{Deref, DerefMut}; use std::sync::Arc; -use trace::FlatTrace; -pub use types::block::{Block, BlockBody, OpenBlock}; -use types::transaction::SignedTransaction; lazy_static! { /// Block Reward diff --git a/cita-executor/core/src/libexecutor/call_request.rs b/cita-executor/core/src/libexecutor/call_request.rs index b028f7097..38c13dcfc 100644 --- a/cita-executor/core/src/libexecutor/call_request.rs +++ b/cita-executor/core/src/libexecutor/call_request.rs @@ -1,5 +1,5 @@ // CITA -// Copyright 2016-2017 Cryptape Technologies LLC. +// Copyright 2016-2019 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public diff --git a/cita-executor/core/src/libexecutor/command.rs b/cita-executor/core/src/libexecutor/command.rs index 74d09252a..84b630df0 100644 --- a/cita-executor/core/src/libexecutor/command.rs +++ b/cita-executor/core/src/libexecutor/command.rs @@ -1,5 +1,5 @@ // CITA -// Copyright 2016-2018 Cryptape Technologies LLC. +// Copyright 2016-2019 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public @@ -18,30 +18,32 @@ use super::economical_model::EconomicalModel; use super::executor::{make_consensus_config, Executor}; use super::sys_config::GlobalSysConfig; +use crate::call_analytics::CallAnalytics; +use crate::contracts::solc::{ + sys_config::ChainId, PermissionManagement, SysConfig, VersionManager, +}; +use crate::engines::NullEngine; +use crate::error::CallError; +use crate::executive::{Executed, Executive, TransactOptions}; +pub use crate::libexecutor::block::*; +use crate::libexecutor::call_request::CallRequest; +use crate::state::State; +use crate::state_db::StateDB; +use crate::types::ids::BlockId; +use crate::types::transaction::{Action, SignedTransaction, Transaction}; pub use byteorder::{BigEndian, ByteOrder}; -use call_analytics::CallAnalytics; use cita_types::traits::LowerHex; use cita_types::{Address, H256, U256}; -use contracts::solc::{sys_config::ChainId, PermissionManagement, SysConfig, VersionManager}; use crossbeam_channel::{Receiver, Sender}; -use engines::NullEngine; -use error::CallError; use evm::env_info::EnvInfo; -use executive::{Executed, Executive, TransactOptions}; use jsonrpc_types::rpc_types::{ BlockNumber, BlockTag, EconomicalModel as RpcEconomicalModel, MetaData, }; -pub use libexecutor::block::*; -use libexecutor::call_request::CallRequest; use libproto::ExecutedResult; use serde_json; -use state::State; -use state_db::StateDB; use std::convert::{From, Into}; use std::fmt; use std::sync::Arc; -use types::ids::BlockId; -use types::transaction::{Action, SignedTransaction, Transaction}; use util::Bytes; use util::RwLock; diff --git a/cita-executor/core/src/libexecutor/economical_model.rs b/cita-executor/core/src/libexecutor/economical_model.rs index 57937121c..f6b893837 100644 --- a/cita-executor/core/src/libexecutor/economical_model.rs +++ b/cita-executor/core/src/libexecutor/economical_model.rs @@ -1,5 +1,5 @@ // CITA -// Copyright 2016-2017 Cryptape Technologies LLC. +// Copyright 2016-2019 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public diff --git a/cita-executor/core/src/libexecutor/executor.rs b/cita-executor/core/src/libexecutor/executor.rs index 4718693d9..874afa13a 100644 --- a/cita-executor/core/src/libexecutor/executor.rs +++ b/cita-executor/core/src/libexecutor/executor.rs @@ -1,5 +1,5 @@ // CITA -// Copyright 2016-2018 Cryptape Technologies LLC. +// Copyright 2016-2019 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public @@ -18,30 +18,30 @@ use super::command::{Command, CommandResp, Commander}; use super::fsm::FSM; use super::sys_config::GlobalSysConfig; -use bloomchain::group::{BloomGroup, BloomGroupDatabase, GroupPosition}; +use crate::bloomchain::group::{BloomGroup, BloomGroupDatabase, GroupPosition}; +use crate::cita_db::kvdb::{DBTransaction, Database, DatabaseConfig}; +use crate::cita_db::trie::{TrieFactory, TrieSpec}; +use crate::cita_db::{journaldb, KeyValueDB}; +use crate::contracts::{native::factory::Factory as NativeFactory, solc::NodeManager}; +use crate::db; +use crate::db::*; +use crate::engines::{Engine, NullEngine}; +use crate::factory::*; +use crate::header::*; +pub use crate::libexecutor::block::*; +use crate::libexecutor::genesis::Genesis; +use crate::state_db::StateDB; +use crate::types::extras::*; +use crate::types::ids::BlockId; pub use byteorder::{BigEndian, ByteOrder}; -use cita_db::kvdb::{DBTransaction, Database, DatabaseConfig}; -use cita_db::trie::{TrieFactory, TrieSpec}; -use cita_db::{journaldb, KeyValueDB}; use cita_types::H256; -use contracts::{native::factory::Factory as NativeFactory, solc::NodeManager}; use crossbeam_channel::{Receiver, Sender}; -use db; -use db::*; -use engines::{Engine, NullEngine}; use evm::env_info::LastHashes; use evm::Factory as EvmFactory; -use factory::*; -use header::*; -pub use libexecutor::block::*; -use libexecutor::genesis::Genesis; use libproto::{ConsensusConfig, ExecutedResult}; -use state_db::StateDB; use std::convert::{From, Into}; use std::sync::Arc; use std::time::Instant; -use types::extras::*; -use types::ids::BlockId; use util::RwLock; use util::UtilError; @@ -452,7 +452,7 @@ pub fn make_consensus_config(sys_config: GlobalSysConfig) -> ConsensusConfig { consensus_config.set_check_quota(sys_config.block_sys_config.check_options.quota); consensus_config.set_block_interval(sys_config.block_interval); consensus_config.set_version(sys_config.block_sys_config.chain_version); - if sys_config.emergency_brake { + if sys_config.emergency_intervention { let super_admin_account = sys_config .block_sys_config .super_admin_account @@ -465,64 +465,31 @@ pub fn make_consensus_config(sys_config: GlobalSysConfig) -> ConsensusConfig { } #[cfg(test)] mod tests { - extern crate logger; + extern crate cita_logger as logger; extern crate tempdir; - + use crate::libexecutor::command::Commander; + use crate::libexecutor::command::{Command, CommandResp}; + use crate::libexecutor::fsm::FSM; + use crate::tests::helpers; + use crate::types::ids::BlockId; use cita_crypto::{CreateKey, KeyPair}; - use cita_types::traits::LowerHex; use cita_types::Address; - use contracts::solc::sys_config::SysConfig; - use core::receipt::ReceiptError; - use libexecutor::command::Commander; - use libexecutor::command::{Command, CommandResp}; - use libexecutor::fsm::FSM; - use rustc_hex::FromHex; - use std::str::FromStr; use std::thread; use std::time::Duration; - use tests::helpers; - use types::ids::BlockId; - use types::reserved_addresses; - - #[test] - fn test_contract_address_from_permission_denied() { - let keypair = KeyPair::gen_keypair(); - let privkey = keypair.privkey(); - - let mut executor = - helpers::init_executor(vec![("SysConfig.checkCreateContractPermission", "true")]); - - let chain = helpers::init_chain(); - let data = helpers::generate_contract(); - let block = helpers::create_block(&executor, Address::from(0), &data, (0, 1), &privkey); - let inchain = chain.clone(); - let txs = block.body().transactions().clone(); - let hash = txs[0].hash(); - let h = executor.get_current_height() + 1; - - let closed_block = executor.into_fsm(block.clone()); - let executed_result = executor.grow(closed_block); - inchain.set_block_body(h, &block); - inchain.set_db_result(&executed_result, &block); - - let receipt = chain - .localized_receipt(hash) - .expect("failed to get localized_receipt"); - assert_eq!(receipt.contract_address, None); - assert_eq!(receipt.error, Some(ReceiptError::NoContractPermission)); - } #[test] + #[cfg(feature = "sha3hash")] fn test_chain_name_valid_block_number() { - let keypair = KeyPair::gen_keypair(); - let privkey = keypair.privkey(); - let addr = keypair.address().lower_hex(); + use crate::contracts::solc::sys_config::SysConfig; + use crate::types::reserved_addresses; + use cita_types::H256; + use rustc_hex::FromHex; + use std::str::FromStr; - let mut executor = helpers::init_executor(vec![ - ("SysConfig.chainName", "abcd"), - ("Admin.admin", &addr), - ]); + let privkey = + H256::from("0x5f0258a4778057a8a7d97809bd209055b2fbafa654ce7d31ec7191066b9225e6"); + let mut executor = helpers::init_executor(); let to = Address::from_str(reserved_addresses::SYS_CONFIG).unwrap(); let data = "c0c41f220000000000000000000000000000000000000000000\ 000000000000000000020000000000000000000000000000000\ @@ -543,14 +510,14 @@ mod tests { .unwrap(); assert_eq!(chain_name_pending, "12345"); - assert_eq!(chain_name_latest, "abcd"); + assert_eq!(chain_name_latest, "test-chain"); } #[test] fn test_rollback_current_height() { let keypair = KeyPair::gen_keypair(); let privkey = keypair.privkey(); - let mut executor = helpers::init_executor(vec![]); + let mut executor = helpers::init_executor(); let data = helpers::generate_contract(); for _i in 0..5 { @@ -580,7 +547,7 @@ mod tests { fn test_closed_block_grow() { let keypair = KeyPair::gen_keypair(); let privkey = keypair.privkey(); - let mut executor = helpers::init_executor(vec![]); + let mut executor = helpers::init_executor(); let data = helpers::generate_contract(); let block = helpers::create_block(&executor, Address::from(0), &data, (0, 1), &privkey); @@ -602,7 +569,6 @@ mod tests { let (command_req_sender, command_req_receiver) = crossbeam_channel::bounded(0); let (command_resp_sender, command_resp_receiver) = crossbeam_channel::bounded(0); let mut executor = helpers::init_executor2( - vec![], fsm_req_receiver.clone(), fsm_resp_sender, command_req_receiver, diff --git a/cita-executor/core/src/libexecutor/fsm.rs b/cita-executor/core/src/libexecutor/fsm.rs index be0684c74..fd2c2f1bd 100644 --- a/cita-executor/core/src/libexecutor/fsm.rs +++ b/cita-executor/core/src/libexecutor/fsm.rs @@ -1,5 +1,5 @@ // CITA -// Copyright 2016-2018 Cryptape Technologies LLC. +// Copyright 2016-2019 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public @@ -142,17 +142,17 @@ impl FSM for Executor { #[cfg(test)] mod tests { use super::ExecutedBlock; + use crate::libexecutor::block::OpenBlock; + use crate::libexecutor::executor::Executor; + use crate::libexecutor::fsm::{StatusOfFSM, FSM}; + use crate::tests::helpers::{ + create_block, generate_block_body, generate_block_header, generate_contract, init_executor, + init_executor2, + }; use cita_crypto::{CreateKey, KeyPair}; use cita_types::Address; - use libexecutor::block::OpenBlock; - use libexecutor::executor::Executor; - use libexecutor::fsm::{StatusOfFSM, FSM}; use std::thread; use std::time::Duration; - use tests::helpers::{ - create_block, generate_block_body, generate_block_header, generate_contract, init_executor, - init_executor2, - }; fn generate_empty_block() -> OpenBlock { let block_body = generate_block_body(); @@ -217,7 +217,7 @@ mod tests { #[test] fn test_fsm_initialize() { - let executor = init_executor(vec![]); + let executor = init_executor(); let open_block = generate_empty_block(); { @@ -257,7 +257,6 @@ mod tests { let (_command_req_sender, command_req_receiver) = crossbeam_channel::bounded(0); let (command_resp_sender, _command_resp_receiver) = crossbeam_channel::bounded(0); let executor = init_executor2( - vec![], fsm_req_receiver.clone(), fsm_resp_sender, command_req_receiver, @@ -290,7 +289,6 @@ mod tests { let (_command_req_sender, command_req_receiver) = crossbeam_channel::bounded(0); let (command_resp_sender, _command_resp_receiver) = crossbeam_channel::bounded(0); let executor = init_executor2( - vec![], fsm_req_receiver.clone(), fsm_resp_sender, command_req_receiver, @@ -321,7 +319,6 @@ mod tests { let (_command_req_sender, command_req_receiver) = crossbeam_channel::bounded(0); let (command_resp_sender, _command_resp_receiver) = crossbeam_channel::bounded(0); let mut executor = init_executor2( - vec![], fsm_req_receiver.clone(), fsm_resp_sender, command_req_receiver, @@ -397,7 +394,6 @@ mod tests { let (_command_req_sender, command_req_receiver) = crossbeam_channel::bounded(0); let (command_resp_sender, _command_resp_receiver) = crossbeam_channel::bounded(0); let mut executor = init_executor2( - vec![], fsm_req_receiver.clone(), fsm_resp_sender, command_req_receiver, diff --git a/cita-executor/core/src/libexecutor/genesis.rs b/cita-executor/core/src/libexecutor/genesis.rs index bc9585afb..dbad1ac00 100644 --- a/cita-executor/core/src/libexecutor/genesis.rs +++ b/cita-executor/core/src/libexecutor/genesis.rs @@ -1,5 +1,5 @@ // CITA -// Copyright 2016-2017 Cryptape Technologies LLC. +// Copyright 2016-2019 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public @@ -15,25 +15,25 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . -use cita_db::kvdb::KeyValueDB; +use crate::cita_db::kvdb::KeyValueDB; +use crate::db::{self as db, Writable}; +use crate::factory::Factories; +use crate::libexecutor::block::Block; +use crate::state::State; +use crate::state_db::StateDB; +use crate::types::extras::*; use cita_types::traits::ConvertType; use cita_types::{clean_0x, Address, H256, U256}; use crypto::digest::Digest; use crypto::md5::Md5; -use db::{self as db, Writable}; -use factory::Factories; -use libexecutor::block::Block; use rustc_hex::FromHex; use serde_json; -use state::State; -use state_db::StateDB; use std::collections::HashMap; use std::fs::File; use std::io::BufReader; use std::io::Read; use std::path::Path; use std::sync::Arc; -use types::extras::*; #[cfg(feature = "privatetx")] use zktx::set_param_path; @@ -187,8 +187,8 @@ impl Genesis { #[cfg(test)] mod test { + use crate::libexecutor::genesis::{Contract, Spec}; use cita_types::{H256, U256}; - use libexecutor::genesis::{Contract, Spec}; use serde_json; use std::collections::HashMap; use std::str::FromStr; diff --git a/cita-executor/core/src/libexecutor/lru_cache.rs b/cita-executor/core/src/libexecutor/lru_cache.rs index 29250f6f4..2f6f8076c 100644 --- a/cita-executor/core/src/libexecutor/lru_cache.rs +++ b/cita-executor/core/src/libexecutor/lru_cache.rs @@ -1,5 +1,5 @@ // CITA -// Copyright 2016-2017 Cryptape Technologies LLC. +// Copyright 2016-2019 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public diff --git a/cita-executor/core/src/libexecutor/mod.rs b/cita-executor/core/src/libexecutor/mod.rs index b4c98d771..afe1963bf 100644 --- a/cita-executor/core/src/libexecutor/mod.rs +++ b/cita-executor/core/src/libexecutor/mod.rs @@ -1,5 +1,5 @@ // CITA -// Copyright 2016-2017 Cryptape Technologies LLC. +// Copyright 2016-2019 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public @@ -28,5 +28,5 @@ pub mod lru_cache; pub mod sys_config; pub use self::genesis::Genesis; -pub use cita_db::journaldb; +pub use crate::cita_db::journaldb; pub use libproto::*; diff --git a/cita-executor/core/src/libexecutor/sys_config.rs b/cita-executor/core/src/libexecutor/sys_config.rs index c46ae685c..6eaf093f5 100644 --- a/cita-executor/core/src/libexecutor/sys_config.rs +++ b/cita-executor/core/src/libexecutor/sys_config.rs @@ -1,5 +1,5 @@ // CITA -// Copyright 2016-2018 Cryptape Technologies LLC. +// Copyright 2016-2019 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public @@ -16,14 +16,14 @@ // along with this program. If not, see . use super::executor::Executor; -use cita_types::{Address, U256}; -use contracts::solc::{ - AccountQuotaLimit, EmergencyBrake, NodeManager, PermissionManagement, PriceManagement, +use crate::contracts::solc::{ + AccountQuotaLimit, EmergencyIntervention, NodeManager, PermissionManagement, PriceManagement, QuotaManager, Resource, SysConfig, UserManagement, VersionManager, AUTO_EXEC_QL_VALUE, }; -use libexecutor::economical_model::EconomicalModel; +use crate::libexecutor::economical_model::EconomicalModel; +use crate::types::ids::BlockId; +use cita_types::{Address, U256}; use std::collections::HashMap; -use types::ids::BlockId; #[derive(Serialize, Deserialize, PartialEq, Debug, Clone)] pub struct GlobalSysConfig { @@ -34,7 +34,7 @@ pub struct GlobalSysConfig { pub changed_height: usize, /// Interval time for creating a block (milliseconds) pub block_interval: u64, - pub emergency_brake: bool, + pub emergency_intervention: bool, pub block_sys_config: BlockSysConfig, } @@ -47,7 +47,7 @@ impl Default for GlobalSysConfig { delay_active_interval: 1, changed_height: 0, block_interval: 3000, - emergency_brake: false, + emergency_intervention: false, block_sys_config: BlockSysConfig::default(), } } @@ -133,10 +133,10 @@ impl GlobalSysConfig { .set_specific_quota_limit(specific); conf.changed_height = executor.get_current_height() as usize; - let emergency_manager = EmergencyBrake::new(executor); - conf.emergency_brake = emergency_manager + let emergency_manager = EmergencyIntervention::new(executor); + conf.emergency_intervention = emergency_manager .state(block_id) - .unwrap_or_else(EmergencyBrake::default_state); + .unwrap_or_else(EmergencyIntervention::default_state); let version_manager = VersionManager::new(executor); conf.block_sys_config.chain_version = version_manager diff --git a/cita-executor/core/src/pod_account.rs b/cita-executor/core/src/pod_account.rs index f91e4a557..87b839a6f 100644 --- a/cita-executor/core/src/pod_account.rs +++ b/cita-executor/core/src/pod_account.rs @@ -14,12 +14,12 @@ // You should have received a copy of the GNU General Public License // along with Parity. If not, see . -use account_db::AccountDBMut; -use cita_db::{sec_trie_root, HashDB, TrieFactory}; +use crate::account_db::AccountDBMut; +use crate::cita_db::{sec_trie_root, HashDB, TrieFactory}; +use crate::state::Account; use cita_types::{H256, U256}; use hashable::Hashable; use rlp::{self, RlpStream}; -use state::Account; use std::collections::BTreeMap; use std::fmt; use util::*; diff --git a/cita-executor/core/src/snapshot/account.rs b/cita-executor/core/src/snapshot/account.rs index 16fb5d61c..c1f79ca9a 100644 --- a/cita-executor/core/src/snapshot/account.rs +++ b/cita-executor/core/src/snapshot/account.rs @@ -16,15 +16,15 @@ //! Account state encoding and decoding -use account_db::{AccountDB, AccountDBMut}; -use cita_db::hashdb::HashDB; -use cita_db::{Trie, TrieDB, TrieDBMut, TrieMut}; +use crate::account_db::{AccountDB, AccountDBMut}; +use crate::cita_db::hashdb::HashDB; +use crate::cita_db::{Trie, TrieDB, TrieDBMut, TrieMut}; +use crate::snapshot::Error; +use crate::types::basic_account::BasicAccount; use cita_types::{Address, H256, U256}; use hashable::{HASH_EMPTY, HASH_NULL_RLP}; use rlp::{RlpStream, UntrustedRlp}; -use snapshot::Error; use std::collections::HashSet; -use types::basic_account::BasicAccount; use util::Bytes; // An empty account -- these were replaced with RLP null data for a space optimization in v1. diff --git a/cita-executor/core/src/snapshot/error.rs b/cita-executor/core/src/snapshot/error.rs index 805209c60..17dff3cb1 100644 --- a/cita-executor/core/src/snapshot/error.rs +++ b/cita-executor/core/src/snapshot/error.rs @@ -18,9 +18,9 @@ use std::fmt; -use types::ids::BlockId; +use crate::types::ids::BlockId; -use cita_db::trie::TrieError; +use crate::cita_db::trie::TrieError; use cita_types::{Address, H256}; use rlp::DecoderError; use snappy::SnappyError; diff --git a/cita-executor/core/src/snapshot/io.rs b/cita-executor/core/src/snapshot/io.rs index adeccb472..39bfdeabb 100644 --- a/cita-executor/core/src/snapshot/io.rs +++ b/cita-executor/core/src/snapshot/io.rs @@ -299,7 +299,7 @@ pub struct LooseReader { impl LooseReader { /// Create a new `LooseReader` which will read the manifest and chunk data from /// the given directory. - pub fn create(mut dir: PathBuf) -> Result { + pub fn create(mut dir: PathBuf) -> Result { let mut manifest_buf = Vec::new(); dir.push("MANIFEST"); diff --git a/cita-executor/core/src/snapshot/mod.rs b/cita-executor/core/src/snapshot/mod.rs index 980433798..8faa45ee7 100644 --- a/cita-executor/core/src/snapshot/mod.rs +++ b/cita-executor/core/src/snapshot/mod.rs @@ -19,17 +19,17 @@ // chunks around 4MB before compression const PREFERRED_CHUNK_SIZE: usize = 4 * 1024 * 1024; -use account_db::{AccountDB, AccountDBMut}; - -use cita_db::hashdb::DBValue; -use cita_db::journaldb::{self, Algorithm, JournalDB}; -use cita_db::kvdb::{DBTransaction, Database, KeyValueDB}; -use cita_db::{HashDB, Trie, TrieDB, TrieDBMut, TrieMut}; +use crate::account_db::{AccountDB, AccountDBMut}; + +use crate::cita_db::hashdb::DBValue; +use crate::cita_db::journaldb::{self, Algorithm, JournalDB}; +use crate::cita_db::kvdb::{DBTransaction, Database, KeyValueDB}; +use crate::cita_db::{HashDB, Trie, TrieDB, TrieDBMut, TrieMut}; +use crate::db::{Writable, COL_EXTRA, COL_HEADERS, COL_STATE}; +use crate::libexecutor::executor::Executor; use cita_types::{Address, H256, U256}; -use db::{Writable, COL_EXTRA, COL_HEADERS, COL_STATE}; use hashable::Hashable; use hashable::{HASH_EMPTY, HASH_NULL_RLP}; -use libexecutor::executor::Executor; use rlp::{DecoderError, Encodable, RlpStream, UntrustedRlp}; use snappy; use std::collections::{HashMap, HashSet, VecDeque}; @@ -46,17 +46,17 @@ pub use self::error::Error; use self::io::SnapshotReader; use self::io::SnapshotWriter; use self::service::Service; -use snapshot::service::SnapshotService; -pub use types::basic_account::BasicAccount; -use types::ids::BlockId; +use crate::snapshot::service::SnapshotService; +pub use crate::types::basic_account::BasicAccount; +use crate::types::ids::BlockId; use super::state::backend::Backend; use super::state::Account as StateAccount; use super::state_db::StateDB; +use crate::header::Header; use ethcore_bloom_journal::Bloom; -use header::Header; -use types::extras::CurrentHash; +use crate::types::extras::CurrentHash; /// A sink for produced chunks. pub type ChunkSink<'a> = FnMut(&[u8]) -> Result<(), Error> + 'a; @@ -518,7 +518,7 @@ impl StateRebuilder { } /// Feed an uncompressed state chunk into the rebuilder. - pub fn feed(&mut self, chunk: &[u8], flag: &AtomicBool) -> Result<(), ::error::Error> { + pub fn feed(&mut self, chunk: &[u8], flag: &AtomicBool) -> Result<(), crate::error::Error> { let rlp = UntrustedRlp::new(chunk); let empty_rlp = StateAccount::new_basic(U256::zero(), U256::zero()).rlp(); let mut pairs = Vec::with_capacity(rlp.item_count()?); @@ -609,7 +609,7 @@ impl StateRebuilder { /// Finalize the restoration. Check for accounts missing code and make a dummy /// journal entry. /// Once all chunks have been fed, there should be nothing missing. - pub fn finalize(mut self, era: u64, id: H256) -> Result, ::error::Error> { + pub fn finalize(mut self, era: u64, id: H256) -> Result, crate::error::Error> { let mut batch = self.db.backing().transaction(); self.db.journal_under(&mut batch, era, &id)?; self.db.backing().write_buffered(batch); @@ -643,7 +643,7 @@ fn rebuild_accounts( known_abi: &HashMap, known_storage_roots: &mut HashMap, abort_flag: &AtomicBool, -) -> Result { +) -> Result { let mut status = RebuiltStatus::default(); for (account_rlp, out) in account_fat_rlps.into_iter().zip(out_chunk.iter_mut()) { if !abort_flag.load(Ordering::SeqCst) { @@ -760,7 +760,11 @@ impl BlockRebuilder { } /// Feed an uncompressed state chunk into the rebuilder. - pub fn feed(&mut self, chunk: &[u8], abort_flag: &AtomicBool) -> Result<(), ::error::Error> { + pub fn feed( + &mut self, + chunk: &[u8], + abort_flag: &AtomicBool, + ) -> Result<(), crate::error::Error> { let rlp = UntrustedRlp::new(chunk); let item_count = rlp.item_count()?; let num_blocks = (item_count - 2) as u64; @@ -840,7 +844,7 @@ impl BlockRebuilder { } /// Glue together any disconnected chunks and check that the chain is complete. - fn finalize(&self) -> Result<(), ::error::Error> { + fn finalize(&self) -> Result<(), crate::error::Error> { let mut batch = self.db.transaction(); let genesis_header = self .executor diff --git a/cita-executor/core/src/snapshot/service.rs b/cita-executor/core/src/snapshot/service.rs index c1925ea89..aeb83e15d 100644 --- a/cita-executor/core/src/snapshot/service.rs +++ b/cita-executor/core/src/snapshot/service.rs @@ -27,14 +27,14 @@ use std::sync::Arc; use super::io::{LooseReader, LooseWriter, SnapshotReader, SnapshotWriter}; use super::{BlockRebuilder, ManifestData, RestorationStatus, StateRebuilder}; -use error::Error; +use crate::error::Error; +use crate::libexecutor::executor::Executor; use cita_types::H256; -use libexecutor::executor::Executor; -use cita_db::journaldb::Algorithm; -use cita_db::kvdb::{Database, DatabaseConfig, KeyValueDB}; -use cita_db::TrieError; +use crate::cita_db::journaldb::Algorithm; +use crate::cita_db::kvdb::{Database, DatabaseConfig, KeyValueDB}; +use crate::cita_db::TrieError; use snappy; use util::Bytes; use util::UtilError; diff --git a/cita-executor/core/src/spec/builtin.rs b/cita-executor/core/src/spec/builtin.rs index 5340436ea..4d6e2de05 100644 --- a/cita-executor/core/src/spec/builtin.rs +++ b/cita-executor/core/src/spec/builtin.rs @@ -53,8 +53,8 @@ pub struct Builtin { #[cfg(test)] mod tests { + use crate::spec::builtin::{Builtin, Linear, Pricing}; use serde_json; - use spec::builtin::{Builtin, Linear, Pricing}; #[test] fn builtin_deserialization() { diff --git a/cita-executor/core/src/state/account.rs b/cita-executor/core/src/state/account.rs index d2a6fc7b3..20ceac16a 100644 --- a/cita-executor/core/src/state/account.rs +++ b/cita-executor/core/src/state/account.rs @@ -19,19 +19,20 @@ //! Single account in the system. -use cita_db::{trie, DBValue, HashDB, Trie, TrieFactory}; +use crate::cita_db::{trie, DBValue, HashDB, Trie, TrieFactory}; +use crate::pod_account::*; +use crate::types::basic_account::BasicAccount; use cita_types::traits::LowerHex; use cita_types::{Address, H256, U256}; use hashable::{Hashable, HASH_EMPTY, HASH_NULL_RLP}; use lru_cache::LruCache; -use pod_account::*; use rlp::*; use std::cell::{Cell, RefCell}; +use std::collections::BTreeMap; use std::collections::HashMap; use std::convert::Into; use std::fmt; use std::sync::Arc; -use types::basic_account::BasicAccount; use util::*; const STORAGE_CACHE_ITEMS: usize = 8192; @@ -560,6 +561,17 @@ impl Account { &self.storage_changes } + /// Return the storage cache + pub fn storage_cache(&self) -> BTreeMap { + let mut result = BTreeMap::new(); + for (k, v) in self.storage_cache.borrow().iter() { + let key = String::from("0x") + &hex::encode(*k); + let value = String::from("0x") + &hex::encode(*v); + result.insert(key.clone(), value.clone()); + } + result + } + /// Increment the nonce of the account by one. pub fn inc_nonce(&mut self) { self.nonce = self.nonce + U256::from(1u8); @@ -708,8 +720,8 @@ impl fmt::Debug for Account { #[cfg(test)] mod tests { use super::*; - use account_db::*; - use cita_db::MemoryDB; + use crate::account_db::*; + use crate::cita_db::MemoryDB; use rlp::{Compressible, RlpType, UntrustedRlp}; #[test] diff --git a/cita-executor/core/src/state/backend.rs b/cita-executor/core/src/state/backend.rs index 7058cdf55..8205d9c39 100644 --- a/cita-executor/core/src/state/backend.rs +++ b/cita-executor/core/src/state/backend.rs @@ -16,9 +16,9 @@ use std::sync::Arc; -use cita_db::HashDB; +use crate::cita_db::HashDB; +use crate::state::Account; use cita_types::{Address, H256}; -use state::Account; /// State backend. See module docs for more details. pub trait Backend: Send { diff --git a/cita-executor/core/src/state/mod.rs b/cita-executor/core/src/state/mod.rs index 9a27dc51b..424e27e94 100644 --- a/cita-executor/core/src/state/mod.rs +++ b/cita-executor/core/src/state/mod.rs @@ -19,19 +19,21 @@ //! Unconfirmed sub-states are managed with `checkpoint`s which may be canonicalized //! or rolled back. -use cita_db::{trie, HashDB, Trie, TrieError}; +use crate::cita_db::{trie, HashDB, Trie, TrieError}; +use crate::engines::Engine; +use crate::error::{Error, ExecutionError}; +use crate::executive::{Executive, TransactOptions}; +use crate::factory::Factories; +use crate::libexecutor::economical_model::EconomicalModel; +use crate::libexecutor::sys_config::BlockSysConfig; +use crate::receipt::{Receipt, ReceiptError}; +use crate::trace::FlatTrace; +use crate::types::transaction::SignedTransaction; use cita_types::{Address, H256, U256}; -use engines::Engine; -use error::{Error, ExecutionError}; use evm::env_info::EnvInfo; use evm::Error as EvmError; use evm::Schedule; -use executive::{Executive, TransactOptions}; -use factory::Factories; use hashable::HASH_EMPTY; -use libexecutor::economical_model::EconomicalModel; -use libexecutor::sys_config::BlockSysConfig; -use receipt::{Receipt, ReceiptError}; use rlp::{self, Encodable}; use std::cell::{Ref, RefCell, RefMut}; use std::cmp; @@ -39,8 +41,6 @@ use std::collections::hash_map::Entry; use std::collections::{HashMap, HashSet}; use std::fmt; use std::sync::Arc; -use trace::FlatTrace; -use types::transaction::SignedTransaction; use util::*; pub mod account; @@ -48,7 +48,7 @@ pub mod backend; pub use self::account::Account; use self::backend::*; -pub use substate::Substate; +pub use crate::substate::Substate; /// Used to return information about an `State::apply` operation. pub struct ApplyOutcome { @@ -458,6 +458,13 @@ impl State { }) } + /// Get account of `a` + pub fn account(&self, a: &Address) -> trie::Result> { + self.ensure_cached(a, RequireCache::None, false, |a| { + a.as_ref().map(|account| account.clone_all()) + }) + } + /// Get the nonce of account `a`. pub fn nonce(&self, a: &Address) -> trie::Result { self.ensure_cached(a, RequireCache::None, true, |a| { @@ -1196,23 +1203,23 @@ impl fmt::Debug for State { #[cfg(test)] mod tests { + extern crate cita_logger as logger; extern crate libproto; - extern crate logger; extern crate rustc_hex; //////////////////////////////////////////////////////////////////////////////// use self::libproto::blockchain; use self::rustc_hex::FromHex; use super::*; + use crate::engines::NullEngine; + use crate::libexecutor::sys_config::BlockSysConfig; + use crate::tests::helpers::*; use cita_crypto::KeyPair; use cita_crypto_trait::CreateKey; use cita_types::traits::LowerHex; use cita_types::{Address, H256}; - use engines::NullEngine; use evm::env_info::EnvInfo; - use libexecutor::sys_config::BlockSysConfig; use std::sync::Arc; - use tests::helpers::*; #[test] #[ignore] @@ -1269,7 +1276,7 @@ mod tests { gas_used: 0.into(), account_gas_limit: 1844674.into(), }; - let contract_address = ::executive::contract_address(&signed.sender(), &U256::from(1)); + let contract_address = crate::executive::contract_address(&signed.sender(), &U256::from(1)); let engine = NullEngine::cita(); println!("contract_address {:?}", contract_address); diff --git a/cita-executor/core/src/state_db.rs b/cita-executor/core/src/state_db.rs index 0f272ac7a..3afffcf21 100644 --- a/cita-executor/core/src/state_db.rs +++ b/cita-executor/core/src/state_db.rs @@ -17,15 +17,15 @@ // CITA, Copyright 2016-2017 Cryptape Technologies LLC. // Remove some hf code. +use crate::cita_db::{DBTransaction, HashDB, JournalDB, KeyValueDB}; +use crate::db::COL_ACCOUNT_BLOOM; +use crate::header::BlockNumber; +use crate::state::backend::*; +use crate::state::Account; use byteorder::{ByteOrder, LittleEndian}; -use cita_db::{DBTransaction, HashDB, JournalDB, KeyValueDB}; use cita_types::{Address, H256}; -use db::COL_ACCOUNT_BLOOM; use ethcore_bloom_journal::{Bloom, BloomJournal}; -use header::BlockNumber; use lru_cache::LruCache; -use state::backend::*; -use state::Account; use std::collections::{HashSet, VecDeque}; use std::sync::Arc; use util::cache::MemoryLruCache; diff --git a/cita-executor/core/src/substate.rs b/cita-executor/core/src/substate.rs index 1494760b9..81087f0b7 100644 --- a/cita-executor/core/src/substate.rs +++ b/cita-executor/core/src/substate.rs @@ -16,8 +16,8 @@ //! Execution environment substate. +use crate::log_entry::LogEntry; use cita_types::{Address, U256}; -use log_entry::LogEntry; use std::collections::HashSet; /// State changes which should be applied in finalize, @@ -60,7 +60,7 @@ impl Substate { #[cfg(test)] mod tests { use super::Substate; - use log_entry::LogEntry; + use crate::log_entry::LogEntry; #[test] fn created() { diff --git a/cita-executor/core/src/tests/amend_data_test.rs b/cita-executor/core/src/tests/amend_data_test.rs index 4e6beea66..802e82c2f 100644 --- a/cita-executor/core/src/tests/amend_data_test.rs +++ b/cita-executor/core/src/tests/amend_data_test.rs @@ -16,26 +16,26 @@ // along with this program. If not, see . use super::helpers::*; +use crate::executive::Executive; +use crate::libexecutor::economical_model::EconomicalModel; +use crate::reserved_addresses; +use crate::state::State; +use crate::state_db::*; use cita_types::{Address, H256, U256}; use evm; use evm::action_params::{ActionParams, ActionValue}; -use executive::Executive; -use libexecutor::economical_model::EconomicalModel; -use reserved_addresses; -use state::State; -use state_db::*; use util::{Bytes, BytesRef}; fn call_vm( state: &mut State, params: ActionParams, ) -> evm::Result { - use contracts::native::factory::Factory as NativeFactory; - use engines::NullEngine; + use crate::contracts::native::factory::Factory as NativeFactory; + use crate::engines::NullEngine; + use crate::state::Substate; + use crate::trace::{ExecutiveTracer, ExecutiveVMTracer}; use evm::env_info::EnvInfo; use evm::{Factory, VMType}; - use state::Substate; - use trace::{ExecutiveTracer, ExecutiveVMTracer}; let factory = Factory::new(VMType::Interpreter, 1024 * 32); let native_factory = NativeFactory::default(); let mut tracer = ExecutiveTracer::default(); diff --git a/cita-executor/core/src/tests/grpc_test.rs b/cita-executor/core/src/tests/grpc_test.rs index ecce136b0..90d04fafc 100644 --- a/cita-executor/core/src/tests/grpc_test.rs +++ b/cita-executor/core/src/tests/grpc_test.rs @@ -1,5 +1,5 @@ // CITA -// Copyright 2016-2018 Cryptape Technologies LLC. +// Copyright 2016-2019 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public @@ -16,23 +16,23 @@ // along with this program. If not, see . use super::helpers::*; -use cita_types::{Address, U256}; -use contracts::{ +use crate::contracts::{ grpc::{ contract::{contract_creation_address, low_contract_address}, service_registry, }, native::factory::Factory as NativeFactory, }; -use engines::NullEngine; +use crate::engines::NullEngine; +use crate::executive::Executive; +use crate::libexecutor::economical_model::EconomicalModel; +use crate::state::Substate; +use crate::trace::{ExecutiveTracer, ExecutiveVMTracer}; +use cita_types::{Address, U256}; use evm; use evm::action_params::{ActionParams, ActionValue}; use evm::env_info::EnvInfo; use evm::{Factory, VMType}; -use executive::Executive; -use libexecutor::economical_model::EconomicalModel; -use state::Substate; -use trace::{ExecutiveTracer, ExecutiveVMTracer}; use util::BytesRef; mod grpc_service { @@ -69,7 +69,7 @@ mod grpc_service { (*count).to_string() } "count" => { - let mut count = self.init_count.lock().unwrap(); + let count = self.init_count.lock().unwrap(); (*count).to_string() } "hello" => "hello".to_string(), diff --git a/cita-executor/core/src/tests/helpers.rs b/cita-executor/core/src/tests/helpers.rs index cdd7bdc76..becc834a4 100644 --- a/cita-executor/core/src/tests/helpers.rs +++ b/cita-executor/core/src/tests/helpers.rs @@ -20,34 +20,31 @@ extern crate tempdir; use self::rustc_serialize::hex::FromHex; use self::tempdir::TempDir; +use crate::cita_db::kvdb::{self, Database, DatabaseConfig}; +use crate::cita_db::KeyValueDB; +use crate::db; +use crate::journaldb; +use crate::libexecutor::block::{BlockBody, ClosedBlock, OpenBlock}; +use crate::libexecutor::command; +use crate::libexecutor::executor::Executor; +use crate::state::State; +use crate::state_db::*; +use crate::types::header::OpenHeader; +use crate::types::transaction::SignedTransaction; use cita_crypto::PrivKey; -use cita_db::kvdb::{self, Database, DatabaseConfig}; -use cita_db::KeyValueDB; use cita_types::traits::LowerHex; use cita_types::{Address, U256}; use core::libchain::chain; use crossbeam_channel::{Receiver, Sender}; -use db; -use journaldb; -use libexecutor::block::{Block, BlockBody, ClosedBlock, OpenBlock}; -use libexecutor::command; -use libexecutor::executor::Executor; -use libexecutor::genesis::Genesis; -use libexecutor::genesis::Spec; use libproto::blockchain; -use serde_json; -use state::State; -use state_db::*; use std::env; use std::fs::File; use std::io::Read; use std::io::Write; use std::path::Path; -use std::process::{Command, Output}; +use std::process::Command; use std::sync::Arc; use std::time::UNIX_EPOCH; -use types::header::OpenHeader; -use types::transaction::SignedTransaction; use util::AsMillis; const CHAIN_CONFIG: &str = "chain.toml"; @@ -64,7 +61,7 @@ fn new_db() -> Arc { pub fn get_temp_state_db() -> StateDB { let db = new_db(); - let journal_db = journaldb::new(db, journaldb::Algorithm::Archive, ::db::COL_STATE); + let journal_db = journaldb::new(db, journaldb::Algorithm::Archive, crate::db::COL_STATE); StateDB::new(journal_db, 5 * 1024 * 1024) } @@ -108,13 +105,12 @@ pub fn solc(name: &str, source: &str) -> (Vec, Vec) { (deploy_code, runtime_code) } -pub fn init_executor(contract_arguments: Vec<(&str, &str)>) -> Executor { +pub fn init_executor() -> Executor { let (_fsm_req_sender, fsm_req_receiver) = crossbeam_channel::unbounded(); let (fsm_resp_sender, _fsm_resp_receiver) = crossbeam_channel::unbounded(); let (_command_req_sender, command_req_receiver) = crossbeam_channel::bounded(0); let (command_resp_sender, _command_resp_receiver) = crossbeam_channel::bounded(0); init_executor2( - contract_arguments, fsm_req_receiver, fsm_resp_sender, command_req_receiver, @@ -123,7 +119,6 @@ pub fn init_executor(contract_arguments: Vec<(&str, &str)>) -> Executor { } pub fn init_executor2( - contract_arguments: Vec<(&str, &str)>, fsm_req_receiver: Receiver, fsm_resp_sender: Sender, command_req_receiver: Receiver, @@ -131,74 +126,13 @@ pub fn init_executor2( ) -> Executor { // FIXME temp dir should be removed automatically, but at present it is not let tempdir = TempDir::new("init_executor").unwrap().into_path(); - let create_init_data_py = Path::new(SCRIPTS_DIR).join("config_tool/create_init_data.py"); - let create_genesis_py = Path::new(SCRIPTS_DIR).join("config_tool/create_genesis.py"); - let contracts_dir = Path::new(SCRIPTS_DIR).join("contracts"); - let mut init_data_yml = tempdir.clone(); - init_data_yml.push("init_data.yml"); - let mut genesis_json = tempdir.clone(); - genesis_json.push("genesis.json"); - - let contract_arguments = contract_arguments - .iter() - .map(|(key, value)| format!("{}={}", key, value)) - .collect::>(); - let mut init_data_args: Vec<&str> = vec![ - create_init_data_py.to_str().unwrap(), - "--output", - init_data_yml.to_str().unwrap(), - ]; - if !contract_arguments.is_empty() { - init_data_args.push("--contract_arguments"); - contract_arguments.iter().for_each(|arg| { - init_data_args.push(arg); - }); - } - - fn check_command_output(output: Output) { - if !output.status.success() { - panic!( - "\n[stderr]: {}\n[stdout]: {}", - String::from_utf8_lossy(output.stderr.as_slice()), - String::from_utf8_lossy(output.stdout.as_slice()), - ); - } - } - - let output = Command::new("python3") - .args(init_data_args.as_slice()) - .output() - .expect("Failed to create init data"); - - check_command_output(output); - let output = Command::new("python3") - .args(&[ - create_genesis_py.to_str().unwrap(), - "--output", - genesis_json.to_str().unwrap(), - "--init_data_file", - init_data_yml.to_str().unwrap(), - "--contracts_dir", - contracts_dir.to_str().unwrap(), - ]) - .output() - .expect("Failed to create init data"); - check_command_output(output); - - // Load from genesis json file - println!("genesis_json: {}", genesis_json.to_str().unwrap()); - let genesis_file = File::open(genesis_json.to_str().unwrap()).unwrap(); - let spec: Spec = serde_json::from_reader(genesis_file).expect("Failed to load genesis."); - let _genesis = Genesis { - spec, - block: Block::default(), - }; + let genesis_path = Path::new(SCRIPTS_DIR).join("config_tool/genesis/genesis.json"); let mut data_path = tempdir.clone(); data_path.push("data"); env::set_var("DATA_PATH", data_path); let executor = Executor::init( - genesis_json.to_str().unwrap(), + genesis_path.to_str().unwrap(), "archive", 5 * 1024 * 1024, tempdir.to_str().unwrap().to_string(), @@ -286,7 +220,7 @@ pub fn generate_block_header() -> OpenHeader { pub fn generate_block_body() -> BlockBody { let mut stx = SignedTransaction::default(); - use types::transaction::SignedTransaction; + use crate::types::transaction::SignedTransaction; stx.data = vec![1; 200]; let transactions = vec![stx; 200]; BlockBody { transactions } diff --git a/cita-executor/core/src/trace/config.rs b/cita-executor/core/src/trace/config.rs index 745b88113..f7252adbe 100644 --- a/cita-executor/core/src/trace/config.rs +++ b/cita-executor/core/src/trace/config.rs @@ -16,7 +16,7 @@ //! Traces config. -use bloomchain::Config as BloomConfig; +use crate::bloomchain::Config as BloomConfig; /// Traces config. #[derive(Debug, PartialEq, Clone, Copy)] diff --git a/cita-executor/core/src/trace/db.rs b/cita-executor/core/src/trace/db.rs index a8b0f9bd0..0dfda5f5d 100644 --- a/cita-executor/core/src/trace/db.rs +++ b/cita-executor/core/src/trace/db.rs @@ -17,20 +17,20 @@ //! Trace database. use super::flat::{FlatBlockTraces, FlatTrace, FlatTransactionTraces}; -use bloomchain::group::{BloomGroup, BloomGroupChain, BloomGroupDatabase, GroupPosition}; -use bloomchain::{Bloom, Config as BloomChainConfig, Number as BloomChainNumber}; -use cache_manager::CacheManager; -use cita_db::{DBTransaction, KeyValueDB}; +use crate::bloomchain::group::{BloomGroup, BloomGroupChain, BloomGroupDatabase, GroupPosition}; +use crate::bloomchain::{Bloom, Config as BloomChainConfig, Number as BloomChainNumber}; +use crate::cache_manager::CacheManager; +use crate::cita_db::{DBTransaction, KeyValueDB}; +use crate::db::{self, CacheUpdatePolicy, Key, Readable, Writable}; +use crate::header::BlockNumber; +use crate::log_blooms::LogBloomGroup; +use crate::trace::{ + Config, Database as TraceDatabase, DatabaseExtras, Filter, ImportRequest, LocalizedTrace, +}; use cita_types::{H256, H264}; -use db::{self, CacheUpdatePolicy, Key, Readable, Writable}; -use header::BlockNumber; -use log_blooms::LogBloomGroup; use std::collections::{HashMap, VecDeque}; use std::ops::Deref; use std::sync::Arc; -use trace::{ - Config, Database as TraceDatabase, DatabaseExtras, Filter, ImportRequest, LocalizedTrace, -}; use util::{HeapSizeOf, RwLock}; const TRACE_DB_VER: &[u8] = b"1.0"; @@ -490,16 +490,16 @@ where #[cfg(test)] mod tests { - use cita_db::{kvdb, DBTransaction, KeyValueDB}; + use crate::cita_db::{kvdb, DBTransaction, KeyValueDB}; + use crate::header::BlockNumber; + use crate::trace::flat::{FlatBlockTraces, FlatTrace, FlatTransactionTraces}; + use crate::trace::trace::{Action, Call, Res}; + use crate::trace::{AddressesFilter, Filter, LocalizedTrace, TraceError}; + use crate::trace::{Config, Database as TraceDatabase, DatabaseExtras, ImportRequest, TraceDB}; use cita_types::{Address, H256, U256}; use evm::call_type::CallType; - use header::BlockNumber; use std::collections::HashMap; use std::sync::Arc; - use trace::flat::{FlatBlockTraces, FlatTrace, FlatTransactionTraces}; - use trace::trace::{Action, Call, Res}; - use trace::{AddressesFilter, Filter, LocalizedTrace, TraceError}; - use trace::{Config, Database as TraceDatabase, DatabaseExtras, ImportRequest, TraceDB}; struct NoopExtras; @@ -549,7 +549,7 @@ mod tests { } fn new_db() -> Arc { - Arc::new(kvdb::in_memory(::db::NUM_COLUMNS.unwrap_or(0))) + Arc::new(kvdb::in_memory(crate::db::NUM_COLUMNS.unwrap_or(0))) } #[test] diff --git a/cita-executor/core/src/trace/executive_tracer.rs b/cita-executor/core/src/trace/executive_tracer.rs index a856af215..694c48f1a 100644 --- a/cita-executor/core/src/trace/executive_tracer.rs +++ b/cita-executor/core/src/trace/executive_tracer.rs @@ -16,13 +16,13 @@ //! Simple executive tracer. -use cita_types::{Address, U256}; -use evm::action_params::ActionParams; -use trace::trace::{ +use crate::trace::trace::{ Action, Call, CallResult, Create, CreateResult, MemoryDiff, Res, StorageDiff, Suicide, VMExecutedOperation, VMOperation, VMTrace, }; -use trace::{FlatTrace, TraceError, Tracer, VMTracer}; +use crate::trace::{FlatTrace, TraceError, Tracer, VMTracer}; +use cita_types::{Address, U256}; +use evm::action_params::ActionParams; use util::Bytes; /// Simple executive tracer. Traces all calls and creates. Ignores delegatecalls. diff --git a/cita-executor/core/src/trace/import.rs b/cita-executor/core/src/trace/import.rs index 8951e8198..d22c91f4f 100644 --- a/cita-executor/core/src/trace/import.rs +++ b/cita-executor/core/src/trace/import.rs @@ -16,9 +16,9 @@ //! Traces import request. +use crate::header::BlockNumber; +use crate::trace::FlatBlockTraces; use cita_types::H256; -use header::BlockNumber; -use trace::FlatBlockTraces; /// Traces import request. pub struct ImportRequest { diff --git a/cita-executor/core/src/trace/mod.rs b/cita-executor/core/src/trace/mod.rs index 4f5c53067..822f04776 100644 --- a/cita-executor/core/src/trace/mod.rs +++ b/cita-executor/core/src/trace/mod.rs @@ -37,10 +37,10 @@ pub use self::types::filter::{AddressesFilter, Filter}; pub use self::types::flat::{FlatBlockTraces, FlatTrace, FlatTransactionTraces}; pub use self::types::trace::{MemoryDiff, StorageDiff, VMExecutedOperation, VMOperation, VMTrace}; pub use self::types::{filter, flat, localized, trace}; -use cita_db::DBTransaction; +use crate::cita_db::DBTransaction; +use crate::header::BlockNumber; use cita_types::{Address, H256, U256}; use evm::action_params::ActionParams; -use header::BlockNumber; use util::Bytes; /// This trait is used by executive to build traces. diff --git a/cita-executor/core/src/trace/noop_tracer.rs b/cita-executor/core/src/trace/noop_tracer.rs index f10eb970f..70acfcc12 100644 --- a/cita-executor/core/src/trace/noop_tracer.rs +++ b/cita-executor/core/src/trace/noop_tracer.rs @@ -16,10 +16,10 @@ //! Nonoperative tracer. +use crate::trace::trace::{Call, Create, VMTrace}; +use crate::trace::{FlatTrace, TraceError, Tracer, VMTracer}; use cita_types::{Address, U256}; use evm::action_params::ActionParams; -use trace::trace::{Call, Create, VMTrace}; -use trace::{FlatTrace, TraceError, Tracer, VMTracer}; use util::Bytes; /// Nonoperative tracer. Does not trace anything. diff --git a/cita-executor/core/src/trace/types/filter.rs b/cita-executor/core/src/trace/types/filter.rs index d7799a77e..87fb5de9e 100644 --- a/cita-executor/core/src/trace/types/filter.rs +++ b/cita-executor/core/src/trace/types/filter.rs @@ -17,12 +17,12 @@ //! Trace filters type definitions use super::trace::{Action, Res}; -use basic_types::LogBloom; -use bloomchain::{Bloom, Filter as BloomFilter, Number}; +use crate::basic_types::LogBloom; +use crate::bloomchain::{Bloom, Filter as BloomFilter, Number}; +use crate::trace::flat::FlatTrace; use cita_types::traits::BloomTools; use cita_types::Address; use std::ops::Range; -use trace::flat::FlatTrace; /// Addresses filter. /// @@ -146,13 +146,13 @@ impl Filter { #[cfg(test)] mod tests { - use basic_types::LogBloom; + use crate::basic_types::LogBloom; + use crate::trace::flat::FlatTrace; + use crate::trace::trace::{Action, Call, Create, CreateResult, Res, Suicide}; + use crate::trace::{AddressesFilter, Filter, TraceError}; use cita_types::traits::BloomTools; use cita_types::Address; use evm::call_type::CallType; - use trace::flat::FlatTrace; - use trace::trace::{Action, Call, Create, CreateResult, Res, Suicide}; - use trace::{AddressesFilter, Filter, TraceError}; #[test] fn empty_trace_filter_bloom_possibilities() { diff --git a/cita-executor/core/src/trace/types/flat.rs b/cita-executor/core/src/trace/types/flat.rs index af2d2a5a5..49a6f2c8b 100644 --- a/cita-executor/core/src/trace/types/flat.rs +++ b/cita-executor/core/src/trace/types/flat.rs @@ -17,7 +17,7 @@ //! Flat trace module use super::trace::{Action, Res}; -use basic_types::LogBloom; +use crate::basic_types::LogBloom; use rlp::*; use std::collections::VecDeque; use util::HeapSizeOf; @@ -165,9 +165,9 @@ impl Into> for FlatBlockTraces { #[cfg(test)] mod tests { use super::{FlatBlockTraces, FlatTrace, FlatTransactionTraces}; + use crate::trace::trace::{Action, Call, CallResult, Res, Suicide}; use evm::call_type::CallType; use rlp::*; - use trace::trace::{Action, Call, CallResult, Res, Suicide}; #[test] fn encode_flat_transaction_traces() { diff --git a/cita-executor/core/src/trace/types/localized.rs b/cita-executor/core/src/trace/types/localized.rs index da653e5e4..17cd0d3ce 100644 --- a/cita-executor/core/src/trace/types/localized.rs +++ b/cita-executor/core/src/trace/types/localized.rs @@ -17,8 +17,8 @@ //! Localized traces type definitions use super::trace::{Action, Res}; +use crate::header::BlockNumber; use cita_types::H256; -use header::BlockNumber; /// Localized trace. #[derive(Debug, PartialEq, Clone)] diff --git a/cita-executor/core/src/trace/types/trace.rs b/cita-executor/core/src/trace/types/trace.rs index ca4205e8b..19420d3b2 100644 --- a/cita-executor/core/src/trace/types/trace.rs +++ b/cita-executor/core/src/trace/types/trace.rs @@ -18,7 +18,7 @@ use super::error::Error; -use basic_types::LogBloom; +use crate::basic_types::LogBloom; use cita_types::traits::BloomTools; use cita_types::{Address, U256}; use evm::action_params::ActionParams; diff --git a/cita-executor/evm/Cargo.toml b/cita-executor/evm/Cargo.toml index 0dfa3ccfc..9be6efcc6 100644 --- a/cita-executor/evm/Cargo.toml +++ b/cita-executor/evm/Cargo.toml @@ -2,8 +2,10 @@ name = "evm" version = "0.1.0" authors = ["Parity Technologies ", "Cryptape Technologies "] +edition = "2018" [dependencies] +cita-logger = "0.1.0" cita-types = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } hashable = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } lazy_static = "0.2" @@ -11,7 +13,6 @@ util = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" bit-set = "0.4" common-types = { path = "../../cita-chain/types" } rlp = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } -logger = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } rustc-hex = "1.0" db = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } diff --git a/cita-executor/evm/src/action_params.rs b/cita-executor/evm/src/action_params.rs index ede9aa2fe..e279321da 100644 --- a/cita-executor/evm/src/action_params.rs +++ b/cita-executor/evm/src/action_params.rs @@ -17,7 +17,7 @@ //! Evm input params. // use ethjson; -use call_type::CallType; +use crate::call_type::CallType; use cita_types::{Address, H256, U256}; use hashable::HASH_EMPTY; diff --git a/cita-executor/evm/src/env_info.rs b/cita-executor/evm/src/env_info.rs index 58c348bdf..090a78ee0 100644 --- a/cita-executor/evm/src/env_info.rs +++ b/cita-executor/evm/src/env_info.rs @@ -16,9 +16,9 @@ // use std::cmp; +use crate::types::BlockNumber; use cita_types::{Address, H256, U256}; use std::sync::Arc; -use types::BlockNumber; // use ethjson; /// Simple vector of hashes, should be at most 256 items large, can be smaller if being used diff --git a/cita-executor/evm/src/error.rs b/cita-executor/evm/src/error.rs index ae82f6aa1..db5d6fe04 100644 --- a/cita-executor/evm/src/error.rs +++ b/cita-executor/evm/src/error.rs @@ -16,7 +16,7 @@ //! Evm errors -use cita_db::trie; +use crate::cita_db::trie; use std::fmt; #[derive(Debug, Clone, PartialEq)] diff --git a/cita-executor/evm/src/evm.rs b/cita-executor/evm/src/evm.rs index a54c2d835..afc72609e 100644 --- a/cita-executor/evm/src/evm.rs +++ b/cita-executor/evm/src/evm.rs @@ -16,12 +16,12 @@ //! Evm interface. -use action_params::ActionParams; +use crate::action_params::ActionParams; +use crate::error::{Error, Result}; +use crate::return_data::{GasLeft, ReturnData}; +use crate::Ext; use cita_types::{U128, U256, U512}; -use error::{Error, Result}; -use return_data::{GasLeft, ReturnData}; use std::{cmp, fmt, ops}; -use Ext; /// Finalization result. Gas Left: either it is a known value, or it needs to be computed by processing /// a return instruction. diff --git a/cita-executor/evm/src/ext.rs b/cita-executor/evm/src/ext.rs index 117fcc805..bf04503d5 100644 --- a/cita-executor/evm/src/ext.rs +++ b/cita-executor/evm/src/ext.rs @@ -16,14 +16,14 @@ //! Interface for Evm externalities. -use call_type::CallType; +use crate::call_type::CallType; +use crate::env_info::*; +use crate::error::Result; +use crate::return_data::ReturnData; +use crate::Schedule; use cita_types::{Address, H256, U256}; -use env_info::*; -use error::Result; -use return_data::ReturnData; use std::sync::Arc; use util::*; -use Schedule; /// Result of externalities create function. pub enum ContractCreateResult { diff --git a/cita-executor/evm/src/factory.rs b/cita-executor/evm/src/factory.rs index a6ab0a6c4..3eebb4fdf 100644 --- a/cita-executor/evm/src/factory.rs +++ b/cita-executor/evm/src/factory.rs @@ -19,8 +19,8 @@ //! TODO: consider spliting it into two separate files. use super::interpreter::SharedCache; +use crate::evm::Evm; use cita_types::U256; -use evm::Evm; use std::fmt; use std::sync::Arc; diff --git a/cita-executor/evm/src/fake_tests.rs b/cita-executor/evm/src/fake_tests.rs index 276fdca8c..2ebc58d6d 100644 --- a/cita-executor/evm/src/fake_tests.rs +++ b/cita-executor/evm/src/fake_tests.rs @@ -14,13 +14,13 @@ // You should have received a copy of the GNU General Public License // along with Parity. If not, see . -use call_type::CallType; +use crate::call_type::CallType; +use crate::env_info::EnvInfo; +use crate::error; +use crate::ext::{ContractCreateResult, Ext, MessageCallResult}; +use crate::return_data::{GasLeft, ReturnData}; +use crate::schedule::Schedule; use cita_types::{Address, H256, U256}; -use env_info::EnvInfo; -use error; -use ext::{ContractCreateResult, Ext, MessageCallResult}; -use return_data::{GasLeft, ReturnData}; -use schedule::Schedule; use std::collections::{HashMap, HashSet}; use std::sync::Arc; use util::*; diff --git a/cita-executor/evm/src/interpreter/gasometer.rs b/cita-executor/evm/src/interpreter/gasometer.rs index b76b5b1f7..a0b5aead5 100644 --- a/cita-executor/evm/src/interpreter/gasometer.rs +++ b/cita-executor/evm/src/interpreter/gasometer.rs @@ -15,13 +15,13 @@ // along with Parity. If not, see . use super::u256_to_address; +use crate::error::{Error, Result}; +use crate::evm::CostType; +use crate::ext::Ext; +use crate::instructions::{self, Instruction, InstructionInfo}; +use crate::interpreter::stack::Stack; +use crate::schedule::Schedule; use cita_types::{H256, U256}; -use error::{Error, Result}; -use evm::CostType; -use ext::Ext; -use instructions::{self, Instruction, InstructionInfo}; -use interpreter::stack::Stack; -use schedule::Schedule; use std::cmp; macro_rules! overflowing { diff --git a/cita-executor/evm/src/interpreter/memory.rs b/cita-executor/evm/src/interpreter/memory.rs index dc28d4342..6ee3b3477 100644 --- a/cita-executor/evm/src/interpreter/memory.rs +++ b/cita-executor/evm/src/interpreter/memory.rs @@ -13,8 +13,8 @@ // You should have received a copy of the GNU General Public License // along with Parity. If not, see . +use crate::return_data::ReturnData; use cita_types::U256; -use return_data::ReturnData; const MAX_RETURN_WASTE_BYTES: usize = 16384; @@ -32,7 +32,7 @@ pub trait Memory { /// Read a word from memory fn read(&self, offset: U256) -> U256; /// Write slice of bytes to memory. Does not resize memory! - fn write_slice(&mut self, offset: U256, &[u8]); + fn write_slice(&mut self, offset: U256, _: &[u8]); /// Retrieve part of the memory between offset and offset + size fn read_slice(&self, offset: U256, size: U256) -> &[u8]; /// Retrieve writeable part of memory diff --git a/cita-executor/evm/src/interpreter/mod.rs b/cita-executor/evm/src/interpreter/mod.rs index 5bf5764ec..16158b933 100644 --- a/cita-executor/evm/src/interpreter/mod.rs +++ b/cita-executor/evm/src/interpreter/mod.rs @@ -30,11 +30,11 @@ use self::stack::{Stack, VecStack}; use super::call_type::CallType; use super::error::{Error, Result}; use super::return_data::{GasLeft, ReturnData}; -use action_params::{ActionParams, ActionValue}; +use crate::action_params::{ActionParams, ActionValue}; +use crate::evm::{self, CostType}; +use crate::ext::{ContractCreateResult, Ext, MessageCallResult}; +use crate::instructions::{self, Instruction, InstructionInfo}; use bit_set::BitSet; -use evm::{self, CostType}; -use ext::{ContractCreateResult, Ext, MessageCallResult}; -use instructions::{self, Instruction, InstructionInfo}; use std::cmp; use std::mem; diff --git a/cita-executor/evm/src/lib.rs b/cita-executor/evm/src/lib.rs index ed6e4fa48..146457fa8 100644 --- a/cita-executor/evm/src/lib.rs +++ b/cita-executor/evm/src/lib.rs @@ -16,16 +16,11 @@ //! Ethereum virtual machine. -extern crate bit_set; +#[cfg_attr(feature = "evm-debug", macro_use)] +extern crate cita_logger as logger; pub extern crate cita_types; extern crate common_types as types; extern crate db as cita_db; -extern crate hashable; -#[cfg_attr(feature = "evm-debug", macro_use)] -extern crate logger; -extern crate rlp; -extern crate rustc_hex; -extern crate util; pub mod action_params; pub mod call_type; diff --git a/cita-executor/evm/src/storage.rs b/cita-executor/evm/src/storage.rs index 9f70c8e7a..f016f4a58 100644 --- a/cita-executor/evm/src/storage.rs +++ b/cita-executor/evm/src/storage.rs @@ -15,13 +15,13 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . +use crate::Error as EvmError; +use crate::Ext; use cita_types::{H256, U256}; use std::boxed::Box; use std::convert::From; use std::string::FromUtf8Error; use util::sha3; -use Error as EvmError; -use Ext; //////////////////////////////////////////////////////////////////////////////// pub trait Serialize { @@ -285,7 +285,7 @@ impl Map { #[cfg(test)] mod tests { use super::*; - use fake_tests::FakeExt; + use crate::fake_tests::FakeExt; #[test] fn test_scalar_bytes() { diff --git a/cita-executor/evm/src/tests.rs b/cita-executor/evm/src/tests.rs index 45fef4357..38ae48202 100644 --- a/cita-executor/evm/src/tests.rs +++ b/cita-executor/evm/src/tests.rs @@ -15,12 +15,12 @@ // along with Parity. If not, see . use self::rustc_hex::FromHex; -use action_params::{ActionParams, ActionValue}; +use crate::action_params::{ActionParams, ActionValue}; +use crate::error; +use crate::evm::Evm; +use crate::factory::{Factory, VMType}; +use crate::fake_tests::{test_finalize, FakeCall, FakeCallType, FakeExt}; use cita_types::{Address, H256, U256}; -use error; -use evm::Evm; -use factory::{Factory, VMType}; -use fake_tests::{test_finalize, FakeCall, FakeCallType, FakeExt}; use rustc_hex; use std::collections::{HashMap, HashSet}; use std::fmt::Debug; diff --git a/cita-executor/src/backlogs.rs b/cita-executor/src/backlogs.rs index e4680e0e5..1247fd2fa 100644 --- a/cita-executor/src/backlogs.rs +++ b/cita-executor/src/backlogs.rs @@ -1,5 +1,5 @@ // CITA -// Copyright 2016-2018 Cryptape Technologies LLC. +// Copyright 2016-2019 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public @@ -16,7 +16,7 @@ // along with this program. If not, see . use super::core::libexecutor::block::{ClosedBlock, OpenBlock}; -use cita_db::Itertools; +use crate::cita_db::Itertools; use cita_types::Address; use libproto::{ExecutedResult, Proof}; use std::cmp::min; @@ -414,18 +414,18 @@ pub fn wrap_height(height: usize) -> u64 { #[cfg(test)] mod tests { use super::{wrap_height, Backlog, Backlogs, Priority}; - use cita_db::journaldb; - use cita_db::kvdb::{in_memory, KeyValueDB}; - use core::header::OpenHeader; - use core::libexecutor::block::{BlockBody, ClosedBlock, ExecutedBlock, OpenBlock}; - use core::libexecutor::sys_config::BlockSysConfig; - use core::state_db::StateDB; + use crate::cita_db::journaldb; + use crate::cita_db::kvdb::{in_memory, KeyValueDB}; + use crate::core::header::OpenHeader; + use crate::core::libexecutor::block::{BlockBody, ClosedBlock, ExecutedBlock, OpenBlock}; + use crate::core::libexecutor::sys_config::BlockSysConfig; + use crate::core::state_db::StateDB; use hashable::HASH_NULL_RLP; use std::sync::Arc; fn generate_block_body() -> BlockBody { let mut stx = SignedTransaction::default(); - use types::transaction::SignedTransaction; + use crate::types::transaction::SignedTransaction; stx.data = vec![1; 200]; let transactions = vec![stx; 200]; BlockBody { transactions } diff --git a/cita-executor/src/main.rs b/cita-executor/src/main.rs index 4a13005f3..f711fbf37 100644 --- a/cita-executor/src/main.rs +++ b/cita-executor/src/main.rs @@ -1,5 +1,5 @@ // CITA -// Copyright 2016-2018 Cryptape Technologies LLC. +// Copyright 2016-2019 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public @@ -83,39 +83,28 @@ #[cfg(test)] extern crate cita_crypto; -extern crate cita_directories; -extern crate cita_types; -extern crate clap; extern crate common_types as types; extern crate core_executor as core; #[macro_use] extern crate crossbeam_channel; extern crate db as cita_db; -extern crate dotenv; -extern crate error; -extern crate evm; -extern crate grpc; #[cfg(test)] extern crate hashable; -extern crate jsonrpc_types; #[macro_use] extern crate libproto; #[macro_use] -extern crate logger; -extern crate proof; -extern crate pubsub; +extern crate cita_logger as logger; #[macro_use] extern crate serde_derive; -extern crate serde_json; #[macro_use] extern crate util; +use crate::core::contracts::grpc::grpc_vm_adapter; +use crate::core::libexecutor::executor::Executor; +use crate::postman::Postman; use cita_directories::DataPath; use clap::App; -use core::contracts::grpc::grpc_vm_adapter; -use core::libexecutor::executor::Executor; use libproto::router::{MsgType, RoutingKey, SubModules}; -use postman::Postman; use pubsub::channel; use pubsub::start_pubsub; use std::thread; diff --git a/cita-executor/src/postman.rs b/cita-executor/src/postman.rs index 8b8316e2b..e909714a9 100644 --- a/cita-executor/src/postman.rs +++ b/cita-executor/src/postman.rs @@ -1,5 +1,5 @@ // CITA -// Copyright 2016-2018 Cryptape Technologies LLC. +// Copyright 2016-2019 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public @@ -15,13 +15,14 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . +use crate::core::contracts::solc::sys_config::ChainId; +use crate::core::libexecutor::blacklist::BlackList; +use crate::core::libexecutor::block::{ClosedBlock, OpenBlock}; +use crate::core::libexecutor::call_request::CallRequest; +use crate::core::libexecutor::economical_model::EconomicalModel; +use crate::core::receipt::ReceiptError; +use crate::types::ids::BlockId; use cita_types::{Address, H256, U256}; -use core::contracts::solc::sys_config::ChainId; -use core::libexecutor::blacklist::BlackList; -use core::libexecutor::block::{ClosedBlock, OpenBlock}; -use core::libexecutor::call_request::CallRequest; -use core::libexecutor::economical_model::EconomicalModel; -use core::receipt::ReceiptError; use crossbeam_channel::{Receiver, Sender}; use error::ErrorCode; use jsonrpc_types::rpc_types::{BlockNumber, CountOrCode}; @@ -36,10 +37,9 @@ use serde_json; use std::convert::Into; use std::sync::RwLock; use std::u8; -use types::ids::BlockId; -use core::libexecutor::command; -use core::libexecutor::lru_cache::LRUCache; +use crate::core::libexecutor::command; +use crate::core::libexecutor::lru_cache::LRUCache; use evm::Schedule; use super::backlogs::{wrap_height, Backlogs}; @@ -766,8 +766,8 @@ impl Postman { mod tests { use self::helpers::generate_executed_result; use super::*; + use crate::tests::helpers; use libproto::Message; - use tests::helpers; #[test] fn test_bootstrap_broadcast_at_0th() { diff --git a/cita-executor/src/snapshot.rs b/cita-executor/src/snapshot.rs index a20c61a37..92ded9a0b 100644 --- a/cita-executor/src/snapshot.rs +++ b/cita-executor/src/snapshot.rs @@ -1,5 +1,5 @@ // CITA -// Copyright 2016-2018 Cryptape Technologies LLC. +// Copyright 2016-2019 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public @@ -15,14 +15,12 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . -extern crate crossbeam_channel; - -use cita_db::journaldb::Algorithm; -use cita_db::DatabaseConfig; -use core::db::NUM_COLUMNS; -use core::libexecutor::command; -use core::snapshot as CoreSnapshot; -use core::snapshot::io::{PackedReader, PackedWriter}; +use crate::cita_db::journaldb::Algorithm; +use crate::cita_db::DatabaseConfig; +use crate::core::db::NUM_COLUMNS; +use crate::core::libexecutor::command; +use crate::core::snapshot as CoreSnapshot; +use crate::core::snapshot::io::{PackedReader, PackedWriter}; use crossbeam_channel::{Receiver, Sender}; use libproto::router::{MsgType, RoutingKey, SubModules}; use libproto::snapshot::{Resp as Ack, SnapshotResp}; diff --git a/cita-executor/src/tests/helpers.rs b/cita-executor/src/tests/helpers.rs index a508b1e3c..21a5fee85 100644 --- a/cita-executor/src/tests/helpers.rs +++ b/cita-executor/src/tests/helpers.rs @@ -15,10 +15,10 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . +use crate::postman::Postman; use cita_crypto::{CreateKey, PrivKey, Sign, Signature, Signer}; use cita_types::{traits::LowerHex, Address, H256, U256}; use hashable::Hashable; -use postman::Postman; use std::str::FromStr; #[cfg(feature = "secp256k1")] diff --git a/cita-forever b/cita-forever index 98151d3c9..b7ed8570d 160000 --- a/cita-forever +++ b/cita-forever @@ -1 +1 @@ -Subproject commit 98151d3c9fd89445e08946d01e113dacb8f76002 +Subproject commit b7ed8570d6762c2d3c4c607da7f6379538157eba diff --git a/cita-jsonrpc/Cargo.toml b/cita-jsonrpc/Cargo.toml index 8a9ce241f..ad2e2cb02 100644 --- a/cita-jsonrpc/Cargo.toml +++ b/cita-jsonrpc/Cargo.toml @@ -2,6 +2,7 @@ name = "cita-jsonrpc" version = "0.1.0" authors = ["Cryptape Technologies "] +edition = "2018" [dependencies] futures = "0.1" @@ -14,9 +15,9 @@ serde_json = "1.0" cpuprofiler = "0.0.3" dotenv = "0.13.0" clap = "2" +cita-logger = "0.1.0" util = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } error = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } -logger = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } pubsub = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } libproto = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } jsonrpc-types = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } diff --git a/cita-jsonrpc/README.md b/cita-jsonrpc/README.md index 634bcc725..3cc4111c6 100644 --- a/cita-jsonrpc/README.md +++ b/cita-jsonrpc/README.md @@ -1,19 +1,11 @@ ## JSON-RPC -[在线文档](https://cryptape.github.io/cita/zh/usage-guide/rpc/index.html) +[在线文档](https://docs.citahub.com/zh-CN/next/cita/rpc-guide/rpc) -[online doc](https://cryptape.github.io/cita/en/usage-guide/rpc/index.html) - -文档路径: `docs/docs/zh/usage-guide/rpc.md` - -Path of doc: `docs/docs/en/usage-guide/rpc.md` +[online doc](https://docs.citahub.com/en-US/next/cita/rpc-guide/rpc) ## JSON-RPC ERROR CODE -[在线文档](https://cryptape.github.io/cita/zh/usage-guide/rpc_error_code/index.html) - -[online doc](https://cryptape.github.io/cita/en/usage-guide/rpc_error_code/index.html) - -文档路径: `docs/docs/zh/usage-guide/rpc_error_code.md` +[在线文档](https://docs.citahub.com/zh-CN/next/cita/rpc-guide/rpc-error-code) -Path of doc: `docs/docs/en/usage-guide/rpc_error_code.md` +[online doc](https://docs.citahub.com/en-US/next/cita/rpc-guide/rpc-error-code) diff --git a/cita-jsonrpc/build.rs b/cita-jsonrpc/build.rs index a0533082a..c20d26175 100644 --- a/cita-jsonrpc/build.rs +++ b/cita-jsonrpc/build.rs @@ -1,5 +1,5 @@ // CITA -// Copyright 2016-2018 Cryptape Technologies LLC. +// Copyright 2016-2019 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public @@ -15,8 +15,6 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . -extern crate util; - use std::env; use util::build_info::gen_build_info; diff --git a/cita-jsonrpc/src/config.rs b/cita-jsonrpc/src/config.rs index 97f6fd878..7cceee0c4 100644 --- a/cita-jsonrpc/src/config.rs +++ b/cita-jsonrpc/src/config.rs @@ -1,5 +1,5 @@ // CITA -// Copyright 2016-2017 Cryptape Technologies LLC. +// Copyright 2016-2019 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public diff --git a/cita-jsonrpc/src/extractor.rs b/cita-jsonrpc/src/extractor.rs index fd3530aa0..4f4f88693 100644 --- a/cita-jsonrpc/src/extractor.rs +++ b/cita-jsonrpc/src/extractor.rs @@ -1,5 +1,5 @@ // CITA -// Copyright 2016-2018 Cryptape Technologies LLC. +// Copyright 2016-2019 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public diff --git a/cita-jsonrpc/src/fdlimit.rs b/cita-jsonrpc/src/fdlimit.rs index 3d13f6e57..f48307a3c 100644 --- a/cita-jsonrpc/src/fdlimit.rs +++ b/cita-jsonrpc/src/fdlimit.rs @@ -1,5 +1,5 @@ // CITA -// Copyright 2016-2018 Cryptape Technologies LLC. +// Copyright 2016-2019 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public diff --git a/cita-jsonrpc/src/helper.rs b/cita-jsonrpc/src/helper.rs index ba7782ba7..1eb7796ed 100644 --- a/cita-jsonrpc/src/helper.rs +++ b/cita-jsonrpc/src/helper.rs @@ -1,5 +1,5 @@ // CITA -// Copyright 2016-2018 Cryptape Technologies LLC. +// Copyright 2016-2019 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public diff --git a/cita-jsonrpc/src/http_header.rs b/cita-jsonrpc/src/http_header.rs index 0c5bef398..191856a8b 100644 --- a/cita-jsonrpc/src/http_header.rs +++ b/cita-jsonrpc/src/http_header.rs @@ -1,5 +1,5 @@ // CITA -// Copyright 2016-2018 Cryptape Technologies LLC. +// Copyright 2016-2019 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public diff --git a/cita-jsonrpc/src/http_server.rs b/cita-jsonrpc/src/http_server.rs index 83d519528..878a87000 100644 --- a/cita-jsonrpc/src/http_server.rs +++ b/cita-jsonrpc/src/http_server.rs @@ -1,5 +1,5 @@ // CITA -// Copyright 2016-2018 Cryptape Technologies LLC. +// Copyright 2016-2019 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public @@ -294,23 +294,20 @@ pub fn listener_from_socket_addr(addr: &SocketAddr) -> std::io::Result. -use helper::{RpcMap, TransferType}; +use crate::helper::{RpcMap, TransferType}; use jsonrpc_proto::response::OutputExt; use jsonrpc_types::rpc_response::Output; use libproto::router::{MsgType, RoutingKey, SubModules}; diff --git a/cita-jsonrpc/src/mq_publisher.rs b/cita-jsonrpc/src/mq_publisher.rs index ef14c9cc9..8b450302a 100644 --- a/cita-jsonrpc/src/mq_publisher.rs +++ b/cita-jsonrpc/src/mq_publisher.rs @@ -1,5 +1,5 @@ // CITA -// Copyright 2016-2018 Cryptape Technologies LLC. +// Copyright 2016-2019 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public diff --git a/cita-jsonrpc/src/response.rs b/cita-jsonrpc/src/response.rs index 73a7d7620..70ea637f2 100644 --- a/cita-jsonrpc/src/response.rs +++ b/cita-jsonrpc/src/response.rs @@ -1,5 +1,5 @@ // CITA -// Copyright 2016-2018 Cryptape Technologies LLC. +// Copyright 2016-2019 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public @@ -49,7 +49,7 @@ impl HyperResponseExt for HyperResponse { } pub trait IntoResponse { - fn into_response(self, Headers) -> Response; + fn into_response(self, _: Headers) -> Response; } pub trait FutureResponse @@ -195,7 +195,7 @@ mod tests { #[test] fn test_hyper_response_with_headers() { - use http_header::HeaderMapExt; + use crate::http_header::HeaderMapExt; use hyper::{header::*, Method}; let mut headers = HeaderMap::new(); diff --git a/cita-jsonrpc/src/service_error.rs b/cita-jsonrpc/src/service_error.rs index 5d68274a4..3288349e4 100644 --- a/cita-jsonrpc/src/service_error.rs +++ b/cita-jsonrpc/src/service_error.rs @@ -1,5 +1,5 @@ // CITA -// Copyright 2016-2018 Cryptape Technologies LLC. +// Copyright 2016-2019 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public diff --git a/cita-jsonrpc/src/soliloquy.rs b/cita-jsonrpc/src/soliloquy.rs index 7cb7d3aae..6d3fb084e 100644 --- a/cita-jsonrpc/src/soliloquy.rs +++ b/cita-jsonrpc/src/soliloquy.rs @@ -15,8 +15,8 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . -use config::Config; -use get_build_info_str; +use crate::config::Config; +use crate::get_build_info_str; use jsonrpc_types::rpc_types::SoftwareVersion; use jsonrpc_types::ErrorCode; use libproto::protos::response::Response; @@ -71,11 +71,11 @@ impl Soliloquy { #[cfg(test)] pub mod tests { - use config::Config; + use crate::config::Config; + use crate::soliloquy::Soliloquy; use jsonrpc_types::ErrorCode; use libproto::Message; use libproto::TryInto; - use soliloquy::Soliloquy; fn get_response(toml_str: String) -> libproto::response::Response { let config = util::parse_config_from_buffer::(&toml_str) diff --git a/cita-jsonrpc/src/ws_handler.rs b/cita-jsonrpc/src/ws_handler.rs index d1a51e75e..edcaff260 100644 --- a/cita-jsonrpc/src/ws_handler.rs +++ b/cita-jsonrpc/src/ws_handler.rs @@ -1,5 +1,5 @@ // CITA -// Copyright 2016-2017 Cryptape Technologies LLC. +// Copyright 2016-2019 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public @@ -15,7 +15,7 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . -use helper::{select_topic, RpcMap, TransferType}; +use crate::helper::{select_topic, RpcMap, TransferType}; use jsonrpc_proto::complete::CompleteInto; use jsonrpc_types::rpc_request::{PartialRequest, RequestInfo}; use jsonrpc_types::rpc_response::RpcFailure; @@ -70,7 +70,6 @@ impl Factory for WsFactory { impl Handler for WsHandler { fn on_message(&mut self, msg: ws::Message) -> ws::Result<()> { trace!("Server got message '{}' post thread_pool deal task ", msg); - // let this = self.clone(); let tx = self.tx.clone(); let response = Arc::clone(&self.responses); let sender = self.sender.clone(); diff --git a/cita-network/Cargo.toml b/cita-network/Cargo.toml index c9c083958..27b564956 100644 --- a/cita-network/Cargo.toml +++ b/cita-network/Cargo.toml @@ -6,14 +6,14 @@ edition = "2018" [dependencies] tentacle-discovery = "0.2.4" -tentacle = "0.2.0-alpha.14" +tentacle = "0.2.1" tokio = "0.1.14" futures = "0.1.25" +cita-logger = "0.1.0" cita-types = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } util = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } libproto = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } pubsub = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } -logger = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } jsonrpc-types = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } serde = "1.0.84" serde_json = "1.0" diff --git a/cita-network/src/cita_protocol.rs b/cita-network/src/cita_protocol.rs index 1cc05e59b..0ad3b62c9 100644 --- a/cita-network/src/cita_protocol.rs +++ b/cita-network/src/cita_protocol.rs @@ -18,8 +18,8 @@ //! A multiplexed cita protocol use byteorder::{ByteOrder, NetworkEndian}; -use bytes::BufMut; -use bytes::BytesMut; +use bytes::{BufMut, Bytes, BytesMut}; +use cita_types::Address; use logger::{error, warn}; use std::str; @@ -36,8 +36,12 @@ use std::str; /// +------------------------+--------------------------+ /// | Symbol for Start | \xDEADBEEF | /// | Length of Full Payload | u32 | -/// +------------------------+--------------------------+ +/// | Version | u64 | +/// | Address | u8;20 | /// | Length of Key | u8 | +/// | TTL | u8 | +/// | Reserved | u8;2 | +/// +------------------------+--------------------------+ /// | Key | bytes of a str | /// +------------------------+--------------------------+ /// | Message | a serialize data | @@ -47,79 +51,116 @@ use std::str; // Start of network messages. const NETMSG_START: u64 = 0xDEAD_BEEF_0000_0000; -// According to CITA frame, defines its frame header length as: -// "Symbol for Start" + "Length of Full Payload" + "Length of Key", -// And this will consume "4 + 4 + 1" fixed-lengths of the frame. -pub const CITA_FRAME_HEADER_LEN: usize = 4 + 4 + 1; +/// According to CITA frame, defines its frame header length as: +/// "Symbol for Start" + "Length of Full Payload" + "Version"+ +/// "Address"+ "Length of Key"+"TTL"+"Reserved", +/// And this will consume "4 + 4 + 8 + 20 + 1 + 1+ 2" fixed-lengths of the frame. +pub const CITA_FRAME_HEADER_LEN: usize = 4 + 4 + 8 + 20 + 1 + 1 + 2; +pub const HEAD_VERSION_OFFSET: usize = 4 + 4; +pub const HEAD_ADDRESS_OFFSET: usize = 4 + 4 + 8; +pub const HEAD_KEY_LEN_OFFSET: usize = 4 + 4 + 8 + 20; +pub const HEAD_TTL_OFFSET: usize = 4 + 4 + 8 + 20 + 1; + +pub const DEFAULT_TTL_NUM: u8 = 0; +pub const CONSENSUS_TTL_NUM: u8 = 9; +pub const CONSENSUS_STR: &str = "consensus"; + +#[derive(Debug, Clone)] +pub struct NetMessageUnit { + pub key: String, + pub data: Vec, + pub addr: Address, + pub version: u64, + pub ttl: u8, +} -fn opt_bytes_extend(buf: &mut Vec, data: &[u8]) { - buf.reserve(data.len()); - unsafe { - buf.bytes_mut()[..data.len()].copy_from_slice(data); - buf.advance_mut(data.len()); +impl NetMessageUnit { + pub fn new(key: String, data: Vec, addr: Address, version: u64, ttl: u8) -> Self { + NetMessageUnit { + key, + data, + addr, + version, + ttl, + } } } -pub fn pubsub_message_to_network_message(buf: &mut Vec, msg: Option<(String, Vec)>) { - let mut request_id_bytes = [0; 8]; - if let Some((key, body)) = msg { - let length_key = key.len(); - // Use 1 byte to store key length. - if length_key > u8::max_value() as usize { - error!("[CitaProtocol] The MQ message key is too long {}.", key); - return; - } - // Use 1 bytes to store the length for key, then store key, the last part is body. - let length_full = 1 + length_key + body.len(); - if length_full > u32::max_value() as usize { - error!( - "[CitaProtocol] The MQ message with key {} is too long {}.", - key, - body.len() - ); - return; +impl Default for NetMessageUnit { + fn default() -> Self { + NetMessageUnit { + key: String::default(), + data: Vec::new(), + addr: Address::zero(), + version: 0, + ttl: DEFAULT_TTL_NUM, } - let request_id = NETMSG_START + length_full as u64; - NetworkEndian::write_u64(&mut request_id_bytes, request_id); - opt_bytes_extend(buf, &request_id_bytes); - buf.put_u8(length_key as u8); - opt_bytes_extend(buf, key.as_bytes()); - opt_bytes_extend(buf, &body); - } else { - let request_id = NETMSG_START; - NetworkEndian::write_u64(&mut request_id_bytes, request_id); - opt_bytes_extend(buf, &request_id_bytes); } } -pub fn network_message_to_pubsub_message(buf: &mut BytesMut) -> Option<(String, Vec)> { - if buf.len() < 8 { +pub fn pubsub_message_to_network_message(info: &NetMessageUnit) -> Option { + let length_key = info.key.len(); + // Use 1 byte to store key length. + if length_key == 0 || length_key > u8::max_value() as usize { + error!( + "[CitaProtocol] The MQ message key is too long or empty {}.", + info.key + ); + return None; + } + let length_full = length_key + info.data.len(); + // Use 1 bytes to store the length for key, then store key, the last part is body. + if length_full > u32::max_value() as usize { + error!( + "[CitaProtocol] The MQ message with key {} is too long {}.", + info.key, + info.data.len() + ); + return None; + } + + let mut buf = BytesMut::with_capacity(length_full + CITA_FRAME_HEADER_LEN); + let request_id = NETMSG_START + length_full as u64; + buf.put_u64_be(request_id); + buf.put_u64_be(info.version); + buf.put(info.addr.to_vec()); + buf.put_u8(length_key as u8); + buf.put_u8(info.ttl); + buf.put_u16_be(0); + + buf.put(info.key.as_bytes()); + buf.put_slice(&info.data); + + Some(buf.into()) +} + +pub fn network_message_to_pubsub_message(buf: &mut BytesMut) -> Option { + if buf.len() < CITA_FRAME_HEADER_LEN { return None; } - let request_id = NetworkEndian::read_u64(buf.as_ref()); + let head_buf = buf.split_to(CITA_FRAME_HEADER_LEN); + + let request_id = NetworkEndian::read_u64(&head_buf); let netmsg_start = request_id & 0xffff_ffff_0000_0000; let length_full = (request_id & 0x0000_0000_ffff_ffff) as usize; if netmsg_start != NETMSG_START { return None; } - if length_full + 8 > buf.len() { + if length_full > buf.len() || length_full == 0 { return None; } - let _request_id_buf = buf.split_to(8); - if length_full == 0 { - return None; - } - let mut payload_buf = buf.split_to(length_full); + let addr = Address::from_slice(&head_buf[HEAD_ADDRESS_OFFSET..]); + let version = NetworkEndian::read_u64(&head_buf[HEAD_VERSION_OFFSET..]); - let length_key = payload_buf[0] as usize; - let _length_key_buf = payload_buf.split_to(1); + let length_key = head_buf[HEAD_KEY_LEN_OFFSET] as usize; + let ttl = head_buf[HEAD_TTL_OFFSET]; if length_key == 0 { error!("[CitaProtocol] Network message key is empty."); return None; } - if length_key > payload_buf.len() { + if length_key > buf.len() { error!( "[CitaProtocol] Buffer is not enough for key {} > {}.", length_key, @@ -127,7 +168,7 @@ pub fn network_message_to_pubsub_message(buf: &mut BytesMut) -> Option<(String, ); return None; } - let key_buf = payload_buf.split_to(length_key); + let key_buf = buf.split_to(length_key); let key_str_result = str::from_utf8(&key_buf); if key_str_result.is_err() { error!( @@ -137,35 +178,46 @@ pub fn network_message_to_pubsub_message(buf: &mut BytesMut) -> Option<(String, return None; } let key = key_str_result.unwrap().to_string(); - if length_full == 1 + length_key { + if length_full == length_key { warn!("[CitaProtocol] Network message is empty."); } - Some((key, payload_buf.to_vec())) + Some(NetMessageUnit { + key, + data: buf.to_vec(), + addr, + version, + ttl, + }) } #[cfg(test)] mod test { - use super::{network_message_to_pubsub_message, pubsub_message_to_network_message}; + use super::{ + network_message_to_pubsub_message, pubsub_message_to_network_message, NetMessageUnit, + }; use bytes::BytesMut; #[test] fn convert_empty_message() { - let mut buf = Vec::with_capacity(4 + 4); - pubsub_message_to_network_message(&mut buf, None); - let pub_msg_opt = network_message_to_pubsub_message(&mut BytesMut::from(buf)); + let buf = pubsub_message_to_network_message(&NetMessageUnit::default()); + let pub_msg_opt = network_message_to_pubsub_message(&mut BytesMut::new()); assert!(pub_msg_opt.is_none()); + assert!(buf.is_none()); } #[test] fn convert_messages() { + let mut msg = NetMessageUnit::default(); let key = "this-is-the-key".to_string(); - let msg: Vec = vec![1, 3, 5, 7, 9]; - let mut buf = Vec::with_capacity(4 + 4 + 1 + key.len() + msg.len()); - pubsub_message_to_network_message(&mut buf, Some((key.clone(), msg.clone()))); - let pub_msg_opt = network_message_to_pubsub_message(&mut BytesMut::from(buf)); + let data = vec![1, 3, 5, 7, 9]; + msg.key = key.clone(); + msg.data = data.clone(); + + let buf = pubsub_message_to_network_message(&msg).unwrap(); + let pub_msg_opt = network_message_to_pubsub_message(&mut buf.try_mut().unwrap()); assert!(pub_msg_opt.is_some()); - let (key_new, msg_new) = pub_msg_opt.unwrap(); - assert_eq!(key, key_new); - assert_eq!(msg, msg_new); + let info = pub_msg_opt.unwrap(); + assert_eq!(key, info.key); + assert_eq!(data, info.data); } } diff --git a/cita-network/src/config.rs b/cita-network/src/config.rs index 05d60a157..376151232 100644 --- a/cita-network/src/config.rs +++ b/cita-network/src/config.rs @@ -16,7 +16,6 @@ // along with this program. If not, see . use cita_types::{clean_0x, Address}; -use logger::info; use serde_derive::Deserialize; use std::fs::File; use std::io::Read; diff --git a/cita-network/src/main.rs b/cita-network/src/main.rs index f3e2fbbd0..fa2cd4955 100644 --- a/cita-network/src/main.rs +++ b/cita-network/src/main.rs @@ -79,6 +79,9 @@ //! [`network_message_to_pubsub_message`]: ./citaprotocol/fn.network_message_to_pubsub_message.html //! +#[macro_use] +extern crate cita_logger as logger; + pub mod cita_protocol; pub mod config; pub mod mq_agent; @@ -98,7 +101,6 @@ use crate::synchronizer::Synchronizer; use clap::App; use dotenv; use futures::prelude::*; -use logger::{debug, info}; use notify::{RecommendedWatcher, RecursiveMode, Watcher}; use std::path::Path; use std::sync::mpsc::channel; @@ -169,7 +171,8 @@ fn main() { mq_agent.set_nodes_mgr_client(nodes_mgr.client()); mq_agent.set_network_client(network_mgr.client()); - let transfer_meta = create_transfer_meta(network_mgr.client(), nodes_mgr.client()); + let transfer_meta = + create_transfer_meta(network_mgr.client(), nodes_mgr.client(), own_addr.addr); let mut service_cfg = ServiceBuilder::default() .insert_protocol(transfer_meta) .forever(true); @@ -188,7 +191,7 @@ fn main() { }); } - if nodes_mgr.is_enable_tls() { + if config.enable_tls.unwrap_or(false) { service_cfg = service_cfg.key_pair(SecioKeyPair::secp256k1_generated()); } let mut service = service_cfg.build(SHandle::new(nodes_mgr.client())); diff --git a/cita-network/src/mq_agent.rs b/cita-network/src/mq_agent.rs index 40cbaa75f..f88d4662d 100644 --- a/cita-network/src/mq_agent.rs +++ b/cita-network/src/mq_agent.rs @@ -20,7 +20,6 @@ use crate::node_manager::NodesManagerClient; use libproto::router::{MsgType, RoutingKey, SubModules}; use libproto::routing_key; use libproto::{Message, TryFrom}; -use logger::{trace, warn}; use pubsub::channel::{unbounded, Receiver, Sender}; use pubsub::start_pubsub; use std::thread; @@ -67,6 +66,7 @@ impl MqAgent { "network", routing_key!([ Chain >> Status, + Chain >> RichStatus, Chain >> SyncResponse, Jsonrpc >> RequestNet, Jsonrpc >> RequestPeersInfo, diff --git a/cita-network/src/network.rs b/cita-network/src/network.rs index 02c25cdac..c118516dd 100644 --- a/cita-network/src/network.rs +++ b/cita-network/src/network.rs @@ -17,7 +17,8 @@ use crate::mq_agent::{MqAgentClient, PubMessage}; use crate::node_manager::{ - BroadcastReq, GetPeerCountReq, GetPeersInfoReq, NodesManagerClient, SingleTxReq, + BroadcastReq, DealRichStatusReq, GetPeerCountReq, GetPeersInfoReq, NodesManagerClient, + SingleTxReq, }; use crate::synchronizer::{SynchronizerClient, SynchronizerMessage}; use jsonrpc_types::rpc_types::PeersInfo; @@ -27,7 +28,6 @@ use libproto::routing_key; use libproto::snapshot::{Cmd, Resp, SnapshotResp}; use libproto::{Message as ProtoMessage, OperateType, Response}; use libproto::{TryFrom, TryInto}; -use logger::{error, info, trace, warn}; use pubsub::channel::{unbounded, Receiver, Sender}; use serde_json; use std::iter::FromIterator; @@ -138,6 +138,11 @@ impl LocalMessage { .sync_client .handle_local_status(SynchronizerMessage::new(self.key, self.data)); } + routing_key!(Chain >> RichStatus) => { + let msg = ProtoMessage::try_from(&self.data).unwrap(); + let req = DealRichStatusReq::new(msg); + service.nodes_mgr_client.deal_rich_status(req); + } routing_key!(Chain >> SyncResponse) => { let msg = ProtoMessage::try_from(&self.data).unwrap(); send_message( diff --git a/cita-network/src/node_manager.rs b/cita-network/src/node_manager.rs index a464b7bb9..af3f06723 100644 --- a/cita-network/src/node_manager.rs +++ b/cita-network/src/node_manager.rs @@ -15,17 +15,18 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . -use crate::cita_protocol::{pubsub_message_to_network_message, CITA_FRAME_HEADER_LEN}; +use crate::cita_protocol::{ + pubsub_message_to_network_message, NetMessageUnit, CONSENSUS_STR, CONSENSUS_TTL_NUM, +}; use crate::config::NetConfig; use crate::p2p_protocol::transfer::TRANSFER_PROTOCOL_ID; use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; use cita_types::Address; use fnv::FnvHashMap as HashMap; use libproto::{Message as ProtoMessage, TryInto}; -use logger::{debug, error, info, trace, warn}; use notify::DebouncedEvent; use pubsub::channel::{select, tick, unbounded, Receiver, Sender}; -use rand; +use rand::{thread_rng, Rng}; use std::sync::mpsc::Receiver as StdReceiver; use std::{ collections::{BTreeMap, BTreeSet}, @@ -127,14 +128,66 @@ impl TransformAddr { } } +#[derive(Default, Debug)] +pub struct ConsensusNodeTopology { + pub linked_nodes: BTreeSet
, + pub validator_nodes: BTreeSet
, + //pub consensus_threshold_linked : bool, + pub consensus_all_linked: bool, + pub height: u64, +} + +impl ConsensusNodeTopology { + pub fn new(self_address: Address) -> ConsensusNodeTopology { + let mut top = ConsensusNodeTopology::default(); + top.linked_nodes.insert(self_address); + top + } + + fn validator_subset_linked(&self) -> bool { + self.validator_nodes.is_subset(&self.linked_nodes) + } + + pub fn update_validators(&mut self, height: u64, validators: BTreeSet
) { + if height < self.height || validators == self.validator_nodes { + debug!("No need update validator height {} self height {} validator {:?} self validator {:?}", + height,self.height,validators,self.validator_nodes); + + if height > self.height { + self.height = height; + } + return; + } + self.validator_nodes = validators; + self.consensus_all_linked = self.validator_subset_linked(); + } + + pub fn add_linked_nodes(&mut self, linked_node: Address) { + if self.linked_nodes.insert(linked_node) { + self.consensus_all_linked = self.validator_subset_linked(); + } + } + + pub fn del_linked_nodes(&mut self, linked_node: &Address) { + if self.linked_nodes.remove(linked_node) { + self.consensus_all_linked = self.validator_subset_linked(); + } + } + + pub fn consensus_all_linked(&self) -> bool { + self.consensus_all_linked + } + //pub fn consensus_threshold_linked(&self) -> bool {self.consensus_threshold_linked} +} + pub struct NodesManager { known_addrs: HashMap, config_addrs: BTreeMap>, - connected_addrs: HashMap, - pending_connected_addrs: HashMap, + connected_addrs: BTreeMap, + pending_connected_addrs: BTreeMap, - connected_peer_keys: HashMap, + connected_peer_keys: BTreeMap, check_connected_nodes: Receiver, max_connects: usize, @@ -142,27 +195,49 @@ pub struct NodesManager { nodes_manager_service_receiver: Receiver, service_ctrl: Option, peer_key: Address, - enable_tls: bool, + + gossip_key_version: HashMap, + consensus_topology: ConsensusNodeTopology, + + self_version: u64, + dialing_node: Option, self_addr: Option, } impl NodesManager { - pub fn new(known_addrs: HashMap) -> Self { - let mut node_mgr = NodesManager::default(); - node_mgr.known_addrs = known_addrs; - node_mgr + fn new(peer_key: Address) -> NodesManager { + let (tx, rx) = unbounded(); + let ticker = tick(CHECK_CONNECTED_NODES); + let client = NodesManagerClient { sender: tx }; + + // Set enable_tls = false as default. + NodesManager { + check_connected_nodes: ticker, + known_addrs: HashMap::default(), + config_addrs: BTreeMap::default(), + connected_addrs: BTreeMap::default(), + connected_peer_keys: BTreeMap::default(), + pending_connected_addrs: BTreeMap::default(), + max_connects: DEFAULT_MAX_CONNECTS, + nodes_manager_client: client, + nodes_manager_service_receiver: rx, + service_ctrl: None, + peer_key, + dialing_node: None, + self_addr: None, + gossip_key_version: HashMap::default(), + self_version: 0, + consensus_topology: ConsensusNodeTopology::new(peer_key), + } } pub fn from_config(cfg: NetConfig, key: Address) -> Self { - let mut node_mgr = NodesManager::default(); + let mut node_mgr = NodesManager::new(key); let max_connects = cfg.max_connects.unwrap_or(DEFAULT_MAX_CONNECTS); node_mgr.max_connects = max_connects; node_mgr.peer_key = key; - if let Some(enable_tls) = cfg.enable_tls { - node_mgr.enable_tls = enable_tls; - } if let Some(cfg_addrs) = cfg.peers { for addr in cfg_addrs { if let (Some(ip), Some(port)) = (addr.ip, addr.port) { @@ -248,12 +323,16 @@ impl NodesManager { // If connected node has not reach MAX, select a node from known_addrs to dial. if self.connected_addrs.len() < self.max_connects { - for (key, value) in self.known_addrs.iter_mut() { + let mut socks: Vec<_> = self.known_addrs.keys().cloned().collect(); + thread_rng().shuffle(&mut socks); + + for key in socks { + let value = self.known_addrs.get_mut(&key).unwrap(); // Node has been connected if let Some(session_id) = value.session_id { debug!( "[NodeManager] Address {:?} has been connected on : {:?}.", - *key, session_id + key, session_id ); // Node keep on line, reward KEEP_ON_LINE_SCORE. @@ -265,19 +344,8 @@ impl NodesManager { continue; } - // Give 50% probability to select this node, this design can avoid two nodes - // simultaneously dialing each other. - let selected_miss: bool = (rand::random::() % 2) != 0; - if selected_miss { - debug!( - "[NodeManager] Address {:?} selects miss in this round.", - *key - ); - continue; - } - if let Some(self_addr) = self.self_addr { - if *key == self_addr { + if key == self_addr { debug!( "[NodeManager] Trying to connected self: {:?}, skip it", self_addr @@ -290,7 +358,7 @@ impl NodesManager { if value.score < MIN_DIALING_SCORE { debug!( "[NodeManager] Address {:?} has to low score ({:?}) to dial.", - *key, value.score + key, value.score ); // The node will get time sugar, the nodes which in config file can get 2, and the @@ -305,9 +373,9 @@ impl NodesManager { // Dial this address if let Some(ref mut ctrl) = self.service_ctrl { - self.dialing_node = Some(*key); + self.dialing_node = Some(key); info!("Trying to dial: {:?}", self.dialing_node); - match ctrl.dial(socketaddr_to_multiaddr(*key), DialProtocol::All) { + match ctrl.dial(socketaddr_to_multiaddr(key), DialProtocol::All) { Ok(_) => { // Need DIALING_SCORE for every dial. value.score -= DIALING_SCORE; @@ -337,10 +405,6 @@ impl NodesManager { self.service_ctrl = Some(ctrl); } - pub fn is_enable_tls(&self) -> bool { - self.enable_tls - } - pub fn translate_address(&mut self) { for (key, value) in self.config_addrs.iter_mut() { // The address has translated. @@ -370,32 +434,6 @@ impl NodesManager { } } -impl Default for NodesManager { - fn default() -> NodesManager { - let (tx, rx) = unbounded(); - let ticker = tick(CHECK_CONNECTED_NODES); - let client = NodesManagerClient { sender: tx }; - - // Set enable_tls = false as default. - NodesManager { - check_connected_nodes: ticker, - known_addrs: HashMap::default(), - config_addrs: BTreeMap::default(), - connected_addrs: HashMap::default(), - connected_peer_keys: HashMap::default(), - pending_connected_addrs: HashMap::default(), - max_connects: DEFAULT_MAX_CONNECTS, - nodes_manager_client: client, - nodes_manager_service_receiver: rx, - service_ctrl: None, - peer_key: Address::zero(), - enable_tls: false, - dialing_node: None, - self_addr: None, - } - } -} - #[derive(Clone, Debug)] pub struct NodesManagerClient { sender: Sender, @@ -438,6 +476,10 @@ impl NodesManagerClient { self.send_req(NodesManagerMessage::Broadcast(req)); } + pub fn retrans_net_msg(&self, req: RetransNetMsgReq) { + self.send_req(NodesManagerMessage::RetransNetMsg(req)); + } + pub fn send_message(&self, req: SingleTxReq) { self.send_req(NodesManagerMessage::SingleTxReq(req)); } @@ -462,6 +504,10 @@ impl NodesManagerClient { self.send_req(NodesManagerMessage::ModifiedConfigPeers(req)); } + pub fn deal_rich_status(&self, req: DealRichStatusReq) { + self.send_req(NodesManagerMessage::DealRichStatus(req)); + } + fn send_req(&self, req: NodesManagerMessage) { if let Err(e) = self.sender.try_send(req) { warn!( @@ -480,6 +526,7 @@ pub enum NodesManagerMessage { PendingConnectedNodeReq(PendingConnectedNodeReq), DelConnectedNodeReq(DelConnectedNodeReq), Broadcast(BroadcastReq), + RetransNetMsg(RetransNetMsgReq), SingleTxReq(SingleTxReq), GetPeerCount(GetPeerCountReq), NetworkInit(NetworkInitReq), @@ -488,6 +535,7 @@ pub enum NodesManagerMessage { ConnectedSelf(ConnectedSelfReq), GetPeersInfo(GetPeersInfoReq), ModifiedConfigPeers(ModifiedConfigPeersReq), + DealRichStatus(DealRichStatusReq), } impl NodesManagerMessage { @@ -507,6 +555,8 @@ impl NodesManagerMessage { NodesManagerMessage::ConnectedSelf(req) => req.handle(service), NodesManagerMessage::GetPeersInfo(req) => req.handle(service), NodesManagerMessage::ModifiedConfigPeers(req) => req.handle(service), + NodesManagerMessage::RetransNetMsg(req) => req.handle(service), + NodesManagerMessage::DealRichStatus(req) => req.handle(service), } } } @@ -633,6 +683,9 @@ impl AddConnectedNodeReq { let _ = service .connected_peer_keys .insert(self.init_msg.peer_key, self.session_id); + service + .consensus_topology + .add_linked_nodes(self.init_msg.peer_key); info!( "[NodeManager] connected_addrs info: {:?}", @@ -666,23 +719,23 @@ impl NetworkInitReq { pub fn handle(self, service: &mut NodesManager) { let peer_key = service.peer_key; - let send_key = "network.init".to_string(); let init_msg = InitMsg { chain_id: 0, peer_key, }; - let msg_bytes: Vec = init_msg.into(); - let mut buf = Vec::with_capacity(CITA_FRAME_HEADER_LEN + send_key.len() + msg_bytes.len()); - pubsub_message_to_network_message(&mut buf, Some((send_key, msg_bytes))); + let mut msg_unit = NetMessageUnit::default(); + msg_unit.key = "network.init".to_string(); + msg_unit.data = init_msg.into(); - if let Some(ref mut ctrl) = service.service_ctrl { - // FIXME: handle the error! - let ret = ctrl.send_message_to(self.session_id, TRANSFER_PROTOCOL_ID, buf.into()); - info!( - "[NodeManager] Send network init message!, id: {:?}, peer_addr: {:?}, ret: {:?}", - self.session_id, peer_key, ret, - ); + if let Some(buf) = pubsub_message_to_network_message(&msg_unit) { + if let Some(ref mut ctrl) = service.service_ctrl { + let ret = ctrl.send_message_to(self.session_id, TRANSFER_PROTOCOL_ID, buf); + info!( + "[NodeManager] Send network init message!, id: {:?}, peer_addr: {:?}, ret: {:?}", + self.session_id, peer_key, ret, + ); + } } } } @@ -788,7 +841,9 @@ impl GetRandomNodesReq { } pub fn handle(self, service: &mut NodesManager) { - let addrs = service.known_addrs.keys().take(self.num).cloned().collect(); + let mut addrs: Vec<_> = service.known_addrs.keys().cloned().collect(); + thread_rng().shuffle(&mut addrs); + addrs.truncate(self.num); if let Err(e) = self.return_channel.try_send(addrs) { warn!( @@ -854,15 +909,21 @@ impl DelConnectedNodeReq { self.fix_node_status(trans_addr, service); // Remove connected peer keys - for (key, value) in service.connected_peer_keys.iter() { - if self.session_id == *value { - info!( - "[NodeManager] Remove session [{:?}] from connected_peer_keys.", - *value - ); - service.connected_peer_keys.remove(&key.clone()); - break; + let key = { + if let Some((&key, _)) = service + .connected_peer_keys + .iter() + .find(|(_, &v)| v == self.session_id) + { + Some(key) + } else { + None } + }; + + if let Some(key) = key { + service.consensus_topology.del_linked_nodes(&key); + service.connected_peer_keys.remove(&key); } } @@ -897,6 +958,82 @@ impl DelConnectedNodeReq { } } +#[derive(Debug)] +pub struct RetransNetMsgReq { + msg_unit: NetMessageUnit, + incomming_session_id: SessionId, +} + +impl RetransNetMsgReq { + pub fn new(msg_unit: NetMessageUnit, incomming_session_id: SessionId) -> Self { + RetransNetMsgReq { + msg_unit, + incomming_session_id, + } + } + + pub fn handle(mut self, service: &mut NodesManager) { + let msg_version = self.msg_unit.version; + let in_id = self.incomming_session_id; + + trace!( + "[NodeManager] RetranseReq msg.key {:?}, from session {},version {} self current version {} ttl {}", + self.msg_unit.key, + self.incomming_session_id, + msg_version, + service.self_version, + self.msg_unit.ttl, + ); + + let saved_version = service + .gossip_key_version + .entry(self.msg_unit.addr) + .or_insert(0); + if msg_version == 0 || *saved_version < msg_version { + *saved_version = msg_version; + let mut ids: Vec<_> = service.connected_addrs.keys().cloned().collect(); + ids.retain(|id| *id != in_id); + + if service.consensus_topology.consensus_all_linked { + self.msg_unit.ttl = 0; + } + + if let Some(buf) = pubsub_message_to_network_message(&self.msg_unit) { + if let Some(ref mut ctrl) = service.service_ctrl { + let _ = + ctrl.filter_broadcast(TargetSession::Multi(ids), TRANSFER_PROTOCOL_ID, buf); + } + } + } + } +} + +#[derive(Debug)] +pub struct DealRichStatusReq { + msg: ProtoMessage, +} + +impl DealRichStatusReq { + pub fn new(msg: ProtoMessage) -> Self { + DealRichStatusReq { msg } + } + + pub fn handle(mut self, service: &mut NodesManager) { + let rich_status = self.msg.take_rich_status().unwrap(); + info!("DealRichStatusReq rich status {:?}", rich_status); + + let validators: BTreeSet
= rich_status + .get_validators() + .iter() + .map(|node| Address::from_slice(node)) + .collect(); + + service + .consensus_topology + .update_validators(rich_status.get_height(), validators); + } +} + #[derive(Debug)] pub struct BroadcastReq { key: String, @@ -914,12 +1051,26 @@ impl BroadcastReq { self.msg, self.key ); - let msg_bytes: Vec = self.msg.try_into().unwrap(); - let mut buf = Vec::with_capacity(CITA_FRAME_HEADER_LEN + self.key.len() + msg_bytes.len()); - pubsub_message_to_network_message(&mut buf, Some((self.key, msg_bytes))); - if let Some(ref mut ctrl) = service.service_ctrl { - let _ = ctrl.filter_broadcast(TargetSession::All, TRANSFER_PROTOCOL_ID, buf.into()); + let mut info = NetMessageUnit::default(); + info.key = self.key; + info.data = self.msg.try_into().unwrap(); + info.addr = service.peer_key; + info.version = service.self_version; + service.self_version += 1; + + // Broadcast msg with three types: + // Synchronizer >> Status for declaring myself status,only send to neighbors + // If consensus node all be connected,consensus msg and tx msg only be sent once + // No need to resend tx info + if !service.consensus_topology.consensus_all_linked() && info.key.contains(CONSENSUS_STR) { + info.ttl = CONSENSUS_TTL_NUM; + } + + if let Some(buf) = pubsub_message_to_network_message(&info) { + if let Some(ref mut ctrl) = service.service_ctrl { + let _ = ctrl.filter_broadcast(TargetSession::All, TRANSFER_PROTOCOL_ID, buf); + } } } } @@ -942,13 +1093,15 @@ impl SingleTxReq { self.dst, self.key ); - let msg_bytes: Vec = self.msg.try_into().unwrap(); + let dst = self.dst; + let mut msg_unit = NetMessageUnit::default(); + msg_unit.key = self.key; + msg_unit.data = self.msg.try_into().unwrap(); - let mut buf = Vec::with_capacity(CITA_FRAME_HEADER_LEN + self.key.len() + msg_bytes.len()); - pubsub_message_to_network_message(&mut buf, Some((self.key, msg_bytes))); - if let Some(ref mut ctrl) = service.service_ctrl { - // FIXME: handle the error! - let _ = ctrl.send_message_to(self.dst, TRANSFER_PROTOCOL_ID, buf.into()); + if let Some(buf) = pubsub_message_to_network_message(&msg_unit) { + if let Some(ref mut ctrl) = service.service_ctrl { + let _ = ctrl.send_message_to(dst, TRANSFER_PROTOCOL_ID, buf); + } } } } diff --git a/cita-network/src/p2p_protocol/mod.rs b/cita-network/src/p2p_protocol/mod.rs index d87b20adf..4c33aa874 100644 --- a/cita-network/src/p2p_protocol/mod.rs +++ b/cita-network/src/p2p_protocol/mod.rs @@ -19,7 +19,6 @@ use crate::node_manager::{ AddRepeatedNodeReq, ConnectedSelfReq, DelConnectedNodeReq, DialedErrorReq, NodesManagerClient, PendingConnectedNodeReq, }; -use logger::{info, warn}; use tentacle::{ context::ServiceContext, error, @@ -126,6 +125,12 @@ impl ServiceHandle for SHandle { proto_id, error ); } + ServiceError::SessionBlocked { session_context } => { + warn!( + "[P2pProtocol] ServiceError::SessionBlocked session_context {:?}", + session_context + ); + } } } diff --git a/cita-network/src/p2p_protocol/node_discovery.rs b/cita-network/src/p2p_protocol/node_discovery.rs index 0940a52ef..c1da0da3a 100644 --- a/cita-network/src/p2p_protocol/node_discovery.rs +++ b/cita-network/src/p2p_protocol/node_discovery.rs @@ -16,7 +16,6 @@ // along with this program. If not, see . use crate::node_manager::{AddNodeReq, GetRandomNodesReq, NodeSource, NodesManagerClient}; -use logger::{info, warn}; use pubsub::channel::unbounded; use tentacle::{ builder::MetaBuilder, diff --git a/cita-network/src/p2p_protocol/transfer.rs b/cita-network/src/p2p_protocol/transfer.rs index 33116bb74..95a13db22 100644 --- a/cita-network/src/p2p_protocol/transfer.rs +++ b/cita-network/src/p2p_protocol/transfer.rs @@ -17,10 +17,12 @@ use crate::cita_protocol::network_message_to_pubsub_message; use crate::network::{NetworkClient, RemoteMessage}; -use crate::node_manager::{AddConnectedNodeReq, InitMsg, NetworkInitReq, NodesManagerClient}; +use crate::node_manager::{ + AddConnectedNodeReq, InitMsg, NetworkInitReq, NodesManagerClient, RetransNetMsgReq, +}; use bytes::BytesMut; +use cita_types::Address; use libproto::{Message as ProtoMessage, TryFrom, TryInto}; -use logger::{info, warn}; use tentacle::{ builder::MetaBuilder, context::{ProtocolContext, ProtocolContextMutRef}, @@ -41,6 +43,7 @@ struct TransferProtocol { connected_session_ids: Vec, network_client: NetworkClient, nodes_mgr_client: NodesManagerClient, + self_address: Address, } impl ServiceProtocol for TransferProtocol { @@ -80,18 +83,34 @@ impl ServiceProtocol for TransferProtocol { fn received(&mut self, env: ProtocolContextMutRef, data: bytes::Bytes) { let mut data = BytesMut::from(data); - if let Some((key, message)) = network_message_to_pubsub_message(&mut data) { - if key.eq(&"network.init".to_string()) { - let msg = InitMsg::from(message); + if let Some(mut info) = network_message_to_pubsub_message(&mut data) { + if info.key.eq(&"network.init".to_string()) { + let msg = InitMsg::from(info.data); let req = AddConnectedNodeReq::new(env.session.id, env.session.ty, msg); self.nodes_mgr_client.add_connected_node(req); return; } - let mut msg = ProtoMessage::try_from(&message).unwrap(); - msg.set_origin(env.session.id.value() as u32); + if info.addr == self.self_address { + debug!("[Transfer] Recieve myself {:?} message", info.addr); + return; + } + + let sid = env.session.id; + let mut msg = ProtoMessage::try_from(&info.data).unwrap(); + msg.set_origin(sid.value() as u32); self.network_client - .handle_remote_message(RemoteMessage::new(key, msg.try_into().unwrap())); + .handle_remote_message(RemoteMessage::new( + info.key.clone(), + msg.try_into().unwrap(), + )); + + // Now only consensus need be retransfered + if info.ttl > 0 { + info.ttl -= 1; + let req = RetransNetMsgReq::new(info, sid); + self.nodes_mgr_client.retrans_net_msg(req); + } } else { warn!("[Transfer] Cannot convert network message to pubsub message!"); } @@ -101,6 +120,7 @@ impl ServiceProtocol for TransferProtocol { pub fn create_transfer_meta( network_client: NetworkClient, nodes_mgr_client: NodesManagerClient, + self_address: Address, ) -> ProtocolMeta { MetaBuilder::default() .id(TRANSFER_PROTOCOL_ID) @@ -115,6 +135,7 @@ pub fn create_transfer_meta( connected_session_ids: Vec::default(), network_client: network_client.clone(), nodes_mgr_client: nodes_mgr_client.clone(), + self_address, }); ProtocolHandle::Callback(handle) }) diff --git a/cita-network/src/synchronizer.rs b/cita-network/src/synchronizer.rs index 00f8321a0..813173347 100644 --- a/cita-network/src/synchronizer.rs +++ b/cita-network/src/synchronizer.rs @@ -22,7 +22,6 @@ use libproto::router::{MsgType, RoutingKey, SubModules}; use libproto::routing_key; use libproto::{Message, OperateType, SyncRequest, SyncResponse}; use libproto::{TryFrom, TryInto}; -use logger::{debug, error, info, warn}; use pubsub::channel::{unbounded, Receiver, Sender}; use rand::{thread_rng, Rng, ThreadRng}; use std::collections::{BTreeMap, HashSet, VecDeque}; diff --git a/docs/wiki/images/rocksdb-db-impl.png b/docs/wiki/images/rocksdb-db-impl.png new file mode 100644 index 000000000..f374d86cd Binary files /dev/null and b/docs/wiki/images/rocksdb-db-impl.png differ diff --git a/docs/wiki/images/rocksdb-lsm-tree.png b/docs/wiki/images/rocksdb-lsm-tree.png new file mode 100644 index 000000000..1764c4af8 Binary files /dev/null and b/docs/wiki/images/rocksdb-lsm-tree.png differ diff --git a/docs/wiki/rocksdb-in-cita.md b/docs/wiki/rocksdb-in-cita.md new file mode 100644 index 000000000..500107178 --- /dev/null +++ b/docs/wiki/rocksdb-in-cita.md @@ -0,0 +1,89 @@ +## RocksDB 简单介绍 +当前 CITA 使用 RocksDB 作为其底层存储的数据库。 +RocksBD 采用的是 LSM-Tree(Log-Structured-Merge-Tree), 如下图所示: + + + +LSM 树的设计思想非常简单,它的原理是把一颗大树拆分成 N 棵小树,它首先写入到内存中(内存没有寻道速度的问题,随机写的性能得到大幅提升), +在内存中构建一颗有序小树,随着小树越来越大,内存的小树会 flush 到磁盘上。磁盘中的树定期可以做 merge 操作,合并成一棵大树。 + +RocksDB 的三种基本文件格式是 memtable/sstfile/logfile,memtable 是一种内存文件数据系统,新写数据会被写进 memtable,部分请求内容会被写进 logfile。 +logfile 是一种有利于顺序写的文件系统。memtable 的内存空间被填满之后,会有一部分老数据被转移到 sstfile 里面,这些数据对应的 logfile 里的 log 就会被安全删除。 +sstfile 中的内容是有序的。 + + + +上图所示,所有 Column Family 共享一个 WAL 文件,但是每个 Column Family 有自己单独的 memtable & ssttable(sstfile),即 log 共享而数据分离。 + +在下面这几种条件下 RocksDB 会 flush memtable 到磁盘. + +1. 当某一个 memtable 的大小超过 write_buffer_size. +2. 当总的 memtable 的大小超过 db_write_buffer_size. +3. 当 WAL 文件的大小超过 max_total_wal_size 之后. + +## 参数配置及相关配置 + +### Columns +CITA 总共创建了 7 个 columns, 分别在 Executor 与 Chain 微服务中使用。它们分别是: +* COL_STATE +* COL_HEADERS +* COL_BODIES +* COL_EXTRA +* COL_TRACE +* COL_ACCOUNT_BLOOM +* COL_NODE_INFO + +### 数据库配置 +* columns : 7 (COLUMNS) +* cache_sizes : 2 M for each column +* max_open_files : 512 +* compaction (default as ssd ): + * initial_file_size : 64 * 1024 * 1024 + * file_size_multiplier : 1 + * write_rate_limit : None + +* wal : true + +### 其它选项 +* see rocksdb_options_create for default options +* max_total_wal_size : 64 * 1024 * 1024 +* verify_checksums_in_compaction : 0 +* create_if_missing : true +* use_fsync : false +* db_write_buffer_size : 4 * 64 * 1024 * 1024 +* max_background_flushes : 2 +* max_background_compactions : 2 +* compaction_style : DBLevelCompaction +* target_file_size_base : 64 * 1024 * 1024 +* target_file_size_multiplier : 1 + +### Column 选项 +* compaction_style : DBLevelCompaction +* target_file_size_base : 64 * 1024 * 1024 +* target_file_size_multiplier : 1 +* db_write_buffer_size : 4 * 64 * 1024 * 1024 +* block_opts.cache : 2 * 1024 * 1024 + +## 关键配置说明 + +在说明配置之前先简单介绍一下 RocksDB。 + +* max_total_wal_size + +wal 的最大空间,CITA 设置为 64M。 + +* db_write_buffer_size + +最大的 DB 写 buffer,即所有 Column 使用的写 buffer 不大于 256M。 + +* write_buffer_size + +这个配置项 CITA 没有特殊配置,使用的是默认值 64M。在执行过程中每个 column 有两个。 + +* max_background_flushes + +最大的 flushes 线程。 + +* max_background_compactions + +最大的压缩线程,线程不宜过多,过多容易导致写请求被 hang 住。 diff --git a/env.sh b/env.sh index de223f4e8..eb278ad66 100755 --- a/env.sh +++ b/env.sh @@ -13,7 +13,7 @@ fi if test -f "${SOURCE_DIR}/Cargo.toml"; then readonly CONTAINER_NAME='cita_build_container' - readonly DOCKER_IMAGE='cita/cita-build:ubuntu-18.04-20190429' + readonly DOCKER_IMAGE='cita/cita-build:ubuntu-18.04-20190515' else readonly CONTAINER_NAME='cita_run_container' readonly DOCKER_IMAGE='cita/cita-run:ubuntu-18.04-20190419' @@ -38,7 +38,7 @@ fi # Expose parameter for docker needs something like "-p 1337:1337 -p 1338:1338", but not "-p 1337:1337 1338:1338" EXPOSE_PARAM=() for port in "${EXPOSE[@]}"; do - EXPOSE_PARAM+=" -p ${port}" + EXPOSE_PARAM+=(-p ${port}) done # Docker Arguments @@ -65,7 +65,7 @@ if ! docker ps | grep "${CONTAINER_NAME}" > '/dev/null' 2>&1; then --env "USER_ID=${USER_ID}" \ --workdir "${WORKDIR}" \ --name "${CONTAINER_NAME}" \ - ${EXPOSE_PARAM[@]} "${DOCKER_IMAGE}" \ + "${EXPOSE_PARAM[@]}" "${DOCKER_IMAGE}" \ /bin/bash -c "${INIT_CMD}" # Wait entrypoint.sh to finish sleep 3 diff --git a/release_guide.md b/release-guide.md similarity index 95% rename from release_guide.md rename to release-guide.md index 609f4865e..4078301a6 100644 --- a/release_guide.md +++ b/release-guide.md @@ -83,7 +83,11 @@ Broadcast internal mail: Merge the bug fixes occurred during the test into the release branch `release-x.y.z`. -If the test passes, modify the update log and update the release date with other information. +If the test passes: + +* Create a `tag` of corresponding version +* Update `submodule` using `tag` +* Modify the update log and update the release date with other information ## Merge Branch @@ -117,7 +121,8 @@ git push origin vx.y.z ***The transition branch is named `merge-master-to-develop`*** -Merge the `master` branch into the `develop` branch. Because of the branch protection, we need to create a middle branch `merge-master-to-develop` via `pull request`. +Merge the `master` branch into the `develop` branch. +Because of the branch protection, we need to create a middle branch `merge-master-to-develop` via `pull request`. 1. Update the `master` branch code as follows: @@ -283,7 +288,11 @@ git push origin release-x.y.z 测试过程中出现的 Bug 修复合并入发布分支 `release-x.y.z`。 -当测试通过时,修改更新日志,更新版本发布日期等信息。 +测试通过后: + +* `submodule` 创建对应版本 `tag` +* 使用 `tag` 方式更新 `submodule` +* 修改更新日志,更新版本发布日期等信息 ## 合并分支 diff --git a/scripts/amend_system_contracts.py b/scripts/amend_system_contracts.py index 433437c2e..5fb405c9e 100644 --- a/scripts/amend_system_contracts.py +++ b/scripts/amend_system_contracts.py @@ -13,7 +13,7 @@ import time from jsonrpcclient.http_client import HTTPClient -LATEST_VERSION = 1 +LATEST_VERSION = 2 AMEND_ADDR = '0xffffffffffffffffffffffffffffffffff010002' SYS_CONF = '0xffffffffffffffffffffffffffffffffff020000' NEW = '0xffffffffffffffffffffffffffffffffff020012' diff --git a/scripts/amend_system_contracts.sh b/scripts/amend_system_contracts.sh index 7c26bec7a..6249ec3d4 100755 --- a/scripts/amend_system_contracts.sh +++ b/scripts/amend_system_contracts.sh @@ -1,17 +1,17 @@ #!/bin/bash set -e -if [[ `uname` == 'Darwin' ]] +if [[ $(uname) == 'Darwin' ]] then - SOURCE_DIR=$(realpath $(dirname $0)/..) + SOURCE_DIR=$(realpath "$(dirname "$0")"/..) else - SOURCE_DIR=$(readlink -f $(dirname $0)/..) + SOURCE_DIR=$(readlink -f "$(dirname "$0")"/..) fi if [ "$1" = "help" ]; then echo "Admin private key, chain id, version, url as the params. For example: \\ - ./env.sh scripts/amend_system_contracts.sh \\ + bin/cita scripts/amend_system_contracts.sh \\ 0x5f0258a4778057a8a7d97809bd209055b2fbafa654ce7d31ec7191066b9225e6 \\ 1 \\ 1 \\ @@ -20,8 +20,8 @@ if [ "$1" = "help" ]; then fi # Clean tmp files -rm -rf ${SOURCE_DIR}/tmp -rm -f ${SOURCE_DIR}/scripts/genesis.json +rm -rf "${SOURCE_DIR}"/tmp +rm -f "${SOURCE_DIR}"/scripts/genesis.json # Just get the genensis.json scripts/create_cita_config.py create \ @@ -30,10 +30,10 @@ scripts/create_cita_config.py create \ --nodes "127.0.0.1:4000" \ && cp tmp/0/genesis.json scripts/ \ && cd ./scripts/txtool/txtool \ -&& python3 ${SOURCE_DIR}/scripts/amend_system_contracts.py \ +&& python3 "${SOURCE_DIR}"/scripts/amend_system_contracts.py \ --privkey "$1" \ --chain_id "$2" \ --version "$3" \ --url "$4" \ -&& rm -rf ${SOURCE_DIR}/tmp \ -&& rm -f ${SOURCE_DIR}/scripts/genesis.json +&& rm -rf "${SOURCE_DIR}"/tmp \ +&& rm -f "${SOURCE_DIR}"/scripts/genesis.json diff --git a/scripts/cita b/scripts/cita.sh similarity index 57% rename from scripts/cita rename to scripts/cita.sh index 4fd2d3add..efa22f645 100755 --- a/scripts/cita +++ b/scripts/cita.sh @@ -2,49 +2,31 @@ # -*- tab-width:4;indent-tabs-mode:nil -*- # ex: ts=4 sw=4 et +# Exit immediately if a command exits with a non-zero status +set -e + # Commands Paths -if [ `uname` == 'Darwin' ]; then - CITA_BIN="$(dirname $(realpath $0))" +if [[ $(uname) == 'Darwin' ]]; then + CITA_BIN=$(dirname "$(realpath "$0")") else - CITA_BIN="$(dirname $(readlink -f $0))" + CITA_BIN=$(dirname "$(readlink -f "$0")") fi -CITA_SCRIPTS="$(dirname $CITA_BIN)/scripts" - -if [ "$1" != "bebop" ]; then - stat $CITA_BIN/cita-env > /dev/null 2>&1 - if [ $? -eq 0 ]; then - $CITA_BIN/cita-env bin/cita bebop $@ - else - echo -e "\033[0;31mPlease run this command after build 🎨" - echo -e "\033[0;32mRun \`cita bebop\` to preview help! 🎸 \033[0m\n" - fi - exit 0 -fi - -# Delete the verbose parameters -set -- "${@:2}" - -# Exit immediately if a command exits with a non-zero status -set -e # Add cita scripts into system executable paths export PATH=$CITA_BIN:$PATH +CITA_SCRIPTS=$(dirname "$CITA_BIN")/scripts SERVICES=( forever auth bft chain executor jsonrpc network ) -SCRIPT=`basename $0` -COMMAND=$1 -NODE_NAME=$2 -NODE_PATH="$(dirname $CITA_BIN)/${NODE_NAME}" -NODE_LOGS_DIR="${NODE_PATH}/logs" -NODE_DATA_DIR="${NODE_PATH}/data" -TNODE=`echo ${NODE_NAME} | sed 's/\//%2f/g'` - -sudo(){ +SCRIPT=$(basename "$0") +# DIAGNOSTIC COMMANDS +PING_STATUS="" + +sudo() { set -o noglob if [ "$(whoami)" == "root" ] ; then - $* + "$@" else - /usr/bin/sudo $* + /usr/bin/sudo "$@" fi set +o noglob } @@ -59,7 +41,6 @@ Run \`$SCRIPT help\` for more detailed information. EOF } - # INFORMATIONAL COMMANDS help() { cat < /dev/null || brew services restart rabbitmq > /dev/null + pgrep -f rabbitmq-server > /dev/null || brew services restart rabbitmq > /dev/null RABBITMQ_USER=cita_monitor RABBITMQ_PASSWD=cita_monitor - sudo rabbitmqctl list_vhosts | grep ${NODE_NAME} > /dev/null || sudo rabbitmqctl add_vhost ${NODE_NAME} > /dev/null - sudo rabbitmqctl set_permissions -p ${NODE_NAME} guest '.*' '.*' '.*' > /dev/null + sudo rabbitmqctl list_vhosts | grep "${NODE_NAME}" > /dev/null || sudo rabbitmqctl add_vhost "${NODE_NAME}" > /dev/null + sudo rabbitmqctl set_permissions -p "${NODE_NAME}" guest '.*' '.*' '.*' > /dev/null sudo rabbitmq-plugins enable rabbitmq_management > /dev/null sudo rabbitmqctl list_users | grep ${RABBITMQ_USER} > /dev/null || sudo rabbitmqctl add_user ${RABBITMQ_USER} ${RABBITMQ_PASSWD} > /dev/null sudo rabbitmqctl set_user_tags ${RABBITMQ_USER} monitoring > /dev/null - sudo rabbitmqctl set_permissions -p ${NODE_NAME} ${RABBITMQ_USER} '.*' '.*' '.*' > /dev/null + sudo rabbitmqctl set_permissions -p "${NODE_NAME}" ${RABBITMQ_USER} '.*' '.*' '.*' > /dev/null else flock -x -w 30 /tmp/rabbitmq.lock -c "ps -C rabbitmq-server > /dev/null || sudo /etc/init.d/rabbitmq-server restart > /dev/null" RABBITMQ_USER=cita_monitor @@ -167,22 +143,21 @@ do_setup() { for i in {1..3} do start_rabbitmq - curl http://localhost:15672/ > /dev/null 2>&1 - if [ $? -eq 0 ]; then + if curl http://localhost:15672/ > /dev/null 2>&1; then return 0 fi done - echo "Failed to start RabbitMQ" + echo "Failed to start RabbitMQ after $i times." exit 1 } - do_start() { - debug=$1 - mock=$2 + local debug=$1 + local mock=$2 + local config # Make sure log directory exists - mkdir -p ${NODE_LOGS_DIR} + mkdir -p "${NODE_LOGS_DIR}" # Tricky if [[ -z ${mock} ]]; then @@ -192,18 +167,18 @@ do_start() { fi # Start cita-forever - if [ -z ${debug} ]; then - cita-forever -c ${config} start 2>&1 + if [ -z "${debug}" ]; then + cita-forever -c "${config}" start 2>&1 else RUST_LOG=cita_auth=${debug},cita_chain=${debug},cita_executor=${debug},cita_jsonrpc=${debug},cita_network=${debug},cita_bft=${debug},\ core_executor=${debug},engine=${debug},jsonrpc_types=${debug},libproto=${debug},proof=${debug},txpool=${debug},core=${debug} \ - cita-forever -c ${config} start 2>&1 + cita-forever -c "${config}" start 2>&1 fi # Wait for the node to come up WAIT=3 while [ $WAIT -gt 0 ]; do - WAIT=`expr $WAIT - 1` + WAIT="$(( WAIT - 1 ))" sleep 1 do_ping if [ "${PING_STATUS}" == "pong" ]; then @@ -230,23 +205,18 @@ do_stop() { echo "stop...ok" } - -# DIAGNOSTIC COMMANDS -PING_STATUS="" do_ping() { - for service in forever; do - pidfile="${NODE_PATH}/.cita-${service}.pid" - if [ ! -e $pidfile ]; then - PING_STATUS="pang" - return - fi + local pidfile="${NODE_PATH}/.cita-forever.pid" + if [[ ! -e "$pidfile" ]]; then + PING_STATUS="pang" + return + fi - alive=`ps -p $(cat ${pidfile}) | wc -l` - if [ "${alive}" -le "1" ]; then - PING_STATUS="pang" - return - fi - done + alive=$(ps -p "$(cat "${pidfile}")" | wc -l) + if [ "${alive}" -le "1" ]; then + PING_STATUS="pang" + return + fi PING_STATUS="pong" } @@ -254,17 +224,17 @@ do_ping() { do_top() { for service in "${SERVICES[@]}"; do pidfile="${NODE_PATH}/.cita-${service}.pid" - if [ -e $pidfile ]; then - ps -p `cat ${pidfile}` -f | tail -n +2 + if [ -e "$pidfile" ]; then + ps -p "$(cat "${pidfile}")" -f | tail -n +2 fi done } do_status() { - for pid_file in `find . -name "*.pid"`; do - pid=$(cat ${pid_file}) - ps -A -o command=50,pid,time|grep ${pid} |grep -v "grep" || true - done + while IFS= read -r -d '' pid_file; do + pid=$(cat "${pid_file}") + pgrep -f "${pid}" || true + done < <(find . -name "*.pid") } @@ -277,19 +247,20 @@ do_clean() { fi # Move data/ and logs/ into backup directory - backup_dir="$(pwd)/backup.$(date -Iseconds)" - mkdir -p ${backup_dir} - if [ -e ${NODE_DATA_DIR} ] ; then - echo "mv ${NODE_DATA_DIR} ${backup_dir}/" - mv ${NODE_DATA_DIR} ${backup_dir}/ + backup_dir=$(pwd)/backup.$(date -Iseconds) + mkdir -p "${backup_dir}" + if [ -e "${NODE_DATA_DIR}" ] ; then + echo "mv ${NODE_DATA_DIR} ${backup_dir}" + mv "${NODE_DATA_DIR}" "${backup_dir}" fi - if [ -e ${NODE_LOGS_DIR} ] ; then - echo "mv ${NODE_LOGS_DIR} ${backup_dir}/" - mv ${NODE_LOGS_DIR} ${backup_dir}/ + if [ -e "${NODE_LOGS_DIR}" ] ; then + echo "mv ${NODE_LOGS_DIR} ${backup_dir}" + mv "${NODE_LOGS_DIR}" "${backup_dir}" fi } do_backup() { + local backup_dir # Backup empty node always successfully if [[ ! -d ${NODE_DATA_DIR} || ! -d ${NODE_LOGS_DIR} ]]; then echo "Node ${NODE_NAME} has no data and logs directories" @@ -298,20 +269,20 @@ do_backup() { # Copy data/ and logs/ into backup directory backup_dir="$(pwd)/backup.$(date -Iseconds)" - mkdir -p ${backup_dir} - if [ -e ${NODE_DATA_DIR} ] ; then + mkdir -p "${backup_dir}" + if [ -e "${NODE_DATA_DIR}" ] ; then echo "cp -r ${NODE_DATA_DIR} ${backup_dir}/" - cp -r ${NODE_DATA_DIR} ${backup_dir}/ + cp -r "${NODE_DATA_DIR}" "${backup_dir}"/ fi - if [ -e ${NODE_LOGS_DIR} ] ; then + if [ -e "${NODE_LOGS_DIR}" ] ; then echo "cp -r ${NODE_LOGS_DIR} ${backup_dir}/" - cp -r ${NODE_LOGS_DIR} ${backup_dir}/ + cp -r "${NODE_LOGS_DIR}" "${backup_dir}"/ fi } do_logs() { - service0=$1 - if [ -z ${service0} ]; then + local service0=$1 + if [ -z "${service0}" ]; then echo "'${SCRIPT} logs' requires exactly 2 arguments." echo echo "Usage: ${SCRIPT} logs NODE_NAME SERVICE" @@ -320,7 +291,7 @@ do_logs() { fi for service in "${SERVICES[@]}"; do - if [[ $service = $service0 || "cita-${service}" = $service0 ]]; then + if [[ $service = "$service0" || cita-"${service}" = "$service0" ]]; then tail -f "${NODE_LOGS_DIR}/cita-${service}.log" exit 0 fi @@ -331,7 +302,8 @@ do_logs() { } do_logrotate() { - logs=$(ls -1 ${NODE_LOGS_DIR}/cita-*.log) + local logs + logs=$(ls -1 "${NODE_LOGS_DIR}"/cita-*.log) cita-forever logrotate > /dev/null 2>&1 # Wait for services to rotate their logs @@ -344,16 +316,17 @@ do_logrotate() { } clear_rabbit_mq() { - MQ_COMMAND="curl -i -u guest:guest -H content-type:application/json -XDELETE http://localhost:15672/api/queues/${TNODE}" - - $MQ_COMMAND/auth > /dev/null 2>&1 || true - $MQ_COMMAND/chain > /dev/null 2>&1 || true - $MQ_COMMAND/consensus > /dev/null 2>&1 || true - $MQ_COMMAND/jsonrpc > /dev/null 2>&1 || true - $MQ_COMMAND/network > /dev/null 2>&1 || true - $MQ_COMMAND/network_tx > /dev/null 2>&1 || true - $MQ_COMMAND/network_consensus > /dev/null 2>&1 || true - $MQ_COMMAND/executor > /dev/null 2>&1 || true + local mq_command + local mq_command="curl -i -u guest:guest -H content-type:application/json -XDELETE http://localhost:15672/api/queues/${TNODE}" + + "$mq_command"/auth > /dev/null 2>&1 || true + "$mq_command"/chain > /dev/null 2>&1 || true + "$mq_command"/consensus > /dev/null 2>&1 || true + "$mq_command"/jsonrpc > /dev/null 2>&1 || true + "$mq_command"/network > /dev/null 2>&1 || true + "$mq_command"/network_tx > /dev/null 2>&1 || true + "$mq_command"/network_consensus > /dev/null 2>&1 || true + "$mq_command"/executor > /dev/null 2>&1 || true } node_down_check() { @@ -372,128 +345,159 @@ node_up_check() { fi } -# Commands not depend on $NODE_PATH -case "${COMMAND}" in - help) - help - exit 0 - ;; - - usage) - usage - exit 0 - ;; - - create) - create $@ - exit 0 - ;; - - append) - append $@ - exit 0 - ;; - -esac - -if [ $# -lt 2 ]; then - usage - exit 1 -fi - -# Make sure the node directory exists -if [ ! -d "${NODE_PATH}" ]; then - echo "No such node directory: ${NODE_NAME}" - exit 1 -elif [[ ! -e "${NODE_PATH}/forever.toml" && ! -e "${NODE_PATH}/forever_mock.toml" ]]; then - echo "'${NODE_NAME}' is not a ${SCRIPT} node directory" - exit 1 -fi - -# Enter the node directory -pushd . > /dev/null -cd ${NODE_PATH} - -case "${COMMAND}" in - setup) - do_setup - ;; - - start) - do_stop # TODO: should not do so, but present tests need this - node_down_check - - # Make sure the RabbitMQ fresh - clear_rabbit_mq - - do_start $3 $4 - ;; - - stop) - node_up_check - do_stop - ;; +parse_command() { + local command="$1" + case "${command}" in + help) + help + exit 0 + ;; - restart) - node_up_check - do_stop + usage) + usage + exit 0 + ;; - # Make sure the RabbitMQ fresh - clear_rabbit_mq + create) + config "$@" + exit 0 + ;; - do_start $3 $4 - ;; + append) + config "$@" + exit 0 + ;; + + setup) + do_setup + ;; + + start) + # TODO: should not do so, but present tests need this + do_stop + node_down_check + + # Make sure the RabbitMQ fresh + clear_rabbit_mq + + do_start "$3" "$4" + ;; + + stop) + node_up_check + do_stop + ;; + + restart) + node_up_check + do_stop + + # Make sure the RabbitMQ fresh + clear_rabbit_mq + + do_start "$3" "$4" + ;; + + ping) + do_ping + if [ "${PING_STATUS}" == "pong" ]; then + echo "pong" + else + echo "Node '${NODE_NAME}' not responding to pings." + exit 1 + fi + ;; + + top) + node_up_check + do_top + ;; + # deprecated, use 'top' instead + stat) + node_up_check + do_top + ;; + # similar to 'top', but ... ? + status) + do_status + ;; + + logrotate) + do_logrotate + ;; + + logs) + do_logs "$3" + ;; + + backup) + node_down_check + do_backup + ;; + + clean) + node_down_check + do_clean + ;; + + *) + usage + ;; + + esac +} - ping) - do_ping - if [ "${PING_STATUS}" == "pong" ]; then - echo "pong" +main() { + if [ "$1" != "bebop" ]; then + if stat "$CITA_BIN"/cita-env > /dev/null 2>&1; then + "$CITA_BIN"/cita-env bin/cita bebop "$@" else - echo "Node '${NODE_NAME}' not responding to pings." - exit 1 + echo -e "\033[0;31mPlease run this command after build 🎨" + echo -e "\033[0;32mRun \`cita bebop\` to preview help! 🎸 \033[0m\n" fi - ;; + exit 0 + fi - top) - node_up_check - do_top - ;; + # Delete the verbose parameters + set -- "${@:2}" + local command=$1 - stat) # deprecated, use 'top' instead - node_up_check - do_top - ;; + # Commands not depend on $NODE_PATH + local indie=( help usage create append ) + if [[ "${indie[*]}" =~ $command ]]; then + parse_command "$@" + fi - status) # similar to 'top', but ... ? - do_status - ;; + # Commands depend on $NODE_PATH + if [ $# -lt 2 ]; then + usage + exit 1 + fi - logrotate) - do_logrotate - ;; + NODE_NAME=$2 + NODE_PATH=$(realpath "${NODE_NAME}") + NODE_LOGS_DIR="${NODE_PATH}/logs" + NODE_DATA_DIR="${NODE_PATH}/data" + TNODE=$(echo "${NODE_NAME}" | sed 's/\//%2f/g') - logs) - do_logs $3 - ;; + # Make sure the node directory exists + if [ ! -d "${NODE_PATH}" ]; then + echo "No such node directory: ${NODE_NAME}" + exit 1 + elif [[ ! -e "${NODE_PATH}/forever.toml" && ! -e "${NODE_PATH}/forever_mock.toml" ]]; then + echo "'${NODE_NAME}' is not a ${SCRIPT} node directory" + exit 1 + fi - backup) - node_down_check - do_backup - ;; + # Enter the node directory + pushd . > /dev/null + cd "${NODE_PATH}" - clean) - node_down_check - do_clean - ;; + parse_command "$@" - help) - help - ;; + popd > /dev/null - *) - usage - ;; -esac -popd > /dev/null + exit 0 +} -exit 0 +main "$@" diff --git a/scripts/cita_config.sh b/scripts/cita_config.sh index 4a5d130c5..a02e9d1c9 100755 --- a/scripts/cita_config.sh +++ b/scripts/cita_config.sh @@ -1,12 +1,12 @@ #!/bin/bash # Enviroments -CITA_BIN=$(realpath $(dirnamme $0)) -CITA_SCRIPTS=$(dirname $CITA_BIN)/scripts +CITA_BIN=$(realpath "$(dirnamme "$0")") +CITA_SCRIPTS=$(dirname "$CITA_BIN")/scripts # Wrap the create script. -if [ -e $CITA_SCRIPTS/create_cita_config.py ]; then - $CITA_SCRIPTS/create_cita_config.py $@ +if [ -e "$CITA_SCRIPTS"/create_cita_config.py ]; then + "$CITA_SCRIPTS"/create_cita_config.py "$@" else echo -e "\033[0;31mPlease run this command after build 🎨" fi diff --git a/scripts/config_tool/README.md b/scripts/config_tool/README.md deleted file mode 100755 index ac3915a89..000000000 --- a/scripts/config_tool/README.md +++ /dev/null @@ -1,7 +0,0 @@ -[在线文档](https://cryptape.github.io/cita/zh/usage-guide/admintool/index.html) - -[online doc](https://cryptape.github.io/cita/en/usage-guide/admintool/index.html) - -文档路径: `docs/docs/zh/usage-guide/admintool.md` - -Path of doc: `docs/docs/en/usage-guide/admintool.md` diff --git a/scripts/config_tool/create_genesis.py b/scripts/config_tool/create_genesis.py deleted file mode 100755 index c2300fac5..000000000 --- a/scripts/config_tool/create_genesis.py +++ /dev/null @@ -1,322 +0,0 @@ -#!/usr/bin/env python3 -# -*- coding:utf-8 -*- -# pylint: disable=missing-docstring - -import argparse -import binascii -import json -import os -import sys -import time - -from ethereum.abi import ContractTranslator -import sha3 -import yaml - -from create_init_data import dictlist_to_ordereddict - -DEFAULT_PREVHASH = '0x{:064x}'.format(0) -BLOCK_GAS_LIMIT = 471238800 - - -def disable_import_warning(): - """This is a temporary method. - We do NOT need bitcoin. We want to decrease the size of docker. - So, just filter out the unnecessary warning. - """ - - import builtins - from types import ModuleType - - class DummyModule(ModuleType): - def __getattr__(self, key): - return None - - __all__ = [] - - def filterimport(name, globals=None, locals=None, fromlist=(), level=0): - if name == 'bitcoin': - return DummyModule(name) - return realimport(name, globals, locals, fromlist, level) - - realimport, builtins.__import__ = builtins.__import__, filterimport - - -disable_import_warning() -import ethereum.tools.tester as eth_tester -import ethereum.tools._solidity as solidity - - -def replaceLogRecord(): - """This is a temporary method. - We will remove pyethereum in the near future. - """ - - import logging - import re - - def makeRecord(self, - name, - level, - fn, - lno, - msg, - args, - exc_info, - func=None, - extra=None, - sinfo=None): - name = re.sub(r'(^|[^a-zA-Z])eth([^a-zA-Z]|$)', r'\1cita\2', name) - rv = logging._logRecordFactory(name, level, fn, lno, msg, args, - exc_info, func, sinfo) - if extra is not None: - for key in extra: - if (key in ["message", "asctime"]) or (key in rv.__dict__): - raise KeyError( - "Attempt to overwrite %r in LogRecord" % key) - rv.__dict__[key] = extra[key] - return rv - - def getMessage(self): - msg = str(self.msg) - if self.args: - msg = msg % self.args - msg = re.sub(r'(^|[^a-zA-Z])eth([^a-zA-Z]|$)', r'\1cita\2', msg) - msg = re.sub(r'(^|[^a-zA-Z])gas([^a-zA-Z]|$)', r'\1quota\2', msg) - return msg - - logging.Logger.makeRecord = makeRecord - logging.LogRecord.getMessage = getMessage - - -def function_encode(func_sign): - keccak = sha3.keccak_256() - keccak.update(func_sign.encode('utf-8')) - return binascii.unhexlify(keccak.hexdigest()[0:8]) - - -class GenesisData(object): - # pylint: disable=too-many-instance-attributes,too-many-arguments - def __init__(self, contracts_dir, contracts_docs_dir, init_data_file, - timestamp, prevhash): - self.timestamp = int( - time.time() * 1000) if not timestamp else timestamp - self.prevhash = DEFAULT_PREVHASH if not prevhash else prevhash - - self.contracts_dir = os.path.join(contracts_dir, 'src') - self.contracts_docs_dir = contracts_docs_dir - self.contracts_common_dir = os.path.join(self.contracts_dir, 'common') - self.contracts_lib_dir = os.path.join(self.contracts_dir, 'lib') - self.contracts_interaction_dir = os.path.join(contracts_dir, - 'interaction') - contracts_list_file = os.path.join(contracts_dir, 'contracts.yml') - self.load_contracts_list(contracts_list_file) - self.load_contracts_args(init_data_file) - - self.init_chain_tester() - - self.accounts = dict() - - def load_contracts_list(self, contracts_list_file): - """From file to load the list of contracts.""" - with open(contracts_list_file, 'r') as stream: - contracts_list = yaml.safe_load(stream) - contracts_list['NormalContracts'] = dictlist_to_ordereddict( - contracts_list['NormalContracts']) - contracts_list['PermissionContracts']['basic'] \ - = dictlist_to_ordereddict( - contracts_list['PermissionContracts']['basic']) - contracts_list['PermissionContracts']['contracts'] \ - = dictlist_to_ordereddict( - contracts_list['PermissionContracts']['contracts']) - self.contracts_list = contracts_list - - def load_contracts_args(self, init_data_file): - """From file to load arguments for contracts.""" - with open(init_data_file, 'r') as stream: - data = yaml.safe_load(stream) - contracts_args = dictlist_to_ordereddict(data['Contracts']) - for name, arguments in contracts_args.items(): - contracts_args[name] = dictlist_to_ordereddict(arguments) - self.contracts_args = contracts_args - - def init_chain_tester(self): - """Init a chain tester.""" - chain_env = eth_tester.get_env(None) - chain_env.config['BLOCK_GAS_LIMIT'] = BLOCK_GAS_LIMIT - self.chain_tester = eth_tester.Chain(env=chain_env) - - def compile_to_data(self, name, path): - """Compile a solidity file and return the result data.""" - - import logging - - compiled = solidity.compile_file( - path, - combined='bin,abi,userdoc,devdoc,hashes', - extra_args='common={} lib={} interaction={}'.format( - self.contracts_common_dir, self.contracts_lib_dir, - self.contracts_interaction_dir)) - data = solidity.solidity_get_contract_data(compiled, path, name) - if not data['bin']: - logging.critical( - 'The bin of contract %r is empty. Please check it!', name) - sys.exit(1) - return data - - def write_docs(self, name, data): - """Save userdoc, devdoc and hashes of contract function.""" - if self.contracts_docs_dir: - for doc_type in ('userdoc', 'devdoc', 'hashes'): - doc_file = os.path.join(self.contracts_docs_dir, - '{}-{}.json'.format(name, doc_type)) - with open(doc_file, 'w') as stream: - json.dump( - data[doc_type], - stream, - separators=(',', ': '), - indent=4) - - def mine_contract_on_chain_tester(self, addr, code): - """Mine in test chain to get data of a contract.""" - addr_in_tester = self.chain_tester.contract( - code, language='evm', startgas=30000000) - self.chain_tester.mine() - account_in_tester = self.chain_tester \ - .chain.state.account_to_dict(addr_in_tester) - self.accounts[addr] = { - key: val - for (key, val) in filter( - lambda keyval: keyval[0] in ('code', 'storage', 'nonce'), - account_in_tester.items(), - ) - } - - def init_normal_contracts(self): - """Compile normal contracts from files and construct by arguments. - """ - flags = [ - 'checkCallPermission', 'checkSendTxPermission', - 'checkCreateContractPermission', 'checkQuota', - 'checkFeeBackPlatform', 'autoExec' - ] - ncinfo = self.contracts_list['NormalContracts'] - for name, info in ncinfo.items(): - addr = info['address'] - path = os.path.join(self.contracts_dir, info['file']) - data = self.compile_to_data(name, path) - self.write_docs(name, data) - ctt = ContractTranslator(data['abi']) - args = self.contracts_args.get(name) - if name == 'SysConfig': - args['flags'] = [] - for flag in flags: - args['flags'].append(args[flag]) - args.pop(flag) - extra = b'' if not args else ctt.encode_constructor_arguments( - [arg for arg in args.values()]) - self.mine_contract_on_chain_tester(addr, data['bin'] + extra) - - def init_permission_contracts(self): - ncinfo = self.contracts_list['NormalContracts'] - pcinfo = self.contracts_list['PermissionContracts'] - path = os.path.join(self.contracts_dir, pcinfo['file']) - data = self.compile_to_data('Permission', path) - self.write_docs('Permission', data) - for name, info in pcinfo['basic'].items(): - addr = info['address'] - conts = [addr] - funcs = [binascii.unhexlify('00000000')] - ctt = ContractTranslator(data['abi']) - extra = ctt.encode_constructor_arguments([name, conts, funcs]) - self.mine_contract_on_chain_tester(addr, data['bin'] + extra) - for name, info in pcinfo['contracts'].items(): - addr = info['address'] - conts = [ncinfo[cont]['address'] for cont in info['contracts']] - funcs = [function_encode(func) for func in info['functions']] - ctt = ContractTranslator(data['abi']) - extra = ctt.encode_constructor_arguments([name, conts, funcs]) - self.mine_contract_on_chain_tester(addr, data['bin'] + extra) - - def set_account_value(self, address, value): - self.accounts[address] = { - 'code': '', - 'storage': {}, - 'nonce': '1', - 'value': value, - } - - def save_to_file(self, filepath): - with open(filepath, 'w') as stream: - json.dump( - dict( - timestamp=self.timestamp, - prevhash=self.prevhash, - alloc=self.accounts, - ), - stream, - separators=(',', ': '), - indent=4) - - -def parse_arguments(): - parser = argparse.ArgumentParser() - parser.add_argument( - '--contracts_dir', required=True, help='The directory of contracts.') - parser.add_argument( - '--contracts_docs_dir', - help='The directory of generated documents for contracts.' - ' If did not be specified, no documents will be generated.') - parser.add_argument( - '--init_data_file', - required=True, - help='Path of the file for initialization data of contracts.') - parser.add_argument( - '--output', required=True, help='Path of the output file.') - parser.add_argument( - '--timestamp', type=int, help='Specify a timestamp to use.') - parser.add_argument( - '--init_token', - type=lambda x: hex(int(x,16)), - default=hex(int("0xffffffffffffffffffffffffff", 16)), - help='Init token for this chain, INIT_TOKEN is a hexadecimal number') - parser.add_argument('--prevhash', help='Prevhash of genesis.') - args = parser.parse_args() - return dict( - contracts_dir=args.contracts_dir, - contracts_docs_dir=args.contracts_docs_dir, - init_data_file=args.init_data_file, - output=args.output, - timestamp=args.timestamp, - init_token=args.init_token, - prevhash=args.prevhash, - ) - - -def core(contracts_dir, contracts_docs_dir, init_data_file, output, timestamp, - init_token, prevhash): - # pylint: disable=too-many-arguments - replaceLogRecord() - if solidity.get_solidity() is None: - print('Solidity not found!') - sys.exit(1) - if contracts_docs_dir: - contracts_docs_dir = os.path.abspath(contracts_docs_dir) - genesis_data = GenesisData( - os.path.abspath(contracts_dir), - contracts_docs_dir, - os.path.abspath(init_data_file), - timestamp, - prevhash, - ) - with open(init_data_file, 'r') as stream: - data = yaml.safe_load(stream) - super_admin = data['Contracts'][6]['Admin'][0]['admin'] - genesis_data.init_normal_contracts() - genesis_data.init_permission_contracts() - genesis_data.set_account_value(super_admin, init_token) - genesis_data.save_to_file(output) - - -if __name__ == '__main__': - core(**parse_arguments()) diff --git a/scripts/config_tool/create_init_data.py b/scripts/config_tool/create_init_data.py index 5443dcec5..ec34cf410 100755 --- a/scripts/config_tool/create_init_data.py +++ b/scripts/config_tool/create_init_data.py @@ -8,59 +8,49 @@ DEFAULT_CONFIG = ''' Contracts: -- SysConfig: - - delayBlockNumber: 1 - - checkCallPermission: false - - checkSendTxPermission: false - - checkCreateContractPermission: false - - checkQuota: false - - checkFeeBackPlatform: false - - chainOwner: '0x0000000000000000000000000000000000000000' - - chainName: test-chain - - chainId: 1 - - operator: test-operator - - website: https://www.example.com - - blockInterval: 3000 - - economicalModel: 0 - - name: CITA Test Token - - symbol: CTT - - avatar: https://cdn.cryptape.com/icon_cita.png - - autoExec: false -- QuotaManager: - - admin: '0x4b5ae4567ad5d9fb92bc9afd6a657e6fa13a2523' -- NodeManager: - - nodes: - - '0x4b5ae4567ad5d9fb92bc9afd6a657e6fa13a2523' - - stakes: - - 0 -- ChainManager: - - parentChainId: 0 - - parentChainAuthorities: [] -- Authorization: - - superAdmin: '0x4b5ae4567ad5d9fb92bc9afd6a657e6fa13a2523' -- Group: - - parent: '0x0000000000000000000000000000000000000000' - - name: rootGroup - - accounts: - - '0x4b5ae4567ad5d9fb92bc9afd6a657e6fa13a2523' -- Admin: - - admin: '0x4b5ae4567ad5d9fb92bc9afd6a657e6fa13a2523' -- VersionManager: - - version: 2 -- PriceManager: - - quotaPrice: 1000000 + SysConfig: + delayBlockNumber: 1 + checkCallPermission: false + checkSendTxPermission: false + checkCreateContractPermission: false + checkQuota: false + checkFeeBackPlatform: false + chainOwner: '0x0000000000000000000000000000000000000000' + chainName: test-chain + chainId: 1 + operator: test-operator + website: https://www.example.com + blockInterval: 3000 + economicalModel: 0 + name: CITA Test Token + symbol: CTT + avatar: https://cdn.cryptape.com/icon_cita.png + autoExec: false + QuotaManager: + admin: '0x4b5ae4567ad5d9fb92bc9afd6a657e6fa13a2523' + NodeManager: + nodes: + - '0x4b5ae4567ad5d9fb92bc9afd6a657e6fa13a2523' + stakes: + - 0 + ChainManager: + parentChainId: 0 + parentChainAuthorities: [] + Authorization: + superAdmin: '0x4b5ae4567ad5d9fb92bc9afd6a657e6fa13a2523' + Group: + parent: '0x0000000000000000000000000000000000000000' + name: rootGroup + accounts: + - '0x4b5ae4567ad5d9fb92bc9afd6a657e6fa13a2523' + Admin: + admin: '0x4b5ae4567ad5d9fb92bc9afd6a657e6fa13a2523' + VersionManager: + version: 2 + PriceManager: + quotaPrice: 1000000 ''' - -def dictlist_to_ordereddict(dictlist): - """Convert a list of dict to an ordered dict.""" - odd = collections.OrderedDict() - for dic in dictlist: - for key, val in dic.items(): - odd[key] = val - return odd - - def ordereddict_to_dictlist(ordereddict): """Convert an ordered dict to a list of dict.""" return [{key: value} for key, value in ordereddict.items()] @@ -99,10 +89,7 @@ def __init__(self, contracts_cfgs): @classmethod def load_from_string(cls, cfg): data = yaml.safe_load(cfg) - contracts_cfgs = dictlist_to_ordereddict(data['Contracts']) - for name, arguments in contracts_cfgs.items(): - contracts_cfgs[name] = dictlist_to_ordereddict(arguments) - return cls(contracts_cfgs=contracts_cfgs) + return cls(contracts_cfgs=data['Contracts']) def update_by_kkv_dict(self, kkv_dict): if not kkv_dict: @@ -134,9 +121,7 @@ def set_super_admin(self, super_admin): def save_to_file(self, filepath): data = dict() contracts_cfgs = self.contracts_cfgs - for name, arguments in contracts_cfgs.items(): - contracts_cfgs[name] = ordereddict_to_dictlist(arguments) - data['Contracts'] = ordereddict_to_dictlist(contracts_cfgs) + data['Contracts'] = self.contracts_cfgs with open(filepath, 'w') as stream: yaml.dump(data, stream, default_flow_style=False) diff --git a/scripts/config_tool/config_example/auth.toml b/scripts/config_tool/default_config/auth.toml similarity index 100% rename from scripts/config_tool/config_example/auth.toml rename to scripts/config_tool/default_config/auth.toml diff --git a/scripts/config_tool/config_example/chain.toml b/scripts/config_tool/default_config/chain.toml similarity index 100% rename from scripts/config_tool/config_example/chain.toml rename to scripts/config_tool/default_config/chain.toml diff --git a/scripts/config_tool/config_example/consensus.toml b/scripts/config_tool/default_config/consensus.toml similarity index 100% rename from scripts/config_tool/config_example/consensus.toml rename to scripts/config_tool/default_config/consensus.toml diff --git a/scripts/config_tool/config_example/executor.toml b/scripts/config_tool/default_config/executor.toml similarity index 100% rename from scripts/config_tool/config_example/executor.toml rename to scripts/config_tool/default_config/executor.toml diff --git a/scripts/config_tool/config_example/forever.toml b/scripts/config_tool/default_config/forever.toml similarity index 100% rename from scripts/config_tool/config_example/forever.toml rename to scripts/config_tool/default_config/forever.toml diff --git a/scripts/config_tool/config_example/forever_mock.toml b/scripts/config_tool/default_config/forever_mock.toml similarity index 100% rename from scripts/config_tool/config_example/forever_mock.toml rename to scripts/config_tool/default_config/forever_mock.toml diff --git a/scripts/config_tool/config_example/jsonrpc.toml b/scripts/config_tool/default_config/jsonrpc.toml similarity index 100% rename from scripts/config_tool/config_example/jsonrpc.toml rename to scripts/config_tool/default_config/jsonrpc.toml diff --git a/scripts/config_tool/genesis b/scripts/config_tool/genesis index c883acdff..0ab5c9947 160000 --- a/scripts/config_tool/genesis +++ b/scripts/config_tool/genesis @@ -1 +1 @@ -Subproject commit c883acdff4d950e434c148c8671dde355bd26613 +Subproject commit 0ab5c9947df48e55dfc16d2b375c5509a58d5aeb diff --git a/scripts/contracts/contracts.yml b/scripts/contracts/contracts.yml index d062a9be6..fb261855c 100644 --- a/scripts/contracts/contracts.yml +++ b/scripts/contracts/contracts.yml @@ -1,62 +1,62 @@ NormalContracts: -- SysConfig: + SysConfig: address: '0xffffffffffffffffffffffffffffffffff020000' file: system/SysConfig.sol -- NodeManager: + NodeManager: address: '0xffffffffffffffffffffffffffffffffff020001' file: system/NodeManager.sol -- ChainManager: + ChainManager: address: '0xffffffffffffffffffffffffffffffffff020002' file: system/ChainManager.sol -- QuotaManager: + QuotaManager: address: '0xffffffffffffffffffffffffffffffffff020003' file: system/QuotaManager.sol -- PermissionManagement: + PermissionManagement: address: '0xffffffffffffffffffffffffffffffffff020004' file: permission_management/PermissionManagement.sol -- PermissionCreator: + PermissionCreator: address: '0xffffffffffffffffffffffffffffffffff020005' file: permission_management/PermissionCreator.sol -- Authorization: + Authorization: address: '0xffffffffffffffffffffffffffffffffff020006' file: permission_management/Authorization.sol -- RoleManagement: + RoleManagement: address: '0xffffffffffffffffffffffffffffffffff020007' file: role_management/RoleManagement.sol -- RoleCreator: + RoleCreator: address: '0xffffffffffffffffffffffffffffffffff020008' file: role_management/RoleCreator.sol -- Group: + Group: address: '0xffffffffffffffffffffffffffffffffff020009' file: user_management/Group.sol -- GroupManagement: + GroupManagement: address: '0xffffffffffffffffffffffffffffffffff02000a' file: user_management/GroupManagement.sol -- GroupCreator: + GroupCreator: address: '0xffffffffffffffffffffffffffffffffff02000b' file: user_management/GroupCreator.sol -- Admin: + Admin: address: '0xffffffffffffffffffffffffffffffffff02000c' file: common/Admin.sol -- RoleAuth: + RoleAuth: address: '0xffffffffffffffffffffffffffffffffff02000d' file: role_management/RoleAuth.sol -- BatchTx: + BatchTx: address: '0xffffffffffffffffffffffffffffffffff02000e' file: system/BatchTx.sol -- EmergencyBrake: + EmergencyIntervention: address: '0xffffffffffffffffffffffffffffffffff02000f' - file: system/EmergencyBrake.sol -- PriceManager: + file: system/EmergencyIntervention.sol + PriceManager: address: '0xffffffffffffffffffffffffffffffffff020010' file: system/PriceManager.sol -- VersionManager: + VersionManager: address: '0xffffffffffffffffffffffffffffffffff020011' file: system/VersionManager.sol -- AllGroups: + AllGroups: address: '0xffffffffffffffffffffffffffffffffff020012' file: user_management/AllGroups.sol -- AutoExec: + AutoExec: address: '0xffffffffffffffffffffffffffffffffff020013' file: system/AutoExec.sol @@ -64,162 +64,164 @@ NormalContracts: PermissionContracts: file: permission_management/Permission.sol basic: - - sendTx: + sendTx: address: '0xffffffffffffffffffffffffffffffffff021000' - - createContract: + createContract: address: '0xffffffffffffffffffffffffffffffffff021001' contracts: - - newPermission: + newPermission: address: '0xffffffffffffffffffffffffffffffffff021010' contracts: - - PermissionManagement + - PermissionManagement functions: - - 'newPermission(bytes32,address[],bytes4[])' - - deletePermission: + - 'newPermission(bytes32,address[],bytes4[])' + deletePermission: address: '0xffffffffffffffffffffffffffffffffff021011' contracts: - - PermissionManagement + - PermissionManagement functions: - - 'deletePermission(address)' - - updatePermission: + - 'deletePermission(address)' + updatePermission: address: '0xffffffffffffffffffffffffffffffffff021012' contracts: - - PermissionManagement - - PermissionManagement - - PermissionManagement + - PermissionManagement + - PermissionManagement + - PermissionManagement functions: - - 'addResources(address,address[],bytes4[])' - - 'deleteResources(address,address[],bytes4[])' - - 'updatePermissionName(address,bytes32)' - - setAuth: + - 'addResources(address,address[],bytes4[])' + - 'deleteResources(address,address[],bytes4[])' + - 'updatePermissionName(address,bytes32)' + setAuth: address: '0xffffffffffffffffffffffffffffffffff021013' contracts: - - PermissionManagement - - PermissionManagement + - PermissionManagement + - PermissionManagement functions: - - 'setAuthorization(address,address)' - - 'setAuthorizations(address,address[])' - - cancelAuth: + - 'setAuthorization(address,address)' + - 'setAuthorizations(address,address[])' + cancelAuth: address: '0xffffffffffffffffffffffffffffffffff021014' contracts: - - PermissionManagement - - PermissionManagement - - PermissionManagement + - PermissionManagement + - PermissionManagement + - PermissionManagement functions: - - 'cancelAuthorization(address,address)' - - 'clearAuthorization(address)' - - 'cancelAuthorizations(address,address[])' - - newRole: + - 'cancelAuthorization(address,address)' + - 'clearAuthorization(address)' + - 'cancelAuthorizations(address,address[])' + newRole: address: '0xffffffffffffffffffffffffffffffffff021015' contracts: - - RoleManagement + - RoleManagement functions: - - 'newRole(bytes32,address[])' - - deleteRole: + - 'newRole(bytes32,address[])' + deleteRole: address: '0xffffffffffffffffffffffffffffffffff021016' contracts: - - RoleManagement + - RoleManagement functions: - - 'deleteRole(address)' - - updateRole: + - 'deleteRole(address)' + updateRole: address: '0xffffffffffffffffffffffffffffffffff021017' contracts: - - RoleManagement - - RoleManagement - - RoleManagement + - RoleManagement + - RoleManagement + - RoleManagement functions: - - 'addPermissions(address,address[])' - - 'deletePermissions(address,address[])' - - 'updateRoleName(address,bytes32)' - - setRole: + - 'addPermissions(address,address[])' + - 'deletePermissions(address,address[])' + - 'updateRoleName(address,bytes32)' + setRole: address: '0xffffffffffffffffffffffffffffffffff021018' contracts: - - RoleManagement + - RoleManagement functions: - - 'setRole(address,address)' - - cancelRole: + - 'setRole(address,address)' + cancelRole: address: '0xffffffffffffffffffffffffffffffffff021019' contracts: - - RoleManagement - - RoleManagement + - RoleManagement + - RoleManagement functions: - - 'cancelRole(address,address)' - - 'clearRole(address)' - - newGroup: + - 'cancelRole(address,address)' + - 'clearRole(address)' + newGroup: address: '0xffffffffffffffffffffffffffffffffff02101a' contracts: - - GroupManagement + - GroupManagement functions: - - 'newGroup(address,bytes32,address[])' - - deleteGroup: + - 'newGroup(address,bytes32,address[])' + deleteGroup: address: '0xffffffffffffffffffffffffffffffffff02101b' contracts: - - GroupManagement + - GroupManagement functions: - - 'deleteGroup(address,address)' - - updateGroup: + - 'deleteGroup(address,address)' + updateGroup: address: '0xffffffffffffffffffffffffffffffffff02101c' contracts: - - GroupManagement - - GroupManagement - - GroupManagement + - GroupManagement + - GroupManagement + - GroupManagement functions: - - 'addAccounts(address,address,address[])' - - 'deleteAccounts(address,address,address[])' - - 'updateGroupName(address,address,bytes32)' - - newNode: + - 'addAccounts(address,address,address[])' + - 'deleteAccounts(address,address,address[])' + - 'updateGroupName(address,address,bytes32)' + newNode: address: '0xffffffffffffffffffffffffffffffffff021020' contracts: - - NodeManager + - NodeManager functions: - - 'approveNode(address)' - - deleteNode: + - 'approveNode(address)' + deleteNode: address: '0xffffffffffffffffffffffffffffffffff021021' contracts: - - NodeManager + - NodeManager functions: - - 'deleteNode(address)' - - updateNode: + - 'deleteNode(address)' + updateNode: address: '0xffffffffffffffffffffffffffffffffff021022' contracts: - - NodeManager + - NodeManager functions: - - 'setStake(address,uint64)' - - accountQuota: + - 'setStake(address,uint64)' + accountQuota: address: '0xffffffffffffffffffffffffffffffffff021023' contracts: - - QuotaManager - - QuotaManager + - QuotaManager + - QuotaManager functions: - - 'setDefaultAQL(uint256)' - - 'setAQL(address,uint256)' - - blockQuota: + - 'setDefaultAQL(uint256)' + - 'setAQL(address,uint256)' + blockQuota: address: '0xffffffffffffffffffffffffffffffffff021024' contracts: - - QuotaManager + - QuotaManager functions: - - 'setBQL(uint256)' - - batchTx: + - 'setBQL(uint256)' + batchTx: address: '0xffffffffffffffffffffffffffffffffff021025' contracts: - - BatchTx + - BatchTx functions: - - 'multiTxs(bytes)' - - emergencyBrake: + - 'multiTxs(bytes)' + emergencyIntervention: address: '0xffffffffffffffffffffffffffffffffff021026' contracts: - - EmergencyBrake + - EmergencyIntervention functions: - - 'setState(bool)' - - quotaPrice: + - 'setState(bool)' + quotaPrice: address: '0xffffffffffffffffffffffffffffffffff021027' contracts: - - PriceManager + - PriceManager functions: - - 'setQuotaPrice(uint256)' - - version: + - 'setQuotaPrice(uint256)' + version: address: '0xffffffffffffffffffffffffffffffffff021028' contracts: - - VersionManager + - VersionManager + - VersionManager functions: - - 'setVersion(uint32)' + - 'setVersion(uint32)' + - 'setProtocolVersion(uint32)' diff --git a/scripts/contracts/interaction b/scripts/contracts/interaction index a04224eac..0be3ed1ab 160000 --- a/scripts/contracts/interaction +++ b/scripts/contracts/interaction @@ -1 +1 @@ -Subproject commit a04224eac9eb0a97bfbd0c6938fbd98f671860be +Subproject commit 0be3ed1ab06e69f032c6d5b5fee0d54c108f3a0f diff --git a/scripts/contracts/src/role_management/RoleAuth.sol b/scripts/contracts/src/role_management/RoleAuth.sol index 28fa6c4b6..2a25f11aa 100644 --- a/scripts/contracts/src/role_management/RoleAuth.sol +++ b/scripts/contracts/src/role_management/RoleAuth.sol @@ -4,7 +4,7 @@ import "./RoleCreator.sol"; import "../../interaction/interface/IAuthorization.sol"; import "../lib/ContractCheck.sol"; import "../lib/AddressArray.sol"; -import "../interaction/interface/IRoleAuth.sol"; +import "../../interaction/interface/IRoleAuth.sol"; /// @title Authorization about role and account /// @author ["Cryptape Technologies "] diff --git a/scripts/contracts/src/system/EmergencyBrake.sol b/scripts/contracts/src/system/EmergencyIntervention.sol similarity index 72% rename from scripts/contracts/src/system/EmergencyBrake.sol rename to scripts/contracts/src/system/EmergencyIntervention.sol index 7067440ff..adecdfc88 100644 --- a/scripts/contracts/src/system/EmergencyBrake.sol +++ b/scripts/contracts/src/system/EmergencyIntervention.sol @@ -2,9 +2,9 @@ pragma solidity 0.4.24; import "../common/Admin.sol"; import "../common/ReservedAddrPublic.sol"; -import "../../interaction/interface/IEmergencyBrake.sol"; +import "../../interaction/interface/IEmergencyIntervention.sol"; -contract EmergencyBrake is IEmergencyBrake, ReservedAddrPublic { +contract EmergencyIntervention is IEmergencyIntervention, ReservedAddrPublic { bool public state; Admin admin = Admin(adminAddr); diff --git a/scripts/contracts/src/system/VersionManager.sol b/scripts/contracts/src/system/VersionManager.sol index 18dbcd4f2..182c9535b 100644 --- a/scripts/contracts/src/system/VersionManager.sol +++ b/scripts/contracts/src/system/VersionManager.sol @@ -23,7 +23,7 @@ contract VersionManager is IVersionManager, ReservedAddrPublic { version = _version; } - function setVersion(uint32 _version) + function setProtocolVersion(uint32 _version) public onlyAdmin { @@ -37,11 +37,28 @@ contract VersionManager is IVersionManager, ReservedAddrPublic { version = _version; } - function getVersion() + /// @notice Deprecated. Check the setProtocolVersion + function setVersion(uint32 _version) + public + onlyAdmin + { + setProtocolVersion(_version); + } + + function getProtocolVersion() public view returns (uint32) { return version; } + + /// @notice Deprecated. Check the getProtocolVersion + function getVersion() + public + view + returns (uint32) + { + return getProtocolVersion(); + } } diff --git a/scripts/contracts/tests/contracts b/scripts/contracts/tests/contracts deleted file mode 160000 index a7a2ff2f9..000000000 --- a/scripts/contracts/tests/contracts +++ /dev/null @@ -1 +0,0 @@ -Subproject commit a7a2ff2f9d11da4f9f944e268d70c8d274678de6 diff --git a/scripts/contracts/tests/package.json b/scripts/contracts/tests/package.json index 226995a70..deb3b54ac 100644 --- a/scripts/contracts/tests/package.json +++ b/scripts/contracts/tests/package.json @@ -27,6 +27,8 @@ "batch_tx": "eslint test/integrate/batch_tx.js && mocha test/integrate/batch_tx.js -t 20s --exit", "permission": "eslint test/integrate/permission.js && mocha test/integrate/permission.js -t 20s --exit", "auto_exec": "eslint test/integrate/auto_exec.js && mocha test/integrate/auto_exec.js -t 20s --exit", + "lifetime": "eslint test/integrate/lifetime.js && mocha test/integrate/lifetime.js -t 20s --exit", + "unit_vm": "eslint test/unit/version_manager.js && mocha test/unit/version_manager.js -t 20s --exit", "lint": "eslint test", "lint-fix": "eslint --fix test" }, diff --git a/scripts/contracts/tests/test/config.js b/scripts/contracts/tests/test/config.js index 9e5f38f51..778368839 100644 --- a/scripts/contracts/tests/test/config.js +++ b/scripts/contracts/tests/test/config.js @@ -12,6 +12,7 @@ module.exports = { admin: '0xffffffffffffffffffffffffffffffffff02000c', roleAuth: '0xffffffffffffffffffffffffffffffffff02000d', autoExecAddr: '0xffffffffffffffffffffffffffffffffff020013', + versionManager: '0xffffffffffffffffffffffffffffffffff020011', }, localServer: 'http://127.0.0.1:1337', remoteServer: 'http://xx.xx.xx.xx:1337', diff --git a/scripts/contracts/tests/test/helpers/util.js b/scripts/contracts/tests/test/helpers/util.js index 29e23fded..f2cf24437 100644 --- a/scripts/contracts/tests/test/helpers/util.js +++ b/scripts/contracts/tests/test/helpers/util.js @@ -50,4 +50,5 @@ module.exports = { genContract, getTxReceipt, getBlockNumber, + getMetaData, }; diff --git a/scripts/contracts/tests/test/helpers/version_manager.js b/scripts/contracts/tests/test/helpers/version_manager.js new file mode 100644 index 000000000..c89b57d0b --- /dev/null +++ b/scripts/contracts/tests/test/helpers/version_manager.js @@ -0,0 +1,25 @@ +const fs = require('fs'); +const util = require('./util'); +const config = require('../config'); + +const { genContract, genTxParams } = util; + +const { superAdmin } = config; +const { versionManager } = config.contract; +const abi = JSON.parse(fs.readFileSync('../interaction/abi/VersionManager.abi')); +const contract = genContract(abi, versionManager); + +const getVersion = () => contract.methods.getVersion().call('pending'); + +const setProtocolVersion = async (account, _sender = superAdmin) => { + const param = await genTxParams(_sender); + return contract.methods.setProtocolVersion(account).send(param); +}; + +const getProtocolVersion = () => contract.methods.getProtocolVersion().call('pending'); + +module.exports = { + setProtocolVersion, + getProtocolVersion, + getVersion, +}; diff --git a/scripts/contracts/tests/test/integrate/auto_exec.js b/scripts/contracts/tests/test/integrate/auto_exec.js index 9dd79d613..4f30830ee 100644 --- a/scripts/contracts/tests/test/integrate/auto_exec.js +++ b/scripts/contracts/tests/test/integrate/auto_exec.js @@ -20,9 +20,11 @@ let param; let hash; // test data -const bin = '608060405234801561001057600080fd5b5060cf8061001f6000396000f3006080604052600436106049576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff1680630c55699c14604e578063844cbc43146076575b600080fd5b348015605957600080fd5b506060608a565b6040518082815260200191505060405180910390f35b348015608157600080fd5b5060886090565b005b60005481565b60008081548092919060010191905055505600a165627a7a72305820d5b2c5380ae2f0103722d0da7d082e8f342e2a017de0fd63f11c48cfc4a0b0140029'; +const bin = '608060405234801561001057600080fd5b506101a1806100206000396000f300608060405260043610610057576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff1680630c55699c1461005c5780634826c2be14610087578063844cbc43146100de575b600080fd5b34801561006857600080fd5b506100716100f5565b6040518082815260200191505060405180910390f35b34801561009357600080fd5b5061009c6100fb565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b3480156100ea57600080fd5b506100f3610121565b005b60005481565b600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b600080815480929190600101919050555041600160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055505600a165627a7a723058203e04df92be8ab872ae22ab17a37324afaea0956de6408cb798dcb2394353f1e70029'; const abi = [{ constant: true, inputs: [], name: 'x', outputs: [{ name: '', type: 'uint256' }], payable: false, stateMutability: 'view', type: 'function', +}, { + constant: true, inputs: [], name: 'coinBase', outputs: [{ name: '', type: 'address' }], payable: false, stateMutability: 'view', type: 'function', }, { constant: false, inputs: [], name: 'autoExec', outputs: [], payable: false, stateMutability: 'nonpayable', type: 'function', }]; @@ -69,6 +71,13 @@ describe('\n\ntest auto exec\n\n', () => { expect(+ret).to.be.above(1); }); + it('get the coinbase after auto exec', async () => { + const contract = genContract(abi, addr); + const ret = await contract.methods.coinBase().call('pending'); + logger.debug('\nThe coinBase:\n', ret); + expect(ret).to.not.equal('0x0000000000000000000000000000000000000000'); + }); + it('should not exec tx', async () => { const res = await autoExec(); logger.debug('\nSend tx ok:\n', JSON.stringify(res)); diff --git a/scripts/contracts/tests/test/integrate/lifetime.js b/scripts/contracts/tests/test/integrate/lifetime.js new file mode 100644 index 000000000..7ae0b58f2 --- /dev/null +++ b/scripts/contracts/tests/test/integrate/lifetime.js @@ -0,0 +1,81 @@ +const chai = require('chai'); +const util = require('../helpers/util'); +const config = require('../config'); + +const { expect } = chai; +const { + citaSDK, logger, genTxParams, genContract, getTxReceipt, +} = util; + +const { superAdmin } = config; + +// tmp +let addr; +let param; +let hash; +let balance; +const value = '0x100000'; + +// test data +const bin = '6080604052336000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506000600260006101000a81548160ff0219169083151502179055506103aa8061006e6000396000f300608060405260043610610083576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff168063054f7d9c1461008557806341c0e1b5146100b457806360fe47b1146100cb57806362a5af3b146100f85780636a28f0001461010f5780636d4ce63c146101265780638da5cb5b14610151575b005b34801561009157600080fd5b5061009a6101a8565b604051808215151515815260200191505060405180910390f35b3480156100c057600080fd5b506100c96101bb565b005b3480156100d757600080fd5b506100f660048036038101908080359060200190929190505050610280565b005b34801561010457600080fd5b5061010d610315565b005b34801561011b57600080fd5b50610124610332565b005b34801561013257600080fd5b5061013b61034f565b6040518082815260200191505060405180910390f35b34801561015d57600080fd5b50610166610359565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b600260009054906101000a900460ff1681565b60001515600260009054906101000a900460ff161515141515610246576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260188152602001807f546869732066756e6374696f6e2069732066726f7a656e2e000000000000000081525060200191505060405180910390fd5b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16ff5b60001515600260009054906101000a900460ff16151514151561030b576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260188152602001807f546869732066756e6374696f6e2069732066726f7a656e2e000000000000000081525060200191505060405180910390fd5b8060018190555050565b6001600260006101000a81548160ff021916908315150217905550565b6000600260006101000a81548160ff021916908315150217905550565b6000600154905090565b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff16815600a165627a7a72305820c3bf27393a60762b7e0ea2853f01849fccbc0f1c065fad2f2db0db1a005e36ee0029'; +const abi = [{ + constant: true, inputs: [], name: 'frozen', outputs: [{ name: '', type: 'bool' }], payable: false, stateMutability: 'view', type: 'function', +}, { + constant: false, inputs: [], name: 'kill', outputs: [], payable: false, stateMutability: 'nonpayable', type: 'function', +}, { + constant: false, inputs: [{ name: 'x', type: 'uint256' }], name: 'set', outputs: [], payable: false, stateMutability: 'nonpayable', type: 'function', +}, { + constant: false, inputs: [], name: 'freeze', outputs: [], payable: false, stateMutability: 'nonpayable', type: 'function', +}, { + constant: false, inputs: [], name: 'unfreeze', outputs: [], payable: false, stateMutability: 'nonpayable', type: 'function', +}, { + constant: true, inputs: [], name: 'get', outputs: [{ name: '', type: 'uint256' }], payable: false, stateMutability: 'view', type: 'function', +}, { + constant: true, inputs: [], name: 'owner', outputs: [{ name: '', type: 'address' }], payable: false, stateMutability: 'view', type: 'function', +}, { + inputs: [], payable: true, stateMutability: 'payable', type: 'constructor', +}, { payable: true, stateMutability: 'payable', type: 'fallback' }]; + +describe('\n\nDeploy a contract\n\n', () => { + it('should send a tx: deploy_contract', async () => { + param = await genTxParams(superAdmin); + const res = await citaSDK.base.deploy( + bin, + { ...param, value }, + ); + logger.debug('\nDeploy a contract:\n', res.contractAddress); + addr = res.contractAddress; + }); +}); + +describe('\n\ntest lifetime of contract\n\n', () => { + it('get the balance of superAdmin and contract', async () => { + balance = await citaSDK.base.getBalance(superAdmin.address, 'pending'); + const res = await citaSDK.base.getBalance(addr, 'pending'); + logger.debug('\nThe balance of admin: %s,\nand contract: %s\n', balance, res); + expect(+res).to.equal(+value); + }); + + it('should send a suicide tx', async () => { + const contract = genContract(abi, addr); + const res = await contract.methods.kill().send(param); + logger.debug('\nSend tx ok:\n', JSON.stringify(res)); + expect(res.status).to.equal('OK'); + ({ hash } = res); + }); + + it('should get receipt:', async () => { + const res = await getTxReceipt(hash); + logger.debug('\nget receipt:\n', res); + expect(res.errorMessage).to.be.null; + }); + + it('get the balance of superAdmin and contract', async () => { + const resAdmin = await citaSDK.base.getBalance(superAdmin.address, 'pending'); + const resCont = await citaSDK.base.getBalance(addr, 'pending'); + logger.debug('\nThe balance of admin: %s\nThe contract: %s', resAdmin, resCont); + expect(+resCont).to.equal(0); + // Not equal balance+value: cause the tx fee. + expect(+resAdmin).to.be.above(+balance); + }); +}); diff --git a/scripts/contracts/tests/test/unit/version_manager.js b/scripts/contracts/tests/test/unit/version_manager.js new file mode 100644 index 000000000..f7e52cef8 --- /dev/null +++ b/scripts/contracts/tests/test/unit/version_manager.js @@ -0,0 +1,56 @@ +const chai = require('chai'); +const util = require('../helpers/util'); +const versionManager = require('../helpers/version_manager'); + +const { expect } = chai; +const { + logger, getTxReceipt, getMetaData, +} = util; +const { + setProtocolVersion, getProtocolVersion, getVersion, +} = versionManager; + +// temp +let hash; +let version; + +describe('\n\ntest version manager\n\n', () => { + before('should have version', async () => { + const metaData = await getMetaData(); + ({ version } = metaData); + logger.debug('\nthe version of metaData is:\n', version); + }); + + it('should get the protocol version', async () => { + const res = await getProtocolVersion(); + logger.debug('\nthe version is:\n', res); + expect(+res).to.be.equal(version); + }); + + it('should send a tx: setProtocolVersion', async () => { + const res = await setProtocolVersion(version + 1); + logger.debug('\nSend tx ok:\n', JSON.stringify(res)); + expect(res.status).to.equal('OK'); + ({ hash } = res); + }); + + it('should get receipt: setProtocolVersion', async () => { + const res = await getTxReceipt(hash); + logger.debug('\nget receipt:\n', res); + expect(res.errorMessage).to.be.null; + version += 1; + }); + + it('should get the protocol version', async () => { + const res = await getProtocolVersion(); + logger.debug('\nthe version is:\n', res); + expect(+res).to.be.equal(version); + }); + + // old interface + it('should get the version', async () => { + const res = await getVersion(); + logger.debug('\nthe version is:\n', res); + expect(+res).to.be.equal(version); + }); +}); diff --git a/scripts/contracts/tests/yarn.lock b/scripts/contracts/tests/yarn.lock index c3ece95e4..3d3670655 100644 --- a/scripts/contracts/tests/yarn.lock +++ b/scripts/contracts/tests/yarn.lock @@ -1357,10 +1357,10 @@ fs.realpath@^1.0.0: resolved "https://registry.yarnpkg.com/fs.realpath/-/fs.realpath-1.0.0.tgz#1504ad2523158caa40db4a2787cb01411994ea4f" integrity sha1-FQStJSMVjKpA20onh8sBQRmU6k8= -fstream@^1.0.2, fstream@^1.0.8: - version "1.0.11" - resolved "https://registry.yarnpkg.com/fstream/-/fstream-1.0.11.tgz#5c1fb1f117477114f0632a0eb4b71b3cb0fd3171" - integrity sha1-XB+x8RdHcRTwYyoOtLcbPLD9MXE= +fstream@^1.0.12, fstream@^1.0.8: + version "1.0.12" + resolved "https://registry.yarnpkg.com/fstream/-/fstream-1.0.12.tgz#4e8ba8ee2d48be4f7d0de505455548eae5932045" + integrity sha512-WvJ193OHa0GHPEL+AycEJgxvBEwyfRkN1vhjca23OaPVMCaLCXTd5qAu82AjTcgP1UJmytkOKb63Ypde7raDIg== dependencies: graceful-fs "^4.1.2" inherits "~2.0.0" @@ -1419,7 +1419,7 @@ getpass@^0.1.1: dependencies: assert-plus "^1.0.0" -glob@7.1.3, glob@^7.1.2, glob@^7.1.3: +glob@7.1.3, glob@^7.1.2: version "7.1.3" resolved "https://registry.yarnpkg.com/glob/-/glob-7.1.3.tgz#3960832d3f1574108342dafd3a67b332c0969df1" integrity sha512-vcfuiIxogLV4DlGBHIUOwI0IbrJ8HWPc4MU7HzviGeNho/UJDfi6B5p3sHeWIQ0KGIU0Jpxi5ZHxemQfLkkAwQ== @@ -1431,6 +1431,18 @@ glob@7.1.3, glob@^7.1.2, glob@^7.1.3: once "^1.3.0" path-is-absolute "^1.0.0" +glob@^7.1.3: + version "7.1.4" + resolved "https://registry.yarnpkg.com/glob/-/glob-7.1.4.tgz#aa608a2f6c577ad357e1ae5a5c26d9a8d1969255" + integrity sha512-hkLPepehmnKk41pUGm3sYxoFs/umurYfYJCerbXEyFIWcAzvpipAgVkBqqT9RBKMGjnq6kMuyYwha6csxbiM1A== + dependencies: + fs.realpath "^1.0.0" + inflight "^1.0.4" + inherits "2" + minimatch "^3.0.4" + once "^1.3.0" + path-is-absolute "^1.0.0" + global@~4.3.0: version "4.3.2" resolved "https://registry.yarnpkg.com/global/-/global-4.3.2.tgz#e76989268a6c74c38908b1305b10fc0e394e9d0f" @@ -3175,12 +3187,12 @@ tar.gz@^1.0.5: tar "^2.1.1" tar@^2.1.1: - version "2.2.1" - resolved "https://registry.yarnpkg.com/tar/-/tar-2.2.1.tgz#8e4d2a256c0e2185c6b18ad694aec968b83cb1d1" - integrity sha1-jk0qJWwOIYXGsYrWlK7JaLg8sdE= + version "2.2.2" + resolved "https://registry.yarnpkg.com/tar/-/tar-2.2.2.tgz#0ca8848562c7299b8b446ff6a4d60cdbb23edc40" + integrity sha512-FCEhQ/4rE1zYv9rYXJw/msRqsnmlje5jHP6huWeBZ704jUTy02c5AZyWujpMR1ax6mVw9NyJMfuK2CMDWVIfgA== dependencies: block-stream "*" - fstream "^1.0.2" + fstream "^1.0.12" inherits "2" text-table@^0.2.0: diff --git a/scripts/create_cita_config.py b/scripts/create_cita_config.py index 53bf0a9e6..5f787473c 100755 --- a/scripts/create_cita_config.py +++ b/scripts/create_cita_config.py @@ -10,7 +10,10 @@ import sys import tempfile import toml +import subprocess +import time +DEFAULT_PREVHASH = '0x{:064x}'.format(0) def update_search_paths(work_dir): """Add new path to the search path.""" @@ -60,7 +63,7 @@ def generate_keypairs(amount): privkeys = list() _, address_path = tempfile.mkstemp() _, secret_path = tempfile.mkstemp() - cmd = 'create_key_addr "{}" "{}"'.format(secret_path, address_path) + cmd = 'create-key-addr "{}" "{}"'.format(secret_path, address_path) for _ in range(0, amount): os.system(cmd) with open(address_path, 'rt') as stream: @@ -239,14 +242,17 @@ def create_init_data(self, super_admin, contract_arguments): create_init_data(self.init_data_file, super_admin, contract_arguments) def create_genesis(self, timestamp, init_token, resource_dir): - from create_genesis import core as create_genesis prevhash = generate_prevhash(resource_dir) if resource_dir is not None: shutil.copytree(resource_dir, os.path.join(self.configs_dir, 'resource'), False) - create_genesis(self.contracts_dir, self.contracts_docs_dir, - self.init_data_file, self.genesis_path, timestamp, - init_token, prevhash) + + prevhash = DEFAULT_PREVHASH if not prevhash else str(prevhash) + timestamp = str(int(time.time() * 1000)) if not timestamp else str(timestamp) + + process = subprocess.Popen(["./bin/create-genesis",self.contracts_dir, self.contracts_docs_dir, + self.init_data_file, self.genesis_path, timestamp, init_token, prevhash]) + process.wait() def append_node(self, node): # For append mode: use the first element to store the new node @@ -337,7 +343,7 @@ def run_subcmd_create(args, work_dir): info = ChainInfo(args.chain_name, work_dir) info.template_create_from_arguments( args, os.path.join(work_dir, 'scripts/contracts'), - os.path.join(work_dir, 'scripts/config_tool/config_example')) + os.path.join(work_dir, 'scripts/config_tool/default_config')) info.create_init_data(args.super_admin, args.contract_arguments) info.create_genesis(args.timestamp, args.init_token, args.resource_dir) info.enable_tls = args.enable_tls diff --git a/scripts/release.sh b/scripts/release.sh index a91f0b087..33e6343fa 100755 --- a/scripts/release.sh +++ b/scripts/release.sh @@ -1,13 +1,13 @@ #!/bin/bash -if [[ `uname` == 'Darwin' ]] +if [[ $(uname) == 'Darwin' ]] then - SOURCE_DIR=$(realpath $(dirname $(realpath $0))/..) + SOURCE_DIR=$(realpath "$(dirname "$(realpath "$0")")"/..) else - SOURCE_DIR=$(readlink -f $(dirname $(realpath $0))/..) + SOURCE_DIR=$(readlink -f "$(dirname "$(realpath "$0")")"/..) fi -cd ${SOURCE_DIR} +cd "${SOURCE_DIR}" || exit if [ $# -ne 1 ] ; then echo "usage: $0 debug|release" @@ -30,19 +30,20 @@ for binary in \ cita-forever \ cita-jsonrpc \ cita-network \ - create_key_addr \ + create-key-addr \ + create-genesis \ cita-relayer-parser \ - snapshot_tool \ + snapshot-tool \ consensus-mock \ chain-executor-mock \ - box_executor \ + box-executor \ ; do cp -rf "target/${type}/${binary}" target/install/bin/ done #strip target/install/bin/* # 2) cita -cp -rf scripts/cita target/install/bin/ +cp -rf scripts/cita.sh target/install/bin/cita # 3) contract cp -rf scripts/contracts target/install/scripts/ diff --git a/scripts/replace_default_feature.sh b/scripts/replace_default_feature.sh index c3fd0fff5..00b9dc7c4 100755 --- a/scripts/replace_default_feature.sh +++ b/scripts/replace_default_feature.sh @@ -11,9 +11,9 @@ function replace_default_feature () { fi local before_feature='[ \t]*default[ \t]*=[ \t]*\[.*\"' local after_feature='\".*' - find "${workspacedir}" -mindepth 2 -name "Cargo.toml" \ - | xargs grep -l "^${before_feature}${old_feature}${after_feature}" \ - | while read cargotoml; do + find "${workspacedir}" -mindepth 2 -name "Cargo.toml" -print0 \ + | xargs -0 grep -l "^${before_feature}${old_feature}${after_feature}" \ + | while read -r cargotoml; do if [ -f "${cargotoml}" ]; then echo "[Info ] Replace [${old_feature}] by [${new_feature}] for [${cargotoml}] ..." sed -i "s/\(${before_feature}\)${old_feature}\(${after_feature}\)\$/\1${new_feature}\2/" "${cargotoml}" diff --git a/style-guide/JavaScript.md b/style-guide/js.md similarity index 100% rename from style-guide/JavaScript.md rename to style-guide/js.md diff --git a/style-guide/naming.md b/style-guide/naming.md new file mode 100644 index 000000000..5ba614f6d --- /dev/null +++ b/style-guide/naming.md @@ -0,0 +1,17 @@ +# Naming Style Guide + +## Filenames + +1. First rule: Follow the rules of programming language community(Rust, Python, JavaScript, Shell, Solidity) +2. Second rule: Follow the [google-style] + +------------- + +# 命名风格指南 + +## 文件名称 + +1. 第一原则: 使用各个编程语言社区的规范(Rust, Python, JavaScript, Shell, Solidity) +2. 第二原则: 与 [google-style] 保持一致 + +[google-style]: https://developers.google.com/style/filenames diff --git a/style-guide/Python.md b/style-guide/python.md similarity index 100% rename from style-guide/Python.md rename to style-guide/python.md diff --git a/style-guide/Rust.md b/style-guide/rust.md similarity index 100% rename from style-guide/Rust.md rename to style-guide/rust.md diff --git a/style-guide/Shell.md b/style-guide/shell.md similarity index 100% rename from style-guide/Shell.md rename to style-guide/shell.md diff --git a/style-guide/Solidity.md b/style-guide/solidity.md similarity index 100% rename from style-guide/Solidity.md rename to style-guide/solidity.md diff --git a/tests/box_executor/Cargo.toml b/tests/box-executor/Cargo.toml similarity index 92% rename from tests/box_executor/Cargo.toml rename to tests/box-executor/Cargo.toml index aecc63f40..87759d52f 100644 --- a/tests/box_executor/Cargo.toml +++ b/tests/box-executor/Cargo.toml @@ -1,7 +1,8 @@ [package] -name = "box_executor" +name = "box-executor" version = "0.1.0" authors = ["Cryptape Technologies "] +edition = "2018" [dependencies] serde = "1.0" @@ -11,11 +12,11 @@ clap = "2" rustc-serialize = "0.3" dotenv = "0.13.0" bincode = "0.8.0" +cita-logger = "0.1.0" libproto = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } cita-types = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } cita-crypto = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } hashable = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } -logger = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } proof = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } rlp = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } pubsub = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } diff --git a/tests/box_executor/README.md b/tests/box-executor/README.md similarity index 100% rename from tests/box_executor/README.md rename to tests/box-executor/README.md diff --git a/tests/box_executor/src/config.rs b/tests/box-executor/src/config.rs similarity index 88% rename from tests/box_executor/src/config.rs rename to tests/box-executor/src/config.rs index 440822b4c..ffec35aeb 100644 --- a/tests/box_executor/src/config.rs +++ b/tests/box-executor/src/config.rs @@ -1,14 +1,6 @@ -extern crate bincode; extern crate cita_crypto as crypto; -extern crate cita_types; -extern crate clap; -extern crate dotenv; -extern crate pubsub; -extern crate rlp; -extern crate rustc_serialize; -extern crate serde_yaml; -use crypto::PrivKey; +use crate::crypto::PrivKey; use std::collections::HashMap; use std::fs; use std::io::Read; diff --git a/tests/box_executor/src/generate_block.rs b/tests/box-executor/src/generate_block.rs similarity index 98% rename from tests/box_executor/src/generate_block.rs rename to tests/box-executor/src/generate_block.rs index 7711fa15e..1974737e0 100644 --- a/tests/box_executor/src/generate_block.rs +++ b/tests/box-executor/src/generate_block.rs @@ -15,9 +15,9 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . +use crate::crypto::{CreateKey, KeyPair, PrivKey, Sign, Signature}; use bincode::{serialize, Infinite}; use cita_types::H256; -use crypto::{CreateKey, KeyPair, PrivKey, Sign, Signature}; use hashable::Hashable; use libproto::TryInto; use libproto::{ diff --git a/tests/box_executor/src/main.rs b/tests/box-executor/src/main.rs similarity index 83% rename from tests/box_executor/src/main.rs rename to tests/box-executor/src/main.rs index 9ccddd9b8..1366471d0 100644 --- a/tests/box_executor/src/main.rs +++ b/tests/box-executor/src/main.rs @@ -1,5 +1,5 @@ // CITA -// Copyright 2016-2017 Cryptape Technologies LLC. +// Copyright 2016-2019 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public @@ -15,31 +15,21 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . -extern crate bincode; extern crate cita_crypto as crypto; -extern crate cita_types; -extern crate clap; #[macro_use] extern crate libproto; -extern crate dotenv; -extern crate hashable; -extern crate proof; -extern crate rustc_serialize; #[macro_use] -extern crate logger; +extern crate cita_logger as logger; -extern crate pubsub; -extern crate rlp; #[macro_use] extern crate serde_derive; -extern crate serde_yaml; mod config; mod generate_block; mod runner; +use crate::config::Config; use clap::App; -use config::Config; use std::env; fn main() { diff --git a/tests/box_executor/src/runner.rs b/tests/box-executor/src/runner.rs similarity index 95% rename from tests/box_executor/src/runner.rs rename to tests/box-executor/src/runner.rs index c05ca1581..4ae599818 100644 --- a/tests/box_executor/src/runner.rs +++ b/tests/box-executor/src/runner.rs @@ -1,14 +1,5 @@ -extern crate bincode; extern crate cita_crypto as crypto; -extern crate cita_types; -extern crate clap; -extern crate dotenv; -extern crate logger; -extern crate proof; -extern crate pubsub; -extern crate rlp; -extern crate rustc_serialize; -extern crate serde_yaml; +extern crate cita_logger as logger; use libproto::{TryFrom, TryInto}; use std::convert::{From, Into}; @@ -16,10 +7,10 @@ use std::str::FromStr; use std::u8; use std::{thread, time}; +use crate::config::Config; +use crate::crypto::PrivKey; +use crate::generate_block::BuildBlock; use cita_types::H256; -use config::Config; -use crypto::PrivKey; -use generate_block::BuildBlock; use libproto::{Message, RichStatus, SignedTransaction}; use libproto::router::{MsgType, RoutingKey, SubModules}; diff --git a/tests/chain-executor-mock/Cargo.toml b/tests/chain-executor-mock/Cargo.toml index 6d77e2007..97b76469c 100644 --- a/tests/chain-executor-mock/Cargo.toml +++ b/tests/chain-executor-mock/Cargo.toml @@ -2,6 +2,7 @@ name = "chain-executor-mock" version = "0.1.0" authors = ["Cryptape Technologies "] +edition = "2018" [dependencies] serde = "1.0" @@ -11,11 +12,11 @@ clap = "2" rustc-serialize = "0.3" dotenv = "0.13.0" bincode = "0.8.0" +cita-logger = "0.1.0" libproto = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } cita-types = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } cita-crypto = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } hashable = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } -logger = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } proof = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } rlp = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } pubsub = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } diff --git a/tests/chain-executor-mock/README.md b/tests/chain-executor-mock/README.md deleted file mode 100644 index eaeaec42d..000000000 --- a/tests/chain-executor-mock/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# 功能 - -Mock chain executor 的数据 diff --git a/tests/chain-executor-mock/src/generate_block.rs b/tests/chain-executor-mock/src/generate_block.rs index 8669dfe4c..d1e128d93 100644 --- a/tests/chain-executor-mock/src/generate_block.rs +++ b/tests/chain-executor-mock/src/generate_block.rs @@ -1,5 +1,5 @@ // CITA -// Copyright 2016-2017 Cryptape Technologies LLC. +// Copyright 2016-2019 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public @@ -15,9 +15,9 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . +use crate::crypto::{CreateKey, KeyPair, PrivKey, Sign, Signature}; use bincode::{serialize, Infinite}; use cita_types::{Address, H256, U256}; -use crypto::{CreateKey, KeyPair, PrivKey, Sign, Signature}; use hashable::Hashable; use libproto::TryInto; use libproto::{Block, BlockWithProof, Message, SignedTransaction, Transaction}; @@ -57,17 +57,6 @@ impl BuildBlock { From::from(stream.out().crypt_hash()) } - /// Generate a signed transaction - /// - /// ```no_run - /// message Transaction { - /// string to = 1; - /// string nonce = 2; - /// uint64 quota = 3; - /// uint64 valid_until_block = 4; - /// bytes data = 5; - /// } - /// ``` pub fn build_tx( to_address: &str, data: &str, diff --git a/tests/chain-executor-mock/src/main.rs b/tests/chain-executor-mock/src/main.rs index bb337812b..3ee46592e 100644 --- a/tests/chain-executor-mock/src/main.rs +++ b/tests/chain-executor-mock/src/main.rs @@ -1,5 +1,5 @@ // CITA -// Copyright 2016-2017 Cryptape Technologies LLC. +// Copyright 2016-2019 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public @@ -15,24 +15,13 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . -extern crate bincode; extern crate cita_crypto as crypto; -extern crate cita_types; -extern crate clap; #[macro_use] extern crate libproto; -extern crate hashable; -extern crate proof; -extern crate rustc_serialize; - #[macro_use] -extern crate logger; -extern crate pubsub; -extern crate rlp; +extern crate cita_logger as logger; #[macro_use] extern crate serde_derive; -extern crate dotenv; -extern crate serde_yaml; mod generate_block; @@ -46,12 +35,11 @@ use std::sync::{Arc, Mutex}; use std::time; use std::{fs, u8}; -use clap::App; - +use crate::crypto::{CreateKey, KeyPair, PrivKey}; +use crate::generate_block::BuildBlock; use cita_types::traits::LowerHex; use cita_types::{H256, U256}; -use crypto::{CreateKey, KeyPair, PrivKey}; -use generate_block::BuildBlock; +use clap::App; use libproto::router::{MsgType, RoutingKey, SubModules}; use libproto::Message; use libproto::TryFrom; @@ -68,7 +56,7 @@ fn main() { info!("CITA:Chain executor mock"); let matches = App::new("Chain executor mock") - .version("0.1") + .version("0.1.0") .author("Cryptape") .arg( clap::Arg::with_name("mock-data") @@ -103,10 +91,10 @@ fn main() { info!("AMQP_URL={}", amqp_url); let sys_time = Arc::new(Mutex::new(time::SystemTime::now())); - let privkey: PrivKey = { - let privkey_str = mock_data["privkey"].as_str().unwrap(); - PrivKey::from_str(privkey_str).unwrap() - }; + let privkey = mock_data["privkey"] + .as_str() + .and_then(|p| PrivKey::from_str(p).ok()) + .unwrap(); let mut mock_blocks: HashMap = HashMap::new(); for block in mock_data["blocks"].as_sequence_mut().unwrap() { let block_number = block["number"].as_u64().unwrap(); @@ -130,7 +118,7 @@ fn main() { let (key, body) = rx_sub.recv().unwrap(); info!("received: key={}", key); let mut msg = Message::try_from(&body).unwrap(); - // 接受 chain 发送的 authorities_list + // Receive authorities_list from chain if RoutingKey::from(&key) == routing_key!(Chain >> RichStatus) { let rich_status = msg.take_rich_status().unwrap(); let height = rich_status.height + 1; @@ -194,7 +182,6 @@ fn send_block( let quota = tx["quota"].as_u64().unwrap(); let nonce = tx["nonce"].as_u64().unwrap() as u32; let valid_until_block = tx["valid_until_block"].as_u64().unwrap(); - let sender = KeyPair::from_privkey(*privkey).unwrap().address(); info!( "sender={}, contract_address={}", @@ -216,7 +203,7 @@ fn send_block( }) .collect(); - // 构造block + // Build block let (send_data, _block) = BuildBlock::build_block_with_proof( &txs[..], pre_hash, @@ -224,11 +211,8 @@ fn send_block( privkey, GENESIS_TIMESTAMP + height * 3, ); - info!( - "===============send block ({} transactions)===============", - txs.len() - ); - (*sys_time.lock().unwrap()) = time::SystemTime::now(); + info!("send block ({} transactions)", txs.len()); + *sys_time.lock().unwrap() = time::SystemTime::now(); pub_sender .send(( routing_key!(Consensus >> BlockWithProof).into(), diff --git a/tests/chain_performance_by_mq/Cargo.toml b/tests/chain-performance-by-mq/Cargo.toml similarity index 92% rename from tests/chain_performance_by_mq/Cargo.toml rename to tests/chain-performance-by-mq/Cargo.toml index 88ff62a6f..10e4baaae 100644 --- a/tests/chain_performance_by_mq/Cargo.toml +++ b/tests/chain-performance-by-mq/Cargo.toml @@ -1,19 +1,20 @@ [package] -name = "chain_performance_by_mq" +name = "chain-performance-by-mq" version = "0.1.0" authors = ["Cryptape Technologies "] +edition = "2018" [dependencies] serde = "1.0" serde_derive = "1.0" clap = "2" +cita-logger = "0.1.0" libproto = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } rustc-serialize = "0.3" cita-types = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } cita-crypto = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } hashable = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } dotenv = "0.13.0" -logger = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } proof = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } bincode = "0.8.0" cpuprofiler = "0.0.3" diff --git a/tests/chain_performance_by_mq/README.md b/tests/chain-performance-by-mq/README.md similarity index 100% rename from tests/chain_performance_by_mq/README.md rename to tests/chain-performance-by-mq/README.md diff --git a/tests/chain_performance_by_mq/Test.sol b/tests/chain-performance-by-mq/Test.sol similarity index 100% rename from tests/chain_performance_by_mq/Test.sol rename to tests/chain-performance-by-mq/Test.sol diff --git a/tests/chain_performance_by_mq/src/generate_block.rs b/tests/chain-performance-by-mq/src/generate_block.rs similarity index 99% rename from tests/chain_performance_by_mq/src/generate_block.rs rename to tests/chain-performance-by-mq/src/generate_block.rs index 3d24af29c..3a6f0519f 100644 --- a/tests/chain_performance_by_mq/src/generate_block.rs +++ b/tests/chain-performance-by-mq/src/generate_block.rs @@ -15,9 +15,9 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . +use crate::crypto::*; use bincode::{serialize, Infinite}; use cita_types::H256; -use crypto::*; use hashable::Hashable; use libproto::TryInto; use libproto::{Block, BlockWithProof, Message, SignedTransaction, Transaction}; diff --git a/tests/chain_performance_by_mq/src/main.rs b/tests/chain-performance-by-mq/src/main.rs similarity index 95% rename from tests/chain_performance_by_mq/src/main.rs rename to tests/chain-performance-by-mq/src/main.rs index cd2e42e74..e851666a0 100644 --- a/tests/chain_performance_by_mq/src/main.rs +++ b/tests/chain-performance-by-mq/src/main.rs @@ -1,5 +1,5 @@ // CITA -// Copyright 2016-2017 Cryptape Technologies LLC. +// Copyright 2016-2019 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public @@ -15,30 +15,21 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . -extern crate bincode; extern crate cita_crypto as crypto; -extern crate cita_types; -extern crate clap; -extern crate cpuprofiler; -extern crate dotenv; #[macro_use] extern crate libproto; -extern crate hashable; -extern crate proof; -extern crate rustc_serialize; #[macro_use] -extern crate logger; -extern crate pubsub; +extern crate cita_logger as logger; #[macro_use] extern crate serde_derive; mod generate_block; +use crate::crypto::*; +use crate::generate_block::Generateblock; use cita_types::H256; use clap::App; -use crypto::*; -use generate_block::Generateblock; use libproto::router::{MsgType, RoutingKey, SubModules}; use libproto::Message; use libproto::TryFrom; diff --git a/tests/compatibility/check_genesis.py b/tests/compatibility/check_genesis.py index aaade5f04..fc8628e20 100644 --- a/tests/compatibility/check_genesis.py +++ b/tests/compatibility/check_genesis.py @@ -7,7 +7,7 @@ NODE_KEYS = [ '0x98a476f1687bc3d60a2da2adbcba2c46958e61fa2fb4042cd7bc5816a710195b', - '0x0958fc78ca04a68fd52c5622ef2ca3cdb177cce96303c25fe1f487c6436a6dac' + '0xfa669cc5530281d59cb9af15f8c4ce666af51805dc63aaa69995533fb756c150', ] @@ -48,12 +48,16 @@ def check(old, new, check_code): return False # Check the storage storage = old_alloc[addr]['storage'] - for key in storage: + for old_key in storage: + old_value = storage[old_key] + + key = "0x" + old_key[2:].zfill(64) + value = "0x" + old_value[2:].zfill(64) # Ignore the node manager's constructor if key in NODE_KEYS: continue if key not in new_alloc[addr]['storage'] \ - or storage[key] != new_alloc[addr]['storage'][key]: + or value != new_alloc[addr]['storage'][key]: return False return True diff --git a/tests/compatibility/check_genesis.sh b/tests/compatibility/check_genesis.sh index 4f614529d..960b46350 100755 --- a/tests/compatibility/check_genesis.sh +++ b/tests/compatibility/check_genesis.sh @@ -11,7 +11,7 @@ BINARY_DIR=${SOURCE_DIR}/target/install cd ${BINARY_DIR} \ && ./scripts/create_cita_config.py create \ - --super_admin "0x0000000000000000000000000000000000000000" \ + --super_admin "0x4b5ae4567ad5d9fb92bc9afd6a657e6fa13a2523" \ --nodes "127.0.0.1:4000" \ && python3 ${SOURCE_DIR}/tests/compatibility/check_genesis.py \ --genesis test-chain/0/genesis.json \ diff --git a/tests/consensus-mock/Cargo.toml b/tests/consensus-mock/Cargo.toml index 498a2fdca..8e57fad0d 100644 --- a/tests/consensus-mock/Cargo.toml +++ b/tests/consensus-mock/Cargo.toml @@ -2,11 +2,13 @@ name = "consensus-mock" version = "0.1.0" authors = ["Cryptape Technologies "] +edition = "2018" [dependencies] serde = "1.0" serde_derive = "1.0" bincode = "0.8.0" +cita-logger = "0.1.0" libproto = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } hashable = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } clap = "2" @@ -14,7 +16,6 @@ pubsub = { git = "https://github.com/cryptape/cita-common.git", branch = "develo cita-types = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } cita-crypto = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } proof = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } -logger = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } chrono = "0.4.2" [features] diff --git a/tests/consensus-mock/src/main.rs b/tests/consensus-mock/src/main.rs index c2228f1c4..93e3e9a11 100644 --- a/tests/consensus-mock/src/main.rs +++ b/tests/consensus-mock/src/main.rs @@ -1,5 +1,5 @@ // CITA -// Copyright 2016-2018 Cryptape Technologies LLC. +// Copyright 2016-2019 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public @@ -15,25 +15,21 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . -extern crate bincode; -extern crate chrono; extern crate cita_crypto as crypto; #[macro_use] extern crate clap; #[macro_use] extern crate libproto; #[macro_use] -extern crate logger; -extern crate proof; -extern crate pubsub; +extern crate cita_logger as logger; #[macro_use] extern crate serde_derive; extern crate cita_types as types; -extern crate hashable; +use crate::crypto::{CreateKey, KeyPair, PrivKey, Sign, Signature}; +use crate::types::{Address, H256}; use bincode::{serialize, Infinite}; use clap::App; -use crypto::{CreateKey, KeyPair, PrivKey, Sign, Signature}; use hashable::Hashable; use libproto::blockchain::{Block, BlockBody, BlockTxs, BlockWithProof}; use libproto::router::{MsgType, RoutingKey, SubModules}; @@ -46,7 +42,6 @@ use std::collections::HashMap; use std::convert::Into; use std::thread::sleep; use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; -use types::{Address, H256}; pub type PubType = (String, Vec); diff --git a/tests/contracts b/tests/contracts new file mode 160000 index 000000000..3ed3e5ede --- /dev/null +++ b/tests/contracts @@ -0,0 +1 @@ +Subproject commit 3ed3e5ede13bba04bc8c91853584bafd2b230b02 diff --git a/tests/integrate_test/blockNumber.sh b/tests/integrate_test/blockNumber.sh deleted file mode 100755 index ef6c9f0bf..000000000 --- a/tests/integrate_test/blockNumber.sh +++ /dev/null @@ -1,23 +0,0 @@ -#!/bin/bash -set -e -#echo "args: ip port" -IP=$1 -PORT=$2 -if [ ! -n "$IP" ]; then - IP="127.0.0.1" -fi -if [ ! -n "$PORT" ]; then - PORT=1337 -fi -response=$(curl -s -X POST -d '{"jsonrpc":"2.0","method":"blockNumber","params":[],"id":2}' $IP:$PORT) -if [ $? -ne 0 ]; then - exit 1 -fi - -height=$(echo ${response}|jq ".result"|sed 's/\"//g') - -if [ "$height" == null ]; then - exit 1 -fi - -echo $((height)) diff --git a/tests/integrate_test/box_executor_test.sh b/tests/integrate_test/box_executor_test.sh index e03390e2c..5604ed888 100755 --- a/tests/integrate_test/box_executor_test.sh +++ b/tests/integrate_test/box_executor_test.sh @@ -3,76 +3,56 @@ set -e ECONOMICAL_MODEL="0" -if [ -n $1 ] && [ "$1" = "charge" ]; then +if [[ -n "$1" ]] && [ "$1" = "charge" ]; then ECONOMICAL_MODEL="1" fi -if [[ `uname` == 'Darwin' ]] +if [[ $(uname) == 'Darwin' ]] then - SOURCE_DIR=$(realpath $(dirname $0)/../..) + SOURCE_DIR=$(realpath "$(dirname "$0")"/../..) else - SOURCE_DIR=$(readlink -f $(dirname $0)/../..) + SOURCE_DIR=$(readlink -f "$(dirname "$0")"/../..) fi BINARY_DIR=${SOURCE_DIR}/target/install -TESTS_DIR=${SOURCE_DIR}/tests/jsondata/rpc/tests -CHAIN_NAME="mock-chain" -NODE_NAME="${CHAIN_NAME}/0" -NODE_DIR="${BINARY_DIR}/${NODE_NAME}" -TNODE=`echo ${NODE_NAME} | sed 's/\//%2f/g'` -################################################################################ -echo -n "0) prepare ... " -. ${SOURCE_DIR}/tests/integrate_test/util.sh -cd ${BINARY_DIR} -echo "DONE" -################################################################################ -echo -n "1) cleanup ... " -cleanup ${CHAIN_NAME} -echo -n "DONE" - -################################################################################ -echo -n "2) generate config ... " -if [ ! -d "resource" ]; then - mkdir resource -fi - -AUTHORITIES=`cat ${SOURCE_DIR}/tests/interfaces/config/authorities | xargs echo |sed "s/ /,/g"` -${BINARY_DIR}/scripts/create_cita_config.py create \ - --nodes "127.0.0.1:4000,127.0.0.1:4001,127.0.0.1:4002,127.0.0.1:4003" \ - --chain_name ${CHAIN_NAME} \ - --super_admin "0x4b5ae4567ad5d9fb92bc9afd6a657e6fa13a2523" \ - --contract_arguments "SysConfig.economicalModel=${ECONOMICAL_MODEL}" \ - --contract_arguments "SysConfig.chainId=123" \ - --timestamp 1524000000 \ - --authorities ${AUTHORITIES} -echo -n "DONE" - -################################################################################ -echo -n "3) start cita-chain and cita-executor on ${NODE_NAME} ... " -${BINARY_DIR}/bin/cita setup ${NODE_NAME} - -curl -i -u guest:guest -H content-type:application/json -XDELETE \ - http://localhost:15672/api/queues/${TNODE}/consensus > /dev/null - -cd ${NODE_DIR} -${BINARY_DIR}/bin/cita-chain -c chain.toml & -chain_pid=$! -${BINARY_DIR}/bin/cita-executor -c executor.toml & -executor_pid=$! -echo -n "DONE" - -## ################################################################################ -echo -n "4) testing ... " -AMQP_URL=amqp://guest:guest@localhost/${NODE_NAME} \ - timeout 100s ${BINARY_DIR}/bin/box_executor \ - -m ${SOURCE_DIR}/tests/interfaces/config/blockchain.yaml -echo -n "DONE" - -################################################################################ -echo -n "5) stop cita-chain and cita-executor on ${NODE_NAME}" -kill "${chain_pid}" -kill "${executor_pid}" -cleanup ${CHAIN_NAME} -echo -n "PASS" -exit 0 +main() { + echo -n "0) prepare ... " + # shellcheck source=/dev/null + . ${SOURCE_DIR}/tests/integrate_test/util.sh + cd "${BINARY_DIR}" + echo "DONE" + + echo -n "1) generate config ... " + if [ ! -d "resource" ]; then + mkdir resource + fi + + autorities=$(xargs echo < "${SOURCE_DIR}"/tests/interfaces/config/authorities | sed "s/ /,/g") + create_config \ + --contract_arguments "SysConfig.economicalModel=${ECONOMICAL_MODEL}" \ + --contract_arguments "SysConfig.chainId=123" \ + --timestamp 1524000000 \ + --authorities "${autorities}" + echo -n "DONE" + + echo -n "2) start cita-chain and cita-executor on node0 ... " + bin/cita bebop setup "${CHAIN_NAME}"/0 + + tnode=$(echo "${CHAIN_NAME}"/0 | sed 's/\//%2f/g') + curl -i -u guest:guest -H content-type:application/json -XDELETE \ + http://localhost:15672/api/queues/"${tnode}"/consensus > /dev/null + + node_dir="${BINARY_DIR}/${CHAIN_NAME}/0" + bin/cita-chain -c "${node_dir}"/chain.toml & + bin/cita-executor -c "${node_dir}"/executor.toml & + echo -n "DONE" + + echo -n "3) testing ... " + AMQP_URL=amqp://guest:guest@localhost/${CHAIN_NAME}/0 \ + timeout 100s "${BINARY_DIR}"/bin/box_executor \ + -m "${SOURCE_DIR}"/tests/interfaces/config/blockchain.yaml + echo -n "DONE" +} + +main "$@" diff --git a/tests/integrate_test/cita_amend_test.sh b/tests/integrate_test/cita_amend_test.sh index 440fdf17c..d3a5246fa 100755 --- a/tests/integrate_test/cita_amend_test.sh +++ b/tests/integrate_test/cita_amend_test.sh @@ -1,135 +1,113 @@ #!/usr/bin/env bash # Set bash environment -set -e -SOURCE_DIR=$(cd $(dirname "$0")/../..; pwd) -if [[ `uname` == 'Darwin' ]] +if [[ $(uname) == 'Darwin' ]] then - SED="gsed" + SOURCE_DIR=$(realpath "$(dirname "$0")"/../..) else - SED="sed" + SOURCE_DIR=$(readlink -f "$(dirname "$0")"/../..) fi +set -e # Set CITA system environment BINARY_DIR=${SOURCE_DIR}/target/install -CHAIN_NAME="test-chain" -SUPER_ADMIN="0x4b5ae4567ad5d9fb92bc9afd6a657e6fa13a2523" - -################################################################################ -echo "0) Prepare ..." -source "${SOURCE_DIR}/tests/integrate_test/util.sh" -cd "${BINARY_DIR}" -echo "DONE" - -################################################################################ -echo "1) Clean Up ..." -cleanup "${CHAIN_NAME}" -echo "DONE" - -################################################################################ -echo "2) Generate CITA configurations ..." -${BINARY_DIR}/scripts/create_cita_config.py create \ - --nodes "127.0.0.1:4000" \ - --super_admin "${SUPER_ADMIN}" -echo "DONE" - -################################################################################ -echo "3) Run node-0" -${BINARY_DIR}/bin/cita bebop setup ${CHAIN_NAME}/0 > /dev/null -${BINARY_DIR}/bin/cita bebop start ${CHAIN_NAME}/0 trace -echo "DONE" - -sleep 10 - -################################################################################ -echo "4) Check node grow up ..." -echo "chech_height_growth_normal 0 ..." -timeout=`check_height_growth_normal 0 15`||(echo "FAILED" - echo "error msg: ${timeout}" - exit 1) -echo "${timeout}s DONE" - -################################################################################ -echo "5) Amend chain name ..." -cd ${BINARY_DIR}/scripts/txtool/txtool - -curl -X POST --data '{"jsonrpc":"2.0","method":"getMetaData","params":["latest"],"id":1}' 127.0.0.1:1337 \ - | grep "\"chainName\"\:\"test-chain\"" - -python3 make_tx.py \ ---code 0xffffffffffffffffffffffffffffffffff0200000000000000000000000000000000000000000000000000000000000000000027306573742d636861696e00000000000000000000000000000000000000000014 \ ---to 0xffffffffffffffffffffffffffffffffff010002 \ ---value 3 \ ---privkey 0x5f0258a4778057a8a7d97809bd209055b2fbafa654ce7d31ec7191066b9225e6 - -python3 send_tx.py - -sleep 10 - -curl -X POST --data '{"jsonrpc":"2.0","method":"getMetaData","params":["latest"],"id":1}' 127.0.0.1:1337 \ - | grep "\"chainName\"\:\"0est-chain\"" - -################################################################################ -echo "6) Amend abi ..." -cd ${BINARY_DIR}/scripts/txtool/txtool - -# set abi of 0xffffffffffffffffffffffffffffffffff020000 as "amendabitest" -python3 make_tx.py \ ---code 0xffffffffffffffffffffffffffffffffff0200000000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000c616d656e64616269746573740000000000000000000000000000000000000000 \ ---to 0xffffffffffffffffffffffffffffffffff010002 \ ---value 1 \ ---privkey 0x5f0258a4778057a8a7d97809bd209055b2fbafa654ce7d31ec7191066b9225e6 - -python3 send_tx.py - -sleep 10 - -# ascii of "amendabitest" -curl -X POST --data '{"jsonrpc":"2.0","method":"getAbi","params":["0xffffffffffffffffffffffffffffffffff020000", "latest"],"id":1}' 127.0.0.1:1337 \ - | grep "616d656e6461626974657374" - -################################################################################ -echo "7) Amend balance ..." -cd ${BINARY_DIR}/scripts/txtool/txtool - -# set balance of 0xffffffffffffffffffffffffffffffffff020000 as 1234(0x4d2) -python3 make_tx.py \ ---code 0xffffffffffffffffffffffffffffffffff02000000000000000000000000000000000000000000000000000000000000000004d2 \ ---to 0xffffffffffffffffffffffffffffffffff010002 \ ---value 5 \ ---privkey 0x5f0258a4778057a8a7d97809bd209055b2fbafa654ce7d31ec7191066b9225e6 - -python3 send_tx.py - -sleep 10 - -# hex of 1234 -curl -X POST --data '{"jsonrpc":"2.0","method":"getBalance","params":["0xffffffffffffffffffffffffffffffffff020000", "latest"],"id":1}' 127.0.0.1:1337 \ - | grep "0x4d2" - -################################################################################ -echo "8) Amend code ..." -cd ${BINARY_DIR}/scripts/txtool/txtool - -# set code of 0xffffffffffffffffffffffffffffffffff020004 as "deadbeef" -python3 make_tx.py \ ---code 0xffffffffffffffffffffffffffffffffff020004deadbeef \ ---to 0xffffffffffffffffffffffffffffffffff010002 \ ---value 2 \ ---privkey 0x5f0258a4778057a8a7d97809bd209055b2fbafa654ce7d31ec7191066b9225e6 - -python3 send_tx.py - -sleep 10 - -# hex of 1234 -curl -X POST --data '{"jsonrpc":"2.0","method":"getCode","params":["0xffffffffffffffffffffffffffffffffff020004", "latest"],"id":1}' 127.0.0.1:1337 \ - | grep "0xdeadbeef" - -################################################################################ -echo "9) Clean Up ..." -cd ${BINARY_DIR} -${BINARY_DIR}/bin/cita bebop stop ${CHAIN_NAME}/0 -cleanup -echo "DONE" +amend_chain_name() { + python3 make_tx.py \ + --code 0xffffffffffffffffffffffffffffffffff0200000000000000000000000000000000000000000000000000000000000000000027306573742d636861696e00000000000000000000000000000000000000000014 \ + --to 0xffffffffffffffffffffffffffffffffff010002 \ + --value 3 \ + --privkey 0x5f0258a4778057a8a7d97809bd209055b2fbafa654ce7d31ec7191066b9225e6 > /dev/null + + python3 send_tx.py > /dev/null + python3 get_receipt.py --forever true + + curl -X POST --data '{"jsonrpc":"2.0","method":"getMetaData","params":["pending"],"id":1}' 127.0.0.1:1337 \ + | grep "\"chainName\"\:\"0est-chain\"" +} + +amend_abi() { + # set abi of 0xffffffffffffffffffffffffffffffffff020000 as "amendabitest" + python3 make_tx.py \ + --code 0xffffffffffffffffffffffffffffffffff0200000000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000c616d656e64616269746573740000000000000000000000000000000000000000 \ + --to 0xffffffffffffffffffffffffffffffffff010002 \ + --value 1 \ + --privkey 0x5f0258a4778057a8a7d97809bd209055b2fbafa654ce7d31ec7191066b9225e6 > /dev/null + + python3 send_tx.py > /dev/null + python3 get_receipt.py --forever true + + # ascii of "amendabitest" + curl -X POST --data '{"jsonrpc":"2.0","method":"getAbi","params":["0xffffffffffffffffffffffffffffffffff020000", "pending"],"id":1}' 127.0.0.1:1337 \ + | grep "616d656e6461626974657374" +} + +amend_balance() { + # set balance of 0xffffffffffffffffffffffffffffffffff020000 as 1234(0x4d2) + python3 make_tx.py \ + --code 0xffffffffffffffffffffffffffffffffff02000000000000000000000000000000000000000000000000000000000000000004d2 \ + --to 0xffffffffffffffffffffffffffffffffff010002 \ + --value 5 \ + --privkey 0x5f0258a4778057a8a7d97809bd209055b2fbafa654ce7d31ec7191066b9225e6 > /dev/null + + python3 send_tx.py > /dev/null + python3 get_receipt.py --forever true + + # hex of 1234 + curl -X POST --data '{"jsonrpc":"2.0","method":"getBalance","params":["0xffffffffffffffffffffffffffffffffff020000", "pending"],"id":1}' 127.0.0.1:1337 \ + | grep "0x4d2" +} + +amend_code() { + # set code of 0xffffffffffffffffffffffffffffffffff020004 as "deadbeef" + python3 make_tx.py \ + --code 0xffffffffffffffffffffffffffffffffff020004deadbeef \ + --to 0xffffffffffffffffffffffffffffffffff010002 \ + --value 2 \ + --privkey 0x5f0258a4778057a8a7d97809bd209055b2fbafa654ce7d31ec7191066b9225e6 > /dev/null + + python3 send_tx.py > /dev/null + python3 get_receipt.py --forever true + + # hex of 1234 + curl -X POST --data '{"jsonrpc":"2.0","method":"getCode","params":["0xffffffffffffffffffffffffffffffffff020004", "pending"],"id":1}' 127.0.0.1:1337 \ + | grep "0xdeadbeef" +} + +main() { + echo "0) Prepare ..." + # shellcheck source=/dev/null + source "${SOURCE_DIR}/tests/integrate_test/util.sh" + cd "${BINARY_DIR}" + echo "DONE" + + echo "1) Generate configurations ..." + create_config + echo "DONE" + + echo "2) Run nodes" + start_nodes + echo "DONE" + + echo "3) Check node grow up ..." + timeout=$(check_height_growth_normal 0 30) || (echo "FAILED" + echo "error msg: ${timeout}" + exit 1) + echo "${timeout}s DONE" + + cd "${BINARY_DIR}"/scripts/txtool/txtool + echo "4) Amend chain name ..." + amend_chain_name + echo "DONE" + echo "5) Amend abi ..." + amend_abi + echo "DONE" + echo "6) Amend balance ..." + amend_balance + echo "DONE" + echo "7) Amend code ..." + amend_code + echo "DONE" +} + +main "$@" diff --git a/tests/integrate_test/cita_basic.sh b/tests/integrate_test/cita_basic.sh index f9dd6e7bd..646eedd6e 100755 --- a/tests/integrate_test/cita_basic.sh +++ b/tests/integrate_test/cita_basic.sh @@ -1,130 +1,88 @@ #!/bin/bash -set -e -if [[ `uname` == 'Darwin' ]] +set -e +if [[ $(uname) == 'Darwin' ]] then - SOURCE_DIR=$(realpath $(dirname $0)/../..) + SOURCE_DIR=$(realpath "$(dirname "$0")"/../..) else - SOURCE_DIR=$(readlink -f $(dirname $0)/../..) + SOURCE_DIR=$(readlink -f "$(dirname "$0")"/../..) fi BINARY_DIR=${SOURCE_DIR}/target/install - -################################################################################ -echo -n "0) prepare ... " -. ${SOURCE_DIR}/tests/integrate_test/util.sh -cd ${BINARY_DIR} -echo "DONE" - -################################################################################ -echo -n "1) cleanup ... " -cleanup -echo "DONE" - -################################################################################ -echo -n "2) generate config ... " -./scripts/create_cita_config.py create \ - --chain_name "node" \ - --super_admin "0x4b5ae4567ad5d9fb92bc9afd6a657e6fa13a2523" \ - --nodes "127.0.0.1:4000,127.0.0.1:4001,127.0.0.1:4002,127.0.0.1:4003" \ - > /dev/null 2>&1 -echo "DONE" - -################################################################################ -echo -n "3) start nodes ... " -for i in {0..3} ; do - bin/cita bebop setup node/$i > /dev/null -done -for i in {0..3} ; do - bin/cita bebop start node/$i trace > /dev/null & -done -echo "DONE" - -sleep 60 - -################################################################################ -echo -n "4) check height growth normal ... " -timeout=$(check_height_growth_normal 0 15)||(echo "FAILED" - echo "error msg: ${timeout}" - exit 1) -echo "${timeout}s DONE" - -################################################################################ -echo -n "5) stop node3, check height growth ... " -bin/cita bebop stop node/3 > /dev/null -timeout=$(check_height_growth_normal 0 15) || (echo "FAILED" - echo "error msg: ${timeout}" - exit 1) -echo "${timeout}s DONE" - -################################################################################ -echo -n "6) stop node2, check height stopped ... " -bin/cita bebop stop node/2 > /dev/null -timeout=$(check_height_stopped 0 27) || (echo "FAILED" +IP="127.0.0.1" +PORT="1337" + +main() { + echo -n "0) prepare ... " + # shellcheck source=/dev/null + . "${SOURCE_DIR}"/tests/integrate_test/util.sh + cd "${BINARY_DIR}" + echo "DONE" + + echo -n "1) generate config ... " + create_config "$1" + echo "DONE" + + echo -n "2) start nodes ... " + start_nodes + echo "DONE" + + echo -n "3) check height growth normal ... " + timeout=$(check_height_growth_normal 0 60) || (echo "FAILED" + echo "error msg: ${timeout}" + exit 1) + echo "${timeout}s DONE" + + echo -n "4) check JSON-RPC CORS ... " + # Check JSON-RPC CORS: Access-Control-Allow-Origin should be existed. + curl -i -X POST -d '{"jsonrpc":"2.0","method":"peerCount","params":[],"id":2}' "$IP":"$PORT" 2>/dev/null | grep -ic "^access-control-allow-origin: " + echo "DONE" + + echo -n "5) stop node3, check height growth ... " + bin/cita bebop stop $CHAIN_NAME/3 2>&1 + timeout=$(check_height_growth_normal 0 60) || (echo "FAILED" + echo "error msg: ${timeout}" + exit 1) + echo "${timeout}s DONE" + + echo -n "6) stop node2, check height stopped ... " + bin/cita bebop stop $CHAIN_NAME/2 2>&1 + timeout=$(check_height_stopped 0 30) || (echo "FAILED" + echo "error msg: ${timeout}" + exit 1) + echo "${timeout}s DONE" + + echo -n "7) start node2, check height growth ... " + bin/cita bebop start $CHAIN_NAME/2 2>&1 + timeout=$(check_height_growth_normal 0 60) || (echo "FAILED" + echo "error msg: ${timeout}" + exit 1) + echo "${timeout}s DONE" + + echo -n "8) start node3, check synch ... " + bin/cita bebop start $CHAIN_NAME/3 2>&1 + timeout=$(check_height_sync 3 0) || (echo "FAILED" echo "error msg: ${timeout}" exit 1) -echo "${timeout}s DONE" - -################################################################################ -echo -n "7) start node2, check height growth ... " -bin/cita bebop start node/2 trace > /dev/null & -sleep 24 #wait for recovery from stop -timeout=$(check_height_growth_normal 0 15) || (echo "FAILED" - echo "error msg: ${timeout}" - exit 1) -echo "${timeout}s DONE" - -################################################################################ -echo -n "8) start node3, check synch ... " -node0_height=$(get_height 0) - -if [ $? -ne 0 ] ; then - echo "failed to get_height: ${node0_height}" - exit 1 -fi -bin/cita bebop start node/3 trace > /dev/null & -timeout=$(check_height_sync 3 0) || (echo "FAILED" - echo "error msg: ${timeout}" - exit 1) -echo "${timeout}s DONE" - -################################################################################ -echo -n "9) stop all nodes, check height changed after restart ... " -before_height=$(get_height 0) -if [ $? -ne 0 ] ; then - echo "failed to get_height: ${before_height}" - exit 1 -fi -for i in {0..3}; do - bin/cita bebop stop node/$i > /dev/null -done -# sleep 1 # TODO: change to this value will produce very different result -for i in {0..3}; do - bin/cita bebop start node/$i trace > /dev/null & -done - -timeout=$(check_height_growth_normal 0 300) || (echo "FAILED" - echo "error msg: ${timeout}" - exit 1) -after_height=$(get_height 0)|| (echo "failed to get_height: ${after_height}" - exit 1) -if [ $after_height -le $before_height ]; then - echo "FAILED" - echo "before:${before_height} after:${after_height}" - exit 1 -fi -echo "${timeout}s DONE" - -################################################################################ -echo -n "10) stop&clean node3, check height synch after restart ... " -bin/cita bebop stop node/3 > /dev/null -bin/cita bebop clean node/3 > /dev/null -bin/cita bebop start node/3 trace > /dev/null & -timeout=$(check_height_sync 3 0) || (echo "FAILED" - echo "error msg: ${timeout}" - exit 1) -echo "${timeout}s DONE" + echo "${timeout}s DONE" + + echo -n "9) stop all nodes, check height changed after restart ... " + for i in {0..3}; do + bin/cita bebop restart $CHAIN_NAME/$i 2>&1 + done + + timeout=$(check_height_growth_normal 0 300) || (echo "FAILED" + echo "error msg: ${timeout}" + exit 1) + echo "${timeout}s DONE" + + echo -n "10) stop&clean node3, check height synch after restart ... " + bin/cita bebop stop $CHAIN_NAME/3 2>&1 + bin/cita bebop clean $CHAIN_NAME/3 2>&1 + bin/cita bebop start $CHAIN_NAME/3 2>&1 + timeout=$(check_height_sync 3 0) || (echo "FAILED" + echo "error msg: ${timeout}" + exit 1) + echo "${timeout}s DONE" +} -################################################################################ -echo -n "11) cleanup ... " -cleanup -echo "DONE" +main "$@" diff --git a/tests/integrate_test/cita_bft.sh b/tests/integrate_test/cita_bft.sh deleted file mode 100755 index e9c114a7d..000000000 --- a/tests/integrate_test/cita_bft.sh +++ /dev/null @@ -1,272 +0,0 @@ -#!/bin/bash -set +e -tx_num=0 -pid=0 -CUR_PATH=$(cd `dirname $0`; pwd) -sudo rabbitmqctl stop_app -sudo rabbitmqctl reset -sudo rabbitmqctl start_app -cd ${CUR_PATH}/../../admintool/ -./scripts/create_cita_config.py create \ - --chain_name "node" \ - --super_admin "0x4b5ae4567ad5d9fb92bc9afd6a657e6fa13a2523" \ - --nodes "127.0.0.1:4000,127.0.0.1:4001,127.0.0.1:4002,127.0.0.1:4003" - -setup_node() { - id=$1 - cd ${CUR_PATH}/../../admintool/release/node/${id} - ./cita setup ${id} -} - -start_node() { - id=$1 - cd ${CUR_PATH}/../../admintool/release/node/${id} - ./cita start ${id} -} - -stop_node() { - id=$1 - cd ${CUR_PATH}/../../admintool/release/node/${id} - ./cita stop ${id} -} - -stop_all () { - stop_node 0 - stop_node 1 - stop_node 2 - stop_node 3 - stop_consensus 3 -} - -delete_pid_file() -{ - id=$1 - cd ${CUR_PATH}/../../admintool/release/node/${id} - if [ -f "consensus_cita_bft.pid" ]; then - rm -rf consensus_cita_bft.pid - fi -} - -stop_consensus_cmd() -{ - id=$1 - cd ${CUR_PATH}/../../admintool/release/node/${id} - - if [ ! -f "consensus_cita_bft.pid" ]; then - consensus_cita_bft_pid=$(tail -3 .pid | head -1) -# kill -9 $consensus_cita_bft_pid - else - consensus_cita_bft_pid=$(cat consensus_cita_bft.pid) -# kill -9 $consensus_cita_bft_pid - rm -rf consensus_cita_bft.pid - fi - - flag=$(ps -ef | grep $consensus_cita_bft_pid | grep -v grep | wc -l) - if [ $flag -gt 0 ]; then - kill -9 $consensus_cita_bft_pid - fi -} - -stop_consensus() -{ -# killall consensus_cita_bft - for((i=0; i<=$1;i++)) - do - stop_consensus_cmd $i - done -} - -start_consensus_cmd() -{ - id=$1 - cd ${CUR_PATH}/../../admintool/release/node/${id} - RUST_LOG=consensus_cita_bft bin/consensus_cita_bft -c consensus.json >log/node/${id}.consensus 2>&1 & - echo $! > consensus_cita_bft.pid -} - -start_consensus() -{ - while : - do - process=$(ps -ef | grep "bin/consensus_cita_bft" | grep -v grep | wc -l) - if [ $process -lt 4 ]; then - break - fi - done - for((i=0; i<=$1;i++)) - do - start_consensus_cmd $i - sleep 1 - done -} - -start_all () { - start_node 0 - start_node 1 - start_node 2 - start_node 3 -} - -get_height(){ - h=`${CUR_PATH}/blockNumber.sh` - h=$(echo $h | sed 's/\"//g') - echo $((h)) -} - -check_height_change () { - echo "check block height" - old_height=$(get_height) - echo "block height $old_height" - sleep 30 - new_height=$(get_height) - echo "block height $new_height" - if [ $new_height -eq $old_height ]; then - stop_all - exit 1 - fi -} - -delete_log() -{ - cd ${CUR_PATH}/../wrk_benchmark_test/ - if [ -f "result.log" ]; then - rm -rf result.log - fi -} - -delete_tc() -{ - flag=$(tc -s qdisc show dev lo | grep "qdisc prio" | wc -l) - if [ $flag -eq 1 ]; then - sudo tc qdisc del dev lo root - fi -} - -stop_trans() -{ - flag=$(ps -ef | grep benchmark.sh | grep -v grep | wc -l) - if [ $flag -eq 1 ]; then - killall benchmark.sh - fi - flag=$(ps -ef | grep make_transaction | grep -v grep | wc -l) - if [ $flag -eq 1 ]; then - killall make_transaction - fi -} - -start_send_tx() -{ - stop_trans - cd ${CUR_PATH}/../wrk_benchmark_test/ -# if [ ! -f "result.log" ]; then - if [ $1 -eq 0 ]; then - ./benchmark.sh - err=`echo $?` - if [ $err -ne 0 ]; then - echo "create account error!" - delete_tc - stop_all - #stop_consensus - stop_trans - exit 1 - fi - fi - - sleep 10 - - #./setPortDelay.sh 4000 1000 10 > /dev/null & - pid=$! - ./benchmark.sh config_call.json 2 > result.log & - while : - do - - if [ ! -f "result.log" ]; then - continue - fi - flag=$(grep "write successfully\.\[" result.log | wc -l) - err=`echo $?` - if [ $err -ne 0 ]; then - continue - fi - - if [ $flag -eq 1 ]; then - #stop_consensus - stop_consensus $2 - sleep 2 - break - fi - done -} - -send_tx_over() -{ - cd ${CUR_PATH}/../wrk_benchmark_test/ - while : - do - if [ ! -f "result.log" ]; then - continue - fi - - flag=$(grep "send tx num" result.log | wc -l) - err=`echo $?` - if [ $err -ne 0 ]; then - continue - fi - if [ $flag -eq 1 ]; then - tx_num=$(grep "write successfully\.\[" result.log | grep -o "[[:digit:]]*") - flag=$(grep "send tx num" result.log | grep "$tx_num" | wc -l) - if [ $flag -eq 0 ]; then - echo "###send_tx_over exit [$tx_num]" - delete_tc - stop_all - stop_trans - exit 1 - fi - break - fi - done -} - - -echo "###start nodes..." -(setup_node 0;start_node 0) & -(setup_node 1;start_node 1) & -(setup_node 2;start_node 2) & -(setup_node 3;start_node 3) & - -echo "###wait for start..." -sleep 80 - -check_height_change - -stop_num=0 - -echo "###start_test_consensus_cita_bft" -delete_pid_file 0 -delete_pid_file 1 -delete_pid_file 2 -delete_pid_file 3 -run=0 -while : -do - if [ $stop_num -gt 3 ]; then - break - fi - sleep 30 - echo "###start consensus_cita_bft process $stop_num" - delete_log - start_send_tx $run $stop_num & - start_consensus $stop_num & - send_tx_over - run=1 - echo "###end consensus_cita_bft process $stop_num" - stop_num=$[$stop_num+1] -done - -delete_tc -sleep 30 -check_height_change -stop_all -stop_trans -echo "###Test OK" -exit 0 diff --git a/tests/integrate_test/cita_bft_resend.sh b/tests/integrate_test/cita_bft_resend.sh index 544a533fc..30f673ade 100755 --- a/tests/integrate_test/cita_bft_resend.sh +++ b/tests/integrate_test/cita_bft_resend.sh @@ -2,81 +2,69 @@ # Set bash environment set -e -if [[ `uname` == 'Darwin' ]] +if [[ $(uname) == 'Darwin' ]] then - SOURCE_DIR=$(realpath $(dirname $0)/../..) - SED="gsed" + SOURCE_DIR=$(realpath "$(dirname "$0")"/../..) else - SOURCE_DIR=$(readlink -f $(dirname $0)/../..) - SED="sed" + SOURCE_DIR=$(readlink -f "$(dirname "$0")"/../..) fi - # Set CITA system environment BINARY_DIR=${SOURCE_DIR}/target/install -CHAIN_NAME="mock-chain" SUPER_ADMIN="0x4b5ae4567ad5d9fb92bc9afd6a657e6fa13a2523" -################################################################################ -echo "0) Prepare ..." -source "${SOURCE_DIR}/tests/integrate_test/util.sh" -cd "${BINARY_DIR}" -echo "DONE" - -################################################################################ -echo "1) Clean Up ..." -cleanup "${CHAIN_NAME}" -echo "DONE" - -################################################################################ -echo "2) Generate CITA configurations ..." -${BINARY_DIR}/scripts/create_cita_config.py create \ - --nodes "127.0.0.1:4000" \ - --super_admin "${SUPER_ADMIN}" \ - --chain_name "${CHAIN_NAME}" \ - --timestamp 1524000000 -echo "DONE" +main() { + echo "0) Prepare ..." + # shellcheck source=/dev/null + source "${SOURCE_DIR}/tests/integrate_test/util.sh" + cd "${BINARY_DIR}" + echo "DONE" -################################################################################ -echo "3) Start CITA components manually" -${BINARY_DIR}/bin/cita bebop setup ${CHAIN_NAME}/0 -${BINARY_DIR}/bin/cita bebop start ${CHAIN_NAME}/0 trace -sleep 3 -${BINARY_DIR}/bin/cita bebop stop ${CHAIN_NAME}/0 + echo "1) Generate CITA configurations ..." + scripts/create_cita_config.py create \ + --nodes "127.0.0.1:4000" \ + --super_admin "${SUPER_ADMIN}" \ + --chain_name "${CHAIN_NAME}" \ + --timestamp 1524000000 + echo "DONE" -cd ${CHAIN_NAME}/0 -${BINARY_DIR}/bin/cita-auth -c auth.toml & auth_pid=$! -${BINARY_DIR}/bin/cita-bft -c consensus.toml -p privkey & bft_pid=$! -${BINARY_DIR}/bin/cita-chain -c chain.toml & chain_pid=$i -${BINARY_DIR}/bin/cita-executor -c executor.toml & executor_pid=$! -${BINARY_DIR}/bin/cita-jsonrpc -c jsonrpc.toml & jsonrpc_pid=$! -${BINARY_DIR}/bin/cita-network -c network.toml & network_pid=$! -wait_timeout=30 -timeout=`check_height_growth_normal 0 $wait_timeout` || (echo "FAILED" - echo "error msg: ${timeout}" - exit 1) + echo "2) Start CITA components manually" + bin/cita bebop setup "${CHAIN_NAME}"/0 + bin/cita bebop start "${CHAIN_NAME}"/0 + sleep 3 + bin/cita bebop stop "${CHAIN_NAME}"/0 -################################################################################ -echo "4) Kill cita-executor and cita-chain, and rm -rf data/statedb" -jobs -l | grep cita-executor | awk '{print $2}' | xargs -I {} kill {} -sleep 3 -jobs -l | grep cita-chai | awk '{print $2}' | xargs -I {} kill {} -rm -rf data/statedb -sleep 10 + cd "${CHAIN_NAME}"/0 + "${BINARY_DIR}"/bin/cita-auth -c auth.toml & auth_pid=$! + "${BINARY_DIR}"/bin/cita-bft -c consensus.toml -p privkey & bft_pid=$! + "${BINARY_DIR}"/bin/cita-chain -c chain.toml & chain_pid=$! + "${BINARY_DIR}"/bin/cita-executor -c executor.toml & executor_pid=$! + "${BINARY_DIR}"/bin/cita-jsonrpc -c jsonrpc.toml & jsonrpc_pid=$! + "${BINARY_DIR}"/bin/cita-network -c network.toml & network_pid=$! + wait_timeout=30 + timeout=$(check_height_growth_normal 0 $wait_timeout) || (echo "FAILED" + echo "error msg: ${timeout}" + exit 1) + cd "${BINARY_DIR}" + echo "DONE" -################################################################################ -echo "5) Restart CITA" -kill ${auth_pid} ${bft_pid} ${jsonrpc_pid} ${network_pid} + echo "3) Kill cita-executor and cita-chain, and rm -rf data/statedb" + kill ${executor_pid} + sleep 3 + kill ${chain_pid} + rm -rf "${CHAIN_NAME}"/0/data/statedb + sleep 10 + echo "DONE" -cd ${BINARY_DIR} -${BINARY_DIR}/bin/cita bebop start ${CHAIN_NAME}/0 trace + echo "4) Restart CITA" + kill ${auth_pid} ${bft_pid} ${jsonrpc_pid} ${network_pid} -wait_timeout=30 -timeout=`check_height_growth_normal 0 $wait_timeout` || (echo "FAILED" - echo "error msg: ${timeout}" - exit 1) + bin/cita bebop start "${CHAIN_NAME}"/0 + wait_timeout=30 + timeout=$(check_height_growth_normal 0 $wait_timeout) || (echo "FAILED" + echo "error msg: ${timeout}" + exit 1) + echo "DONE" +} -################################################################################ -echo "6) Cleanup" -cleanup "${CHAIN_NAME}" -echo "DONE" +main "$@" diff --git a/tests/integrate_test/cita_byzantinetest.sh b/tests/integrate_test/cita_byzantinetest.sh index bd87b8e52..40c9c5e82 100755 --- a/tests/integrate_test/cita_byzantinetest.sh +++ b/tests/integrate_test/cita_byzantinetest.sh @@ -2,131 +2,108 @@ set -e ECONOMICAL_MODEL="0" -if [ -n $1 ] && [ "$1" = "charge" ]; then +if [[ -n "$1" ]] && [ "$1" = "charge" ]; then ECONOMICAL_MODEL="1" fi -if [[ `uname` == 'Darwin' ]] +if [[ $(uname) == 'Darwin' ]] then - SOURCE_DIR=$(realpath $(dirname $0)/../..) + SOURCE_DIR=$(realpath "$(dirname "$0")"/../..) else - SOURCE_DIR=$(readlink -f $(dirname $0)/../..) + SOURCE_DIR=$(readlink -f "$(dirname "$0")"/../..) fi -BINARY_DIR=${SOURCE_DIR}/target/install - -################################################################################ -echo -n "0) prepare ... " -. ${SOURCE_DIR}/tests/integrate_test/util.sh -cd ${BINARY_DIR} -echo "DONE" - -################################################################################ -echo -n "1) cleanup ... " -cleanup -echo "DONE" -################################################################################ +BINARY_DIR=${SOURCE_DIR}/target/install -echo -n "2) generate config ... " -./scripts/create_cita_config.py create \ - --chain_name "node" \ - --super_admin "0x4b5ae4567ad5d9fb92bc9afd6a657e6fa13a2523" \ - --nodes "127.0.0.1:4000,127.0.0.1:4001,127.0.0.1:4002,127.0.0.1:4003" \ - --contract_arguments "SysConfig.economicalModel=${ECONOMICAL_MODEL}" \ - > /dev/null 2>&1 -echo "DONE" +main() { + echo -n "0) prepare ... " + # shellcheck source=/dev/null + . ${SOURCE_DIR}/tests/integrate_test/util.sh + cd "${BINARY_DIR}" + echo "DONE" -################################################################################ -echo -n "3) start nodes ... " -for i in {0..3} ; do - bin/cita bebop setup node/$i > /dev/null -done -for i in {0..3} ; do - bin/cita bebop start node/$i debug > /dev/null & -done -echo "DONE" + echo -n "1) generate config ... " + create_config --contract_arguments "SysConfig.economicalModel=${ECONOMICAL_MODEL}" + echo "DONE" -################################################################################ -echo -n "4) check alive ... " -timeout=$(check_height_growth_normal 0 60) || (echo "FAILED" - echo "failed to check_height_growth 0: ${timeout}" - exit 1) -echo "${timeout}s DONE" + echo -n "2) start nodes ... " + start_nodes + echo "DONE" -################################################################################ -echo "5) set delay at one nodes, , output time used for produce block growth" -delay=10000 -for i in {0..3}; do - id=$(($i%4)) - echo -n "set delay at node ${id} ... " - refer=$((($i+1)%4)) - port=$((4000+${id})) - set_delay_at_port ${port} ${delay} - timeout1=$(check_height_growth_normal ${refer} 60) ||(echo "FAILED" - echo "failed to check_height_growth: ${timeout1}" - exit 1) - unset_delay_at_port ${port} - #synch for node ${id} - timeout=$(check_height_sync ${id} ${refer}) ||(echo "FAILED" - echo "failed to check_height_sync: ${timeout}" + echo -n "3) check alive ... " + timeout=$(check_height_growth_normal 0 60) || (echo "FAILED" + echo "failed to check_height_growth 0: ${timeout}" exit 1) - echo "${timeout1}s DONE" -done + echo "${timeout}s DONE" -################################################################################ -echo "6) set delay at two nodes, output time used for produce block" -delay=3000 -for i in {0..3}; do - id1=$i - id2=$((($i+1)%4)) - refer=$((($i+2)%4)) - echo -n "set delay=${delay} at nodes ${id1},${id2} ... " - set_delay_at_port $((4000+${id1})) ${delay} - set_delay_at_port $((4000+${id2})) ${delay} + echo "4) set delay at one nodes, , output time used for produce block growth" + delay=10000 + for i in {0..3}; do + id=$((i%4)) + echo -n "set delay at node ${id} ... " + refer=$(((i+1)%4)) + port=$((4000+id)) + set_delay_at_port ${port} ${delay} + timeout1=$(check_height_growth_normal ${refer} 60) ||(echo "FAILED" + echo "failed to check_height_growth: ${timeout1}" + exit 1) + unset_delay_at_port ${port} + #synch for node ${id} + timeout=$(check_height_sync ${id} ${refer}) ||(echo "FAILED" + echo "failed to check_height_sync: ${timeout}" + exit 1) + echo "${timeout1}s DONE" + done - timeout1=$(check_height_growth_normal ${refer} 100) ||(echo "FAILED" - echo "failed to check_height_growth ${refer}: ${timeout1}" - exit 1) - unset_delay_at_port $((4000+${id1})) - unset_delay_at_port $((4000+${id2})) - sleep 3 - timeout=$(check_height_growth_normal ${refer} 100) ||(echo "FAILED" - echo "failed to check_height_growth ${refer}: ${timeout}" - exit 1) - #synch for node id1, id2 - timeout=$(check_height_sync ${id1} ${refer}) ||(echo "FAILED" - echo "failed to check_height_sync ${id1}: ${timeout}" - exit 1) - timeout=$(check_height_sync ${id2} ${refer}) ||(echo "FAILED" - echo "failed to check_height_sync ${id2}: ${timeout}" - exit 1) - echo "${timeout1}s DONE" -done + echo "5) set delay at two nodes, output time used for produce block" + delay=3000 + for i in {0..3}; do + id1=$i + id2=$(((i+1)%4)) + refer=$(((i+2)%4)) + echo -n "set delay=${delay} at nodes ${id1},${id2} ... " + set_delay_at_port $((4000+id1)) ${delay} + set_delay_at_port $((4000+id2)) ${delay} -################################################################################ -echo "7) set delay at all nodes, output time used for produce block" -for i in {0..6}; do - delay=$((i*400)) - timeout=$(check_height_growth_normal 0 60) ||(echo "FAILED" - echo "failed to check_height_growth: ${timeout}" - exit 1) - echo -n "set delay=${delay} ... " - for node in {0..3} ; do - set_delay_at_port $((4000+${node})) ${delay} + timeout1=$(check_height_growth_normal ${refer} 100) ||(echo "FAILED" + echo "failed to check_height_growth ${refer}: ${timeout1}" + exit 1) + unset_delay_at_port $((4000+id1)) + unset_delay_at_port $((4000+id2)) + sleep 3 + timeout=$(check_height_growth_normal ${refer} 100) ||(echo "FAILED" + echo "failed to check_height_growth ${refer}: ${timeout}" + exit 1) + #synch for node id1, id2 + timeout=$(check_height_sync ${id1} ${refer}) ||(echo "FAILED" + echo "failed to check_height_sync ${id1}: ${timeout}" + exit 1) + timeout=$(check_height_sync ${id2} ${refer}) ||(echo "FAILED" + echo "failed to check_height_sync ${id2}: ${timeout}" + exit 1) + echo "${timeout1}s DONE" done - timeout=$(check_height_growth_normal 0 60) ||(echo "FAILED" - echo "failed to check_height_growth: ${timeout}" - exit 1) - for node in {0..3} ; do - unset_delay_at_port $((4000+${node})) + + echo "6) set delay at all nodes, output time used for produce block" + for i in {0..6}; do + delay=$((i*400)) + timeout=$(check_height_growth_normal 0 60) ||(echo "FAILED" + echo "failed to check_height_growth: ${timeout}" + exit 1) + echo -n "set delay=${delay} ... " + for node in {0..3} ; do + set_delay_at_port $((4000+node)) ${delay} + done + timeout=$(check_height_growth_normal 0 60) ||(echo "FAILED" + echo "failed to check_height_growth: ${timeout}" + exit 1) + for node in {0..3} ; do + unset_delay_at_port $((4000+node)) + done + sleep 4 + echo "${timeout}s DONE" done - sleep 4 - echo "${timeout}s DONE" -done +} -echo "DONE" -echo "11) cleanup" -cleanup -echo "DONE" -exit 0 +main "$@" diff --git a/tests/integrate_test/cita_charge_mode.sh b/tests/integrate_test/cita_charge_mode.sh index 8e887a740..804f15411 100755 --- a/tests/integrate_test/cita_charge_mode.sh +++ b/tests/integrate_test/cita_charge_mode.sh @@ -1,130 +1,100 @@ #!/bin/bash set -e -if [[ `uname` == 'Darwin' ]] +if [[ $(uname) == 'Darwin' ]] then - SOURCE_DIR=$(realpath $(dirname $0)/../..) + SOURCE_DIR=$(realpath "$(dirname "$0")"/../..) else - SOURCE_DIR=$(readlink -f $(dirname $0)/../..) + SOURCE_DIR=$(readlink -f "$(dirname "$0")"/../..) fi BINARY_DIR=${SOURCE_DIR}/target/install -################################################################################ -echo -n "0) prepare ... " -. ${SOURCE_DIR}/tests/integrate_test/util.sh -cd ${BINARY_DIR} -echo "DONE" - -################################################################################ -echo -n "1) cleanup ... " -cleanup -echo "DONE" - -################################################################################ -echo -n "2) generate config ... " -./scripts/create_cita_config.py \ - create \ - --chain_name "node" \ - --super_admin "0x4b5ae4567ad5d9fb92bc9afd6a657e6fa13a2523" \ - --nodes "127.0.0.1:4000,127.0.0.1:4001,127.0.0.1:4002,127.0.0.1:4003" \ - --contract_arguments "SysConfig.checkFeeBackPlatform=true" \ - --contract_arguments "SysConfig.economicalModel=1" \ - --contract_arguments "VersionManager.version=0" \ - --contract_arguments "PriceManager.quotaPrice=1000000" \ - --contract_arguments "SysConfig.chainOwner=0x36a60d575b0dee0423abb6a57dbc6ca60bf47545" > /dev/null 2>&1 -echo "DONE" - -################################################################################ -echo -n "3) start nodes ... " -for i in {0..3} ; do - ./bin/cita bebop setup node/$i > /dev/null -done -for i in {0..3} ; do - ./bin/cita bebop start node/$i trace > /dev/null & -done -echo "DONE" - -################################################################################ -echo -n "4) check alive ... " -timeout=$(check_height_growth_normal 0 60) || (echo "FAILED" - echo "failed to check_height_growth 0: ${timeout}" - exit 1) -echo "${timeout}s DONE" - -################################################################################ -echo -n "5) Run fee back tests ... " -cd ./scripts/txtool/txtool -python3 ${SOURCE_DIR}/tests/integrate_test/test_fee_back.py --version=0 -cd ../../.. -echo "DONE" - -################################################################################ -echo -n "6) Run charge mode tests ... " -echo "" - -NODE_0_PRIVKEY=`cat ./node/0/privkey` -NODE_1_PRIVKEY=`cat ./node/1/privkey` -NODE_2_PRIVKEY=`cat ./node/2/privkey` -NODE_3_PRIVKEY=`cat ./node/3/privkey` -cd ./scripts/txtool/txtool -python3 ${SOURCE_DIR}/tests/integrate_test/test_charge_mode.py \ - --miner-privkeys \ - ${NODE_0_PRIVKEY} \ - ${NODE_0_PRIVKEY} \ - ${NODE_0_PRIVKEY} \ - ${NODE_0_PRIVKEY} \ - --version=0 -cd ../../.. -echo "DONE" - -################################################################################ -echo -n "7) Update to chainIDV1 ... " -cd ./scripts/txtool/txtool -python3 ${SOURCE_DIR}/tests/integrate_test/update_version.py --version=0 -cd ../../.. -echo "DONE" - -################################################################################ -echo -n "8) check alive ... " -timeout=$(check_height_growth_normal 0 60) || (echo "FAILED" - echo "failed to check_height_growth 0: ${timeout}" - exit 1) -echo "${timeout}s DONE" - -################################################################################ -echo -n "9) Run fee back tests in v1 ... " -cd ./scripts/txtool/txtool -python3 ${SOURCE_DIR}/tests/integrate_test/test_fee_back.py --version=1 -cd ../../.. -echo "DONE" - -################################################################################ -echo -n "10) Run charge mode tests in v1 ... " -echo "" - -NODE_0_PRIVKEY=`cat ./node/0/privkey` -NODE_1_PRIVKEY=`cat ./node/1/privkey` -NODE_2_PRIVKEY=`cat ./node/2/privkey` -NODE_3_PRIVKEY=`cat ./node/3/privkey` -cd ./scripts/txtool/txtool -python3 ${SOURCE_DIR}/tests/integrate_test/test_charge_mode.py \ - --miner-privkeys \ - ${NODE_0_PRIVKEY} \ - ${NODE_0_PRIVKEY} \ - ${NODE_0_PRIVKEY} \ - ${NODE_0_PRIVKEY} \ - --version 1 -cd ../../.. -echo "DONE" - -################################################################################ -echo -n "11) stop nodes ... " -for i in {0..3} ; do - ./bin/cita bebop stop node/$i > /dev/null -done -echo "DONE" - -################################################################################ -echo -n "11) cleanup ... " -cleanup -echo "DONE" +test_charge_mode() { + local version=$1 + local node_0_privkey + local node_1_privkey + local node_2_privkey + local node_3_privkey + node_0_privkey=$(cat ./"$CHAIN_NAME"/0/privkey) + node_1_privkey=$(cat ./"$CHAIN_NAME"/1/privkey) + node_2_privkey=$(cat ./"$CHAIN_NAME"/2/privkey) + node_3_privkey=$(cat ./"$CHAIN_NAME"/3/privkey) + cd ./scripts/txtool/txtool + python3 "${SOURCE_DIR}"/tests/integrate_test/test_charge_mode.py \ + --miner-privkeys \ + "${node_0_privkey}" \ + "${node_1_privkey}" \ + "${node_2_privkey}" \ + "${node_3_privkey}" \ + --version="$version" + cd ../../.. +} + +test_fee_back() { + local version=$1 + cd ./scripts/txtool/txtool + python3 "${SOURCE_DIR}"/tests/integrate_test/test_fee_back.py --version="$version" + cd ../../.. +} + +update_version() { + local version=$1 + cd ./scripts/txtool/txtool + python3 "${SOURCE_DIR}"/tests/integrate_test/update_version.py --version="$version" + cd ../../.. +} + +main() { + echo -n "0) prepare ... " + # shellcheck source=/dev/null + . ${SOURCE_DIR}/tests/integrate_test/util.sh + cd "${BINARY_DIR}" + echo "DONE" + + echo -n "1) generate config ... " + create_config \ + --contract_arguments "SysConfig.checkFeeBackPlatform=true" \ + --contract_arguments "SysConfig.economicalModel=1" \ + --contract_arguments "VersionManager.version=0" \ + --contract_arguments "PriceManager.quotaPrice=1000000" \ + --contract_arguments "SysConfig.chainOwner=0x36a60d575b0dee0423abb6a57dbc6ca60bf47545" + echo "DONE" + + echo -n "2) start nodes ... " + start_nodes + echo "DONE" + + echo -n "3) check alive ... " + timeout=$(check_height_growth_normal 0 60) || (echo "FAILED" + echo "failed to check_height_growth 0: ${timeout}" + exit 1) + echo "${timeout}s DONE" + + echo -n "4) Run fee back tests ... " + test_fee_back 0 + echo "DONE" + + echo -n "5) Run charge mode tests in v0 ... " + test_charge_mode 0 + echo "DONE" + + echo -n "6) Update to chainIDV1 ... " + update_version 0 + echo "DONE" + + echo -n "7) check alive ... " + timeout=$(check_height_growth_normal 0 60) || (echo "FAILED" + echo "failed to check_height_growth 0: ${timeout}" + exit 1) + echo "${timeout}s DONE" + + echo -n "8) Run fee back tests in v1 ... " + test_fee_back 1 + echo "DONE" + + echo -n "9) Run charge mode tests in v1 ... " + test_charge_mode 1 + echo "DONE" +} + +main "$@" diff --git a/tests/integrate_test/cita_crosschain.sh b/tests/integrate_test/cita_crosschain.sh index 5e303e569..0bfd1a8b2 100755 --- a/tests/integrate_test/cita_crosschain.sh +++ b/tests/integrate_test/cita_crosschain.sh @@ -2,6 +2,13 @@ set -e -o pipefail +if [[ $(uname) == 'Darwin' ]] +then + SOURCE_DIR=$(realpath "$(dirname "$0")"/../..) +else + SOURCE_DIR=$(readlink -f "$(dirname "$0")"/../..) +fi + # Test private key & address PKEY="1234567890123456789012345678901234567890123456789012345678901234" PADDR="2e988a386a799f506693793c6a5af6b54dfaabfb" @@ -12,7 +19,7 @@ CMC="scripts/contracts/src/system/ChainManager.sol" CMC_ABI= # Base dir for import contract files -CONTRACT_LIBS_DIR="scripts/contracts" +CONTRACT_LIBS_DIR="$SOURCE_DIR" # Templates for some shell commands JSONRPC_CALL='{"jsonrpc":"2.0","method":"call", "params":[{"to":"%s", "data":"%s"}, "pending"],"id":2}' @@ -20,7 +27,7 @@ JSONRPC_BLOCKHEADER='{"jsonrpc":"2.0","method":"getBlockHeader","params":["0x%x" JSONRPC_STATEPROOF='{"jsonrpc":"2.0","method":"getStateProof","params":["0x%s","0x%s","0x%x"],"id":1}' # Test contract file -CONTRACT_DEMO="scripts/contracts/tests/contracts/MyToken.sol" +CONTRACT_DEMO="${SOURCE_DIR}/tests/contracts/MyToken.sol" DEMO_ABI= # Global variables which are set in functions @@ -147,7 +154,7 @@ function deploy_contract () { local chain="$1" local solfile="$2" local extra="$3" - local code="$(solc --allow-paths "$(pwd)/${CONTRACT_LIBS_DIR}" \ + local code="$(solc --allow-paths "${CONTRACT_LIBS_DIR}" \ --bin "${solfile}" 2>/dev/null | tail -1)${extra}" txtool_run ${chain} make_tx.py --privkey "${PKEY}" --code "${code}" txtool_run ${chain} send_tx.py @@ -347,7 +354,7 @@ function test_demo_contract () { "The tokens is not right for side chain." title "Send tokens from main chain." - DEMO_ABI=$(solc --allow-paths "$(pwd)/${CONTRACT_LIBS_DIR}" \ + DEMO_ABI=$(solc --allow-paths "${CONTRACT_LIBS_DIR}" \ --combined-json abi ${CONTRACT_DEMO} \ | sed "s@${CONTRACT_DEMO}:@@g" \ | json_get '.contracts.MyToken.abi') @@ -494,7 +501,7 @@ function main () { title "Create side chain keys ..." for ((id=0;id<4;id++)); do - bin/create_key_addr secret${id} address${id} + bin/create-key-addr secret${id} address${id} done local side_auths=$(ls address[0-4] | sort | xargs -I {} cat {} \ | tr '\n' ',' | rev | cut -c 2- | rev) @@ -512,7 +519,7 @@ function main () { wait_chain_for_height main 3 title "Register side chain ..." - CMC_ABI=$(solc --allow-paths "$(pwd)/${CONTRACT_LIBS_DIR}" \ + CMC_ABI=$(solc --allow-paths "${CONTRACT_LIBS_DIR}" \ --combined-json abi ${CMC} 2>/dev/null \ | sed "s@${CMC}:@@g" \ | json_get '.contracts.ChainManager.abi') diff --git a/tests/integrate_test/cita_datasynctest.sh b/tests/integrate_test/cita_datasynctest.sh deleted file mode 100755 index 6383dbb7d..000000000 --- a/tests/integrate_test/cita_datasynctest.sh +++ /dev/null @@ -1,66 +0,0 @@ -#!/bin/bash - -stop_node3() { - cd ${CUR_PATH}/../../admintool/release/node3 - ./cita stop 3 -} - -start_node3() { - cd ${CUR_PATH}/../../admintool/release/node3 - ./cita start 3 & -} - -get_height(){ - nodeid=$1 - if [ ! -n "$nodeid" ]; then - nodeid=0 - fi - h=`${CUR_PATH}/blockNumber.sh 127.0.0.1 $((1337+${nodeid}))` - h=$(echo $h | sed 's/\"//g') - echo $((h)) -} - -COUNT=$1 -if [ ! -n "$COUNT" ]; then - COUNT=100 -fi - -CUR_PATH=$(cd `dirname $0`; pwd) - -${CUR_PATH}/cita_start.sh - -stop_node3 -echo "###Stop node3" - -height=$(get_height) -hi=$[height+COUNT] - -echo "current height:$height" -echo "aim height:$hi" - -while [ $height -le $hi ] -do - height=$(get_height) - sleep 3 -done - - -echo "###start node3" -start_node3 - -start=$(date +%s) - -num_3=$(get_height 3) - -while(($num_3<$hi)) -do - num_3=$(get_height 3) -done - -end=$(date +%s) - -time=$((end - start)) - -echo "Syn $COUNT block spent time:$time" - -${CUR_PATH}/cita_stop.sh diff --git a/tests/integrate_test/cita_discovery.sh b/tests/integrate_test/cita_discovery.sh index cbcff0cc4..73db50095 100755 --- a/tests/integrate_test/cita_discovery.sh +++ b/tests/integrate_test/cita_discovery.sh @@ -356,20 +356,16 @@ main() { set_hosts echo "DONE" - echo -n "1) cleanup ... " - cleanup - echo "DONE" - - echo -n "2) generate config ... " + echo -n "1) generate config ... " generate_config echo "DONE" - echo -n "3) pre start nodes[0..3] ... " + echo -n "2) pre start nodes[0..3] ... " pre_start_nodes echo "DONE" # Pre-check peer count, it is OK to check node0 only - echo -n "4) pre-check peer count ... " + echo -n "3) pre-check peer count ... " timeout=$(check_peer_count 0 3 90)||(echo "FAILED" echo "error msg: ${timeout}" exit 1) @@ -402,11 +398,6 @@ main() { test_repeated_address test_max_connected_limit_as_client test_max_connected_limit_as_server - - echo -n "5) cleanup ... " - clean_host - cleanup - echo "DONE" } main "$@" diff --git a/tests/integrate_test/cita_jsonrpcTest.sh b/tests/integrate_test/cita_jsonrpcTest.sh deleted file mode 100755 index ab833f909..000000000 --- a/tests/integrate_test/cita_jsonrpcTest.sh +++ /dev/null @@ -1,74 +0,0 @@ -#!/bin/bash - -#echo "args: ip port" -IP=$1 -PORT=$2 -if [ ! -n "$IP" ]; then - IP="127.0.0.1" -fi -if [ ! -n "$PORT" ]; then - PORT=1337 -fi - -assert() { - if [ $1 -ne $2 ]; then - echo "$3 test failed" - ./cita_stop.sh - exit 1 - fi - echo "$3 test ok" -} - -assert_null() { - if [ "$1" != "null" ]; then - echo "$2 test failed" - ./cita_stop.sh - exit 1 - fi - echo "$2 test ok" -} - -invalid_http_method=-32600 -invalid_params=-32605 -invalid_data=-32600 -invalid_jsonrpc_method=-32601 - -./cita_start.sh - -# Check JSON-RPC CORS: Access-Control-Allow-Origin should be existed. -has_cors=$(curl -i -X POST -d '{"jsonrpc":"2.0","method":"peerCount","params":[],"id":2}' $IP:$PORT 2>/dev/null | grep -ic "^access-control-allow-origin: ") -assert ${has_cors} 1 "Check JSON-RPC CORS" - -## request of invalid http method -err_code=`curl -s -X GET -d '{"jsonrpc":"2.0","method":"peerCount","params":[],"id":2}' $IP:$PORT | jq ".error.code"` -assert $err_code $invalid_http_method "request of invalid http method" - -## invalid request of missing id -err_code=`curl -s -X POST -d '{"jsonrpc":"2.0","method":"peerCount","params":[]}' $IP:$PORT | jq ".error.code"` -assert $err_code $invalid_params "invalid request of missing id" - -## request of invalid json -err_code=`curl -s -X POST -d 'abc' $IP:$PORT | jq ".error.code"` -assert $err_code $invalid_params "request of invalid json" - -## invalid jsonrpc method -err_code=`curl -s -X POST -d '{"jsonrpc":"2.0","method":"invalid_method","params":[],"id":2}' $IP:$PORT | jq ".error.code"` -assert $err_code $invalid_jsonrpc_method "invalid jsonrpc method" - -## invalid request of missing params -err_code=`curl -s -X POST -d '{"jsonrpc":"2.0","method":"getTransaction","params":[],"id":2}' $IP:$PORT | jq ".error.code"` -assert $err_code $invalid_params "invalid request params" - -## get null block -result=`curl -s -X POST -d '{"jsonrpc":"2.0","method":"cita_getBlockByHeight","params":[9999999999999999,true],"id":2}' $IP:$PORT | jq ".error.code"` -assert_null $result "get null block" - -## get null transaction -result=`curl -s -X POST -d '{"jsonrpc":"2.0","method":"getTransaction","params":["0000000000000000000000000000000000000000000000000000000000000000"],"id":2}' $IP:$PORT | jq ".error.code"` -assert_null $result "get null transaction" - -## null block hash -result=`curl -s -X POST -d '{"jsonrpc":"2.0","method":"getBlockByHash","params":["0000000000000000000000000000000000000000000000000000000000000000",true],"id":2}' $IP:$PORT | jq ".error.code"` -assert_null $result "null block hash" - -./cita_stop.sh diff --git a/tests/integrate_test/cita_jsonrpc_schema_mock.sh b/tests/integrate_test/cita_jsonrpc_schema_mock.sh index 937416f2b..05e8e47b4 100755 --- a/tests/integrate_test/cita_jsonrpc_schema_mock.sh +++ b/tests/integrate_test/cita_jsonrpc_schema_mock.sh @@ -3,74 +3,54 @@ set -e ECONOMICAL_MODEL="0" -if [ -n $1 ] && [ "$1" = "charge" ]; then +if [[ -n "$1" ]] && [ "$1" = "charge" ]; then ECONOMICAL_MODEL="1" fi -if [[ `uname` == 'Darwin' ]] +if [[ $(uname) == 'Darwin' ]] then - SOURCE_DIR=$(realpath $(dirname $0)/../..) + SOURCE_DIR=$(realpath "$(dirname "$0")"/../..) else - SOURCE_DIR=$(readlink -f $(dirname $0)/../..) + SOURCE_DIR=$(readlink -f "$(dirname "$0")"/../..) fi -BINARY_DIR=${SOURCE_DIR}/target/install -TESTS_DIR=${SOURCE_DIR}/tests/interfaces/rpc/tests - -################################################################################ -echo -n "0) prepare ... " -. ${SOURCE_DIR}/tests/integrate_test/util.sh -cd ${BINARY_DIR} -echo "DONE" - -################################################################################ -echo -n "1) cleanup ... " -cleanup "mock-chain" -echo "DONE" - -################################################################################ -echo -n "2) generate config ... " -if [ ! -d "resource" ]; then - mkdir resource -fi - -AUTHORITIES=`cat ${SOURCE_DIR}/tests/interfaces/config/authorities |xargs echo |sed "s/ /,/g"` -${BINARY_DIR}/scripts/create_cita_config.py create --nodes "127.0.0.1:4000,127.0.0.1:4001,127.0.0.1:4002,127.0.0.1:4003" \ - --chain_name "mock-chain" \ +BINARY_DIR=${SOURCE_DIR}/target/install +CHAIN_NAME="mock-chain" + +main() { + echo -n "0) prepare ... " + cd "${BINARY_DIR}" + echo "DONE" + + echo -n "1) generate config ... " + AUTHORITIES=$(xargs echo < "${SOURCE_DIR}"/tests/interfaces/config/authorities |sed "s/ /,/g") + "${BINARY_DIR}"/scripts/create_cita_config.py create \ + --nodes "127.0.0.1:4000,127.0.0.1:4001,127.0.0.1:4002,127.0.0.1:4003" \ + --chain_name "$CHAIN_NAME" \ --super_admin "0x4b5ae4567ad5d9fb92bc9afd6a657e6fa13a2523" \ --contract_arguments "SysConfig.economicalModel=${ECONOMICAL_MODEL}" \ --contract_arguments "SysConfig.chainId=123" \ --timestamp 1524000000 \ - --authorities ${AUTHORITIES} \ + --authorities "${AUTHORITIES}" \ --enable_version -echo "DONE" - -################################################################################ -echo -n "3) just start mock-chain/0 ... " -${BINARY_DIR}/bin/cita bebop setup mock-chain/0 > /dev/null -${BINARY_DIR}/bin/cita bebop start mock-chain/0 trace -echo "DONE" - -################################################################################ -echo -n "4) generate mock data ... " -AMQP_URL=amqp://guest:guest@localhost/mock-chain/0 \ - ${BINARY_DIR}/bin/chain-executor-mock \ - -m ${SOURCE_DIR}/tests/interfaces/config/blockchain.yaml -echo "DONE" - -################################################################################ -echo -n "5) check mock data ... " -python3 ${SOURCE_DIR}/tests/interfaces/rpc_test_runner.py \ - --rpc-url http://127.0.0.1:1337 \ - --directory ${SOURCE_DIR}/tests/jsondata/rpc/ -echo "DONE" - -################################################################################ -echo -n "6) stop mock-chain/0 ... " -${BINARY_DIR}/bin/cita bebop stop mock-chain/0 -echo "DONE" - -################################################################################ -echo -n "7) cleanup ... " -cleanup "mock-chain" -echo "DONE" + echo "DONE" + + echo -n "2) just start node0 ... " + bin/cita bebop setup "$CHAIN_NAME"/0 > /dev/null + bin/cita bebop start "$CHAIN_NAME"/0 + echo "DONE" + + echo -n "3) generate mock data ... " + AMQP_URL=amqp://guest:guest@localhost/"$CHAIN_NAME"/0 \ + "${BINARY_DIR}"/bin/chain-executor-mock \ + -m "${SOURCE_DIR}"/tests/interfaces/config/blockchain.yaml + echo "DONE" + + echo -n "4) check mock data ... " + python3 "${SOURCE_DIR}"/tests/interfaces/rpc_test_runner.py \ + --rpc-url http://127.0.0.1:1337 \ + --directory "${SOURCE_DIR}"/tests/jsondata/rpc/ + echo "DONE" +} + +main "$@" diff --git a/tests/integrate_test/cita_snapshot_test.sh b/tests/integrate_test/cita_snapshot_test.sh index dadf013cd..d46e91457 100755 --- a/tests/integrate_test/cita_snapshot_test.sh +++ b/tests/integrate_test/cita_snapshot_test.sh @@ -2,137 +2,111 @@ # Set bash environment set -e -if [[ `uname` == 'Darwin' ]] +if [[ $(uname) == 'Darwin' ]] then - SOURCE_DIR=$(realpath $(dirname $0)/../..) - SED="gsed" + SOURCE_DIR=$(realpath "$(dirname "$0")"/../..) else - SOURCE_DIR=$(readlink -f $(dirname $0)/../..) - SED="sed" + SOURCE_DIR=$(readlink -f "$(dirname "$0")"/../..) fi # Set CITA system environment BINARY_DIR=${SOURCE_DIR}/target/install -CHAIN_NAME="mock-chain" -SUPER_ADMIN="0x4b5ae4567ad5d9fb92bc9afd6a657e6fa13a2523" - -################################################################################ -echo "0) Prepare ..." -source "${SOURCE_DIR}/tests/integrate_test/util.sh" -cd "${BINARY_DIR}" -echo "DONE" - -################################################################################ -echo "1) Clean Up ..." -cleanup "${CHAIN_NAME}" -echo "DONE" - -################################################################################ -echo "2) Generate CITA configurations ..." -${BINARY_DIR}/scripts/create_cita_config.py create \ - --nodes "127.0.0.1:4000,127.0.0.1:4001,127.0.0.1:4002,127.0.0.1:4003" \ - --super_admin "${SUPER_ADMIN}" \ - --chain_name "${CHAIN_NAME}" \ - --timestamp 1524000000 -echo "DONE" - -################################################################################ -echo "3) Run node-0, node-1, node-2" -for id in {0,1,2}; do - ${BINARY_DIR}/bin/cita bebop setup ${CHAIN_NAME}/${id} > /dev/null -done -for id in {0,1,2}; do - ${BINARY_DIR}/bin/cita bebop start ${CHAIN_NAME}/${id} trace -done -echo "DONE" - -sleep 10 - -################################################################################ -echo "4) Check all nodes grow up ..." -for id in {0..2}; do - echo "chech_height_growth_normal $id ..." - timeout=`check_height_growth_normal $id 15`||(echo "FAILED" - echo "error msg: ${timeout}" - exit 1) -done -echo "${timeout}s DONE" - -################################################################################ -echo "5) Stop node-1 and node-2, so that node-0 cannot grow up via cita-consensus and cita-sync mechanisms" -${BINARY_DIR}/bin/cita bebop stop ${CHAIN_NAME}/1 -${BINARY_DIR}/bin/cita bebop stop ${CHAIN_NAME}/2 - -# Ensure that the current round of BFT has been finished. So that node-0 will -# not continue growing up, which means its height stay the same. -sleep 3 -echo "DONE" - -################################################################################ -echo "6) Take snapshot on node-0 at height {0, 2, 100000} ..." -for height in {0,2,10000}; do - cd ${BINARY_DIR}/${CHAIN_NAME}/0 - ${BINARY_DIR}/bin/snapshot_tool \ - --cmd snapshot \ - --file snapshot-test-${height} \ - --end_height ${height} || ( - echo "FAILED" - echo "error msg: fail to take snapshot at ${height}" - exit 1) -done - -cd "${BINARY_DIR}" -echo "DONE" - -################################################################################ -echo "7) Restore snapshot on node-0 ..." -before_height=`get_height 0` -for height in {10000,2,0,10000,2,0}; do - cd ${BINARY_DIR}/${CHAIN_NAME}/0 - echo "restoring with before_height=${before_height}, height=${height} ..." - - ${BINARY_DIR}/bin/snapshot_tool \ - --cmd restore \ - --file snapshot-test-${height} || ( - echo "FAILED" - echo "error msg: fail to restore snapshot to ${height}" - exit 1) - - case $height in - 0) expect_height=${before_height};; - 2) expect_height=2;; - 10000) expect_height=${before_height};; - esac - - current_height=`get_height 0` - if [ "${current_height}" != "${expect_height}" ]; then - echo "FAILED: expect_height(${expect_height})!= current_height(${current_height})" - exit 1 - fi -done - -cd "${BINARY_DIR}" -echo "DONE" - -################################################################################ -echo "8) Start node-1 and node-2 and check all grow up ..." -${BINARY_DIR}/bin/cita bebop start ${CHAIN_NAME}/1 trace -${BINARY_DIR}/bin/cita bebop start ${CHAIN_NAME}/2 trace - -wait_timeout=30 -timeout=`check_height_growth_normal 1 $wait_timeout` || (echo "FAILED" - echo "error msg: ${timeout}" - exit 1) -timeout=`check_height_growth_normal 0 $wait_timeout` || (echo "FAILED" + +main() { + echo "0) Prepare ..." + # shellcheck source=/dev/null + source "${SOURCE_DIR}/tests/integrate_test/util.sh" + cd "${BINARY_DIR}" + echo "DONE" + + echo "1) Generate configurations ..." + create_config --timestamp 1524000000 + echo "DONE" + + echo "2) Run node-0, node-1, node-2" + for id in {0,1,2}; do + "${BINARY_DIR}"/bin/cita bebop setup "${CHAIN_NAME}"/${id} > /dev/null + done + for id in {0,1,2}; do + "${BINARY_DIR}"/bin/cita bebop start "${CHAIN_NAME}"/${id} + done + echo "DONE" + + echo "3) Check all nodes grow up ..." + for id in {0..2}; do + echo "chech_height_growth_normal $id ..." + timeout=$(check_height_growth_normal $id 60) || (echo "FAILED" echo "error msg: ${timeout}" exit 1) -echo "DONE" - -################################################################################ -echo "9) Clean Up ..." -for id in {0,1,2}; do - ${BINARY_DIR}/bin/cita bebop stop ${CHAIN_NAME}/${id} -done - -cleanup -echo "DONE" + done + echo "${timeout}s DONE" + + echo "4) Stop node-1 and node-2, so that node-0 cannot grow up via cita-consensus and cita-sync mechanisms" + "${BINARY_DIR}"/bin/cita bebop stop "${CHAIN_NAME}"/1 + "${BINARY_DIR}"/bin/cita bebop stop "${CHAIN_NAME}"/2 + + # Ensure that the current round of BFT has been finished. So that node-0 will + # not continue growing up, which means its height stay the same. + sleep 3 + echo "DONE" + + echo "5) Take snapshot on node-0 at height {0, 2, 100000} ..." + for height in {0,2,10000}; do + cd "${BINARY_DIR}"/"${CHAIN_NAME}"/0 + "${BINARY_DIR}"/bin/snapshot-tool \ + --cmd snapshot \ + --file snapshot-test-${height} \ + --end_height ${height} || ( + echo "FAILED" + echo "error msg: fail to take snapshot at ${height}" + exit 1) + done + + cd "${BINARY_DIR}" + echo "DONE" + + echo "6) Restore snapshot on node-0 ..." + before_height=$(get_height 0) + for height in {10000,2,0,10000,2,0}; do + cd "${BINARY_DIR}"/"${CHAIN_NAME}"/0 + echo "restoring with before_height=${before_height}, height=${height} ..." + + "${BINARY_DIR}"/bin/snapshot-tool \ + --cmd restore \ + --file snapshot-test-${height} || ( + echo "FAILED" + echo "error msg: fail to restore snapshot to ${height}" + exit 1) + + case $height in + 0) expect_height=${before_height};; + 2) expect_height=2;; + 10000) expect_height=${before_height};; + esac + + current_height=$(get_height 0) + if [ "${current_height}" != "${expect_height}" ]; then + echo "FAILED: expect_height(${expect_height})!= current_height(${current_height})" + exit 1 + fi + done + + cd "${BINARY_DIR}" + echo "DONE" + + echo "7) Start node-1 and node-2 and check all grow up ..." + for id in {1,2}; do + "${BINARY_DIR}"/bin/cita bebop start "${CHAIN_NAME}"/${id} + done + + wait_timeout=30 + for id in {0,1}; do + timeout=$(check_height_growth_normal ${id} $wait_timeout) || (echo "FAILED" + echo "error msg: ${timeout}" + exit 1) + done + + echo "DONE" +} + +main "$@" diff --git a/tests/integrate_test/cita_start.sh b/tests/integrate_test/cita_start.sh deleted file mode 100755 index c723cca75..000000000 --- a/tests/integrate_test/cita_start.sh +++ /dev/null @@ -1,56 +0,0 @@ -#!/bin/bash -#usage: start demo nodes -# ./cita_start.sh -# ./cita_start.sh [error,info, warn, debug, trace] [cita-bft] - -set +e - -debug=$1 -consensus=$2 - -if [[ `uname` == 'Darwin' ]] -then - SOURCE_DIR=$(realpath $(dirname $0)/../..) -else - SOURCE_DIR=$(readlink -f $(dirname $0)/../..) -fi -BINARY_DIR=${SOURCE_DIR}/target/install -. ${SOURCE_DIR}/tests/integrate_test/util.sh - -if [ ! -n "$consensus" ]; then - consensus="cita-bft" -fi - -echo "###cleanup" -cleanup - -echo "###generate config files" -cd ${BINARY_DIR} -./scripts/create_cita_config.py create \ - --chain_name "node" \ - --super_admin "0x4b5ae4567ad5d9fb92bc9afd6a657e6fa13a2523" \ - --nodes "127.0.0.1:4000,127.0.0.1:4001,127.0.0.1:4002,127.0.0.1:4003" >/dev/null 2>&1 - - -echo "###start nodes" -for i in {0..3} ; do - setup_node $i -done - -for i in {0..3} ; do - start_node $i & -done - -echo -n "###check height growth" -msg=$(check_height_growth 0 60)|| (echo "FAILED" - echo "check height growth: ${msg}" - exit 1) -echo "###CITA start OK" - -cita_pid=`cat ${BINARY_DIR}/node/0/.cita-forever.pid` -pid_file="/proc/${cita_pid}/cmdline" - -while [ -e ${pid_file} ];do - sleep 3; -done - diff --git a/tests/integrate_test/cita_start_with_kafka.sh b/tests/integrate_test/cita_start_with_kafka.sh deleted file mode 100755 index 7f8b161d6..000000000 --- a/tests/integrate_test/cita_start_with_kafka.sh +++ /dev/null @@ -1,56 +0,0 @@ -#!/bin/bash -#usage: start demo nodes -# ./cita_start_with_kafka.sh -# ./cita_start_with_kafka.sh [error,info, warn, debug, trace] - -set +e - -debug=$1 -consensus=$2 - -if [[ `uname` == 'Darwin' ]] -then - SOURCE_DIR=$(realpath $(dirname $0)/../..) -else - SOURCE_DIR=$(readlink -f $(dirname $0)/../..) -fi -BINARY_DIR=${SOURCE_DIR}/target/install -. ${SOURCE_DIR}/tests/integrate_test/util.sh - -if [ ! -n "$consensus" ]; then - consensus="cita-bft" -fi - -echo "###cleanup" -cleanup - -echo "###generate config files" -cd ${BINARY_DIR} -./scripts/create_cita_config.py create \ - --chain_name "node" \ - --super_admin "0x4b5ae4567ad5d9fb92bc9afd6a657e6fa13a2523" \ - --nodes "127.0.0.1:4000,127.0.0.1:4001,127.0.0.1:4002,127.0.0.1:4003" >/dev/null 2>&1 - -echo "###wait for kafka start" -$SOURCE_DIR/tests/integrate_test/kafka_start.sh ${BINARY_DIR} -if [ "$?" -ne "0" ]; then - exit 1 -fi -sleep 5 - -echo "###start nodes" -for i in {0..3} ; do - setup_node $i -done - -for i in {0..3} ; do - start_node $i & -done - -echo -n "###check height growth" -msg=$(check_height_growth 0)|| (echo "FAILED" - echo "check height growth: ${msg}" - exit 1) -echo "###CITA start OK" -exit 0 - diff --git a/tests/integrate_test/cita_stop.sh b/tests/integrate_test/cita_stop.sh deleted file mode 100755 index 14c4d24a2..000000000 --- a/tests/integrate_test/cita_stop.sh +++ /dev/null @@ -1,25 +0,0 @@ -#!/bin/bash -set -e -kafka=$1 -if [[ `uname` == 'Darwin' ]] -then - SOURCE_DIR=$(realpath $(dirname $0)/../..) -else - SOURCE_DIR=$(readlink -f $(dirname $0)/../..) -fi -BINARY_DIR=${SOURCE_DIR}/target/install - -. ${SOURCE_DIR}/tests/integrate_test/util.sh -cd ${BINARY_DIR} - -date -echo "###Stop CITA " -stop_all -if [ "$kafka" == "kafka" ]; then - echo "###Stop kafka" - $SOURCE_DIR/tests/integrate_test/kafka_stop.sh $BINARY_DIR -fi -date - -exit 0 - diff --git a/tests/integrate_test/cita_tls_basic.sh b/tests/integrate_test/cita_tls_basic.sh deleted file mode 100755 index b3ba7fb4f..000000000 --- a/tests/integrate_test/cita_tls_basic.sh +++ /dev/null @@ -1,131 +0,0 @@ -#!/bin/bash -set -e - -if [[ `uname` == 'Darwin' ]] -then - SOURCE_DIR=$(realpath $(dirname $0)/../..) -else - SOURCE_DIR=$(readlink -f $(dirname $0)/../..) -fi -BINARY_DIR=${SOURCE_DIR}/target/install - -################################################################################ -echo -n "0) prepare ... " -. ${SOURCE_DIR}/tests/integrate_test/util.sh -cd ${BINARY_DIR} -echo "DONE" - -################################################################################ -echo -n "1) cleanup ... " -cleanup -echo "DONE" - -################################################################################ -echo -n "2) generate config ... " -./scripts/create_cita_config.py create \ - --chain_name "node" \ - --super_admin "0x4b5ae4567ad5d9fb92bc9afd6a657e6fa13a2523" \ - --enable_tls \ - --nodes "127.0.0.1:4000,127.0.0.1:4001,127.0.0.1:4002,127.0.0.1:4003" \ - > /dev/null 2>&1 -echo "DONE" - -################################################################################ -echo -n "3) start nodes ... " -for i in {0..3} ; do - bin/cita bebop setup node/$i > /dev/null -done -for i in {0..3} ; do - bin/cita bebop start node/$i trace > /dev/null & -done -echo "DONE" - -sleep 60 - -################################################################################ -echo -n "4) check height growth normal ... " -timeout=$(check_height_growth_normal 0 15)||(echo "FAILED" - echo "error msg: ${timeout}" - exit 1) -echo "${timeout}s DONE" - -################################################################################ -echo -n "5) stop node3, check height growth ... " -bin/cita bebop stop node/3 > /dev/null -timeout=$(check_height_growth_normal 0 15) || (echo "FAILED" - echo "error msg: ${timeout}" - exit 1) -echo "${timeout}s DONE" - -################################################################################ -echo -n "6) stop node2, check height stopped ... " -bin/cita bebop stop node/2 > /dev/null -timeout=$(check_height_stopped 0 27) || (echo "FAILED" - echo "error msg: ${timeout}" - exit 1) -echo "${timeout}s DONE" - -################################################################################ -echo -n "7) start node2, check height growth ... " -bin/cita bebop start node/2 trace > /dev/null & -sleep 24 #wait for recovery from stop -timeout=$(check_height_growth_normal 0 15) || (echo "FAILED" - echo "error msg: ${timeout}" - exit 1) -echo "${timeout}s DONE" - -################################################################################ -echo -n "8) start node3, check synch ... " -node0_height=$(get_height 0) - -if [ $? -ne 0 ] ; then - echo "failed to get_height: ${node0_height}" - exit 1 -fi -bin/cita bebop start node/3 trace > /dev/null & -timeout=$(check_height_sync 3 0) || (echo "FAILED" - echo "error msg: ${timeout}" - exit 1) -echo "${timeout}s DONE" - -################################################################################ -echo -n "9) stop all nodes, check height changed after restart ... " -before_height=$(get_height 0) -if [ $? -ne 0 ] ; then - echo "failed to get_height: ${before_height}" - exit 1 -fi -for i in {0..3}; do - bin/cita bebop stop node/$i > /dev/null -done -# sleep 1 # TODO: change to this value will produce very different result -for i in {0..3}; do - bin/cita bebop start node/$i trace > /dev/null & -done - -timeout=$(check_height_growth_normal 0 300) || (echo "FAILED" - echo "error msg: ${timeout}" - exit 1) -after_height=$(get_height 0)|| (echo "failed to get_height: ${after_height}" - exit 1) -if [ $after_height -le $before_height ]; then - echo "FAILED" - echo "before:${before_height} after:${after_height}" - exit 1 -fi -echo "${timeout}s DONE" - -################################################################################ -echo -n "10) stop&clean node3, check height synch after restart ... " -bin/cita bebop stop node/3 > /dev/null -bin/cita bebop clean node/3 > /dev/null -bin/cita bebop start node/3 trace > /dev/null & -timeout=$(check_height_sync 3 0) || (echo "FAILED" - echo "error msg: ${timeout}" - exit 1) -echo "${timeout}s DONE" - -################################################################################ -echo -n "11) cleanup ... " -cleanup -echo "DONE" diff --git a/tests/integrate_test/cita_transactiontest.sh b/tests/integrate_test/cita_transactiontest.sh deleted file mode 100755 index 19fdafd77..000000000 --- a/tests/integrate_test/cita_transactiontest.sh +++ /dev/null @@ -1,26 +0,0 @@ -#!/bin/bash -set +e - - -if [[ `uname` == 'Darwin' ]] -then - SOURCE_DIR=$(realpath $(dirname $0)/../..) -else - SOURCE_DIR=$(readlink -f $(dirname $0)/../..) -fi -BINARY_DIR=${SOURCE_DIR}/target/install - -. ${SOURCE_DIR}/tests/integrate_test/util.sh -${SOURCE_DIR}/tests/integrate_test/cita_start.sh & - -cd ${SOURCE_DIR}/tests/wrk_benchmark_test/ -./benchmark.sh -sleep 10 -./benchmark.sh config_call.json - -check_height_growth 0 60 - -${SOURCE_DIR}/tests/integrate_test/cita_stop.sh -echo "###Test OK" -exit 0 - diff --git a/tests/integrate_test/getBlockByNumber.sh b/tests/integrate_test/getBlockByNumber.sh deleted file mode 100755 index 5e2f7dc49..000000000 --- a/tests/integrate_test/getBlockByNumber.sh +++ /dev/null @@ -1,12 +0,0 @@ -#!/bin/bash -if [ $# == 1 ]; then - HEIGHT=$1 - IP="127.0.0.1"; -elif [ $# == 2 ]; then - HEIGHT=$1 - IP=$2; -else - echo "args: height ip (default localhost) " - exit -fi -curl -s -X POST -d '{"jsonrpc":"2.0","method":"getBlockByNumber","params":["'$HEIGHT'",false],"id":2}' $IP:1337 diff --git a/tests/integrate_test/getTransaction.sh b/tests/integrate_test/getTransaction.sh deleted file mode 100755 index 011c3ded6..000000000 --- a/tests/integrate_test/getTransaction.sh +++ /dev/null @@ -1,12 +0,0 @@ -#!/bin/bash -if [ $# == 1 ]; then - HASH=$1 - IP="127.0.0.1"; -elif [ $# == 2 ]; then - HASH=$1 - IP=$2; -else - echo "args: hash ip (default localhost) " - exit -fi -curl -s -X POST -d '{"jsonrpc":"2.0","method":"getTransaction","params":['\"$HASH\"'],"id":2}' $IP:1337 diff --git a/tests/integrate_test/getTransactionReceipt.sh b/tests/integrate_test/getTransactionReceipt.sh deleted file mode 100755 index 22d370124..000000000 --- a/tests/integrate_test/getTransactionReceipt.sh +++ /dev/null @@ -1,12 +0,0 @@ -#!/bin/bash -if [ $# == 1 ]; then - HASH=$1 - IP="127.0.0.1"; -elif [ $# == 2 ]; then - HASH=$1 - IP=$2; -else - echo "args: hash ip (default localhost) " - exit -fi -curl -s -X POST -d '{"jsonrpc":"2.0","method":"getTransactionReceipt","params":['\"$HASH\"'],"id":2}' $IP:1337 diff --git a/tests/integrate_test/kafka_start.sh b/tests/integrate_test/kafka_start.sh deleted file mode 100755 index 2408b5c6e..000000000 --- a/tests/integrate_test/kafka_start.sh +++ /dev/null @@ -1,27 +0,0 @@ -#!/bin/bash - -if [ $# -ne 1 ]; then - echo "usage: $0 INSTALL_PATH" - exit 1 -fi - -if [ -z "$KAFKA_HOME" ]; then - echo "Please set KAFKA_HOME environment var first" - exit 1 -fi - -install_path=$1 -kafka_pid=.kafka_pid -for i in {0..3} ; do - node_path=$install_path/node$i - nohup $KAFKA_HOME/bin/zookeeper-server-start.sh $node_path/zookeeper.properties > /tmp/zookeeper$i.log 2>&1 & - echo $! >> $node_path/$kafka_pid -done - -sleep 5 - -for i in {0..3}; do - node_path=$install_path/node$i - nohup $KAFKA_HOME/bin/kafka-server-start.sh $node_path/kafka.properties > /tmp/kafka$i.log 2>&1 & - echo $! >> $node_path/$kafka_pid -done diff --git a/tests/integrate_test/kafka_stop.sh b/tests/integrate_test/kafka_stop.sh deleted file mode 100755 index 9ec6bf560..000000000 --- a/tests/integrate_test/kafka_stop.sh +++ /dev/null @@ -1,28 +0,0 @@ -#!/bin/bash - -if [ $# -ne 1 ]; then - echo "usage: $0 INSTALL_PATH" - exit 1 -fi - -install_path=$1 -kafka_pid=.kafka_pid - -stop_kafka() { - id=$1 - file=$install_path/node$id/$kafka_pid - if [ -e $file ]; then - for pid in $(cat $file); do - kill -9 $pid || true - done - rm -f $file - fi -} - -stop_all_kafka() { - for id in {0..3}; do - stop_kafka $id - done -} - -stop_all_kafka diff --git a/tests/integrate_test/peerCount.sh b/tests/integrate_test/peerCount.sh deleted file mode 100755 index b4c301977..000000000 --- a/tests/integrate_test/peerCount.sh +++ /dev/null @@ -1,11 +0,0 @@ -#!/bin/bash - -IP=$1 -PORT=$2 -if [ ! -n "$IP" ]; then - IP="127.0.0.1" -fi -if [ ! -n "$PORT" ]; then - PORT=1337 -fi -curl -s -X POST -d '{"jsonrpc":"2.0","method":"peerCount","params":[],"id":2}' $IP:$PORT | jq ".result" \ No newline at end of file diff --git a/tests/integrate_test/util.sh b/tests/integrate_test/util.sh index 644206568..7bdb96662 100644 --- a/tests/integrate_test/util.sh +++ b/tests/integrate_test/util.sh @@ -1,45 +1,29 @@ +#!/bin/bash -sudo(){ +CHAIN_NAME="test" + +sudo() { set -o noglob if [ "$(whoami)" == "root" ] ; then - $* + "$@" else - /usr/bin/sudo $* + /usr/bin/sudo "$@" fi set +o noglob } -# Clean up only when it successes -cleanup() { - for pid in cita-forever cita-jsonrpc cita-auth cita-chain cita-network cita-bft trans_evm cita-executor; do - ps ax | grep ${pid} | grep -v grep | awk '{print $1}' | xargs -n 1 -I % kill -9 % 2>&1 >/dev/null ||true - done - - rm -rf ${BINARY_DIR}/${1:-node}* - rm -rf ${BINARY_DIR}/*.json - sudo tc qdisc del dev lo root> /dev/null 2>&1||true +get_height() { + local id=$1 + local timeout=$2 - pid_file=/tmp/cita_basic-trans_evm.pid - if [ -e ${pid_file} ] ; then - for pid in $(cat ${pid_file}) ; do - kill -9 ${pid} 2>&1 > /dev/null || true - done + if [ ! -n "$timeout" ]; then + timeout=30 fi -} -get_height(){ - if [ $# -ne 1 ] ; then - echo "usage: $0 node_id" - return 1 - fi - id=$1 - timeout=60 # 60 seconds start=$(date +%s) - - while [ 1 ] ; do - height=$(${SOURCE_DIR}/tests/integrate_test/blockNumber.sh 127.0.0.1 $((1337+${id}))) - if [ $? -eq 0 ] ; then - echo ${height} + while true; do + if height=$(blockNumber 127.0.0.1 $((1337+"${id}"))); then + echo "${height}" return 0 fi @@ -50,25 +34,24 @@ get_height(){ fi sleep 1 done - return 1 } -get_peer_count(){ - if [ $# -ne 1 ] ; then - echo "usage: $0 node_id" - return 1 +get_peer_count() { + local id=$1 + local timeout=$2 + local peer_count + local start + local now + + if [ ! -n "$timeout" ]; then + timeout=30 fi - id=$1 - timeout=60 # 60 seconds - start=$(date +%s) - while [ 1 ] ; do - peer_count=$(${SOURCE_DIR}/tests/integrate_test/peerCount.sh 127.0.0.1 $((1337+${id}))) - if [ $? -eq 0 ] ; then - # Remove quotes - peer_count_str=`echo ${peer_count} | sed 's/\"//g'` + start=$(date +%s) - echo ${peer_count_str} + while true; do + if peer_count=$(peerCount 127.0.0.1 $((1337+"${id}"))); then + echo "${peer_count}" return 0 fi @@ -79,210 +62,184 @@ get_peer_count(){ fi sleep 1 done - return 1 } -# output information about time used if exit 0 -check_height_growth () { +check_height_growth() { if [ $# -ne 2 ] ; then - echo "usage: $0 node_id timeout" + echo "usage: $0 node_id old_height" return 1 fi - id=$1 - timeout=$2 # seconds - old=$(get_height ${id}) - if [[ $? -ne 0 ]]; then - echo "failed to get_height(old): ${old}" - return 1 - fi - start=$(date +%s) - while [ 1 ] ; do - new=$(get_height ${id}) - if [[ $? -ne 0 ]] ; then - echo "failed to get_height! old height: ${old} new height: ${new}" - return 1 - fi - - now=$(date +%s) - if [ ${new} -gt $(($old + 2)) ]; then - echo "$((now-start))" + local id=$1 + local old=$2 + local new + if new=$(get_height "${id}"); then + if [ "${new}" -gt "${old}" ]; then + echo "height growth" return 0 fi - if [ $((now-start)) -gt ${timeout} ] ; then - echo "time used: $((now-start)) old height: ${old} new height: ${new}" - return 20 - fi - sleep 1 - done + fi return 1 } # output information about time used if exit 0 -check_peer_count () { +check_peer_count() { if [ $# -ne 3 ] ; then echo "usage: $0 node_id expected_count timeout" return 1 fi - id=$1 - expected_count=$2 - timeout=$3 # seconds + local id=$1 + local expected_count=$2 + local timeout=$3 + local start + local peer_count + local now - if [[ $? -ne 0 ]]; then - echo "failed to get_height(old): ${old}" - return 1 - fi start=$(date +%s) - while [ 1 ] ; do - peer_count=$(get_peer_count ${id}) - if [[ $? -ne 0 ]] ; then - echo "failed to get_peer_count! node id: ${id} expected count: ${expected_count}" - return 1 + while true; do + if peer_count=$(get_peer_count "${id}" "${timeout}"); then + if [ $((peer_count)) -eq $((expected_count)) ]; then + echo "$((now-start))" + return 0 + fi fi - now=$(date +%s) - if [ $((peer_count)) -eq $((expected_count)) ]; then - echo "$((now-start))" - return 0 - fi - if [ $((now-start)) -gt ${timeout} ] ; then - echo "time used: $((now-start)) get peer count: ${peer_count} expected count: ${expected_count}" + if [ $((now-start)) -gt "${timeout}" ] ; then + echo "time used: $((now-start)) \ + get peer count: ${peer_count} \ + expected count: ${expected_count}" return 1 fi sleep 1 done - return 1 } # output information about time used if exit 0 -check_peer_count_max () { +check_peer_count_max() { if [ $# -ne 3 ] ; then echo "usage: $0 node_id expected_count timeout" return 1 fi - id=$1 - max_count=$2 - timeout=$3 # seconds + local id=$1 + local max_count=$2 + local timeout=$3 + local start + local peer_count + local now - if [[ $? -ne 0 ]]; then - echo "failed to get_height(old): ${old}" - return 1 - fi start=$(date +%s) - while [ 1 ] ; do - peer_count=$(get_peer_count ${id}) - if [[ $? -ne 0 ]] ; then - echo "failed to get_peer_count! node id: ${id} expected count: ${expected_count}" - return 1 + while true; do + if peer_count=$(get_peer_count "${id}" "${timeout}"); then + if [ $((peer_count)) -le $((max_count)) ]; then + echo "$((now-start))" + return 0 + fi fi - now=$(date +%s) - if [ $((peer_count)) -le $((max_count)) ]; then - echo "$((now-start))" - return 0 - fi - if [ $((now-start)) -gt ${timeout} ] ; then - echo "time used: $((now-start)) get peer count: ${peer_count} expected count: ${expected_count}" + if [ $((now-start)) -gt "${timeout}" ] ; then + echo "time used: $((now-start)) \ + get peer count: ${peer_count} \ + expected count: ${expected_count}" return 1 fi sleep 1 done - return 1 } -check_height_growth_normal () { +check_height_growth_normal() { if [ $# -ne 2 ] ; then echo "usage: $0 id timeout" return 1 fi - id=$1 - timeout=$2 - start=$(date +%s) - for i in {0..1}; do - msg=$(check_height_growth ${id} ${timeout}) - if [ $? -ne 0 ] ; then - echo "check_height_growth_normal failed id(${id}) timeout(${timeout}) msg(${msg})" - return 1 - fi - if [[ ${msg} -lt ${timeout} ]]; then + local id=$1 + local timeout=$2 + local old + local now + + if old=$(get_height "${id}"); then + start=$(date +%s) + while true; do + if check_height_growth "${id}" "${old}"; then + return 0 + fi now=$(date +%s) - echo "$((now-start))" - return 0 - fi - done - echo "check_height_growth_normal timeout(${timeout}) msg(${msg})" + if [ $((now-start)) -gt "${timeout}" ] ; then + echo "check_height_growth_normal failed id(${id}) timeout(${timeout})" + return 1 + fi + sleep 1 + done + fi + echo "failed to get old height" return 1 } # output information about time used if exit 0 -check_height_sync () { +check_height_sync() { if [ $# -ne 2 ] ; then echo "usage: $0 node_id refer_node_id" return 1 fi - id=$1 - refer=$2 - timeout=180 # seconds - refer_height=$(get_height ${refer}) - if [ $? -ne 0 ] ; then - echo "check_height_sync failed to get_height(refer): ${refer_height}" - return 1 + local id=$1 + local refer=$2 + local timeout=180 + local refer_height + local now + local height + + if refer_height=$(get_height "${refer}"); then + start=$(date +%s) + while true; do + now=$(date +%s) + if [ $((now-start)) -gt ${timeout} ] ; then + echo "check_height_sync timeout(${timeout}) \ + time used $((now-start)) \ + refer height ${refer_height} \ + sync height ${height}" + return 1 + fi + if height=$(get_height "${id}"); then + if [ "${height}" -gt "${refer_height}" ]; then + echo "$((now-start))" + return 0 + fi + fi + done fi - start=$(date +%s) - - while [ 1 ] ; do - height=$(get_height ${id}) - if [ $? -ne 0 ] ; then - echo "check_height_sync failed to get_height(sync): ${height}" - return 1 - fi - now=$(date +%s) - if [ ${height} -gt ${refer_height} ]; then - echo "$((now-start))" - return 0 - fi - - if [ $((now-start)) -gt ${timeout} ] ; then - echo "check_height_sync timeout(${timeout}) time used $((now-start)) refer height ${refer_height} sync height ${height}" - return 1 - fi - sleep 1 - done + echo "check_height_sync failed to get_height(refer): ${refer_height}" return 1 } -check_height_stopped () { +check_height_stopped() { if [ $# -ne 2 ] ; then echo "usage: $0 node_id timeout" return 1 fi - id=$1 - timeout=$2 - old=$(get_height ${id}) - if [ $? -ne 0 ] ; then - echo "check_height_stopped failed to get_height(old): ${old}" - return 1 + local id=$1 + local timeout=$2 + local old + local now + local new + + if old=$(get_height "${id}"); then + start=$(date +%s) + while true; do + now=$(date +%s) + if [ $((now-start)) -gt "${timeout}" ] ; then + echo "$((now-start))" + return 0 + fi + if new=$(get_height "${id}"); then + if [ "$new" -gt "$old" ]; then + echo "check_height_stopped height change from ${old} to ${new}" + return 1 + fi + sleep 1 + continue + fi + done fi - - start=$(date +%s) - while [ 1 ] ; do - now=$(date +%s) - if [ $((now-start)) -gt ${timeout} ] ; then - echo "$((now-start))" - return 0 - fi - new=$(get_height ${id}) - if [ $? -ne 0 ] ; then - echo "check_height_stopped failed to get_height(new): ${new}" - return 1 - fi - if [ $new -gt $(($old + 2)) ]; then - # if two more blocks was generated, it shows cita still reach consensus. - echo "check_height_stopped height change from ${old} to ${new}" - return 1 - fi - sleep 1 - done + echo "check_height_stopped failed to get_height(old): ${old}" return 1 } @@ -291,48 +248,96 @@ set_delay_at_port() { echo "usage: set_delay_at_port port delay" return 1 fi - port=$1 - delay=$2 + local port=$1 + local delay=$2 + # TODO: need more description sudo tc qdisc add dev lo root handle 1: prio bands 4 >/dev/null 2>&1 || true - sudo tc qdisc add dev lo parent 1:4 handle 40: netem delay ${delay}ms >/dev/null 2>&1 || true - sudo tc filter add dev lo protocol ip parent 1:0 prio 4 u32 match ip dport ${port} 0xffff flowid 1:4 >/dev/null 2>&1 || true + sudo tc qdisc add dev lo parent 1:4 handle 40: netem delay "${delay}"ms >/dev/null 2>&1 || true + sudo tc filter add dev lo protocol ip parent 1:0 prio 4 u32 match ip dport "${port}" 0xffff flowid 1:4 >/dev/null 2>&1 || true } + unset_delay_at_port() { if [ $# -ne 1 ] ; then echo "usage: $0 port" return 1 fi - port=$1 + local port=$1 #sudo tc filter del dev lo protocol ip parent 1:0 prio 4 u32 match ip dport ${port} 0xffff flowid 1:4 >/dev/null 2>&1 || true sudo tc qdisc del dev lo root> /dev/null 2>&1||true } -setup_node() { - id=$1 - ./bin/cita setup node/${id} +blockNumber() { + local ip=$1 + local port=$2 + local response + local height + + if [ ! -n "$ip" ]; then + ip="127.0.0.1" + fi + if [ ! -n "$port" ]; then + port=1337 + fi + if response=$(curl -s -X POST -d '{"jsonrpc":"2.0","method":"blockNumber","params":[],"id":2}' $ip:$port); then + height=$(echo "${response}" |jq ".result"|sed 's/\"//g') + if [ "$height" == null ]; then + exit 1 + fi + echo $((height)) + return 0 + fi + echo "failed to get glock number" + return 1 } -start_node() { - id=$1 - ./bin/cita start node/${id} ${debug} +peerCount() { + local ip=$1 + local port=$2 + local response + local count + + if [ ! -n "$ip" ]; then + ip="127.0.0.1" + fi + if [ ! -n "$port" ]; then + port=1337 + fi + if response=$(curl -s -X POST -d '{"jsonrpc":"2.0","method":"peerCount","params":[],"id":2}' $ip:$port); then + count=$(echo "${response}" |jq ".result"|sed 's/\"//g') + if [ "$count" == null ]; then + exit 1 + fi + echo $((count)) + return 0 + fi + echo "failed to get peer count" + return 1 } -stop_node() { - id=$1 - ./bin/cita stop node/${id} +start_nodes() { + local num=$1 + if [ ! -n "$num" ]; then + num=4 + fi + for ((i=0; i&1 + done + for ((i=0; i&1 + done } -stop_all () { - stop_node 0 - stop_node 1 - stop_node 2 - stop_node 3 +config_script() { + ./scripts/create_cita_config.py "$@" > /dev/null 2>&1 } -start_all () { - start_node 0 - start_node 1 - start_node 2 - start_node 3 +create_config() { + local param="create \ + --chain_name $CHAIN_NAME \ + --super_admin 0x4b5ae4567ad5d9fb92bc9afd6a657e6fa13a2523 \ + --nodes 127.0.0.1:4000,127.0.0.1:4001,127.0.0.1:4002,127.0.0.1:4003 \ + $*" + # shellcheck disable=SC2086 + config_script $param } diff --git a/tests/interfaces/config/blockchain.yaml b/tests/interfaces/config/blockchain.yaml index 32f568c7c..2ba792abc 100644 --- a/tests/interfaces/config/blockchain.yaml +++ b/tests/interfaces/config/blockchain.yaml @@ -17,7 +17,7 @@ blocks: - number: 2 transactions: # Create a SimpleStorage contract - # [Source Code]: contracts/HelloWorld.sol + # [Source Code]: tests/contracts/HelloWorld.sol - privkey: 'ef98e68db428906d626cd37782cdfb052ac282132beee53a99948738ea553b4a' # Sender's private key nonce: 0 quota: 200000 @@ -41,7 +41,7 @@ blocks: - number: 4 transactions: # Create a Token contract - # [Source Code]: contracts/ERC20-Token/StandardToken.sol + # [Source Code]: tests/contracts/ERC20-Token/StandardToken.sol - privkey: 'ef98e68db428906d626cd37782cdfb052ac282132beee53a99948738ea553b4a' nonce: 2 quota: 100000 @@ -52,7 +52,7 @@ blocks: - number: 5 transactions: # Create a Token contract - # [Source Code]: contracts/ERC20-Token/StandardToken.sol + # [Source Code]: tests/contracts/ERC20-Token/StandardToken.sol - privkey: 'ef98e68db428906d626cd37782cdfb052ac282132beee53a99948738ea553b4a' nonce: 3 quota: 100000 @@ -65,7 +65,7 @@ blocks: - number: 6 transactions: # Create a Token contract - # [Source Code]: contracts/ERC20-Token/StandardToken.sol + # [Source Code]: tests/contracts/ERC20-Token/StandardToken.sol - privkey: 'ef98e68db428906d626cd37782cdfb052ac282132beee53a99948738ea553b4a' nonce: 4 quota: 100000 @@ -77,7 +77,7 @@ blocks: - number: 7 transactions: - # [Source Code]: contracts/AccountGasLimitReached.sol + # [Source Code]: tests/contracts/AccountGasLimitReached.sol - privkey: 'ef98e68db428906d626cd37782cdfb052ac282132beee53a99948738ea553b4a' nonce: 5 # Should be NotEnoughBaseGas Receipt @@ -88,7 +88,7 @@ blocks: - number: 8 transactions: - # [Source Code]: contracts/AccountGasLimitReached.sol + # [Source Code]: tests/contracts/AccountGasLimitReached.sol - privkey: 'ef98e68db428906d626cd37782cdfb052ac282132beee53a99948738ea553b4a' nonce: 6 # Should be OutOfGas Receipt (1073741824 + 1) @@ -102,7 +102,7 @@ blocks: - number: 10 transactions: - # [Source Code]: contracts/AccountGasLimitReached.sol + # [Source Code]: tests/contracts/AccountGasLimitReached.sol - privkey: 'ef98e68db428906d626cd37782cdfb052ac282132beee53a99948738ea553b4a' nonce: 8 quota: 100000 @@ -114,7 +114,7 @@ blocks: - number: 11 transactions: - # [Source Code]: contracts/Reverted.sol + # [Source Code]: tests/contracts/Reverted.sol - privkey: 'ef98e68db428906d626cd37782cdfb052ac282132beee53a99948738ea553b4a' nonce: 9 # Should be Reverted Receipt @@ -126,7 +126,7 @@ blocks: - number: 12 transactions: # Create a contract - # [Source Code]: contracts/SimpleStorage.sol + # [Source Code]: tests/contracts/SimpleStorage.sol - privkey: 'ef98e68db428906d626cd37782cdfb052ac282132beee53a99948738ea553b4a' nonce: 10 quota: 1000000 @@ -134,7 +134,7 @@ blocks: to: '' data: '608060405234801561001057600080fd5b5060646000819055507f8fb1356be6b2a4e49ee94447eb9dcb8783f51c41dcddfe7919f945017d163bf3336064604051808373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020018281526020019250505060405180910390a161018a806100946000396000f30060806040526004361061004c576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff16806360fe47b1146100515780636d4ce63c1461007e575b600080fd5b34801561005d57600080fd5b5061007c600480360381019080803590602001909291905050506100a9565b005b34801561008a57600080fd5b50610093610155565b6040518082815260200191505060405180910390f35b7fc6d8c0af6d21f291e7c359603aa97e0ed500f04db6e983b9fce75a91c6b8da6b816040518082815260200191505060405180910390a1806000819055507ffd28ec3ec2555238d8ad6f9faf3e4cd10e574ce7e7ef28b73caa53f9512f65b93382604051808373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020018281526020019250505060405180910390a150565b600080549050905600a165627a7a723058200b008257b7c6ae78c1c2bde97f3c72005d0f7063ad98e02a3399ee94642fe7810029' # Create a HelloWorld contract - # [Source Code]: contracts/HelloWorld.sol + # [Source Code]: tests/contracts/HelloWorld.sol - privkey: '00000000b428906d626cd37782cdfb052ac282132beee53a99948738ea553b4a' # Fake Sender's private key nonce: 0 quota: 100000 @@ -149,7 +149,7 @@ blocks: nonce: 11 quota: 200000 valid_until_block: 100 - # In contracts/SimpleStorage.sol + # In tests/contracts/SimpleStorage.sol # Call set(11228899) to: 'a31af83ee35e753a2bb19c2a82468080c2e92eee' data: '60fe47b10000000000000000000000000000000000000000000000000000000011228899' @@ -160,7 +160,7 @@ blocks: nonce: 11 quota: 200000 valid_until_block: 100 - # In contracts/SimpleStorage.sol + # In tests/contracts/SimpleStorage.sol # Call set(11228899) to: 'a31af83ee35e753a2bb19c2a82468080c2e92eee' data: '60fe47b10000000000000000000000000000000000000000000000000000000011228899' @@ -170,8 +170,8 @@ blocks: valid_until_block: 100 # A special address to store contract ABI data to: 'ffffffffffffffffffffffffffffffffff010001' - # Store contracts/SimpleStorage.sol ABI to blockchain + # Store tests/contracts/SimpleStorage.sol ABI to blockchain # Data generated by commands: - # $ solc --abi contracts/SimpleStorage.sol + # $ solc --abi tests/contracts/SimpleStorage.sol # $ ethabi params -v string "[data generated by above command]" data: 'a31af83ee35e753a2bb19c2a82468080c2e92eee0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000030f5b7b22636f6e7374616e74223a66616c73652c22696e70757473223a5b7b226e616d65223a2278222c2274797065223a2275696e74323536227d5d2c226e616d65223a22736574222c226f757470757473223a5b5d2c2270617961626c65223a66616c73652c2273746174654d75746162696c697479223a226e6f6e70617961626c65222c2274797065223a2266756e6374696f6e227d2c7b22636f6e7374616e74223a747275652c22696e70757473223a5b5d2c226e616d65223a22676574222c226f757470757473223a5b7b226e616d65223a22222c2274797065223a2275696e74323536227d5d2c2270617961626c65223a66616c73652c2273746174654d75746162696c697479223a2276696577222c2274797065223a2266756e6374696f6e227d2c7b22696e70757473223a5b5d2c2270617961626c65223a66616c73652c2273746174654d75746162696c697479223a226e6f6e70617961626c65222c2274797065223a22636f6e7374727563746f72227d2c7b22616e6f6e796d6f7573223a66616c73652c22696e70757473223a5b7b22696e6465786564223a66616c73652c226e616d65223a22222c2274797065223a2261646472657373227d2c7b22696e6465786564223a66616c73652c226e616d65223a22222c2274797065223a2275696e74323536227d5d2c226e616d65223a22496e6974222c2274797065223a226576656e74227d2c7b22616e6f6e796d6f7573223a66616c73652c22696e70757473223a5b7b22696e6465786564223a66616c73652c226e616d65223a22222c2274797065223a2261646472657373227d2c7b22696e6465786564223a66616c73652c226e616d65223a22222c2274797065223a2275696e74323536227d5d2c226e616d65223a22536574222c2274797065223a226576656e74227d2c7b22616e6f6e796d6f7573223a66616c73652c22696e70757473223a5b7b22696e6465786564223a66616c73652c226e616d65223a22222c2274797065223a2275696e74323536227d5d2c226e616d65223a2253746f726564222c2274797065223a226576656e74227d5d0000000000000000000000000000000000' diff --git a/tests/interfaces/config/contracts/AccountGasLimitReached.sol b/tests/interfaces/config/contracts/AccountGasLimitReached.sol deleted file mode 100644 index 1fa06461c..000000000 --- a/tests/interfaces/config/contracts/AccountGasLimitReached.sol +++ /dev/null @@ -1,11 +0,0 @@ -pragma solidity ^0.4.24; - -contract AccountGasLimitReached { - bytes32[] balance; - - constructor() public { - for (uint i = 0; i < 99999999999; i++) { - balance.push(keccak256(abi.encodePacked(i))); - } - } -} diff --git a/tests/interfaces/config/contracts/ERC20-Token/BasicToken.sol b/tests/interfaces/config/contracts/ERC20-Token/BasicToken.sol deleted file mode 100644 index 6a748a2a4..000000000 --- a/tests/interfaces/config/contracts/ERC20-Token/BasicToken.sol +++ /dev/null @@ -1,51 +0,0 @@ -pragma solidity ^0.4.24; - - -import "./ERC20Basic.sol"; -import "./SafeMath.sol"; - - -/** - * @title Basic token - * @dev Basic version of StandardToken, with no allowances. - */ -contract BasicToken is ERC20Basic { - using SafeMath for uint256; - - mapping(address => uint256) balances; - - uint256 totalSupply_; - - /** - * @dev total number of tokens in existence - */ - function totalSupply() public view returns (uint256) { - return totalSupply_; - } - - /** - * @dev transfer token for a specified address - * @param _to The address to transfer to. - * @param _value The amount to be transferred. - */ - function transfer(address _to, uint256 _value) public returns (bool) { - require(_to != address(0)); - require(_value <= balances[msg.sender]); - - // SafeMath.sub will throw if there is not enough balance. - balances[msg.sender] = balances[msg.sender].sub(_value); - balances[_to] = balances[_to].add(_value); - emit Transfer(msg.sender, _to, _value); - return true; - } - - /** - * @dev Gets the balance of the specified address. - * @param _owner The address to query the the balance of. - * @return An uint256 representing the amount owned by the passed address. - */ - function balanceOf(address _owner) public view returns (uint256 balance) { - return balances[_owner]; - } - -} diff --git a/tests/interfaces/config/contracts/ERC20-Token/ERC20.sol b/tests/interfaces/config/contracts/ERC20-Token/ERC20.sol deleted file mode 100644 index 533e53ea5..000000000 --- a/tests/interfaces/config/contracts/ERC20-Token/ERC20.sol +++ /dev/null @@ -1,15 +0,0 @@ -pragma solidity ^0.4.24; - -import "./ERC20Basic.sol"; - - -/** - * @title ERC20 interface - * @dev see https://github.com/ethereum/EIPs/issues/20 - */ -contract ERC20 is ERC20Basic { - function allowance(address owner, address spender) public view returns (uint256); - function transferFrom(address from, address to, uint256 value) public returns (bool); - function approve(address spender, uint256 value) public returns (bool); - event Approval(address indexed owner, address indexed spender, uint256 value); -} diff --git a/tests/interfaces/config/contracts/ERC20-Token/ERC20Basic.sol b/tests/interfaces/config/contracts/ERC20-Token/ERC20Basic.sol deleted file mode 100644 index c326601de..000000000 --- a/tests/interfaces/config/contracts/ERC20-Token/ERC20Basic.sol +++ /dev/null @@ -1,14 +0,0 @@ -pragma solidity ^0.4.24; - - -/** - * @title ERC20Basic - * @dev Simpler version of ERC20 interface - * @dev see https://github.com/ethereum/EIPs/issues/179 - */ -contract ERC20Basic { - function totalSupply() public view returns (uint256); - function balanceOf(address who) public view returns (uint256); - function transfer(address to, uint256 value) public returns (bool); - event Transfer(address indexed from, address indexed to, uint256 value); -} diff --git a/tests/interfaces/config/contracts/ERC20-Token/SafeMath.sol b/tests/interfaces/config/contracts/ERC20-Token/SafeMath.sol deleted file mode 100644 index c347da189..000000000 --- a/tests/interfaces/config/contracts/ERC20-Token/SafeMath.sol +++ /dev/null @@ -1,48 +0,0 @@ -pragma solidity ^0.4.24; - - -/** - * @title SafeMath - * @dev Math operations with safety checks that throw on error - */ -library SafeMath { - - /** - * @dev Multiplies two numbers, throws on overflow. - */ - function mul(uint256 a, uint256 b) internal pure returns (uint256) { - if (a == 0) { - return 0; - } - uint256 c = a * b; - assert(c / a == b); - return c; - } - - /** - * @dev Integer division of two numbers, truncating the quotient. - */ - function div(uint256 a, uint256 b) internal pure returns (uint256) { - // assert(b > 0); // Solidity automatically throws when dividing by 0 - uint256 c = a / b; - // assert(a == b * c + a % b); // There is no case in which this doesn't hold - return c; - } - - /** - * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). - */ - function sub(uint256 a, uint256 b) internal pure returns (uint256) { - assert(b <= a); - return a - b; - } - - /** - * @dev Adds two numbers, throws on overflow. - */ - function add(uint256 a, uint256 b) internal pure returns (uint256) { - uint256 c = a + b; - assert(c >= a); - return c; - } -} diff --git a/tests/interfaces/config/contracts/ERC20-Token/StandardToken.sol b/tests/interfaces/config/contracts/ERC20-Token/StandardToken.sol deleted file mode 100644 index 6c816aba4..000000000 --- a/tests/interfaces/config/contracts/ERC20-Token/StandardToken.sol +++ /dev/null @@ -1,100 +0,0 @@ -pragma solidity ^0.4.24; - -import "./BasicToken.sol"; -import "./ERC20.sol"; - - -/** - * @title Standard ERC20 token - * - * @dev Implementation of the basic standard token. - * @dev https://github.com/ethereum/EIPs/issues/20 - * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol - */ -contract StandardToken is ERC20, BasicToken { - - mapping (address => mapping (address => uint256)) internal allowed; - - - /** - * @dev Transfer tokens from one address to another - * @param _from address The address which you want to send tokens from - * @param _to address The address which you want to transfer to - * @param _value uint256 the amount of tokens to be transferred - */ - function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { - require(_to != address(0)); - require(_value <= balances[_from]); - require(_value <= allowed[_from][msg.sender]); - - balances[_from] = balances[_from].sub(_value); - balances[_to] = balances[_to].add(_value); - allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); - emit Transfer(_from, _to, _value); - return true; - } - - /** - * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. - * - * Beware that changing an allowance with this method brings the risk that someone may use both the old - * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this - * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: - * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 - * @param _spender The address which will spend the funds. - * @param _value The amount of tokens to be spent. - */ - function approve(address _spender, uint256 _value) public returns (bool) { - allowed[msg.sender][_spender] = _value; - emit Approval(msg.sender, _spender, _value); - return true; - } - - /** - * @dev Function to check the amount of tokens that an owner allowed to a spender. - * @param _owner address The address which owns the funds. - * @param _spender address The address which will spend the funds. - * @return A uint256 specifying the amount of tokens still available for the spender. - */ - function allowance(address _owner, address _spender) public view returns (uint256) { - return allowed[_owner][_spender]; - } - - /** - * @dev Increase the amount of tokens that an owner allowed to a spender. - * - * approve should be called when allowed[_spender] == 0. To increment - * allowed value is better to use this function to avoid 2 calls (and wait until - * the first transaction is mined) - * From MonolithDAO Token.sol - * @param _spender The address which will spend the funds. - * @param _addedValue The amount of tokens to increase the allowance by. - */ - function increaseApproval(address _spender, uint _addedValue) public returns (bool) { - allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); - emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); - return true; - } - - /** - * @dev Decrease the amount of tokens that an owner allowed to a spender. - * - * approve should be called when allowed[_spender] == 0. To decrement - * allowed value is better to use this function to avoid 2 calls (and wait until - * the first transaction is mined) - * From MonolithDAO Token.sol - * @param _spender The address which will spend the funds. - * @param _subtractedValue The amount of tokens to decrease the allowance by. - */ - function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { - uint oldValue = allowed[msg.sender][_spender]; - if (_subtractedValue > oldValue) { - allowed[msg.sender][_spender] = 0; - } else { - allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); - } - emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); - return true; - } - -} diff --git a/tests/interfaces/config/contracts/HelloWorld.sol b/tests/interfaces/config/contracts/HelloWorld.sol deleted file mode 100644 index 1fad1cdcc..000000000 --- a/tests/interfaces/config/contracts/HelloWorld.sol +++ /dev/null @@ -1,10 +0,0 @@ -pragma solidity ^0.4.24; - -contract HelloWorld { - uint balance; - - function update(uint amount) public returns (address, uint) { - balance += amount; - return (msg.sender, balance); - } -} diff --git a/tests/interfaces/config/contracts/Reverted.sol b/tests/interfaces/config/contracts/Reverted.sol deleted file mode 100644 index 1b5b0fd1a..000000000 --- a/tests/interfaces/config/contracts/Reverted.sol +++ /dev/null @@ -1,7 +0,0 @@ -pragma solidity ^0.4.24; - -contract RevertedDemo { - constructor() public { - assert(false); - } -} diff --git a/tests/interfaces/config/contracts/SimpleStorage.sol b/tests/interfaces/config/contracts/SimpleStorage.sol deleted file mode 100644 index 06e292837..000000000 --- a/tests/interfaces/config/contracts/SimpleStorage.sol +++ /dev/null @@ -1,23 +0,0 @@ -pragma solidity ^0.4.24; - -contract SimpleStorage { - uint storedData; - event Init(address, uint); - event Set(address, uint); - event Stored(uint); - - constructor() public { - storedData = 100; - emit Init(msg.sender, 100); - } - - function set(uint x) public { - emit Stored(x); - storedData = x; - emit Set(msg.sender, x); - } - - function get() public constant returns (uint) { - return storedData; - } -} diff --git a/tests/json_test/Cargo.toml b/tests/json-test/Cargo.toml similarity index 96% rename from tests/json_test/Cargo.toml rename to tests/json-test/Cargo.toml index 41a4e879f..98d687ba1 100644 --- a/tests/json_test/Cargo.toml +++ b/tests/json-test/Cargo.toml @@ -1,5 +1,5 @@ [package] -name = "state_test" +name = "state-test" version = "0.1.0" authors = ["Cryptape Technologies "] edition = "2018" diff --git a/tests/json_test/README.md b/tests/json-test/README.md similarity index 100% rename from tests/json_test/README.md rename to tests/json-test/README.md diff --git a/tests/json_test/src/helper.rs b/tests/json-test/src/helper.rs similarity index 100% rename from tests/json_test/src/helper.rs rename to tests/json-test/src/helper.rs diff --git a/tests/json_test/src/json/mod.rs b/tests/json-test/src/json/mod.rs similarity index 100% rename from tests/json_test/src/json/mod.rs rename to tests/json-test/src/json/mod.rs diff --git a/tests/json_test/src/json/state.rs b/tests/json-test/src/json/state.rs similarity index 100% rename from tests/json_test/src/json/state.rs rename to tests/json-test/src/json/state.rs diff --git a/tests/json_test/src/json/vm.rs b/tests/json-test/src/json/vm.rs similarity index 100% rename from tests/json_test/src/json/vm.rs rename to tests/json-test/src/json/vm.rs diff --git a/tests/json_test/src/lib.rs b/tests/json-test/src/lib.rs similarity index 100% rename from tests/json_test/src/lib.rs rename to tests/json-test/src/lib.rs diff --git a/tests/json_test/src/state_test.rs b/tests/json-test/src/state_test.rs similarity index 100% rename from tests/json_test/src/state_test.rs rename to tests/json-test/src/state_test.rs diff --git a/tests/json_test/src/vm_test.rs b/tests/json-test/src/vm_test.rs similarity index 100% rename from tests/json_test/src/vm_test.rs rename to tests/json-test/src/vm_test.rs diff --git a/tools/create-genesis/Cargo.toml b/tools/create-genesis/Cargo.toml new file mode 100644 index 000000000..c3875de7b --- /dev/null +++ b/tools/create-genesis/Cargo.toml @@ -0,0 +1,22 @@ +[package] +name = "create-genesis" +version = "0.1.0" +authors = ["Cryptape Technologies "] +edition = "2018" + +[dependencies] +serde = { version = "1.0", features = ["derive"] } +serde_yaml = "0.8" +json = "0.11.13" +serde_json = "1.0.39" +ethabi = "7.0.0" +ethereum-types = "0.5.2" +hex = "0.3" +tiny-keccak = "1.4.2" +libsecp256k1 = "0.2.2" +clap = "2.33.0" + +libproto = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } + +core-executor = { path="../../cita-executor/core", default-features = false} +evm = { path="../../cita-executor/evm"} diff --git a/tools/create-genesis/src/common.rs b/tools/create-genesis/src/common.rs new file mode 100644 index 000000000..23302c4aa --- /dev/null +++ b/tools/create-genesis/src/common.rs @@ -0,0 +1,59 @@ +use ethereum_types::Public; +use evm::cita_types::{Address, U256}; + +use core_executor::cita_db::{journaldb, kvdb, KeyValueDB}; +use core_executor::db; +use core_executor::state::State; +use core_executor::state_db::StateDB; +use std::sync::Arc; + +pub fn clean_0x(s: &str) -> &str { + if s.starts_with("0x") { + &s[2..] + } else { + s + } +} + +pub fn string_2_bytes(value: String) -> Vec { + let v = Box::leak(value.into_boxed_str()); + let v = clean_0x(v); + hex::decode(v).unwrap() +} + +pub fn string_2_u256(value: String) -> U256 { + let v = Box::leak(value.into_boxed_str()); + let v = clean_0x(v); + U256::from(v) +} + +pub fn public_2_address(public: &Public) -> Address { + let hash = tiny_keccak::keccak256(&public.0); + let mut result = Address::default(); + result.copy_from_slice(&hash[12..]); + result +} + +pub fn secret_2_address(secret: &str) -> Address { + let a = hex::decode(clean_0x(secret)).unwrap(); + let secret_key = secp256k1::SecretKey::parse_slice(a.as_slice()).unwrap(); + let public_key = secp256k1::PublicKey::from_secret_key(&secret_key); + let serialized = public_key.serialize(); + let public = Public::from_slice(&serialized[1..65]); + public_2_address(&public) +} + +pub fn get_temp_state() -> State { + let state_db = get_temp_state_db(); + State::new(state_db, 0.into(), Default::default()) +} + +pub fn new_db() -> Arc { + Arc::new(kvdb::in_memory(8)) +} + +pub fn get_temp_state_db() -> StateDB { + let db = new_db(); + let journal_db = journaldb::new(db, journaldb::Algorithm::Archive, db::COL_STATE); + StateDB::new(journal_db, 5 * 1024 * 1024) +} diff --git a/tools/create-genesis/src/contracts.rs b/tools/create-genesis/src/contracts.rs new file mode 100644 index 000000000..a5835ffa4 --- /dev/null +++ b/tools/create-genesis/src/contracts.rs @@ -0,0 +1,573 @@ +use crate::common::clean_0x; +use ethabi::Token; +use ethereum_types::Address; +use serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; +use std::fs::File; +use std::str::FromStr; +use tiny_keccak::keccak256; + +#[derive(Debug, PartialEq, Serialize, Deserialize)] +pub struct ContractsData { + #[serde(rename = "NormalContracts")] + pub normal_contracts: NormalContracts, + + #[serde(rename = "PermissionContracts")] + pub permission_contracts: PermissionContracts, +} + +impl ContractsData { + pub fn load_contract_list(path: &str) -> ContractsData { + let f = File::open(path).expect("failed to open file"); + serde_yaml::from_reader(f).unwrap() + } +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct NormalContracts { + #[serde(rename = "SysConfig")] + pub sys_config: Info, + + #[serde(rename = "NodeManager")] + pub node_manager: Info, + + #[serde(rename = "ChainManager")] + pub chain_manager: Info, + + #[serde(rename = "QuotaManager")] + pub quota_manager: Info, + + #[serde(rename = "PermissionManagement")] + pub permission_management: Info, + + #[serde(rename = "PermissionCreator")] + pub permission_creator: Info, + + #[serde(rename = "Authorization")] + pub authorization: Info, + + #[serde(rename = "RoleManagement")] + pub role_management: Info, + + #[serde(rename = "RoleCreator")] + pub role_creator: Info, + + #[serde(rename = "Group")] + pub group: Info, + + #[serde(rename = "GroupManagement")] + pub group_management: Info, + + #[serde(rename = "GroupCreator")] + pub group_creator: Info, + + #[serde(rename = "Admin")] + pub admin: Info, + + #[serde(rename = "RoleAuth")] + pub role_auth: Info, + + #[serde(rename = "BatchTx")] + pub batch_tx: Info, + + #[serde(rename = "EmergencyIntervention")] + pub emergency_intervention: Info, + + #[serde(rename = "PriceManager")] + pub price_manager: Info, + + #[serde(rename = "VersionManager")] + pub version_manager: Info, + + #[serde(rename = "AllGroups")] + pub all_groups: Info, + + #[serde(rename = "AutoExec")] + pub auto_exec: Info, +} + +impl NormalContracts { + pub fn list(&self) -> BTreeMap<&'static str, Info> { + let mut normal_contracts = BTreeMap::new(); + normal_contracts.insert("SysConfig", self.sys_config.clone()); + normal_contracts.insert("NodeManager", self.node_manager.clone()); + normal_contracts.insert("ChainManager", self.chain_manager.clone()); + normal_contracts.insert("QuotaManager", self.quota_manager.clone()); + normal_contracts.insert("PermissionManagement", self.permission_management.clone()); + normal_contracts.insert("PermissionCreator", self.permission_creator.clone()); + normal_contracts.insert("Authorization", self.authorization.clone()); + normal_contracts.insert("RoleManagement", self.role_management.clone()); + normal_contracts.insert("RoleCreator", self.role_creator.clone()); + normal_contracts.insert("Group", self.group.clone()); + normal_contracts.insert("GroupManagement", self.group_management.clone()); + normal_contracts.insert("GroupCreator", self.group_creator.clone()); + normal_contracts.insert("Admin", self.admin.clone()); + normal_contracts.insert("RoleAuth", self.role_auth.clone()); + normal_contracts.insert("BatchTx", self.batch_tx.clone()); + normal_contracts.insert("EmergencyIntervention", self.emergency_intervention.clone()); + normal_contracts.insert("PriceManager", self.price_manager.clone()); + normal_contracts.insert("VersionManager", self.version_manager.clone()); + normal_contracts.insert("AllGroups", self.all_groups.clone()); + normal_contracts.insert("AutoExec", self.auto_exec.clone()); + normal_contracts + } +} + +#[derive(Debug, PartialEq, Serialize, Deserialize, Clone)] +pub struct Info { + pub address: String, + pub file: String, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct PermissionContracts { + pub file: String, + pub basic: Basic, + pub contracts: Contracts, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Basic { + #[serde(rename = "sendTx")] + pub send_tx: BasicInfo, + + #[serde(rename = "createContract")] + pub create_contract: BasicInfo, +} + +impl Basic { + pub fn list(&self) -> BTreeMap<&'static str, BasicInfo> { + let mut basic = BTreeMap::new(); + basic.insert("sendTx", self.send_tx.clone()); + basic.insert("createContract", self.create_contract.clone()); + basic + } + + pub fn as_params(&self, name: &str) -> Vec { + let mut tokens = Vec::new(); + if let Some(info) = self.list().get(name) { + tokens.push(Token::FixedBytes(String::from(name).into_bytes())); + let mut conts = Vec::new(); + let addr = Address::from_str(clean_0x(&info.address)).unwrap(); + conts.push(Token::Address(addr)); + let mut funcs = Vec::new(); + funcs.push(Token::FixedBytes(vec![0, 0, 0, 0])); + + tokens.push(Token::Array(conts)); + tokens.push(Token::Array(funcs)); + } + tokens + } +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct BasicInfo { + pub address: String, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Contracts { + #[serde(rename = "newPermission")] + pub new_permission: ContractsInfo, + + #[serde(rename = "deletePermission")] + pub delete_permission: ContractsInfo, + + #[serde(rename = "updatePermission")] + pub update_permission: ContractsInfo, + + #[serde(rename = "setAuth")] + pub set_auth: ContractsInfo, + + #[serde(rename = "cancelAuth")] + pub cancel_auth: ContractsInfo, + + #[serde(rename = "newRole")] + pub new_role: ContractsInfo, + + #[serde(rename = "deleteRole")] + pub delete_role: ContractsInfo, + + #[serde(rename = "updateRole")] + pub update_role: ContractsInfo, + + #[serde(rename = "setRole")] + pub set_role: ContractsInfo, + + #[serde(rename = "cancelRole")] + pub cancel_role: ContractsInfo, + + #[serde(rename = "newGroup")] + pub new_group: ContractsInfo, + + #[serde(rename = "deleteGroup")] + pub delete_group: ContractsInfo, + + #[serde(rename = "updateGroup")] + pub update_group: ContractsInfo, + + #[serde(rename = "newNode")] + pub new_node: ContractsInfo, + + #[serde(rename = "deleteNode")] + pub delete_node: ContractsInfo, + + #[serde(rename = "updateNode")] + pub update_node: ContractsInfo, + + #[serde(rename = "accountQuota")] + pub account_quota: ContractsInfo, + + #[serde(rename = "blockQuota")] + pub block_quota: ContractsInfo, + + #[serde(rename = "batchTx")] + pub batch_tx: ContractsInfo, + + #[serde(rename = "emergencyIntervention")] + pub emergency_intervention: ContractsInfo, + + #[serde(rename = "quotaPrice")] + pub quota_price: ContractsInfo, + + #[serde(rename = "version")] + pub version: ContractsInfo, +} + +impl Contracts { + pub fn list(&self) -> BTreeMap<&'static str, ContractsInfo> { + let mut contracts = BTreeMap::new(); + contracts.insert("newPermission", self.new_permission.clone()); + contracts.insert("deletePermission", self.delete_permission.clone()); + contracts.insert("updatePermission", self.update_permission.clone()); + contracts.insert("setAuth", self.set_auth.clone()); + contracts.insert("cancelAuth", self.cancel_auth.clone()); + contracts.insert("newRole", self.new_role.clone()); + contracts.insert("deleteRole", self.delete_role.clone()); + contracts.insert("updateRole", self.update_role.clone()); + contracts.insert("setRole", self.set_role.clone()); + contracts.insert("cancelRole", self.cancel_role.clone()); + contracts.insert("newGroup", self.new_group.clone()); + contracts.insert("deleteGroup", self.delete_group.clone()); + contracts.insert("updateGroup", self.update_group.clone()); + contracts.insert("newNode", self.new_node.clone()); + contracts.insert("deleteNode", self.delete_node.clone()); + contracts.insert("updateNode", self.update_node.clone()); + contracts.insert("accountQuota", self.account_quota.clone()); + contracts.insert("blockQuota", self.block_quota.clone()); + contracts.insert("batchTx", self.batch_tx.clone()); + contracts.insert("emergencyIntervention", self.emergency_intervention.clone()); + contracts.insert("quotaPrice", self.quota_price.clone()); + contracts.insert("version", self.version.clone()); + contracts + } + + pub fn as_params(&self, normal_contracts: &NormalContracts, name: &str) -> Vec { + let mut tokens = Vec::new(); + if let Some(info) = self.list().get(name) { + tokens.push(Token::FixedBytes(String::from(name).into_bytes())); + let (conts, funcs) = info.get_contract_info(normal_contracts); + tokens.push(Token::Array(conts)); + tokens.push(Token::Array(funcs)); + } + tokens + } +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct ContractsInfo { + pub address: String, + pub contracts: Vec, + pub functions: Vec, +} + +impl ContractsInfo { + pub fn get_contract_info( + &self, + normal_contracts: &NormalContracts, + ) -> (Vec, Vec) { + let mut conts = Vec::new(); + let reference = normal_contracts.list(); + for a in self.contracts.iter() { + let contract_info = &reference[a.as_str()]; + let address = Address::from_str(clean_0x(&contract_info.address)).unwrap(); + conts.push(Token::Address(address)); + } + + let mut funcs = Vec::new(); + for f in self.functions.iter() { + let func = keccak256(f.as_bytes()).to_vec(); + funcs.push(Token::FixedBytes(func[0..4].to_vec())); + } + (conts, funcs) + } +} +#[cfg(test)] +mod tests { + use super::ContractsData; + + #[test] + pub fn test_contracts() { + let contracts_string = r#" + NormalContracts: + SysConfig: + address: '0xffffffffffffffffffffffffffffffffff020000' + file: system/SysConfig.sol + NodeManager: + address: '0xffffffffffffffffffffffffffffffffff020001' + file: system/NodeManager.sol + ChainManager: + address: '0xffffffffffffffffffffffffffffffffff020002' + file: system/ChainManager.sol + QuotaManager: + address: '0xffffffffffffffffffffffffffffffffff020003' + file: system/QuotaManager.sol + PermissionManagement: + address: '0xffffffffffffffffffffffffffffffffff020004' + file: permission_management/PermissionManagement.sol + PermissionCreator: + address: '0xffffffffffffffffffffffffffffffffff020005' + file: permission_management/PermissionCreator.sol + Authorization: + address: '0xffffffffffffffffffffffffffffffffff020006' + file: permission_management/Authorization.sol + RoleManagement: + address: '0xffffffffffffffffffffffffffffffffff020007' + file: role_management/RoleManagement.sol + RoleCreator: + address: '0xffffffffffffffffffffffffffffffffff020008' + file: role_management/RoleCreator.sol + Group: + address: '0xffffffffffffffffffffffffffffffffff020009' + file: user_management/Group.sol + GroupManagement: + address: '0xffffffffffffffffffffffffffffffffff02000a' + file: user_management/GroupManagement.sol + GroupCreator: + address: '0xffffffffffffffffffffffffffffffffff02000b' + file: user_management/GroupCreator.sol + Admin: + address: '0xffffffffffffffffffffffffffffffffff02000c' + file: common/Admin.sol + RoleAuth: + address: '0xffffffffffffffffffffffffffffffffff02000d' + file: role_management/RoleAuth.sol + BatchTx: + address: '0xffffffffffffffffffffffffffffffffff02000e' + file: system/BatchTx.sol + EmergencyIntervention: + address: '0xffffffffffffffffffffffffffffffffff02000f' + file: system/EmergencyIntervention.sol + PriceManager: + address: '0xffffffffffffffffffffffffffffffffff020010' + file: system/PriceManager.sol + VersionManager: + address: '0xffffffffffffffffffffffffffffffffff020011' + file: system/VersionManager.sol + AllGroups: + address: '0xffffffffffffffffffffffffffffffffff020012' + file: user_management/AllGroups.sol + AutoExec: + address: '0xffffffffffffffffffffffffffffffffff020013' + file: system/AutoExec.sol + + PermissionContracts: + file: permission_management/Permission.sol + basic: + sendTx: + address: '0xffffffffffffffffffffffffffffffffff021000' + createContract: + address: '0xffffffffffffffffffffffffffffffffff021001' + contracts: + newPermission: + address: '0xffffffffffffffffffffffffffffffffff021010' + contracts: + - PermissionManagement + functions: + - 'newPermission(bytes32,address[],bytes4[])' + deletePermission: + address: '0xffffffffffffffffffffffffffffffffff021011' + contracts: + - PermissionManagement + functions: + - 'deletePermission(address)' + updatePermission: + address: '0xffffffffffffffffffffffffffffffffff021012' + contracts: + - PermissionManagement + - PermissionManagement + - PermissionManagement + functions: + - 'addResources(address,address[],bytes4[])' + - 'deleteResources(address,address[],bytes4[])' + - 'updatePermissionName(address,bytes32)' + setAuth: + address: '0xffffffffffffffffffffffffffffffffff021013' + contracts: + - PermissionManagement + - PermissionManagement + functions: + - 'setAuthorization(address,address)' + - 'setAuthorizations(address,address[])' + cancelAuth: + address: '0xffffffffffffffffffffffffffffffffff021014' + contracts: + - PermissionManagement + - PermissionManagement + - PermissionManagement + functions: + - 'cancelAuthorization(address,address)' + - 'clearAuthorization(address)' + - 'cancelAuthorizations(address,address[])' + newRole: + address: '0xffffffffffffffffffffffffffffffffff021015' + contracts: + - RoleManagement + functions: + - 'newRole(bytes32,address[])' + deleteRole: + address: '0xffffffffffffffffffffffffffffffffff021016' + contracts: + - RoleManagement + functions: + - 'deleteRole(address)' + updateRole: + address: '0xffffffffffffffffffffffffffffffffff021017' + contracts: + - RoleManagement + - RoleManagement + - RoleManagement + functions: + - 'addPermissions(address,address[])' + - 'deletePermissions(address,address[])' + - 'updateRoleName(address,bytes32)' + setRole: + address: '0xffffffffffffffffffffffffffffffffff021018' + contracts: + - RoleManagement + functions: + - 'setRole(address,address)' + cancelRole: + address: '0xffffffffffffffffffffffffffffffffff021019' + contracts: + - RoleManagement + - RoleManagement + functions: + - 'cancelRole(address,address)' + - 'clearRole(address)' + newGroup: + address: '0xffffffffffffffffffffffffffffffffff02101a' + contracts: + - GroupManagement + functions: + - 'newGroup(address,bytes32,address[])' + deleteGroup: + address: '0xffffffffffffffffffffffffffffffffff02101b' + contracts: + - GroupManagement + functions: + - 'deleteGroup(address,address)' + updateGroup: + address: '0xffffffffffffffffffffffffffffffffff02101c' + contracts: + - GroupManagement + - GroupManagement + - GroupManagement + functions: + - 'addAccounts(address,address,address[])' + - 'deleteAccounts(address,address,address[])' + - 'updateGroupName(address,address,bytes32)' + newNode: + address: '0xffffffffffffffffffffffffffffffffff021020' + contracts: + - NodeManager + functions: + - 'approveNode(address)' + deleteNode: + address: '0xffffffffffffffffffffffffffffffffff021021' + contracts: + - NodeManager + functions: + - 'deleteNode(address)' + updateNode: + address: '0xffffffffffffffffffffffffffffffffff021022' + contracts: + - NodeManager + functions: + - 'setStake(address,uint64)' + accountQuota: + address: '0xffffffffffffffffffffffffffffffffff021023' + contracts: + - QuotaManager + - QuotaManager + functions: + - 'setDefaultAQL(uint256)' + - 'setAQL(address,uint256)' + blockQuota: + address: '0xffffffffffffffffffffffffffffffffff021024' + contracts: + - QuotaManager + functions: + - 'setBQL(uint256)' + batchTx: + address: '0xffffffffffffffffffffffffffffffffff021025' + contracts: + - BatchTx + functions: + - 'multiTxs(bytes)' + emergencyIntervention: + address: '0xffffffffffffffffffffffffffffffffff021026' + contracts: + - EmergencyIntervention + functions: + - 'setState(bool)' + quotaPrice: + address: '0xffffffffffffffffffffffffffffffffff021027' + contracts: + - PriceManager + functions: + - 'setQuotaPrice(uint256)' + version: + address: '0xffffffffffffffffffffffffffffffffff021028' + contracts: + - VersionManager + functions: + - 'setVersion(uint32)' + "#; + let contracts: ContractsData = serde_yaml::from_str(&contracts_string).unwrap(); + assert_eq!( + contracts.normal_contracts.sys_config.address, + String::from("0xffffffffffffffffffffffffffffffffff020000") + ); + assert_eq!( + contracts.normal_contracts.sys_config.file, + String::from("system/SysConfig.sol") + ); + assert_eq!( + contracts.normal_contracts.auto_exec.address, + String::from("0xffffffffffffffffffffffffffffffffff020013") + ); + assert_eq!( + contracts.normal_contracts.auto_exec.file, + String::from("system/AutoExec.sol") + ); + + assert_eq!( + contracts.permission_contracts.file, + String::from("permission_management/Permission.sol") + ); + assert_eq!( + contracts.permission_contracts.basic.send_tx.address, + String::from("0xffffffffffffffffffffffffffffffffff021000") + ); + + assert_eq!( + contracts + .permission_contracts + .contracts + .new_permission + .address, + String::from("0xffffffffffffffffffffffffffffffffff021010") + ); + } +} diff --git a/tools/create-genesis/src/genesis.rs b/tools/create-genesis/src/genesis.rs new file mode 100644 index 000000000..2fc41a552 --- /dev/null +++ b/tools/create-genesis/src/genesis.rs @@ -0,0 +1,206 @@ +use crate::common::{clean_0x, string_2_bytes}; +use crate::contracts::ContractsData; +use crate::miner::Miner; +use crate::params::InitData; +use crate::solc::Solc; +use ethabi::Contract; +use evm::cita_types::U256; +use json; +use serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; +use std::fs::File; +use std::io::Write; +use std::path::Path; +use std::str::FromStr; + +pub struct GenesisCreator<'a> { + pub contract_dir: &'a str, + pub contract_docs_dir: &'a str, + pub genesis_path: &'a str, + pub timestamp: u64, + pub init_token: &'a str, + pub prevhash: &'a str, + pub contract_args: InitData, + pub contract_list: ContractsData, + pub accounts: BTreeMap, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct Account { + pub nonce: U256, + pub code: String, + pub storage: BTreeMap, + pub value: U256, +} + +#[derive(Serialize, Deserialize)] +pub struct Genesis { + pub timestamp: u64, + pub prevhash: String, + pub alloc: BTreeMap, +} + +impl Default for Genesis { + fn default() -> Self { + Genesis { + timestamp: 0, + prevhash: String::default(), + alloc: BTreeMap::new(), + } + } +} + +impl<'a> GenesisCreator<'a> { + pub fn new( + contract_dir: &'a str, + contract_docs_dir: &'a str, + params_path: &'a str, + genesis_path: &'a str, + timestamp: u64, + init_token: &'a str, + prevhash: &'a str, + ) -> Self { + let params = InitData::load_contract_args(params_path); + let contracts_list = contract_dir.to_owned() + "/contracts.yml"; + let constracts = ContractsData::load_contract_list(&contracts_list); + + GenesisCreator { + contract_dir, + contract_docs_dir, + genesis_path, + timestamp, + init_token, + prevhash, + contract_args: params, + contract_list: constracts, + accounts: BTreeMap::new(), + } + } + + pub fn create(&mut self) { + // 1. Check compile exit or not + if !Solc::compiler_version() { + panic!("solc compiler not exit"); + } + // 2. Init normal contracts + self.init_normal_contracts(); + // 3. Init permission contracts + self.init_permission_contracts(); + // 4. Save super admin + let super_admin = self.contract_args.contracts.admin.admin.clone(); + self.set_account_value( + &super_admin, + U256::from_str(clean_0x(&self.init_token)).unwrap(), + ); + // 5. Save genesis to file + self.save_to_file(); + println!("Create genesis successfully !"); + } + + pub fn init_normal_contracts(&mut self) { + let normal_params = self.contract_args.get_params(); + for (contract_name, contract_info) in self.contract_list.normal_contracts.list().iter() { + let address = &contract_info.address; + let data = self.get_data(contract_name, contract_info.file.clone()); + let input_data = string_2_bytes(data["bin"].clone()); + + self.write_docs(contract_name, data); + if let Some(constructor) = self.load_contract(contract_name.to_string()).constructor() { + let params = normal_params + .get(*contract_name) + .map_or(Vec::new(), |p| (*p).clone()); + let bytes = constructor.encode_input(input_data, ¶ms).unwrap(); + let account = Miner::mine(bytes); + self.accounts.insert((*address).clone(), account); + } else { + let account = Miner::mine(input_data); + self.accounts.insert((*address).clone(), account); + } + println!("Normal contracts: {:?} {:?} is ok!", contract_name, address); + } + } + + pub fn init_permission_contracts(&mut self) { + let normal_contracts = self.contract_list.normal_contracts.clone(); + let perm_contracts = self.contract_list.permission_contracts.clone(); + let contract_name = "Permission".to_string(); + let data = self.get_data(&contract_name, perm_contracts.file); + let input_data = string_2_bytes(data["bin"].clone()); + + self.write_docs(&contract_name, data); + if let Some(constructor) = self.load_contract(contract_name).constructor() { + for (name, info) in perm_contracts.basic.list().iter() { + let address = &info.address; + let params = self + .contract_list + .permission_contracts + .basic + .as_params(name); + + let bytes = constructor + .encode_input(input_data.clone(), ¶ms) + .unwrap(); + let account = Miner::mine(bytes); + self.accounts.insert(address.clone(), account); + println!("Permission contracts: {:?} {:?} is ok!", name, address); + } + + for (name, info) in perm_contracts.contracts.list().iter() { + let perm_address = &info.address; + let params = self + .contract_list + .permission_contracts + .contracts + .as_params(&normal_contracts, name); + + let bytes = constructor + .encode_input(input_data.clone(), ¶ms) + .unwrap(); + let account = Miner::mine(bytes); + self.accounts.insert((*perm_address).clone(), account); + println!("Permission contracts: {:?} {:?} is ok!", name, perm_address); + } + } + } + + pub fn write_docs(&self, name: &str, data: BTreeMap) { + for doc_type in ["hashes", "userdoc", "devdoc"].iter() { + let file_path = + self.contract_docs_dir.to_owned() + "/" + name + "-" + doc_type + ".json"; + let path = Path::new(&file_path); + let json = json::stringify_pretty(data[*doc_type].clone(), 4); + let mut f = File::create(path).expect("failed to write docs."); + let _ = f.write_all(&json.as_bytes()); + } + } + + pub fn set_account_value(&mut self, address: &str, value: U256) { + let account = Account { + nonce: U256::one(), + code: String::from(""), + storage: BTreeMap::new(), + value, + }; + self.accounts.insert(address.to_owned(), account); + } + + pub fn save_to_file(&mut self) { + let mut genesis = Genesis::default(); + genesis.timestamp = self.timestamp; + genesis.prevhash = self.prevhash.to_owned(); + genesis.alloc = self.accounts.clone(); + let f = File::create(self.genesis_path.to_owned()).expect("failed to create genesis.json."); + let _ = serde_json::to_writer_pretty(f, &genesis); + } + + pub fn get_data(&self, contract_name: &str, file_path: String) -> BTreeMap { + let path = self.contract_dir.to_owned() + "/src/" + &file_path; + Solc::get_contracts_data(path, contract_name) + } + + pub fn load_contract(&self, contract_name: String) -> Contract { + let abi_path = self.contract_dir.to_owned() + "/interaction/abi/" + &contract_name + ".abi"; + let abi_file = File::open(abi_path).expect("failed to open abi file."); + Contract::load(abi_file).unwrap() + } +} diff --git a/tools/create-genesis/src/main.rs b/tools/create-genesis/src/main.rs new file mode 100644 index 000000000..610eedec7 --- /dev/null +++ b/tools/create-genesis/src/main.rs @@ -0,0 +1,71 @@ +mod common; +mod contracts; +mod genesis; +mod params; + +pub mod miner; +pub mod solc; + +use clap::{App, Arg}; +use genesis::GenesisCreator; + +fn main() { + let matches = App::new("CITA genesis creator") + .version(env!("CARGO_PKG_VERSION")) + .author(env!("CARGO_PKG_AUTHORS")) + .arg( + Arg::with_name("contract_dir") + .help("The directory of contracts.") + .required(true), + ) + .arg( + Arg::with_name("contract_docs_dir") + .help("The directory of generated documents for contracts.") + .required(true), + ) + .arg( + Arg::with_name("params_path") + .help("Path of the file for initialization data of contracts.") + .required(true), + ) + .arg( + Arg::with_name("genesis_path") + .help("Set created genesis path") + .required(true), + ) + .arg( + Arg::with_name("timestamp") + .help("Specify a timestamp to use.") + .required(true), + ) + .arg( + Arg::with_name("init_token") + .help("Init token for this chain") + .required(true), + ) + .arg( + Arg::with_name("prevhash") + .help("Prevhash of genesis.") + .required(true), + ) + .get_matches(); + + let contract_dir = matches.value_of("contract_dir").unwrap(); + let contract_docs_dir = matches.value_of("contract_docs_dir").unwrap(); + let params_path = matches.value_of("params_path").unwrap(); + let genesis_path = matches.value_of("genesis_path").unwrap(); + let timestamp = matches.value_of("timestamp").unwrap(); + let init_token = matches.value_of("init_token").unwrap(); + let prevhash = matches.value_of("prevhash").unwrap(); + let mut creator = GenesisCreator::new( + contract_dir, + contract_docs_dir, + params_path, + genesis_path, + timestamp.parse::().unwrap(), + init_token, + prevhash, + ); + + creator.create(); +} diff --git a/tools/create-genesis/src/miner.rs b/tools/create-genesis/src/miner.rs new file mode 100644 index 000000000..0a5dd1d1a --- /dev/null +++ b/tools/create-genesis/src/miner.rs @@ -0,0 +1,51 @@ +use crate::common::{get_temp_state, secret_2_address, string_2_bytes, string_2_u256}; +use crate::genesis::Account; +use core_executor::engines::NullEngine; +use core_executor::executive::contract_address; +use core_executor::libexecutor::sys_config::BlockSysConfig; +use core_executor::types::transaction::Transaction; +use evm::cita_types::U256; +use evm::env_info::EnvInfo; +use libproto::blockchain::Transaction as ProtoTransaction; + +pub struct Miner; + +impl Miner { + pub fn mine(code: Vec) -> Account { + let mut state = get_temp_state(); + + // Create a transaction + let mut proto_tx = ProtoTransaction::new(); + proto_tx.set_data(code); + proto_tx.set_value(string_2_bytes(String::from("0x00"))); + proto_tx.set_nonce("0x00".to_string()); + proto_tx.set_quota(string_2_u256(String::from("0x99999999999")).low_u64()); + + let private_key = + String::from("0x5f0258a4778057a8a7d97809bd209055b2fbafa654ce7d31ec7191066b9225e6"); + let tx = Transaction::create(&proto_tx).unwrap(); + let sender = secret_2_address(&private_key); + let signed_transaction = tx.fake_sign(sender); + + let env_info = EnvInfo::default(); + let engine = NullEngine::cita(); + let config = BlockSysConfig::default(); + + // Cal contract address + let contract_address = contract_address(&sender, &U256::from(0)); + // Apply tx and commit to state + let _ = state.apply(&env_info, &engine, &signed_transaction, false, &config); + state.commit().unwrap(); + + // Get account content according to contract address + let account = state.account(&contract_address).unwrap().unwrap(); + let code = account.code().unwrap(); + + Account { + nonce: *account.nonce(), + code: String::from("0x") + &hex::encode(code.to_vec()), + storage: account.storage_cache(), + value: *account.balance(), + } + } +} diff --git a/tools/create-genesis/src/params.rs b/tools/create-genesis/src/params.rs new file mode 100644 index 000000000..b38743fa8 --- /dev/null +++ b/tools/create-genesis/src/params.rs @@ -0,0 +1,401 @@ +use crate::common::clean_0x; +use ethabi::Token; +use ethereum_types::{Address, U256}; +use serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; +use std::fs::File; +use std::str::FromStr; + +pub trait GetParams { + fn as_params(&self) -> Vec; +} + +#[derive(Debug, PartialEq, Serialize, Deserialize)] +pub struct InitData { + #[serde(rename = "Contracts")] + pub contracts: Contracts, +} + +impl InitData { + pub fn load_contract_args(path: &str) -> InitData { + let f = File::open(path).expect("failed to open file"); + serde_yaml::from_reader(f).unwrap() + } + + pub fn get_params(&self) -> BTreeMap> { + let mut params = BTreeMap::new(); + params.insert( + "SysConfig".to_string(), + self.contracts.sys_config.as_params(), + ); + params.insert( + "QuotaManager".to_string(), + self.contracts.quota_manager.as_params(), + ); + params.insert( + "NodeManager".to_string(), + self.contracts.node_manager.as_params(), + ); + params.insert( + "ChainManager".to_string(), + self.contracts.chain_manager.as_params(), + ); + params.insert( + "Authorization".to_string(), + self.contracts.authorization.as_params(), + ); + params.insert("Group".to_string(), self.contracts.group.as_params()); + params.insert("Admin".to_string(), self.contracts.admin.as_params()); + params.insert( + "VersionManager".to_string(), + self.contracts.version_manager.as_params(), + ); + params.insert( + "PriceManager".to_string(), + self.contracts.price_manager.as_params(), + ); + params + } +} + +#[derive(Debug, PartialEq, Serialize, Deserialize)] +pub struct Contracts { + #[serde(rename = "SysConfig")] + pub sys_config: SysConfig, + + #[serde(rename = "QuotaManager")] + pub quota_manager: QuotaManager, + + #[serde(rename = "NodeManager")] + pub node_manager: NodeManager, + + #[serde(rename = "ChainManager")] + pub chain_manager: ChainManager, + + #[serde(rename = "Authorization")] + pub authorization: Authorization, + + #[serde(rename = "Group")] + pub group: Group, + + #[serde(rename = "Admin")] + pub admin: Admin, + + #[serde(rename = "VersionManager")] + pub version_manager: VersionManager, + + #[serde(rename = "PriceManager")] + pub price_manager: PriceManager, +} + +#[derive(Debug, PartialEq, Serialize, Deserialize)] +pub struct SysConfig { + #[serde(rename = "delayBlockNumber")] + pub delay_block_number: String, + + #[serde(rename = "checkCallPermission")] + pub check_call_permission: bool, + + #[serde(rename = "checkSendTxPermission")] + pub check_send_tx_permission: bool, + + #[serde(rename = "checkCreateContractPermission")] + pub check_create_contract_permission: bool, + + #[serde(rename = "checkQuota")] + pub check_quota: bool, + + #[serde(rename = "checkFeeBackPlatform")] + pub check_fee_back_platform: bool, + + #[serde(rename = "chainOwner")] + pub chain_owner: String, + + #[serde(rename = "chainName")] + pub chain_name: String, + + #[serde(rename = "chainId")] + pub chain_id: String, + + #[serde(rename = "operator")] + pub operator: String, + + #[serde(rename = "website")] + pub website: String, + + #[serde(rename = "blockInterval")] + pub block_interval: String, + + #[serde(rename = "economicalModel")] + pub economical_model: String, + + pub name: String, + pub symbol: String, + pub avatar: String, + + #[serde(rename = "autoExec")] + pub auto_exec: bool, +} + +impl GetParams for SysConfig { + fn as_params(&self) -> Vec { + let mut tokens = Vec::new(); + tokens.push(Token::Uint( + U256::from_str(&self.delay_block_number).unwrap(), + )); + tokens.push(Token::Address( + Address::from_str(clean_0x(&self.chain_owner)).unwrap(), + )); + tokens.push(Token::String(self.chain_name.clone())); + tokens.push(Token::Uint(U256::from_str(&self.chain_id).unwrap())); + tokens.push(Token::String(self.operator.clone())); + tokens.push(Token::String(self.website.clone())); + tokens.push(Token::Uint( + U256::from_dec_str(&self.block_interval).unwrap(), + )); + tokens.push(Token::Uint(U256::from_str(&self.economical_model).unwrap())); + tokens.push(Token::String(self.name.clone())); + tokens.push(Token::String(self.symbol.clone())); + tokens.push(Token::String(self.avatar.clone())); + + let mut flags = Vec::new(); + flags.push(Token::Bool(self.check_call_permission)); + flags.push(Token::Bool(self.check_send_tx_permission)); + flags.push(Token::Bool(self.check_create_contract_permission)); + flags.push(Token::Bool(self.check_quota)); + flags.push(Token::Bool(self.check_fee_back_platform)); + flags.push(Token::Bool(self.auto_exec)); + + tokens.push(Token::Array(flags)); + tokens + } +} + +#[derive(Debug, PartialEq, Serialize, Deserialize)] +pub struct QuotaManager { + pub admin: String, +} + +impl GetParams for QuotaManager { + fn as_params(&self) -> Vec { + let mut tokens = Vec::new(); + tokens.push(Token::Address( + Address::from_str(clean_0x(&self.admin)).unwrap(), + )); + tokens + } +} + +#[derive(Debug, PartialEq, Serialize, Deserialize)] +pub struct NodeManager { + pub nodes: Vec, + pub stakes: Vec, +} + +impl GetParams for NodeManager { + fn as_params(&self) -> Vec { + let mut tokens = Vec::new(); + + let mut nodes = Vec::new(); + for n in self.nodes.iter() { + let addr = Address::from_str(clean_0x(&n)).unwrap(); + nodes.push(Token::Address(addr)); + } + let mut stakes = Vec::new(); + for s in self.stakes.iter() { + stakes.push(Token::Uint(U256::from_str(&s).unwrap())); + } + + tokens.push(Token::Array(nodes)); + tokens.push(Token::Array(stakes)); + tokens + } +} + +#[derive(Debug, PartialEq, Serialize, Deserialize)] +pub struct ChainManager { + #[serde(rename = "parentChainId")] + pub parent_chain_id: String, + + #[serde(rename = "parentChainAuthorities")] + pub parent_chain_authorities: Vec, +} + +impl GetParams for ChainManager { + fn as_params(&self) -> Vec { + let mut tokens = Vec::new(); + tokens.push(Token::Uint(U256::from_str(&self.parent_chain_id).unwrap())); + + let mut authorities = Vec::new(); + for a in self.parent_chain_authorities.iter() { + let addr = Address::from_str(clean_0x(a)).unwrap(); + authorities.push(Token::Address(addr)); + } + tokens.push(Token::Array(authorities)); + tokens + } +} + +#[derive(Debug, PartialEq, Serialize, Deserialize)] +pub struct Authorization { + #[serde(rename = "superAdmin")] + pub super_admin: String, +} + +impl GetParams for Authorization { + fn as_params(&self) -> Vec { + let mut tokens = Vec::new(); + tokens.push(Token::Address( + Address::from_str(clean_0x(&self.super_admin)).unwrap(), + )); + tokens + } +} + +#[derive(Debug, PartialEq, Serialize, Deserialize)] +pub struct Group { + pub parent: String, + pub name: String, + pub accounts: Vec, +} + +impl GetParams for Group { + fn as_params(&self) -> Vec { + let mut tokens = Vec::new(); + tokens.push(Token::Address( + Address::from_str(clean_0x(&self.parent)).unwrap(), + )); + tokens.push(Token::FixedBytes(self.name.clone().into_bytes())); + + let mut accounts = Vec::new(); + for a in self.accounts.iter() { + accounts.push(Token::Address(Address::from_str(clean_0x(&a)).unwrap())) + } + tokens.push(Token::Array(accounts)); + tokens + } +} + +#[derive(Debug, PartialEq, Serialize, Deserialize)] +pub struct Admin { + pub admin: String, +} + +impl GetParams for Admin { + fn as_params(&self) -> Vec { + let mut tokens = Vec::new(); + tokens.push(Token::Address( + Address::from_str(clean_0x(&self.admin)).unwrap(), + )); + tokens + } +} + +#[derive(Debug, PartialEq, Serialize, Deserialize)] +pub struct VersionManager { + pub version: String, +} + +impl GetParams for VersionManager { + fn as_params(&self) -> Vec { + let mut tokens = Vec::new(); + tokens.push(Token::Uint(U256::from_str(&self.version).unwrap())); + tokens + } +} + +#[derive(Debug, PartialEq, Serialize, Deserialize)] +pub struct PriceManager { + #[serde(rename = "quotaPrice")] + pub quota_price: String, +} + +impl GetParams for PriceManager { + fn as_params(&self) -> Vec { + let mut tokens = Vec::new(); + tokens.push(Token::Uint(U256::from_dec_str(&self.quota_price).unwrap())); + tokens + } +} + +#[cfg(test)] +mod tests { + use super::InitData; + + #[test] + pub fn test_params() { + let params_string = r#" + Contracts: + Admin: + admin: '0x4b5ae4567ad5d9fb92bc9afd6a657e6fa13a2523' + Authorization: + superAdmin: '0x4b5ae4567ad5d9fb92bc9afd6a657e6fa13a2523' + ChainManager: + parentChainAuthorities: [] + parentChainId: 0 + Group: + accounts: + - '0x4b5ae4567ad5d9fb92bc9afd6a657e6fa13a2523' + name: rootGroup + parent: '0x0000000000000000000000000000000000000000' + NodeManager: + nodes: + - '0xdcfa10bf99d3618c5a9d08ec41b448585e45e0ee' + stakes: + - 0 + PriceManager: + quotaPrice: 1000000 + QuotaManager: + admin: '0x4b5ae4567ad5d9fb92bc9afd6a657e6fa13a2523' + SysConfig: + autoExec: false + avatar: https://cdn.cryptape.com/icon_cita.png + blockInterval: 3000 + chainId: 1 + chainName: test-chain + chainOwner: '0x0000000000000000000000000000000000000000' + checkCallPermission: false + checkCreateContractPermission: false + checkFeeBackPlatform: false + checkQuota: false + checkSendTxPermission: false + delayBlockNumber: 1 + economicalModel: 0 + name: CITA Test Token + operator: test-operator + symbol: CTT + website: https://www.example.com + VersionManager: + version: 2"#; + + let config: InitData = serde_yaml::from_str(¶ms_string).unwrap(); + assert_eq!( + config.contracts.sys_config.delay_block_number, + "1".to_string() + ); + assert_eq!(config.contracts.sys_config.check_call_permission, false); + assert_eq!( + config.contracts.sys_config.avatar, + "https://cdn.cryptape.com/icon_cita.png".to_string() + ); + assert_eq!( + config.contracts.quota_manager.admin, + String::from("0x4b5ae4567ad5d9fb92bc9afd6a657e6fa13a2523") + ); + assert_eq!( + *config.contracts.node_manager.nodes.get(0).unwrap(), + String::from("0xdcfa10bf99d3618c5a9d08ec41b448585e45e0ee") + ); + + assert_eq!( + config.contracts.group.parent, + String::from("0x0000000000000000000000000000000000000000") + ); + assert_eq!(config.contracts.group.name, String::from("rootGroup")); + assert_eq!(config.contracts.version_manager.version, String::from("2")); + assert_eq!( + config.contracts.price_manager.quota_price, + String::from("1000000") + ); + } +} diff --git a/tools/create-genesis/src/solc.rs b/tools/create-genesis/src/solc.rs new file mode 100644 index 000000000..e008a628b --- /dev/null +++ b/tools/create-genesis/src/solc.rs @@ -0,0 +1,49 @@ +use json; +use std::collections::BTreeMap; +use std::process::Command; + +pub struct Solc; + +impl Solc { + pub fn get_contracts_data(file_path: String, contract_name: &str) -> BTreeMap { + let output = Command::new("solc") + .arg(file_path.clone()) + .arg("--allow-paths") + .arg(".") + .arg("--optimize") + .arg("--combined-json") + .arg("abi,bin,userdoc,hashes,devdoc") + .output() + .expect("solc command fail to execute"); + let output = String::from_utf8(output.stdout).unwrap(); + let compiled = json::parse(&output).unwrap(); + let index = [&file_path, ":", contract_name].concat(); + + let bin = &compiled["contracts"][&index]["bin"]; + let abi = &compiled["contracts"][&index]["abi"]; + let hashes = &compiled["contracts"][&index]["hashes"]; + let userdoc = &compiled["contracts"][&index]["userdoc"]; + let devdoc = &compiled["contracts"][&index]["devdoc"]; + + let mut data = BTreeMap::new(); + data.insert("bin".to_string(), bin.to_string()); + data.insert("abi".to_string(), abi.to_string()); + data.insert("hashes".to_string(), hashes.to_string()); + data.insert("userdoc".to_string(), userdoc.to_string()); + data.insert("devdoc".to_string(), devdoc.to_string()); + + data + } + + pub fn compiler_version() -> bool { + let output = Command::new("solc") + .arg("--version") + .output() + .expect("solc compiler not exist !"); + println!( + "Solc version: {:?}", + String::from_utf8(output.stdout).unwrap() + ); + output.status.success() + } +} diff --git a/tools/create_key_addr/Cargo.toml b/tools/create-key-addr/Cargo.toml similarity index 92% rename from tools/create_key_addr/Cargo.toml rename to tools/create-key-addr/Cargo.toml index 7dabe5146..b7eae4c06 100644 --- a/tools/create_key_addr/Cargo.toml +++ b/tools/create-key-addr/Cargo.toml @@ -1,7 +1,8 @@ [package] -name = "create_key_addr" +name = "create-key-addr" version = "0.1.0" authors = ["Cryptape Technologies "] +edition = "2018" [dependencies] cita-crypto = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } diff --git a/tools/create_key_addr/src/main.rs b/tools/create-key-addr/src/main.rs similarity index 94% rename from tools/create_key_addr/src/main.rs rename to tools/create-key-addr/src/main.rs index 9bdd40189..c47e69f7b 100644 --- a/tools/create_key_addr/src/main.rs +++ b/tools/create-key-addr/src/main.rs @@ -1,5 +1,5 @@ // CITA -// Copyright 2016-2017 Cryptape Technologies LLC. +// Copyright 2016-2019 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public @@ -16,9 +16,8 @@ // along with this program. If not, see . extern crate cita_crypto as crypto; -extern crate hashable; -use crypto::{CreateKey, KeyPair, PubKey}; +use crate::crypto::{CreateKey, KeyPair, PubKey}; use hashable::Hashable; use std::env; use std::fs::{File, OpenOptions}; diff --git a/tools/relayer-parser/Cargo.toml b/tools/relayer-parser/Cargo.toml index 206da8db5..ad19d56f4 100644 --- a/tools/relayer-parser/Cargo.toml +++ b/tools/relayer-parser/Cargo.toml @@ -2,9 +2,10 @@ name = "cita-relayer-parser" version = "0.1.0" authors = ["Cryptape Technologies "] +edition = "2018" [dependencies] -logger = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } +cita-logger = "0.1.0" serde = "1.0" serde_derive = "1.0" serde_json = "1.0" diff --git a/tools/relayer-parser/src/arguments.rs b/tools/relayer-parser/src/arguments.rs index 723187265..bfcee20cf 100644 --- a/tools/relayer-parser/src/arguments.rs +++ b/tools/relayer-parser/src/arguments.rs @@ -1,5 +1,5 @@ // CITA -// Copyright 2016-2018 Cryptape Technologies LLC. +// Copyright 2016-2019 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public @@ -15,11 +15,10 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . +use cita_types::{H256, U256}; use clap; use std::str::FromStr; -use cita_types::{H256, U256}; - pub struct AppArgs { pub cfg_file: String, pub chain_id: U256, diff --git a/tools/relayer-parser/src/communication.rs b/tools/relayer-parser/src/communication.rs index abbb59edb..59b756083 100644 --- a/tools/relayer-parser/src/communication.rs +++ b/tools/relayer-parser/src/communication.rs @@ -1,5 +1,5 @@ // CITA -// Copyright 2016-2018 Cryptape Technologies LLC. +// Copyright 2016-2019 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public @@ -25,8 +25,8 @@ use serde_json; use std::convert::Into; use tokio_core::reactor::{Core, Timeout}; +use crate::configuration::UpStream; use cita_types::{H256, U256}; -use configuration::UpStream; use jsonrpc_types::{rpc_request, rpc_types}; use libproto::blockchain::UnverifiedTransaction; diff --git a/tools/relayer-parser/src/configuration.rs b/tools/relayer-parser/src/configuration.rs index 1a97bf30a..96880752a 100644 --- a/tools/relayer-parser/src/configuration.rs +++ b/tools/relayer-parser/src/configuration.rs @@ -1,5 +1,5 @@ // CITA -// Copyright 2016-2018 Cryptape Technologies LLC. +// Copyright 2016-2019 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public @@ -15,13 +15,12 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . +use cita_crypto::PrivKey; +use cita_types::U256; use serde_json; use std::collections::HashMap; use std::time::Duration; -use cita_crypto::PrivKey; -use cita_types::U256; - #[derive(Debug, Deserialize, Clone)] pub struct UpStream { pub url: String, diff --git a/tools/relayer-parser/src/main.rs b/tools/relayer-parser/src/main.rs index a0bf870a2..dda1fa559 100644 --- a/tools/relayer-parser/src/main.rs +++ b/tools/relayer-parser/src/main.rs @@ -1,5 +1,5 @@ // CITA -// Copyright 2016-2018 Cryptape Technologies LLC. +// Copyright 2016-2019 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public @@ -15,25 +15,12 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . -extern crate cita_crypto; #[macro_use] extern crate clap; -extern crate ethabi; -extern crate futures; -extern crate hyper; -extern crate parking_lot; -extern crate serde; #[macro_use] extern crate serde_derive; -extern crate serde_json; -extern crate tokio_core; - -extern crate cita_types; -extern crate core; -extern crate jsonrpc_types; -extern crate libproto; #[macro_use] -extern crate logger; +extern crate cita_logger as logger; mod arguments; mod communication; diff --git a/tools/relayer-parser/src/transaction.rs b/tools/relayer-parser/src/transaction.rs index d04803c27..1779cebd8 100644 --- a/tools/relayer-parser/src/transaction.rs +++ b/tools/relayer-parser/src/transaction.rs @@ -1,5 +1,5 @@ // CITA -// Copyright 2016-2018 Cryptape Technologies LLC. +// Copyright 2016-2019 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public diff --git a/tools/snapshot_tool/Cargo.toml b/tools/snapshot-tool/Cargo.toml similarity index 88% rename from tools/snapshot_tool/Cargo.toml rename to tools/snapshot-tool/Cargo.toml index a9015aefa..3743ba7a3 100644 --- a/tools/snapshot_tool/Cargo.toml +++ b/tools/snapshot-tool/Cargo.toml @@ -1,14 +1,15 @@ [package] -name = "snapshot_tool" +name = "snapshot-tool" version = "0.2.0" authors = ["Cryptape Technologies "] +edition = "2018" [dependencies] dotenv = "0.13.0" clap = "2" fs2 = "0.4.3" +cita-logger = "0.1.0" util = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } -logger = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } pubsub = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } libproto = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } error = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } diff --git a/tools/snapshot_tool/src/main.rs b/tools/snapshot-tool/src/main.rs similarity index 96% rename from tools/snapshot_tool/src/main.rs rename to tools/snapshot-tool/src/main.rs index ae1401da6..a27473617 100644 --- a/tools/snapshot_tool/src/main.rs +++ b/tools/snapshot-tool/src/main.rs @@ -15,22 +15,17 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . -extern crate clap; -extern crate dotenv; -extern crate error; -extern crate fs2; #[macro_use] extern crate libproto; #[macro_use] -extern crate logger; -extern crate pubsub; +extern crate cita_logger as logger; #[macro_use] extern crate util; +use crate::postman::Postman; use clap::App; use fs2::FileExt; use libproto::router::{MsgType, RoutingKey, SubModules}; -use postman::Postman; use pubsub::channel; use pubsub::start_pubsub; use std::fs::{self, File, OpenOptions}; diff --git a/tools/snapshot_tool/src/postman.rs b/tools/snapshot-tool/src/postman.rs similarity index 100% rename from tools/snapshot_tool/src/postman.rs rename to tools/snapshot-tool/src/postman.rs