├── cita-executor ├── core │ ├── src │ │ ├── libexecutor │ │ │ ├── cache.rs │ │ │ ├── mod.rs │ │ │ ├── call_request.rs │ │ │ └── economical_model.rs │ │ ├── contracts │ │ │ ├── native │ │ │ │ ├── zk_privacy.md │ │ │ │ └── mod.rs │ │ │ ├── tools │ │ │ │ └── mod.rs │ │ │ ├── mod.rs │ │ │ └── solc │ │ │ │ └── admin.rs │ │ ├── tests │ │ │ └── mod.rs │ │ ├── benches │ │ │ └── mod.rs │ │ ├── spec │ │ │ └── mod.rs │ │ ├── trace │ │ │ ├── types │ │ │ │ ├── mod.rs │ │ │ │ └── localized.rs │ │ │ ├── import.rs │ │ │ ├── error.rs │ │ │ └── config.rs │ │ ├── factory.rs │ │ ├── snapshot │ │ │ └── README.md │ │ └── engines │ │ │ └── null_engine.rs │ ├── chain.toml │ ├── executor.toml │ └── README.md ├── evm │ ├── README.md │ ├── Cargo.toml │ └── src │ │ ├── lib.rs │ │ └── return_data.rs ├── src │ └── tests │ │ └── mod.rs └── build.rs ├── cita-chain ├── core │ ├── chain.toml │ ├── README.md │ └── src │ │ ├── libchain │ │ ├── mod.rs │ │ ├── cache.rs │ │ ├── status.rs │ │ └── rich_status.rs │ │ ├── filters │ │ ├── mod.rs │ │ └── poll_filter.rs │ │ └── lib.rs ├── build.rs ├── types │ ├── README.md │ ├── src │ │ ├── basic_types.rs │ │ ├── call_analytics.rs │ │ ├── lib.rs │ │ ├── state_diff.rs │ │ ├── ids.rs │ │ ├── basic_account.rs │ │ └── log_blooms.rs │ └── Cargo.toml ├── src │ └── block_processor.rs └── Cargo.toml ├── .gitattributes ├── scripts ├── config_tool │ └── default_config │ │ ├── chain.toml │ │ ├── consensus.toml │ │ ├── executor.toml │ │ ├── auth.toml │ │ ├── forever.toml │ │ ├── forever_mock.toml │ │ └── jsonrpc.toml ├── contracts │ ├── .soliumignore │ ├── src │ │ ├── common │ │ │ ├── EconomicalType.sol │ │ │ ├── Error.sol │ │ │ ├── Check.sol │ │ │ └── Admin.sol │ │ ├── system │ │ │ ├── EmergencyIntervention.sol │ │ │ ├── PriceManager.sol │ │ │ ├── AutoExec.sol │ │ │ ├── VersionManager.sol │ │ │ └── BatchTx.sol │ │ ├── lib │ │ │ ├── ContractCheck.sol │ │ │ └── SafeMath.sol │ │ ├── role_management │ │ │ └── RoleCreator.sol │ │ ├── user_management │ │ │ ├── GroupCreator.sol │ │ │ └── AllGroups.sol │ │ └── permission_management │ │ │ └── PermissionCreator.sol │ ├── tests │ │ ├── .eslintrc.js │ │ └── test │ │ │ ├── helpers │ │ │ ├── permission.js │ │ │ ├── admin.js │ │ │ ├── auto_exec.js │ │ │ ├── group.js │ │ │ ├── version_manager.js │ │ │ ├── role_auth.js │ │ │ ├── authorization.js │ │ │ ├── node_manager.js │ │ │ ├── util.js │ │ │ ├── chain_manager.js │ │ │ ├── quota.js │ │ │ └── group_management.js │ │ │ ├── unit │ │ │ ├── group.js │ │ │ ├── admin.js │ │ │ ├── quota.js │ │ │ ├── version_manager.js │ │ │ └── permission.js │ │ │ └── integrate │ │ │ ├── store.js │ │ │ └── abi.js │ └── .soliumrc.json ├── txtool │ ├── txtool │ │ ├── config │ │ │ ├── setting.cfg │ │ │ └── logging.yml │ │ ├── create_protobuf.sh │ │ ├── __init__.py │ │ ├── solidity │ │ │ └── test.sol │ │ ├── block_number.py │ │ ├── peer_count.py │ │ ├── check.py │ │ ├── block_by_hash.py │ │ ├── block_by_number.py │ │ ├── url_util.py │ │ ├── get_code.py │ │ ├── tx_count.py │ │ ├── get_logs.py │ │ ├── get_tx.py │ │ ├── call.py │ │ ├── log.py │ │ └── send_tx.py │ ├── requirements_sudo.sh │ └── requirements.txt ├── cita_config.sh ├── security_audit.sh ├── replace_default_feature.sh ├── amend_system_contracts.sh └── release.sh ├── tests ├── json-test │ ├── src │ │ ├── json │ │ │ └── mod.rs │ │ ├── lib.rs │ │ └── helper.rs │ ├── README.md │ └── Cargo.toml ├── chain-performance-by-mq │ ├── Test.sol │ ├── README.md │ └── Cargo.toml ├── interfaces │ ├── config │ │ └── authorities │ └── .gitignore ├── compatibility │ └── check_genesis.sh ├── integrate_test │ ├── update_version.py │ ├── test_perm_denied.py │ ├── txtool_utils.py │ ├── box_executor_test.sh │ ├── cita_features_test.sh │ ├── cita_jsonrpc_schema_mock.sh │ └── test_fee_back.py ├── box-executor │ ├── README.md │ ├── Cargo.toml │ └── src │ │ ├── config.rs │ │ └── main.rs ├── consensus-mock │ └── Cargo.toml └── chain-executor-mock │ └── Cargo.toml ├── .env ├── docs ├── wiki │ └── images │ │ ├── rocksdb-db-impl.png │ │ └── rocksdb-lsm-tree.png └── style-guide │ ├── python.md │ ├── js.md │ ├── naming.md │ ├── solidity.md │ ├── shell.md │ ├── rust.md │ └── logging.md ├── .github ├── PULL_REQUEST_TEMPLATE │ └── simple.md ├── ISSUE_TEMPLATE │ ├── custom.md │ ├── feature_request.md │ └── bug_report.md └── pull_request_template.md ├── cita-jsonrpc ├── README.md ├── build.rs └── Cargo.toml ├── Cargo.toml ├── tools ├── create-key-addr │ ├── Cargo.toml │ └── src │ │ └── main.rs ├── create-genesis │ ├── Cargo.toml │ └── src │ │ ├── common.rs │ │ ├── solc.rs │ │ └── miner.rs ├── snapshot-tool │ └── Cargo.toml └── relayer-parser │ ├── res │ └── relayer-parser-demo.json │ ├── Cargo.toml │ └── src │ ├── configuration.rs │ └── transaction.rs ├── .gitignore ├── .editorconfig ├── cita-network ├── build.rs ├── Cargo.toml └── src │ └── sync_protocol.md ├── cita-auth ├── build.rs ├── src │ └── transaction_verify.rs └── Cargo.toml ├── Makefile └── .gitmodules /cita-executor/core/src/libexecutor/cache.rs: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /cita-chain/core/chain.toml: -------------------------------------------------------------------------------- 1 | prooftype = 2 2 | -------------------------------------------------------------------------------- /cita-executor/core/chain.toml: -------------------------------------------------------------------------------- 1 | prooftype = 2 2 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | *.sol linguist-language=Solidity 2 | -------------------------------------------------------------------------------- /scripts/config_tool/default_config/chain.toml: -------------------------------------------------------------------------------- 1 | prooftype = 2 2 | -------------------------------------------------------------------------------- /tests/json-test/src/json/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod state; 2 | pub mod vm; 3 | -------------------------------------------------------------------------------- /.env: -------------------------------------------------------------------------------- 1 | AMQP_URL=amqp://guest:guest@localhost/dev 2 | DATA_PATH=./data 3 | -------------------------------------------------------------------------------- /scripts/contracts/.soliumignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | interaction/interface 3 | -------------------------------------------------------------------------------- /cita-executor/core/executor.toml: -------------------------------------------------------------------------------- 1 | prooftype = 2 2 | journaldb_type = "archive" 3 | -------------------------------------------------------------------------------- /scripts/txtool/txtool/config/setting.cfg: -------------------------------------------------------------------------------- 1 | [jsonrpc_url] 2 | host=127.0.0.1 3 | port=1337 4 | -------------------------------------------------------------------------------- /scripts/txtool/requirements_sudo.sh: -------------------------------------------------------------------------------- 1 | sudo apt-get install openssl 2 | sudo apt-get install libyaml-dev 3 | -------------------------------------------------------------------------------- /docs/wiki/images/rocksdb-db-impl.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nasa8x/cita/develop/docs/wiki/images/rocksdb-db-impl.png -------------------------------------------------------------------------------- /docs/wiki/images/rocksdb-lsm-tree.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nasa8x/cita/develop/docs/wiki/images/rocksdb-lsm-tree.png -------------------------------------------------------------------------------- /scripts/txtool/txtool/create_protobuf.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | protoc --proto_path=proto --python_out=. blockchain.proto 4 | -------------------------------------------------------------------------------- /cita-executor/evm/README.md: -------------------------------------------------------------------------------- 1 | # EVM for CITA 2 | 3 | This repository is extracted from [Parity](https://github.com/paritytech/parity) 4 | -------------------------------------------------------------------------------- /scripts/config_tool/default_config/consensus.toml: -------------------------------------------------------------------------------- 1 | [ntp_config] 2 | enabled = false 3 | threshold = 1000 4 | address = "0.pool.ntp.org:123" 5 | -------------------------------------------------------------------------------- /tests/json-test/src/lib.rs: -------------------------------------------------------------------------------- 1 | #[macro_use] 2 | extern crate log; 3 | 4 | pub mod helper; 5 | pub mod json; 6 | pub mod state_test; 7 | pub mod vm_test; 8 | -------------------------------------------------------------------------------- /scripts/txtool/requirements.txt: -------------------------------------------------------------------------------- 1 | jsonrpcclient[requests]==2.4.2 2 | py_solc==1.2.2 3 | simplejson==3.11.1 4 | protobuf==3.4.0 5 | pathlib==1.0.1 6 | ecdsa 7 | pysha3>=1.0.2 8 | pysodium 9 | -------------------------------------------------------------------------------- /scripts/config_tool/default_config/executor.toml: -------------------------------------------------------------------------------- 1 | journaldb_type = "archive" 2 | prooftype = 2 3 | genesis_path = "./genesis.json" 4 | statedb_cache_size = 5242880 5 | eth_compatibility = false 6 | -------------------------------------------------------------------------------- /tests/chain-performance-by-mq/Test.sol: -------------------------------------------------------------------------------- 1 | pragma solidity ^0.4.24; 2 | 3 | contract Test { 4 | uint x; 5 | 6 | function add() public { 7 | x = x + 1; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /scripts/contracts/src/common/EconomicalType.sol: -------------------------------------------------------------------------------- 1 | pragma solidity 0.4.24; 2 | 3 | contract EconomicalType { 4 | 5 | enum EconomicalModel { 6 | Quota, 7 | Charge 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /cita-chain/build.rs: -------------------------------------------------------------------------------- 1 | use std::env; 2 | 3 | use util::build_info::gen_build_info; 4 | 5 | fn main() { 6 | let out_dir = env::var("OUT_DIR").unwrap(); 7 | gen_build_info(out_dir.as_ref(), "build_info.rs"); 8 | } 9 | -------------------------------------------------------------------------------- /scripts/contracts/tests/.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | 'extends': "airbnb-base", 3 | 'rules': { 4 | 'no-unused-expressions': 'off', 5 | }, 6 | 'env': { 7 | 'mocha': true 8 | } 9 | }; 10 | -------------------------------------------------------------------------------- /tests/interfaces/config/authorities: -------------------------------------------------------------------------------- 1 | 0xa83ca59edc87a9cc7e384afa8d218dcca71cae88 2 | 0xbc1fafd5ba5485f97e937fe574f836b275e593dd 3 | 0xfc788efe3fda574e21691d383e429be02c530e4c 4 | 0xe9deeae8b2a43675f113d11573119b9c68e5e3d8 5 | -------------------------------------------------------------------------------- /scripts/txtool/txtool/__init__.py: -------------------------------------------------------------------------------- 1 | from util import * 2 | from check import * 3 | from compile import * 4 | from tx_count import get_transaction_count 5 | 6 | __all__ = ['util', 'check', 'compile', 'generate_account', 'tx_count'] 7 | -------------------------------------------------------------------------------- /scripts/config_tool/default_config/auth.toml: -------------------------------------------------------------------------------- 1 | count_per_batch = 30 2 | buffer_duration = 30 3 | tx_verify_thread_num = 4 4 | tx_verify_cache_size = 100000 5 | tx_pool_limit = 0 6 | wal_enable = false 7 | prof_start = 0 8 | prof_duration = 0 9 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE/simple.md: -------------------------------------------------------------------------------- 1 | # Pull Request Template 2 | 3 | ## Requirements 4 | 5 | - Filling out the template is required. Any pull request that does not include enough information to be reviewed in a timely manner may be closed at the maintainers' discretion. 6 | 7 | ## Templates 8 | 9 | ### Description of the Change 10 | ### Applicable Issues 11 | -------------------------------------------------------------------------------- /scripts/contracts/.soliumrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "solium:recommended", 3 | "plugins": [ 4 | "security" 5 | ], 6 | "rules": { 7 | "quotes": [ 8 | "error", 9 | "double" 10 | ], 11 | "indentation": [ 12 | "error", 13 | 4 14 | ], 15 | "max-len": [ 16 | "error", 17 | 79 18 | ] 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/custom.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Custom issue template 3 | about: Any question that isn't answered in docs or forum 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | ## Description 11 | 12 | [Description of the issue] 13 | 14 | ## Additional Information 15 | 16 | [Any other information which would be helpful to reproduce the issue]. 17 | -------------------------------------------------------------------------------- /tests/interfaces/.gitignore: -------------------------------------------------------------------------------- 1 | # Generated by Cargo 2 | # will have compiled files and executables 3 | /target/ 4 | 5 | # Remove Cargo.lock from gitignore if creating an executable, leave it for libraries 6 | # More information here http://doc.crates.io/guide.html#cargotoml-vs-cargolock 7 | Cargo.lock 8 | 9 | # These are backup files generated by rustfmt 10 | **/*.rs.bk 11 | -------------------------------------------------------------------------------- /scripts/cita_config.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Enviroments 4 | CITA_BIN=$(realpath "$(dirnamme "$0")") 5 | CITA_SCRIPTS=$(dirname "$CITA_BIN")/scripts 6 | 7 | # Wrap the create script. 8 | if [ -e "$CITA_SCRIPTS"/create_cita_config.py ]; then 9 | "$CITA_SCRIPTS"/create_cita_config.py "$@" 10 | else 11 | echo -e "\033[0;31mPlease run this command after build 🎨" 12 | fi 13 | -------------------------------------------------------------------------------- /cita-jsonrpc/README.md: -------------------------------------------------------------------------------- 1 | ## JSON-RPC 2 | 3 | [在线文档](https://docs.citahub.com/zh-CN/next/cita/rpc-guide/rpc) 4 | 5 | [online doc](https://docs.citahub.com/en-US/next/cita/rpc-guide/rpc) 6 | 7 | ## JSON-RPC ERROR CODE 8 | 9 | [在线文档](https://docs.citahub.com/zh-CN/next/cita/rpc-guide/rpc-error-code) 10 | 11 | [online doc](https://docs.citahub.com/en-US/next/cita/rpc-guide/rpc-error-code) 12 | -------------------------------------------------------------------------------- /tests/json-test/README.md: -------------------------------------------------------------------------------- 1 | # Json Test 2 | 3 | Test CITA using [Tests](https://github.com/cryptape/cita-testdata/) 4 | 5 | ## Usage 6 | 7 | ### State Tests 8 | 9 | ```sh 10 | $ cd cita 11 | 12 | $ cargo test --features sha3hash state_test::tests::test_json_state 13 | ``` 14 | 15 | ### VM Tests 16 | 17 | ```sh 18 | $ cd cita 19 | 20 | $ cargo test vm_test::tests::test_json_vm 21 | ``` 22 | -------------------------------------------------------------------------------- /docs/style-guide/python.md: -------------------------------------------------------------------------------- 1 | # Python Style Guide 2 | 3 | Use the community-consistent formatting, check [PEP8]. 4 | Use [Pylint] as the formatting tools and use the default settings. 5 | 6 | ------------------- 7 | 8 | # Python 风格指南 9 | 10 | 使用社区一致的格式,参考 [PEP8]。 11 | 使用 [Pylint] 作为格式化工具,并使用默认配置。 12 | 13 | [PEP8]: https://www.python.org/dev/peps/pep-0008/ 14 | [Pylint]: https://github.com/PyCQA/pylint 15 | -------------------------------------------------------------------------------- /scripts/security_audit.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | if [[ "$(git log -n 1 --format="%s")" =~ \[skip\ audit\] ]]; then 4 | echo "[Info_] Skip Security Audit." 5 | exit 0 6 | fi 7 | 8 | which cargo-audit 9 | ret=$? 10 | if [ "${ret}" -ne 0 ]; then 11 | echo "[Info_] Install Security Audit." 12 | cargo install cargo-audit 13 | fi 14 | 15 | echo "[Info_] Run Security Audit." 16 | cargo audit 17 | -------------------------------------------------------------------------------- /cita-chain/types/README.md: -------------------------------------------------------------------------------- 1 | # Common types for Chain and Executor 2 | 3 | Files below are extracted from [Parity](https://github.com/paritytech/parity): 4 | 5 | - ./src/call_analytics.rs 6 | - ./src/state_diff.rs 7 | - ./src/filter.rs 8 | - ./src/log_entry.rs 9 | - ./src/basic_account.rs 10 | - ./src/ids.rs 11 | - ./src/account_diff.rs 12 | - ./src/log_blooms.rs 13 | 14 | with following modifications: 15 | 16 | - ./src/receipt.rs 17 | -------------------------------------------------------------------------------- /cita-executor/core/src/contracts/native/zk_privacy.md: -------------------------------------------------------------------------------- 1 | 使用零知识证明技术实现隐私交易验证系统合约。 2 | 3 | Warning:当前代码仅为原型验证系统,请勿用于生产环境。 4 | 5 | 此功能通过feature控制,默认关闭。 6 | 7 | 打开此功能有两种方法: 8 | 1. 修改 cita-executor/Cargo.toml。 9 | 在 \[features\] 下面 default 列表中增加 privatetx 。 10 | 2. 使用如下命令单独编译cita-executor,并替换原有的可执行文件。 11 | ``` 12 | cd cita-executor 13 | cargo build --release --features "privatetx" 14 | ``` 15 | *** 16 | ### 使用说明 17 | [zktx_example](https://github.com/cryptape/zktx_example) 18 | -------------------------------------------------------------------------------- /docs/style-guide/js.md: -------------------------------------------------------------------------------- 1 | # JavaScript Style Guide 2 | 3 | Refer to the [Airbnb-JavaScript] and gradually develop a style guide for CITA. 4 | Use [ESLint] as the formatting tools and use the `airbnb-base` extend. 5 | 6 | ------------------- 7 | 8 | # JavaScript 风格指南 9 | 10 | 参考 [Airbnb-JavaScript],之后逐步形成适应 `CITA` 的风格指南。 11 | 使用 [ESLint] 作为格式化工具,并使用 `airbnb-base` 扩展。 12 | 13 | [Airbnb-JavaScript]: https://github.com/eslint/eslint 14 | [ESLint]: https://github.com/eslint/eslint 15 | -------------------------------------------------------------------------------- /docs/style-guide/naming.md: -------------------------------------------------------------------------------- 1 | # Naming Style Guide 2 | 3 | ## Filenames 4 | 5 | 1. First rule: Follow the rules of programming language community(Rust, Python, JavaScript, Shell, Solidity) 6 | 2. Second rule: Follow the [google-style] 7 | 8 | ------------- 9 | 10 | # 命名风格指南 11 | 12 | ## 文件名称 13 | 14 | 1. 第一原则: 使用各个编程语言社区的规范(Rust, Python, JavaScript, Shell, Solidity) 15 | 2. 第二原则: 与 [google-style] 保持一致 16 | 17 | [google-style]: https://developers.google.com/style/filenames 18 | -------------------------------------------------------------------------------- /docs/style-guide/solidity.md: -------------------------------------------------------------------------------- 1 | # Solidity Style Guide 2 | 3 | Use the community-consistent formatting, check [Solidity-Style-Guide]. 4 | Use [Ethlint] as the formatting tool and use the default settings. 5 | 6 | ---------------------- 7 | 8 | # Solidity 风格指南 9 | 10 | 使用社区一致的格式,参考 [Solidity-Style-Guide]。 11 | 使用 [Ethlint] 作为格式化工具,并使用默认配置。 12 | 13 | [Ethlint]: https://github.com/duaraghav8/Ethlint 14 | [Solidity-Style-Guide]: https://solidity.readthedocs.io/en/latest/style-guide.html 15 | -------------------------------------------------------------------------------- /docs/style-guide/shell.md: -------------------------------------------------------------------------------- 1 | # Shell Style Guide 2 | 3 | Refer to the [Google-Shell-Style-Guide] and gradually develop a style guide for CITA. 4 | Use [ShellCheck] as the formatting tools and use the default settings. 5 | 6 | ------------------ 7 | 8 | # Shell 风格指南 9 | 10 | 参考 [Google-Shell-Style-Guide],之后逐步形成适应 `CITA` 的风格指南。 11 | 使用 [ShellCheck] 作为格式化工具,并使用默认配置。 12 | 13 | [Google-Shell-Style-Guide]: https://google.github.io/styleguide/shell.xml 14 | [ShellCheck]: https://github.com/koalaman/shellcheck 15 | -------------------------------------------------------------------------------- /.github/pull_request_template.md: -------------------------------------------------------------------------------- 1 | # Pull Request Template 2 | 3 | ## Requirements 4 | 5 | - Filling out the template is required. Any pull request that does not include enough information to be reviewed in a timely manner may be closed at the maintainers' discretion. 6 | - All new codes require tests to ensure against regressions. 7 | 8 | ## Templates 9 | 10 | ### Description of the Change 11 | ### Alternate Design 12 | ### Benefits 13 | ### Possible Drawbacks 14 | ### Verification Process 15 | ### Applicable Issues 16 | -------------------------------------------------------------------------------- /docs/style-guide/rust.md: -------------------------------------------------------------------------------- 1 | # Rust Style Guide 2 | 3 | Use the community-consistent formatting, check [Rust-fmt-rfcs]. 4 | Use [rustfmt] and [clippy] as the formatting tools and use the default settings. 5 | 6 | ----------------- 7 | 8 | # Rust 风格指南 9 | 10 | 使用社区一致的格式,参考 [Rust-fmt-rfcs]。 11 | 使用 [rustfmt] 及 [clippy] 作为格式化工具,并使用默认配置。 12 | 13 | [Rust-fmt-rfcs]: https://github.com/rust-dev-tools/fmt-rfcs/tree/master/guide 14 | [clippy]: https://github.com/rust-lang/rust-clippy 15 | [rustfmt]: https://github.com/rust-lang/rustfmt 16 | -------------------------------------------------------------------------------- /scripts/contracts/src/common/Error.sol: -------------------------------------------------------------------------------- 1 | pragma solidity 0.4.24; 2 | 3 | /// @title The enum data of error 4 | /// @author ["Cryptape Technologies "] 5 | contract Error { 6 | 7 | enum ErrorType { 8 | NotAdmin, 9 | OutOfBaseLimit, 10 | OutOfBlockLimit, 11 | NoParentChain, 12 | NoSideChain, 13 | NotOneOperate, 14 | NotClose, 15 | NotStart, 16 | NotReady 17 | } 18 | 19 | event ErrorLog(ErrorType indexed errorType, string msg); 20 | } 21 | -------------------------------------------------------------------------------- /scripts/txtool/txtool/solidity/test.sol: -------------------------------------------------------------------------------- 1 | pragma solidity ^0.4.0; 2 | 3 | contract SimpleStorage { 4 | uint storedData; 5 | event Init(address, uint); 6 | event Set(address, uint); 7 | 8 | function SimpleStorage() { 9 | storedData = 100; 10 | Init(msg.sender, 100); 11 | } 12 | 13 | event Stored(uint); 14 | 15 | function set(uint x) { 16 | Stored(x); 17 | storedData = x; 18 | Set(msg.sender, x); 19 | } 20 | 21 | function get() constant returns (uint) { 22 | return storedData; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /scripts/txtool/txtool/block_number.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # coding=utf-8 3 | 4 | from jsonrpcclient.http_client import HTTPClient 5 | from url_util import endpoint 6 | 7 | 8 | def block_number(): 9 | try: 10 | url = endpoint() 11 | response = HTTPClient(url).request("blockNumber", []) 12 | except: 13 | return None 14 | 15 | return response 16 | 17 | 18 | def main(): 19 | number = block_number() 20 | if number: 21 | print(int(number, 16)) 22 | else: 23 | print("None") 24 | 25 | 26 | if __name__ == "__main__": 27 | main() 28 | -------------------------------------------------------------------------------- /tests/compatibility/check_genesis.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -e 3 | 4 | if [[ `uname` == 'Darwin' ]] 5 | then 6 | SOURCE_DIR=$(realpath $(dirname $0)/../..) 7 | else 8 | SOURCE_DIR=$(readlink -f $(dirname $0)/../..) 9 | fi 10 | BINARY_DIR=${SOURCE_DIR}/target/install 11 | 12 | cd ${BINARY_DIR} \ 13 | && ./scripts/create_cita_config.py create \ 14 | --super_admin "0x4b5ae4567ad5d9fb92bc9afd6a657e6fa13a2523" \ 15 | --nodes "127.0.0.1:4000" \ 16 | && python3 ${SOURCE_DIR}/tests/compatibility/check_genesis.py \ 17 | --genesis test-chain/0/genesis.json \ 18 | && rm -rf test-chain genesis 19 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [workspace] 2 | members = ["cita-auth" 3 | ,"cita-jsonrpc" 4 | ,"cita-chain" 5 | ,"cita-bft" 6 | ,"cita-network" 7 | ,"cita-executor" 8 | ,"cita-forever" 9 | ,"tools/create-key-addr" 10 | ,"tools/snapshot-tool" 11 | ,"tools/create-genesis" 12 | ,"tools/relayer-parser" 13 | ,"tests/chain-executor-mock" 14 | ,"tests/consensus-mock" 15 | ,"tests/chain-performance-by-mq" 16 | ,"tests/box-executor" 17 | ,"tests/json-test" 18 | ] 19 | 20 | [profile.bench] 21 | opt-level = 3 22 | debug = false 23 | rpath = false 24 | lto = false 25 | debug-assertions = false 26 | codegen-units = 1 27 | panic = 'unwind' 28 | -------------------------------------------------------------------------------- /scripts/txtool/txtool/peer_count.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # coding=utf-8 3 | 4 | from jsonrpcclient.http_client import HTTPClient 5 | from url_util import endpoint 6 | 7 | 8 | def peer_count(): 9 | try: 10 | url = endpoint() 11 | response = HTTPClient(url).request("peerCount", []) 12 | except: 13 | return None 14 | 15 | return response 16 | 17 | 18 | def main(): 19 | count = peer_count() 20 | if count is not None: 21 | print(int(count, 16)) 22 | else: 23 | print("Please check CITA is on.") 24 | 25 | 26 | if __name__ == "__main__": 27 | main() 28 | -------------------------------------------------------------------------------- /scripts/contracts/src/system/EmergencyIntervention.sol: -------------------------------------------------------------------------------- 1 | pragma solidity 0.4.24; 2 | 3 | import "../common/Admin.sol"; 4 | import "../common/ReservedAddrPublic.sol"; 5 | import "../../interaction/interface/IEmergencyIntervention.sol"; 6 | 7 | contract EmergencyIntervention is IEmergencyIntervention, ReservedAddrPublic { 8 | bool public state; 9 | 10 | Admin admin = Admin(adminAddr); 11 | 12 | modifier onlyAdmin { 13 | if (admin.isAdmin(msg.sender)) 14 | _; 15 | else return; 16 | } 17 | 18 | function setState(bool _state) 19 | public 20 | onlyAdmin 21 | { 22 | state = _state; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /tools/create-key-addr/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "create-key-addr" 3 | version = "0.1.0" 4 | authors = ["Cryptape Technologies "] 5 | edition = "2018" 6 | 7 | [dependencies] 8 | cita-crypto = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 9 | hashable = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 10 | 11 | [features] 12 | default = ["secp256k1", "sha3hash"] 13 | secp256k1 = ["cita-crypto/secp256k1"] 14 | ed25519 = ["cita-crypto/ed25519"] 15 | sm2 = ["cita-crypto/sm2"] 16 | sha3hash = ["hashable/sha3hash"] 17 | blake2bhash = ["hashable/blake2bhash"] 18 | sm3hash = ["hashable/sm3hash"] 19 | -------------------------------------------------------------------------------- /tools/create-genesis/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "create-genesis" 3 | version = "0.1.0" 4 | authors = ["Cryptape Technologies "] 5 | edition = "2018" 6 | 7 | [dependencies] 8 | serde = { version = "1.0", features = ["derive"] } 9 | serde_yaml = "0.8" 10 | json = "0.11.13" 11 | serde_json = "1.0.39" 12 | ethabi = "7.0.0" 13 | ethereum-types = "0.5.2" 14 | hex = "0.3" 15 | tiny-keccak = "1.4.2" 16 | libsecp256k1 = "0.2.2" 17 | clap = "2.33.0" 18 | 19 | libproto = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 20 | 21 | core-executor = { path="../../cita-executor/core", default-features = false} 22 | evm = { path="../../cita-executor/evm"} 23 | -------------------------------------------------------------------------------- /scripts/contracts/tests/test/helpers/permission.js: -------------------------------------------------------------------------------- 1 | const fs = require('fs'); 2 | const util = require('./util'); 3 | const config = require('../config'); 4 | 5 | const { genContract } = util; 6 | 7 | const { permission } = config.contract; 8 | const abi = JSON.parse(fs.readFileSync('../interaction/abi/Permission.abi')); 9 | 10 | const contract = genContract(abi, permission); 11 | 12 | // queryInfo 13 | const queryInfo = () => contract.methods.queryInfo().call('pending'); 14 | 15 | // inPermission 16 | const inPermission = (cont, func) => contract.methods.inPermission( 17 | cont, 18 | func, 19 | ).call('pending'); 20 | 21 | module.exports = { 22 | queryInfo, 23 | inPermission, 24 | abi, 25 | }; 26 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /cita-chain/core/README.md: -------------------------------------------------------------------------------- 1 | # Chain microservice core for CITA 2 | 3 | Files below are extracted from [Parity](https://github.com/paritytech/parity): 4 | 5 | - ./src/cache_manager.rs 6 | - ./src/env_info.rs 7 | - ./src/snapshot/mod.rs 8 | - ./src/snapshot/io.rs 9 | - ./src/snapshot/error.rs 10 | - ./src/snapshot/service.rs 11 | - ./src/db.rs 12 | - ./src/basic_types.rs 13 | - ./src/state/mod.rs 14 | - ./src/state/backend.rs 15 | - ./src/libchain/cache.rs 16 | - ./src/filters/mod.rs 17 | - ./src/filters/poll_manager.rs 18 | - ./src/filters/poll_filter.rs 19 | - ./src/filters/eth_filter.rs 20 | - ./src/state_db.rs 21 | 22 | with following modifications: 23 | 24 | - ./src/error.rs 25 | - ./src/libchain/extras.rs 26 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: bug 6 | assignees: jerry-yu 7 | 8 | --- 9 | 10 | ## Description 11 | 12 | [Description of the issue] 13 | 14 | ## Steps to Reproduce 15 | 16 | 1. [First Step] 17 | 2. [Second Step] 18 | 3. [and so on …] 19 | 20 | **Expected behavior**: [What you expect to happen] 21 | 22 | **Actual behavior**: [What actually happens] 23 | 24 | **Reproduce how often**: [What percentage of the time does it reproduce?] 25 | 26 | ## Versions 27 | 28 | [The versions of the CITA, operating systems or VM software you use] 29 | 30 | ## Additional Information 31 | 32 | [Any other information which would be helpful to reproduce the issue]. 33 | -------------------------------------------------------------------------------- /tests/json-test/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "state-test" 3 | version = "0.1.0" 4 | authors = ["Cryptape Technologies "] 5 | edition = "2018" 6 | 7 | [dependencies] 8 | ethereum-types = "0.4.0" 9 | serde = "1.0" 10 | serde_derive = "1.0" 11 | serde_json = "1.0" 12 | hex = "0.3" 13 | libsecp256k1 = "0.2.2" 14 | tiny-keccak = "1.4.2" 15 | env_logger = "0.6.1" 16 | log = "0.4.0" 17 | 18 | libproto = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 19 | core-executor = { path="../../cita-executor/core"} 20 | evm = { path="../../cita-executor/evm"} 21 | 22 | [features] 23 | default = ["secp256k1", "sha3hash"] 24 | secp256k1 = [] 25 | ed25519 = [] 26 | sm2 = [] 27 | sha3hash = [] 28 | blake2bhash = [] 29 | sm3hash = [] 30 | -------------------------------------------------------------------------------- /scripts/contracts/src/lib/ContractCheck.sol: -------------------------------------------------------------------------------- 1 | pragma solidity 0.4.24; 2 | 3 | /// @title A library for operation of contract 4 | /// @author ["Cryptape Technologies "] 5 | /// @notice Use prefix to import it 6 | /// @dev TODO more interface 7 | library ContractCheck { 8 | 9 | /// @notice Check an address is contract address 10 | /// @param _target The address to be checked 11 | /// @return true if successed, false otherwise 12 | function isContract(address _target) 13 | internal 14 | view 15 | returns (bool) 16 | { 17 | uint size; 18 | // solium-disable-next-line security/no-inline-assembly 19 | assembly { size := extcodesize(_target) } 20 | return size > 0; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /scripts/contracts/tests/test/helpers/admin.js: -------------------------------------------------------------------------------- 1 | const fs = require('fs'); 2 | const util = require('./util'); 3 | const config = require('../config'); 4 | 5 | const { genContract, genTxParams } = util; 6 | 7 | const { superAdmin } = config; 8 | const { admin } = config.contract; 9 | const abi = JSON.parse(fs.readFileSync('../interaction/abi/Admin.abi')); 10 | const contract = genContract(abi, admin); 11 | 12 | // addAdmin 13 | const update = async (account, _sender = superAdmin) => { 14 | const param = await genTxParams(_sender); 15 | return contract.methods.update(account).send(param); 16 | }; 17 | 18 | // isAdmin 19 | const isAdmin = account => contract.methods.isAdmin(account).call('pending'); 20 | 21 | module.exports = { 22 | update, 23 | isAdmin, 24 | }; 25 | -------------------------------------------------------------------------------- /cita-executor/src/tests/mod.rs: -------------------------------------------------------------------------------- 1 | // CITA 2 | // Copyright 2016-2018 Cryptape Technologies LLC. 3 | 4 | // This program is free software: you can redistribute it 5 | // and/or modify it under the terms of the GNU General Public 6 | // License as published by the Free Software Foundation, 7 | // either version 3 of the License, or (at your option) any 8 | // later version. 9 | 10 | // This program is distributed in the hope that it will be 11 | // useful, but WITHOUT ANY WARRANTY; without even the implied 12 | // warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR 13 | // PURPOSE. See the GNU General Public License for more details. 14 | 15 | // You should have received a copy of the GNU General Public License 16 | // along with this program. If not, see . 17 | 18 | pub mod helpers; 19 | -------------------------------------------------------------------------------- /cita-executor/core/src/tests/mod.rs: -------------------------------------------------------------------------------- 1 | // CITA 2 | // Copyright 2016-2017 Cryptape Technologies LLC. 3 | 4 | // This program is free software: you can redistribute it 5 | // and/or modify it under the terms of the GNU General Public 6 | // License as published by the Free Software Foundation, 7 | // either version 3 of the License, or (at your option) any 8 | // later version. 9 | 10 | // This program is distributed in the hope that it will be 11 | // useful, but WITHOUT ANY WARRANTY; without even the implied 12 | // warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR 13 | // PURPOSE. See the GNU General Public License for more details. 14 | 15 | // You should have received a copy of the GNU General Public License 16 | // along with this program. If not, see . 17 | 18 | pub mod amend_data_test; 19 | pub mod helpers; 20 | -------------------------------------------------------------------------------- /cita-executor/core/src/benches/mod.rs: -------------------------------------------------------------------------------- 1 | // CITA 2 | // Copyright 2016-2019 Cryptape Technologies LLC. 3 | 4 | // This program is free software: you can redistribute it 5 | // and/or modify it under the terms of the GNU General Public 6 | // License as published by the Free Software Foundation, 7 | // either version 3 of the License, or (at your option) any 8 | // later version. 9 | 10 | // This program is distributed in the hope that it will be 11 | // useful, but WITHOUT ANY WARRANTY; without even the implied 12 | // warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR 13 | // PURPOSE. See the GNU General Public License for more details. 14 | 15 | // You should have received a copy of the GNU General Public License 16 | // along with this program. If not, see . 17 | 18 | #[cfg(all(feature = "benches", test))] 19 | pub mod executor; 20 | -------------------------------------------------------------------------------- /scripts/txtool/txtool/config/logging.yml: -------------------------------------------------------------------------------- 1 | version: 1 2 | formatters: 3 | simple: 4 | format: '%(asctime)s - %(filename)s - %(name)s %(lineno)d - %(levelname)s - %(message)s' 5 | handlers: 6 | console: 7 | class: logging.FileHandler 8 | level: INFO 9 | formatter: simple 10 | filename: info.log 11 | console_debug: 12 | class: logging.FileHandler 13 | level: DEBUG 14 | formatter: simple 15 | filename: info.log 16 | console_error: 17 | class: logging.StreamHandler 18 | level: ERROR 19 | formatter: simple 20 | stream: ext://sys.stderr 21 | loggers: 22 | info: 23 | level: INFO 24 | handlers: [console] 25 | propagate: yes 26 | debug: 27 | level: DEBUG 28 | handlers: [console_debug] 29 | propagate: yes 30 | error: 31 | level: ERROR 32 | handlers: [console_error] 33 | propagate: yes 34 | -------------------------------------------------------------------------------- /cita-executor/core/src/spec/mod.rs: -------------------------------------------------------------------------------- 1 | // CITA 2 | // Copyright 2016-2018 Cryptape Technologies LLC. 3 | 4 | // This program is free software: you can redistribute it 5 | // and/or modify it under the terms of the GNU General Public 6 | // License as published by the Free Software Foundation, 7 | // either version 3 of the License, or (at your option) any 8 | // later version. 9 | 10 | // This program is distributed in the hope that it will be 11 | // useful, but WITHOUT ANY WARRANTY; without even the implied 12 | // warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR 13 | // PURPOSE. See the GNU General Public License for more details. 14 | 15 | // You should have received a copy of the GNU General Public License 16 | // along with this program. If not, see . 17 | 18 | mod builtin; 19 | 20 | pub use self::builtin::{Builtin, Linear, Pricing}; 21 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | # Compiled files 5 | *.o 6 | *.so 7 | *.rlib 8 | *.dll 9 | *.pyc 10 | 11 | # Executables 12 | *.exe 13 | 14 | # intermedia file directory 15 | target/ 16 | */target/ 17 | 18 | # Cargo lock in subs 19 | **/Cargo.lock 20 | 21 | 22 | # editor specific 23 | # vim stuff 24 | *.swp 25 | # emacs stuff 26 | *~ 27 | # vscode 28 | .vscode 29 | # jetbrains ide stuff 30 | .idea 31 | *.iml 32 | # mac stuff 33 | .DS_Store 34 | 35 | # gdb files 36 | .gdb_history 37 | 38 | # ctags 39 | TAGS 40 | 41 | # sphinx 42 | docs/build 43 | 44 | # vagrant file 45 | .vagrant 46 | 47 | # tmp files 48 | tests/wrk_benchmark_test/hash.txt 49 | consensus/authority_round/data/ 50 | 51 | scripts/txtool/output 52 | scripts/txtool/txtool/*.log 53 | 54 | # node 55 | **/node_modules 56 | yarn-error.log 57 | 58 | # docs 59 | docs/site 60 | 61 | # localtime for macos users 62 | localtime 63 | -------------------------------------------------------------------------------- /cita-executor/core/src/contracts/tools/mod.rs: -------------------------------------------------------------------------------- 1 | // CITA 2 | // Copyright 2016-2018 Cryptape Technologies LLC. 3 | 4 | // This program is free software: you can redistribute it 5 | // and/or modify it under the terms of the GNU General Public 6 | // License as published by the Free Software Foundation, 7 | // either version 3 of the License, or (at your option) any 8 | // later version. 9 | 10 | // This program is distributed in the hope that it will be 11 | // useful, but WITHOUT ANY WARRANTY; without even the implied 12 | // warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR 13 | // PURPOSE. See the GNU General Public License for more details. 14 | 15 | // You should have received a copy of the GNU General Public License 16 | // along with this program. If not, see . 17 | 18 | //! Contracts Tools. 19 | 20 | pub mod decode; 21 | pub mod method; 22 | -------------------------------------------------------------------------------- /scripts/contracts/tests/test/helpers/auto_exec.js: -------------------------------------------------------------------------------- 1 | const fs = require('fs'); 2 | const util = require('./util'); 3 | const config = require('../config'); 4 | 5 | const { genContract, genTxParams } = util; 6 | 7 | const { superAdmin } = config; 8 | const { autoExecAddr } = config.contract; 9 | const abi = JSON.parse(fs.readFileSync('../interaction/abi/AutoExec.abi')); 10 | const contract = genContract(abi, autoExecAddr); 11 | 12 | // register 13 | const register = async (contAddr, _sender = superAdmin) => { 14 | const param = await genTxParams(_sender); 15 | return contract.methods.register(contAddr).send(param); 16 | }; 17 | 18 | // autoExec 19 | const autoExec = async (_sender = superAdmin) => { 20 | const param = await genTxParams(_sender); 21 | return contract.methods.autoExec().send(param); 22 | }; 23 | 24 | module.exports = { 25 | register, 26 | autoExec, 27 | }; 28 | -------------------------------------------------------------------------------- /cita-executor/core/src/contracts/mod.rs: -------------------------------------------------------------------------------- 1 | // CITA 2 | // Copyright 2016-2018 Cryptape Technologies LLC. 3 | 4 | // This program is free software: you can redistribute it 5 | // and/or modify it under the terms of the GNU General Public 6 | // License as published by the Free Software Foundation, 7 | // either version 3 of the License, or (at your option) any 8 | // later version. 9 | 10 | // This program is distributed in the hope that it will be 11 | // useful, but WITHOUT ANY WARRANTY; without even the implied 12 | // warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR 13 | // PURPOSE. See the GNU General Public License for more details. 14 | 15 | // You should have received a copy of the GNU General Public License 16 | // along with this program. If not, see . 17 | 18 | //! Contracts. 19 | 20 | pub mod native; 21 | pub mod solc; 22 | pub mod tools; 23 | -------------------------------------------------------------------------------- /cita-executor/evm/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "evm" 3 | version = "0.1.0" 4 | authors = ["Parity Technologies ", "Cryptape Technologies "] 5 | edition = "2018" 6 | 7 | [dependencies] 8 | cita-logger = "0.1.0" 9 | cita-types = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 10 | hashable = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 11 | lazy_static = "0.2" 12 | util = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 13 | bit-set = "0.4" 14 | common-types = { path = "../../cita-chain/types" } 15 | rlp = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 16 | rustc-hex = "1.0" 17 | db = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 18 | 19 | [features] 20 | evm-debug = [] 21 | evm-debug-tests = ["evm-debug"] 22 | -------------------------------------------------------------------------------- /scripts/txtool/txtool/check.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # coding=utf-8 3 | 4 | # TODO List all the acceptable params 5 | # TODO Handle passed params 6 | 7 | from log import logger 8 | from jsonrpcclient.http_client import HTTPClient 9 | from url_util import endpoint 10 | 11 | # '{"jsonrpc":"2.0","method":"blockNumber","params":[],"id":1}' 12 | 13 | 14 | def check_cita_status(): 15 | result_status = False 16 | try: 17 | url = endpoint() 18 | response = HTTPClient(url).request("blockNumber", []) 19 | result_status = int(response, base=16) > 0 20 | except Exception as e: 21 | logger.error(e) 22 | result_status = False 23 | finally: 24 | return result_status 25 | 26 | 27 | if __name__ == '__main__': 28 | if check_cita_status(): 29 | print("CITA is on.") 30 | else: 31 | print("CITA is not working.") 32 | -------------------------------------------------------------------------------- /scripts/contracts/tests/test/helpers/group.js: -------------------------------------------------------------------------------- 1 | const fs = require('fs'); 2 | const util = require('./util'); 3 | const config = require('../config'); 4 | 5 | const { genContract } = util; 6 | 7 | const { group } = config.contract; 8 | const abi = JSON.parse(fs.readFileSync('../interaction/abi/Group.abi')); 9 | 10 | const contract = genContract(abi, group); 11 | 12 | // queryInfo 13 | const queryInfo = () => contract.methods.queryInfo().call('pending'); 14 | 15 | // queryAccounts 16 | const queryAccounts = () => contract.methods.queryAccounts().call('pending'); 17 | 18 | // queryParent 19 | const queryParent = () => contract.methods.queryParent().call('pending'); 20 | 21 | // inGroup 22 | const inGroup = account => contract.methods.inGroup(account).call('pending'); 23 | 24 | module.exports = { 25 | queryInfo, 26 | queryAccounts, 27 | queryParent, 28 | inGroup, 29 | abi, 30 | }; 31 | -------------------------------------------------------------------------------- /scripts/contracts/tests/test/helpers/version_manager.js: -------------------------------------------------------------------------------- 1 | const fs = require('fs'); 2 | const util = require('./util'); 3 | const config = require('../config'); 4 | 5 | const { genContract, genTxParams } = util; 6 | 7 | const { superAdmin } = config; 8 | const { versionManager } = config.contract; 9 | const abi = JSON.parse(fs.readFileSync('../interaction/abi/VersionManager.abi')); 10 | const contract = genContract(abi, versionManager); 11 | 12 | const getVersion = () => contract.methods.getVersion().call('pending'); 13 | 14 | const setProtocolVersion = async (account, _sender = superAdmin) => { 15 | const param = await genTxParams(_sender); 16 | return contract.methods.setProtocolVersion(account).send(param); 17 | }; 18 | 19 | const getProtocolVersion = () => contract.methods.getProtocolVersion().call('pending'); 20 | 21 | module.exports = { 22 | setProtocolVersion, 23 | getProtocolVersion, 24 | getVersion, 25 | }; 26 | -------------------------------------------------------------------------------- /scripts/txtool/txtool/block_by_hash.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # coding=utf-8 3 | 4 | import argparse 5 | from jsonrpcclient.http_client import HTTPClient 6 | from url_util import endpoint 7 | 8 | 9 | def block_by_hash(params): 10 | try: 11 | url = endpoint() 12 | response = HTTPClient(url).request("getBlockByHash", params) 13 | except: 14 | return None 15 | 16 | return response 17 | 18 | 19 | def main(): 20 | parser = argparse.ArgumentParser() 21 | parser.add_argument("hash", help="block hash as param") 22 | parser.add_argument('--detail', dest='detail', action='store_true') 23 | parser.add_argument('--no-detail', dest='detail', action='store_false') 24 | parser.set_defaults(detail=True) 25 | args = parser.parse_args() 26 | 27 | params = [args.hash, args.detail] 28 | resp = block_by_hash(params) 29 | 30 | 31 | if __name__ == "__main__": 32 | main() 33 | -------------------------------------------------------------------------------- /docs/style-guide/logging.md: -------------------------------------------------------------------------------- 1 | # Logging Format 2 | 3 | TBD 4 | 5 | ---------------- 6 | 7 | # 日志格式 8 | 9 | 日志分为三个部分,以 `|` 符号分隔,分别是 10 | 11 | * [时间](#时间) 12 | * [位置](#位置) 13 | * [消息](#消息) 14 | 15 | 每个部分内部以 `-` 符号分隔。 16 | 17 | 参考实现如下所示: 18 | 19 | ``` 20 | "{d(%Y-%m-%d - %H:%M:%S)} | {T:10} - {t:10} - {L:5} | {l:5} - {m}{n}" 21 | ``` 22 | 23 | 可适当修改数字调整相关信息的字符长度。 24 | 25 | ## 时间 26 | 27 | 使用 `local` 时间。 28 | 29 | ## 位置 30 | 31 | 日志产生位置的相关信息: 32 | 33 | * 线程名称: 当前线程的名称 34 | * 所在路径: 日志的 `module::path` 35 | * 所在行数: 日志所在的行数 36 | 37 | ## 消息 38 | 39 | 日志消息的相关信息: 40 | 41 | * 级别: 日志等级 42 | * 主题: 每个模块的主题固定,增加主题先提交此文档,主题用 `[]` 标记。 若无则省略 43 | 44 | - `cita-chain`: TBD 45 | - `cita-executor`: TBD 46 | - `cita-bft`: TBD 47 | - `cita-auth`: TBD 48 | - `cita-jsonrpc`: TBD 49 | - `cita-network`: TBD 50 | - `cita-forever`: TBD 51 | 52 | * 内容: 具体的消息内容。 53 | 54 | - 避免无意义的数据 55 | - `Hash` 值用 `0x1234...5678` 格式 56 | -------------------------------------------------------------------------------- /scripts/txtool/txtool/block_by_number.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # coding=utf-8 3 | 4 | import argparse 5 | from jsonrpcclient.http_client import HTTPClient 6 | from url_util import endpoint 7 | 8 | 9 | def block_by_number(params): 10 | try: 11 | url = endpoint() 12 | response = HTTPClient(url).request("getBlockByNumber", params) 13 | except: 14 | return None 15 | 16 | return response 17 | 18 | 19 | def main(): 20 | parser = argparse.ArgumentParser() 21 | parser.add_argument("number", help="block number as param") 22 | parser.add_argument('--detail', dest='detail', action='store_true') 23 | parser.add_argument('--no-detail', dest='detail', action='store_false') 24 | parser.set_defaults(detail=True) 25 | args = parser.parse_args() 26 | 27 | params = [args.number, args.detail] 28 | resp = block_by_number(params) 29 | 30 | 31 | if __name__ == "__main__": 32 | main() 33 | -------------------------------------------------------------------------------- /cita-executor/core/src/contracts/native/mod.rs: -------------------------------------------------------------------------------- 1 | // CITA 2 | // Copyright 2016-2018 Cryptape Technologies LLC. 3 | 4 | // This program is free software: you can redistribute it 5 | // and/or modify it under the terms of the GNU General Public 6 | // License as published by the Free Software Foundation, 7 | // either version 3 of the License, or (at your option) any 8 | // later version. 9 | 10 | // This program is distributed in the hope that it will be 11 | // useful, but WITHOUT ANY WARRANTY; without even the implied 12 | // warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR 13 | // PURPOSE. See the GNU General Public License for more details. 14 | 15 | // You should have received a copy of the GNU General Public License 16 | // along with this program. If not, see . 17 | 18 | mod crosschain_verify; 19 | pub mod factory; 20 | #[cfg(test)] 21 | mod storage; 22 | #[cfg(feature = "privatetx")] 23 | mod zk_privacy; 24 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # EditorConfig is awesome: https://EditorConfig.org 2 | 3 | # top-most EditorConfig file 4 | root = true 5 | 6 | # Unix-style newlines with a newline ending every file 7 | [*] 8 | end_of_line = lf 9 | insert_final_newline = true 10 | trim_trailing_whitespace = true 11 | # Set default charset 12 | charset = utf-8 13 | indent_style = space 14 | indent_size = 4 15 | 16 | # Follow https://github.com/rust-dev-tools/fmt-rfcs/blob/master/guide/guide.md 17 | [*.rs] 18 | indent_style = space 19 | indent_size = 4 20 | max_line_length = 100 21 | 22 | # Matches multiple files with brace expansion notation 23 | [*.{json,py,md,markdown}] 24 | indent_style = space 25 | indent_size = 4 26 | 27 | [Makefile] 28 | indent_style = tab 29 | indent_size = 4 30 | 31 | [*.yml] 32 | indent_style = space 33 | indent_size = 2 34 | 35 | # Indentation override for all JS under scripts directory 36 | [scripts/**.js] 37 | indent_style = space 38 | indent_size = 2 39 | -------------------------------------------------------------------------------- /cita-chain/core/src/libchain/mod.rs: -------------------------------------------------------------------------------- 1 | // CITA 2 | // Copyright 2016-2019 Cryptape Technologies LLC. 3 | 4 | // This program is free software: you can redistribute it 5 | // and/or modify it under the terms of the GNU General Public 6 | // License as published by the Free Software Foundation, 7 | // either version 3 of the License, or (at your option) any 8 | // later version. 9 | 10 | // This program is distributed in the hope that it will be 11 | // useful, but WITHOUT ANY WARRANTY; without even the implied 12 | // warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR 13 | // PURPOSE. See the GNU General Public License for more details. 14 | 15 | // You should have received a copy of the GNU General Public License 16 | // along with this program. If not, see . 17 | 18 | pub mod cache; 19 | pub mod chain; 20 | pub mod rich_status; 21 | pub mod status; 22 | pub use crate::cita_db::journaldb; 23 | pub use crate::types::block::*; 24 | -------------------------------------------------------------------------------- /cita-executor/core/src/trace/types/mod.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2015-2017 Parity Technologies (UK) Ltd. 2 | // This file is part of Parity. 3 | 4 | // This software is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | 9 | // This software is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | 14 | // You should have received a copy of the GNU General Public License 15 | // along with Parity. If not, see . 16 | 17 | //! Types used in the public api 18 | 19 | pub mod error; 20 | pub mod filter; 21 | pub mod flat; 22 | pub mod localized; 23 | pub mod trace; 24 | -------------------------------------------------------------------------------- /scripts/txtool/txtool/url_util.py: -------------------------------------------------------------------------------- 1 | import configparser 2 | try: 3 | import httplib 4 | except: 5 | import http.client as httplib 6 | 7 | SETTING_PATH = 'config/setting.cfg' 8 | 9 | 10 | def _join_url(host, port, scheme='http://'): 11 | return scheme + host + ':' + port 12 | 13 | 14 | def host(): 15 | config = configparser.ConfigParser() 16 | config.read(SETTING_PATH) 17 | host = config.get('jsonrpc_url', 'host') 18 | return host 19 | 20 | 21 | def endpoint(): 22 | config = configparser.ConfigParser() 23 | config.read(SETTING_PATH) 24 | host = config.get('jsonrpc_url', 'host') 25 | port = config.get('jsonrpc_url', 'port') 26 | return _join_url(host, port) 27 | 28 | 29 | def have_internet(url): 30 | conn = httplib.HTTPConnection(url, timeout=4) 31 | try: 32 | conn.request("HEAD", "/") 33 | conn.close() 34 | return True 35 | except: 36 | conn.close() 37 | return False 38 | -------------------------------------------------------------------------------- /cita-executor/build.rs: -------------------------------------------------------------------------------- 1 | // CITA 2 | // Copyright 2016-2019 Cryptape Technologies LLC. 3 | 4 | // This program is free software: you can redistribute it 5 | // and/or modify it under the terms of the GNU General Public 6 | // License as published by the Free Software Foundation, 7 | // either version 3 of the License, or (at your option) any 8 | // later version. 9 | 10 | // This program is distributed in the hope that it will be 11 | // useful, but WITHOUT ANY WARRANTY; without even the implied 12 | // warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR 13 | // PURPOSE. See the GNU General Public License for more details. 14 | 15 | // You should have received a copy of the GNU General Public License 16 | // along with this program. If not, see . 17 | 18 | use std::env; 19 | use util::build_info::gen_build_info; 20 | 21 | fn main() { 22 | let out_dir = env::var("OUT_DIR").unwrap(); 23 | gen_build_info(out_dir.as_ref(), "build_info.rs"); 24 | } 25 | -------------------------------------------------------------------------------- /cita-jsonrpc/build.rs: -------------------------------------------------------------------------------- 1 | // CITA 2 | // Copyright 2016-2019 Cryptape Technologies LLC. 3 | 4 | // This program is free software: you can redistribute it 5 | // and/or modify it under the terms of the GNU General Public 6 | // License as published by the Free Software Foundation, 7 | // either version 3 of the License, or (at your option) any 8 | // later version. 9 | 10 | // This program is distributed in the hope that it will be 11 | // useful, but WITHOUT ANY WARRANTY; without even the implied 12 | // warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR 13 | // PURPOSE. See the GNU General Public License for more details. 14 | 15 | // You should have received a copy of the GNU General Public License 16 | // along with this program. If not, see . 17 | 18 | use std::env; 19 | 20 | use util::build_info::gen_build_info; 21 | 22 | fn main() { 23 | let out_dir = env::var("OUT_DIR").unwrap(); 24 | gen_build_info(out_dir.as_ref(), "build_info.rs"); 25 | } 26 | -------------------------------------------------------------------------------- /cita-network/build.rs: -------------------------------------------------------------------------------- 1 | // CITA 2 | // Copyright 2016-2018 Cryptape Technologies LLC. 3 | 4 | // This program is free software: you can redistribute it 5 | // and/or modify it under the terms of the GNU General Public 6 | // License as published by the Free Software Foundation, 7 | // either version 3 of the License, or (at your option) any 8 | // later version. 9 | 10 | // This program is distributed in the hope that it will be 11 | // useful, but WITHOUT ANY WARRANTY; without even the implied 12 | // warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR 13 | // PURPOSE. See the GNU General Public License for more details. 14 | 15 | // You should have received a copy of the GNU General Public License 16 | // along with this program. If not, see . 17 | 18 | use std::env; 19 | 20 | use util::build_info::gen_build_info; 21 | 22 | fn main() { 23 | let out_dir = env::var("OUT_DIR").unwrap(); 24 | gen_build_info(out_dir.as_ref(), "build_info.rs"); 25 | } 26 | -------------------------------------------------------------------------------- /cita-chain/core/src/filters/mod.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2015-2017 Parity Technologies (UK) Ltd. 2 | // This file is part of Parity. 3 | 4 | // This software is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | 9 | // This software is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | 14 | // You should have received a copy of the GNU General Public License 15 | // along with Parity. If not, see . 16 | 17 | pub mod eth_filter; 18 | pub mod poll_filter; 19 | pub mod poll_manager; 20 | 21 | pub use self::poll_filter::{limit_logs, PollFilter}; 22 | pub use self::poll_manager::{PollId, PollManager}; 23 | -------------------------------------------------------------------------------- /scripts/contracts/tests/test/helpers/role_auth.js: -------------------------------------------------------------------------------- 1 | const fs = require('fs'); 2 | const util = require('./util'); 3 | const config = require('../config'); 4 | 5 | const { genContract } = util; 6 | 7 | const { roleAuth } = config.contract; 8 | const abi = JSON.parse(fs.readFileSync('../interaction/abi/RoleAuth.abi')); 9 | 10 | const contract = genContract(abi, roleAuth); 11 | 12 | // queryRoles 13 | const queryRoles = account => contract.methods.queryRoles(account).call('pending'); 14 | 15 | // queryAccounts 16 | const queryAccounts = account => contract.methods.queryAccounts(account).call('pending'); 17 | 18 | // queryPermissions 19 | const queryPermissions = role => contract.methods.queryPermissions(role).call('pending'); 20 | 21 | // hasPermission 22 | const hasPermission = (account, permission) => contract.methods.hasPermission( 23 | account, 24 | permission, 25 | ).call('pending'); 26 | 27 | module.exports = { 28 | queryRoles, 29 | queryAccounts, 30 | queryPermissions, 31 | hasPermission, 32 | }; 33 | -------------------------------------------------------------------------------- /cita-auth/build.rs: -------------------------------------------------------------------------------- 1 | // CITA 2 | // Copyright 2016-2019 Cryptape Technologies LLC. 3 | 4 | // This program is free software: you can redistribute it 5 | // and/or modify it under the terms of the GNU General Public 6 | // License as published by the Free Software Foundation, 7 | // either version 3 of the License, or (at your option) any 8 | // later version. 9 | 10 | // This program is distributed in the hope that it will be 11 | // useful, but WITHOUT ANY WARRANTY; without even the implied 12 | // warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR 13 | // PURPOSE. See the GNU General Public License for more details. 14 | 15 | // You should have received a copy of the GNU General Public License 16 | // along with this program. If not, see . 17 | 18 | extern crate util; 19 | 20 | use std::env; 21 | 22 | use util::build_info::gen_build_info; 23 | 24 | fn main() { 25 | let out_dir = env::var("OUT_DIR").unwrap(); 26 | gen_build_info(out_dir.as_ref(), "build_info.rs"); 27 | } 28 | -------------------------------------------------------------------------------- /scripts/replace_default_feature.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | set -e 4 | 5 | function replace_default_feature () { 6 | local workspacedir="${1}" 7 | local old_feature="${2}" 8 | local new_feature="${3}" 9 | if [ "${old_feature}" = "${new_feature}" ]; then 10 | return 11 | fi 12 | local before_feature='[ \t]*default[ \t]*=[ \t]*\[.*\"' 13 | local after_feature='\".*' 14 | find "${workspacedir}" -mindepth 2 -name "Cargo.toml" -print0 \ 15 | | xargs -0 grep -l "^${before_feature}${old_feature}${after_feature}" \ 16 | | while read -r cargotoml; do 17 | if [ -f "${cargotoml}" ]; then 18 | echo "[Info ] Replace [${old_feature}] by [${new_feature}] for [${cargotoml}] ..." 19 | sed -i "s/\(${before_feature}\)${old_feature}\(${after_feature}\)\$/\1${new_feature}\2/" "${cargotoml}" 20 | else 21 | echo "[Error] [${cargotoml}] is not a file." 22 | fi 23 | done 24 | } 25 | 26 | replace_default_feature "$@" 27 | -------------------------------------------------------------------------------- /tools/snapshot-tool/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "snapshot-tool" 3 | version = "0.2.0" 4 | authors = ["Cryptape Technologies "] 5 | edition = "2018" 6 | 7 | [dependencies] 8 | dotenv = "0.13.0" 9 | clap = "2" 10 | fs2 = "0.4.3" 11 | cita-logger = "0.1.0" 12 | util = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 13 | pubsub = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 14 | libproto = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 15 | error = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 16 | 17 | [features] 18 | default = ["secp256k1", "sha3hash", "rabbitmq"] 19 | secp256k1 = ["libproto/secp256k1"] 20 | ed25519 = ["libproto/ed25519"] 21 | sm2 = ["libproto/sm2"] 22 | sha3hash = ["libproto/sha3hash"] 23 | blake2bhash = ["libproto/blake2bhash"] 24 | sm3hash = ["libproto/sm3hash"] 25 | rabbitmq = ["pubsub/rabbitmq"] 26 | zeromq = ["pubsub/zeromq"] 27 | kafka = ["pubsub/kafka"] 28 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | CARGO=RUSTFLAGS='-F warnings' cargo 2 | 3 | .PHONY: debug release test test-release bench fmt cov clean clippy security_audit 4 | 5 | debug: 6 | $(CARGO) build --all 7 | scripts/release.sh debug 8 | 9 | release: 10 | $(CARGO) build --all --release 11 | scripts/release.sh release 12 | 13 | test: 14 | RUST_BACKTRACE=full $(CARGO) test --all 2>&1 15 | 16 | test-release: 17 | RUST_BACKTRACE=full $(CARGO) test --release --all 18 | 19 | bench: 20 | -rm target/bench.log 21 | cargo bench --all --no-run |tee target/bench.log 22 | cargo bench --all --jobs 1 |tee -a target/bench.log 23 | 24 | fmt: 25 | cargo fmt --all -- --check 26 | 27 | cov: 28 | cargo cov test --all 29 | cargo cov report --open 30 | 31 | clean: 32 | rm -rf target/debug/ 33 | rm -rf target/release/ 34 | 35 | clippy: 36 | $(CARGO) clippy --all 37 | 38 | # use cargo-audit to audit Cargo.lock for crates with security vulnerabilities 39 | # expecting to see "Success No vulnerable packages found" 40 | security_audit: 41 | scripts/security_audit.sh 42 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "cita-forever"] 2 | path = cita-forever 3 | url = https://github.com/cryptape/cita-forever.git 4 | branch = develop 5 | [submodule "cita-bft"] 6 | path = cita-bft 7 | url = https://github.com/cryptape/cita-bft.git 8 | branch = develop 9 | [submodule "scripts/txtool/txtool/proto"] 10 | path = scripts/txtool/txtool/proto 11 | url = https://github.com/cryptape/cita-proto.git 12 | branch = master 13 | [submodule "tests/contracts"] 14 | path = tests/contracts 15 | url = https://github.com/cryptape/test-contracts.git 16 | branch = master 17 | [submodule "scripts/contracts/interaction"] 18 | path = scripts/contracts/interaction 19 | url = https://github.com/cryptape/cita-sys-interaction.git 20 | branch = master 21 | [submodule "scripts/config_tool/genesis"] 22 | path = scripts/config_tool/genesis 23 | url = https://github.com/cryptape/genesis.git 24 | branch = master 25 | [submodule "tests/jsondata"] 26 | path = tests/jsondata 27 | url = https://github.com/cryptape/cita-testdata.git 28 | branch = master 29 | -------------------------------------------------------------------------------- /scripts/contracts/tests/test/helpers/authorization.js: -------------------------------------------------------------------------------- 1 | const fs = require('fs'); 2 | const util = require('./util'); 3 | const config = require('../config'); 4 | 5 | const { genContract } = util; 6 | 7 | const { authorization } = config.contract; 8 | const abi = JSON.parse(fs.readFileSync('../interaction/abi/Authorization.abi')); 9 | const contract = genContract(abi, authorization); 10 | 11 | // queryPermissions 12 | const queryPermissions = account => contract.methods.queryPermissions(account).call('pending'); 13 | 14 | // queryAccounts 15 | const queryAccounts = perm => contract.methods.queryAccounts(perm).call('pending'); 16 | 17 | // checkPermission 18 | const checkPermission = (account, permission) => contract.methods.checkPermission( 19 | account, 20 | permission, 21 | ).call('pending'); 22 | 23 | // queryAllAccounts 24 | const queryAllAccounts = () => contract.methods.queryAllAccounts().call('pending'); 25 | 26 | module.exports = { 27 | queryPermissions, 28 | queryAccounts, 29 | checkPermission, 30 | queryAllAccounts, 31 | }; 32 | -------------------------------------------------------------------------------- /tests/integrate_test/update_version.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """ 3 | Test case of fee back to operator in charge economical mode. 4 | """ 5 | 6 | import argparse 7 | from txtool_utils import get_receipt, rpc_request, send_tx, get_balance 8 | 9 | 10 | def main(): 11 | """ Run the test. """ 12 | admin_privkey = '0x5f0258a4778057a8a7d97809bd209055b2fbafa654ce7d31ec7191066b9225e6' 13 | code = '0x62ddb8e10000000000000000000000000000000000000000000000000000000000000001' 14 | version_manager = "ffffffffffffffffffffffffffffffffff020011" 15 | 16 | opts = parse_arguments() 17 | version = opts.version 18 | 19 | tx_hash = send_tx( 20 | admin_privkey, code=code, to=version_manager, version=version) 21 | get_receipt(tx_hash) 22 | print('>>> Update version successfully!') 23 | 24 | 25 | def parse_arguments(): 26 | parser = argparse.ArgumentParser() 27 | parser.add_argument("--version", help="Tansaction version.", type=int) 28 | 29 | return parser.parse_args() 30 | 31 | 32 | if __name__ == '__main__': 33 | main() 34 | -------------------------------------------------------------------------------- /scripts/config_tool/default_config/forever.toml: -------------------------------------------------------------------------------- 1 | name="cita-forever" 2 | command = "cita-forever" 3 | pidfile = ".cita-forever.pid" 4 | 5 | [[process]] 6 | name = "cita-auth" 7 | command = "cita-auth" 8 | args = ["-c","auth.toml"] 9 | pidfile = ".cita-auth.pid" 10 | respawn = 3 11 | 12 | [[process]] 13 | name = "cita-network" 14 | command = "cita-network" 15 | args = ["-c","network.toml"] 16 | pidfile = ".cita-network.pid" 17 | respawn = 3 18 | 19 | [[process]] 20 | name = "cita-bft" 21 | command = "cita-bft" 22 | args = ["-c","consensus.toml","-p","privkey"] 23 | pidfile = ".cita-bft.pid" 24 | respawn = 3 25 | 26 | [[process]] 27 | name = "cita-jsonrpc" 28 | command = "cita-jsonrpc" 29 | args = ["-c","jsonrpc.toml"] 30 | pidfile = ".cita-jsonrpc.pid" 31 | respawn = 3 32 | 33 | 34 | [[process]] 35 | name = "cita-chain" 36 | command = "cita-chain" 37 | args = ["-c","chain.toml"] 38 | pidfile = ".cita-chain.pid" 39 | respawn = 3 40 | 41 | [[process]] 42 | name = "cita-executor" 43 | command = "cita-executor" 44 | args = ["-c","executor.toml"] 45 | pidfile = ".cita-executor.pid" 46 | respawn = 3 47 | -------------------------------------------------------------------------------- /scripts/txtool/txtool/get_code.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # coding=utf-8 3 | 4 | import argparse 5 | from jsonrpcclient.http_client import HTTPClient 6 | from url_util import endpoint 7 | 8 | 9 | def get_code(params): 10 | try: 11 | url = endpoint() 12 | response = HTTPClient(url).request("getCode", params) 13 | except: 14 | return None 15 | 16 | return response 17 | 18 | 19 | def contract_address_infile(): 20 | with open("../output/transaction/contract_address") as addressfile: 21 | address = addressfile.read() 22 | return address 23 | 24 | 25 | def main(): 26 | parser = argparse.ArgumentParser() 27 | parser.add_argument( 28 | "address", help="20 bytes ethereum compatiable address.") 29 | parser.add_argument("number", help="integer block number(Hex string)") 30 | 31 | args = parser.parse_args() 32 | 33 | address = args.address 34 | 35 | params = [address, args.number] 36 | resp = get_code(params) 37 | if resp is not None: 38 | print(resp) 39 | 40 | 41 | if __name__ == "__main__": 42 | main() 43 | -------------------------------------------------------------------------------- /scripts/config_tool/default_config/forever_mock.toml: -------------------------------------------------------------------------------- 1 | name="cita-forever" 2 | command = "cita-forever" 3 | args = ["-c","forever_mock.toml"] 4 | pidfile = ".cita-forever.pid" 5 | 6 | [[process]] 7 | name = "cita-auth" 8 | command = "cita-auth" 9 | args = ["-c","auth.toml"] 10 | pidfile = ".cita-auth.pid" 11 | respawn = 3 12 | 13 | [[process]] 14 | name = "cita-network" 15 | command = "cita-network" 16 | args = ["-c","network.toml"] 17 | pidfile = ".cita-network.pid" 18 | respawn = 3 19 | 20 | [[process]] 21 | name = "consensus-mock" 22 | command = "consensus-mock" 23 | args = ["-i","0.5"] 24 | pidfile = ".consensus-mock.pid" 25 | respawn = 3 26 | 27 | [[process]] 28 | name = "cita-jsonrpc" 29 | command = "cita-jsonrpc" 30 | args = ["-c","jsonrpc.toml"] 31 | pidfile = ".cita-jsonrpc.pid" 32 | respawn = 3 33 | 34 | 35 | [[process]] 36 | name = "cita-chain" 37 | command = "cita-chain" 38 | args = ["-c","chain.toml"] 39 | pidfile = ".cita-chain.pid" 40 | respawn = 3 41 | 42 | [[process]] 43 | name = "cita-executor" 44 | command = "cita-executor" 45 | args = ["-c","executor.toml"] 46 | pidfile = ".cita-executor.pid" 47 | respawn = 3 48 | -------------------------------------------------------------------------------- /scripts/contracts/src/role_management/RoleCreator.sol: -------------------------------------------------------------------------------- 1 | pragma solidity 0.4.24; 2 | 3 | import "./Role.sol"; 4 | import "../common/ReservedAddrPublic.sol"; 5 | 6 | /// @title Role factory contract to create role contract 7 | /// @author ["Cryptape Technologies "] 8 | /// @notice The address: 0xffffffffffffffffffffffffffffffffff020008 9 | /// The interface: None 10 | contract RoleCreator is ReservedAddrPublic { 11 | 12 | event RoleCreated( 13 | address indexed _id, 14 | bytes32 indexed _name, 15 | address[] indexed _permissions 16 | ); 17 | 18 | /// @notice Create a new role contract 19 | /// @param _name The name of role 20 | /// @param _permissions The permissions of role 21 | /// @return New role's address 22 | function createRole(bytes32 _name, address[] _permissions) 23 | public 24 | returns (Role roleAddress) 25 | { 26 | require(roleManagementAddr == msg.sender, "permission denied."); 27 | 28 | roleAddress = new Role(_name, _permissions); 29 | emit RoleCreated(roleAddress, _name, _permissions); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /scripts/contracts/tests/test/helpers/node_manager.js: -------------------------------------------------------------------------------- 1 | const fs = require('fs'); 2 | const util = require('./util'); 3 | const config = require('../config'); 4 | 5 | const { genContract, genTxParams } = util; 6 | 7 | const { superAdmin } = config; 8 | const { nodeManager } = config.contract; 9 | const abi = JSON.parse(fs.readFileSync('../interaction/abi/NodeManager.abi')); 10 | 11 | const contract = genContract(abi, nodeManager); 12 | 13 | // approveNode 14 | const approveNode = async (node, _sender = superAdmin) => { 15 | const param = await genTxParams(_sender); 16 | return contract.methods.approveNode(node).send(param); 17 | }; 18 | 19 | // deleteNode 20 | const deleteNode = async (node, _sender = superAdmin) => { 21 | const param = await genTxParams(_sender); 22 | return contract.methods.deleteNode(node).send(param); 23 | }; 24 | 25 | // listNode 26 | const listNode = () => contract.methods.listNode().call('pending'); 27 | 28 | // getStatus 29 | const getStatus = node => contract.methods.getStatus(node).call('pending'); 30 | 31 | module.exports = { 32 | approveNode, 33 | deleteNode, 34 | listNode, 35 | getStatus, 36 | }; 37 | -------------------------------------------------------------------------------- /tools/relayer-parser/res/relayer-parser-demo.json: -------------------------------------------------------------------------------- 1 | { 2 | "private_key": "0x1111111111111111111111111111111111111111111111111111111111111111", 3 | "chains": [ 4 | { 5 | "id": "0x3", 6 | "servers": [ 7 | { "url": "http://127.0.0.1:11337", "timeout": { "secs": 30, "nanos": 0 } }, 8 | { "url": "http://127.0.0.1:11338", "timeout": { "secs": 30, "nanos": 0 } }, 9 | { "url": "http://127.0.0.1:11339", "timeout": { "secs": 30, "nanos": 0 } }, 10 | { "url": "http://127.0.0.1:11340", "timeout": { "secs": 30, "nanos": 0 } } 11 | ] 12 | }, 13 | { 14 | "id": "0x4", 15 | "servers": [ 16 | { "url": "http://127.0.0.1:21337", "timeout": { "secs": 30, "nanos": 0 } }, 17 | { "url": "http://127.0.0.1:21338", "timeout": { "secs": 30, "nanos": 0 } }, 18 | { "url": "http://127.0.0.1:21339", "timeout": { "secs": 30, "nanos": 0 } }, 19 | { "url": "http://127.0.0.1:21340", "timeout": { "secs": 30, "nanos": 0 } } 20 | ] 21 | } 22 | ] 23 | } 24 | -------------------------------------------------------------------------------- /cita-executor/core/src/libexecutor/mod.rs: -------------------------------------------------------------------------------- 1 | // CITA 2 | // Copyright 2016-2019 Cryptape Technologies LLC. 3 | 4 | // This program is free software: you can redistribute it 5 | // and/or modify it under the terms of the GNU General Public 6 | // License as published by the Free Software Foundation, 7 | // either version 3 of the License, or (at your option) any 8 | // later version. 9 | 10 | // This program is distributed in the hope that it will be 11 | // useful, but WITHOUT ANY WARRANTY; without even the implied 12 | // warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR 13 | // PURPOSE. See the GNU General Public License for more details. 14 | 15 | // You should have received a copy of the GNU General Public License 16 | // along with this program. If not, see . 17 | 18 | pub mod auto_exec; 19 | pub mod blacklist; 20 | pub mod block; 21 | pub mod call_request; 22 | pub mod command; 23 | pub mod economical_model; 24 | pub mod executor; 25 | pub mod fsm; 26 | pub mod genesis; 27 | pub mod lru_cache; 28 | pub mod sys_config; 29 | 30 | pub use self::genesis::Genesis; 31 | pub use crate::cita_db::journaldb; 32 | pub use libproto::*; 33 | -------------------------------------------------------------------------------- /cita-chain/types/src/basic_types.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2015-2017 Parity Technologies (UK) Ltd. 2 | // This file is part of Parity. 3 | 4 | // This software is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | 9 | // This software is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | 14 | // You should have received a copy of the GNU General Public License 15 | // along with Parity. If not, see . 16 | 17 | //! Ethcore basic typenames. 18 | 19 | /// Type for a 2048-bit log-bloom, as used by our blocks. 20 | pub use crate::log_entry::LogBloom; 21 | 22 | pub use crate::log_blooms::LogBloomGroup; 23 | 24 | /// Constant 2048-bit datum for 0. Often used as a default. 25 | lazy_static! { 26 | pub static ref ZERO_LOGBLOOM: LogBloom = LogBloom::from([0x00; 256]); 27 | } 28 | -------------------------------------------------------------------------------- /tests/box-executor/README.md: -------------------------------------------------------------------------------- 1 | ## 相关记录: 2 | 3 | * https://cryptape.atlassian.net/browse/CITA-1491 4 | * https://cryptape.atlassian.net/browse/CITA-1537 5 | 6 | ## 测试目的: 7 | 8 | CITA 对共识和交易预执行做了并行处理优化,本脚本以接口测试的方式来验证该优化的正确性。由于优化逻辑对外部不可见,所以没法验证优化的有效性。 9 | 10 | 验证 cita-executor 在收到 `SignedProposal`/`BlockWithProof` 后是否能正确返回处理结果。 11 | 12 | ## 测试方法: 13 | 14 | * 启动 `cita-executor` 和 `cita-chain`,本脚本以 mock cita-bft 的角色运行 15 | 16 | * 消息流图: 17 | 18 | ``` 19 | ExecutedResult 20 | executor --------------> chain 21 | ^ / 22 | \ / RichStatus 23 | Messages \ / 24 | \ v 25 | box-executor 26 | ``` 27 | 28 | `Messages` 是测试脚本 `box_executor` 生成的一些测试块,可能是 `SignedProposal` 或 `BlockWithProof` 结构 29 | 30 | * 主要通过 RabbitMQ 发送消息的方式来进行测试,主要测试以下几种不同情况: 31 | 32 | - 发送 `Proposal`,执行完成后,再发送对应的 `BlockWithProof`,检查是否能正常执行。 33 | - 发送 `Proposal`,执行完成后,再发送不对应的 `BlockWithProof`,在检查是否能正常执行 34 | - 发送 `Proposal` A,再发送等价的 `Proposal` B(查看 `is_equivalent` 方法),~~检查是否能正常执行,~~再发送 `BlockWithProof`,检查是否能执行。 35 | - 发送 `Proposal` A,在发送不等价的 `Proposal` B,~~检查是否正常执行,~~在发送 `BlockWithProof`,检查是否能正常执行。 36 | -------------------------------------------------------------------------------- /scripts/contracts/src/user_management/GroupCreator.sol: -------------------------------------------------------------------------------- 1 | pragma solidity 0.4.24; 2 | 3 | import "./Group.sol"; 4 | import "../common/ReservedAddrPublic.sol"; 5 | 6 | /// @title Group factory contract to create group contract 7 | /// @author ["Cryptape Technologies "] 8 | /// @notice The address: 0xfFFffFfFFFFfFFFfFfffffFFfffffffffF02000B 9 | /// The interface: None 10 | contract GroupCreator is ReservedAddrPublic { 11 | 12 | event GroupCreated( 13 | address indexed _id, 14 | address indexed _parent, 15 | bytes32 indexed _name, 16 | address[] accounts 17 | ); 18 | 19 | /// @notice Create a new group contract 20 | /// @param _parent The parent group 21 | /// @param _name The name of group 22 | /// @return New group's accounts 23 | function createGroup(address _parent, bytes32 _name, address[] _accounts) 24 | public 25 | returns (Group groupAddress) 26 | { 27 | require(userManagementAddr == msg.sender, "permission denied."); 28 | 29 | groupAddress = new Group(_parent, _name, _accounts); 30 | emit GroupCreated(groupAddress, _parent, _name, _accounts); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /scripts/config_tool/default_config/jsonrpc.toml: -------------------------------------------------------------------------------- 1 | backlog_capacity = 1000 2 | enable_version = false 3 | 4 | [profile_config] 5 | flag_prof_start = 0 6 | enable = false 7 | flag_prof_duration = 0 8 | 9 | [http_config] 10 | allow_origin = "*" 11 | timeout = 3 12 | enable = true 13 | listen_port = "1337" 14 | listen_ip = "0.0.0.0" 15 | 16 | [ws_config] 17 | panic_on_internal = true 18 | fragments_grow = true 19 | panic_on_protocol = false 20 | enable = true 21 | in_buffer_capacity = 2048 22 | panic_on_queue = false 23 | fragment_size = 65535 24 | panic_on_timeout = false 25 | method_strict = false 26 | thread_number = 2 27 | panic_on_capacity = false 28 | masking_strict = false 29 | key_strict = false 30 | max_connections = 800 31 | listen_ip = "0.0.0.0" 32 | listen_port = "4337" 33 | queue_size = 200 34 | fragments_capacity = 100 35 | tcp_nodelay = false 36 | shutdown_on_interrupt = true 37 | out_buffer_grow = true 38 | panic_on_io = false 39 | panic_on_new_connection = false 40 | out_buffer_capacity = 2048 41 | encrypt_server = false 42 | in_buffer_grow = true 43 | panic_on_shutdown = false 44 | panic_on_encoding = false 45 | 46 | [new_tx_flow_config] 47 | buffer_duration = 30000000 48 | count_per_batch = 30 49 | -------------------------------------------------------------------------------- /scripts/amend_system_contracts.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -e 3 | 4 | if [[ $(uname) == 'Darwin' ]] 5 | then 6 | SOURCE_DIR=$(realpath "$(dirname "$0")"/..) 7 | else 8 | SOURCE_DIR=$(readlink -f "$(dirname "$0")"/..) 9 | fi 10 | 11 | if [ "$1" = "help" ]; then 12 | echo "Admin private key, chain id, version, url as the params. 13 | For example: \\ 14 | bin/cita scripts/amend_system_contracts.sh \\ 15 | 0x5f0258a4778057a8a7d97809bd209055b2fbafa654ce7d31ec7191066b9225e6 \\ 16 | 1 \\ 17 | 1 \\ 18 | http://127.0.0.1:1337" 19 | exit 0 20 | fi 21 | 22 | # Clean tmp files 23 | rm -rf "${SOURCE_DIR}"/tmp 24 | rm -f "${SOURCE_DIR}"/scripts/genesis.json 25 | 26 | # Just get the genensis.json 27 | scripts/create_cita_config.py create \ 28 | --chain_name tmp \ 29 | --super_admin "0x4b5ae4567ad5d9fb92bc9afd6a657e6fa13a2523" \ 30 | --nodes "127.0.0.1:4000" \ 31 | && cp tmp/0/genesis.json scripts/ \ 32 | && cd ./scripts/txtool/txtool \ 33 | && python3 "${SOURCE_DIR}"/scripts/amend_system_contracts.py \ 34 | --privkey "$1" \ 35 | --chain_id "$2" \ 36 | --version "$3" \ 37 | --url "$4" \ 38 | && rm -rf "${SOURCE_DIR}"/tmp \ 39 | && rm -f "${SOURCE_DIR}"/scripts/genesis.json 40 | -------------------------------------------------------------------------------- /tools/relayer-parser/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "cita-relayer-parser" 3 | version = "0.1.0" 4 | authors = ["Cryptape Technologies "] 5 | edition = "2018" 6 | 7 | [dependencies] 8 | cita-logger = "0.1.0" 9 | serde = "1.0" 10 | serde_derive = "1.0" 11 | serde_json = "1.0" 12 | cita-types = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 13 | clap = "2" 14 | parking_lot = "0.6" 15 | futures = "0.1" 16 | tokio-core = "0.1" 17 | hyper = { git = "https://github.com/cryptape/hyper.git", branch = "reuse_port" } 18 | core = { path = "../../cita-chain/core" } 19 | jsonrpc-types = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 20 | libproto = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 21 | cita-crypto = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 22 | ethabi = "4.2.0" 23 | 24 | [features] 25 | default = ["secp256k1", "sha3hash"] 26 | secp256k1 = ["cita-crypto/secp256k1", "libproto/secp256k1"] 27 | ed25519 = ["cita-crypto/ed25519", "libproto/ed25519"] 28 | sm2 = ["cita-crypto/sm2", "libproto/sm2"] 29 | sha3hash = ["libproto/sha3hash"] 30 | blake2bhash = ["libproto/blake2bhash"] 31 | sm3hash = ["libproto/sm3hash"] 32 | -------------------------------------------------------------------------------- /cita-chain/types/src/call_analytics.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2015-2017 Parity Technologies (UK) Ltd. 2 | // This file is part of Parity. 3 | 4 | // This software is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | 9 | // This software is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | 14 | // You should have received a copy of the GNU General Public License 15 | // along with Parity. If not, see . 16 | 17 | //! Call analytics related types 18 | 19 | /// Options concerning what analytics we run on the call. 20 | #[derive(Eq, PartialEq, Default, Clone, Copy, Debug)] 21 | #[cfg_attr(feature = "ipc", binary)] 22 | pub struct CallAnalytics { 23 | /// Make a transaction trace. 24 | pub transaction_tracing: bool, 25 | /// Make a VM trace. 26 | pub vm_tracing: bool, 27 | /// Make a diff. 28 | pub state_diffing: bool, 29 | } 30 | -------------------------------------------------------------------------------- /cita-executor/core/README.md: -------------------------------------------------------------------------------- 1 | # Executor microservice core for CITA 2 | 3 | Files below are extracted from [Parity](https://github.com/paritytech/parity): 4 | 5 | - ./src/cache_manager.rs 6 | - ./src/substate.rs 7 | - ./src/snapshot/mod.rs 8 | - ./src/snapshot/io.rs 9 | - ./src/snapshot/account.rs 10 | - ./src/snapshot/error.rs 11 | - ./src/snapshot/service.rs 12 | - ./src/account_db.rs 13 | - ./src/error.rs 14 | - ./src/db.rs 15 | - ./src/basic_types.rs 16 | - ./src/libexecutor/cache.rs 17 | - ./src/trace/mod.rs 18 | - ./src/trace/executive_tracer.rs 19 | - ./src/trace/error.rs 20 | - ./src/trace/noop_tracer.rs 21 | - ./src/trace/db.rs 22 | - ./src/trace/types/mod.rs 23 | - ./src/trace/types/localized.rs 24 | - ./src/trace/types/flat.rs 25 | - ./src/trace/types/error.rs 26 | - ./src/trace/types/filter.rs 27 | - ./src/trace/types/trace.rs 28 | - ./src/trace/import.rs 29 | - ./src/trace/config.rs 30 | - ./src/state/mod.rs 31 | - ./src/state/backend.rs 32 | - ./src/externalities.rs 33 | - ./src/state_db.rs 34 | - ./src/pod_account.rs 35 | - ./src/factory.rs 36 | 37 | with following modifications: 38 | 39 | - ./src/builtin.rs 40 | - ./src/executed.rs 41 | - ./src/engines/null_engine.rs 42 | - ./src/executive.rs 43 | - ./src/state/account.rs 44 | - ./src/spec/builtin.rs 45 | -------------------------------------------------------------------------------- /scripts/txtool/txtool/tx_count.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # coding=utf-8 3 | 4 | import argparse 5 | from log import logger 6 | from jsonrpcclient.http_client import HTTPClient 7 | from url_util import endpoint 8 | 9 | 10 | def get_tx_count(params): 11 | try: 12 | url = endpoint() 13 | response = HTTPClient(url).request("getTransactionCount", params) 14 | logger.debug(response) 15 | except: 16 | return None 17 | 18 | return response 19 | 20 | 21 | def address_infile(): 22 | with open("../output/accounts/address") as addressfile: 23 | address = addressfile.read() 24 | return address 25 | 26 | 27 | def main(): 28 | parser = argparse.ArgumentParser() 29 | parser.add_argument( 30 | "-a", "--address", help="20 bytes ethereum compatiable address.") 31 | parser.add_argument("number", help="integer block number(hex string)") 32 | 33 | args = parser.parse_args() 34 | 35 | address = args.address 36 | if args.address is None: 37 | address = address_infile() 38 | 39 | params = [address, args.number] 40 | logger.debug(params) 41 | resp = get_tx_count(params) 42 | if resp is None: 43 | print('None') 44 | else: 45 | print(int(resp, 16)) 46 | 47 | 48 | if __name__ == "__main__": 49 | main() 50 | -------------------------------------------------------------------------------- /scripts/contracts/src/permission_management/PermissionCreator.sol: -------------------------------------------------------------------------------- 1 | pragma solidity 0.4.24; 2 | 3 | import "./Permission.sol"; 4 | import "../common/ReservedAddrPublic.sol"; 5 | 6 | /// @title Permission factory contract to create permission contract 7 | /// @author ["Cryptape Technologies "] 8 | /// @notice The address:0xffFFFffFfFFffffFffffFFfFffffFfFFFF020005 9 | /// The interface: None 10 | contract PermissionCreator is ReservedAddrPublic { 11 | 12 | event PermissionCreated( 13 | address indexed _id, 14 | bytes32 indexed _name, 15 | address[] _conts, 16 | bytes4[] _funcs 17 | ); 18 | 19 | /// @notice Create a new permission contract 20 | /// @param _name The name of permission 21 | /// @param _conts The contracts of resource 22 | /// @param _funcs The function signature of the resource 23 | /// @return New permission's address 24 | function createPermission(bytes32 _name, address[] _conts, bytes4[] _funcs) 25 | public 26 | returns (Permission permissionAddress) 27 | { 28 | require(permissionManagementAddr == msg.sender, "permission denied."); 29 | 30 | permissionAddress = new Permission(_name, _conts, _funcs); 31 | emit PermissionCreated(permissionAddress, _name, _conts, _funcs); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /scripts/txtool/txtool/get_logs.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # coding=utf-8 3 | 4 | from __future__ import print_function 5 | from jsonrpcclient.http_client import HTTPClient 6 | from url_util import endpoint 7 | import argparse 8 | import simplejson 9 | 10 | 11 | def get_topics(): 12 | with open("../output/transaction/topics", 'r') as topicfile: 13 | topics = simplejson.load(topicfile) 14 | return topics 15 | 16 | 17 | def get_logs(topics, from_block, to_block): 18 | try: 19 | url = endpoint() 20 | response = HTTPClient(url).request("getLogs", [{ 21 | "topics": topics, 22 | "fromBlock": from_block, 23 | "toBlock": to_block 24 | }]) 25 | except: 26 | return None 27 | 28 | return response 29 | 30 | 31 | def parse_arguments(): 32 | parser = argparse.ArgumentParser() 33 | parser.add_argument("--fromBlock", default="0") 34 | parser.add_argument("--toBlock", default="latest") 35 | opts = parser.parse_args() 36 | 37 | return opts.fromBlock, opts.toBlock 38 | 39 | 40 | def main(): 41 | from_block, to_block = parse_arguments() 42 | topics = get_topics() 43 | logger.debug(topics) 44 | resp = get_logs(topics, from_block, to_block) 45 | print(resp) 46 | 47 | 48 | if __name__ == "__main__": 49 | main() 50 | -------------------------------------------------------------------------------- /cita-executor/core/src/factory.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2015-2017 Parity Technologies (UK) Ltd. 2 | // This file is part of Parity. 3 | 4 | // This software is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | 9 | // This software is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | 14 | // You should have received a copy of the GNU General Public License 15 | // along with Parity. If not, see . 16 | 17 | use crate::account_db::Factory as AccountFactory; 18 | use crate::cita_db::trie::TrieFactory; 19 | use crate::contracts::native::factory::Factory as NativeFactory; 20 | use evm::Factory as EvmFactory; 21 | 22 | /// Collection of factories. 23 | #[derive(Default, Clone)] 24 | pub struct Factories { 25 | /// factory for evm. 26 | pub vm: EvmFactory, 27 | pub native: NativeFactory, 28 | /// factory for tries. 29 | pub trie: TrieFactory, 30 | /// factory for account databases. 31 | pub accountdb: AccountFactory, 32 | } 33 | -------------------------------------------------------------------------------- /scripts/contracts/src/system/PriceManager.sol: -------------------------------------------------------------------------------- 1 | pragma solidity 0.4.24; 2 | 3 | import "../common/Admin.sol"; 4 | import "../common/ReservedAddrPublic.sol"; 5 | import "../../interaction/interface/IPriceManager.sol"; 6 | 7 | /// @title Quota Price Manager 8 | /// @author ["Cryptape Technologies "] 9 | contract PriceManager is IPriceManager, ReservedAddrPublic { 10 | uint quotaPrice = 1; 11 | 12 | Admin admin = Admin(adminAddr); 13 | 14 | event SetQuotaPrice(uint indexed _quotaPrice); 15 | 16 | modifier onlyAdmin { 17 | if (admin.isAdmin(msg.sender)) 18 | _; 19 | else return; 20 | } 21 | 22 | /// @notice Setup 23 | constructor(uint _quotaPrice) 24 | public 25 | { 26 | quotaPrice = _quotaPrice; 27 | } 28 | 29 | /// @notice Set quota price 30 | function setQuotaPrice(uint _quotaPrice) 31 | external 32 | onlyAdmin 33 | returns (bool) 34 | { 35 | require(_quotaPrice > 0, "The quota price should larger than zero."); 36 | quotaPrice = _quotaPrice; 37 | emit SetQuotaPrice(_quotaPrice); 38 | return true; 39 | } 40 | 41 | /// @notice Get guota price 42 | function getQuotaPrice() 43 | public 44 | view 45 | returns (uint) 46 | { 47 | return quotaPrice; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /cita-chain/core/src/libchain/cache.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2015-2017 Parity Technologies (UK) Ltd. 2 | // This file is part of Parity. 3 | 4 | // This software is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | 9 | // This software is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | 14 | // You should have received a copy of the GNU General Public License 15 | // along with Parity. If not, see . 16 | 17 | /// Represents blockchain's in-memory cache size in bytes. 18 | #[derive(Debug)] 19 | pub struct CacheSize { 20 | /// Blocks cache size. 21 | pub blocks: usize, 22 | /// Transaction addresses cache size. 23 | pub transaction_addresses: usize, 24 | /// Blooms cache size. 25 | pub blocks_blooms: usize, 26 | /// Block receipts size. 27 | pub block_receipts: usize, 28 | } 29 | 30 | impl CacheSize { 31 | /// Total amount used by the cache. 32 | pub fn total(&self) -> usize { 33 | self.blocks + self.transaction_addresses + self.blocks_blooms + self.block_receipts 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /scripts/contracts/tests/test/unit/group.js: -------------------------------------------------------------------------------- 1 | const chai = require('chai'); 2 | const util = require('../helpers/util'); 3 | const config = require('../config'); 4 | const group = require('../helpers/group'); 5 | 6 | const { expect } = chai; 7 | 8 | const { citaSDK, logger } = util; 9 | 10 | const { 11 | queryInfo, queryAccounts, queryParent, inGroup, 12 | } = group; 13 | 14 | // test data 15 | const { address } = config.superAdmin; 16 | const name = citaSDK.utils.utf8ToHex('rootGroup'); 17 | const nul = '0x0000000000000000000000000000000000000000'; 18 | 19 | describe('test group contract', () => { 20 | it('should be the build-in rootGroup', async () => { 21 | const res = await queryInfo(); 22 | logger.debug('\nInfo:\n', res); 23 | expect(res[0]).to.have.string(name); 24 | expect(address).to.be.oneOf(res[1]); 25 | }); 26 | 27 | it('should be the build-in accounts', async () => { 28 | const res = await queryAccounts(); 29 | logger.debug('\nAccounts:\n', res); 30 | expect(address).to.be.oneOf(res); 31 | }); 32 | 33 | it('should be the build-in parent group', async () => { 34 | const res = await queryParent(); 35 | logger.debug('\nParent group:\n', res); 36 | expect(res).to.equal(nul); 37 | }); 38 | 39 | it('should in the rootGroup', async () => { 40 | const res = await inGroup(address); 41 | logger.debug('\nIs in the group:\n', res); 42 | expect(res).to.be.true; 43 | }); 44 | }); 45 | -------------------------------------------------------------------------------- /scripts/contracts/src/lib/SafeMath.sol: -------------------------------------------------------------------------------- 1 | pragma solidity 0.4.24; 2 | 3 | /** 4 | * @title SafeMath 5 | * @dev Math operations with safety checks that throw on error 6 | */ 7 | library SafeMath { 8 | 9 | /** 10 | * @dev Multiplies two numbers, throws on overflow. 11 | */ 12 | function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { 13 | if (a == 0) { 14 | return 0; 15 | } 16 | c = a * b; 17 | assert(c / a == b); 18 | return c; 19 | } 20 | 21 | /** 22 | * @dev Integer division of two numbers, truncating the quotient. 23 | */ 24 | function div(uint256 a, uint256 b) internal pure returns (uint256) { 25 | // assert(b > 0); // Solidity automatically throws when dividing by 0 26 | // uint256 c = a / b; 27 | // assert(a == b * c + a % b); // There is no case in which this doesn't hold 28 | return a / b; 29 | } 30 | 31 | /** 32 | * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). 33 | */ 34 | function sub(uint256 a, uint256 b) internal pure returns (uint256) { 35 | assert(b <= a); 36 | return a - b; 37 | } 38 | 39 | /** 40 | * @dev Adds two numbers, throws on overflow. 41 | */ 42 | function add(uint256 a, uint256 b) internal pure returns (uint256 c) { 43 | c = a + b; 44 | assert(c >= a); 45 | return c; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /cita-executor/core/src/trace/import.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2015-2017 Parity Technologies (UK) Ltd. 2 | // This file is part of Parity. 3 | 4 | // This software is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | 9 | // This software is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | 14 | // You should have received a copy of the GNU General Public License 15 | // along with Parity. If not, see . 16 | 17 | //! Traces import request. 18 | 19 | use crate::header::BlockNumber; 20 | use crate::trace::FlatBlockTraces; 21 | use cita_types::H256; 22 | 23 | /// Traces import request. 24 | pub struct ImportRequest { 25 | /// Traces to import. 26 | pub traces: FlatBlockTraces, 27 | /// Hash of traces block. 28 | pub block_hash: H256, 29 | /// Number of traces block. 30 | pub block_number: BlockNumber, 31 | /// Blocks enacted by this import. 32 | /// 33 | /// They should be ordered from oldest to newest. 34 | pub enacted: Vec, 35 | /// Number of blocks retracted by this import. 36 | pub retracted: usize, 37 | } 38 | -------------------------------------------------------------------------------- /tests/consensus-mock/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "consensus-mock" 3 | version = "0.1.0" 4 | authors = ["Cryptape Technologies "] 5 | edition = "2018" 6 | 7 | [dependencies] 8 | serde = "1.0" 9 | serde_derive = "1.0" 10 | bincode = "0.8.0" 11 | cita-logger = "0.1.0" 12 | libproto = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 13 | hashable = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 14 | clap = "2" 15 | pubsub = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 16 | cita-types = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 17 | cita-crypto = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 18 | proof = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 19 | chrono = "0.4.2" 20 | 21 | [features] 22 | default = ["secp256k1", "sha3hash", "rabbitmq"] 23 | secp256k1 = ["cita-crypto/secp256k1", "libproto/secp256k1", "proof/secp256k1"] 24 | ed25519 = ["cita-crypto/ed25519", "libproto/ed25519", "proof/ed25519"] 25 | sm2 = ["cita-crypto/sm2", "libproto/sm2", "proof/sm2"] 26 | sha3hash = ["hashable/sha3hash", "libproto/sha3hash", "proof/sha3hash"] 27 | blake2bhash = ["hashable/blake2bhash", "libproto/blake2bhash", "proof/blake2bhash"] 28 | sm3hash = ["hashable/sm3hash", "libproto/sm3hash", "proof/sm3hash"] 29 | rabbitmq = ["pubsub/rabbitmq"] 30 | zeromq = ["pubsub/zeromq"] 31 | kafka = ["pubsub/kafka"] 32 | -------------------------------------------------------------------------------- /scripts/txtool/txtool/get_tx.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # coding=utf-8 3 | 4 | from __future__ import print_function 5 | import argparse 6 | from pathlib import Path 7 | from log import logger 8 | from jsonrpcclient.http_client import HTTPClient 9 | from url_util import endpoint 10 | from util import run_command 11 | 12 | 13 | def get_transaction_hash(): 14 | with open("../output/transaction/hash", 'r') as hashfile: 15 | tx_hash = hashfile.read() 16 | return tx_hash 17 | 18 | 19 | def transaction_by_hash(tx_hash): 20 | try: 21 | url = endpoint() 22 | response = HTTPClient(url).request("getTransaction", tx_hash) 23 | except: 24 | return None 25 | 26 | return response 27 | 28 | 29 | def parse_arguments(): 30 | parser = argparse.ArgumentParser() 31 | parser.add_argument( 32 | "--tx", help="Transaction hash with or without 0x prefix.") 33 | opts = parser.parse_args() 34 | 35 | return opts.tx 36 | 37 | 38 | def main(): 39 | compile_path = Path("../output/transaction") 40 | if not compile_path.is_dir(): 41 | command = 'mkdir -p ../output/transaction'.split() 42 | for line in run_command(command): 43 | logger.debug(line) 44 | 45 | tx_hash = parse_arguments() 46 | if tx_hash is None: 47 | tx_hash = get_transaction_hash() 48 | 49 | transaction = transaction_by_hash(tx_hash) 50 | print(transaction) 51 | 52 | 53 | if __name__ == "__main__": 54 | main() 55 | -------------------------------------------------------------------------------- /tests/chain-performance-by-mq/README.md: -------------------------------------------------------------------------------- 1 | # 功能 2 | 3 | 通过MQ向Chain模块来发送Block来对Chain持续测试 4 | 5 | ## 方法 6 | 7 | 1. 修改节点目录下的chain.json,将权限检查和配额检查改成false 8 | 2. 启动Chain, Executor进程,或者启动单独一个节点 9 | 3. 在node目录下启动测试进程,这样可以正确的使用.env文件 10 | 4. 使用命令进行压力测试: ../../../debug/chain_performance_by_mq --help 11 | 12 | ## 注意 13 | 14 | * 调整交易配额和交易数,防止block超出block quota limit 15 | * 创建合约/更改State时,随着State状态树变大,tps会越来越越慢 16 | * 通过查询block中最后一个交易的receipt来确认交易是否正常执行 17 | 18 | ## 测试单个合约的调用 19 | 20 | ```shell 21 | solc Test.sol --bin-runtime --hashes 22 | 23 | ======= Test.sol:Test ======= 24 | Binary: 25 | 606060405260043610603f576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff1680634f2be91f146044575b600080fd5b3415604e57600080fd5b60546056565b005b6001600054016000819055505600a165627a7a723058207085dc709915ad41cb41e400b83bd863a24143dfb48c10bc007a07b3a7c160cd0029 26 | Function signatures: 27 | 4f2be91f: add() 28 | ``` 29 | 30 | 在节点的genesis.json文件中加入: 31 | 32 | ```json 33 | "0x0000000000000000000000000000000082720029": { 34 | "nonce": "1", 35 | "code": "0x606060405260043610603f576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff1680634f2be91f146044575b600080fd5b3415604e57600080fd5b60546056565b005b6001600054016000819055505600a165627a7a723058207085dc709915ad41cb41e400b83bd863a24143dfb48c10bc007a07b3a7c160cd0029", 36 | "storage": {} 37 | } 38 | ``` 39 | 40 | 使用以下命令进行测试: 41 | 42 | ```shell 43 | ./target/release/chain_performance_by_mq --flag_tx_type 2 44 | ``` 45 | -------------------------------------------------------------------------------- /tests/integrate_test/test_perm_denied.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """ 3 | Test case of checkCreateContractPermission in sysconfig 4 | """ 5 | 6 | import argparse 7 | from txtool_utils import get_receipt, rpc_request, send_tx 8 | 9 | 10 | def main(): 11 | user_privkey = '0xb3964278651fd8a24fa00aeef2a831fb7574f25a2be2ee9e951d0226ee01dd5b' 12 | code = '0x608060405234801561001057600080fd5b5060df8061001f6000396000f3006080604052600436106049576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff16806360fe47b114604e5780636d4ce63c146078575b600080fd5b348015605957600080fd5b5060766004803603810190808035906020019092919050505060a0565b005b348015608357600080fd5b50608a60aa565b6040518082815260200191505060405180910390f35b8060008190555050565b600080549050905600a165627a7a723058205aed214856a5c433292a354261c9eb88eed1396c83dabbe105bde142e49838ac0029' 13 | 14 | opts = parse_arguments() 15 | version = opts.version 16 | 17 | # send create contract tx 18 | tx_hash = send_tx(user_privkey, code=code, version=version) 19 | # get_receipt 20 | receipt = get_receipt(tx_hash) 21 | assert receipt['errorMessage'] == 'No contract permission.' 22 | print(">>> Test create contract permission denied successfully!") 23 | 24 | 25 | def parse_arguments(): 26 | parser = argparse.ArgumentParser() 27 | parser.add_argument("--version", help="Tansaction version.", type=int) 28 | 29 | return parser.parse_args() 30 | 31 | 32 | if __name__ == '__main__': 33 | main() 34 | -------------------------------------------------------------------------------- /scripts/contracts/tests/test/helpers/util.js: -------------------------------------------------------------------------------- 1 | const CITASDK = require('@cryptape/cita-sdk').default; 2 | const log4js = require('log4js'); 3 | const config = require('../config'); 4 | 5 | const flag = true; 6 | let citaSDK; 7 | 8 | if (flag) { 9 | // Use local server 10 | citaSDK = CITASDK(config.localServer); 11 | } else { 12 | // Use remote server 13 | citaSDK = CITASDK(config.remoteServer); 14 | } 15 | 16 | const logger = log4js.getLogger(); 17 | logger.level = 'debug'; 18 | const quota = 9999999; 19 | const blockLimit = 100; 20 | const sender = config.testSender; 21 | 22 | const randomInt = () => Math.floor(Math.random() * 100).toString(); 23 | const genContract = (abi, addr) => new citaSDK.eth.Contract(abi, addr); 24 | 25 | const getTxReceipt = citaSDK.listeners.listenToTransactionReceipt; 26 | const { getBlockNumber, getMetaData } = citaSDK.base; 27 | 28 | const genTxParams = async (_sender = sender) => { 29 | const current = await getBlockNumber(); 30 | const metaData = await getMetaData(); 31 | return { 32 | from: _sender.address, 33 | privateKey: _sender.privkey, 34 | nonce: randomInt(), 35 | quota, 36 | chainId: metaData.chainIdV1, 37 | version: metaData.version, 38 | validUntilBlock: +current + blockLimit, 39 | value: '0x0', 40 | }; 41 | }; 42 | 43 | module.exports = { 44 | citaSDK, 45 | randomInt, 46 | quota, 47 | blockLimit, 48 | genTxParams, 49 | logger, 50 | genContract, 51 | getTxReceipt, 52 | getBlockNumber, 53 | getMetaData, 54 | }; 55 | -------------------------------------------------------------------------------- /scripts/contracts/src/common/Check.sol: -------------------------------------------------------------------------------- 1 | pragma solidity 0.4.24; 2 | 3 | import "../../interaction/interface/IAuthorization.sol"; 4 | import "../../interaction/interface/IAllGroups.sol"; 5 | import "../../interaction/interface/IGroup.sol"; 6 | import "./ReservedAddrPublic.sol"; 7 | 8 | /// @title The modifier for checking permission 9 | /// @author ["Cryptape Technologies "] 10 | contract Check is ReservedAddrPublic { 11 | 12 | modifier hasPermission(address _permission) { 13 | require( 14 | checkPermissionWithGroup(msg.sender, _permission), 15 | "permission denied." 16 | ); 17 | _; 18 | } 19 | 20 | function checkPermissionWithGroup(address _account, address _permission) 21 | private 22 | returns (bool) 23 | { 24 | IAuthorization auth = IAuthorization(authorizationAddr); 25 | if (!auth.checkPermission(msg.sender, _permission)) { 26 | IAllGroups groups = IAllGroups(allGroupsAddr); 27 | address[] memory allGroups = groups.queryGroups(); 28 | IGroup group; 29 | for (uint i; i < allGroups.length; i++) { 30 | group = IGroup(allGroups[i]); 31 | if (group.inGroup(_account) && 32 | auth.checkPermission(allGroups[i], _permission)) 33 | { 34 | return true; 35 | } 36 | } 37 | return false; 38 | } 39 | return true; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /cita-network/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "cita-network" 3 | version = "0.6.0" 4 | authors = ["Cryptape Technologies "] 5 | edition = "2018" 6 | 7 | [dependencies] 8 | tentacle-discovery = "0.2.4" 9 | tentacle = "0.2.1" 10 | tokio = "0.1.14" 11 | futures = "0.1.25" 12 | cita-logger = "0.1.0" 13 | cita-types = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 14 | util = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 15 | libproto = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 16 | pubsub = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 17 | jsonrpc-types = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 18 | serde = "1.0.84" 19 | serde_json = "1.0" 20 | serde_derive = "1.0.84" 21 | clap = "2.32" 22 | bytes = "0.4" 23 | byteorder = "1.3" 24 | rand = "0.4.5" 25 | dotenv = "0.13.0" 26 | fnv = "1.0.6" 27 | notify = "4.0.10" 28 | 29 | [dev-dependencies] 30 | tempfile = "3.0.5" 31 | 32 | [build-dependencies] 33 | util = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 34 | 35 | [features] 36 | default = ["secp256k1", "sha3hash", "rabbitmq"] 37 | secp256k1 = ["libproto/secp256k1"] 38 | ed25519 = ["libproto/ed25519"] 39 | sm2 = ["libproto/sm2"] 40 | sha3hash = ["libproto/sha3hash"] 41 | blake2bhash = ["libproto/blake2bhash"] 42 | sm3hash = ["libproto/sm3hash"] 43 | rabbitmq = ["pubsub/rabbitmq"] 44 | zeromq = ["pubsub/zeromq"] 45 | kafka = ["pubsub/kafka"] 46 | -------------------------------------------------------------------------------- /scripts/contracts/src/common/Admin.sol: -------------------------------------------------------------------------------- 1 | pragma solidity 0.4.24; 2 | 3 | import "./Error.sol"; 4 | 5 | /// @title A common contract about admin 6 | /// @author ["Cryptape Technologies "] 7 | contract Admin is Error { 8 | 9 | address public admin; 10 | 11 | event AdminUpdated( 12 | address indexed _account, 13 | address indexed _old, 14 | address indexed _sender 15 | ); 16 | 17 | modifier onlyAdmin { 18 | if (isAdmin(msg.sender)) 19 | _; 20 | else return; 21 | } 22 | 23 | constructor(address _account) public { 24 | admin = _account; 25 | } 26 | 27 | /// @notice Update the admin 28 | /// Be careful to use it. TODO update the permissions of admin 29 | /// @param _account Address of the admin 30 | /// @return true if successed, otherwise false 31 | function update(address _account) 32 | external 33 | onlyAdmin 34 | returns (bool) 35 | { 36 | emit AdminUpdated(_account, admin, msg.sender); 37 | admin = _account; 38 | return true; 39 | } 40 | 41 | /// @notice Check the account is admin 42 | /// @param _account The address to be checked 43 | /// @return true if it is, otherwise false 44 | function isAdmin(address _account) 45 | public 46 | returns (bool) 47 | { 48 | if (_account == admin) { 49 | return true; 50 | } 51 | emit ErrorLog(ErrorType.NotAdmin, "Not the admin account"); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /scripts/contracts/src/system/AutoExec.sol: -------------------------------------------------------------------------------- 1 | pragma solidity 0.4.24; 2 | 3 | import "../common/Admin.sol"; 4 | import "../common/ReservedAddrConstant.sol"; 5 | import "../../interaction/interface/IAutoExec.sol"; 6 | import "../lib/ContractCheck.sol"; 7 | 8 | /// @title Manage the scheduled executing contract. 9 | /// @author ["Cryptape Technologies "] 10 | contract AutoExec is IAutoExec, ReservedAddrConstant { 11 | 12 | address public contAddr; 13 | 14 | event Registered(address indexed _contAddr); 15 | 16 | modifier onlyAdmin { 17 | Admin admin = Admin(adminAddr); 18 | if (admin.isAdmin(msg.sender)) 19 | _; 20 | else return; 21 | } 22 | 23 | /// @notice Register an autoExec contract 24 | /// There's only one. You can call it to replace another 25 | function register(address _contAddr) 26 | external 27 | onlyAdmin 28 | { 29 | require( 30 | ContractCheck.isContract(_contAddr), 31 | "address should be a contract" 32 | ); 33 | emit Registered(_contAddr); 34 | contAddr = _contAddr; 35 | } 36 | 37 | /// @notice auto exec 38 | function autoExec() 39 | external 40 | { 41 | require(msg.sender == 0x0, "only be called by executor"); 42 | // In case the contract selfdestruct 43 | require( 44 | ContractCheck.isContract(contAddr), 45 | "address should be a contract" 46 | ); 47 | IAutoExec(contAddr).autoExec(); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /cita-chain/core/src/filters/poll_filter.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2015-2017 Parity Technologies (UK) Ltd. 2 | // This file is part of Parity. 3 | 4 | // This software is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | 9 | // This software is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | 14 | // You should have received a copy of the GNU General Public License 15 | // along with Parity. If not, see . 16 | 17 | //! Helper type with all filter state data. 18 | 19 | use jsonrpc_types::rpc_types::{Filter, Log}; 20 | use std::collections::HashSet; 21 | pub type BlockNumber = u64; 22 | 23 | /// Filter state. 24 | #[derive(Clone)] 25 | pub enum PollFilter { 26 | /// Number of last block which client was notified about. 27 | Block(BlockNumber), 28 | /// Number of From block number, pending logs and log filter itself. 29 | Logs(BlockNumber, HashSet, Filter), 30 | } 31 | 32 | /// Returns only last `n` logs 33 | pub fn limit_logs(mut logs: Vec, limit: Option) -> Vec { 34 | let len = logs.len(); 35 | match limit { 36 | Some(limit) if len >= limit => logs.split_off(len - limit), 37 | _ => logs, 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /cita-chain/types/src/lib.rs: -------------------------------------------------------------------------------- 1 | // CITA 2 | // Copyright 2016-2019 Cryptape Technologies LLC. 3 | 4 | // This program is free software: you can redistribute it 5 | // and/or modify it under the terms of the GNU General Public 6 | // License as published by the Free Software Foundation, 7 | // either version 3 of the License, or (at your option) any 8 | // later version. 9 | 10 | // This program is distributed in the hope that it will be 11 | // useful, but WITHOUT ANY WARRANTY; without even the implied 12 | // warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR 13 | // PURPOSE. See the GNU General Public License for more details. 14 | 15 | // You should have received a copy of the GNU General Public License 16 | // along with this program. If not, see . 17 | 18 | extern crate cita_crypto as crypto; 19 | #[macro_use] 20 | extern crate rlp_derive; 21 | #[macro_use] 22 | extern crate serde_derive; 23 | #[macro_use] 24 | extern crate lazy_static; 25 | #[macro_use] 26 | extern crate cita_logger as logger; 27 | extern crate db as cita_db; 28 | 29 | pub extern crate bloomchain; 30 | 31 | pub mod account_diff; 32 | pub mod basic_account; 33 | pub mod basic_types; 34 | pub mod block; 35 | pub mod cache_manager; 36 | pub mod call_analytics; 37 | pub mod db; 38 | pub mod extras; 39 | pub mod filter; 40 | pub mod header; 41 | pub mod ids; 42 | pub mod log_blooms; 43 | pub mod log_entry; 44 | pub mod receipt; 45 | pub mod reserved_addresses; 46 | pub mod state_diff; 47 | pub mod transaction; 48 | 49 | /// Type for block number. 50 | pub type BlockNumber = u64; 51 | -------------------------------------------------------------------------------- /cita-chain/core/src/libchain/status.rs: -------------------------------------------------------------------------------- 1 | // CITA 2 | // Copyright 2016-2019 Cryptape Technologies LLC. 3 | 4 | // This program is free software: you can redistribute it 5 | // and/or modify it under the terms of the GNU General Public 6 | // License as published by the Free Software Foundation, 7 | // either version 3 of the License, or (at your option) any 8 | // later version. 9 | 10 | // This program is distributed in the hope that it will be 11 | // useful, but WITHOUT ANY WARRANTY; without even the implied 12 | // warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR 13 | // PURPOSE. See the GNU General Public License for more details. 14 | 15 | // You should have received a copy of the GNU General Public License 16 | // along with this program. If not, see . 17 | 18 | use cita_types::H256; 19 | use libproto::blockchain::Status as ProtoStatus; 20 | 21 | #[derive(PartialEq, Clone, Debug, Default)] 22 | pub struct Status { 23 | number: u64, 24 | hash: H256, 25 | } 26 | 27 | impl Status { 28 | pub fn hash(&self) -> &H256 { 29 | &self.hash 30 | } 31 | 32 | pub fn number(&self) -> u64 { 33 | self.number 34 | } 35 | 36 | pub fn set_hash(&mut self, h: H256) { 37 | self.hash = h; 38 | } 39 | 40 | pub fn set_number(&mut self, n: u64) { 41 | self.number = n; 42 | } 43 | 44 | pub fn protobuf(&self) -> ProtoStatus { 45 | let mut ps = ProtoStatus::new(); 46 | ps.set_height(self.number()); 47 | ps.set_hash(self.hash().to_vec()); 48 | ps 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /cita-executor/core/src/snapshot/README.md: -------------------------------------------------------------------------------- 1 | # 概述 2 | 3 | 快照含三部分: block chunks, state chunks, 及manifest. 4 | 5 | 每个chunk是snappy压缩后的hash. 压缩前的chunks大小为`CHUNK_SIZE`,目前默认4MB. 6 | 7 | 这里的数据结构都需进行RLP编码。 8 | 9 | # 清单(Manifest) 10 | 11 | 如下结构的rlp list: 12 | ``` 13 | [ 14 | state_hashes: [hash_1: B_32, hash_2: B_32, ...], // list: state chunks (snappy压缩后的hash) 15 | block_hashes: [hash_1: B_32, hash_2: B_32, ...], // list: block chunks (snappy压缩后的hash) 16 | state_root: B_32, // 用于恢复state trie的root 17 | block_number: P, // 快照对应的区块号,state也与其对应 18 | block_hash: B_32, // 快照对应的区块hash 19 | ] 20 | ``` 21 | 22 | # 区块chunks(Block chunks) 23 | 24 | 区块chunks包含原始区块数据: blocks及交易receipts. blocks格式"abridged block"(简称 `AB`), receipts格式list: `[receipt_1: P, receipt_2: P, ...]` (简称`RC`). 25 | 26 | 每个block chunk如下结构的list: 27 | ``` 28 | [ 29 | number: P, // chunk中的第一个区块号 30 | hash: B_32, // chunk中的第一个区块hash 31 | [abridged_1: AB, receipts_1: RC], // 第一个block及receipts的RLP编码(区块连续) 32 | [abridged_2: AB, receipts_2: RC], // 第二个block及receipts的RLP编码 33 | [abridged_3: AB, receipts_3: RC], // ... 34 | ... 35 | ] 36 | ``` 37 | 38 | # 状态chunks(State Chunks) 39 | 40 | State chunks存储给定区块的状态. 41 | 42 | 每个chunk由list集合构成,每个list含两项:地址的`sha3` hash,及相应的账户结构(ACC). 43 | 44 | `[ [hash1: B_32, acc_1: P], [hash_2: B_32, acc_2: P], ... ]`. 45 | 46 | ## 账户(Account) 47 | 48 | 如下格式的RLP编码list: 49 | ``` 50 | [ 51 | nonce: B_32, 52 | code: P, 53 | storage: [[keyhash1: B_32, val1: B_32], [keyhash2: B_32, val2: B_32], ...] 54 | ] 55 | ``` 56 | `storage` 为账户storage的RLP list, 每个元素含两项:`sha3(key)`, 及storage值. 57 | -------------------------------------------------------------------------------- /scripts/contracts/tests/test/unit/admin.js: -------------------------------------------------------------------------------- 1 | const chai = require('chai'); 2 | const util = require('../helpers/util'); 3 | const admin = require('../helpers/admin'); 4 | const config = require('../config'); 5 | 6 | const { expect } = chai; 7 | const { 8 | logger, getTxReceipt, 9 | } = util; 10 | const { 11 | isAdmin, update, 12 | } = admin; 13 | const { testAddr, superAdmin } = config; 14 | 15 | // temo 16 | let hash; 17 | 18 | // test data 19 | const addr = testAddr[0]; 20 | 21 | describe('\n\ntest admin\n\n', () => { 22 | it('should have built-in superAdmin', async () => { 23 | const res = await isAdmin(superAdmin.address); 24 | logger.debug('\nthe account is an superAdmin:\n', res); 25 | expect(res).to.be.true; 26 | }); 27 | 28 | it('should not be superAdmin: testAddr', async () => { 29 | const res = await isAdmin(addr); 30 | logger.debug('\nthe account is an superAdmin:\n', res); 31 | expect(res).to.be.false; 32 | }); 33 | 34 | it('should send a tx: update', async () => { 35 | const res = await update(addr); 36 | logger.debug('\nSend tx ok:\n', JSON.stringify(res)); 37 | expect(res.status).to.equal('OK'); 38 | ({ hash } = res); 39 | }); 40 | 41 | it('should get receipt: update', async () => { 42 | const res = await getTxReceipt(hash); 43 | logger.debug('\nget receipt:\n', res); 44 | expect(res.errorMessage).to.be.null; 45 | }); 46 | 47 | it('should update superAdmin', async () => { 48 | const res = await isAdmin(addr); 49 | logger.debug('\nthe account is an superAdmin:\n', res); 50 | expect(res).to.be.true; 51 | }); 52 | }); 53 | -------------------------------------------------------------------------------- /cita-executor/core/src/trace/error.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2015-2017 Parity Technologies (UK) Ltd. 2 | // This file is part of Parity. 3 | 4 | // This software is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | 9 | // This software is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | 14 | // You should have received a copy of the GNU General Public License 15 | // along with Parity. If not, see . 16 | 17 | //! `TraceDB` errors. 18 | 19 | use std::fmt::{Display, Error as FmtError, Formatter}; 20 | 21 | const RESYNC_ERR: &str = "Your current parity installation has synced without transaction tracing. 22 | To use Parity with transaction tracing, you'll need to resync with tracing. 23 | To do this, remove or move away your current database and restart parity. e.g.: 24 | 25 | > mv ~/.parity/906a34e69aec8c0d /tmp 26 | > parity"; 27 | 28 | /// `TraceDB` errors. 29 | #[derive(Debug)] 30 | pub enum Error { 31 | /// Returned when tracing is enabled, 32 | /// but database does not contain traces of old transactions. 33 | ResyncRequired, 34 | } 35 | 36 | impl Display for Error { 37 | fn fmt(&self, f: &mut Formatter) -> Result<(), FmtError> { 38 | write!(f, "{}", RESYNC_ERR) 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /tests/box-executor/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "box-executor" 3 | version = "0.1.0" 4 | authors = ["Cryptape Technologies "] 5 | edition = "2018" 6 | 7 | [dependencies] 8 | serde = "1.0" 9 | serde_derive = "1.0" 10 | serde_yaml = "0.8.6" 11 | clap = "2" 12 | rustc-serialize = "0.3" 13 | dotenv = "0.13.0" 14 | bincode = "0.8.0" 15 | cita-logger = "0.1.0" 16 | libproto = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 17 | cita-types = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 18 | cita-crypto = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 19 | hashable = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 20 | proof = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 21 | rlp = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 22 | pubsub = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 23 | 24 | [features] 25 | default = ["secp256k1", "sha3hash", "rabbitmq"] 26 | secp256k1 = ["cita-crypto/secp256k1", "libproto/secp256k1", "proof/secp256k1"] 27 | ed25519 = ["cita-crypto/ed25519", "libproto/ed25519", "proof/ed25519"] 28 | sm2 = ["cita-crypto/sm2", "libproto/sm2", "proof/sm2"] 29 | sha3hash = ["hashable/sha3hash", "libproto/sha3hash", "proof/sha3hash"] 30 | blake2bhash = ["hashable/blake2bhash", "libproto/blake2bhash", "proof/blake2bhash"] 31 | sm3hash = ["hashable/sm3hash", "libproto/sm3hash", "proof/sm3hash"] 32 | rabbitmq = ["pubsub/rabbitmq"] 33 | zeromq = ["pubsub/zeromq"] 34 | kafka = ["pubsub/kafka"] 35 | -------------------------------------------------------------------------------- /scripts/contracts/tests/test/integrate/store.js: -------------------------------------------------------------------------------- 1 | const chai = require('chai'); 2 | const util = require('../helpers/util'); 3 | const config = require('../config'); 4 | 5 | const { expect } = chai; 6 | const { superAdmin } = config; 7 | 8 | const { 9 | logger, citaSDK, genTxParams, getTxReceipt, 10 | } = util; 11 | 12 | // tmp 13 | let hash; 14 | let param; 15 | let content; 16 | 17 | // test data 18 | const msg = citaSDK.utils.utf8ToHex('This is a test'); 19 | const store = 'ffffffffffffffffffffffffffffffffff010000'; 20 | 21 | describe('test store data', () => { 22 | it('should send a tx with data', async () => { 23 | param = await genTxParams(superAdmin); 24 | const res = await citaSDK.base.sendTransaction({ 25 | ...param, 26 | to: store, 27 | data: msg, 28 | }); 29 | logger.debug('\nSend tx ok:\n', JSON.stringify(res)); 30 | expect(res.status).to.equal('OK'); 31 | ({ hash } = res); 32 | }); 33 | 34 | it('should get receipt:', async () => { 35 | const res = await getTxReceipt(hash); 36 | logger.debug('\nget receipt:\n', res); 37 | expect(res.errorMessage).to.be.null; 38 | }); 39 | 40 | it('should get tx content', async () => { 41 | const res = await citaSDK.base.getTransaction(hash); 42 | logger.debug('\nTransaction:\n', res); 43 | expect(res.hash).to.equal(hash); 44 | ({ content } = res); 45 | }); 46 | 47 | it('should equal test msg', async () => { 48 | const res = await citaSDK.base.unsigner(content); 49 | logger.debug('\nunsigner transaction content:\n', res); 50 | expect(res.transaction.data).to.equal(msg); 51 | }); 52 | }); 53 | -------------------------------------------------------------------------------- /tests/chain-executor-mock/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "chain-executor-mock" 3 | version = "0.1.0" 4 | authors = ["Cryptape Technologies "] 5 | edition = "2018" 6 | 7 | [dependencies] 8 | serde = "1.0" 9 | serde_derive = "1.0" 10 | serde_yaml = "0.8.6" 11 | clap = "2" 12 | rustc-serialize = "0.3" 13 | dotenv = "0.13.0" 14 | bincode = "0.8.0" 15 | cita-logger = "0.1.0" 16 | libproto = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 17 | cita-types = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 18 | cita-crypto = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 19 | hashable = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 20 | proof = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 21 | rlp = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 22 | pubsub = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 23 | 24 | [features] 25 | default = ["secp256k1", "sha3hash", "rabbitmq"] 26 | secp256k1 = ["cita-crypto/secp256k1", "libproto/secp256k1", "proof/secp256k1"] 27 | ed25519 = ["cita-crypto/ed25519", "libproto/ed25519", "proof/ed25519"] 28 | sm2 = ["cita-crypto/sm2", "libproto/sm2", "proof/sm2"] 29 | sha3hash = ["hashable/sha3hash", "libproto/sha3hash", "proof/sha3hash"] 30 | blake2bhash = ["hashable/blake2bhash", "libproto/blake2bhash", "proof/blake2bhash"] 31 | sm3hash = ["hashable/sm3hash", "libproto/sm3hash", "proof/sm3hash"] 32 | rabbitmq = ["pubsub/rabbitmq"] 33 | zeromq = ["pubsub/zeromq"] 34 | kafka = ["pubsub/kafka"] 35 | -------------------------------------------------------------------------------- /scripts/contracts/tests/test/helpers/chain_manager.js: -------------------------------------------------------------------------------- 1 | const fs = require('fs'); 2 | const util = require('./util'); 3 | const config = require('../config'); 4 | 5 | const { genContract, genTxParams } = util; 6 | 7 | const { superAdmin } = config; 8 | const { chainManager } = config.contract; 9 | 10 | const abi = JSON.parse(fs.readFileSync('../interaction/abi/ChainManager.abi')); 11 | const contract = genContract(abi, chainManager); 12 | 13 | // tmp 14 | let param; 15 | 16 | // newSideChain 17 | const newSideChain = async (id, address, _sender = superAdmin) => { 18 | param = await genTxParams(_sender); 19 | return contract.methods.newSideChain( 20 | id, 21 | address, 22 | ).send(param); 23 | }; 24 | 25 | // enableSideChain 26 | const enableSideChain = async (id, _sender = superAdmin) => { 27 | param = await genTxParams(_sender); 28 | return contract.methods.enableSideChain(id).send(param); 29 | }; 30 | 31 | // disableSideChain 32 | const disableSideChain = async (id, _sender = superAdmin) => { 33 | param = await genTxParams(_sender); 34 | return contract.methods.disableSideChain(id).send(param); 35 | }; 36 | 37 | // getChainId 38 | const getChainId = () => contract.methods.getChainId().call('pending'); 39 | 40 | // getParentChainId 41 | const getParentChainId = () => contract.methods.getParentChainId().call('pending'); 42 | 43 | // Get the nodes of side chain 44 | const getAuthorities = id => contract.methods.getAuthoritirs(id).call('pending'); 45 | 46 | module.exports = { 47 | newSideChain, 48 | enableSideChain, 49 | disableSideChain, 50 | getChainId, 51 | getParentChainId, 52 | getAuthorities, 53 | }; 54 | -------------------------------------------------------------------------------- /tests/chain-performance-by-mq/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "chain-performance-by-mq" 3 | version = "0.1.0" 4 | authors = ["Cryptape Technologies "] 5 | edition = "2018" 6 | 7 | [dependencies] 8 | serde = "1.0" 9 | serde_derive = "1.0" 10 | clap = "2" 11 | cita-logger = "0.1.0" 12 | libproto = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 13 | rustc-serialize = "0.3" 14 | cita-types = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 15 | cita-crypto = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 16 | hashable = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 17 | dotenv = "0.13.0" 18 | proof = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 19 | bincode = "0.8.0" 20 | cpuprofiler = "0.0.3" 21 | pubsub = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 22 | 23 | [dev-dependencies] 24 | common-types = { path = "../../cita-chain/types" } 25 | 26 | [features] 27 | default = ["secp256k1", "sha3hash", "rabbitmq"] 28 | secp256k1 = ["cita-crypto/secp256k1", "libproto/secp256k1", "proof/secp256k1"] 29 | ed25519 = ["cita-crypto/ed25519", "libproto/ed25519", "proof/ed25519"] 30 | sm2 = ["cita-crypto/sm2", "libproto/sm2", "proof/sm2"] 31 | sha3hash = ["hashable/sha3hash", "libproto/sha3hash", "proof/sha3hash"] 32 | blake2bhash = ["hashable/blake2bhash", "libproto/blake2bhash", "proof/blake2bhash"] 33 | sm3hash = ["hashable/sm3hash", "libproto/sm3hash", "proof/sm3hash"] 34 | rabbitmq = ["pubsub/rabbitmq"] 35 | zeromq = ["pubsub/zeromq"] 36 | kafka = ["pubsub/kafka"] 37 | -------------------------------------------------------------------------------- /scripts/contracts/src/user_management/AllGroups.sol: -------------------------------------------------------------------------------- 1 | pragma solidity 0.4.24; 2 | 3 | import "../lib/AddressArray.sol"; 4 | import "../common/ReservedAddrConstant.sol"; 5 | import "../../interaction/interface/IAllGroups.sol"; 6 | 7 | /// @title User management using group struct 8 | /// @author ["Cryptape Technologies "] 9 | /// @notice The address: 0xfFFffFFFfffFfFFFfFfFFfffffffFfFfFf020012 10 | /// The interface the can be called: All 11 | contract AllGroups is IAllGroups, ReservedAddrConstant { 12 | 13 | address[] groups; 14 | 15 | modifier onlyGroupManagement { 16 | require(userManagementAddr == msg.sender, "permission denied."); 17 | _; 18 | } 19 | 20 | /// @notice Constructor 21 | constructor() public { 22 | // Root 23 | groups.push(rootGroupAddr); 24 | } 25 | 26 | /// @notice Insert a new group 27 | /// @param _group the group be added 28 | function insert(address _group) 29 | external 30 | onlyGroupManagement 31 | returns (bool) 32 | { 33 | groups.push(_group); 34 | } 35 | 36 | /// @notice Delete the group 37 | /// @return True if successed, otherwise false 38 | function drop(address _group) 39 | external 40 | onlyGroupManagement 41 | returns (bool) 42 | { 43 | AddressArray.remove(_group, groups); 44 | return true; 45 | } 46 | 47 | /// @notice Query all groups 48 | /// @return All groups 49 | function queryGroups() 50 | public 51 | view 52 | returns (address[]) 53 | { 54 | return groups; 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /cita-executor/core/src/engines/null_engine.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2015-2018 Parity Technologies (UK) Ltd. 2 | // This file is part of Parity. 3 | 4 | // Parity is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | 9 | // Parity is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | 14 | // You should have received a copy of the GNU General Public License 15 | // along with Parity. If not, see . 16 | 17 | use crate::builtin::Builtin; 18 | use crate::engines::Engine; 19 | use cita_types::Address; 20 | use std::collections::BTreeMap; 21 | 22 | /// An engine which does not provide any consensus mechanism and does not seal blocks. 23 | pub struct NullEngine { 24 | builtins: BTreeMap, 25 | } 26 | 27 | impl NullEngine { 28 | /// Returns new instance of NullEngine with default VM Factory 29 | pub fn new(builtins: BTreeMap) -> Self { 30 | NullEngine { builtins } 31 | } 32 | } 33 | 34 | impl Default for NullEngine { 35 | fn default() -> Self { 36 | Self::new(Default::default()) 37 | } 38 | } 39 | 40 | impl Engine for NullEngine { 41 | fn name(&self) -> &str { 42 | "NullEngine" 43 | } 44 | 45 | fn builtins(&self) -> &BTreeMap { 46 | &self.builtins 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /scripts/contracts/tests/test/helpers/quota.js: -------------------------------------------------------------------------------- 1 | const fs = require('fs'); 2 | const util = require('./util'); 3 | const config = require('../config'); 4 | 5 | const { genContract, genTxParams } = util; 6 | 7 | const { superAdmin } = config; 8 | const { quota } = config.contract; 9 | const abi = JSON.parse(fs.readFileSync('../interaction/abi/QuotaManager.abi')); 10 | 11 | const contract = genContract(abi, quota); 12 | 13 | // setBQL 14 | const setBQL = async (value, _sender = superAdmin) => { 15 | const param = await genTxParams(_sender); 16 | return contract.methods.setBQL(value).send(param); 17 | }; 18 | 19 | // setDefaultAQL 20 | const setDefaultAQL = async (value, _sender = superAdmin) => { 21 | const param = await genTxParams(_sender); 22 | return contract.methods.setDefaultAQL(value).send(param); 23 | }; 24 | 25 | // setAQL 26 | const setAQL = async (account, value, _sender = superAdmin) => { 27 | const param = await genTxParams(_sender); 28 | return contract.methods.setAQL(account, value).send(param); 29 | }; 30 | 31 | // getAccounts 32 | const getAccounts = () => contract.methods.getAccounts().call('pending'); 33 | 34 | // getQuotas 35 | const getQuotas = () => contract.methods.getQuotas().call('pending'); 36 | 37 | // getBQL 38 | const getBQL = () => contract.methods.getBQL().call('pending'); 39 | 40 | // getDefaultAQL 41 | const getDefaultAQL = () => contract.methods.getDefaultAQL().call('pending'); 42 | 43 | // getAQL 44 | const getAQL = account => contract.methods.getAQL(account).call('pending'); 45 | 46 | module.exports = { 47 | setBQL, 48 | setDefaultAQL, 49 | setAQL, 50 | getAccounts, 51 | getQuotas, 52 | getBQL, 53 | getDefaultAQL, 54 | getAQL, 55 | }; 56 | -------------------------------------------------------------------------------- /cita-executor/core/src/libexecutor/call_request.rs: -------------------------------------------------------------------------------- 1 | // CITA 2 | // Copyright 2016-2019 Cryptape Technologies LLC. 3 | 4 | // This program is free software: you can redistribute it 5 | // and/or modify it under the terms of the GNU General Public 6 | // License as published by the Free Software Foundation, 7 | // either version 3 of the License, or (at your option) any 8 | // later version. 9 | 10 | // This program is distributed in the hope that it will be 11 | // useful, but WITHOUT ANY WARRANTY; without even the implied 12 | // warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR 13 | // PURPOSE. See the GNU General Public License for more details. 14 | 15 | // You should have received a copy of the GNU General Public License 16 | // along with this program. If not, see . 17 | 18 | use cita_types::Address; 19 | use libproto::request::Call; 20 | use util::Bytes; 21 | 22 | /// Call request 23 | #[derive(Debug, Default, PartialEq)] 24 | pub struct CallRequest { 25 | /// From 26 | pub from: Option
, 27 | /// To 28 | pub to: Address, 29 | /// Data 30 | pub data: Option, 31 | } 32 | 33 | impl From for CallRequest { 34 | fn from(call: Call) -> Self { 35 | CallRequest { 36 | from: if call.get_from().is_empty() { 37 | None 38 | } else { 39 | Some(Address::from(call.get_from())) 40 | }, 41 | to: Address::from(call.get_to()), 42 | data: if call.data.is_empty() { 43 | None 44 | } else { 45 | Some(call.data) 46 | }, 47 | } 48 | } 49 | } 50 | 51 | #[cfg(test)] 52 | mod tests {} 53 | -------------------------------------------------------------------------------- /cita-chain/types/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "common-types" 3 | description = "Common types used throughout the codebase" 4 | version = "0.1.0" 5 | authors = ["Cryptape Technologies "] 6 | edition = "2018" 7 | 8 | [dependencies] 9 | rlp = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 10 | rlp_derive = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 11 | util = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 12 | cita-types = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 13 | hashable = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 14 | jsonrpc-types = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 15 | cita-crypto = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 16 | libproto = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 17 | serde = "1.0" 18 | serde_derive = "1.0" 19 | bloomchain = "0.2" 20 | lazy_static = "0.2" 21 | time = "0.1" 22 | cita-logger = "0.1.0" 23 | proof = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 24 | db = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 25 | 26 | [features] 27 | default = ["secp256k1", "sha3hash"] 28 | secp256k1 = ["cita-crypto/secp256k1", "libproto/secp256k1"] 29 | ed25519 = ["cita-crypto/ed25519", "libproto/ed25519"] 30 | sm2 = ["cita-crypto/sm2", "libproto/sm2"] 31 | sha3hash = ["hashable/sha3hash", "db/sha3hash", "libproto/sha3hash"] 32 | blake2bhash = ["hashable/blake2bhash", "db/blake2bhash", "libproto/blake2bhash"] 33 | sm3hash = ["hashable/sm3hash", "db/sm3hash", "libproto/sm3hash"] 34 | -------------------------------------------------------------------------------- /cita-executor/core/src/trace/config.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2015-2017 Parity Technologies (UK) Ltd. 2 | // This file is part of Parity. 3 | 4 | // This software is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | 9 | // This software is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | 14 | // You should have received a copy of the GNU General Public License 15 | // along with Parity. If not, see . 16 | 17 | //! Traces config. 18 | 19 | use crate::bloomchain::Config as BloomConfig; 20 | 21 | /// Traces config. 22 | #[derive(Debug, PartialEq, Clone, Copy)] 23 | pub struct Config { 24 | /// Indicates if tracing should be enabled or not. 25 | /// If it's None, it will be automatically configured. 26 | pub enabled: bool, 27 | /// Traces blooms configuration. 28 | pub blooms: BloomConfig, 29 | /// Preferef cache-size. 30 | pub pref_cache_size: usize, 31 | /// Max cache-size. 32 | pub max_cache_size: usize, 33 | } 34 | 35 | impl Default for Config { 36 | fn default() -> Self { 37 | Config { 38 | enabled: false, 39 | blooms: BloomConfig { 40 | levels: 3, 41 | elements_per_index: 16, 42 | }, 43 | pref_cache_size: 15 * 1024 * 1024, 44 | max_cache_size: 20 * 1024 * 1024, 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /scripts/contracts/tests/test/unit/quota.js: -------------------------------------------------------------------------------- 1 | const chai = require('chai'); 2 | const util = require('../helpers/util'); 3 | const quota = require('../helpers/quota'); 4 | const config = require('../config'); 5 | 6 | const { expect } = chai; 7 | const { logger } = util; 8 | const { superAdmin } = config; 9 | 10 | const { 11 | getAQL, getDefaultAQL, getBQL, getQuotas, getAccounts, 12 | } = quota; 13 | 14 | // test data TODO as a file 15 | const admin = superAdmin.address; 16 | const BQL = '1073741824'; 17 | const defaultAQL = '268435456'; 18 | const AQL = '1073741824'; 19 | 20 | describe('test quota manager constructor', () => { 21 | it('should have build-in special account', async () => { 22 | const res = await getAccounts(); 23 | logger.debug('\nthe special accounts:\n', res); 24 | expect(res[0]).to.equal(admin); 25 | }); 26 | 27 | it('should have build-in quotas of special accounts', async () => { 28 | const res = await getQuotas(); 29 | logger.debug('\nthe quotas of the special accounts:\n', res); 30 | expect(res[0]).to.equal(AQL); 31 | }); 32 | 33 | it('should have build-in block quota limit', async () => { 34 | const res = await getBQL(); 35 | logger.debug('\nthe block quota limit:\n', res); 36 | expect(res).to.equal(BQL); 37 | }); 38 | 39 | it('should have build-in default quota limit of account', async () => { 40 | const res = await getDefaultAQL(); 41 | logger.debug('\nthe default quota limit of account:\n', res); 42 | expect(res).to.equal(defaultAQL); 43 | }); 44 | 45 | it('should have build-in quota of admin', async () => { 46 | const res = await getAQL(admin); 47 | logger.debug('\nthe quota of admin:\n', res); 48 | expect(res).to.equal(AQL); 49 | }); 50 | }); 51 | -------------------------------------------------------------------------------- /scripts/contracts/src/system/VersionManager.sol: -------------------------------------------------------------------------------- 1 | pragma solidity 0.4.24; 2 | 3 | import "../common/Admin.sol"; 4 | import "../common/ReservedAddrPublic.sol"; 5 | import "../../interaction/interface/IVersionManager.sol"; 6 | import "../../interaction/interface/ISysConfig.sol"; 7 | 8 | contract VersionManager is IVersionManager, ReservedAddrPublic { 9 | uint32 public version; 10 | 11 | Admin admin = Admin(adminAddr); 12 | 13 | modifier onlyAdmin { 14 | if (admin.isAdmin(msg.sender)) 15 | _; 16 | else return; 17 | } 18 | 19 | /// @notice Setup 20 | constructor(uint32 _version) 21 | public 22 | { 23 | version = _version; 24 | } 25 | 26 | function setProtocolVersion(uint32 _version) 27 | public 28 | onlyAdmin 29 | { 30 | if (_version != version + 1) { 31 | revert("New version must be greater by 1 than the older one."); 32 | } 33 | if (version == 0 && _version == 1) { 34 | ISysConfig config = ISysConfig(sysConfigAddr); 35 | config.updateToChainIdV1(); 36 | } 37 | version = _version; 38 | } 39 | 40 | /// @notice Deprecated. Check the setProtocolVersion 41 | function setVersion(uint32 _version) 42 | public 43 | onlyAdmin 44 | { 45 | setProtocolVersion(_version); 46 | } 47 | 48 | function getProtocolVersion() 49 | public 50 | view 51 | returns (uint32) 52 | { 53 | return version; 54 | } 55 | 56 | /// @notice Deprecated. Check the getProtocolVersion 57 | function getVersion() 58 | public 59 | view 60 | returns (uint32) 61 | { 62 | return getProtocolVersion(); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /cita-executor/core/src/trace/types/localized.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2015-2017 Parity Technologies (UK) Ltd. 2 | // This file is part of Parity. 3 | 4 | // This software is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | 9 | // This software is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | 14 | // You should have received a copy of the GNU General Public License 15 | // along with Parity. If not, see . 16 | 17 | //! Localized traces type definitions 18 | 19 | use super::trace::{Action, Res}; 20 | use crate::header::BlockNumber; 21 | use cita_types::H256; 22 | 23 | /// Localized trace. 24 | #[derive(Debug, PartialEq, Clone)] 25 | #[cfg_attr(feature = "ipc", binary)] 26 | pub struct LocalizedTrace { 27 | /// Type of action performed by a transaction. 28 | pub action: Action, 29 | /// Result of this action. 30 | pub result: Res, 31 | /// Number of subtraces. 32 | pub subtraces: usize, 33 | /// Exact location of trace. 34 | /// 35 | /// [index in root, index in first CALL, index in second CALL, ...] 36 | pub trace_address: Vec, 37 | /// Transaction number within the block. 38 | pub transaction_number: usize, 39 | /// Signed transaction hash. 40 | pub transaction_hash: H256, 41 | /// Block number. 42 | pub block_number: BlockNumber, 43 | /// Block hash. 44 | pub block_hash: H256, 45 | } 46 | -------------------------------------------------------------------------------- /tests/box-executor/src/config.rs: -------------------------------------------------------------------------------- 1 | extern crate cita_crypto as crypto; 2 | 3 | use crate::crypto::PrivKey; 4 | use std::collections::HashMap; 5 | use std::fs; 6 | use std::io::Read; 7 | use std::str::FromStr; 8 | 9 | pub struct Config { 10 | pub private_key: PrivKey, 11 | pub blocks: HashMap, 12 | } 13 | 14 | impl Config { 15 | // Initialize Config from given command line options 16 | pub fn init(path: &str) -> Self { 17 | let mut yaml_str = String::new(); 18 | let _ = fs::File::open(path) 19 | .unwrap() 20 | .read_to_string(&mut yaml_str) 21 | .unwrap(); 22 | let mut yaml: serde_yaml::Value = serde_yaml::from_str(yaml_str.as_str()).unwrap(); 23 | 24 | let blocks = { 25 | let mut mock_blocks: HashMap = HashMap::new(); 26 | for block in yaml["blocks"].as_sequence_mut().unwrap().iter() { 27 | let block_number = block["number"].as_u64().unwrap(); 28 | mock_blocks.insert(block_number, block.clone()); 29 | } 30 | Self::detect_missing_blocks(&mock_blocks); 31 | mock_blocks 32 | }; 33 | let private_key: PrivKey = { 34 | let val = &yaml; 35 | let val = val["privkey"].as_str().unwrap(); 36 | PrivKey::from_str(val).unwrap() 37 | }; 38 | 39 | Config { 40 | private_key, 41 | blocks, 42 | } 43 | } 44 | 45 | fn detect_missing_blocks(blocks: &HashMap) { 46 | for number in 1..=blocks.len() as u64 { 47 | if !blocks.contains_key(&number) { 48 | panic!("missing block-{}", number); 49 | } 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /scripts/txtool/txtool/call.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # coding=utf-8 3 | 4 | import argparse 5 | from jsonrpcclient.http_client import HTTPClient 6 | from url_util import endpoint 7 | 8 | 9 | def build_params(sender, to, data, number): 10 | dictionary = { 11 | "from": "" if sender is None else sender, 12 | "to": "" if to is None else to, 13 | "data": data 14 | } 15 | return [dictionary, block_number(number)] 16 | 17 | 18 | def block_number(number): 19 | result = 0 20 | if number.startswith('0x') or number.startswith('0X'): 21 | result = int(number[2:], 16) 22 | elif number == 'pending' or number == 'earliest' or number == 'latest': 23 | result = number 24 | else: 25 | result = int(number, 10) 26 | 27 | return result 28 | 29 | 30 | def call(params): 31 | try: 32 | url = endpoint() 33 | response = HTTPClient(url).request("call", params) 34 | except: 35 | return None 36 | 37 | return response 38 | 39 | 40 | def main(): 41 | parser = argparse.ArgumentParser() 42 | parser.add_argument( 43 | "--sender", help="20 bytes ethereum compatiable address.") 44 | parser.add_argument("to", help="20 bytes ethereum compatiable address.") 45 | parser.add_argument("data", help="compiled solidity function.") 46 | parser.add_argument("number", help="block number", nargs='?') 47 | 48 | args = parser.parse_args() 49 | 50 | sender = args.sender 51 | if args.sender is None: 52 | sender = "" 53 | 54 | number = args.number 55 | if args.number is None: 56 | number = 'latest' 57 | 58 | params = build_params(sender, args.to, args.data, number) 59 | resp = call(params) 60 | if resp is not None: 61 | print(resp) 62 | 63 | 64 | if __name__ == "__main__": 65 | main() 66 | -------------------------------------------------------------------------------- /cita-chain/src/block_processor.rs: -------------------------------------------------------------------------------- 1 | // CITA 2 | // Copyright 2016-2019 Cryptape Technologies LLC. 3 | 4 | // This program is free software: you can redistribute it 5 | // and/or modify it under the terms of the GNU General Public 6 | // License as published by the Free Software Foundation, 7 | // either version 3 of the License, or (at your option) any 8 | // later version. 9 | 10 | // This program is distributed in the hope that it will be 11 | // useful, but WITHOUT ANY WARRANTY; without even the implied 12 | // warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR 13 | // PURPOSE. See the GNU General Public License for more details. 14 | 15 | // You should have received a copy of the GNU General Public License 16 | // along with this program. If not, see . 17 | 18 | use core::libchain::chain::Chain; 19 | use libproto::executor::ExecutedResult; 20 | use pubsub::channel::Sender; 21 | use std::sync::Arc; 22 | 23 | /// Processing blocks and transaction storage 24 | #[derive(Clone)] 25 | pub struct BlockProcessor { 26 | pub chain: Arc, 27 | ctx_pub: Sender<(String, Vec)>, 28 | } 29 | 30 | impl BlockProcessor { 31 | pub fn new(chain: Arc, ctx_pub: Sender<(String, Vec)>) -> Self { 32 | BlockProcessor { chain, ctx_pub } 33 | } 34 | 35 | pub fn broadcast_current_status(&self) { 36 | self.chain.broadcast_current_status(&self.ctx_pub); 37 | } 38 | 39 | pub fn set_executed_result(&self, ret: &ExecutedResult) { 40 | self.chain.set_executed_result(ret, &self.ctx_pub); 41 | } 42 | 43 | pub fn reset_max_store_height(&self) { 44 | self.chain 45 | .set_max_store_height(self.chain.get_current_height()); 46 | } 47 | 48 | pub fn signal_to_executor(&self) { 49 | self.chain.signal_to_executor(&self.ctx_pub) 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /tests/integrate_test/txtool_utils.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import functools 4 | import subprocess 5 | import time 6 | from jsonrpcclient.http_client import HTTPClient 7 | 8 | LATEST_VERSION = 2 9 | DEFAULT_QUOTA = 1000000 10 | 11 | 12 | def send_tx(privkey, 13 | code="", 14 | to="", 15 | value=0, 16 | quota=DEFAULT_QUOTA, 17 | version=LATEST_VERSION): 18 | """ 19 | python3 make_tx.py --privkey "$$" --to "$$" --code "$$" -- version "$$" 20 | 21 | python3 send_tx.py 22 | """ 23 | 24 | kwargs = { 25 | '--privkey': privkey, 26 | '--to': to, 27 | '--code': code, 28 | '--value': str(value), 29 | '--quota': str(quota), 30 | '--version': str(version), 31 | } 32 | args = functools.reduce( 33 | lambda lst, kv: lst + list(kv), 34 | kwargs.items(), 35 | [], 36 | ) 37 | print(['python3', 'make_tx.py', *args]) 38 | subprocess.call(['python3', 'make_tx.py', *args, '--no-newcrypto']) 39 | subprocess.call(['python3', 'send_tx.py']) 40 | with open('../output/transaction/hash') as fobj: 41 | return fobj.read().strip() 42 | 43 | 44 | def get_receipt(tx_hash, retry=8): 45 | """ Get receipt of a transaction """ 46 | while retry > 0: 47 | receipt = rpc_request('getTransactionReceipt', [tx_hash]) 48 | if receipt is not None: 49 | return receipt 50 | time.sleep(4) 51 | retry -= 1 52 | 53 | 54 | def rpc_request(method, params): 55 | """ Send a jsonrpc request to default url. """ 56 | client = HTTPClient('http://127.0.0.1:1337') 57 | return client.request(method, params) 58 | 59 | 60 | def get_balance(addr): 61 | """ Get the balance of an address """ 62 | return int(rpc_request('getBalance', [addr, 'pending']), 16) 63 | -------------------------------------------------------------------------------- /scripts/contracts/tests/test/unit/version_manager.js: -------------------------------------------------------------------------------- 1 | const chai = require('chai'); 2 | const util = require('../helpers/util'); 3 | const versionManager = require('../helpers/version_manager'); 4 | 5 | const { expect } = chai; 6 | const { 7 | logger, getTxReceipt, getMetaData, 8 | } = util; 9 | const { 10 | setProtocolVersion, getProtocolVersion, getVersion, 11 | } = versionManager; 12 | 13 | // temp 14 | let hash; 15 | let version; 16 | 17 | describe('\n\ntest version manager\n\n', () => { 18 | before('should have version', async () => { 19 | const metaData = await getMetaData(); 20 | ({ version } = metaData); 21 | logger.debug('\nthe version of metaData is:\n', version); 22 | }); 23 | 24 | it('should get the protocol version', async () => { 25 | const res = await getProtocolVersion(); 26 | logger.debug('\nthe version is:\n', res); 27 | expect(+res).to.be.equal(version); 28 | }); 29 | 30 | it('should send a tx: setProtocolVersion', async () => { 31 | const res = await setProtocolVersion(version + 1); 32 | logger.debug('\nSend tx ok:\n', JSON.stringify(res)); 33 | expect(res.status).to.equal('OK'); 34 | ({ hash } = res); 35 | }); 36 | 37 | it('should get receipt: setProtocolVersion', async () => { 38 | const res = await getTxReceipt(hash); 39 | logger.debug('\nget receipt:\n', res); 40 | expect(res.errorMessage).to.be.null; 41 | version += 1; 42 | }); 43 | 44 | it('should get the protocol version', async () => { 45 | const res = await getProtocolVersion(); 46 | logger.debug('\nthe version is:\n', res); 47 | expect(+res).to.be.equal(version); 48 | }); 49 | 50 | // old interface 51 | it('should get the version', async () => { 52 | const res = await getVersion(); 53 | logger.debug('\nthe version is:\n', res); 54 | expect(+res).to.be.equal(version); 55 | }); 56 | }); 57 | -------------------------------------------------------------------------------- /cita-chain/core/src/lib.rs: -------------------------------------------------------------------------------- 1 | // CITA 2 | // Copyright 2016-2019 Cryptape Technologies LLC. 3 | 4 | // This program is free software: you can redistribute it 5 | // and/or modify it under the terms of the GNU General Public 6 | // License as published by the Free Software Foundation, 7 | // either version 3 of the License, or (at your option) any 8 | // later version. 9 | 10 | // This program is distributed in the hope that it will be 11 | // useful, but WITHOUT ANY WARRANTY; without even the implied 12 | // warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR 13 | // PURPOSE. See the GNU General Public License for more details. 14 | 15 | // You should have received a copy of the GNU General Public License 16 | // along with this program. If not, see . 17 | 18 | extern crate byteorder; 19 | #[macro_use] 20 | extern crate libproto; 21 | #[macro_use] 22 | extern crate cita_logger as logger; 23 | extern crate cita_merklehash; 24 | extern crate hashable; 25 | extern crate lru_cache; 26 | extern crate proof; 27 | extern crate rlp; 28 | extern crate snappy; 29 | #[macro_use] 30 | extern crate serde_derive; 31 | #[macro_use] 32 | extern crate util; 33 | extern crate db as cita_db; 34 | 35 | #[macro_use] 36 | extern crate rlp_derive; 37 | extern crate rustc_hex; 38 | 39 | extern crate bincode; 40 | extern crate bit_set; 41 | extern crate cita_ed25519; 42 | extern crate cita_secp256k1; 43 | extern crate cita_types; 44 | extern crate common_types as types; 45 | extern crate crossbeam; 46 | extern crate jsonrpc_types; 47 | extern crate pubsub; 48 | extern crate time; 49 | extern crate transient_hashmap; 50 | 51 | #[cfg(test)] 52 | extern crate cita_crypto; 53 | 54 | pub mod env_info; 55 | 56 | #[macro_use] 57 | pub mod error; 58 | pub mod filters; 59 | pub mod libchain; 60 | pub mod snapshot; 61 | pub use crate::cita_db::journaldb; 62 | pub use crate::types::*; 63 | -------------------------------------------------------------------------------- /cita-chain/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | description = "CITA node." 3 | name = "cita-chain" 4 | version = "0.6.0" 5 | authors = ["Cryptape Technologies "] 6 | edition = "2018" 7 | 8 | [dependencies] 9 | dotenv = "0.13.0" 10 | clap = "2" 11 | byteorder = { version = "1", default-features = false } 12 | serde_json = "1.0" 13 | cita-logger = "0.1.0" 14 | cita-types = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 15 | libproto = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 16 | pubsub = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 17 | cita-directories = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 18 | util = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 19 | error = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 20 | jsonrpc-types = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 21 | core = { path = "./core" } 22 | common-types = { path = "./types" } 23 | proof = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 24 | db = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 25 | 26 | [build-dependencies] 27 | util = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 28 | 29 | [features] 30 | default = ["secp256k1", "sha3hash", "rabbitmq"] 31 | secp256k1 = ["libproto/secp256k1", "proof/secp256k1"] 32 | ed25519 = ["libproto/ed25519", "proof/ed25519"] 33 | sm2 = ["libproto/sm2", "proof/sm2"] 34 | sha3hash = ["libproto/sha3hash", "db/sha3hash", "proof/sha3hash"] 35 | blake2bhash = ["libproto/blake2bhash", "db/blake2bhash", "proof/blake2bhash"] 36 | sm3hash = ["libproto/sm3hash", "db/sm3hash", "proof/sm3hash"] 37 | rabbitmq = ["pubsub/rabbitmq"] 38 | zeromq = ["pubsub/zeromq"] 39 | kafka = ["pubsub/kafka"] 40 | -------------------------------------------------------------------------------- /cita-executor/evm/src/lib.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2015-2017 Parity Technologies (UK) Ltd. 2 | // This file is part of Parity. 3 | 4 | // This software is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | 9 | // This software is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | 14 | // You should have received a copy of the GNU General Public License 15 | // along with Parity. If not, see . 16 | 17 | //! Ethereum virtual machine. 18 | 19 | #[cfg_attr(feature = "evm-debug", macro_use)] 20 | extern crate cita_logger as logger; 21 | pub extern crate cita_types; 22 | extern crate common_types as types; 23 | extern crate db as cita_db; 24 | 25 | pub mod action_params; 26 | pub mod call_type; 27 | pub mod env_info; 28 | pub mod error; 29 | pub mod evm; 30 | pub mod ext; 31 | pub mod interpreter; 32 | pub mod return_data; 33 | #[macro_use] 34 | pub mod storage; 35 | #[macro_use] 36 | pub mod factory; 37 | pub mod instructions; 38 | pub mod schedule; 39 | #[macro_use] 40 | extern crate lazy_static; 41 | 42 | #[cfg(all(feature = "benches", test))] 43 | mod benches; 44 | #[cfg(test)] 45 | pub mod tests; 46 | 47 | pub mod fake_tests; 48 | 49 | pub use self::error::{Error, Result}; 50 | pub use self::evm::{CostType, Evm, FinalizationResult, Finalize}; 51 | pub use self::ext::{ContractCreateResult, Ext, MessageCallResult}; 52 | pub use self::factory::{Factory, VMType}; 53 | pub use self::instructions::*; 54 | pub use self::return_data::{GasLeft, ReturnData}; 55 | pub use self::schedule::Schedule; 56 | -------------------------------------------------------------------------------- /cita-chain/types/src/state_diff.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2015-2017 Parity Technologies (UK) Ltd. 2 | // This file is part of Parity. 3 | 4 | // This software is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | 9 | // This software is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | 14 | // You should have received a copy of the GNU General Public License 15 | // along with Parity. If not, see . 16 | 17 | //! State diff module. 18 | 19 | use crate::account_diff::*; 20 | use cita_types::Address; 21 | use std::collections::BTreeMap; 22 | use std::fmt; 23 | use std::ops::*; 24 | 25 | #[derive(Debug, PartialEq, Eq, Clone)] 26 | #[cfg_attr(feature = "ipc", binary)] 27 | /// Expression for the delta between two system states. Encoded the 28 | /// delta of every altered account. 29 | pub struct StateDiff { 30 | /// Raw diff key-value 31 | pub raw: BTreeMap, 32 | } 33 | 34 | impl StateDiff { 35 | /// Get the actual data. 36 | pub fn get(&self) -> &BTreeMap { 37 | &self.raw 38 | } 39 | } 40 | 41 | impl fmt::Display for StateDiff { 42 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 43 | for (add, acc) in &self.raw { 44 | write!(f, "{} {}: {}", acc.existance(), add, acc)?; 45 | } 46 | Ok(()) 47 | } 48 | } 49 | 50 | impl Deref for StateDiff { 51 | type Target = BTreeMap; 52 | 53 | fn deref(&self) -> &Self::Target { 54 | &self.raw 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /scripts/contracts/tests/test/integrate/abi.js: -------------------------------------------------------------------------------- 1 | const chai = require('chai'); 2 | const util = require('../helpers/util'); 3 | const config = require('../config'); 4 | 5 | const { expect } = chai; 6 | const { 7 | citaSDK, logger, genTxParams, 8 | } = util; 9 | 10 | const abiArray = [{ 11 | constant: false, inputs: [{ name: '_value', type: 'uint256' }], name: 'set', outputs: [], payable: false, stateMutability: 'nonpayable', type: 'function', 12 | }, { 13 | constant: true, inputs: [], name: 'get', outputs: [{ name: '', type: 'uint256' }], payable: false, stateMutability: 'view', type: 'function', 14 | }]; 15 | 16 | const abi = JSON.parse('[{"constant":false,"inputs":[{"name":"_value","type":"uint256"}],"name":"set","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"get","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"}]'); 17 | const { testBin } = config; 18 | const { superAdmin } = config; 19 | 20 | let addr; 21 | let param; 22 | 23 | describe('\n\ntest store/get abi\n\n', () => { 24 | it('should send a tx: deploy_contract', async () => { 25 | param = await genTxParams(superAdmin); 26 | const res = await citaSDK.base.deploy( 27 | testBin, 28 | param, 29 | ); 30 | logger.debug('\nDeploy a contract:\n', res.contractAddress); 31 | addr = res.contractAddress; 32 | }); 33 | 34 | it('should send a tx: store abi', async () => { 35 | param = await genTxParams(superAdmin); 36 | const res = await citaSDK.base.storeAbi( 37 | addr, 38 | abi, 39 | param, 40 | ); 41 | logger.debug('\nStore abi:\n', res); 42 | }); 43 | 44 | it('should get the abi', async () => { 45 | const res = await citaSDK.base.getAbi(addr, 'pending'); 46 | logger.debug('\nabi of test:\n', res); 47 | expect(res).to.deep.equal(abiArray); 48 | }); 49 | }); 50 | -------------------------------------------------------------------------------- /tools/create-genesis/src/common.rs: -------------------------------------------------------------------------------- 1 | use ethereum_types::Public; 2 | use evm::cita_types::{Address, U256}; 3 | 4 | use core_executor::cita_db::{journaldb, kvdb, KeyValueDB}; 5 | use core_executor::db; 6 | use core_executor::state::State; 7 | use core_executor::state_db::StateDB; 8 | use std::sync::Arc; 9 | 10 | pub fn clean_0x(s: &str) -> &str { 11 | if s.starts_with("0x") { 12 | &s[2..] 13 | } else { 14 | s 15 | } 16 | } 17 | 18 | pub fn string_2_bytes(value: String) -> Vec { 19 | let v = Box::leak(value.into_boxed_str()); 20 | let v = clean_0x(v); 21 | hex::decode(v).unwrap() 22 | } 23 | 24 | pub fn string_2_u256(value: String) -> U256 { 25 | let v = Box::leak(value.into_boxed_str()); 26 | let v = clean_0x(v); 27 | U256::from(v) 28 | } 29 | 30 | pub fn public_2_address(public: &Public) -> Address { 31 | let hash = tiny_keccak::keccak256(&public.0); 32 | let mut result = Address::default(); 33 | result.copy_from_slice(&hash[12..]); 34 | result 35 | } 36 | 37 | pub fn secret_2_address(secret: &str) -> Address { 38 | let a = hex::decode(clean_0x(secret)).unwrap(); 39 | let secret_key = secp256k1::SecretKey::parse_slice(a.as_slice()).unwrap(); 40 | let public_key = secp256k1::PublicKey::from_secret_key(&secret_key); 41 | let serialized = public_key.serialize(); 42 | let public = Public::from_slice(&serialized[1..65]); 43 | public_2_address(&public) 44 | } 45 | 46 | pub fn get_temp_state() -> State { 47 | let state_db = get_temp_state_db(); 48 | State::new(state_db, 0.into(), Default::default()) 49 | } 50 | 51 | pub fn new_db() -> Arc { 52 | Arc::new(kvdb::in_memory(8)) 53 | } 54 | 55 | pub fn get_temp_state_db() -> StateDB { 56 | let db = new_db(); 57 | let journal_db = journaldb::new(db, journaldb::Algorithm::Archive, db::COL_STATE); 58 | StateDB::new(journal_db, 5 * 1024 * 1024) 59 | } 60 | -------------------------------------------------------------------------------- /scripts/contracts/src/system/BatchTx.sol: -------------------------------------------------------------------------------- 1 | pragma solidity 0.4.24; 2 | 3 | import "../../interaction/interface/IBatchTx.sol"; 4 | 5 | /// @title Batch tx 6 | /// @author ["Cryptape Technologies "] 7 | /// @dev TODO use native contract 8 | contract BatchTx is IBatchTx { 9 | 10 | /// @notice Proxy multiple transactions 11 | /// The encoded transactions data: tuple(address,dataLen,data) 12 | /// dataLen: uint32 13 | /// address: uint160 14 | /// Example: 15 | /// address: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx 16 | /// datalen: 00000004 17 | /// data: xxxxxxxx 18 | function multiTxs(bytes) 19 | external 20 | { 21 | // solium-disable-next-line security/no-inline-assembly 22 | assembly { 23 | // Ignore the function sig: 0x4 24 | // the offset of bytes: 0x20 25 | // the len of bytes: 0x20 26 | let offset := 0x44 27 | for { } lt(offset, calldatasize) { } { 28 | // 0xc bytes forward from the offset(0x20-0x14) 29 | // Use `and` instruction just for safe 30 | let to := and(calldataload(sub(offset, 0xc)), 0x000000000000000000000000ffffffffffffffffffffffffffffffffffffffff) 31 | // 0x8 bytes forward from the offset(0x20-0x14-0x4) 32 | let dataLen := and(calldataload(sub(offset, 0x8)), 0x00000000000000000000000000000000000000000000000000000000ffffffff) 33 | let ptr := mload(0x40) 34 | // Jump the address and dataLen(0x14+0x4) 35 | calldatacopy(ptr, add(offset, 0x18), dataLen) 36 | switch call(gas, to, 0, ptr, dataLen, ptr, 0) 37 | case 0 { revert(0, 0) } 38 | offset := add(add(offset, 0x18), dataLen) 39 | } 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /tests/box-executor/src/main.rs: -------------------------------------------------------------------------------- 1 | // CITA 2 | // Copyright 2016-2019 Cryptape Technologies LLC. 3 | 4 | // This program is free software: you can redistribute it 5 | // and/or modify it under the terms of the GNU General Public 6 | // License as published by the Free Software Foundation, 7 | // either version 3 of the License, or (at your option) any 8 | // later version. 9 | 10 | // This program is distributed in the hope that it will be 11 | // useful, but WITHOUT ANY WARRANTY; without even the implied 12 | // warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR 13 | // PURPOSE. See the GNU General Public License for more details. 14 | 15 | // You should have received a copy of the GNU General Public License 16 | // along with this program. If not, see . 17 | 18 | extern crate cita_crypto as crypto; 19 | #[macro_use] 20 | extern crate libproto; 21 | #[macro_use] 22 | extern crate cita_logger as logger; 23 | 24 | #[macro_use] 25 | extern crate serde_derive; 26 | 27 | mod config; 28 | mod generate_block; 29 | mod runner; 30 | 31 | use crate::config::Config; 32 | use clap::App; 33 | use std::env; 34 | 35 | fn main() { 36 | dotenv::dotenv().ok(); 37 | env::set_var("RUST_BACKTRACE", "full"); 38 | logger::init_config(&logger::LogFavour::File("box_executor")); 39 | let matches = App::new("mock-consensus") 40 | .arg( 41 | clap::Arg::with_name("mock-data") 42 | .short("m") 43 | .long("mock-data") 44 | .required(true) 45 | .takes_value(true) 46 | .help(".yaml which contains blocks data"), 47 | ) 48 | .get_matches(); 49 | let path = matches.value_of("mock-data").unwrap(); 50 | info!("mock-data-path={}", path); 51 | info!("AMQP_URL={}", env::var("AMQP_URL").expect("AMQP_URL empty")); 52 | 53 | let config = Config::init(path); 54 | runner::run(config); 55 | } 56 | -------------------------------------------------------------------------------- /tests/integrate_test/box_executor_test.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | set -e 4 | 5 | ECONOMICAL_MODEL="0" 6 | if [[ -n "$1" ]] && [ "$1" = "charge" ]; then 7 | ECONOMICAL_MODEL="1" 8 | fi 9 | 10 | if [[ $(uname) == 'Darwin' ]] 11 | then 12 | SOURCE_DIR=$(realpath "$(dirname "$0")"/../..) 13 | else 14 | SOURCE_DIR=$(readlink -f "$(dirname "$0")"/../..) 15 | fi 16 | BINARY_DIR=${SOURCE_DIR}/target/install 17 | 18 | 19 | main() { 20 | echo -n "0) prepare ... " 21 | # shellcheck source=/dev/null 22 | . ${SOURCE_DIR}/tests/integrate_test/util.sh 23 | cd "${BINARY_DIR}" 24 | echo "DONE" 25 | 26 | echo -n "1) generate config ... " 27 | if [ ! -d "resource" ]; then 28 | mkdir resource 29 | fi 30 | 31 | autorities=$(xargs echo < "${SOURCE_DIR}"/tests/interfaces/config/authorities | sed "s/ /,/g") 32 | create_config \ 33 | --contract_arguments "SysConfig.economicalModel=${ECONOMICAL_MODEL}" \ 34 | --contract_arguments "SysConfig.chainId=123" \ 35 | --timestamp 1524000000 \ 36 | --authorities "${autorities}" 37 | echo -n "DONE" 38 | 39 | echo -n "2) start cita-chain and cita-executor on node0 ... " 40 | bin/cita bebop setup "${CHAIN_NAME}"/0 41 | 42 | tnode=$(echo "${CHAIN_NAME}"/0 | sed 's/\//%2f/g') 43 | curl -i -u guest:guest -H content-type:application/json -XDELETE \ 44 | http://localhost:15672/api/queues/"${tnode}"/consensus > /dev/null 45 | 46 | node_dir="${BINARY_DIR}/${CHAIN_NAME}/0" 47 | bin/cita-chain -c "${node_dir}"/chain.toml & 48 | bin/cita-executor -c "${node_dir}"/executor.toml & 49 | echo -n "DONE" 50 | 51 | echo -n "3) testing ... " 52 | AMQP_URL=amqp://guest:guest@localhost/${CHAIN_NAME}/0 \ 53 | timeout 100s "${BINARY_DIR}"/bin/box_executor \ 54 | -m "${SOURCE_DIR}"/tests/interfaces/config/blockchain.yaml 55 | echo -n "DONE" 56 | } 57 | 58 | main "$@" 59 | -------------------------------------------------------------------------------- /cita-auth/src/transaction_verify.rs: -------------------------------------------------------------------------------- 1 | // CITA 2 | // Copyright 2016-2019 Cryptape Technologies LLC. 3 | 4 | // This program is free software: you can redistribute it 5 | // and/or modify it under the terms of the GNU General Public 6 | // License as published by the Free Software Foundation, 7 | // either version 3 of the License, or (at your option) any 8 | // later version. 9 | 10 | // This program is distributed in the hope that it will be 11 | // useful, but WITHOUT ANY WARRANTY; without even the implied 12 | // warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR 13 | // PURPOSE. See the GNU General Public License for more details. 14 | 15 | // You should have received a copy of the GNU General Public License 16 | // along with this program. If not, see . 17 | use std::fmt; 18 | 19 | #[derive(Debug, PartialEq)] 20 | pub enum Error { 21 | InvalidNonce, 22 | Dup, 23 | InvalidUntilBlock, 24 | BadSig, 25 | NotReady, 26 | Busy, 27 | BadChainId, 28 | // TODO: rename to QuotaOverflow 29 | QuotaNotEnough, 30 | Forbidden, 31 | InvalidValue, 32 | InvalidVersion, 33 | } 34 | 35 | impl fmt::Display for Error { 36 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 37 | use self::Error::*; 38 | match *self { 39 | InvalidNonce => write!(f, "InvalidNonce"), 40 | Dup => write!(f, "Dup"), 41 | InvalidUntilBlock => write!(f, "InvalidUntilBlock"), 42 | BadSig => write!(f, "BadSig"), 43 | NotReady => write!(f, "NotReady"), 44 | Busy => write!(f, "Busy"), 45 | BadChainId => write!(f, "BadChainId"), 46 | QuotaNotEnough => write!(f, "QuotaNotEnough"), 47 | Forbidden => write!(f, "Forbidden"), 48 | InvalidValue => write!(f, "InvalidValue"), 49 | InvalidVersion => write!(f, "InvalidVersion"), 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /scripts/contracts/tests/test/unit/permission.js: -------------------------------------------------------------------------------- 1 | const chai = require('chai'); 2 | const util = require('../helpers/util'); 3 | const permission = require('../helpers/permission'); 4 | 5 | const { expect } = chai; 6 | 7 | const { citaSDK, logger } = util; 8 | 9 | const { inPermission, queryInfo } = permission; 10 | 11 | describe('test permission contract', () => { 12 | it('should be the build-in newPermission', async () => { 13 | const res = await queryInfo(); 14 | logger.debug('\nInfo:\n', res); 15 | expect(citaSDK.utils.hexToUtf8(res[0])).to.have.string('newPermission'); 16 | expect(res[1]).to.deep.equal(['0xffFffFffFFffFFFFFfFfFFfFFFFfffFFff020004']); 17 | expect(res[2]).to.deep.equal(['0xfc4a089c']); 18 | }); 19 | 20 | it('test resource in permission', async () => { 21 | const res = await inPermission( 22 | '0xffffffffffffffffffffffffffffffffff020004', 23 | '0xfc4a089c', 24 | ); 25 | logger.debug('\nThe result:\n', res); 26 | expect(res).to.equal(true); 27 | }); 28 | 29 | it('test resource not in permission: wrong address', async () => { 30 | const res = await inPermission( 31 | '0xffffffffffffffffffffffffffffffffff020005', 32 | '0xf036ed56', 33 | ); 34 | logger.debug('\nThe result:\n', res); 35 | expect(res).to.equal(false); 36 | }); 37 | 38 | it('test resource not in permission: wrong function', async () => { 39 | const res = await inPermission( 40 | '0xffffffffffffffffffffffffffffffffff020004', 41 | '0xf036ed57', 42 | ); 43 | logger.debug('\nThe result:\n', res); 44 | expect(res).to.equal(false); 45 | }); 46 | 47 | it('test resource not in permission: all wrong', async () => { 48 | const res = await inPermission( 49 | '0xffffffffffffffffffffffffffffffffff020005', 50 | '0xf036ed57', 51 | ); 52 | logger.debug('\nThe result:\n', res); 53 | expect(res).to.equal(false); 54 | }); 55 | }); 56 | -------------------------------------------------------------------------------- /tests/integrate_test/cita_features_test.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -e 3 | 4 | if [[ $(uname) == 'Darwin' ]] 5 | then 6 | SOURCE_DIR=$(realpath "$(dirname "$0")"/../..) 7 | else 8 | SOURCE_DIR=$(readlink -f "$(dirname "$0")"/../..) 9 | fi 10 | BINARY_DIR=${SOURCE_DIR}/target/install 11 | 12 | test_fee_back() { 13 | local version=$1 14 | cd ./scripts/txtool/txtool 15 | python3 "${SOURCE_DIR}"/tests/integrate_test/test_fee_back.py --version="$version" 16 | cd ../../.. 17 | } 18 | 19 | test_perm_denied() { 20 | local version=$1 21 | cd ./scripts/txtool/txtool 22 | python3 "${SOURCE_DIR}"/tests/integrate_test/test_perm_denied.py --version="$version" 23 | cd ../../.. 24 | } 25 | 26 | main() { 27 | echo -n "0) prepare ... " 28 | # shellcheck source=/dev/null 29 | . ${SOURCE_DIR}/tests/integrate_test/util.sh 30 | cd "${BINARY_DIR}" 31 | echo "DONE" 32 | 33 | echo -n "1) generate config ... " 34 | create_config \ 35 | --contract_arguments "SysConfig.checkFeeBackPlatform=true" \ 36 | --contract_arguments "SysConfig.checkCreateContractPermission=true" \ 37 | --contract_arguments "SysConfig.economicalModel=1" \ 38 | --contract_arguments "SysConfig.chainOwner=0x36a60d575b0dee0423abb6a57dbc6ca60bf47545" 39 | echo "DONE" 40 | 41 | echo -n "2) start nodes ... " 42 | start_nodes 43 | echo "DONE" 44 | 45 | echo -n "3) check alive ... " 46 | timeout=$(check_height_growth_normal 0 60) || (echo "FAILED" 47 | echo "failed to check_height_growth 0: ${timeout}" 48 | exit 1) 49 | echo "${timeout}s DONE" 50 | 51 | echo -n "4) Run fee back tests ... " 52 | test_fee_back 2 53 | echo "DONE" 54 | 55 | echo -n "5) Check permission denied ... " 56 | test_perm_denied 2 57 | echo "Done" 58 | } 59 | 60 | main "$@" 61 | -------------------------------------------------------------------------------- /cita-jsonrpc/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "cita-jsonrpc" 3 | version = "0.1.0" 4 | authors = ["Cryptape Technologies "] 5 | edition = "2018" 6 | 7 | [dependencies] 8 | futures = "0.1" 9 | threadpool = "1.7.0" 10 | num_cpus = "1" 11 | uuid = { version = "0.7", features = ["v4"] } 12 | serde = "1.0" 13 | serde_derive = "1.0" 14 | serde_json = "1.0" 15 | cpuprofiler = "0.0.3" 16 | dotenv = "0.13.0" 17 | clap = "2" 18 | cita-logger = "0.1.0" 19 | util = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 20 | error = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 21 | pubsub = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 22 | libproto = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 23 | jsonrpc-types = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 24 | jsonrpc-proto = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 25 | http = "0.1" 26 | httparse = "1.0" 27 | bytes = "0.4" 28 | time = "0.1" 29 | tokio-core = "0.1" 30 | tokio-io = "0.1" 31 | tokio-timer = "0.2" 32 | ws = "0.7" 33 | hyper = "0.12" 34 | net2 = "0.2" 35 | unicase = "2.1.0" 36 | libc = "0.2" 37 | tokio = "0.1.13" 38 | tokio-executor = "0.1.5" 39 | 40 | [build-dependencies] 41 | util = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 42 | 43 | [features] 44 | default = ["secp256k1", "sha3hash", "rabbitmq"] 45 | secp256k1 = ["libproto/secp256k1", "jsonrpc-proto/secp256k1"] 46 | ed25519 = ["libproto/ed25519", "jsonrpc-proto/ed25519"] 47 | sm2 = ["libproto/sm2", "jsonrpc-proto/sm2"] 48 | sha3hash = ["libproto/sha3hash", "jsonrpc-proto/sha3hash"] 49 | blake2bhash = ["libproto/blake2bhash", "jsonrpc-proto/blake2bhash"] 50 | sm3hash = ["libproto/sm3hash", "jsonrpc-proto/sm3hash"] 51 | rabbitmq = ["pubsub/rabbitmq"] 52 | zeromq = ["pubsub/zeromq"] 53 | kafka = ["pubsub/kafka"] 54 | -------------------------------------------------------------------------------- /tools/create-genesis/src/solc.rs: -------------------------------------------------------------------------------- 1 | use json; 2 | use std::collections::BTreeMap; 3 | use std::process::Command; 4 | 5 | pub struct Solc; 6 | 7 | impl Solc { 8 | pub fn get_contracts_data(file_path: String, contract_name: &str) -> BTreeMap { 9 | let output = Command::new("solc") 10 | .arg(file_path.clone()) 11 | .arg("--allow-paths") 12 | .arg(".") 13 | .arg("--optimize") 14 | .arg("--combined-json") 15 | .arg("abi,bin,userdoc,hashes,devdoc") 16 | .output() 17 | .expect("solc command fail to execute"); 18 | let output = String::from_utf8(output.stdout).unwrap(); 19 | let compiled = json::parse(&output).unwrap(); 20 | let index = [&file_path, ":", contract_name].concat(); 21 | 22 | let bin = &compiled["contracts"][&index]["bin"]; 23 | let abi = &compiled["contracts"][&index]["abi"]; 24 | let hashes = &compiled["contracts"][&index]["hashes"]; 25 | let userdoc = &compiled["contracts"][&index]["userdoc"]; 26 | let devdoc = &compiled["contracts"][&index]["devdoc"]; 27 | 28 | let mut data = BTreeMap::new(); 29 | data.insert("bin".to_string(), bin.to_string()); 30 | data.insert("abi".to_string(), abi.to_string()); 31 | data.insert("hashes".to_string(), hashes.to_string()); 32 | data.insert("userdoc".to_string(), userdoc.to_string()); 33 | data.insert("devdoc".to_string(), devdoc.to_string()); 34 | 35 | data 36 | } 37 | 38 | pub fn compiler_version() -> bool { 39 | let output = Command::new("solc") 40 | .arg("--version") 41 | .output() 42 | .expect("solc compiler not exist !"); 43 | println!( 44 | "Solc version: {:?}", 45 | String::from_utf8(output.stdout).unwrap() 46 | ); 47 | output.status.success() 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /cita-network/src/sync_protocol.md: -------------------------------------------------------------------------------- 1 | # 同步协议 2 | 3 | 关键字解释: 4 | * 实现者:指代实现同步协议的结构或者逻辑. 5 | * CITA同步原理:
6 | 举个栗子:
7 | A,B,C,D四个节点,假如全局高度是150,A节点在100时离线,现在A节点重启后,需要同步.
8 | 需要同步块依次是: 101, 102, 103, 104,...149, 150高度块.
9 | 由于共识生成块的各种原因,同步块时需要注意关键点是:同步101时,需要102来推动,而同步102时,需要103来推动,等等依次类推的递归过程.
10 | 而在同步最后一个块时,即150,需要一个高度是std::usize::MAX的虚拟块推动,这些都是同步协议里面实现的.具体见代码.Forward::reply_syn_req方法.
11 | 比较形象描述: "<-" 符号是"推动,验证"的意思.
12 | 即 101 <- 102 <-103 <- 104....149 <- 150 <- std::usize::MAX
13 | 14 | ## 简要说明 15 | 协议的主要是chain的状态进行同步,其它的同步暂时不做考虑,内容有一下: 16 | 17 | 1. 广播状态 18 | 2. 同步请求 19 | 3. 处理请求 20 | 4. 同步状态策略 21 | 5. 分包策略 22 | 6. 排序策略 23 | 7. 同步状态异步化 24 | 8. 丢包\坏包处理 25 | 9. 超时处理 26 | 27 | ## 主要描述实现 28 | 在描述实现之前:请带着以下几个前提问题. 29 | 1. 来自其它节点的状态以及块是不可信的,可是,实现者又不能不去做同步工作,怎么避免这种矛盾问题? 30 | 2. 根据什么条件结束同步? 31 | 3. 如果正在同步中chain或者network断开了怎么办? 32 | 33 | #### 广播状态 34 | 接收自身节点的状态,大于等于之前的状态就要广播,主要是防止攻击. 35 | 36 | #### 同步请求 37 | 发起同步请求的触发时机. 38 | 1. 来自其它节点的状态大于当前节点的状态时,实现者发起同步请求. 39 | 2. 来自自身节点的状态小于其它节点的状态时,实现者发起同步请求. 40 | 41 | 触发结束同步的时机 42 | 1. 就是当前的节点的状态与全局状态一致时,结束同步 43 | 2. 把所有的高度(缓存)到实现者时,结束同步. 44 | 45 | #### 处理请求 46 | 实现者接收同步过来的块,进行拆分包,排序,然后再获取新组K的包发送给当前节点的chain. 47 | 48 | #### 同步状态策略 49 | 同步chain的状态策略:把组好的包K发送给chain后,等待chain的状态(异步实现),如果有组好的包K,再发送给chain,以此循环,来更新chain的状态. 50 | 51 | #### 分包/排序策略 52 | 向其它节点发起同步请求,按迭代步step发起,即step = 20,并且,每一个包的请求是随机向其它节点的任意一个发起. 53 | 由于网络的传输,同步者在得到对应请求的多个应答,先后次序也不一致,因此,我们就需要对接收的块包进行排序. 54 | 在同步者保存好并且排好序的高度块,一次按照step数目,依次再在同步到chain模块. 55 | 56 | 由于chain执行在添加块的时候需要执行交易,所以向其它节点同步过来块的速度大于同步者给chain块的速度. 57 | 58 | #### 同步状态异步化 59 | 发起同步请求与同步高度的逻辑是异步的. 60 | 61 | 可以在一边同步高度时,一边发起同步请求与接收处理同步的块. 62 | 63 | #### 丢包/坏包处理 64 | 如果executor/chain内部校验失败时,直接丢掉整个组包,并广播自己的当前状态,实现者需要记住(当前节点)chain即将要同步的高度,与广播过来的高度是否一致: 65 | 66 | 如果等于,继续获取下个包给chain. 67 | 68 | 如果小于,报错,重新发起同步操作. 69 | 70 | 如果大于,则chain发生丢包,坏包的现象,需要根据当前chain的状态,发起一个step,并覆盖当前的Sync里面的同高度值. 71 | 72 | #### 超时处理 73 | 发起同步请求时超时怎么办?需要什么来打断?怎么打断?怎么重新发起? 74 | 75 | 需要靠下次来一个最新全局状态来打破.即超时机制. 76 | -------------------------------------------------------------------------------- /cita-chain/core/src/libchain/rich_status.rs: -------------------------------------------------------------------------------- 1 | // CITA 2 | // Copyright 2016-2019 Cryptape Technologies LLC. 3 | 4 | // This program is free software: you can redistribute it 5 | // and/or modify it under the terms of the GNU General Public 6 | // License as published by the Free Software Foundation, 7 | // either version 3 of the License, or (at your option) any 8 | // later version. 9 | 10 | // This program is distributed in the hope that it will be 11 | // useful, but WITHOUT ANY WARRANTY; without even the implied 12 | // warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR 13 | // PURPOSE. See the GNU General Public License for more details. 14 | 15 | // You should have received a copy of the GNU General Public License 16 | // along with this program. If not, see . 17 | 18 | use cita_types::{Address, H256}; 19 | use libproto::blockchain::RichStatus as ProtoRichStatus; 20 | 21 | #[derive(PartialEq, Clone, Debug, Default)] 22 | pub struct RichStatus { 23 | number: u64, 24 | hash: H256, 25 | nodes: Vec
, 26 | } 27 | 28 | impl RichStatus { 29 | pub fn hash(&self) -> &H256 { 30 | &self.hash 31 | } 32 | 33 | pub fn number(&self) -> u64 { 34 | self.number 35 | } 36 | 37 | pub fn set_hash(&mut self, h: H256) { 38 | self.hash = h; 39 | } 40 | 41 | pub fn set_number(&mut self, n: u64) { 42 | self.number = n; 43 | } 44 | 45 | pub fn set_nodes(&mut self, nodes: Vec
) { 46 | self.nodes = nodes 47 | } 48 | 49 | pub fn protobuf(&self) -> ProtoRichStatus { 50 | let mut ps = ProtoRichStatus::new(); 51 | ps.set_height(self.number()); 52 | ps.set_hash(self.hash().to_vec()); 53 | ps.set_nodes( 54 | self.nodes 55 | .clone() 56 | .into_iter() 57 | .map(|address| address.to_vec()) 58 | .collect(), 59 | ); 60 | ps 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /cita-chain/types/src/ids.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2015-2017 Parity Technologies (UK) Ltd. 2 | // This file is part of Parity. 3 | 4 | // This software is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | 9 | // This software is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | 14 | // You should have received a copy of the GNU General Public License 15 | // along with Parity. If not, see . 16 | 17 | //! Unique identifiers. 18 | 19 | use crate::BlockNumber; 20 | use cita_types::H256; 21 | use jsonrpc_types::rpc_types::{BlockNumber as RpcBlockNumber, BlockTag}; 22 | 23 | /// Uniquely identifies block. 24 | #[derive(Debug, PartialEq, Copy, Clone, Hash, Eq)] 25 | pub enum BlockId { 26 | /// Block's sha3. 27 | // TODO: Query by number faster 28 | /// Querying by hash is always faster. 29 | Hash(H256), 30 | /// Block number within canon blockchain. 31 | // TODO: Change to Height 32 | Number(BlockNumber), 33 | /// Earliest block (genesis). 34 | Earliest, 35 | /// Latest mined block. 36 | Latest, 37 | /// Pending block. 38 | Pending, 39 | } 40 | 41 | pub type TransactionId = H256; 42 | 43 | impl From for BlockId { 44 | fn from(v: RpcBlockNumber) -> BlockId { 45 | match v { 46 | RpcBlockNumber::Height(height) => BlockId::Number(height.into()), 47 | RpcBlockNumber::Tag(BlockTag::Latest) => BlockId::Latest, 48 | RpcBlockNumber::Tag(BlockTag::Earliest) => BlockId::Earliest, 49 | RpcBlockNumber::Tag(BlockTag::Pending) => BlockId::Pending, 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /cita-executor/core/src/libexecutor/economical_model.rs: -------------------------------------------------------------------------------- 1 | // CITA 2 | // Copyright 2016-2019 Cryptape Technologies LLC. 3 | 4 | // This program is free software: you can redistribute it 5 | // and/or modify it under the terms of the GNU General Public 6 | // License as published by the Free Software Foundation, 7 | // either version 3 of the License, or (at your option) any 8 | // later version. 9 | 10 | // This program is distributed in the hope that it will be 11 | // useful, but WITHOUT ANY WARRANTY; without even the implied 12 | // warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR 13 | // PURPOSE. See the GNU General Public License for more details. 14 | 15 | // You should have received a copy of the GNU General Public License 16 | // along with this program. If not, see . 17 | 18 | use jsonrpc_types::rpc_types::EconomicalModel as RpcEconomicalModel; 19 | 20 | enum_from_primitive! { 21 | #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Copy)] 22 | pub enum EconomicalModel { 23 | /// Default model. Sending Transaction is free, should work with authority together. 24 | Quota, 25 | /// Transaction charges for gas * gasPrice. BlockProposer get the block reward. 26 | Charge, 27 | } 28 | } 29 | 30 | impl Default for EconomicalModel { 31 | fn default() -> Self { 32 | EconomicalModel::Quota 33 | } 34 | } 35 | 36 | impl From for RpcEconomicalModel { 37 | fn from(em: EconomicalModel) -> Self { 38 | match em { 39 | EconomicalModel::Quota => RpcEconomicalModel::Quota, 40 | EconomicalModel::Charge => RpcEconomicalModel::Charge, 41 | } 42 | } 43 | } 44 | 45 | impl Into for RpcEconomicalModel { 46 | fn into(self) -> EconomicalModel { 47 | match self { 48 | RpcEconomicalModel::Quota => EconomicalModel::Quota, 49 | RpcEconomicalModel::Charge => EconomicalModel::Charge, 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /tests/integrate_test/cita_jsonrpc_schema_mock.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | set -e 4 | 5 | ECONOMICAL_MODEL="0" 6 | if [[ -n "$1" ]] && [ "$1" = "charge" ]; then 7 | ECONOMICAL_MODEL="1" 8 | fi 9 | 10 | if [[ $(uname) == 'Darwin' ]] 11 | then 12 | SOURCE_DIR=$(realpath "$(dirname "$0")"/../..) 13 | else 14 | SOURCE_DIR=$(readlink -f "$(dirname "$0")"/../..) 15 | fi 16 | 17 | BINARY_DIR=${SOURCE_DIR}/target/install 18 | CHAIN_NAME="mock-chain" 19 | 20 | main() { 21 | echo -n "0) prepare ... " 22 | cd "${BINARY_DIR}" 23 | echo "DONE" 24 | 25 | echo -n "1) generate config ... " 26 | AUTHORITIES=$(xargs echo < "${SOURCE_DIR}"/tests/interfaces/config/authorities |sed "s/ /,/g") 27 | "${BINARY_DIR}"/scripts/create_cita_config.py create \ 28 | --nodes "127.0.0.1:4000,127.0.0.1:4001,127.0.0.1:4002,127.0.0.1:4003" \ 29 | --chain_name "$CHAIN_NAME" \ 30 | --super_admin "0x4b5ae4567ad5d9fb92bc9afd6a657e6fa13a2523" \ 31 | --contract_arguments "SysConfig.economicalModel=${ECONOMICAL_MODEL}" \ 32 | --contract_arguments "SysConfig.chainId=123" \ 33 | --timestamp 1524000000 \ 34 | --authorities "${AUTHORITIES}" \ 35 | --enable_version 36 | echo "DONE" 37 | 38 | echo -n "2) just start node0 ... " 39 | bin/cita bebop setup "$CHAIN_NAME"/0 > /dev/null 40 | bin/cita bebop start "$CHAIN_NAME"/0 41 | echo "DONE" 42 | 43 | echo -n "3) generate mock data ... " 44 | AMQP_URL=amqp://guest:guest@localhost/"$CHAIN_NAME"/0 \ 45 | "${BINARY_DIR}"/bin/chain-executor-mock \ 46 | -m "${SOURCE_DIR}"/tests/interfaces/config/blockchain.yaml 47 | echo "DONE" 48 | 49 | echo -n "4) check mock data ... " 50 | python3 "${SOURCE_DIR}"/tests/interfaces/rpc_test_runner.py \ 51 | --rpc-url http://127.0.0.1:1337 \ 52 | --directory "${SOURCE_DIR}"/tests/jsondata/rpc/ 53 | echo "DONE" 54 | } 55 | 56 | main "$@" 57 | -------------------------------------------------------------------------------- /scripts/txtool/txtool/log.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # coding=utf-8 3 | 4 | import logging 5 | import logging.config 6 | import re 7 | import yaml 8 | 9 | 10 | def replaceLogRecord(): 11 | """This is a temporary method. 12 | We will remove pyethereum in the near future. 13 | """ 14 | 15 | def makeRecord(self, 16 | name, 17 | level, 18 | fn, 19 | lno, 20 | msg, 21 | args, 22 | exc_info, 23 | func=None, 24 | extra=None, 25 | sinfo=None): 26 | name = re.sub(r'(^|[^a-zA-Z])eth([^a-zA-Z]|$)', r'\1cita\2', name) 27 | rv = logging._logRecordFactory(name, level, fn, lno, msg, args, 28 | exc_info, func, sinfo) 29 | if extra is not None: 30 | for key in extra: 31 | if (key in ["message", "asctime"]) or (key in rv.__dict__): 32 | raise KeyError( 33 | "Attempt to overwrite %r in LogRecord" % key) 34 | rv.__dict__[key] = extra[key] 35 | return rv 36 | 37 | def getMessage(self): 38 | msg = str(self.msg) 39 | if self.args: 40 | msg = msg % self.args 41 | msg = re.sub(r'(^|[^a-zA-Z])eth([^a-zA-Z]|$)', r'\1cita\2', msg) 42 | msg = re.sub(r'(^|[^a-zA-Z])gas([^a-zA-Z]|$)', r'\1quota\2', msg) 43 | return msg 44 | 45 | logging.Logger.makeRecord = makeRecord 46 | logging.LogRecord.getMessage = getMessage 47 | 48 | 49 | replaceLogRecord() 50 | 51 | with open('config/logging.yml', 'r') as f_conf: 52 | dict_conf = yaml.load(f_conf) 53 | 54 | logging.config.dictConfig(dict_conf) 55 | 56 | logger = logging.getLogger('info') 57 | 58 | # logger.debug('debug test message') 59 | # logger.info('info test message') 60 | # logger.warn('warn test message') 61 | # logger.error('error test message') 62 | # logger.critical('critical test message') 63 | -------------------------------------------------------------------------------- /tests/integrate_test/test_fee_back.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """ 3 | Test case of fee back to operator in charge economical mode. 4 | """ 5 | 6 | import argparse 7 | from txtool_utils import get_receipt, rpc_request, send_tx, get_balance 8 | 9 | DEFAULT_QUOTA_PRICE = 1000000 10 | 11 | 12 | def main(): 13 | """ Run the test. """ 14 | admin_privkey = '0x5f0258a4778057a8a7d97809bd209055b2fbafa654ce7d31ec7191066b9225e6' 15 | operator_address = '0x36a60d575b0dee0423abb6a57dbc6ca60bf47545' 16 | code = '0x606060405260008055341561001357600080fd5b60f2806100216000396000f3006060604052600436106053576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff1680634f2be91f1460585780636d4ce63c14606a578063d826f88f146090575b600080fd5b3415606257600080fd5b606860a2565b005b3415607457600080fd5b607a60b4565b6040518082815260200191505060405180910390f35b3415609a57600080fd5b60a060bd565b005b60016000808282540192505081905550565b60008054905090565b600080819055505600a165627a7a72305820906dc3fa7444ee6bea2e59c94fe33064e84166909760c82401f65dfecbd307d50029' 17 | 18 | opts = parse_arguments() 19 | version = opts.version 20 | 21 | operator_balance_old = get_balance(operator_address) 22 | tx_hash = send_tx(admin_privkey, code=code, version=version) 23 | receipt = get_receipt(tx_hash) 24 | operator_balance_new = get_balance(operator_address) 25 | print('[operator.address]:{}'.format(operator_address)) 26 | print('[operator.balance old]:{}'.format(operator_balance_old)) 27 | print('[operator.balance]:{}'.format(operator_balance_new)) 28 | print('[quotaUsed]:{}'.format(receipt['quotaUsed'])) 29 | assert operator_balance_new - operator_balance_old == int( 30 | receipt['quotaUsed'], 16) * DEFAULT_QUOTA_PRICE 31 | 32 | print('>>> Test fee back successfully!') 33 | 34 | 35 | def parse_arguments(): 36 | parser = argparse.ArgumentParser() 37 | parser.add_argument("--version", help="Tansaction version.", type=int) 38 | 39 | return parser.parse_args() 40 | 41 | 42 | if __name__ == '__main__': 43 | main() 44 | -------------------------------------------------------------------------------- /cita-chain/types/src/basic_account.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2015-2017 Parity Technologies (UK) Ltd. 2 | // This file is part of Parity. 3 | 4 | // This software is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | 9 | // This software is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | 14 | // You should have received a copy of the GNU General Public License 15 | // along with Parity. If not, see . 16 | 17 | //! Basic account type -- the decoded RLP from the state trie. 18 | 19 | use cita_types::{H256, U256}; 20 | use rlp::*; 21 | 22 | /// Basic account type. 23 | #[derive(Debug, Clone, PartialEq, Eq)] 24 | pub struct BasicAccount { 25 | /// Nonce of the account. 26 | pub nonce: U256, 27 | /// Balance of the account. 28 | pub balance: U256, 29 | /// Storage root of the account. 30 | pub storage_root: H256, 31 | /// Code hash of the account. 32 | pub code_hash: H256, 33 | /// ABI hash of the account. 34 | pub abi_hash: H256, 35 | } 36 | 37 | impl Encodable for BasicAccount { 38 | fn rlp_append(&self, s: &mut RlpStream) { 39 | s.begin_list(5) 40 | .append(&self.nonce) 41 | .append(&self.balance) 42 | .append(&self.storage_root) 43 | .append(&self.code_hash) 44 | .append(&self.abi_hash); 45 | } 46 | } 47 | 48 | impl Decodable for BasicAccount { 49 | fn decode(rlp: &UntrustedRlp) -> Result { 50 | Ok(BasicAccount { 51 | nonce: rlp.val_at(0)?, 52 | balance: rlp.val_at(1)?, 53 | storage_root: rlp.val_at(2)?, 54 | code_hash: rlp.val_at(3)?, 55 | abi_hash: rlp.val_at(4)?, 56 | }) 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /tools/create-genesis/src/miner.rs: -------------------------------------------------------------------------------- 1 | use crate::common::{get_temp_state, secret_2_address, string_2_bytes, string_2_u256}; 2 | use crate::genesis::Account; 3 | use core_executor::engines::NullEngine; 4 | use core_executor::executive::contract_address; 5 | use core_executor::libexecutor::sys_config::BlockSysConfig; 6 | use core_executor::types::transaction::Transaction; 7 | use evm::cita_types::U256; 8 | use evm::env_info::EnvInfo; 9 | use libproto::blockchain::Transaction as ProtoTransaction; 10 | 11 | pub struct Miner; 12 | 13 | impl Miner { 14 | pub fn mine(code: Vec) -> Account { 15 | let mut state = get_temp_state(); 16 | 17 | // Create a transaction 18 | let mut proto_tx = ProtoTransaction::new(); 19 | proto_tx.set_data(code); 20 | proto_tx.set_value(string_2_bytes(String::from("0x00"))); 21 | proto_tx.set_nonce("0x00".to_string()); 22 | proto_tx.set_quota(string_2_u256(String::from("0x99999999999")).low_u64()); 23 | 24 | let private_key = 25 | String::from("0x5f0258a4778057a8a7d97809bd209055b2fbafa654ce7d31ec7191066b9225e6"); 26 | let tx = Transaction::create(&proto_tx).unwrap(); 27 | let sender = secret_2_address(&private_key); 28 | let signed_transaction = tx.fake_sign(sender); 29 | 30 | let env_info = EnvInfo::default(); 31 | let engine = NullEngine::cita(); 32 | let config = BlockSysConfig::default(); 33 | 34 | // Cal contract address 35 | let contract_address = contract_address(&sender, &U256::from(0)); 36 | // Apply tx and commit to state 37 | let _ = state.apply(&env_info, &engine, &signed_transaction, false, &config); 38 | state.commit().unwrap(); 39 | 40 | // Get account content according to contract address 41 | let account = state.account(&contract_address).unwrap().unwrap(); 42 | let code = account.code().unwrap(); 43 | 44 | Account { 45 | nonce: *account.nonce(), 46 | code: String::from("0x") + &hex::encode(code.to_vec()), 47 | storage: account.storage_cache(), 48 | value: *account.balance(), 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /scripts/release.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | if [[ $(uname) == 'Darwin' ]] 4 | then 5 | SOURCE_DIR=$(realpath "$(dirname "$(realpath "$0")")"/..) 6 | else 7 | SOURCE_DIR=$(readlink -f "$(dirname "$(realpath "$0")")"/..) 8 | fi 9 | 10 | cd "${SOURCE_DIR}" || exit 11 | 12 | if [ $# -ne 1 ] ; then 13 | echo "usage: $0 debug|release" 14 | exit 1 15 | fi 16 | 17 | type=$1 18 | 19 | # 0) setup 20 | mkdir -p target/install/scripts/ 21 | mkdir -p target/install/bin/ 22 | mkdir -p target/install/resource/ 23 | 24 | # 1) binary 25 | for binary in \ 26 | cita-auth \ 27 | cita-bft \ 28 | cita-chain \ 29 | cita-executor \ 30 | cita-forever \ 31 | cita-jsonrpc \ 32 | cita-network \ 33 | create-key-addr \ 34 | create-genesis \ 35 | cita-relayer-parser \ 36 | snapshot-tool \ 37 | consensus-mock \ 38 | chain-executor-mock \ 39 | box-executor \ 40 | ; do 41 | cp -rf "target/${type}/${binary}" target/install/bin/ 42 | done 43 | #strip target/install/bin/* 44 | 45 | # 2) cita 46 | cp -rf scripts/cita.sh target/install/bin/cita 47 | 48 | # 3) contract 49 | cp -rf scripts/contracts target/install/scripts/ 50 | 51 | # 4) config tool 52 | cp -rf scripts/config_tool target/install/scripts/ 53 | cp -f scripts/create_cita_config.py target/install/scripts/ 54 | 55 | # 5) txtool 56 | cp -rf scripts/txtool target/install/scripts/ 57 | 58 | # 6) docker env 59 | cp -f env.sh target/install/bin/cita-env 60 | cp -f scripts/cita_config.sh target/install/bin/cita-config 61 | 62 | # 7) amend info of system contract 63 | cp -f scripts/amend_system_contracts.sh target/install/scripts/ 64 | cp -f scripts/amend_system_contracts.py target/install/scripts/ 65 | 66 | # 8) delete building container 67 | docker container stop cita_build_container > /dev/null 2>&1 68 | docker container rm cita_build_container > /dev/null 2>&1 69 | 70 | exit 0 71 | -------------------------------------------------------------------------------- /scripts/contracts/tests/test/helpers/group_management.js: -------------------------------------------------------------------------------- 1 | const fs = require('fs'); 2 | const util = require('./util'); 3 | const config = require('../config'); 4 | 5 | const { genContract, genTxParams } = util; 6 | 7 | const { superAdmin } = config; 8 | const { groupManagement } = config.contract; 9 | const abi = JSON.parse(fs.readFileSync('../interaction/abi/GroupManagement.abi')); 10 | 11 | const contract = genContract(abi, groupManagement); 12 | 13 | // newPermission 14 | const newGroup = async (origin, name, accounts, _sender = superAdmin) => { 15 | const param = await genTxParams(_sender); 16 | return contract.methods.newGroup( 17 | origin, 18 | name, 19 | accounts, 20 | ).send(param); 21 | }; 22 | 23 | // deleteGroup 24 | const deleteGroup = async (origin, target, _sender = superAdmin) => { 25 | const param = await genTxParams(_sender); 26 | return contract.methods.deleteGroup( 27 | origin, 28 | target, 29 | ).send(param); 30 | }; 31 | 32 | // updateGroupName 33 | const updateGroupName = async (origin, target, name, _sender = superAdmin) => { 34 | const param = await genTxParams(_sender); 35 | return contract.methods.updateGroupName( 36 | origin, 37 | target, 38 | name, 39 | ).send(param); 40 | }; 41 | 42 | // addAccounts 43 | const addAccounts = async (origin, target, accounts, _sender = superAdmin) => { 44 | const param = await genTxParams(_sender); 45 | return contract.methods.addAccounts( 46 | origin, 47 | target, 48 | accounts, 49 | ).send(param); 50 | }; 51 | 52 | // deleteAccounts 53 | const deleteAccounts = async (origin, target, accounts, _sender = superAdmin) => { 54 | const param = await genTxParams(_sender); 55 | return contract.methods.deleteAccounts( 56 | origin, 57 | target, 58 | accounts, 59 | ).send(param); 60 | }; 61 | 62 | // checkScope 63 | const checkScope = async (origin, target) => contract.methods.checkScope(origin, target).call('pending'); 64 | 65 | // queryGroups 66 | const queryGroups = () => contract.methods.queryGroups().call('pending'); 67 | 68 | module.exports = { 69 | newGroup, 70 | updateGroupName, 71 | addAccounts, 72 | deleteAccounts, 73 | deleteGroup, 74 | checkScope, 75 | queryGroups, 76 | }; 77 | -------------------------------------------------------------------------------- /cita-executor/evm/src/return_data.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2015-2017 Parity Technologies (UK) Ltd. 2 | // This file is part of Parity. 3 | 4 | // This software is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | 9 | // This software is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | 14 | // You should have received a copy of the GNU General Public License 15 | // along with Parity. If not, see . 16 | 17 | //! Evm interface. 18 | 19 | use cita_types::U256; 20 | 21 | /// Return data buffer. Holds memory from a previous call and a slice into that memory. 22 | #[derive(Debug)] 23 | pub struct ReturnData { 24 | mem: Vec, 25 | offset: usize, 26 | size: usize, 27 | } 28 | 29 | impl ::std::ops::Deref for ReturnData { 30 | type Target = [u8]; 31 | fn deref(&self) -> &[u8] { 32 | &self.mem[self.offset..self.offset + self.size] 33 | } 34 | } 35 | 36 | impl ReturnData { 37 | /// Create empty `ReturnData`. 38 | pub fn empty() -> Self { 39 | ReturnData { 40 | mem: Vec::new(), 41 | offset: 0, 42 | size: 0, 43 | } 44 | } 45 | /// Create `ReturnData` from give buffer and slice. 46 | pub fn new(mem: Vec, offset: usize, size: usize) -> Self { 47 | ReturnData { mem, offset, size } 48 | } 49 | } 50 | 51 | /// Gas Left: either it is a known value, or it needs to be computed by processing 52 | /// a return instruction. 53 | #[derive(Debug)] 54 | pub enum GasLeft { 55 | /// Known gas left 56 | Known(U256), 57 | /// Return or Revert instruction must be processed. 58 | NeedsReturn { 59 | /// Amount of gas left. 60 | gas_left: U256, 61 | /// Return data buffer. 62 | data: ReturnData, 63 | /// Apply or revert state changes on revert. 64 | apply_state: bool, 65 | }, 66 | } 67 | -------------------------------------------------------------------------------- /cita-auth/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "cita-auth" 3 | version = "0.1.0" 4 | authors = ["Cryptape Technologies "] 5 | edition = "2018" 6 | 7 | [dependencies] 8 | clap = "2" 9 | dotenv = "0.13.0" 10 | cpuprofiler = "0.0.3" 11 | serde = "1.0" 12 | serde_derive = "1.0" 13 | serde_json = "1.0" 14 | cita-logger = "0.1.0" 15 | cita-types = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 16 | cita-directories = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 17 | util = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 18 | error = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 19 | pubsub = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 20 | libproto = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 21 | cita-crypto = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 22 | tx_pool = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 23 | jsonrpc-types = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 24 | core = { path = "../cita-chain/core" } 25 | uuid = { version = "0.7", features = ["v4"] } 26 | lru = "0.1" 27 | rayon = "1.0" 28 | hashable = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 29 | db = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 30 | evm = {path = "../cita-executor/evm"} 31 | 32 | [dev-dependencies] 33 | tempfile = "2" 34 | tempdir = "0.3.7" 35 | quickcheck = "0.7.2" 36 | 37 | [build-dependencies] 38 | util = { git = "https://github.com/cryptape/cita-common.git", branch = "develop" } 39 | 40 | [features] 41 | default = ["secp256k1", "sha3hash", "rabbitmq"] 42 | secp256k1 = ["cita-crypto/secp256k1", "libproto/secp256k1", "tx_pool/secp256k1"] 43 | ed25519 = ["cita-crypto/ed25519", "libproto/ed25519", "tx_pool/ed25519"] 44 | sm2 = ["cita-crypto/sm2", "libproto/sm2", "tx_pool/sm2"] 45 | sha3hash = ["libproto/sha3hash", "db/sha3hash", "tx_pool/sha3hash"] 46 | blake2bhash = ["libproto/blake2bhash", "db/blake2bhash", "tx_pool/blake2bhash"] 47 | sm3hash = ["libproto/sm3hash", "db/sm3hash", "tx_pool/sm3hash"] 48 | rabbitmq = ["pubsub/rabbitmq"] 49 | zeromq = ["pubsub/zeromq"] 50 | kafka = ["pubsub/kafka"] 51 | -------------------------------------------------------------------------------- /tests/json-test/src/helper.rs: -------------------------------------------------------------------------------- 1 | use core_executor::cita_db::{journaldb, kvdb, KeyValueDB}; 2 | use core_executor::db; 3 | use core_executor::state::State; 4 | use core_executor::state_db::StateDB; 5 | use ethereum_types::Public; 6 | use evm::cita_types::{Address, H256, U256}; 7 | use std::sync::Arc; 8 | 9 | pub fn clean_0x(s: &str) -> &str { 10 | if s.starts_with("0x") { 11 | &s[2..] 12 | } else { 13 | s 14 | } 15 | } 16 | 17 | pub fn string_2_u256(value: String) -> U256 { 18 | let v = Box::leak(value.into_boxed_str()); 19 | let v = clean_0x(v); 20 | U256::from(v) 21 | } 22 | 23 | pub fn string_2_h256(value: String) -> H256 { 24 | let v = Box::leak(value.into_boxed_str()); 25 | let v = clean_0x(v); 26 | if v.len() < 64 { 27 | let mut s = String::from("0").repeat(64 - v.len()); 28 | s.push_str(v); 29 | let s: &'static str = Box::leak(s.into_boxed_str()); 30 | return H256::from(s); 31 | } 32 | H256::from(v) 33 | } 34 | 35 | pub fn string_2_bytes(value: String) -> Vec { 36 | let v = Box::leak(value.into_boxed_str()); 37 | let v = clean_0x(v); 38 | hex::decode(v).unwrap() 39 | } 40 | 41 | pub fn public_2_address(public: &Public) -> Address { 42 | let hash = tiny_keccak::keccak256(&public.0); 43 | let mut result = Address::default(); 44 | result.copy_from_slice(&hash[12..]); 45 | result 46 | } 47 | 48 | pub fn secret_2_address(secret: &str) -> Address { 49 | let a = hex::decode(clean_0x(secret)).unwrap(); 50 | let secret_key = secp256k1::SecretKey::parse_slice(a.as_slice()).unwrap(); 51 | let public_key = secp256k1::PublicKey::from_secret_key(&secret_key); 52 | let serialized = public_key.serialize(); 53 | let mut public = Public::default(); 54 | public.copy_from_slice(&serialized[1..65]); 55 | public_2_address(&public) 56 | } 57 | 58 | pub fn get_temp_state() -> State { 59 | let state_db = get_temp_state_db(); 60 | State::new(state_db, 0.into(), Default::default()) 61 | } 62 | 63 | pub fn new_db() -> Arc { 64 | Arc::new(kvdb::in_memory(8)) 65 | } 66 | 67 | pub fn get_temp_state_db() -> StateDB { 68 | let db = new_db(); 69 | let journal_db = journaldb::new(db, journaldb::Algorithm::Archive, db::COL_STATE); 70 | StateDB::new(journal_db, 5 * 1024 * 1024) 71 | } 72 | -------------------------------------------------------------------------------- /cita-chain/types/src/log_blooms.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2015-2017 Parity Technologies (UK) Ltd. 2 | // This file is part of Parity. 3 | 4 | // This software is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | 9 | // This software is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | 14 | // You should have received a copy of the GNU General Public License 15 | // along with Parity. If not, see . 16 | 17 | //! Bridge between bloomchain crate types and cita LogBloom. 18 | 19 | use crate::log_entry::LogBloom; 20 | use bloomchain::group::BloomGroup; 21 | use bloomchain::Bloom; 22 | use rlp::*; 23 | use util::HeapSizeOf; 24 | 25 | /// Represents group of X consecutive blooms. 26 | #[derive(Debug, Clone)] 27 | pub struct LogBloomGroup { 28 | blooms: Vec, 29 | } 30 | 31 | impl From for LogBloomGroup { 32 | fn from(group: BloomGroup) -> Self { 33 | let blooms = group 34 | .blooms 35 | .into_iter() 36 | .map(|x| LogBloom::from(Into::<[u8; 256]>::into(x))) 37 | .collect(); 38 | LogBloomGroup { blooms } 39 | } 40 | } 41 | 42 | impl Into for LogBloomGroup { 43 | fn into(self) -> BloomGroup { 44 | let blooms = self 45 | .blooms 46 | .into_iter() 47 | .map(|x| Bloom::from(Into::<[u8; 256]>::into(x))) 48 | .collect(); 49 | BloomGroup { blooms } 50 | } 51 | } 52 | 53 | impl Decodable for LogBloomGroup { 54 | fn decode(rlp: &UntrustedRlp) -> Result { 55 | let blooms = rlp.as_list()?; 56 | let group = LogBloomGroup { blooms }; 57 | Ok(group) 58 | } 59 | } 60 | 61 | impl Encodable for LogBloomGroup { 62 | fn rlp_append(&self, s: &mut RlpStream) { 63 | s.append_list(&self.blooms); 64 | } 65 | } 66 | 67 | impl HeapSizeOf for LogBloomGroup { 68 | fn heap_size_of_children(&self) -> usize { 69 | 0 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /tools/create-key-addr/src/main.rs: -------------------------------------------------------------------------------- 1 | // CITA 2 | // Copyright 2016-2019 Cryptape Technologies LLC. 3 | 4 | // This program is free software: you can redistribute it 5 | // and/or modify it under the terms of the GNU General Public 6 | // License as published by the Free Software Foundation, 7 | // either version 3 of the License, or (at your option) any 8 | // later version. 9 | 10 | // This program is distributed in the hope that it will be 11 | // useful, but WITHOUT ANY WARRANTY; without even the implied 12 | // warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR 13 | // PURPOSE. See the GNU General Public License for more details. 14 | 15 | // You should have received a copy of the GNU General Public License 16 | // along with this program. If not, see . 17 | 18 | extern crate cita_crypto as crypto; 19 | 20 | use crate::crypto::{CreateKey, KeyPair, PubKey}; 21 | use hashable::Hashable; 22 | use std::env; 23 | use std::fs::{File, OpenOptions}; 24 | use std::io::Write; 25 | 26 | fn to_hex_string(data: &[u8]) -> String { 27 | let strs: Vec = data.iter().map(|a| format!("{:02x}", a)).collect(); 28 | strs.join("") 29 | } 30 | 31 | fn write_to_file(path: String, data: &str, append: bool) { 32 | let mut file = if append { 33 | OpenOptions::new() 34 | .create(true) 35 | .append(true) 36 | .open(path) 37 | .unwrap() 38 | } else { 39 | File::create(path).unwrap() 40 | }; 41 | write!(&mut file, "{}", data).unwrap(); 42 | } 43 | 44 | fn create_key(path: String) -> PubKey { 45 | let keypair = KeyPair::gen_keypair(); 46 | let privkey = *keypair.privkey(); 47 | let hex_str = to_hex_string(&privkey); 48 | let hex_str_with_0x = String::from("0x") + &hex_str + "\n"; 49 | write_to_file(path, &hex_str_with_0x, false); 50 | *keypair.pubkey() 51 | } 52 | 53 | fn create_addr(path: String, pubkey: PubKey) { 54 | let hash = pubkey.crypt_hash(); 55 | let addr = &hash.0[12..]; 56 | let hex_str = to_hex_string(addr); 57 | let hex_str_with_0x = String::from("0x") + &hex_str + "\n"; 58 | write_to_file(path, &hex_str_with_0x, true); 59 | } 60 | 61 | fn main() { 62 | let mut args = env::args(); 63 | let _ = args.next().unwrap(); 64 | let pubkey = create_key(args.next().unwrap()); 65 | create_addr(args.next().unwrap(), pubkey); 66 | } 67 | -------------------------------------------------------------------------------- /tools/relayer-parser/src/configuration.rs: -------------------------------------------------------------------------------- 1 | // CITA 2 | // Copyright 2016-2019 Cryptape Technologies LLC. 3 | 4 | // This program is free software: you can redistribute it 5 | // and/or modify it under the terms of the GNU General Public 6 | // License as published by the Free Software Foundation, 7 | // either version 3 of the License, or (at your option) any 8 | // later version. 9 | 10 | // This program is distributed in the hope that it will be 11 | // useful, but WITHOUT ANY WARRANTY; without even the implied 12 | // warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR 13 | // PURPOSE. See the GNU General Public License for more details. 14 | 15 | // You should have received a copy of the GNU General Public License 16 | // along with this program. If not, see . 17 | 18 | use cita_crypto::PrivKey; 19 | use cita_types::U256; 20 | use serde_json; 21 | use std::collections::HashMap; 22 | use std::time::Duration; 23 | 24 | #[derive(Debug, Deserialize, Clone)] 25 | pub struct UpStream { 26 | pub url: String, 27 | pub timeout: Duration, 28 | } 29 | 30 | #[derive(Debug, Deserialize, Clone)] 31 | struct Chain { 32 | pub id: U256, 33 | pub servers: Vec, 34 | } 35 | 36 | #[derive(Debug, Deserialize, Clone)] 37 | struct FileConfig { 38 | pub private_key: PrivKey, 39 | pub chains: Vec, 40 | } 41 | 42 | #[derive(Debug, Clone)] 43 | pub struct Config { 44 | pkey: PrivKey, 45 | servers: HashMap>, 46 | } 47 | 48 | impl FileConfig { 49 | fn load(path: &str) -> Self { 50 | let file = ::std::fs::File::open(path).expect("open config file failed"); 51 | let reader = ::std::io::BufReader::new(file); 52 | serde_json::from_reader(reader).expect("serde_json::from_reader failed") 53 | } 54 | } 55 | 56 | impl Config { 57 | #[inline] 58 | pub fn get_servers(&self, chain_id: U256) -> Option<&Vec> { 59 | self.servers.get(&chain_id) 60 | } 61 | #[inline] 62 | pub fn get_private_key(&self) -> &PrivKey { 63 | &self.pkey 64 | } 65 | } 66 | 67 | pub fn parse_configfile(path: &str) -> Config { 68 | let config = FileConfig::load(path); 69 | let pkey = config.private_key; 70 | let servers = config 71 | .chains 72 | .into_iter() 73 | .map(|c| (c.id, c.servers)) 74 | .collect(); 75 | Config { pkey, servers } 76 | } 77 | -------------------------------------------------------------------------------- /cita-executor/core/src/contracts/solc/admin.rs: -------------------------------------------------------------------------------- 1 | // CITA 2 | // Copyright 2016-2019 Cryptape Technologies LLC. 3 | 4 | // This program is free software: you can redistribute it 5 | // and/or modify it under the terms of the GNU General Public 6 | // License as published by the Free Software Foundation, 7 | // either version 3 of the License, or (at your option) any 8 | // later version. 9 | 10 | // This program is distributed in the hope that it will be 11 | // useful, but WITHOUT ANY WARRANTY; without even the implied 12 | // warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR 13 | // PURPOSE. See the GNU General Public License for more details. 14 | 15 | // You should have received a copy of the GNU General Public License 16 | // along with this program. If not, see . 17 | 18 | //! Get Admin Info 19 | 20 | use super::ContractCallExt; 21 | use crate::contracts::tools::{decode as decode_tools, method as method_tools}; 22 | use crate::libexecutor::executor::Executor; 23 | use crate::types::ids::BlockId; 24 | use crate::types::reserved_addresses; 25 | use cita_types::Address; 26 | use std::str::FromStr; 27 | 28 | lazy_static! { 29 | static ref GET_ADMIN: Vec = method_tools::encode_to_vec(b"admin()"); 30 | static ref CONTRACT_ADDRESS: Address = Address::from_str(reserved_addresses::ADMIN).unwrap(); 31 | } 32 | 33 | pub struct Admin<'a> { 34 | executor: &'a Executor, 35 | } 36 | 37 | impl<'a> Admin<'a> { 38 | pub fn new(executor: &'a Executor) -> Self { 39 | Admin { executor } 40 | } 41 | 42 | /// Get Admin 43 | pub fn get_admin(&self, block_id: BlockId) -> Option
{ 44 | self.executor 45 | .call_method(&*CONTRACT_ADDRESS, &*GET_ADMIN.as_slice(), None, block_id) 46 | .ok() 47 | .and_then(|output| decode_tools::to_address(&output)) 48 | } 49 | } 50 | 51 | #[cfg(test)] 52 | mod tests { 53 | use super::Admin; 54 | use crate::tests::helpers::init_executor; 55 | use crate::types::ids::BlockId; 56 | use cita_types::Address; 57 | 58 | #[test] 59 | fn test_admin() { 60 | let executor = init_executor(); 61 | let admin = Admin::new(&executor); 62 | let addr = admin.get_admin(BlockId::Pending).unwrap(); 63 | assert_eq!( 64 | addr, 65 | Address::from("0x4b5ae4567ad5d9fb92bc9afd6a657e6fa13a2523") 66 | ); 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /scripts/txtool/txtool/send_tx.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # coding=utf-8 3 | 4 | from __future__ import print_function 5 | import argparse 6 | from pathlib import Path 7 | from log import logger 8 | from jsonrpcclient.http_client import HTTPClient 9 | from url_util import endpoint 10 | from util import findDict, run_command 11 | 12 | 13 | def save_transaction_hash(tx_hash): 14 | deployfile = open("../output/transaction/hash", "w+") 15 | deployfile.write(tx_hash) 16 | deployfile.close() 17 | 18 | 19 | def get_deploy_code(): 20 | with open("../output/transaction/deploycode", 'r') as deployfile: 21 | code = deployfile.read() 22 | return code 23 | 24 | 25 | def send_transaction(params): 26 | if params is not None \ 27 | and (len(params) < 2 or params[:2].lower() != '0x'): 28 | params = '0x' + params 29 | try: 30 | url = endpoint() 31 | response = HTTPClient(url).request("sendRawTransaction", params) 32 | except Exception as e: 33 | logger.error(e) 34 | return None 35 | 36 | return response 37 | 38 | 39 | def send_txs(params): 40 | try: 41 | for item in params: 42 | response = send_transaction(item) 43 | except: 44 | return None 45 | 46 | return response 47 | 48 | 49 | def parse_arguments(): 50 | args = None 51 | parser = argparse.ArgumentParser() 52 | parser.add_argument('--codes', nargs="+", help="send transaction params.") 53 | opts = parser.parse_args() 54 | if opts.codes: 55 | args = opts.codes 56 | 57 | return args 58 | 59 | 60 | def main(): 61 | compile_path = Path("../output/transaction") 62 | if not compile_path.is_dir(): 63 | command = 'mkdir -p ../output/transaction'.split() 64 | for line in run_command(command): 65 | logger.debug(line) 66 | 67 | params = parse_arguments() 68 | if params is None: 69 | params = get_deploy_code() 70 | resp = send_transaction(params) 71 | elif isinstance(params, list) and len(params) > 1: 72 | resp = send_txs(params) 73 | else: 74 | resp = send_transaction(params) 75 | 76 | logger.info("transaction hash is stored in../output/transaction/hash") 77 | if resp is not None: 78 | tx_hash = findDict(resp, 'hash') 79 | save_transaction_hash(tx_hash) 80 | 81 | 82 | if __name__ == "__main__": 83 | main() 84 | -------------------------------------------------------------------------------- /tools/relayer-parser/src/transaction.rs: -------------------------------------------------------------------------------- 1 | // CITA 2 | // Copyright 2016-2019 Cryptape Technologies LLC. 3 | 4 | // This program is free software: you can redistribute it 5 | // and/or modify it under the terms of the GNU General Public 6 | // License as published by the Free Software Foundation, 7 | // either version 3 of the License, or (at your option) any 8 | // later version. 9 | 10 | // This program is distributed in the hope that it will be 11 | // useful, but WITHOUT ANY WARRANTY; without even the implied 12 | // warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR 13 | // PURPOSE. See the GNU General Public License for more details. 14 | 15 | // You should have received a copy of the GNU General Public License 16 | // along with this program. If not, see . 17 | 18 | use ethabi; 19 | 20 | use cita_crypto::PrivKey; 21 | use cita_types::{H160, H256, U256}; 22 | use libproto::blockchain::{Transaction, UnverifiedTransaction}; 23 | 24 | pub fn construct_transaction( 25 | pkey: &PrivKey, 26 | tx_proof_rlp: &[u8], 27 | dest_hasher: [u8; 4], 28 | dest_contract: H160, 29 | chain_id: U256, 30 | height: U256, 31 | ) -> UnverifiedTransaction { 32 | let code = encode(dest_hasher, tx_proof_rlp); 33 | sign(pkey, dest_contract, code, chain_id, height) 34 | } 35 | 36 | #[inline] 37 | fn encode(dest_hasher: [u8; 4], tx_proof_rlp: &[u8]) -> Vec { 38 | trace!("encode dest_hasher {:?}", dest_hasher); 39 | trace!("encode proof_len {:?}", tx_proof_rlp.len()); 40 | trace!("encode proof_data {:?}", tx_proof_rlp); 41 | let encoded = ethabi::encode(&[ethabi::Token::Bytes(tx_proof_rlp.to_vec())]); 42 | let ret = Vec::from(&dest_hasher[..]) 43 | .into_iter() 44 | .chain(encoded.into_iter()) 45 | .collect(); 46 | trace!("encode result {:?}", ret); 47 | ret 48 | } 49 | 50 | #[inline] 51 | fn sign( 52 | pkey: &PrivKey, 53 | addr: H160, 54 | code: Vec, 55 | chain_id: U256, 56 | height: U256, 57 | ) -> UnverifiedTransaction { 58 | let mut tx = Transaction::new(); 59 | tx.set_data(code); 60 | tx.set_to_v1(addr.to_vec()); 61 | tx.set_valid_until_block(height.low_u64() + 100); 62 | tx.set_quota(1_000_000); 63 | tx.set_chain_id_v1(H256::from(chain_id).to_vec()); 64 | tx.set_version(2); 65 | tx.set_value(vec![0u8; 32]); 66 | tx.sign(*pkey).take_transaction_with_sig() 67 | } 68 | --------------------------------------------------------------------------------