├── .dockerignore ├── .editorconfig ├── .github └── workflows │ └── build-and-test.yml ├── .gitignore ├── .maintain └── frame-weight-template.hbs ├── Cargo.lock ├── Cargo.toml ├── Host ├── LICENSE ├── Makefile ├── README.md ├── crates ├── bloom-filter │ ├── Cargo.toml │ └── src │ │ └── lib.rs ├── ces-allocator │ ├── .rustfmt.toml │ ├── Cargo.toml │ └── src │ │ └── lib.rs ├── ces-crypto │ ├── .rustfmt.toml │ ├── Cargo.toml │ └── src │ │ ├── aead.rs │ │ ├── aead │ │ └── stream.rs │ │ ├── ecdh.rs │ │ ├── key_share.rs │ │ ├── lib.rs │ │ ├── rsa.rs │ │ └── sr25519.rs ├── ces-mq │ ├── .rustfmt.toml │ ├── Cargo.toml │ ├── src │ │ ├── checkpoint_helper.rs │ │ ├── dispatcher.rs │ │ ├── lib.rs │ │ ├── send_queue.rs │ │ ├── signer │ │ │ └── mod.rs │ │ ├── simple_mpsc.rs │ │ └── types.rs │ └── tests │ │ └── tests.rs ├── ces-node-rpc-ext │ ├── .rustfmt.toml │ ├── Cargo.toml │ ├── src │ │ ├── lib.rs │ │ ├── mq_seq.rs │ │ └── storage_changes.rs │ └── types │ │ ├── Cargo.toml │ │ └── src │ │ └── lib.rs ├── ces-pdp │ ├── .rustfmt.toml │ ├── Cargo.toml │ └── src │ │ └── lib.rs ├── ces-pois │ ├── .rustfmt.toml │ ├── Cargo.toml │ └── src │ │ ├── acc │ │ ├── file_manager.rs │ │ ├── hash_2_prime.rs │ │ ├── mod.rs │ │ └── multi_level_acc.rs │ │ ├── expanders │ │ ├── generate_expanders.rs │ │ ├── generate_idle_file.rs │ │ └── mod.rs │ │ ├── lib.rs │ │ ├── pois │ │ ├── challenge.rs │ │ ├── mod.rs │ │ ├── prove.rs │ │ └── verify.rs │ │ ├── tree │ │ └── mod.rs │ │ └── util │ │ └── mod.rs ├── ces-sanitized-logger │ ├── .rustfmt.toml │ ├── Cargo.toml │ └── src │ │ ├── all-log-targets.txt │ │ ├── lib.rs │ │ ├── logger.rs │ │ ├── subscriber.rs │ │ └── test.rs ├── ces-serde-more │ ├── .rustfmt.toml │ ├── Cargo.toml │ └── src │ │ ├── key_bytes.rs │ │ ├── lib.rs │ │ ├── option_key_bytes.rs │ │ ├── pubkey_bytes.rs │ │ ├── rsa_key_bytes.rs │ │ └── scale_bytes.rs ├── ces-trie-storage │ ├── .rustfmt.toml │ ├── Cargo.toml │ ├── src │ │ ├── lib.rs │ │ ├── memdb.rs │ │ └── ser.rs │ └── tests │ │ ├── data │ │ ├── changes.json │ │ ├── dev-spec.json │ │ └── state_roots.txt │ │ └── test_state_root.rs ├── ces-types │ ├── Cargo.toml │ ├── sample │ │ └── ias_attestation.json │ └── src │ │ ├── attestation.rs │ │ ├── attestation │ │ └── legacy.rs │ │ └── lib.rs ├── cestory │ ├── .rustfmt.toml │ ├── Cargo.toml │ ├── api │ │ ├── .gitignore │ │ ├── Cargo.toml │ │ ├── build.rs │ │ ├── proto │ │ │ ├── ceseal_rpc.proto │ │ │ ├── podr2-api.proto │ │ │ ├── pois-api.proto │ │ │ └── pubkeys.proto │ │ ├── src │ │ │ ├── blocks.rs │ │ │ ├── crpc.rs │ │ │ ├── crypto.rs │ │ │ ├── ecall_args.rs │ │ │ ├── lib.rs │ │ │ ├── proto_generated │ │ │ │ ├── .gitignore │ │ │ │ ├── mod.rs │ │ │ │ └── tests.rs │ │ │ └── storage_sync.rs │ │ └── tests │ │ │ ├── snapshots │ │ │ ├── test_block_abi__sync_blocks_abi_should_not_change-2.snap │ │ │ ├── test_block_abi__sync_blocks_abi_should_not_change-3.snap │ │ │ ├── test_block_abi__sync_blocks_abi_should_not_change-4.snap │ │ │ └── test_block_abi__sync_blocks_abi_should_not_change.snap │ │ │ └── test_block_abi.rs │ ├── pal │ │ ├── Cargo.toml │ │ └── src │ │ │ └── lib.rs │ ├── src │ │ ├── bootstrap.rs │ │ ├── ceseal_service.rs │ │ ├── cryptography │ │ │ ├── aead.rs │ │ │ └── mod.rs │ │ ├── expert.rs │ │ ├── lib.rs │ │ ├── light_validation │ │ │ ├── error.rs │ │ │ ├── justification.rs │ │ │ ├── mod.rs │ │ │ ├── storage_proof.rs │ │ │ └── types.rs │ │ ├── podr2.rs │ │ ├── podr2 │ │ │ └── proxy.rs │ │ ├── pois.rs │ │ ├── pois │ │ │ └── proxy.rs │ │ ├── pubkeys.rs │ │ ├── secret_channel.rs │ │ ├── storage.rs │ │ ├── system │ │ │ ├── keyfairy.rs │ │ │ ├── master_key.rs │ │ │ └── mod.rs │ │ └── types.rs │ └── tests │ │ ├── snapshots │ │ ├── test_serde__versioning_ciborium.snap │ │ ├── test_serde__versioning_rmp_serde.snap │ │ └── test_serde__versioning_serde_cbor.snap │ │ ├── test_podr2.rs │ │ ├── test_pois.rs │ │ ├── test_pubkeys.rs │ │ └── test_serde.rs ├── cesxt │ ├── .rustfmt.toml │ ├── Cargo.toml │ └── src │ │ ├── chain_api.rs │ │ ├── dynamic.rs │ │ ├── dynamic │ │ └── tx.rs │ │ ├── lib.rs │ │ └── rpc.rs ├── common │ ├── Cargo.toml │ └── src │ │ └── lib.rs ├── enclave-verify │ ├── Cargo.toml │ └── src │ │ └── lib.rs ├── reqwest-env-proxy │ ├── .rustfmt copy.toml │ ├── .rustfmt.toml │ ├── Cargo.toml │ └── src │ │ └── lib.rs ├── rrsc │ ├── Cargo.toml │ ├── README.md │ ├── pallet │ │ ├── Cargo.toml │ │ ├── README.md │ │ └── src │ │ │ ├── benchmarking.rs │ │ │ ├── default_weights.rs │ │ │ ├── equivocation.rs │ │ │ ├── lib.rs │ │ │ ├── mock.rs │ │ │ ├── randomness.rs │ │ │ ├── tests.rs │ │ │ └── vrf_solver.rs │ ├── primitives │ │ ├── Cargo.toml │ │ ├── README.md │ │ └── src │ │ │ ├── digests.rs │ │ │ ├── inherents.rs │ │ │ ├── lib.rs │ │ │ └── traits.rs │ ├── rpc │ │ ├── Cargo.toml │ │ ├── README.md │ │ └── src │ │ │ └── lib.rs │ ├── src │ │ ├── authorship.rs │ │ ├── aux_schema.rs │ │ ├── lib.rs │ │ ├── migration.rs │ │ └── verification.rs │ └── sync-state │ │ ├── Cargo.toml │ │ └── src │ │ └── lib.rs ├── scheduler-credit │ ├── Cargo.toml │ └── src │ │ └── lib.rs ├── sgx-api-lite │ ├── .rustfmt.toml │ ├── Cargo.toml │ ├── src │ │ ├── enclave_api.S │ │ ├── lib.rs │ │ └── sys.rs │ └── tests │ │ └── tests.rs └── sgx-attestation │ ├── .rustfmt.toml │ ├── Cargo.toml │ ├── sample │ └── ias_attestation.json │ └── src │ ├── dcap │ ├── constants.rs │ ├── mod.rs │ ├── quote.rs │ ├── report.rs │ ├── tcb_info.rs │ ├── utils.rs │ └── verify.rs │ ├── gramine.rs │ ├── ias │ ├── mod.rs │ ├── report.rs │ └── verify.rs │ ├── lib.rs │ ├── snapshots │ ├── sgx_attestation__ias__test__could_parse-2.snap │ ├── sgx_attestation__ias__test__could_parse-3.snap │ └── sgx_attestation__ias__test__could_parse.snap │ └── types.rs ├── docs ├── AccountGuide.md ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.adoc ├── code-overview-for-sbp.md ├── designs-of-storage-mining.md ├── on-src │ └── node │ │ └── src │ │ └── chain_spec.rs.md ├── rust-setup.md └── setup.md ├── pallets ├── audit │ ├── Cargo.toml │ ├── README.md │ └── src │ │ ├── benchmarking.rs │ │ ├── constants.rs │ │ ├── lib.rs │ │ ├── migrations.rs │ │ ├── mock.rs │ │ ├── temp_weights.rs │ │ ├── tests.rs │ │ ├── types.rs │ │ └── weights.rs ├── cacher │ ├── Cargo.toml │ ├── README.md │ └── src │ │ ├── benchmarking.rs │ │ ├── lib.rs │ │ ├── mock.rs │ │ ├── tests.rs │ │ ├── types.rs │ │ └── weights.rs ├── cess-treasury │ ├── Cargo.toml │ ├── README.md │ └── src │ │ ├── benchmarking.rs │ │ ├── constants.rs │ │ ├── lib.rs │ │ └── types.rs ├── evm-account-mapping │ ├── Cargo.toml │ ├── README.md │ └── src │ │ ├── benchmarking.rs │ │ ├── eip712.rs │ │ ├── encode.rs │ │ ├── lib.rs │ │ ├── mock.rs │ │ ├── tests.rs │ │ └── weights.rs ├── file-bank │ ├── Cargo.toml │ ├── README.md │ └── src │ │ ├── benchmarking.rs │ │ ├── constants.rs │ │ ├── functions.rs │ │ ├── impls │ │ ├── dealimpl.rs │ │ ├── mod.rs │ │ └── receptionist.rs │ │ ├── lib.rs │ │ ├── migration.rs │ │ ├── mock.rs │ │ ├── tests.rs │ │ ├── types.rs │ │ └── weights.rs ├── mq │ ├── Cargo.toml │ ├── runtime-api │ │ ├── Cargo.toml │ │ └── src │ │ │ └── lib.rs │ └── src │ │ ├── check_seq.rs │ │ └── lib.rs ├── oss │ ├── Cargo.toml │ ├── README.md │ └── src │ │ ├── benchmarking.rs │ │ ├── lib.rs │ │ ├── mock.rs │ │ ├── tests.rs │ │ ├── types.rs │ │ └── weights.rs ├── reservoir │ ├── Cargo.toml │ └── src │ │ ├── impls.rs │ │ ├── lib.rs │ │ └── types.rs ├── scheduler-credit │ ├── Cargo.toml │ ├── README.md │ └── src │ │ ├── lib.rs │ │ ├── mock.rs │ │ └── tests.rs ├── sminer │ ├── Cargo.toml │ ├── README.md │ └── src │ │ ├── benchmarking.rs │ │ ├── constants.rs │ │ ├── functions.rs │ │ ├── helper.rs │ │ ├── lib.rs │ │ ├── migration.rs │ │ ├── mock.rs │ │ ├── tests.rs │ │ ├── types.rs │ │ └── weights.rs ├── staking │ ├── Cargo.toml │ ├── README.md │ └── src │ │ ├── asset.rs │ │ ├── benchmarking.rs │ │ ├── election_size_tracker.rs │ │ ├── inflation.rs │ │ ├── ledger.rs │ │ ├── lib.rs │ │ ├── migrations.rs │ │ ├── mock.rs │ │ ├── pallet │ │ ├── impls.rs │ │ └── mod.rs │ │ ├── slashing.rs │ │ ├── testing_utils.rs │ │ ├── tests.rs │ │ └── weights.rs ├── storage-handler │ ├── Cargo.toml │ ├── README.md │ └── src │ │ ├── benchmarking.rs │ │ ├── impls.rs │ │ ├── lib.rs │ │ ├── types.rs │ │ └── weights.rs └── tee-worker │ ├── Cargo.toml │ ├── README.md │ └── src │ ├── benchmarking.rs │ ├── functions.rs │ ├── lib.rs │ ├── mock.rs │ ├── tests.rs │ ├── types.rs │ ├── weights.rs │ └── weights_demo.rs ├── rust-toolchain.toml ├── rustfmt.toml ├── scripts ├── docker │ ├── build.sh │ ├── cargo-config.toml │ ├── ceseal │ │ └── gramine │ │ │ ├── Dockerfile │ │ │ ├── handover.Dockerfile │ │ │ ├── handover.ts │ │ │ ├── start-with-handover.sh │ │ │ └── start.sh │ ├── cifrost │ │ └── Dockerfile │ ├── env │ │ ├── gramine-rust.Dockerfile │ │ ├── intel-sgx-deno.Dockerfile │ │ ├── intel-sgx.Dockerfile │ │ └── rust-chef-protoc.Dockerfile │ └── node │ │ └── Dockerfile ├── run │ ├── ceseal.sh │ ├── cifrost.sh │ └── node.sh └── wasm_overrides │ └── testnet │ └── spec_100.wasm └── standalone ├── chain ├── node │ ├── Cargo.toml │ ├── build.rs │ ├── ccg │ │ ├── cess-develop-spec-raw.json │ │ └── cess-testnet-spec-raw.json │ └── src │ │ ├── benchmarking.rs │ │ ├── chain_spec.rs │ │ ├── cli.rs │ │ ├── client.rs │ │ ├── command.rs │ │ ├── eth.rs │ │ ├── main.rs │ │ ├── rpc │ │ ├── eth.rs │ │ └── mod.rs │ │ └── service.rs ├── primitives │ ├── Cargo.toml │ └── src │ │ └── lib.rs └── runtime │ ├── Cargo.toml │ ├── build.rs │ └── src │ ├── assets_api.rs │ ├── constants.rs │ ├── frontier.rs │ ├── frontier │ └── precompiles.rs │ ├── impls.rs │ ├── lib.rs │ ├── msg_routing.rs │ └── voter_bags.rs └── teeworker ├── ceseal ├── .gitignore ├── .rustfmt.toml ├── Cargo.lock ├── Cargo.toml ├── Makefile ├── bin │ └── .gitignore ├── build.rs ├── gramine-build │ ├── .gitignore │ ├── Makefile │ ├── ceseal.manifest.template │ ├── conf │ │ ├── aesmd.conf │ │ └── sgx_default_qcnl.conf │ ├── gramine-dir │ ├── gramine-sgx │ └── private.dev.pem └── src │ ├── handover.rs │ ├── main.rs │ └── pal_gramine.rs ├── cifrost ├── .rustfmt.toml ├── Cargo.toml └── src │ ├── authority.rs │ ├── block_subscribe.rs │ ├── chain_client.rs │ ├── error.rs │ ├── lib.rs │ ├── main.rs │ ├── msg_sync.rs │ ├── prefetcher.rs │ ├── tx.rs │ └── types.rs └── handover ├── Cargo.toml └── src ├── arg.rs ├── error.rs └── main.rs /.dockerignore: -------------------------------------------------------------------------------- 1 | DS_Store 2 | Dockerfile 3 | **/target 4 | **/ceseal/bin/* 5 | .github 6 | .maintain 7 | .vscode 8 | docs 9 | LICENSE 10 | README.md -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | [*] 3 | indent_style=space 4 | indent_size=4 5 | tab_width=4 6 | end_of_line=lf 7 | charset=utf-8 8 | trim_trailing_whitespace=true 9 | max_line_length=120 10 | insert_final_newline=true 11 | 12 | [pallets/**.rs] 13 | indent_style=tab 14 | indent_size=tab 15 | 16 | [standalone/chain/{node,runtime}/**.rs] 17 | indent_style=tab 18 | indent_size=tab 19 | 20 | [standalone/teeworker/{ceseal,cifrost}/**.rs] 21 | indent_style=space 22 | indent_size=4 23 | 24 | [*.{yml,yaml}] 25 | indent_style=space 26 | indent_size=2 27 | tab_width=2 28 | end_of_line=lf 29 | 30 | [scripts/**] 31 | indent_style=space 32 | indent_size=4 -------------------------------------------------------------------------------- /.github/workflows/build-and-test.yml: -------------------------------------------------------------------------------- 1 | name: build-and-test 2 | 3 | on: 4 | push: 5 | branches: [ "main" , "dev"] 6 | pull_request: 7 | branches: [ "main" , "dev"] 8 | # Allows you to run this workflow manually from the Actions tab 9 | workflow_dispatch: 10 | 11 | env: 12 | CARGO_TERM_COLOR: always 13 | 14 | jobs: 15 | build: 16 | 17 | runs-on: ubuntu-latest 18 | 19 | steps: 20 | - name: Install Protoc 21 | uses: arduino/setup-protoc@v2 22 | - uses: actions/checkout@v3 23 | - name: install toolchain 24 | uses: 0xbillw/install-rust-substrate-action@main 25 | - name: Build 26 | run: cargo build -r --verbose 27 | # We don't run cargo test for now. 28 | # - name: Run tests 29 | # run: cargo test -r --verbose 30 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Generated by Cargo 2 | # will have compiled files and executables 3 | **/target/ 4 | # These are backup files generated by rustfmt 5 | **/*.rs.bk 6 | 7 | .DS_Store 8 | 9 | # The cache for docker container dependency 10 | .cargo 11 | 12 | # The cache for chain data in container 13 | .local 14 | local_run 15 | 16 | # direnv cache 17 | .direnv 18 | 19 | .idea 20 | .vscode 21 | 22 | docker/.cache 23 | docker/cess/cess-node -------------------------------------------------------------------------------- /Host: -------------------------------------------------------------------------------- 1 | Host github.com 2 | Hostname ssh.github.com 3 | stname ssh.github.com 4 | Port 443 5 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | BUILD?=release 2 | OA?=1 3 | VC?=1 4 | XARGS= 5 | DEV= 6 | ifeq ($(DEV),1) 7 | OA=0 8 | VC=0 9 | BUILD=debug 10 | endif 11 | ifeq ($(BUILD),release) 12 | XARGS = --release 13 | endif 14 | ifeq ($(OA),1) 15 | XARGS += --features only-attestation 16 | endif 17 | ifeq ($(VC),1) 18 | XARGS += --features verify-cesealbin 19 | endif 20 | 21 | .PHONY: all node ceseal test clippy 22 | 23 | all: ceseal 24 | cargo build ${XARGS} 25 | node: 26 | cargo build -p cess-node ${XARGS} 27 | cifrost: 28 | cargo build -p cifrost ${XARGS} 29 | handover: 30 | cargo build -p handover --release 31 | ceseal: 32 | $(MAKE) -C standalone/teeworker/ceseal BUILD=${BUILD} OA=${OA} VC=${VC} 33 | test: 34 | cargo test --workspace --exclude node-executor --exclude cess-node 35 | 36 | clippy: 37 | cargo clippy --tests 38 | $(MAKE) clippy -C standalone/teeworker/ceseal 39 | 40 | lint: 41 | cargo dylint --all --workspace 42 | 43 | clean: 44 | cargo clean 45 | $(MAKE) -C standalone/teeworker/ceseal clean 46 | -------------------------------------------------------------------------------- /crates/bloom-filter/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "cp-bloom-filter" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | [dependencies] 7 | codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive", "max-encoded-len"] } 8 | scale-info = { workspace = true, features = ["derive"] } 9 | sp-core = { workspace = true } 10 | 11 | [features] 12 | default = ["std"] 13 | std = [ 14 | "codec/std", 15 | "scale-info/std", 16 | "sp-core/std", 17 | ] -------------------------------------------------------------------------------- /crates/ces-allocator/.rustfmt.toml: -------------------------------------------------------------------------------- 1 | hard_tabs = false -------------------------------------------------------------------------------- /crates/ces-allocator/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "ces-allocator" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 7 | 8 | [dependencies] 9 | -------------------------------------------------------------------------------- /crates/ces-crypto/.rustfmt.toml: -------------------------------------------------------------------------------- 1 | hard_tabs = false -------------------------------------------------------------------------------- /crates/ces-crypto/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "ces-crypto" 3 | version = "0.1.0" 4 | edition = "2021" 5 | resolver = "2" 6 | 7 | [dependencies] 8 | sp-core = { workspace = true } 9 | rsa = { workspace = true } 10 | sp-application-crypto = { workspace = true } 11 | 12 | ring = { workspace = true, features = ["alloc"] } 13 | curve25519-dalek = { workspace = true } 14 | schnorrkel = { workspace = true, features = ["preaudit_deprecated"] } 15 | aead = { workspace = true, optional = true } 16 | typenum = { workspace = true, optional = true } 17 | aead-io = { workspace = true, optional = true } 18 | 19 | [dev-dependencies] 20 | rand = "0.8.5" 21 | hex = "0.4" 22 | 23 | [features] 24 | default = [ "full_crypto" ] 25 | std = [ "aead/std" ] 26 | full_crypto = [ 27 | "sp-core/full_crypto", 28 | "sp-application-crypto/full_crypto", 29 | ] 30 | 31 | stream = [ 32 | "std", 33 | "aead/stream", 34 | "aead-io", 35 | "typenum", 36 | ] 37 | 38 | -------------------------------------------------------------------------------- /crates/ces-crypto/src/aead.rs: -------------------------------------------------------------------------------- 1 | #[cfg(feature = "stream")] 2 | pub mod stream; 3 | 4 | use crate::CryptoError; 5 | 6 | use alloc::vec::Vec; 7 | use core::cmp::min; 8 | use ring::aead::{LessSafeKey, UnboundKey}; 9 | 10 | // aes-256-gcm key 11 | pub struct AeadKey(LessSafeKey); 12 | 13 | pub const IV_BYTES: usize = 12; 14 | pub type IV = [u8; IV_BYTES]; 15 | 16 | pub fn generate_iv(nonce: &[u8]) -> IV { 17 | let mut iv: IV = Default::default(); 18 | let min_len = min(nonce.len(), iv.len()); 19 | iv.copy_from_slice(&nonce[..min_len]); 20 | iv 21 | } 22 | 23 | fn load_key(raw: &[u8]) -> Result { 24 | let unbound_key = 25 | UnboundKey::new(&ring::aead::AES_256_GCM, raw).map_err(|_| CryptoError::AeadInvalidKey)?; 26 | Ok(AeadKey(LessSafeKey::new(unbound_key))) 27 | } 28 | 29 | // Encrypts the data in-place and appends a 128bit auth tag 30 | pub fn encrypt(iv: &IV, secret: &[u8], in_out: &mut Vec) -> Result<(), CryptoError> { 31 | let nonce = ring::aead::Nonce::assume_unique_for_key(*iv); 32 | let key = load_key(secret)?; 33 | 34 | key.0 35 | .seal_in_place_append_tag(nonce, ring::aead::Aad::empty(), in_out) 36 | .map_err(|_| CryptoError::AeadEncryptError)?; 37 | Ok(()) 38 | } 39 | 40 | // Decrypts the cipher (with 128 auth tag appended) in-place and returns the message as a slice. 41 | pub fn decrypt<'in_out>( 42 | iv: &[u8], 43 | secret: &[u8], 44 | in_out: &'in_out mut [u8], 45 | ) -> Result<&'in_out mut [u8], CryptoError> { 46 | let mut iv_arr = [0_u8; IV_BYTES]; 47 | iv_arr.copy_from_slice(&iv[..IV_BYTES]); 48 | let key = load_key(secret)?; 49 | let nonce = ring::aead::Nonce::assume_unique_for_key(iv_arr); 50 | 51 | key.0 52 | .open_in_place(nonce, ring::aead::Aad::empty(), in_out) 53 | .map_err(|_| CryptoError::AeadDecryptError) 54 | } 55 | 56 | #[cfg(test)] 57 | mod test { 58 | use super::*; 59 | use ring::rand::SecureRandom; 60 | 61 | pub fn generate_random_iv() -> IV { 62 | let mut nonce_vec = [0_u8; IV_BYTES]; 63 | let rand = ring::rand::SystemRandom::new(); 64 | rand.fill(&mut nonce_vec).unwrap(); 65 | nonce_vec 66 | } 67 | 68 | #[test] 69 | fn encrypt_and_decrypt() { 70 | let iv = generate_random_iv(); 71 | let secret = [233_u8; 32]; 72 | let message = [233_u8; 64]; 73 | 74 | let mut encrypted_message = Vec::new(); 75 | encrypted_message.extend_from_slice(&message); 76 | 77 | encrypt(&iv, &secret, &mut encrypted_message).unwrap(); 78 | let decrypted_messgae = decrypt(&iv, &secret, &mut encrypted_message[..]).unwrap(); 79 | 80 | assert_eq!(decrypted_messgae, message); 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /crates/ces-crypto/src/key_share.rs: -------------------------------------------------------------------------------- 1 | use crate::aead::{self, IV}; 2 | use crate::ecdh::{self, EcdhKey, EcdhPublicKey}; 3 | use crate::sr25519::{KDF, SECRET_KEY_LENGTH}; 4 | use crate::CryptoError; 5 | use crate::SecretKey; 6 | 7 | use alloc::borrow::ToOwned; 8 | use alloc::vec::Vec; 9 | use sp_core::sr25519; 10 | 11 | pub fn encrypt_secret_to( 12 | my_key: &sr25519::Pair, 13 | key_derive_info: &[&[u8]], 14 | ecdh_pubkey: &EcdhPublicKey, 15 | secret_key: &SecretKey, 16 | iv: &IV, 17 | ) -> Result<(EcdhPublicKey, Vec), CryptoError> { 18 | let derived_key = my_key.derive_sr25519_pair(key_derive_info)?; 19 | let my_ecdh_key = derived_key.derive_ecdh_key()?; 20 | let secret = ecdh::agree(&my_ecdh_key, ecdh_pubkey)?; 21 | let mut data = match secret_key { 22 | SecretKey::Rsa(rsa_key) => rsa_key.to_vec(), 23 | SecretKey::Sr25519(sr25519_key) => sr25519_key.to_vec(), 24 | }; 25 | aead::encrypt(iv, &secret, &mut data)?; 26 | 27 | Ok((my_ecdh_key.public(), data)) 28 | } 29 | 30 | pub fn decrypt_secret_from( 31 | my_ecdh_key: &EcdhKey, 32 | ecdh_pubkey: &EcdhPublicKey, 33 | encrypted_key: &[u8], 34 | iv: &IV, 35 | ) -> Result { 36 | let secret = ecdh::agree(my_ecdh_key, ecdh_pubkey)?; 37 | let mut key_buff = encrypted_key.to_owned(); 38 | let secret_key = aead::decrypt(iv, &secret, &mut key_buff[..])?; 39 | match secret_key.len() { 40 | SECRET_KEY_LENGTH => Ok(SecretKey::Sr25519( 41 | secret_key 42 | .try_into() 43 | .map_err(|_| CryptoError::Sr25519InvalidSecret)?, 44 | )), 45 | _ => Ok(SecretKey::Rsa(secret_key.to_vec())), 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /crates/ces-crypto/src/lib.rs: -------------------------------------------------------------------------------- 1 | #![cfg_attr(not(feature = "std"), no_std)] 2 | 3 | extern crate alloc; 4 | 5 | #[cfg(test)] 6 | #[macro_use] 7 | extern crate std; 8 | 9 | pub mod aead; 10 | pub mod ecdh; 11 | pub mod rsa; 12 | pub mod sr25519; 13 | 14 | #[cfg(feature = "full_crypto")] 15 | pub mod key_share; 16 | 17 | #[derive(Debug)] 18 | pub enum CryptoError { 19 | HkdfExpandError, 20 | // Ecdh errors 21 | EcdhInvalidSecretKey, 22 | EcdhInvalidPublicKey, 23 | // Aead errors 24 | AeadInvalidKey, 25 | AeadEncryptError, 26 | AeadDecryptError, 27 | // sr25519 28 | Sr25519InvalidSecret, 29 | //rsa 30 | RsaSigningError, 31 | RsaInvalidDer, 32 | } 33 | 34 | pub enum SecretKey { 35 | Rsa(rsa::RsaDer), 36 | Sr25519(sr25519::Sr25519SecretKey), 37 | } 38 | -------------------------------------------------------------------------------- /crates/ces-crypto/src/rsa.rs: -------------------------------------------------------------------------------- 1 | use crate::CryptoError; 2 | use rsa::{ 3 | Pkcs1v15Sign, pkcs8::{DecodePrivateKey,EncodePrivateKey}, PublicKey, 4 | }; 5 | use alloc::vec::Vec; 6 | 7 | pub const SIGNATURE_BYTES: usize = 256; 8 | pub const RSA_BIT_SIZE: usize = 2048; 9 | 10 | pub type RsaDer = Vec; 11 | pub type Signature = [u8; SIGNATURE_BYTES]; 12 | 13 | pub trait Signing { 14 | fn sign_data(&self, data: &[u8]) -> Result; 15 | 16 | fn verify_data(&self, sig: &Signature, data: &[u8]) -> bool; 17 | } 18 | 19 | pub trait Persistence { 20 | fn dump_seed(&self) -> RsaDer; 21 | 22 | fn dump_secret_der(&self) -> RsaDer; 23 | 24 | fn restore_from_der(seed: &RsaDer) -> Result; 25 | } 26 | 27 | impl Signing for rsa::RsaPrivateKey { 28 | fn sign_data(&self, data: &[u8]) -> Result { 29 | self.sign(Pkcs1v15Sign::new_raw(), data).map_err(|_|CryptoError::RsaSigningError)?.try_into().map_err(|_|CryptoError::RsaSigningError) 30 | } 31 | 32 | fn verify_data(&self, sig: &Signature, hashed: &[u8]) -> bool { 33 | self.verify(Pkcs1v15Sign::new_raw(), hashed, sig).is_ok() 34 | } 35 | } 36 | 37 | impl Persistence for rsa::RsaPrivateKey { 38 | fn dump_seed(&self) -> RsaDer { 39 | panic!("No available seed for rsa pair"); 40 | } 41 | 42 | fn dump_secret_der(&self) -> RsaDer { 43 | self.to_pkcs8_der().unwrap().as_bytes().to_vec() 44 | } 45 | 46 | fn restore_from_der(seed: &RsaDer) -> Result { 47 | rsa::RsaPrivateKey::from_pkcs8_der(&seed).map_err(|_|CryptoError::RsaInvalidDer) 48 | } 49 | } -------------------------------------------------------------------------------- /crates/ces-mq/.rustfmt.toml: -------------------------------------------------------------------------------- 1 | hard_tabs = false -------------------------------------------------------------------------------- /crates/ces-mq/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "ces-mq" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 7 | 8 | [dependencies] 9 | log = { workspace = true } 10 | tracing = { workspace = true } 11 | hex = { workspace = true, features = ['alloc'] } 12 | derive_more = { workspace = true, features = ["display"] } 13 | parity-scale-codec = { workspace = true, features = ["derive"] } 14 | scale-info = { workspace = true, features = ["derive"] } 15 | sp-core = { workspace = true } 16 | serde = { workspace = true, features = ["derive"] } 17 | spin = { workspace = true, features = ["mutex", "use_ticket_mutex"], optional = true } 18 | # for checkpoint 19 | environmental = { workspace = true, optional = true } 20 | im = { workspace = true } 21 | ces-serde-more = { workspace = true } 22 | 23 | 24 | [features] 25 | default = ["dispatcher", "queue", "signers", "checkpoint"] 26 | dispatcher = ["spin"] 27 | queue = ["spin"] 28 | signers = [ 29 | "sp-core/full_crypto", 30 | "ces-serde-more/crypto", 31 | ] 32 | checkpoint = ["environmental", "std"] 33 | std = [] 34 | -------------------------------------------------------------------------------- /crates/ces-mq/src/checkpoint_helper.rs: -------------------------------------------------------------------------------- 1 | pub use { 2 | dispatcher::{subscribe_default, using as using_dispatcher}, 3 | send_mq::{global_send_mq, using as using_send_mq}, 4 | }; 5 | 6 | mod send_mq { 7 | use crate::MessageSendQueue; 8 | 9 | environmental::environmental!(global_send_mq: MessageSendQueue); 10 | 11 | pub fn using(mq: &mut MessageSendQueue, f: F) -> R 12 | where 13 | F: FnOnce() -> R, 14 | { 15 | global_send_mq::using(mq, f) 16 | } 17 | 18 | pub fn global_send_mq() -> MessageSendQueue { 19 | global_send_mq::with(|mq| mq.clone()) 20 | .expect("global_send_mq is called without using a global_send_mq") 21 | } 22 | } 23 | 24 | mod dispatcher { 25 | use crate::{dispatcher::Receiver, Message, MessageDispatcher, Path}; 26 | 27 | environmental::environmental!(global_dispatcher: MessageDispatcher); 28 | 29 | pub fn using(mq: &mut MessageDispatcher, f: F) -> R 30 | where 31 | F: FnOnce() -> R, 32 | { 33 | global_dispatcher::using(mq, f) 34 | } 35 | 36 | fn with R, R>(f: F) -> Option { 37 | global_dispatcher::with(f) 38 | } 39 | 40 | pub fn subscribe_default(path: impl Into) -> Receiver { 41 | with(move |dispatcher| dispatcher.subscribe(path)) 42 | .expect("subscribe_default called without using a global dispatcher") 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /crates/ces-mq/src/signer/mod.rs: -------------------------------------------------------------------------------- 1 | use alloc::vec::Vec; 2 | 3 | pub trait MessageSigner { 4 | fn sign(&self, data: &[u8]) -> Vec; 5 | } 6 | 7 | #[cfg(feature = "signers")] 8 | pub mod signers { 9 | use super::MessageSigner; 10 | use alloc::vec::Vec; 11 | use ces_serde_more as more; 12 | use serde::{Deserialize, Serialize}; 13 | use sp_core::{crypto::Pair as PairTrait, sr25519}; 14 | 15 | #[derive(Serialize, Deserialize, Clone, ::scale_info::TypeInfo)] 16 | pub struct Sr25519Signer { 17 | #[serde(with = "more::key_bytes")] 18 | #[codec(skip)] 19 | key: sr25519::Pair, 20 | } 21 | 22 | impl MessageSigner for Sr25519Signer { 23 | fn sign(&self, data: &[u8]) -> Vec { 24 | self.key.sign(data).0.to_vec() 25 | } 26 | } 27 | 28 | impl From for Sr25519Signer { 29 | fn from(key: sr25519::Pair) -> Self { 30 | Self { key } 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /crates/ces-node-rpc-ext/.rustfmt.toml: -------------------------------------------------------------------------------- 1 | hard_tabs = false -------------------------------------------------------------------------------- /crates/ces-node-rpc-ext/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "ces-node-rpc-ext" 3 | version = "0.1.0" 4 | edition = "2021" 5 | authors = ["CESS Network"] 6 | license = "Apache-2.0" 7 | homepage = "https://cess.cloud/" 8 | repository = "https://github.com/CESSProject/cess" 9 | 10 | [dependencies] 11 | # third-party dependencies 12 | serde = { workspace = true, features = ["derive"] } 13 | thiserror = { workspace = true } 14 | jsonrpsee = { workspace = true, features = ["server", "macros"] } 15 | impl-serde = { workspace = true } 16 | log = { workspace = true } 17 | hex = { workspace = true } 18 | parity-scale-codec = { workspace = true } 19 | scale-info = { workspace = true } 20 | # primitives 21 | sp-runtime = { workspace = true } 22 | sp-blockchain = { workspace = true } 23 | sp-api = { workspace = true } 24 | sp-state-machine = { workspace = true } 25 | # client dependencies 26 | sc-client-api = { workspace = true } 27 | sc-transaction-pool-api = { workspace = true } 28 | 29 | ces-mq = { workspace = true, default-features = true } 30 | ces-pallet-mq = { workspace = true, default-features = true } 31 | ces-pallet-mq-runtime-api = { workspace = true, default-features = true } 32 | ces-node-rpc-ext-types = { workspace = true, default-features = true } 33 | -------------------------------------------------------------------------------- /crates/ces-node-rpc-ext/src/mq_seq.rs: -------------------------------------------------------------------------------- 1 | use super::*; 2 | use ces_mq::MessageOrigin; 3 | use ces_pallet_mq::tag; 4 | use ces_pallet_mq_runtime_api::MqApi; 5 | use parity_scale_codec::Decode; 6 | 7 | pub(super) fn get_mq_seq( 8 | client: &Client, 9 | pool: &Arc

, 10 | sender_hex: String, 11 | ) -> Result 12 | where 13 | BE: Backend, 14 | Client: StorageProvider 15 | + HeaderBackend 16 | + BlockBackend 17 | + HeaderMetadata 18 | + ProvideRuntimeApi, 19 | Block: BlockT + 'static, 20 | Client::Api: sp_api::Metadata + ApiExt, 21 | Client::Api: MqApi, 22 | <::Header as Header>::Number: Into, 23 | P: TransactionPool, 24 | { 25 | let sender_scl = hex::decode(sender_hex).map_err(|_| Error::InvalidSender)?; 26 | let sender = MessageOrigin::decode(&mut &sender_scl[..]).map_err(|_| Error::InvalidSender)?; 27 | 28 | let api = client.runtime_api(); 29 | let best_hash = client.info().best_hash; 30 | 31 | let seq = api.sender_sequence(best_hash, &sender)?.unwrap_or(0); 32 | 33 | log::debug!(target: "rpc-ext", "State seq for {}: {}", sender, seq); 34 | 35 | // Now we need to query the transaction pool 36 | // and find transactions originating from the same sender. 37 | // 38 | // Since extrinsics are opaque to us, we look for them using 39 | // `provides` tag. And increment the sequence if we find a transaction 40 | // that matches the current one. 41 | let mut current_seq = seq; 42 | let mut current_tag = tag(&sender, seq); 43 | for tx in pool.ready() { 44 | log::debug!( 45 | target: "rpc-ext", 46 | "Current seq to {}, checking {} vs {:?}", 47 | current_seq, 48 | hex::encode(¤t_tag), 49 | tx.provides().iter().map(hex::encode).collect::>(), 50 | ); 51 | // since transactions in `ready()` need to be ordered by sequence 52 | // it's fine to continue with current iterator. 53 | for tg in tx.provides() { 54 | if tg == ¤t_tag { 55 | current_seq += 1; 56 | current_tag = tag(&sender, current_seq); 57 | break; 58 | } 59 | } 60 | } 61 | 62 | log::debug!(target: "rpc-ext", "return seq {}", current_seq); 63 | 64 | Ok(current_seq) 65 | } 66 | -------------------------------------------------------------------------------- /crates/ces-node-rpc-ext/types/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "ces-node-rpc-ext-types" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | [dependencies] 7 | serde = { workspace = true, features = ["derive"] } 8 | impl-serde = { workspace = true } 9 | scale-info = { workspace = true } 10 | parity-scale-codec = { workspace = true } 11 | -------------------------------------------------------------------------------- /crates/ces-node-rpc-ext/types/src/lib.rs: -------------------------------------------------------------------------------- 1 | use parity_scale_codec::{Decode, Encode}; 2 | use scale_info::TypeInfo; 3 | use serde::{Deserialize, Serialize}; 4 | 5 | /// Storage key. 6 | #[derive(Serialize, Deserialize, Clone, Debug, Encode, Decode, TypeInfo)] 7 | pub struct StorageKey(#[serde(with = "impl_serde::serialize")] pub Vec); 8 | 9 | /// Storage value. 10 | pub type StorageValue = StorageKey; 11 | 12 | /// In memory array of storage values. 13 | pub type StorageCollection = Vec<(K, Option)>; 14 | 15 | /// In memory arrays of storage values for multiple child tries. 16 | pub type ChildStorageCollection = Vec<(K, StorageCollection)>; 17 | 18 | #[derive(Serialize, Deserialize, Clone, Debug, Encode, Decode, TypeInfo)] 19 | #[serde(rename_all = "camelCase")] 20 | pub struct StorageChanges { 21 | /// A value of `None` means that it was deleted. 22 | pub main_storage_changes: StorageCollection, 23 | /// All changes to the child storages. 24 | pub child_storage_changes: ChildStorageCollection, 25 | } 26 | 27 | /// Response for the `pha_getStorageChanges` RPC. 28 | pub type GetStorageChangesResponse = Vec; 29 | 30 | #[derive(Serialize, Deserialize, Clone, Debug, Encode, Decode, TypeInfo)] 31 | #[serde(rename_all = "camelCase")] 32 | pub struct StorageChangesWithRoot { 33 | pub changes: StorageChanges, 34 | pub state_root: Vec, 35 | } 36 | 37 | /// Response for the `pha_getStorageChangesWithRoot` RPC. 38 | pub type GetStorageChangesResponseWithRoot = Vec; 39 | 40 | // Stuffs to convert ChildStorageCollection and StorageCollection types, 41 | // in order to dump the keys values into hex strings instead of list of dec numbers. 42 | pub trait MakeInto: Sized { 43 | fn into_(self) -> T; 44 | } 45 | 46 | impl MakeInto for Vec { 47 | fn into_(self) -> StorageKey { 48 | StorageKey(self) 49 | } 50 | } 51 | 52 | impl MakeInto> for StorageKey { 53 | fn into_(self) -> Vec { 54 | self.0 55 | } 56 | } 57 | 58 | impl, T> MakeInto> for Option { 59 | fn into_(self) -> Option { 60 | self.map(|v| v.into_()) 61 | } 62 | } 63 | 64 | impl MakeInto<(T1, T2)> for (F1, F2) 65 | where 66 | F1: MakeInto, 67 | F2: MakeInto, 68 | { 69 | fn into_(self) -> (T1, T2) { 70 | (self.0.into_(), self.1.into_()) 71 | } 72 | } 73 | 74 | impl, T> MakeInto> for Vec { 75 | fn into_(self) -> Vec { 76 | self.into_iter().map(|v| v.into_()).collect() 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /crates/ces-pdp/.rustfmt.toml: -------------------------------------------------------------------------------- 1 | # Basic 2 | edition = "2021" 3 | hard_tabs = false 4 | tab_spaces = 4 5 | max_width = 120 6 | use_small_heuristics = "Max" 7 | # Imports 8 | imports_granularity = "Crate" 9 | reorder_imports = true 10 | # Consistency 11 | newline_style = "Unix" 12 | # Format comments 13 | comment_width = 120 14 | wrap_comments = true 15 | # Misc 16 | chain_width = 80 17 | spaces_around_ranges = false 18 | binop_separator = "Back" 19 | reorder_impl_items = false 20 | match_arm_leading_pipes = "Preserve" 21 | match_arm_blocks = false 22 | match_block_trailing_comma = true 23 | trailing_comma = "Vertical" 24 | trailing_semicolon = false 25 | use_field_init_shorthand = true -------------------------------------------------------------------------------- /crates/ces-pdp/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "ces-pdp" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 7 | 8 | [dependencies] 9 | rand = { workspace = true } 10 | rsa = { workspace = true, features = ["default"] } 11 | serde = { workspace = true, features = ["derive"] } 12 | threadpool = { workspace = true } 13 | rust-crypto = { workspace = true } 14 | num-integer = { workspace = true } 15 | num-traits = { workspace = true } 16 | num-bigint-dig = { workspace = true } 17 | num-bigint = { workspace = true } 18 | sha2 = { workspace = true, default-features = false , features = ["oid"]} 19 | hex = { workspace = true, features = ["alloc"] } -------------------------------------------------------------------------------- /crates/ces-pois/.rustfmt.toml: -------------------------------------------------------------------------------- 1 | # Basic 2 | edition = "2021" 3 | hard_tabs = false 4 | tab_spaces = 4 5 | max_width = 120 6 | use_small_heuristics = "Max" 7 | # Imports 8 | imports_granularity = "Crate" 9 | reorder_imports = true 10 | # Consistency 11 | newline_style = "Unix" 12 | # Format comments 13 | comment_width = 120 14 | wrap_comments = true 15 | # Misc 16 | chain_width = 80 17 | spaces_around_ranges = false 18 | binop_separator = "Back" 19 | reorder_impl_items = false 20 | match_arm_leading_pipes = "Preserve" 21 | match_arm_blocks = false 22 | match_block_trailing_comma = true 23 | trailing_comma = "Vertical" 24 | trailing_semicolon = false 25 | use_field_init_shorthand = true -------------------------------------------------------------------------------- /crates/ces-pois/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "ces-pois" 3 | version = "0.4.5" 4 | edition = "2021" 5 | 6 | [features] 7 | default = [] 8 | use-sysinfo = [] 9 | 10 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 11 | 12 | [dependencies] 13 | anyhow = { workspace = true } 14 | bigdecimal = { workspace = true } 15 | dashmap = { workspace = true } 16 | hex = { workspace = true, features = ["alloc"] } 17 | lazy_static = { workspace = true } 18 | merkle_light = { workspace = true } 19 | num-bigint-dig = { workspace = true } 20 | num-integer = { workspace = true } 21 | num-traits = { workspace = true } 22 | prost = { workspace = true } 23 | rand = { workspace = true } 24 | rsa = { workspace = true, features = ["std"] } 25 | serde = { workspace = true, features = ["derive"] } 26 | serde_json = { workspace = true, features = ["std"] } 27 | sha2 = { workspace = true } 28 | tokio = { workspace = true, features = ["full"] } 29 | sysinfo = { workspace = true, optional = true } 30 | async-trait = { workspace = true } 31 | byteorder = { workspace = true } 32 | -------------------------------------------------------------------------------- /crates/ces-pois/src/acc/hash_2_prime.rs: -------------------------------------------------------------------------------- 1 | use std::{ 2 | ops::{Div, Mul, Shl}, 3 | str::FromStr, 4 | }; 5 | 6 | use bigdecimal::BigDecimal; 7 | use num_bigint_dig::{prime::probably_prime, BigUint}; 8 | use num_traits::{FromPrimitive, One, ToPrimitive}; 9 | use sha2::{Digest, Sha512}; 10 | 11 | fn fu(x: &BigUint) -> BigUint { 12 | let u = x.clone(); 13 | let one = BigUint::one(); 14 | 15 | let two = BigUint::from(2u32); 16 | 17 | let mut temp1: BigUint = &u + &two; 18 | temp1 *= &two; 19 | let temp2 = &u + &one; 20 | let bit = temp2.bits(); 21 | let divisor = one.shl(bit - 1); 22 | 23 | let f = BigDecimal::from_str(&temp2.to_string()).unwrap(); 24 | let z = f.div(BigDecimal::from_str(divisor.to_string().as_str()).unwrap()); 25 | let w = z.to_f64().unwrap(); 26 | let y = (f64::log2(w) + (bit - 1) as f64).powi(2); 27 | let y = BigUint::from_f64(y).unwrap(); 28 | let temp1 = &temp1.mul(&y); 29 | 30 | temp1.clone() 31 | } 32 | 33 | pub fn h_prime(u: &BigUint) -> BigUint { 34 | let mut h = Sha512::new(); 35 | h.update(u.to_bytes_be()); 36 | let huj = fu(&BigUint::from_bytes_be(h.finalize().as_slice())); 37 | let mut j = huj.clone(); 38 | let temp = huj; 39 | 40 | loop { 41 | let prime = &temp + &j; 42 | if probably_prime(&prime, 10) { 43 | return prime; 44 | } 45 | j += BigUint::from(1u32); 46 | } 47 | } -------------------------------------------------------------------------------- /crates/ces-pois/src/expanders/generate_expanders.rs: -------------------------------------------------------------------------------- 1 | use sha2::{Digest, Sha512}; 2 | 3 | use super::{Expanders, Node, NodeType}; 4 | 5 | pub fn construct_stacked_expanders(k: i64, n: i64, d: i64) -> Expanders { 6 | Expanders::new(k, n, d) 7 | } 8 | 9 | pub fn calc_parents(expanders: &Expanders, node: &mut Node, miner_id: &[u8], count: i64, rlayer: i64) { 10 | if node.parents.capacity() != (expanders.d + 1) as usize { 11 | return; 12 | } 13 | 14 | let layer = node.index as i64 / expanders.n; 15 | if layer == 0 { 16 | return; 17 | } 18 | 19 | let group_size = expanders.n / expanders.d; 20 | let offset = group_size / 256; 21 | 22 | let mut hasher = Sha512::new(); 23 | hasher.update(miner_id); 24 | hasher.update(&count.to_be_bytes()); 25 | hasher.update(&rlayer.to_be_bytes()); 26 | hasher.update((node.index as i64).to_be_bytes()); 27 | 28 | let mut res = hasher.finalize().to_vec(); 29 | 30 | if expanders.d > 64 { 31 | let mut hasher2 = Sha512::new(); 32 | hasher2.update(&res); 33 | let extra = hasher2.finalize().to_vec(); 34 | res.extend_from_slice(&extra); 35 | } 36 | 37 | res.truncate(expanders.d as usize); 38 | 39 | let parent = (node.index - expanders.n as i32) as NodeType; 40 | node.add_parent(parent); 41 | 42 | for (i, &byte_val) in res.iter().enumerate() { 43 | let byte_i64 = byte_val as i64; 44 | let calc_index = (layer - 1) * expanders.n + i as i64 * group_size + byte_i64 * offset + (byte_i64 % offset); 45 | 46 | let index = calc_index as NodeType; 47 | 48 | if index == parent { 49 | node.add_parent(index + 1); 50 | } else if index < parent { 51 | node.add_parent(index + expanders.n as i32); 52 | } else { 53 | node.add_parent(index); 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /crates/ces-pois/src/lib.rs: -------------------------------------------------------------------------------- 1 | pub mod acc; 2 | pub mod expanders; 3 | pub mod pois; 4 | pub mod tree; 5 | pub mod util; -------------------------------------------------------------------------------- /crates/ces-pois/src/pois/challenge.rs: -------------------------------------------------------------------------------- 1 | use crate::expanders::{self, generate_idle_file::get_hash}; 2 | 3 | pub fn new_challenge_handle( 4 | miner_id: &[u8], 5 | tee_id: &[u8], 6 | chal: &[i64], 7 | front: i64, 8 | rear: i64, 9 | proof_num: i64, 10 | ) -> Option bool> { 11 | let bytes_chal = expanders::get_bytes_slice(chal); 12 | let front_size = miner_id.len() + tee_id.len() + bytes_chal.len(); 13 | let mut source = Vec::with_capacity(front_size + 32); 14 | source.extend_from_slice(miner_id); 15 | source.extend_from_slice(tee_id); 16 | source.extend_from_slice(&bytes_chal); 17 | source.extend_from_slice(&[0; 32]); 18 | 19 | let file_num: i64 = 256; 20 | let group_size: i64 = 16; 21 | 22 | let start = front / file_num; 23 | let mut count: i64 = 0; 24 | let total = (rear - front + front % file_num - 1) / (file_num * group_size) + 1; 25 | 26 | if total > proof_num { 27 | return None; 28 | } 29 | 30 | Some(move |prior_hash: &[u8], left: i64, right: i64| -> bool { 31 | if !prior_hash.is_empty() { 32 | source[front_size..].copy_from_slice(prior_hash); 33 | } 34 | let mut max = group_size - 1; 35 | if count == total - 1 { 36 | max = rear / file_num - (start + count * group_size) 37 | } 38 | let hash = get_hash(&source); 39 | let v = expanders::bytes_to_node_value(&hash, max) as i64; 40 | let mut l = (start + count * group_size + v) * file_num + 1; 41 | let r = ((l - 1) / file_num + 1) * file_num + 1; 42 | if l <= front { 43 | l = front + 1; 44 | } 45 | count += 1; 46 | if l != left || r != right { 47 | return false; 48 | } 49 | true 50 | }) 51 | } 52 | -------------------------------------------------------------------------------- /crates/ces-pois/src/pois/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod challenge; 2 | pub mod prove; 3 | pub mod verify; 4 | -------------------------------------------------------------------------------- /crates/ces-sanitized-logger/.rustfmt.toml: -------------------------------------------------------------------------------- 1 | hard_tabs = false -------------------------------------------------------------------------------- /crates/ces-sanitized-logger/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "ces-sanitized-logger" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | [dependencies] 7 | log = { workspace = true } 8 | env_logger = { workspace = true } 9 | tracing-core = { workspace = true } 10 | tracing-subscriber = { workspace = true, features = ["env-filter"] } 11 | -------------------------------------------------------------------------------- /crates/ces-sanitized-logger/src/lib.rs: -------------------------------------------------------------------------------- 1 | use env_logger::Logger; 2 | 3 | pub use logger::init_env_logger; 4 | pub use subscriber::init_subscriber; 5 | 6 | #[cfg(test)] 7 | mod test; 8 | 9 | mod logger; 10 | mod subscriber; 11 | 12 | fn get_env(name: &str, default: T) -> T 13 | where 14 | T: std::str::FromStr, 15 | { 16 | std::env::var(name) 17 | .ok() 18 | .and_then(|v| v.parse().ok()) 19 | .unwrap_or(default) 20 | } 21 | 22 | fn target_allowed(target: &str) -> bool { 23 | use MatchMode::*; 24 | enum MatchMode { 25 | Prefix, 26 | Eq, 27 | } 28 | 29 | // Keep more frequently targets in the front 30 | let whitelist = [ 31 | ("cestory", Prefix), 32 | ("rocket::launch", Prefix), 33 | ("rocket::server", Eq), 34 | ("crpc_measuring", Eq), 35 | ("ces_", Prefix), 36 | ("cess_node_runtime", Prefix), 37 | ("ceseal", Prefix), 38 | ("cestory", Prefix), 39 | ("cestory_api", Prefix), 40 | ]; 41 | for (rule, mode) in whitelist.into_iter() { 42 | match mode { 43 | Prefix => { 44 | if target.starts_with(rule) { 45 | return true; 46 | } 47 | } 48 | Eq => { 49 | if rule == target { 50 | return true; 51 | } 52 | } 53 | } 54 | } 55 | false 56 | } 57 | -------------------------------------------------------------------------------- /crates/ces-sanitized-logger/src/logger.rs: -------------------------------------------------------------------------------- 1 | use super::*; 2 | /// A logger that only allow our codes to print logs 3 | struct SanitizedLogger(Logger); 4 | 5 | pub fn init_env_logger(sanitized: bool) { 6 | let sanitized = crate::get_env("RUST_LOG_SANITIZED", sanitized); 7 | let env = env_logger::Env::default().default_filter_or("info"); 8 | let mut builder = env_logger::Builder::from_env(env); 9 | builder.format_timestamp_micros(); 10 | if sanitized { 11 | let env_logger = builder.build(); 12 | let max_level = env_logger.filter(); 13 | let logger = SanitizedLogger(env_logger); 14 | log::set_boxed_logger(Box::new(logger)).expect("Failed to install sanitized logger"); 15 | log::set_max_level(max_level); 16 | } else { 17 | builder.init(); 18 | } 19 | } 20 | 21 | impl log::Log for SanitizedLogger { 22 | fn enabled(&self, metadata: &log::Metadata) -> bool { 23 | self.0.enabled(metadata) && target_allowed(metadata.target()) 24 | } 25 | 26 | fn log(&self, record: &log::Record) { 27 | if self.enabled(record.metadata()) { 28 | self.0.log(record) 29 | } 30 | } 31 | 32 | fn flush(&self) { 33 | self.0.flush() 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /crates/ces-sanitized-logger/src/test.rs: -------------------------------------------------------------------------------- 1 | use super::*; 2 | 3 | #[test] 4 | fn whitelist_works() { 5 | let allowed: Vec<_> = include_str!("all-log-targets.txt") 6 | .split('\n') 7 | .filter(|t| target_allowed(t)) 8 | .collect(); 9 | assert_eq!( 10 | allowed, 11 | [ 12 | "cestory", 13 | "cestory::benchmark", 14 | "cestory::light_validation", 15 | "cestory::light_validation::justification::communication", 16 | "cestory::crpc_service", 17 | "cestory::storage::storage_ext", 18 | "cestory::system", 19 | "cestory::system::gk", 20 | "cestory::system::master_key", 21 | "cestory_api::storage_sync", 22 | "ces_mq", 23 | "cess_node_runtime", 24 | "crpc_measuring", 25 | "ceseal", 26 | "ceseal::api_server", 27 | "ceseal::ias", 28 | "ceseal::pal_gramine", 29 | "ceseal::runtime", 30 | "rocket::launch", 31 | "rocket::launch_", 32 | "rocket::server", 33 | ] 34 | ); 35 | } 36 | 37 | #[test] 38 | fn see_log() { 39 | use log::info; 40 | 41 | init_env_logger(true); 42 | info!(target: "cestory", "target cestory"); 43 | info!(target: "other", "target other"); 44 | } 45 | -------------------------------------------------------------------------------- /crates/ces-serde-more/.rustfmt.toml: -------------------------------------------------------------------------------- 1 | hard_tabs = false -------------------------------------------------------------------------------- /crates/ces-serde-more/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "ces-serde-more" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | [dependencies] 7 | serde = { workspace = true, features = ["derive", "alloc"] } 8 | sp-core = { workspace = true } 9 | parity-scale-codec = { workspace = true } 10 | hex = { workspace = true, features = ["alloc"] } 11 | # ces-pdp = { workspace = true } 12 | rsa = { workspace = true } 13 | 14 | [features] 15 | default = ["std"] 16 | crypto = ["sp-core/full_crypto"] 17 | std = [ 18 | "sp-core/std", 19 | ] 20 | -------------------------------------------------------------------------------- /crates/ces-serde-more/src/key_bytes.rs: -------------------------------------------------------------------------------- 1 | use alloc::vec::Vec; 2 | use serde::{de, Deserialize, Deserializer, Serialize, Serializer}; 3 | use sp_core::{sr25519, Pair}; 4 | 5 | pub fn serialize(data: &sr25519::Pair, ser: S) -> Result { 6 | let bytes = data.as_ref().secret.to_bytes().to_vec(); 7 | bytes.serialize(ser) 8 | } 9 | 10 | pub fn deserialize<'de, De: Deserializer<'de>>(der: De) -> Result { 11 | let bytes: Vec = Deserialize::deserialize(der)?; 12 | sr25519::Pair::from_seed_slice(&bytes).map_err(|_| de::Error::custom("invalid sr25519 key")) 13 | } 14 | -------------------------------------------------------------------------------- /crates/ces-serde-more/src/lib.rs: -------------------------------------------------------------------------------- 1 | #![no_std] 2 | extern crate alloc; 3 | 4 | pub mod scale_bytes; 5 | 6 | #[cfg(feature = "crypto")] 7 | pub mod key_bytes; 8 | 9 | #[cfg(feature = "crypto")] 10 | pub mod rsa_key_bytes; 11 | 12 | #[cfg(feature = "crypto")] 13 | pub mod option_key_bytes; 14 | 15 | #[cfg(feature = "crypto")] 16 | pub mod pubkey_bytes; 17 | -------------------------------------------------------------------------------- /crates/ces-serde-more/src/option_key_bytes.rs: -------------------------------------------------------------------------------- 1 | use alloc::vec::Vec; 2 | use serde::{de, Deserialize, Deserializer, Serialize, Serializer}; 3 | use sp_core::{sr25519, Pair}; 4 | 5 | pub fn serialize(data: &Option, ser: S) -> Result { 6 | let bytes = data 7 | .as_ref() 8 | .map(|data| data.as_ref().secret.to_bytes().to_vec()); 9 | bytes.serialize(ser) 10 | } 11 | 12 | pub fn deserialize<'de, De: Deserializer<'de>>( 13 | der: De, 14 | ) -> Result, De::Error> { 15 | let bytes: Option> = Deserialize::deserialize(der)?; 16 | bytes 17 | .map(|bytes| { 18 | sr25519::Pair::from_seed_slice(&bytes) 19 | .map_err(|_| de::Error::custom("invalid sr25519 key")) 20 | }) 21 | .transpose() 22 | } 23 | -------------------------------------------------------------------------------- /crates/ces-serde-more/src/pubkey_bytes.rs: -------------------------------------------------------------------------------- 1 | use serde::{Deserialize, Deserializer, Serialize, Serializer}; 2 | use sp_core::sr25519; 3 | 4 | pub fn serialize(data: &sr25519::Public, ser: S) -> Result { 5 | data.0.serialize(ser) 6 | } 7 | 8 | pub fn deserialize<'de, De: Deserializer<'de>>(der: De) -> Result { 9 | let bytes = Deserialize::deserialize(der)?; 10 | Ok(sr25519::Public::from_raw(bytes)) 11 | } 12 | -------------------------------------------------------------------------------- /crates/ces-serde-more/src/rsa_key_bytes.rs: -------------------------------------------------------------------------------- 1 | use alloc::{vec::Vec, string::ToString}; 2 | use serde::{de, Deserialize, Deserializer, Serializer, Serialize}; 3 | use rsa::pkcs8::{EncodePrivateKey, DecodePrivateKey}; 4 | 5 | pub fn serialize(data: &rsa::RsaPrivateKey, ser: S) -> Result { 6 | let bytes = data.to_pkcs8_der().unwrap().as_bytes().to_vec(); 7 | bytes.serialize(ser) 8 | } 9 | 10 | pub fn deserialize<'de, De: Deserializer<'de>>(der: De) -> Result { 11 | let bytes: Vec = Deserialize::deserialize(der)?; 12 | let skey = rsa::RsaPrivateKey::from_pkcs8_der(&bytes).map_err(|e|de::Error::custom(e.to_string()))?; 13 | Ok(skey) 14 | } 15 | -------------------------------------------------------------------------------- /crates/ces-serde-more/src/scale_bytes.rs: -------------------------------------------------------------------------------- 1 | use alloc::vec::Vec; 2 | use serde::{de, Deserialize, Deserializer, Serialize, Serializer}; 3 | use parity_scale_codec::{Encode, Decode}; 4 | 5 | pub fn serialize(data: &T, ser: S) -> Result { 6 | data.encode().serialize(ser) 7 | } 8 | 9 | pub fn deserialize<'de, De: Deserializer<'de>, T: Decode>(der: De) -> Result { 10 | let bytes = >::deserialize(der)?; 11 | T::decode(&mut bytes.as_slice()).map_err(de::Error::custom) 12 | } 13 | -------------------------------------------------------------------------------- /crates/ces-trie-storage/.rustfmt.toml: -------------------------------------------------------------------------------- 1 | hard_tabs = false -------------------------------------------------------------------------------- /crates/ces-trie-storage/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "ces-trie-storage" 3 | version = "0.1.0" 4 | edition = "2021" 5 | authors = ["CESS Network"] 6 | license = "Apache-2.0" 7 | homepage = "https://cess.cloud/" 8 | repository = "https://github.com/CESSProject/cess" 9 | 10 | 11 | [dependencies] 12 | parity-scale-codec = { workspace = true } 13 | scale-info = { workspace = true, features = ["derive"] } 14 | sp-core = { workspace = true, features = ["full_crypto"] } 15 | sp-trie = { workspace = true, features = ["std"] } 16 | sp-state-machine = { workspace = true } 17 | 18 | serde = { workspace = true, features = ["derive", "alloc"], optional = true } 19 | hash-db = { workspace = true } 20 | trie-db = { workspace = true } 21 | im = { workspace = true, features = ["serde"] } 22 | log = { workspace = true } 23 | 24 | 25 | [dev-dependencies] 26 | sp-runtime = { workspace = true, features = ["std"] } 27 | sp-io = { workspace = true, features = ["std"] } 28 | sp-application-crypto = { workspace = true, features = ["std", "full_crypto"] } 29 | hash256-std-hasher = { workspace = true } 30 | hex = { workspace = true } 31 | serde_json = { workspace = true } 32 | impl-serde = { workspace = true } 33 | keccak-hasher = { workspace = true } 34 | 35 | 36 | [features] 37 | default = ["serde"] 38 | -------------------------------------------------------------------------------- /crates/ces-trie-storage/src/ser.rs: -------------------------------------------------------------------------------- 1 | use hash_db::Hasher; 2 | use parity_scale_codec::{Decode, Encode}; 3 | use scale_info::TypeInfo; 4 | use serde::{Deserialize, Serialize}; 5 | 6 | use super::{ChildStorageCollection, StorageCollection}; 7 | 8 | #[derive(Serialize, Deserialize, TypeInfo, Encode, Decode, Clone, Debug, Default)] 9 | #[serde(rename_all = "camelCase", crate = "serde")] 10 | pub struct StorageChanges { 11 | pub main_storage_changes: StorageCollection, 12 | pub child_storage_changes: ChildStorageCollection, 13 | } 14 | 15 | #[derive(Serialize, Deserialize, TypeInfo, Encode, Decode, Clone, Debug)] 16 | #[serde(crate = "serde")] 17 | pub struct StorageData { 18 | pub inner: Vec<(Vec, Vec)>, 19 | } 20 | 21 | pub struct SerAsSeq<'a, H: Hasher>(pub &'a crate::MemoryDB) 22 | where 23 | H::Out: Ord; 24 | 25 | impl Serialize for SerAsSeq<'_, H> 26 | where 27 | H::Out: Ord, 28 | { 29 | fn serialize(&self, serializer: S) -> Result 30 | where 31 | S: serde::Serializer, 32 | { 33 | self.0.serialize(serializer) 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /crates/ces-trie-storage/tests/data/state_roots.txt: -------------------------------------------------------------------------------- 1 | 0x4016d69413ce4eb92e128dbc22aa04bd0f47d60ed89a22ea520cacc8a6db2230 2 | 0x4b59c933276bc9e0f2c8451b1dd5b0ff22895bb70382cebe110568d1845c13fc 3 | 0xa633bedfe0645f0b7939f64da489a39fe1adffd95b06dc00fc65f072fb98216a 4 | 0xaf92477005ca1adbf8dfa8a0fb0b44652ee99f67cf0ac5c9c28f67de92fef63c 5 | 0x0d76edb589743a8aad36e25c38628c2ce8763566c0e1411aef13427d468489e1 6 | 0x85757f52e8ea2a917f3b837264949fe8e2be9c0f46d153185a3648676a475719 7 | 0xe8dd8f7e37763c2fbefb04afa2b52e4d518df83111cf1284673af046817cee9d 8 | 0xe286ee4034559bd4add17568b759a7b6f2c0c592a496a381caad93590ece309d 9 | 0x6fc868c4b74739e4e453b3f09ee1c189a9f06931e9a945511200874a60e6cd5b 10 | 0x214029df04dd83809456274515501a8374746ed85eb0a36f89067ba4dd6f33db 11 | 0x785f5726d4621cf258c47e1405f95e2ef4a8737eb8f7b8a533a11c91e6a73443 12 | 0xf9e833dcd3644779ebb430a6b59116729f86fb7fa294f252cdec636965c24fa2 13 | 0x5954d1d82265002f60d39e27322ff08d4d4136c6a79839ed88c5da3ddb611ef1 14 | 0x0e0fa8f2d74a97e52a84d9467033c8119e4c1f8e90d077afa669220b8cc3367c 15 | 0xf6729b6d5951ef16203ca7a6652d02b61abd7c8bef2602c687fb33bf7f0eb210 16 | 0xc0d0b30e924832f0f84ff73dc03160d138c480653c8dd1a21468c98805e1724b 17 | 0x1d6d4cf14e61901dcbad701a0698cdb2d90422653099448404c86ef139345cdc 18 | 0x54aa29a190b6c157d56f0e3ae7625988df509e189c8b45a0a345c6353a580d00 19 | 0x33e7358dac88b4f0218ac211a317d04367e4b33cc73d20e6e378199f2c273eeb 20 | 0x0bba9e3894eea5d044b9ad47592204879cc57e269655d9c0644c026ba38b20f3 21 | 0x2079231f349843ebd6d0dec0b94257ec911b80fe71ead8a627d331142ae11a98 22 | 0x9db50bc2dbb042d4260f5f317a89a2bd95175df9a9fd1c80c95b89d7702ed96e 23 | 0xcc1c276cfad3e6dcb389970a6e40b35927b881c567cf9287de7edee91c641da5 24 | 0x2580a3d7c2f427ef041f5fe31bb6b94bfee27ca3265cba760950d55f4b2eee15 25 | 0xef442e424a71545b592c06985045b3491b0cac02bee8ff09a97ad2ac750904f5 26 | 0xfed2b3b7ee3f87653114b518f8ab18d2e9b2fc0889d028b36f43f88e8b443fc0 27 | 0x90240687646925e9fd2bb060d41cd4924c031ceef5851580d31f9b71296b4c0b 28 | 0x982b6310e6b93d18f629a1f0ae242ba983e2c717e7cc7f6ec54c3f98eec23bba 29 | 0x319b13aa944b5e907d5a72233e6d07f7152c366f998bd49d91f13b4bc1116e38 30 | 0xf0b215c0dbadd57ef62478e046c1723e179df4a1c0390d805d2c9d1b91616ef9 31 | 0x06647cf9bb58fc1e68410b8a13581d2b946dbce36f1be219ae6a1b8523258b06 -------------------------------------------------------------------------------- /crates/ces-types/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "ces-types" 3 | version = "0.3.0" 4 | authors = ["CESS Network"] 5 | edition = "2021" 6 | 7 | [dependencies] 8 | chrono = { workspace = true } 9 | hex = { workspace = true, features = ["alloc"] } 10 | log ={ workspace = true } 11 | parity-scale-codec = { workspace = true, features = ["full"] } 12 | scale-info = { workspace = true, features = ["derive"] } 13 | serde = { workspace = true, optional = true } 14 | serde_json = { workspace = true, features = ["alloc"] } 15 | sp-core = { workspace = true } 16 | sp-std = { workspace = true } 17 | sp-crypto-hashing = { workspace = true } 18 | 19 | ces-mq = { workspace = true } 20 | sgx-attestation = { workspace = true, features = ["verify"] } 21 | 22 | 23 | [dev-dependencies] 24 | frame-support = { workspace = true, features = ["std"] } 25 | 26 | 27 | [features] 28 | default = ["std", "enable_serde"] 29 | std = [ 30 | "chrono/std", 31 | "serde/std", 32 | "scale-info/std", 33 | "parity-scale-codec/std", 34 | "full_crypto", 35 | "sp-core/std", 36 | "sp-std/std", 37 | "ces-mq/std", 38 | "sgx-attestation/std", 39 | ] 40 | enable_serde = [ 41 | "serde/derive", 42 | "serde/alloc", 43 | "scale-info/serde", 44 | ] 45 | full_crypto = [ 46 | "sp-core/full_crypto", 47 | ] 48 | -------------------------------------------------------------------------------- /crates/cestory/.rustfmt.toml: -------------------------------------------------------------------------------- 1 | # Basic 2 | edition = "2021" 3 | hard_tabs = false 4 | tab_spaces = 4 5 | max_width = 120 6 | use_small_heuristics = "Max" 7 | # Imports 8 | imports_granularity = "Crate" 9 | reorder_imports = true 10 | # Consistency 11 | newline_style = "Unix" 12 | # Format comments 13 | comment_width = 120 14 | wrap_comments = true 15 | # Misc 16 | chain_width = 80 17 | spaces_around_ranges = false 18 | binop_separator = "Back" 19 | reorder_impl_items = false 20 | match_arm_leading_pipes = "Preserve" 21 | match_arm_blocks = false 22 | match_block_trailing_comma = true 23 | trailing_comma = "Vertical" 24 | trailing_semicolon = false 25 | use_field_init_shorthand = true -------------------------------------------------------------------------------- /crates/cestory/api/.gitignore: -------------------------------------------------------------------------------- 1 | /proto_rendered 2 | -------------------------------------------------------------------------------- /crates/cestory/api/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "cestory-api" 3 | version = "0.1.0" 4 | edition = "2021" 5 | resolver = "2" 6 | 7 | [dependencies] 8 | frame-system = { workspace = true } 9 | sp-consensus-grandpa = { workspace = true } 10 | sp-core = { workspace = true, features = ["full_crypto"] } 11 | sp-application-crypto = { workspace = true, features = ["full_crypto"] } 12 | sp-runtime = { workspace = true } 13 | parity-scale-codec = { workspace = true, features = ["derive"] } 14 | scale-info = { workspace = true, features = ["derive"] } 15 | serde = { workspace = true, features = ["derive"] } 16 | serde_json = { workspace = true } 17 | base64 = { workspace = true } 18 | derive_more = { workspace = true, features = ["from_str"] } 19 | prost = { workspace = true } 20 | async-trait = { workspace = true } 21 | anyhow = { workspace = true, optional = true } 22 | log = { workspace = true } 23 | primitive-types = { workspace = true, optional = true } 24 | im = { workspace = true } 25 | tonic = { workspace = true } 26 | 27 | ces-trie-storage = { workspace = true, features = ["serde"] } 28 | ces-types = { workspace = true, features = ["enable_serde", "full_crypto"] } 29 | ces-crypto = { workspace = true } 30 | chain = { workspace = true } 31 | ces-mq = { workspace = true } 32 | 33 | 34 | [dev-dependencies] 35 | insta = "1.13.0" 36 | hex = "0.4.3" 37 | 38 | 39 | [build-dependencies] 40 | tonic-build = { workspace = true, features = ["prost"] } 41 | 42 | 43 | [features] 44 | default = ["std"] 45 | 46 | std = [ 47 | "derive_serde", 48 | "sp-core/full_crypto", 49 | "sp-runtime/std", 50 | "sp-application-crypto/std", 51 | "frame-system/std", 52 | "chain/std", 53 | ] 54 | 55 | sgx = [] 56 | ceseal-client = [ 57 | "anyhow", 58 | ] 59 | 60 | derive_serde = [ 61 | "ces-trie-storage/serde", 62 | "primitive-types/serde", 63 | ] 64 | 65 | only-attestation = [ 66 | "chain/only-attestation" 67 | ] 68 | verify-cesealbin = [ 69 | "chain/verify-cesealbin" 70 | ] -------------------------------------------------------------------------------- /crates/cestory/api/build.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | let mut builder = tonic_build::configure() 3 | .out_dir("./src/proto_generated") 4 | .disable_package_emission() 5 | .build_server(true) 6 | .build_client(false); 7 | 8 | #[cfg(feature = "ceseal-client")] 9 | { 10 | builder = builder.build_client(true); 11 | } 12 | 13 | builder = builder.type_attribute( 14 | ".ceseal_rpc", 15 | "#[derive(::serde::Serialize, ::serde::Deserialize)]", 16 | ); 17 | for name in [ 18 | "AttestationReport", 19 | "InitRuntimeResponse", 20 | "Attestation", 21 | "NetworkConfig", 22 | ] { 23 | builder = builder.type_attribute(name, "#[derive(::scale_info::TypeInfo)]"); 24 | } 25 | builder = builder.field_attribute("InitRuntimeResponse.attestation", "#[serde(skip, default)]"); 26 | for field in [ 27 | "HttpFetch.body", 28 | "HttpFetch.headers", 29 | ] { 30 | builder = builder.field_attribute(field, "#[serde(default)]"); 31 | } 32 | builder 33 | .compile(&["ceseal_rpc.proto"], &["proto"]) 34 | .unwrap(); 35 | 36 | tonic_build::compile_protos("proto/pois-api.proto").unwrap(); 37 | tonic_build::compile_protos("proto/podr2-api.proto").unwrap(); 38 | tonic_build::compile_protos("proto/pubkeys.proto").unwrap(); 39 | } 40 | -------------------------------------------------------------------------------- /crates/cestory/api/proto/pubkeys.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package ceseal.pubkeys; 4 | 5 | // Provide the storage miners with Ceseal's various public key queries 6 | service CesealPubkeysProvider { 7 | // Get the Ceseal identity public key 8 | rpc get_identity_pubkey(Request) returns (IdentityPubkeyResponse) {} 9 | // Get the master public key 10 | rpc get_master_pubkey(Request) returns (MasterPubkeyResponse) {} 11 | // Get the PORD2 public key 12 | rpc get_podr2_pubkey(Request) returns (Podr2PubkeyResponse) {} 13 | } 14 | 15 | message Request { 16 | // The account id that the storage miner registered on the chain 17 | bytes storage_miner_account_id = 1; 18 | } 19 | 20 | message IdentityPubkeyResponse { 21 | // the identity public key 22 | bytes pubkey = 1; 23 | // The timestamp for the processing of the request 24 | int64 timestamp = 2; 25 | // Use the sr25519 algorithm to sign the timestamp fields above (use it's Big-Endian bytes) 26 | bytes signature = 3; 27 | } 28 | 29 | message MasterPubkeyResponse { 30 | // the master public key 31 | bytes pubkey = 1; 32 | // The timestamp for the processing of the request 33 | int64 timestamp = 2; 34 | // Use the sr25519 algorithm to sign the timestamp fields above (use it's Big-Endian bytes) 35 | bytes signature = 3; 36 | } 37 | 38 | message Podr2PubkeyResponse { 39 | // the PODR2 public key 40 | bytes pubkey = 1; 41 | // The timestamp for the processing of the request 42 | int64 timestamp = 2; 43 | // Use the RSA algorithm to sign the timestamp fields above (use it's Big-Endian bytes) 44 | bytes signature = 3; 45 | } -------------------------------------------------------------------------------- /crates/cestory/api/src/crpc.rs: -------------------------------------------------------------------------------- 1 | pub use crate::proto_generated::*; 2 | use alloc::vec::Vec; 3 | use ces_types::messaging::{MessageOrigin, SignedMessage}; 4 | pub type EgressMessages = Vec<(MessageOrigin, Vec)>; 5 | -------------------------------------------------------------------------------- /crates/cestory/api/src/ecall_args.rs: -------------------------------------------------------------------------------- 1 | use alloc::string::String; 2 | use ces_types::WorkerRole; 3 | use core::time::Duration; 4 | use parity_scale_codec::{Decode, Encode}; 5 | 6 | #[derive(Debug, Encode, Decode, Default, Clone)] 7 | pub struct InitArgs { 8 | /// The GK master key sealing path. 9 | pub sealing_path: String, 10 | 11 | /// The Ceseal persistent data storing path 12 | pub storage_path: String, 13 | 14 | /// The App version. 15 | pub version: String, 16 | 17 | /// The git commit hash which this binary was built from. 18 | pub git_revision: String, 19 | 20 | /// Enable checkpoint 21 | pub enable_checkpoint: bool, 22 | 23 | /// Checkpoint interval in seconds 24 | pub checkpoint_interval: u64, 25 | 26 | /// Remove corrupted checkpoint so that ceseal can restart to continue to load others. 27 | pub remove_corrupted_checkpoint: bool, 28 | 29 | /// Max number of checkpoint files kept 30 | pub max_checkpoint_files: u32, 31 | 32 | /// Number of cores used to run ceseal service 33 | pub cores: u32, 34 | 35 | /// Listening IP address of H2 server 36 | pub ip_address: Option, 37 | 38 | /// The public rpc port with acl enabled 39 | pub public_port: Option, 40 | 41 | /// Only sync blocks into ceseal without dispatching messages. 42 | pub safe_mode_level: u8, 43 | 44 | /// Disable the RCU policy to update the Ceseal state. 45 | pub no_rcu: bool, 46 | 47 | /// The timeout of getting the attestation report. 48 | pub ra_timeout: Duration, 49 | 50 | /// The max retry times of getting the attestation report. 51 | pub ra_max_retries: u32, 52 | 53 | /// The type of ceseal's remote attestation method,None means epid. 54 | pub ra_type: Option, 55 | 56 | pub role: WorkerRole, 57 | } -------------------------------------------------------------------------------- /crates/cestory/api/src/lib.rs: -------------------------------------------------------------------------------- 1 | extern crate alloc; 2 | 3 | pub mod blocks; 4 | pub mod crpc; 5 | pub mod crypto; 6 | pub mod ecall_args; 7 | pub mod storage_sync; 8 | 9 | mod proto_generated; 10 | 11 | #[cfg(feature = "ceseal-client")] 12 | pub mod ceseal_client { 13 | use crate::crpc::ceseal_api_client::CesealApiClient; 14 | pub type CesealClient = CesealApiClient; 15 | } 16 | 17 | pub mod pois { 18 | tonic::include_proto!("pois"); 19 | } 20 | 21 | #[allow(non_camel_case_types)] 22 | pub mod podr2 { 23 | tonic::include_proto!("podr2"); 24 | } 25 | 26 | pub mod pubkeys { 27 | tonic::include_proto!("ceseal.pubkeys"); 28 | } -------------------------------------------------------------------------------- /crates/cestory/api/src/proto_generated/.gitignore: -------------------------------------------------------------------------------- 1 | * 2 | 3 | !.gitignore 4 | !mod.rs 5 | !tests.rs 6 | -------------------------------------------------------------------------------- /crates/cestory/api/src/proto_generated/tests.rs: -------------------------------------------------------------------------------- 1 | use super::*; 2 | 3 | #[test] 4 | fn make_sure_do_not_store_attestation() { 5 | // Make sure we don't store the attestation by accident in future refactoring. 6 | let response = InitRuntimeResponse { 7 | attestation: Some(Attestation::default()), 8 | ..Default::default() 9 | }; 10 | let json = serde_json::to_string(&response).unwrap(); 11 | let response: InitRuntimeResponse = serde_json::from_str(&json).unwrap(); 12 | assert_eq!(response.attestation, None); 13 | } 14 | -------------------------------------------------------------------------------- /crates/cestory/api/tests/test_block_abi.rs: -------------------------------------------------------------------------------- 1 | use cestory_api::blocks; 2 | use scale_info::{IntoPortable, PortableRegistry, TypeInfo}; 3 | 4 | fn travel_types() -> String { 5 | let mut registry = Default::default(); 6 | let _ = T::type_info().into_portable(&mut registry); 7 | serde_json::to_string_pretty(&PortableRegistry::from(registry).types).unwrap() 8 | } 9 | 10 | #[test] 11 | fn test_sync_blocks_abi_should_not_change() { 12 | insta::assert_snapshot!(travel_types::()); 13 | insta::assert_snapshot!(travel_types::()); 14 | insta::assert_snapshot!(travel_types::()); 15 | insta::assert_snapshot!(travel_types::()); 16 | } 17 | -------------------------------------------------------------------------------- /crates/cestory/pal/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "cestory-pal" 3 | version = "0.1.0" 4 | edition = "2021" 5 | description = "Platform abstraction layer for Ceseal" 6 | 7 | [dependencies] 8 | anyhow = { workspace = true } 9 | ces-types = { workspace = true, features = ["enable_serde", "full_crypto"] } 10 | cestory-api = { workspace = true } 11 | -------------------------------------------------------------------------------- /crates/cestory/pal/src/lib.rs: -------------------------------------------------------------------------------- 1 | //! Platform abstraction layer for Trusted Execution Environments 2 | 3 | use ces_types::AttestationProvider; 4 | use core::time::Duration; 5 | use std::{fmt::Debug, path::Path}; 6 | 7 | pub use ces_types::attestation::ExtendMeasurement; 8 | pub use cestory_api::crpc::MemoryUsage; 9 | 10 | pub trait ErrorType: Debug + Into {} 11 | impl> ErrorType for T {} 12 | 13 | pub trait Sealing { 14 | type SealError: ErrorType; 15 | type UnsealError: ErrorType; 16 | 17 | fn seal_data(&self, path: impl AsRef, data: &[u8]) -> Result<(), Self::SealError>; 18 | fn unseal_data(&self, path: impl AsRef) -> Result>, Self::UnsealError>; 19 | } 20 | 21 | pub trait RA { 22 | type Error: ErrorType; 23 | fn create_attestation_report( 24 | &self, 25 | provider: Option, 26 | data: &[u8], 27 | timeout: Duration, 28 | ) -> Result, Self::Error>; 29 | fn quote_test(&self, provider: Option) -> Result<(), Self::Error>; 30 | fn mr_enclave(&self) -> Option>; 31 | fn extend_measurement(&self) -> Result; 32 | } 33 | 34 | pub trait MemoryStats { 35 | fn memory_usage(&self) -> MemoryUsage; 36 | } 37 | 38 | pub trait Machine { 39 | fn machine_id(&self) -> Vec; 40 | fn cpu_core_num(&self) -> u32; 41 | fn cpu_feature_level(&self) -> u32; 42 | } 43 | 44 | pub struct AppVersion { 45 | pub major: u32, 46 | pub minor: u32, 47 | pub patch: u32, 48 | } 49 | 50 | pub trait AppInfo { 51 | fn app_version() -> AppVersion; 52 | } 53 | 54 | pub trait Platform: Sealing + RA + Machine + MemoryStats + AppInfo + Clone + Send + 'static {} 55 | impl Platform for T {} 56 | -------------------------------------------------------------------------------- /crates/cestory/src/cryptography/aead.rs: -------------------------------------------------------------------------------- 1 | pub const IV_BYTES: usize = 12; 2 | pub type IV = [u8; IV_BYTES]; 3 | 4 | fn load_key(raw: &[u8]) -> ring::aead::LessSafeKey { 5 | let unbound_key = ring::aead::UnboundKey::new(&ring::aead::AES_256_GCM, raw) 6 | .expect("Failed to load the secret key"); 7 | ring::aead::LessSafeKey::new(unbound_key) 8 | } 9 | 10 | // Encrypts the data in-place and appends a 128bit auth tag 11 | #[allow(dead_code)] 12 | pub fn encrypt(iv: &IV, secret: &[u8], in_out: &mut Vec) { 13 | let nonce = ring::aead::Nonce::assume_unique_for_key(*iv); 14 | let key = load_key(secret); 15 | 16 | key.seal_in_place_append_tag(nonce, ring::aead::Aad::empty(), in_out) 17 | .expect("seal_in_place_separate_tag failed"); 18 | } 19 | 20 | // Decrypts the cipher (with 128 auth tag appended) in-place and returns the message as a slice. 21 | #[allow(dead_code)] 22 | pub fn decrypt<'in_out>(iv: &[u8], secret: &[u8], in_out: &'in_out mut [u8]) -> &'in_out mut [u8] { 23 | let mut iv_arr = [0u8; IV_BYTES]; 24 | iv_arr.copy_from_slice(&iv[..IV_BYTES]); 25 | let key = load_key(secret); 26 | let nonce = ring::aead::Nonce::assume_unique_for_key(iv_arr); 27 | 28 | key.open_in_place(nonce, ring::aead::Aad::empty(), in_out) 29 | .expect("open_in_place failed") 30 | } 31 | 32 | // TODO: handle error 33 | -------------------------------------------------------------------------------- /crates/cestory/src/cryptography/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod aead; 2 | -------------------------------------------------------------------------------- /crates/cestory/src/light_validation/error.rs: -------------------------------------------------------------------------------- 1 | use derive_more::{Display, From}; 2 | 3 | /// Substrate Client error 4 | #[derive(Debug, Display, From)] 5 | #[allow(dead_code)] 6 | pub enum JustificationError { 7 | /// Error decoding header justification. 8 | #[display("error decoding justification for header")] 9 | JustificationDecode, 10 | /// Justification for header is correctly encoded, but invalid. 11 | #[display("bad justification for header: {_0}")] 12 | #[from(ignore)] 13 | BadJustification(String), 14 | } 15 | -------------------------------------------------------------------------------- /crates/cestory/src/light_validation/types.rs: -------------------------------------------------------------------------------- 1 | pub use cestory_api::blocks::{find_scheduled_change, AuthoritySet}; 2 | 3 | pub type BlockHeader = sp_runtime::generic::Header; 4 | -------------------------------------------------------------------------------- /crates/cestory/src/podr2/proxy.rs: -------------------------------------------------------------------------------- 1 | use std::pin::Pin; 2 | 3 | use super::Podr2Result; 4 | use crate::expert::{CesealExpertStub, ExternalResourceKind}; 5 | use cestory_api::podr2::{ 6 | podr2_api_server::Podr2Api, podr2_verifier_api_server::Podr2VerifierApi, EchoMessage, RequestAggregateSignature, 7 | RequestBatchVerify, RequestGenTag, ResponseAggregateSignature, ResponseBatchVerify, ResponseGenTag, 8 | }; 9 | use tokio_stream::Stream; 10 | use tonic::{Request, Response, Status, Streaming}; 11 | pub(crate) type ResponseStream = Pin> + Send>>; 12 | 13 | pub struct Podr2ApiServerProxy { 14 | pub(crate) inner: Svc, 15 | pub(crate) ceseal_expert: CesealExpertStub, 16 | } 17 | 18 | #[tonic::async_trait] 19 | impl Podr2Api for Podr2ApiServerProxy 20 | where 21 | Svc: Podr2Api, 22 | { 23 | #[allow(non_camel_case_types)] 24 | type request_gen_tagStream = ResponseStream; 25 | async fn request_gen_tag( 26 | &self, 27 | request: Request>, 28 | ) -> Podr2Result { 29 | let _permit = self 30 | .ceseal_expert 31 | .try_acquire_permit(ExternalResourceKind::Pord2Service) 32 | .await?; 33 | match self.inner.request_gen_tag(request).await { 34 | Ok(result) => { 35 | let a = result.into_inner(); 36 | Ok(Response::new(Box::pin(a) as Self::request_gen_tagStream)) 37 | }, 38 | Err(fail) => Err(fail), 39 | } 40 | } 41 | 42 | async fn echo(&self, request: Request) -> Podr2Result { 43 | self.inner.echo(request).await 44 | } 45 | } 46 | 47 | pub struct Podr2VerifierApiServerProxy { 48 | pub(crate) inner: Svc, 49 | pub(crate) ceseal_expert: CesealExpertStub, 50 | } 51 | 52 | #[tonic::async_trait] 53 | impl Podr2VerifierApi for Podr2VerifierApiServerProxy 54 | where 55 | Svc: Podr2VerifierApi, 56 | { 57 | async fn request_batch_verify(&self, request: Request) -> Podr2Result { 58 | let _permit = self 59 | .ceseal_expert 60 | .try_acquire_permit(ExternalResourceKind::Pord2Service) 61 | .await?; 62 | self.inner.request_batch_verify(request).await 63 | } 64 | async fn request_aggregate_signature( 65 | &self, 66 | request: Request, 67 | ) -> Podr2Result { 68 | self.inner.request_aggregate_signature(request).await 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /crates/cestory/tests/snapshots/test_serde__versioning_ciborium.snap: -------------------------------------------------------------------------------- 1 | --- 2 | source: crates/cestory/tests/test_serde.rs 3 | expression: de 4 | 5 | --- 6 | Ok( 7 | V1 { 8 | a: 42, 9 | c: 0, 10 | b: 24, 11 | }, 12 | ) 13 | -------------------------------------------------------------------------------- /crates/cestory/tests/snapshots/test_serde__versioning_rmp_serde.snap: -------------------------------------------------------------------------------- 1 | --- 2 | source: crates/cestory/tests/test_serde.rs 3 | expression: de 4 | 5 | --- 6 | Err( 7 | Syntax( 8 | "invalid length 2, expected struct V1 with 3 elements", 9 | ), 10 | ) 11 | -------------------------------------------------------------------------------- /crates/cestory/tests/snapshots/test_serde__versioning_serde_cbor.snap: -------------------------------------------------------------------------------- 1 | --- 2 | source: crates/cestory/tests/test_serde.rs 3 | expression: de 4 | 5 | --- 6 | Ok( 7 | V1 { 8 | a: 42, 9 | c: 0, 10 | b: 24, 11 | }, 12 | ) 13 | -------------------------------------------------------------------------------- /crates/cestory/tests/test_podr2.rs: -------------------------------------------------------------------------------- 1 | use cestory_api::podr2::{podr2_api_client::Podr2ApiClient, EchoMessage}; 2 | use tonic::Request; 3 | 4 | #[tokio::test] 5 | async fn test_echo() { 6 | let mut client = Podr2ApiClient::connect("http://127.0.0.1:19999").await.unwrap(); 7 | let resp = client 8 | .echo(Request::new(EchoMessage { echo_msg: vec![60, 61, 62] })) 9 | .await 10 | .unwrap(); 11 | // assert!(resp); 12 | println!("response: {:?}", resp); 13 | } 14 | -------------------------------------------------------------------------------- /crates/cestory/tests/test_pois.rs: -------------------------------------------------------------------------------- 1 | use cestory_api::pois::{pois_certifier_api_client::PoisCertifierApiClient, RequestMinerInitParam}; 2 | use sp_core::{crypto::AccountId32, ByteArray}; 3 | use std::str::FromStr; 4 | use tonic::Request; 5 | 6 | #[tokio::test] 7 | async fn get_pois_key_with_no_exist_miner() { 8 | let miner_id = AccountId32::from_str("cXjEPD6CAnjupMaRrxq9AEKCA3HRCumSxkSxWVKcL3pMeEyFi").unwrap(); 9 | let mut client = PoisCertifierApiClient::connect("http://127.0.0.1:19999").await.unwrap(); 10 | let result = client 11 | .request_miner_get_new_key(Request::new(RequestMinerInitParam { miner_id: miner_id.to_raw_vec() })) 12 | .await; 13 | // println!("response: {:?}", result); 14 | assert!(result.is_err()); 15 | if let Err(e) = result { 16 | assert_eq!("the miner not exists", e.message()); 17 | } else { 18 | panic!("use a exist miner account id") 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /crates/cestory/tests/test_pubkeys.rs: -------------------------------------------------------------------------------- 1 | use cestory_api::pubkeys::{ceseal_pubkeys_provider_client::CesealPubkeysProviderClient, Request as InnerReq}; 2 | use sp_core::{crypto::AccountId32, ByteArray}; 3 | use std::str::FromStr; 4 | use tonic::Request; 5 | 6 | #[tokio::test] 7 | async fn fetch_pubkeys() { 8 | let miner_id = AccountId32::from_str("cXjEPD6CAnjupMaRrxq9AEKCA3HRCumSxkSxWVKcL3pMeEyFi").unwrap(); 9 | let mut client = CesealPubkeysProviderClient::connect("http://45.195.74.39:19999").await.unwrap(); 10 | 11 | { 12 | let resp = client 13 | .get_identity_pubkey(Request::new(InnerReq { storage_miner_account_id: miner_id.to_raw_vec() })) 14 | .await 15 | .expect("identity key must be fetch"); 16 | // assert!(resp); 17 | println!("identity pubkey response: {resp:?}"); 18 | } 19 | 20 | { 21 | let resp = client 22 | .get_master_pubkey(Request::new(InnerReq { storage_miner_account_id: miner_id.to_raw_vec() })) 23 | .await 24 | .expect("master pubkey must be fetch"); 25 | println!("master pubkey response: {resp:?}"); 26 | } 27 | 28 | { 29 | let resp = client 30 | .get_podr2_pubkey(Request::new(InnerReq { storage_miner_account_id: miner_id.to_raw_vec() })) 31 | .await 32 | .expect("podr2 pubkey must be fetch"); 33 | println!("podr2 pubkey response: {resp:?}"); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /crates/cestory/tests/test_serde.rs: -------------------------------------------------------------------------------- 1 | use serde::{Deserialize, Serialize}; 2 | 3 | #[derive(Serialize, Deserialize, Debug)] 4 | struct V0 { 5 | a: u32, 6 | b: u32, 7 | } 8 | 9 | #[derive(Serialize, Deserialize, Debug)] 10 | struct V1 { 11 | a: u32, 12 | #[serde(default)] 13 | c: u32, 14 | b: u32, 15 | } 16 | 17 | #[test] 18 | fn test_versioning_rmp_serde() { 19 | let a = V0 { a: 42, b: 24 }; 20 | 21 | let buf = rmp_serde::to_vec(&a).unwrap(); 22 | let de: Result = rmp_serde::from_slice(&buf); 23 | insta::assert_debug_snapshot!(de); 24 | } 25 | 26 | #[test] 27 | fn test_versioning_serde_cbor() { 28 | let a = V0 { a: 42, b: 24 }; 29 | 30 | let buf = serde_cbor::to_vec(&a).unwrap(); 31 | let de: Result = serde_cbor::from_slice(&buf); 32 | insta::assert_debug_snapshot!(de); 33 | } 34 | 35 | #[test] 36 | fn test_versioning_ciborium() { 37 | let a = V0 { a: 42, b: 24 }; 38 | 39 | let mut buf = Vec::new(); 40 | ciborium::ser::into_writer(&a, &mut buf).unwrap(); 41 | let de: Result = ciborium::de::from_reader(&*buf); 42 | insta::assert_debug_snapshot!(de); 43 | } 44 | -------------------------------------------------------------------------------- /crates/cesxt/.rustfmt.toml: -------------------------------------------------------------------------------- 1 | hard_tabs = false -------------------------------------------------------------------------------- /crates/cesxt/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "cesxt" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | [dependencies] 7 | serde = { workspace = true, features = ["derive"] } 8 | serde_json = { workspace = true } 9 | parity-scale-codec = { workspace = true } 10 | scale-info = { workspace = true } 11 | scale-encode = { workspace = true } 12 | anyhow = { workspace = true } 13 | tokio = { workspace = true } 14 | 15 | subxt = { workspace = true, features = ["jsonrpsee", "native"] } 16 | jsonrpsee = { workspace = true } 17 | primitive-types = { workspace = true, default-features = true } 18 | sp-core = { workspace = true, default-features = true } 19 | sp-runtime = { workspace = true, default-features = true } 20 | 21 | ces-types = { workspace = true, default-features = true } 22 | ces-node-rpc-ext-types = { workspace = true, default-features = true } 23 | -------------------------------------------------------------------------------- /crates/cesxt/src/dynamic.rs: -------------------------------------------------------------------------------- 1 | pub mod tx; 2 | 3 | use subxt::dynamic::{self, Value}; 4 | 5 | pub fn storage_key(pallet: &str, entry: &str) -> Vec { 6 | dynamic::storage(pallet, entry, Vec::::new()).to_root_bytes() 7 | } 8 | -------------------------------------------------------------------------------- /crates/cesxt/src/dynamic/tx.rs: -------------------------------------------------------------------------------- 1 | use ces_types::messaging::SignedMessage; 2 | use parity_scale_codec::Encode; 3 | use subxt::{ext::subxt_core::Error as SubxtCoreError, tx::Payload, utils::Encoded}; 4 | 5 | #[derive(Clone, Debug, Eq, PartialEq)] 6 | pub struct EncodedPayload { 7 | pallet_name: &'static str, 8 | call_name: &'static str, 9 | call_data: Encoded, 10 | } 11 | 12 | impl EncodedPayload { 13 | pub fn new(pallet_name: &'static str, call_name: &'static str, call_data: Vec) -> Self { 14 | Self { 15 | pallet_name, 16 | call_name, 17 | call_data: Encoded(call_data), 18 | } 19 | } 20 | } 21 | 22 | impl Payload for EncodedPayload { 23 | fn encode_call_data_to( 24 | &self, 25 | metadata: &subxt::Metadata, 26 | out: &mut Vec, 27 | ) -> Result<(), SubxtCoreError> { 28 | let pallet = metadata.pallet_by_name_err(self.pallet_name)?; 29 | let call = pallet.call_variant_by_name(self.call_name).ok_or_else(|| { 30 | subxt::error::MetadataError::CallNameNotFound((*self.call_name).to_owned()) 31 | })?; 32 | 33 | let pallet_index = pallet.index(); 34 | let call_index = call.index; 35 | 36 | pallet_index.encode_to(out); 37 | call_index.encode_to(out); 38 | self.call_data.encode_to(out); 39 | Ok(()) 40 | } 41 | } 42 | 43 | pub fn register_worker(ceseal_info: Vec, attestation: Vec, v2: bool) -> EncodedPayload { 44 | let call_name = if v2 { 45 | "register_worker_v2" 46 | } else { 47 | "register_worker" 48 | }; 49 | EncodedPayload::new( 50 | "TeeWorker", 51 | call_name, 52 | (Encoded(ceseal_info), Encoded(attestation)).encode(), 53 | ) 54 | } 55 | 56 | pub fn refresh_tee_status(ceseal_info: Vec, attestation: Vec) -> EncodedPayload { 57 | EncodedPayload::new( 58 | "TeeWorker", 59 | "refresh_tee_status", 60 | (Encoded(ceseal_info), Encoded(attestation)).encode(), 61 | ) 62 | } 63 | 64 | pub fn update_worker_endpoint(signed_endpoint: Vec, signature: Vec) -> EncodedPayload { 65 | let args = (Encoded(signed_endpoint), signature).encode(); 66 | EncodedPayload::new("TeeWorker", "update_worker_endpoint", args) 67 | } 68 | 69 | pub fn apply_master_key(signed_payload: Vec, signature: Vec) -> EncodedPayload { 70 | let args = (Encoded(signed_payload), signature).encode(); 71 | EncodedPayload::new("TeeWorker", "apply_master_key", args) 72 | } 73 | 74 | pub fn sync_offchain_message(message: SignedMessage) -> EncodedPayload { 75 | let args = message.encode(); 76 | EncodedPayload::new("CesMq", "sync_offchain_message", args) 77 | } 78 | -------------------------------------------------------------------------------- /crates/common/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "cp-cess-common" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | [dependencies] 7 | log = { workspace = true } 8 | codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive", "max-encoded-len"] } 9 | scale-info = { workspace = true, features = ["derive"] } 10 | 11 | frame-support = { workspace = true } 12 | sp-std = { workspace = true } 13 | sp-core = { workspace = true } 14 | 15 | 16 | [features] 17 | default = ["std"] 18 | std = [ 19 | "codec/std", 20 | "scale-info/std", 21 | "frame-support/std", 22 | "sp-std/std", 23 | ] 24 | -------------------------------------------------------------------------------- /crates/enclave-verify/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "cp-enclave-verify" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | [dependencies] 7 | rsa = { workspace = true } 8 | 9 | [dev-dependencies] 10 | hex = { workspace = true, features = ['alloc'] } 11 | 12 | [features] 13 | default = ["std"] 14 | std = [] 15 | -------------------------------------------------------------------------------- /crates/reqwest-env-proxy/.rustfmt copy.toml: -------------------------------------------------------------------------------- 1 | hard_tabs = false -------------------------------------------------------------------------------- /crates/reqwest-env-proxy/.rustfmt.toml: -------------------------------------------------------------------------------- 1 | hard_tabs = false -------------------------------------------------------------------------------- /crates/reqwest-env-proxy/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | description = "Helper to let reqwest use proxy from the env `all_proxy`" 3 | name = "reqwest-env-proxy" 4 | version = "0.1.0" 5 | edition = "2021" 6 | license = "Apache-2.0" 7 | repository = "" 8 | 9 | [dependencies] 10 | reqwest = { workspace = true, features = [] } 11 | 12 | [features] 13 | default = ["blocking"] 14 | blocking = ["reqwest/blocking"] 15 | -------------------------------------------------------------------------------- /crates/reqwest-env-proxy/src/lib.rs: -------------------------------------------------------------------------------- 1 | use reqwest::Proxy; 2 | 3 | pub trait EnvProxyBuilder { 4 | fn env_proxy(self, domain: &str) -> Self; 5 | } 6 | 7 | fn proxies_from_env(domain: &str) -> Option<(Proxy, Proxy)> { 8 | let uri = if domain.ends_with(".i2p") { 9 | std::env::var("i2p_proxy").ok() 10 | } else { 11 | None 12 | }; 13 | 14 | let uri = uri.or_else(|| std::env::var("all_proxy").ok())?; 15 | 16 | let http_proxy = Proxy::http(&uri).ok()?; 17 | let https_proxy = Proxy::https(&uri).ok()?; 18 | Some((http_proxy, https_proxy)) 19 | } 20 | 21 | impl EnvProxyBuilder for reqwest::ClientBuilder { 22 | fn env_proxy(self, domain: &str) -> Self { 23 | match proxies_from_env(domain) { 24 | Some((http_proxy, https_proxy)) => self.proxy(http_proxy).proxy(https_proxy), 25 | None => self, 26 | } 27 | } 28 | } 29 | 30 | #[cfg(feature = "blocking")] 31 | impl EnvProxyBuilder for reqwest::blocking::ClientBuilder { 32 | fn env_proxy(self, domain: &str) -> Self { 33 | match proxies_from_env(domain) { 34 | Some((http_proxy, https_proxy)) => self.proxy(http_proxy).proxy(https_proxy), 35 | None => self, 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /crates/rrsc/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "cessc-consensus-rrsc" 3 | version = "0.10.0-dev" 4 | authors = ["CESS"] 5 | description = "RRSC consensus algorithm" 6 | edition = "2021" 7 | license = "GPL-3.0-or-later WITH Classpath-exception-2.0" 8 | homepage = "https://cess.one" 9 | repository = "https://github.com/CESSProject/substrate" 10 | readme = "README.md" 11 | 12 | [package.metadata.docs.rs] 13 | targets = ["x86_64-unknown-linux-gnu"] 14 | 15 | [dependencies] 16 | async-trait = { workspace = true } 17 | scale-info = { workspace = true, features = ["derive"] } 18 | codec = { workspace = true, default-features = true, features = ["derive"] } 19 | futures = { workspace = true } 20 | log = { workspace = true } 21 | num-bigint = { workspace = true } 22 | num-rational = { workspace = true } 23 | num-traits = { workspace = true } 24 | parking_lot = { workspace = true } 25 | thiserror = { workspace = true } 26 | fork-tree = { workspace = true } 27 | prometheus-endpoint = { workspace = true } 28 | sc-client-api = { workspace = true } 29 | sc-consensus = { workspace = true } 30 | sc-consensus-epochs = { workspace = true } 31 | sc-consensus-slots = { workspace = true } 32 | sp-crypto-hashing = { workspace = true, default-features = true } 33 | sc-keystore = { workspace = true } 34 | sc-telemetry = { workspace = true } 35 | sc-transaction-pool-api = { workspace = true } 36 | sp-api = { workspace = true, default-features = true } 37 | sp-application-crypto = { workspace = true, default-features = true } 38 | sp-block-builder = { workspace = true, default-features = true } 39 | sp-blockchain = { workspace = true, default-features = true } 40 | sp-consensus = { workspace = true, default-features = true } 41 | sp-consensus-slots = { workspace = true, default-features = true } 42 | sp-core = { workspace = true, default-features = true } 43 | sp-inherents = { workspace = true, default-features = true } 44 | sp-keystore = { workspace = true, default-features = true } 45 | sp-runtime = { workspace = true, default-features = true } 46 | cessp-consensus-rrsc = { workspace = true, default-features = true } 47 | 48 | [dev-dependencies] 49 | rand_chacha = { workspace = true } 50 | sc-block-builder = { workspace = true } 51 | sp-keyring = { workspace = true } 52 | sc-network = { workspace = true } 53 | sc-network-test = { workspace = true } 54 | sp-timestamp = { workspace = true } 55 | sp-tracing = { workspace = true } 56 | substrate-test-runtime-client = { workspace = true } 57 | tokio = { workspace = true } 58 | -------------------------------------------------------------------------------- /crates/rrsc/pallet/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "pallet-rrsc" 3 | version = "38.0.0" 4 | authors = ["CESS"] 5 | edition = "2021" 6 | license = "Apache-2.0" 7 | homepage = "https://cess.one" 8 | repository = "https://github.com/CESSProject/substrate/" 9 | description = "Consensus extension module for RRSC consensus. Collects on-chain randomness from VRF outputs and manages epoch transitions." 10 | readme = "README.md" 11 | 12 | [package.metadata.docs.rs] 13 | targets = ["x86_64-unknown-linux-gnu"] 14 | 15 | [dependencies] 16 | codec = { workspace = true, default-features = false, features = ["derive"] } 17 | log = { workspace = true } 18 | scale-info = { workspace = true, features = ["derive", "serde"] } 19 | frame-benchmarking = { workspace = true, optional = true } 20 | frame-support = { workspace = true } 21 | frame-system = { workspace = true } 22 | pallet-authorship = { workspace = true } 23 | pallet-session = { workspace = true } 24 | pallet-timestamp = { workspace = true } 25 | sp-application-crypto = { workspace = true, features = ["serde"] } 26 | sp-core = { workspace = true, features = ["serde"] } 27 | sp-io = { workspace = true } 28 | sp-npos-elections = { workspace = true } 29 | sp-runtime = { workspace = true, features = ["serde"] } 30 | sp-session = { workspace = true } 31 | sp-staking = { workspace = true, features = ["serde"] } 32 | sp-std = { workspace = true } 33 | frame-election-provider-support = { workspace = true } 34 | cessp-consensus-rrsc = { workspace = true, features = ["serde"] } 35 | 36 | [dev-dependencies] 37 | frame-election-provider-support = { workspace = true, default-features = true } 38 | pallet-balances = { workspace = true, default-features = true } 39 | pallet-offences = { workspace = true, default-features = true } 40 | pallet-staking = { workspace = true, default-features = true } 41 | pallet-staking-reward-curve = { workspace = true, default-features = true } 42 | sp-core = { workspace = true, default-features = true } 43 | 44 | [features] 45 | default = ["std"] 46 | std = [ 47 | "codec/std", 48 | "frame-benchmarking?/std", 49 | "frame-support/std", 50 | "frame-system/std", 51 | "log/std", 52 | "pallet-authorship/std", 53 | "pallet-session/std", 54 | "pallet-timestamp/std", 55 | "scale-info/std", 56 | "sp-application-crypto/std", 57 | "cessp-consensus-rrsc/std", 58 | "sp-core/std", 59 | "sp-io/std", 60 | "sp-runtime/std", 61 | "sp-session/std", 62 | "sp-staking/std", 63 | "sp-std/std", 64 | "sp-npos-elections/std", 65 | "frame-election-provider-support/std", 66 | ] 67 | runtime-benchmarks = ["frame-benchmarking/runtime-benchmarks"] 68 | try-runtime = ["frame-support/try-runtime"] 69 | -------------------------------------------------------------------------------- /crates/rrsc/pallet/README.md: -------------------------------------------------------------------------------- 1 | Consensus extension module for BABE consensus. Collects on-chain randomness 2 | from VRF outputs and manages epoch transitions. 3 | 4 | License: Apache-2.0 -------------------------------------------------------------------------------- /crates/rrsc/pallet/src/default_weights.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Substrate. 2 | 3 | // Copyright (C) Parity Technologies (UK) Ltd. 4 | // SPDX-License-Identifier: Apache-2.0 5 | 6 | // Licensed under the Apache License, Version 2.0 (the "License"); 7 | // you may not use this file except in compliance with the License. 8 | // You may obtain a copy of the License at 9 | // 10 | // http://www.apache.org/licenses/LICENSE-2.0 11 | // 12 | // Unless required by applicable law or agreed to in writing, software 13 | // distributed under the License is distributed on an "AS IS" BASIS, 14 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | // See the License for the specific language governing permissions and 16 | // limitations under the License. 17 | 18 | //! Default weights for the RRSC Pallet 19 | //! This file was not auto-generated. 20 | 21 | use frame_support::weights::{ 22 | constants::{RocksDbWeight as DbWeight, WEIGHT_REF_TIME_PER_MICROS, WEIGHT_REF_TIME_PER_NANOS}, 23 | Weight, 24 | }; 25 | 26 | impl crate::WeightInfo for () { 27 | fn plan_config_change() -> Weight { 28 | DbWeight::get().writes(1) 29 | } 30 | 31 | fn report_equivocation(validator_count: u32, max_nominators_per_validator: u32) -> Weight { 32 | // we take the validator set count from the membership proof to 33 | // calculate the weight but we set a floor of 100 validators. 34 | let validator_count = validator_count.max(100) as u64; 35 | 36 | // checking membership proof 37 | Weight::from_parts(35u64 * WEIGHT_REF_TIME_PER_MICROS, 0) 38 | .saturating_add( 39 | Weight::from_parts(175u64 * WEIGHT_REF_TIME_PER_NANOS, 0) 40 | .saturating_mul(validator_count), 41 | ) 42 | .saturating_add(DbWeight::get().reads(5)) 43 | // check equivocation proof 44 | .saturating_add(Weight::from_parts(110u64 * WEIGHT_REF_TIME_PER_MICROS, 0)) 45 | // report offence 46 | .saturating_add(Weight::from_parts(110u64 * WEIGHT_REF_TIME_PER_MICROS, 0)) 47 | .saturating_add(Weight::from_parts( 48 | 25u64 * WEIGHT_REF_TIME_PER_MICROS * max_nominators_per_validator as u64, 49 | 0, 50 | )) 51 | .saturating_add(DbWeight::get().reads(14 + 3 * max_nominators_per_validator as u64)) 52 | .saturating_add(DbWeight::get().writes(10 + 3 * max_nominators_per_validator as u64)) 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /crates/rrsc/primitives/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "cessp-consensus-rrsc" 3 | version = "0.10.0-dev" 4 | authors = ["CESS"] 5 | description = "Primitives for RRSC consensus" 6 | edition = "2021" 7 | license = "Apache-2.0" 8 | homepage = "https://cess.one" 9 | repository = "https://github.com/CESSProject/substrate" 10 | readme = "README.md" 11 | 12 | [package.metadata.docs.rs] 13 | targets = ["x86_64-unknown-linux-gnu"] 14 | 15 | [dependencies] 16 | async-trait = { workspace = true, optional = true } 17 | codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false } 18 | scale-info = { workspace = true, features = ["derive"] } 19 | serde = { workspace = true, features = ["derive", "alloc"], optional = true } 20 | sp-api = { workspace = true } 21 | sp-application-crypto = { workspace = true } 22 | sp-consensus-slots = { workspace = true } 23 | sp-core = { workspace = true } 24 | sp-inherents = { workspace = true } 25 | sp-runtime = { workspace = true } 26 | sp-std = { workspace = true } 27 | sp-timestamp = { workspace = true, optional = true } 28 | 29 | [features] 30 | default = [ "std" ] 31 | std = [ 32 | "async-trait", 33 | "codec/std", 34 | "scale-info/std", 35 | "serde/std", 36 | "sp-api/std", 37 | "sp-application-crypto/std", 38 | "sp-consensus-slots/std", 39 | "sp-core/std", 40 | "sp-inherents/std", 41 | "sp-runtime/std", 42 | "sp-std/std", 43 | "sp-timestamp/std", 44 | ] 45 | 46 | # Serde support without relying on std features. 47 | serde = [ 48 | "dep:serde", 49 | "scale-info/serde", 50 | "sp-application-crypto/serde", 51 | "sp-consensus-slots/serde", 52 | "sp-core/serde", 53 | "sp-runtime/serde", 54 | ] 55 | -------------------------------------------------------------------------------- /crates/rrsc/primitives/README.md: -------------------------------------------------------------------------------- 1 | Primitives for RRSC. 2 | 3 | License: Apache-2.0 4 | -------------------------------------------------------------------------------- /crates/rrsc/primitives/src/traits.rs: -------------------------------------------------------------------------------- 1 | //! Traits for dealing with validation and validators. 2 | use sp_std::{collections::btree_map::BTreeMap}; 3 | 4 | /// Trait used to retrieve credits of validators. 5 | pub trait ValidatorCredits { 6 | /// Returns the full score. 7 | fn full_credit() -> u32; 8 | 9 | /// Returns the credits of all validators when `epoch_index`. 10 | fn credits(epoch_index: u64) -> BTreeMap; 11 | } 12 | 13 | impl ValidatorCredits for () { 14 | fn full_credit()-> u32 { 15 | 1000 16 | } 17 | 18 | fn credits(_epoch_index: u64) -> BTreeMap { 19 | BTreeMap::new() 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /crates/rrsc/rpc/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "cessc-consensus-rrsc-rpc" 3 | version = "0.10.0-dev" 4 | authors = ["CESS"] 5 | description = "RPC extensions for the RRSC consensus algorithm" 6 | edition = "2021" 7 | license = "GPL-3.0-or-later WITH Classpath-exception-2.0" 8 | homepage = "https://cess.one" 9 | repository = "https://github.com/CESSProject/substrate" 10 | readme = "README.md" 11 | 12 | [package.metadata.docs.rs] 13 | targets = ["x86_64-unknown-linux-gnu"] 14 | 15 | [dependencies] 16 | jsonrpsee = { workspace = true, features = ["client-core", "server", "macros"] } 17 | futures = { workspace = true } 18 | serde = { workspace = true, features = ["derive"] } 19 | thiserror = { workspace = true } 20 | sc-consensus-epochs = { workspace = true } 21 | sc-rpc-api = { workspace = true } 22 | sp-api = { workspace = true } 23 | sp-application-crypto = { workspace = true } 24 | sp-blockchain = { workspace = true } 25 | sp-consensus = { workspace = true } 26 | sp-core = { workspace = true } 27 | sp-keystore = { workspace = true } 28 | sp-runtime = { workspace = true } 29 | cessc-consensus-rrsc = { workspace = true } 30 | cessp-consensus-rrsc = { workspace = true, features = ["std"] } 31 | 32 | [dev-dependencies] 33 | serde_json = { workspace = true } 34 | tokio = { workspace = true } 35 | sc-consensus = { workspace = true } 36 | sc-keystore = { workspace = true } 37 | sc-transaction-pool-api = { workspace = true } 38 | sp-keyring = { workspace = true } 39 | substrate-test-runtime-client = { workspace = true } 40 | -------------------------------------------------------------------------------- /crates/rrsc/rpc/README.md: -------------------------------------------------------------------------------- 1 | RPC api for rrsc. 2 | 3 | License: GPL-3.0-or-later WITH Classpath-exception-2.0 4 | -------------------------------------------------------------------------------- /crates/rrsc/sync-state/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "cessc-sync-state-rpc" 3 | version = "0.10.0-dev" 4 | authors = ["Parity Technologies "] 5 | description = "A RPC handler to create sync states for light clients." 6 | edition = "2021" 7 | license = "Apache-2.0" 8 | homepage = "https://substrate.io" 9 | repository = "https://github.com/paritytech/substrate/" 10 | 11 | [package.metadata.docs.rs] 12 | targets = ["x86_64-unknown-linux-gnu"] 13 | 14 | [dependencies] 15 | codec = { workspace = true, default-features = true } 16 | jsonrpsee = { workspace = true, features = ["client-core", "server", "macros"] } 17 | serde = { workspace = true, features = ["derive"] } 18 | serde_json = { workspace = true } 19 | thiserror = { workspace = true } 20 | sc-chain-spec = { workspace = true } 21 | sc-client-api = { workspace = true } 22 | cessc-consensus-rrsc = { workspace = true } 23 | sc-consensus-epochs = { workspace = true } 24 | sc-consensus-grandpa = { workspace = true } 25 | sp-blockchain = { workspace = true } 26 | sp-runtime = { workspace = true } 27 | -------------------------------------------------------------------------------- /crates/scheduler-credit/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "cp-scheduler-credit" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 7 | 8 | [dependencies] 9 | frame-support = { workspace = true } 10 | 11 | [features] 12 | default = ["std"] 13 | std = [ 14 | "frame-support/std", 15 | ] 16 | -------------------------------------------------------------------------------- /crates/scheduler-credit/src/lib.rs: -------------------------------------------------------------------------------- 1 | /*! 2 | # Some scheduler credit primitives 3 | */ 4 | #![cfg_attr(not(feature = "std"), no_std)] 5 | use frame_support::dispatch::DispatchResult; 6 | /// API necessary for Scheduler record ops about credit. 7 | pub trait SchedulerCreditCounter { 8 | fn increase_point_for_tag(scheduler_id: &SchedulerCtrlAccountId, space: u128) -> DispatchResult; 9 | 10 | fn increase_point_for_cert(scheduler_id: &SchedulerCtrlAccountId, space: u128) -> DispatchResult; 11 | 12 | fn increase_point_for_idle_verify(scheduler_id: &SchedulerCtrlAccountId, space: u128) -> DispatchResult; 13 | 14 | fn increase_point_for_service_verify(scheduler_id: &SchedulerCtrlAccountId, space: u128) -> DispatchResult; 15 | 16 | fn increase_point_for_replace(scheduler_id: &SchedulerCtrlAccountId, space: u128) -> DispatchResult; 17 | 18 | /// Records the number of file bytes processed by the scheduler 19 | fn record_proceed_block_size(scheduler_id: &SchedulerCtrlAccountId, block_size: u64) -> DispatchResult; 20 | 21 | /// Record the number of times the scheduler has been punished 22 | fn record_punishment(scheduler_id: &SchedulerCtrlAccountId) -> DispatchResult; 23 | 24 | } 25 | 26 | /// Stash account finder, used to find the corresponding Stash account according to the Controller account 27 | pub trait SchedulerStashAccountFinder { 28 | /// find the corresponding Stash account according to the Controller account 29 | fn find_stash_account_id(ctrl_account_id: &AccountId) -> Option; 30 | } 31 | -------------------------------------------------------------------------------- /crates/sgx-api-lite/.rustfmt.toml: -------------------------------------------------------------------------------- 1 | hard_tabs = false -------------------------------------------------------------------------------- /crates/sgx-api-lite/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "sgx-api-lite" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | [dependencies] 7 | cmac = "0.7.1" 8 | aes = "0.8.1" 9 | -------------------------------------------------------------------------------- /crates/sgx-api-lite/src/enclave_api.S: -------------------------------------------------------------------------------- 1 | .global sgx_report 2 | .type sgx_report, @function 3 | sgx_report: 4 | .cfi_startproc 5 | push rbx 6 | push rcx 7 | 8 | mov rbx,rdi 9 | mov rcx,rsi 10 | mov rax,0x0 11 | clc 12 | enclu 13 | setc al 14 | 15 | pop rcx 16 | pop rbx 17 | ret 18 | .cfi_endproc 19 | 20 | .global sgx_getkey 21 | .type sgx_getkey, @function 22 | sgx_getkey: 23 | .cfi_startproc 24 | push rbx 25 | push rcx 26 | 27 | mov rbx,rdi 28 | mov rcx,rsi 29 | mov rax,0x1 30 | enclu 31 | jz .Legetkey_done 32 | xor rax, rax 33 | 34 | .Legetkey_done: 35 | pop rcx 36 | pop rbx 37 | ret 38 | .cfi_endproc 39 | -------------------------------------------------------------------------------- /crates/sgx-api-lite/tests/tests.rs: -------------------------------------------------------------------------------- 1 | use sgx_api_lite as sgx; 2 | 3 | #[test] 4 | #[ignore = "only works under sgx"] 5 | fn it_works() { 6 | // In Enclave A 7 | let my_target_info = sgx::target_info().unwrap(); 8 | let target_info_bytes = sgx::encode(&my_target_info); 9 | 10 | // In Enclave B 11 | let its_target_info = unsafe { sgx::decode(target_info_bytes).unwrap() }; 12 | let report = sgx::report(its_target_info, &[0; 64]).unwrap(); 13 | let report_bytes = sgx::encode(&report); 14 | 15 | // In Enclave A 16 | let recv_report = unsafe { sgx::decode(report_bytes).unwrap() }; 17 | let rv = sgx::verify(recv_report); 18 | assert!(rv.is_ok()); 19 | println!("It works!"); 20 | } 21 | -------------------------------------------------------------------------------- /crates/sgx-attestation/.rustfmt.toml: -------------------------------------------------------------------------------- 1 | hard_tabs = false -------------------------------------------------------------------------------- /crates/sgx-attestation/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "sgx-attestation" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | [dependencies] 7 | serde = { workspace = true, features = ["derive"] } 8 | serde_json = { workspace = true, features = ["preserve_order"], optional = true } 9 | hex = { workspace = true, features = ["alloc"] } 10 | base64 = { workspace = true, features = ["alloc"] } 11 | parity-scale-codec = { workspace = true, features = ["derive"] } 12 | webpki = { workspace = true, features = ["alloc", "ring"] } 13 | rustls-pki-types = { version = "=0.2.1", default-features = false, optional = true } 14 | pink-json = { workspace = true } 15 | scale-info = { workspace = true, features = ["derive"] } 16 | chrono = { workspace = true, features = [ 17 | "alloc", 18 | "serde", 19 | ] } 20 | const-oid = { workspace = true } 21 | x509-cert = { workspace = true } 22 | byteorder = { workspace = true } 23 | pem = { workspace = true } 24 | asn1_der = { workspace = true, features = [ 25 | "native_types", 26 | ] } 27 | der = { workspace = true, features = ["alloc"] } 28 | 29 | log = { workspace = true } 30 | 31 | anyhow = { workspace = true, optional = true } 32 | 33 | ring = { workspace = true, optional = true, features = [ 34 | "alloc", 35 | ] } 36 | reqwest = { workspace = true, optional = true, features = [ 37 | "rustls-tls", 38 | "blocking", 39 | "hickory-dns", 40 | ] } 41 | urlencoding = { workspace = true, optional = true } 42 | tracing = { workspace = true, optional = true } 43 | tokio ={ workspace = true, optional = true } 44 | reqwest-env-proxy = { path = "../reqwest-env-proxy", optional = true } 45 | [dev-dependencies] 46 | insta = "1" 47 | 48 | [features] 49 | default = ["std", "report", "verify"] 50 | std = [ 51 | "pink-json/std", 52 | "serde/std", 53 | "parity-scale-codec/std", 54 | "scale-info/std", 55 | "ring/std", 56 | "webpki/std", 57 | "const-oid/std", 58 | "pem/std", 59 | "asn1_der/std", 60 | "der/std", 61 | "serde_json/std", 62 | "anyhow", 63 | "reqwest", 64 | "urlencoding", 65 | ] 66 | report = ["std","reqwest-env-proxy" ,"tracing", "tokio"] 67 | verify = ["ring", "webpki/ring"] 68 | 69 | -------------------------------------------------------------------------------- /crates/sgx-attestation/src/dcap/mod.rs: -------------------------------------------------------------------------------- 1 | mod constants; 2 | pub mod quote; 3 | 4 | #[cfg(feature = "report")] 5 | pub mod report; 6 | mod tcb_info; 7 | mod utils; 8 | pub mod verify; -------------------------------------------------------------------------------- /crates/sgx-attestation/src/dcap/tcb_info.rs: -------------------------------------------------------------------------------- 1 | use alloc::string::String; 2 | use alloc::vec::Vec; 3 | use serde::{Deserialize, Serialize}; 4 | 5 | #[derive(Debug, Serialize, Deserialize)] 6 | #[serde(rename_all = "camelCase")] 7 | pub struct TcbInfo { 8 | pub id: String, 9 | pub version: u8, 10 | pub issue_date: String, 11 | pub next_update: String, 12 | pub fmspc: String, 13 | pub pce_id: String, 14 | pub tcb_type: u32, 15 | pub tcb_evaluation_data_number: u32, 16 | pub tcb_levels: Vec, 17 | } 18 | 19 | #[derive(Debug, Serialize, Deserialize)] 20 | #[serde(rename_all = "camelCase")] 21 | pub struct TcbLevel { 22 | pub tcb: Tcb, 23 | pub tcb_date: String, 24 | pub tcb_status: String, 25 | #[serde(rename = "advisoryIDs", default)] 26 | pub advisory_ids: Vec, 27 | } 28 | 29 | #[derive(Debug, Serialize, Deserialize)] 30 | #[serde(rename_all = "camelCase")] 31 | pub struct Tcb { 32 | #[serde(rename = "sgxtcbcomponents")] 33 | pub components: Vec, 34 | #[serde(rename = "pcesvn")] 35 | pub pce_svn: u16, 36 | } 37 | 38 | #[derive(Debug, Serialize, Deserialize)] 39 | #[serde(rename_all = "camelCase")] 40 | pub struct TcbComponents { 41 | pub svn: u8, 42 | } 43 | -------------------------------------------------------------------------------- /crates/sgx-attestation/src/gramine.rs: -------------------------------------------------------------------------------- 1 | use std::fs; 2 | use std::io::Result; 3 | 4 | use crate::types::{AttestationType, SgxQuote}; 5 | 6 | /// Create an SGX quote from the given data. 7 | pub fn create_quote_vec(data: &[u8]) -> Result> { 8 | fs::write("/dev/attestation/user_report_data", data)?; 9 | fs::read("/dev/attestation/quote") 10 | } 11 | 12 | /// Create an SGX quote from the given data. 13 | pub fn create_quote(data: &[u8]) -> Option { 14 | let quote = create_quote_vec(data).ok()?; 15 | let attestation_type = attestation_type()?; 16 | Some(SgxQuote { 17 | attestation_type, 18 | quote, 19 | }) 20 | } 21 | 22 | /// Get the attestation type of the current running gramine instance. 23 | /// 24 | /// Possible values are "epid", "dcap" or None if the file does not exist. 25 | pub fn attestation_type_str() -> Option { 26 | fs::read_to_string("/dev/attestation/attestation_type").ok() 27 | } 28 | 29 | /// Get the attestation type of the current running gramine instance. 30 | pub fn attestation_type() -> Option { 31 | attestation_type_str().and_then(|s| match s.as_str() { 32 | "epid" => Some(AttestationType::Epid), 33 | "dcap" => Some(AttestationType::Dcap), 34 | _ => None, 35 | }) 36 | } 37 | 38 | /// Returns true if the current running gramine instance is using DCAP. 39 | pub fn is_dcap() -> bool { 40 | attestation_type() == Some(AttestationType::Dcap) 41 | } 42 | 43 | /// Returns true if the current process is running inside a gramine enclave. 44 | pub fn is_in_enclave() -> bool { 45 | std::path::Path::new("/dev/attestation/attestation_type").exists() 46 | } 47 | -------------------------------------------------------------------------------- /crates/sgx-attestation/src/ias/mod.rs: -------------------------------------------------------------------------------- 1 | #[cfg(feature = "report")] 2 | pub mod report; 3 | #[cfg(feature = "verify")] 4 | pub mod verify; -------------------------------------------------------------------------------- /crates/sgx-attestation/src/lib.rs: -------------------------------------------------------------------------------- 1 | #![cfg_attr(all(not(test), not(feature = "std")), no_std)] 2 | 3 | #[macro_use] 4 | extern crate alloc; 5 | 6 | use parity_scale_codec::{Decode, Encode}; 7 | use scale_info::TypeInfo; 8 | 9 | pub mod dcap; 10 | pub mod ias; 11 | pub mod types; 12 | 13 | #[cfg(feature = "report")] 14 | pub mod gramine; 15 | 16 | #[derive(Encode, Decode, TypeInfo, Debug, Clone, PartialEq, Eq)] 17 | pub enum Error { 18 | InvalidCertificate, 19 | InvalidSignature, 20 | CodecError, 21 | 22 | // DCAP 23 | TCBInfoExpired, 24 | KeyLengthIsInvalid, 25 | PublicKeyIsInvalid, 26 | RsaSignatureIsInvalid, 27 | DerEncodingError, 28 | UnsupportedDCAPQuoteVersion, 29 | UnsupportedDCAPAttestationKeyType, 30 | UnsupportedQuoteAuthData, 31 | UnsupportedDCAPPckCertFormat, 32 | LeafCertificateParsingError, 33 | CertificateChainIsInvalid, 34 | CertificateChainIsTooShort, 35 | IntelExtensionCertificateDecodingError, 36 | IntelExtensionAmbiguity, 37 | CpuSvnLengthMismatch, 38 | CpuSvnDecodingError, 39 | PceSvnDecodingError, 40 | PceSvnLengthMismatch, 41 | FmspcLengthMismatch, 42 | FmspcDecodingError, 43 | FmspcMismatch, 44 | QEReportHashMismatch, 45 | IsvEnclaveReportSignatureIsInvalid, 46 | DerDecodingError, 47 | OidIsMissing, 48 | } 49 | 50 | pub mod quote_status_levels { 51 | pub const SGX_QUOTE_STATUS_LEVEL_1: &[&str] = &[ 52 | // IAS 53 | "OK", 54 | // DCAP 55 | "UpToDate", 56 | ]; 57 | pub const SGX_QUOTE_STATUS_LEVEL_2: &[&str] = &[ 58 | // IAS 59 | "SW_HARDENING_NEEDED", 60 | // DCAP 61 | "SWHardeningNeeded", 62 | ]; 63 | pub const SGX_QUOTE_STATUS_LEVEL_3: &[&str] = &[ 64 | // IAS 65 | "CONFIGURATION_NEEDED", 66 | "CONFIGURATION_AND_SW_HARDENING_NEEDED", 67 | // DCAP 68 | "ConfigurationNeeded", 69 | "ConfigurationAndSWHardeningNeeded", 70 | ]; 71 | // LEVEL 4 is LEVEL 3 with advisors which not included in whitelist 72 | pub const SGX_QUOTE_STATUS_LEVEL_5: &[&str] = &[ 73 | // IAS 74 | "GROUP_OUT_OF_DATE", 75 | // DCAP 76 | "OutOfDate", 77 | "OutOfDateConfigurationNeeded", 78 | ]; 79 | pub const SGX_QUOTE_ADVISORY_ID_WHITELIST: &[&str] = &[ 80 | "INTEL-SA-00334", 81 | "INTEL-SA-00219", 82 | "INTEL-SA-00381", 83 | "INTEL-SA-00389", 84 | ]; 85 | } -------------------------------------------------------------------------------- /crates/sgx-attestation/src/snapshots/sgx_attestation__ias__test__could_parse-2.snap: -------------------------------------------------------------------------------- 1 | --- 2 | source: crates/sgx-attestation/src/ias.rs 3 | assertion_line: 187 4 | expression: report.parse_report().unwrap() 5 | --- 6 | RaReport { 7 | id: "82934912299674180590716290258197145307", 8 | timestamp: "2021-09-12T18:06:20.402478", 9 | version: 4, 10 | epid_pseudonym: "4TUztFNlJtNfyhtdnN3L4ZfOUkUNcw2coVyAYcxi6Q893o6a+lHgfxVYrlsCAaz2IdpD0QZKFbpjBVbPbhGCszGTg/FwliaPlJ0HMa60Cyx1/pd83YHFgOf02/z36QCdiSvlCnRxxE41sZQE8/WrLqv5hzlsLegOEw6X+r0XS2E=", 11 | advisory_url: "https://security-center.intel.com", 12 | advisory_ids: [ 13 | "INTEL-SA-00334", 14 | ], 15 | isv_enclave_quote_status: "SW_HARDENING_NEEDED", 16 | isv_enclave_quote_body: "AgABABMMAAAMAAsAAAAAACA1iY73e440nuw+J3NzpJAAAAAAAAAAAAAAAAAAAAAAERICB/+ABgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAAAAAAHAAAAAAAAAFGEIvp2nS1VmCAVoOBBfGqFIf38cwj17BiqobaSS9DzAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACBX0LxHPZEMMMLq3gWullqHaATDDsCi2cxM6Zs+aPg5gAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAxeNE8tR8hFZM3y+hkwT6i3/F91dSdoF2ztTwfD/I+jAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", 17 | } 18 | -------------------------------------------------------------------------------- /crates/sgx-attestation/src/types.rs: -------------------------------------------------------------------------------- 1 | use alloc::string::String; 2 | use alloc::vec::Vec; 3 | use parity_scale_codec::{Decode, Encode}; 4 | use scale_info::TypeInfo; 5 | 6 | #[derive(Encode, Decode, TypeInfo, Debug, Clone, Copy, PartialEq, Eq)] 7 | pub enum AttestationType { 8 | Epid, 9 | Dcap, 10 | } 11 | 12 | #[derive(Encode, Decode, TypeInfo, Debug, Clone, PartialEq, Eq)] 13 | pub struct SgxQuote { 14 | pub attestation_type: AttestationType, 15 | pub quote: Vec, 16 | } 17 | 18 | #[derive(Encode, Decode, TypeInfo, Debug, Clone, PartialEq, Eq)] 19 | pub enum AttestationReport { 20 | SgxIas { 21 | ra_report: Vec, 22 | signature: Vec, 23 | raw_signing_cert: Vec, 24 | }, 25 | SgxDcap { 26 | quote: Vec, 27 | collateral: Option, 28 | }, 29 | } 30 | 31 | #[derive(Encode, Decode, TypeInfo, Debug, Clone, PartialEq, Eq)] 32 | pub enum Collateral { 33 | SgxV30(SgxV30QuoteCollateral), 34 | } 35 | 36 | #[derive(Encode, Decode, TypeInfo, Clone, PartialEq, Eq, Debug)] 37 | pub struct SgxV30QuoteCollateral { 38 | pub pck_crl_issuer_chain: String, 39 | pub root_ca_crl: String, 40 | pub pck_crl: String, 41 | pub tcb_info_issuer_chain: String, 42 | pub tcb_info: String, 43 | pub tcb_info_signature: Vec, 44 | pub qe_identity_issuer_chain: String, 45 | pub qe_identity: String, 46 | pub qe_identity_signature: Vec, 47 | } 48 | -------------------------------------------------------------------------------- /docs/code-overview-for-sbp.md: -------------------------------------------------------------------------------- 1 | # Project Details 2 | - Version:**v0.1.3** 3 | - Substrate version:**monthly-2021-10** 4 | - For the latest version, the number of blocks is close to **300,000**, and the online upgrade is **3** times 5 | - With testable block explorers:(http://data.cesslab.co.uk/browser/#/explorer ) 6 | - **Passed W3F Grants Milestone 1 and Milestone 2, and Milestone 3 has also been submitted**. 7 | 8 | # Hackathon Details 9 | The data trading market developed during the hackathon includes several modules related to Substrate: 10 | - The CESS Cloud Data Network (cess-node): is developed based on *the Substrate*. 11 | - The FMD-CESS (web-app): An web platform using *polkadot-js-app*. 12 | - Cumulus Encrypted Storage System: consists of storage-mining-tool and scheduler-mining-tool, which using *Go Substrate RPC Client Library (GSRPC)*. 13 | - Blockchain explorer (cess-ui-js): is tailored for the CESS Cloud Data Network, modified from *polkadot-js-app*. 14 | - See more: https://github.com/CESSProject/fmd-cess#%EF%B8%8F-what-it-does 15 | 16 | # Overall Architecture 17 | The project is based on Substrate FRAME, and the following modules are developed on STORAGE (Wasm Runtime) according to functional requirements. The blue part is the official module (Pallets), and the orange part is the custom module (Pallets). 18 | 19 | # ![CESS](https://raw.githubusercontent.com/Cumulus2021/W3F-illustration/main/CESS-TestNet.png) 20 | 21 | Next, introduce our own developed pallets: 22 | https://github.com/CESSProject/cess#module-documentation 23 | -------------------------------------------------------------------------------- /docs/on-src/node/src/chain_spec.rs.md: -------------------------------------------------------------------------------- 1 | The diagram below shows how the functions are related to each other. 2 | 3 | Refer to [mermaid doc: Flowchart](https://mermaid.js.org/syntax/flowchart.html) for syntax. 4 | 5 | `id` is the `id` parameter used in **Cli** [`load_spec()`](https://github.com/CESSProject/cess/blob/main/node/src/command.rs#L57-L69) 6 | 7 | ```mermaid 8 | flowchart LR 9 | %% main 10 | testnet_genesis("testnet_genesis()") --> main_genesis("cess_main_genesis()") --> main("cess_main()") --> initial_testnet(["id: `cess-initial-testnet`"]) 11 | 12 | %% testnet 13 | testnet_genesis --> testnet_config_genesis("cess_testnet_config_genesis()") --> testnet_generate_config("cess_testnet_generate_config()") --> initial_devnet(["id: `cess-initial-devnet`"]) 14 | 15 | %% local 16 | testnet_genesis --> local_testnet_genesis("local_testnet_genesis()") --> local_testnet_config("local_testnet_config()") --> local(["id: `local`"]) 17 | 18 | %% dev 19 | testnet_genesis --> development_config_genesis("development_config_genesis()") --> development_config("development_config()") --> dev(["id: `dev`"]) 20 | 21 | %% Reading from chainspec file 22 | chainSpec("Read from chainSpec") --> testnet_config("cess_testnet_config()") --> cess_testnet(["id: `cess-testnet`"]) 23 | chainSpec --> develop_config("cess_develop_config()") --> cess_devnet(["id: `cess-devnet`"]) 24 | ``` 25 | -------------------------------------------------------------------------------- /docs/rust-setup.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: Installation 3 | --- 4 | 5 | This page will guide you through the steps needed to prepare a computer for development with the 6 | CESS Node. Since Substrate is built with 7 | [the Rust programming language](https://www.rust-lang.org/), the first thing you will need to do is 8 | prepare the computer for Rust development - these steps will vary based on the computer's operating 9 | system. Once Rust is configured, you will use its toolchains to interact with Rust projects; the 10 | commands for Rust's toolchains will be the same for all supported, Unix-based operating systems. 11 | 12 | ## Unix-Based Operating Systems 13 | 14 | Substrate development is easiest on Unix-based operating systems like macOS or Linux. The examples 15 | in the Substrate [Tutorials](https://substrate.dev/tutorials) and [Recipes](https://substrate.dev/recipes/) 16 | use Unix-style terminals to demonstrate how to interact with Substrate from the command line. 17 | 18 | ### macOS 19 | 20 | Open the Terminal application and execute the following commands: 21 | 22 | ```bash 23 | # Install Homebrew if necessary https://brew.sh/ 24 | /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)" 25 | 26 | # Make sure Homebrew is up-to-date, install openssl and cmake 27 | brew update 28 | brew install openssl cmake 29 | ``` 30 | 31 | ### Ubuntu/Debian 32 | 33 | Use a terminal shell to execute the following commands: 34 | 35 | ```bash 36 | sudo apt update 37 | # May prompt for location information 38 | sudo apt install -y cmake pkg-config libssl-dev git build-essential clang libclang-dev curl 39 | ``` 40 | 41 | ### Arch Linux 42 | 43 | Run these commands from a terminal: 44 | 45 | ```bash 46 | pacman -Syu --needed --noconfirm cmake gcc openssl-1.0 pkgconf git clang 47 | export OPENSSL_LIB_DIR="/usr/lib/openssl-1.0" 48 | export OPENSSL_INCLUDE_DIR="/usr/include/openssl-1.0" 49 | ``` 50 | 51 | ### Fedora/RHEL/CentOS 52 | 53 | Use a terminal to run the following commands: 54 | 55 | ```bash 56 | # Update 57 | sudo dnf update 58 | # Install packages 59 | sudo dnf install cmake pkgconfig rocksdb rocksdb-devel llvm git libcurl libcurl-devel curl-devel clang 60 | ``` 61 | 62 | ## Rust Developer Environment 63 | 64 | This project uses [`rustup`](https://rustup.rs/) to help manage the Rust toolchain. First install 65 | and configure `rustup`: 66 | 67 | ```bash 68 | # Install 69 | curl https://sh.rustup.rs -sSf | sh 70 | # Configure 71 | source ~/.cargo/env 72 | ``` 73 | 74 | Finally, configure the Rust toolchain: 75 | 76 | ```bash 77 | rustup default stable 78 | rustup update nightly 79 | rustup update stable 80 | rustup target add wasm32-unknown-unknown --toolchain nightly 81 | ``` 82 | -------------------------------------------------------------------------------- /pallets/audit/src/constants.rs: -------------------------------------------------------------------------------- 1 | // miner cpu use 50%. 2 | pub(super) const SERVICE_PROVE_RATE: u128 = 25_165_824; 3 | // miner cpu use 50%. 4 | pub(super) const IDLE_PROVE_RATE: u128 = 203_613_264; 5 | 6 | pub(super) const IDLE_VERIFY_RATE: u128 = 2_147_483_648; 7 | 8 | // pub(super) const IDLE_FAULT_TOLERANT: u8 = 2; 9 | 10 | pub(super) const SERVICE_FAULT_TOLERANT: u8 = 2; 11 | 12 | pub(super) type SpaceChallengeParam = [u64; 8]; 13 | -------------------------------------------------------------------------------- /pallets/audit/src/migrations.rs: -------------------------------------------------------------------------------- 1 | use crate::*; 2 | use codec::{Decode, Encode}; 3 | use frame_support::{ 4 | codec, generate_storage_alias, 5 | traits::Get, 6 | }; 7 | use frame_support::traits::OnRuntimeUpgrade; 8 | 9 | pub struct MigrationAudit(sp_std::marker::PhantomData); 10 | impl OnRuntimeUpgrade for MigrationAudit { 11 | fn on_runtime_upgrade() -> Weight { 12 | log::info!("Audit migrate start!"); 13 | migrate::() 14 | } 15 | 16 | #[cfg(feature = "try-runtime")] 17 | fn pre_upgrade() -> Result<(), &'static str> { 18 | log::info!("audit check access"); 19 | return Ok(()) 20 | } 21 | 22 | #[cfg(feature = "try-runtime")] 23 | fn post_upgrade() -> Result<(), &'static str> { 24 | let weights = migrate::(); 25 | return Ok(()) 26 | } 27 | } 28 | 29 | pub fn migrate() -> Weight { 30 | let version = StorageVersion::get::>(); 31 | let mut weight: Weight = 0; 32 | 33 | if version < 1 { 34 | log::info!("Audit version 1 -> 2 migrations start!"); 35 | weight = weight.saturating_add(v2::migrate::()); 36 | StorageVersion::new(2).put::>(); 37 | } 38 | 39 | weight 40 | } 41 | 42 | mod v2 { 43 | use super::*; 44 | 45 | #[derive(Decode, Encode)] 46 | struct OldProveInfo { 47 | file_id: Hash, 48 | miner_acc: AccountOf, 49 | challenge_info: ChallengeInfo, 50 | mu: BoundedList, 51 | sigma: BoundedVec, 52 | name: BoundedVec, 53 | u: BoundedList, 54 | } 55 | 56 | generate_storage_alias!( 57 | Audit, 58 | UnVerifyProof => Map< 59 | (Blake2_128Concat, T::AccountId), 60 | BoundedVec, T::ChallengeMaximum> 61 | > 62 | ); 63 | 64 | pub fn migrate() -> Weight { 65 | let mut weight: Weight = 0; 66 | 67 | for (acc, prove_list) in >::iter() { 68 | log::info!("prove_list len is: {:?}", prove_list.len()); 69 | >::remove(&acc); 70 | weight = weight.saturating_add(T::DbWeight::get().writes(1 as Weight)); 71 | } 72 | 73 | weight 74 | } 75 | } -------------------------------------------------------------------------------- /pallets/cacher/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "pallet-cacher" 3 | version = "0.7.0" 4 | edition = "2021" 5 | 6 | [dependencies] 7 | log = { workspace = true } 8 | codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive", "max-encoded-len"] } 9 | scale-info = { workspace = true, features = ["derive"] } 10 | sp-std = { workspace = true } 11 | sp-runtime = { workspace = true } 12 | frame-support = { workspace = true } 13 | frame-system = { workspace = true } 14 | frame-benchmarking = { workspace = true, optional = true} 15 | 16 | #local dependencies 17 | cp-cess-common = { workspace = true } 18 | 19 | [dev-dependencies] 20 | sp-core = { workspace = true } 21 | pallet-balances = { workspace = true } 22 | sp-io = { workspace = true } 23 | 24 | [features] 25 | default = ["std"] 26 | std = [ 27 | "log/std", 28 | "codec/std", 29 | "scale-info/std", 30 | "sp-std/std", 31 | "sp-runtime/std", 32 | "frame-support/std", 33 | "frame-system/std", 34 | "cp-cess-common/std", 35 | "frame-benchmarking/std", 36 | ] 37 | 38 | runtime-benchmarks = [ 39 | "frame-benchmarking/runtime-benchmarks", 40 | ] 41 | try-runtime = [] -------------------------------------------------------------------------------- /pallets/cacher/README.md: -------------------------------------------------------------------------------- 1 | # Cacher Module ( pallet-cacher ) 2 | 3 | Contain operations related cache miner. Cache miner retrieves the bills in the transaction records and provides file downloading service. 4 | 5 | ### Terminology 6 | 7 | * **Bill:** Contains payment and download information. 8 | 9 | ## Interface 10 | 11 | ### Dispatchable Functions 12 | * `register` - A cache miner joins the CDN. 13 | * `update` - Update a cache miner information. 14 | * `logout` - A cache miner exits the CDN. 15 | * `pay` - A retrieval miner pays for downloads. 16 | 17 | ## Tests 18 | ``` 19 | cargo test --package pallet-cacher --features runtime-benchmarks 20 | ``` 21 | 22 | ## Code Walkthrough 23 | 1. A cache miner calls `register` method to join the CDN. Cache miner information will be saved to the `Cachers` StorageMap. 24 | 25 | https://github.com/CESSProject/cess/blob/1acaa2de1a7dcf0c6ec676f1ffa4d605cf43c830/pallets/cacher/src/lib.rs#L109-L117 26 | 27 | 2. Retrieval miners periodically query the `Cachers` StorageMap for all cache miner information. 28 | 29 | https://github.com/CESSProject/cess/blob/1acaa2de1a7dcf0c6ec676f1ffa4d605cf43c830/pallets/cacher/src/lib.rs#L95 30 | 31 | 3. A retrieval miner calls `pay` method to pay cache miners separately for downloading file fragments in batches. 32 | 33 | https://github.com/CESSProject/cess/blob/1acaa2de1a7dcf0c6ec676f1ffa4d605cf43c830/pallets/cacher/src/lib.rs#L157-L172 34 | 35 | 4. A cache miner calls `update` method to change ip or unit price. 36 | 37 | https://github.com/CESSProject/cess/blob/1acaa2de1a7dcf0c6ec676f1ffa4d605cf43c830/pallets/cacher/src/lib.rs#L124-L137 38 | 39 | 5. A cache miner calls `logout` method to exit the CDN. 40 | 41 | https://github.com/CESSProject/cess/blob/1acaa2de1a7dcf0c6ec676f1ffa4d605cf43c830/pallets/cacher/src/lib.rs#L141-L150 42 | -------------------------------------------------------------------------------- /pallets/cacher/src/mock.rs: -------------------------------------------------------------------------------- 1 | //! Test utilities 2 | 3 | use super::*; 4 | use crate as pallet_cacher; 5 | 6 | use frame_support::traits::{ConstU128, ConstU32}; 7 | use sp_core::H256; 8 | use sp_runtime::{ 9 | testing::Header, 10 | traits::{BlakeTwo256, IdentityLookup}, 11 | }; 12 | 13 | type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; 14 | type Block = frame_system::mocking::MockBlock; 15 | 16 | frame_support::construct_runtime!( 17 | pub enum Test where 18 | Block = Block, 19 | NodeBlock = Block, 20 | UncheckedExtrinsic = UncheckedExtrinsic, 21 | { 22 | System: frame_system::{Pallet, Call, Config, Storage, Event}, 23 | Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, 24 | Cacher: pallet_cacher::{Pallet, Call, Storage, Event}, 25 | } 26 | ); 27 | 28 | impl frame_system::Config for Test { 29 | type BaseCallFilter = frame_support::traits::Everything; 30 | type BlockWeights = (); 31 | type BlockLength = (); 32 | type RuntimeOrigin = RuntimeOrigin; 33 | type RuntimeCall = RuntimeCall; 34 | type Index = u64; 35 | type BlockNumber = u64; 36 | type Hash = H256; 37 | type Hashing = BlakeTwo256; 38 | type AccountId = u64; 39 | type Lookup = IdentityLookup; 40 | type Header = Header; 41 | type RuntimeEvent = RuntimeEvent; 42 | type BlockHashCount = Self::BlockHashCount; 43 | type DbWeight = (); 44 | type Version = (); 45 | type PalletInfo = PalletInfo; 46 | type AccountData = pallet_balances::AccountData; 47 | type OnNewAccount = (); 48 | type OnKilledAccount = (); 49 | type SystemWeightInfo = (); 50 | type SS58Prefix = Self::SS58Prefix; 51 | type OnSetCode = (); 52 | type MaxConsumers = frame_support::traits::ConstU32<16>; 53 | } 54 | 55 | impl pallet_balances::Config for Test { 56 | type MaxLocks = (); 57 | type MaxReserves = (); 58 | type ReserveIdentifier = [u8; 8]; 59 | type Balance = u128; 60 | type RuntimeEvent = RuntimeEvent; 61 | type DustRemoval = (); 62 | type ExistentialDeposit = ConstU128<1>; 63 | type AccountStore = System; 64 | type WeightInfo = (); 65 | } 66 | 67 | impl pallet_cacher::Config for Test { 68 | type RuntimeEvent = RuntimeEvent; 69 | type Currency = Balances; 70 | type BillsLimit = ConstU32<10>; 71 | type WeightInfo = (); 72 | } 73 | 74 | pub fn new_test_ext() -> sp_io::TestExternalities { 75 | let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); 76 | pallet_balances::GenesisConfig:: { 77 | balances: vec![(1, 100), (2, 100), (3, 100), (4, 100), (5, 100)], 78 | } 79 | .assimilate_storage(&mut t) 80 | .unwrap(); 81 | 82 | let mut ext: sp_io::TestExternalities = t.into(); 83 | ext.execute_with(|| System::set_block_number(1)); 84 | ext 85 | } 86 | -------------------------------------------------------------------------------- /pallets/cacher/src/types.rs: -------------------------------------------------------------------------------- 1 | use super::*; 2 | use frame_support::pallet_prelude::MaxEncodedLen; 3 | 4 | pub type AccountOf = ::AccountId; 5 | /// The balance type of this pallet. 6 | pub type BalanceOf = 7 | <::Currency as Currency<::AccountId>>::Balance; 8 | 9 | /// The custom struct for cacher info. 10 | #[derive(PartialEq, Eq, Encode, Decode, Clone, RuntimeDebug, MaxEncodedLen, TypeInfo)] 11 | pub struct CacherInfo { 12 | pub payee: AccountId, 13 | pub ip: IpAddress, 14 | pub byte_price: Balance, 15 | } 16 | 17 | /// The custom struct for bill info. 18 | #[derive(PartialEq, Eq, Encode, Decode, Clone, RuntimeDebug, MaxEncodedLen, TypeInfo)] 19 | pub struct Bill { 20 | pub id: [u8; 16], 21 | pub to: AccountId, 22 | pub amount: Balance, 23 | // Hash of the file to download 24 | pub file_hash: Hash, 25 | // Hash of the file slice to download 26 | pub slice_hash: Hash, 27 | pub expiration_time: u64, 28 | } 29 | -------------------------------------------------------------------------------- /pallets/cess-treasury/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "pallet-cess-treasury" 3 | authors = ["CESS LAB"] 4 | version = "0.7.6" 5 | edition = "2021" 6 | license = "Apache-2.0" 7 | repository = "https://github.com/CESSProject/cess" 8 | description = "FRAME pallet for sminer management" 9 | readme = "README.md" 10 | 11 | [dependencies] 12 | scale-info = { workspace = true, features = ["derive"] } 13 | codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive"] } 14 | log = { workspace = true } 15 | 16 | #substrate pallet 17 | frame-benchmarking = { workspace = true, optional = true } 18 | frame-support = { workspace = true } 19 | frame-system = { workspace = true } 20 | sp-std = { workspace = true } 21 | sp-runtime = { workspace = true } 22 | 23 | sp-staking = { workspace = true, features = ["serde"] } 24 | 25 | 26 | [features] 27 | default = ["std"] 28 | std = [ 29 | "codec/std", 30 | "scale-info/std", 31 | "frame-benchmarking/std", 32 | "frame-support/std", 33 | "frame-system/std", 34 | "sp-std/std", 35 | "sp-runtime/std", 36 | ] 37 | 38 | runtime-benchmarks = [ 39 | "frame-benchmarking/runtime-benchmarks", 40 | ] 41 | try-runtime = [] -------------------------------------------------------------------------------- /pallets/cess-treasury/src/benchmarking.rs: -------------------------------------------------------------------------------- 1 | #![cfg(feature = "runtime-benchmarks")] 2 | 3 | use super::*; 4 | 5 | pub fn initialize_reward() { 6 | let era_reward: BalanceOf = 365_000_000_000_000_000_000_000u128.try_into().map_err(|_| "tryinto error!").expect("tryinto error!"); 7 | let currency_reward: BalanceOf = 8_000_000_000_000_000_000_000_000u128.try_into().map_err(|_| "tryinto error!").expect("tryinto error!"); 8 | let reserve_reward: BalanceOf = 8_000_000_000_000_000_000_000_000u128.try_into().map_err(|_| "tryinto error!").expect("tryinto error!"); 9 | let reward_acc = T::MinerRewardId::get().into_account_truncating(); 10 | let reserve_acc = T::ReserveRewardId::get().into_account_truncating(); 11 | 12 | ::Currency::make_free_balance_be( 13 | &reward_acc, 14 | currency_reward, 15 | ); 16 | ::Currency::make_free_balance_be( 17 | &reserve_acc, 18 | reserve_reward, 19 | ); 20 | 21 | EraReward::::put(era_reward); 22 | CurrencyReward::::put(currency_reward); 23 | ReserveReward::::put(reserve_reward); 24 | } 25 | -------------------------------------------------------------------------------- /pallets/cess-treasury/src/constants.rs: -------------------------------------------------------------------------------- 1 | use super::*; 2 | 3 | pub(super) const REWARD_BASE_MUTI: Perbill = Perbill::from_percent(75); -------------------------------------------------------------------------------- /pallets/cess-treasury/src/types.rs: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/CESSProject/cess/d9341e49b0e52968ffee9d7d56aeb6ba69c213d5/pallets/cess-treasury/src/types.rs -------------------------------------------------------------------------------- /pallets/evm-account-mapping/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "pallet-evm-account-mapping" 3 | version = "0.0.1" 4 | description = "A Substrate pallet for compatible with EVM wallets." 5 | authors = ["Phala Network"] 6 | repository = "https://github.com/phala-network/substrate-evm_account_mapping" 7 | homepage = "https://github.com/phala-network/substrate-evm_account_mapping" 8 | license = "Apache-2.0" 9 | edition = "2021" 10 | publish = false 11 | 12 | [dependencies] 13 | codec = { workspace = true, default-features = false, features = ["derive"] } 14 | scale-info = { workspace = true, features = ["derive"] } 15 | sp-io = { workspace = true } 16 | sp-runtime = { workspace = true } 17 | sp-std = { workspace = true } 18 | sp-core = { workspace = true, features = ["serde"] } 19 | frame-benchmarking = { workspace = true, optional = true } 20 | frame-support = { workspace = true } 21 | frame-system = { workspace = true } 22 | pallet-transaction-payment = { workspace = true } 23 | 24 | hex = { workspace = true, features = ["alloc"] } 25 | log = { workspace = true } 26 | ethabi = { workspace = true } 27 | 28 | [dev-dependencies] 29 | pallet-balances = { workspace = true } 30 | 31 | [features] 32 | default = ["std"] 33 | std = [ 34 | "codec/std", 35 | "scale-info/std", 36 | "sp-io/std", 37 | "sp-runtime/std", 38 | "sp-std/std", 39 | "sp-core/std", 40 | "frame-benchmarking?/std", 41 | "frame-support/std", 42 | "frame-system/std", 43 | "pallet-transaction-payment/std", 44 | "hex/std", 45 | "log/std", 46 | "ethabi/std", 47 | ] 48 | runtime-benchmarks = [ 49 | "frame-benchmarking/runtime-benchmarks", 50 | "frame-support/runtime-benchmarks", 51 | "frame-system/runtime-benchmarks", 52 | "sp-runtime/runtime-benchmarks" 53 | ] 54 | try-runtime = [ 55 | "frame-support/try-runtime", 56 | "frame-system/try-runtime", 57 | "sp-runtime/try-runtime" 58 | ] 59 | -------------------------------------------------------------------------------- /pallets/evm-account-mapping/README.md: -------------------------------------------------------------------------------- 1 | EVM Account Mapping Pallet for Substrate 2 | ==== 3 | 4 | ## License 5 | 6 | This project released under [Apache License, Version 2.0](https://opensource.org/license/apache-2-0/). 7 | -------------------------------------------------------------------------------- /pallets/evm-account-mapping/src/benchmarking.rs: -------------------------------------------------------------------------------- 1 | // This file is part of EVM Account Mapping Pallet. 2 | 3 | // Copyright (C) HashForest Technology Pte. Ltd. 4 | // SPDX-License-Identifier: Apache-2.0 5 | 6 | // Licensed under the Apache License, Version 2.0 (the "License"); 7 | // you may not use this file except in compliance with the License. 8 | // You may obtain a copy of the License at 9 | // 10 | // http://www.apache.org/licenses/LICENSE-2.0 11 | // 12 | // Unless required by applicable law or agreed to in writing, software 13 | // distributed under the License is distributed on an "AS IS" BASIS, 14 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | // See the License for the specific language governing permissions and 16 | // limitations under the License. 17 | 18 | //! Benchmarking setup for the pallet 19 | #![cfg(feature = "runtime-benchmarks")] 20 | use super::*; 21 | 22 | #[allow(unused)] 23 | use crate::Pallet as ThisPallet; 24 | use frame_benchmarking::v2::*; 25 | use frame_system::RawOrigin; 26 | 27 | use codec::Decode; 28 | use sp_std::prelude::*; 29 | use sp_core::crypto::Ss58Codec; 30 | use sp_runtime::traits::{Bounded, TrailingZeroInput}; 31 | 32 | #[allow(dead_code)] 33 | fn assert_last_event(generic_event: ::RuntimeEvent) { 34 | frame_system::Pallet::::assert_last_event(generic_event.into()); 35 | } 36 | 37 | #[benchmarks( where PaymentBalanceOf: FixedPointOperand, ::RuntimeCall: Dispatchable, T: frame_system::Config,)] 38 | mod benchmarks { 39 | use super::*; 40 | 41 | #[benchmark] 42 | fn meta_call() -> Result<(), BenchmarkError> { 43 | let account = 44 | T::AccountId::from_ss58check("5DT96geTS2iLpkH8fAhYAAphNpxddKCV36s5ShVFavf1xQiF") 45 | .unwrap(); 46 | let call_data = hex::decode("00071448656c6c6f").expect("Valid"); // system.remarkWithEvent("Hello") 47 | let call = ::RuntimeCall::decode(&mut TrailingZeroInput::new( 48 | &call_data, 49 | )) 50 | .expect("Valid"); 51 | let nonce: u64 = 0; 52 | let signature: [u8; 65] = hex::decode("37cb6ff8e296d7e476ee13a6cfababe788217519d428fcc723b482dc97cb4d1359a8d1c020fe3cebc1d06a67e61b1f0e296739cecacc640b0ba48e8a7555472e1b").expect("Decodable").try_into().expect("Valid"); 53 | 54 | T::Currency::make_free_balance_be(&account, BalanceOf::::max_value() / 2u32.into()); 55 | 56 | #[extrinsic_call] 57 | _(RawOrigin::None, account, Box::new(call.into()), nonce, signature, None); 58 | 59 | Ok(()) 60 | } 61 | 62 | impl_benchmark_test_suite!(ThisPallet, crate::mock::new_test_ext(), crate::mock::Test); 63 | } 64 | -------------------------------------------------------------------------------- /pallets/evm-account-mapping/src/encode.rs: -------------------------------------------------------------------------------- 1 | // This file is part of EVM Account Mapping Pallet. 2 | 3 | // Copyright (C) HashForest Technology Pte. Ltd. 4 | // SPDX-License-Identifier: Apache-2.0 5 | 6 | // Licensed under the Apache License, Version 2.0 (the "License"); 7 | // you may not use this file except in compliance with the License. 8 | // You may obtain a copy of the License at 9 | // 10 | // http://www.apache.org/licenses/LICENSE-2.0 11 | // 12 | // Unless required by applicable law or agreed to in writing, software 13 | // distributed under the License is distributed on an "AS IS" BASIS, 14 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | // See the License for the specific language governing permissions and 16 | // limitations under the License. 17 | 18 | /// Port from https://github.com/roberts-ivanovs/eth-encode-packed-rs 19 | use ethabi::ethereum_types::{Address, U256}; 20 | 21 | pub struct TakeLastXBytes(pub usize); 22 | 23 | #[allow(dead_code)] 24 | pub enum SolidityDataType<'a> { 25 | String(&'a str), 26 | Address(Address), 27 | Bytes(&'a [u8]), 28 | Bool(bool), 29 | Number(U256), 30 | NumberWithShift(U256, TakeLastXBytes), 31 | } 32 | 33 | pub mod abi { 34 | use super::SolidityDataType; 35 | use sp_std::{vec, vec::Vec}; 36 | 37 | /// Pack a single `SolidityDataType` into bytes 38 | #[allow(clippy::needless_lifetimes)] 39 | fn pack<'a>(data_type: &'a SolidityDataType) -> Vec { 40 | let mut res = Vec::new(); 41 | match data_type { 42 | SolidityDataType::String(s) => { 43 | res.extend(s.as_bytes()); 44 | }, 45 | SolidityDataType::Address(a) => { 46 | res.extend(a.0); 47 | }, 48 | SolidityDataType::Number(n) => 49 | for b in n.0.iter().rev() { 50 | let bytes = b.to_be_bytes(); 51 | res.extend(bytes); 52 | }, 53 | SolidityDataType::Bytes(b) => { 54 | res.extend(*b); 55 | }, 56 | SolidityDataType::Bool(b) => 57 | if *b { 58 | res.push(1); 59 | } else { 60 | res.push(0); 61 | }, 62 | SolidityDataType::NumberWithShift(n, to_take) => { 63 | let local_res = n.0.iter().rev().fold(vec![], |mut acc, i| { 64 | let bytes = i.to_be_bytes(); 65 | acc.extend(bytes); 66 | acc 67 | }); 68 | 69 | let to_skip = local_res.len() - (to_take.0 / 8); 70 | let local_res = local_res.into_iter().skip(to_skip).collect::>(); 71 | res.extend(local_res); 72 | }, 73 | }; 74 | res 75 | } 76 | 77 | pub fn encode_packed(items: &[SolidityDataType]) -> Vec { 78 | let res = items.iter().fold(Vec::new(), |mut acc, i| { 79 | let pack = pack(i); 80 | acc.push(pack); 81 | acc 82 | }); 83 | res.join(&[][..]) 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /pallets/file-bank/src/constants.rs: -------------------------------------------------------------------------------- 1 | pub(super) const ONCE_MAX_CLEAR_FILE: u32 = 300; -------------------------------------------------------------------------------- /pallets/file-bank/src/impls/dealimpl.rs: -------------------------------------------------------------------------------- 1 | use crate::*; 2 | 3 | impl DealInfo { 4 | pub fn complete_part(&mut self, miner: AccountOf, index: u8) -> DispatchResult { 5 | for complete_info in &self.complete_list { 6 | ensure!(index != complete_info.index, Error::::Existed); 7 | ensure!(miner != complete_info.miner, Error::::Existed); 8 | } 9 | 10 | T::MinerControl::lock_space(&miner, FRAGMENT_SIZE * self.segment_list.len() as u128)?; 11 | 12 | let complete_info = CompleteInfo:: { 13 | index, 14 | miner, 15 | }; 16 | 17 | self.complete_list.try_push(complete_info).map_err(|_| Error::::BoundedVecError)?; 18 | 19 | Ok(()) 20 | } 21 | 22 | pub fn completed_all(&self) -> DispatchResult { 23 | for complete_info in self.complete_list.iter() { 24 | let replace_space = FRAGMENT_SIZE 25 | .checked_mul(self.segment_list.len() as u128) 26 | .ok_or(Error::::Overflow)?; 27 | T::MinerControl::increase_replace_space(&complete_info.miner, replace_space)?; 28 | } 29 | 30 | Ok(()) 31 | } 32 | 33 | pub fn force_unlock_space(&self) -> DispatchResult { 34 | for complete_info in self.complete_list.iter() { 35 | let space = FRAGMENT_SIZE 36 | .checked_mul(self.segment_list.len() as u128) 37 | .ok_or(Error::::Overflow)?; 38 | T::MinerControl::unlock_space(&complete_info.miner, space)?; 39 | } 40 | 41 | Ok(()) 42 | } 43 | } -------------------------------------------------------------------------------- /pallets/file-bank/src/impls/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod receptionist; 2 | pub mod dealimpl; 3 | -------------------------------------------------------------------------------- /pallets/mq/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | authors = ["CESS Network"] 3 | edition = "2021" 4 | name = "ces-pallet-mq" 5 | version = "4.1.0" 6 | license = "Apache 2.0" 7 | homepage = "https://cess.cloud/" 8 | repository = "https://github.com/CESSProject/cess" 9 | 10 | [package.metadata.docs.rs] 11 | targets = ["x86_64-unknown-linux-gnu"] 12 | 13 | [dependencies] 14 | chrono = { workspace = true } 15 | frame-support = { workspace = true } 16 | frame-system = { workspace = true } 17 | parity-scale-codec = { workspace = true, features = ["derive"] } 18 | primitive-types = { workspace = true, features = ["codec", "byteorder"] } 19 | scale-info = { workspace = true, features = ["derive"] } 20 | serde = { workspace = true, optional = true } 21 | serde_json = { workspace = true, features = ["alloc"] } 22 | sp-core = { workspace = true } 23 | sp-io = { workspace = true } 24 | sp-runtime = { workspace = true } 25 | sp-std = { workspace = true } 26 | sp-weights = { workspace = true } 27 | 28 | ces-types = { workspace = true, features = ["enable_serde"] } 29 | sgx-attestation = { workspace = true } 30 | 31 | 32 | [dev-dependencies] 33 | 34 | 35 | [features] 36 | default = ["std"] 37 | std = [ 38 | "ces-types/enable_serde", 39 | "frame-support/std", 40 | "frame-system/std", 41 | "parity-scale-codec/std", 42 | "primitive-types/std", 43 | "scale-info/std", 44 | "serde/alloc", 45 | "serde/derive", 46 | "sgx-attestation/std", 47 | "sp-core/std", 48 | "sp-io/std", 49 | "sp-runtime/std", 50 | "sp-std/std", 51 | ] 52 | runtime-benchmarks = [] 53 | try-runtime = ["frame-support/try-runtime"] 54 | native = [] 55 | -------------------------------------------------------------------------------- /pallets/mq/runtime-api/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "ces-pallet-mq-runtime-api" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | [dependencies] 7 | sp-api = { workspace = true } 8 | ces-mq = { workspace = true } 9 | 10 | 11 | [features] 12 | default = ["std"] 13 | std = [ 14 | "sp-api/std", 15 | ] 16 | -------------------------------------------------------------------------------- /pallets/mq/runtime-api/src/lib.rs: -------------------------------------------------------------------------------- 1 | #![cfg_attr(not(feature = "std"), no_std)] 2 | 3 | sp_api::decl_runtime_apis! { 4 | pub trait MqApi { 5 | fn sender_sequence(sender: &ces_mq::MessageOrigin) -> Option; 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /pallets/oss/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "pallet-oss" 3 | version = "0.7.0" 4 | edition = "2021" 5 | 6 | [dependencies] 7 | codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive", "max-encoded-len"] } 8 | frame-support = { workspace = true } 9 | frame-system = { workspace = true } 10 | frame-benchmarking = { workspace = true, optional = true} 11 | hex = { workspace = true, features = ["alloc"] } 12 | log = { workspace = true } 13 | scale-info = { workspace = true, features = ["derive"] } 14 | sp-core = { workspace = true } 15 | sp-io = { workspace = true } 16 | sp-std = { workspace = true } 17 | sp-runtime = { workspace = true } 18 | 19 | #local dependencies 20 | cp-cess-common = { workspace = true } 21 | pallet-evm-account-mapping = { workspace = true } 22 | 23 | [dev-dependencies] 24 | sp-core = { workspace = true } 25 | pallet-balances = { workspace = true } 26 | sp-io = { workspace = true } 27 | 28 | [features] 29 | default = ["std"] 30 | std = [ 31 | "log/std", 32 | "codec/std", 33 | "scale-info/std", 34 | "sp-std/std", 35 | "sp-runtime/std", 36 | "frame-support/std", 37 | "frame-system/std", 38 | "cp-cess-common/std", 39 | "frame-benchmarking/std", 40 | ] 41 | 42 | runtime-benchmarks = [ 43 | "frame-benchmarking/runtime-benchmarks", 44 | ] 45 | try-runtime = [] 46 | -------------------------------------------------------------------------------- /pallets/oss/README.md: -------------------------------------------------------------------------------- 1 | # Oss Module 2 | 3 | Manage meta information of DeOss. 4 | 5 | ## Overview 6 | 7 | DeOss is a server used to upload and download files in the cess network. Process files uploaded by users, distribute them to storage nodes, and put the meta information of the files on the chain. 8 | 9 | If you want to make your DeOss public and provide services to others, you need to register in this module and make your information public on the network. 10 | 11 | ## Terminology 12 | 13 | ### Authorize Operator 14 | 15 | In the CESS network, if users want to upload their own files through DeOss, they need to authorize the designated DeOss account. 16 | 17 | After authorization, DeOss will have the authority to perform the following operations for the user: 18 | 19 | * Upload Files. 20 | * Delete Files. 21 | * Create Bucket. 22 | * Delete Bucket. 23 | 24 | Currently, it supports authorizing multiple DeOss to provide services to users. 25 | 26 | ## Extrinsic 27 | 28 | * `authorize()` - User authorization DeOss function. 29 | * `cancel_authorize()` - The user cancels the function of authorizing a certain DeOss. 30 | * `register()` - DeOss registration function, after registration, users across the entire network will be able to access the service through the endpoint or peer id provided by DeOss. 31 | * `update()` - DeOss updates the current endpoint or peer id information. 32 | * `destroy()` - DeOss logout function. 33 | 34 | ## Interface 35 | 36 | ### OssFindAuthor 37 | 38 | Interface provided to other modules for detecting permissions 39 | 40 | #### Function 41 | 42 | * `is_authorized` - Determine whether the user has authorized the DeOss. 43 | 44 | #### Usage 45 | 46 | in pallet::Config 47 | 48 | ```rust 49 | pub trait Config: frame_system::Config + sp_std::fmt::Debug { 50 | // ... 51 | type OssFindAuthor: OssFindAuthor; 52 | // ... 53 | } 54 | ``` 55 | 56 | in runtime.rs 57 | ```rust 58 | impl pallet_file_bank::Config for Runtime { 59 | // ... 60 | type OssFindAuthor = Oss; 61 | // ... 62 | } 63 | ``` 64 | -------------------------------------------------------------------------------- /pallets/oss/src/tests.rs: -------------------------------------------------------------------------------- 1 | use super::*; 2 | use crate::mock::{*, Oss}; 3 | use crate::Oss as OssList; 4 | use frame_support::{assert_err, assert_ok}; 5 | 6 | #[test] 7 | fn authorize_work() { 8 | ExtBuilder::default().build_and_execute(|| { 9 | let owner = account1(); 10 | let operator = account2(); 11 | 12 | assert_ok!(Oss::authorize(RuntimeOrigin::signed(owner.clone()), operator.clone())); 13 | let verify_operator = AuthorityList::::get(&owner).unwrap(); 14 | assert_eq!(verify_operator, operator); 15 | }); 16 | } 17 | 18 | #[test] 19 | fn cancel_authorize_work() { 20 | ExtBuilder::default().build_and_execute(|| { 21 | let owner = account1(); 22 | let operator = account2(); 23 | assert_ok!(Oss::authorize(RuntimeOrigin::signed(owner.clone()), operator.clone())); 24 | assert!(AuthorityList::::contains_key(&owner)); 25 | 26 | assert_ok!(Oss::cancel_authorize(RuntimeOrigin::signed(owner.clone()))); 27 | assert!(!AuthorityList::::contains_key(&owner)); 28 | }); 29 | } 30 | 31 | #[test] 32 | fn register_work() { 33 | ExtBuilder::default().build_and_execute(|| { 34 | let oss = account1(); 35 | let ip = IpAddress::IPV4([127,0,0,1], 15000); 36 | assert_ok!(Oss::register(RuntimeOrigin::signed(oss.clone()), ip.clone())); 37 | 38 | let result_ip = OssList::::get(&oss).unwrap(); 39 | assert_eq!(result_ip, ip); 40 | }); 41 | } 42 | 43 | #[test] 44 | fn register_err_registered() { 45 | ExtBuilder::default().build_and_execute(|| { 46 | let oss = account1(); 47 | let ip = IpAddress::IPV4([127,0,0,1], 15000); 48 | assert_ok!(Oss::register(RuntimeOrigin::signed(oss.clone()), ip.clone())); 49 | assert_err!(Oss::register(RuntimeOrigin::signed(oss.clone()), ip.clone()), Error::::Registered); 50 | }); 51 | } 52 | 53 | #[test] 54 | fn update_work() { 55 | ExtBuilder::default().build_and_execute(|| { 56 | let oss = account1(); 57 | let ip = IpAddress::IPV4([127,0,0,1], 15000); 58 | assert_ok!(Oss::register(RuntimeOrigin::signed(oss.clone()), ip.clone())); 59 | 60 | let result_ip = OssList::::get(&oss).unwrap(); 61 | assert_eq!(result_ip, ip); 62 | 63 | let new_ip = IpAddress::IPV4([127,0,0,1], 15001); 64 | assert_ok!(Oss::update(RuntimeOrigin::signed(oss.clone()), new_ip.clone())); 65 | 66 | let result_ip = OssList::::get(&oss).unwrap(); 67 | assert_eq!(result_ip, new_ip); 68 | }); 69 | } 70 | -------------------------------------------------------------------------------- /pallets/oss/src/types.rs: -------------------------------------------------------------------------------- 1 | use super::*; 2 | 3 | #[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug, MaxEncodedLen, TypeInfo)] 4 | pub struct OssInfo { 5 | pub(super) peer_id: PeerId, 6 | pub(super) domain: BoundedVec>, 7 | } 8 | 9 | #[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug, MaxEncodedLen, TypeInfo)] 10 | #[scale_info(skip_type_params(T))] 11 | #[codec(mel_bound())] 12 | pub struct ProxyAuthPayload { 13 | pub(super) oss: AccountOf, 14 | pub(super) exp: BlockNumberFor, 15 | } -------------------------------------------------------------------------------- /pallets/reservoir/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "pallet-reservoir" 3 | authors = ["CESS LAB"] 4 | version = "0.7.7" 5 | edition = "2021" 6 | license = "Apache-2.0" 7 | repository = "https://github.com/CESSProject/cess" 8 | description = "FRAME pallet for segment management" 9 | readme = "README.md" 10 | 11 | [dependencies] 12 | codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive", "max-encoded-len"] } 13 | scale-info = { workspace = true, features = ["derive"] } 14 | sp-std = { workspace = true } 15 | sp-runtime = { workspace = true } 16 | 17 | # substrate 18 | frame-support = { workspace = true } 19 | frame-system = { workspace = true } 20 | pallet-balances = { workspace = true } 21 | 22 | [features] 23 | default = ["std"] 24 | std = [ 25 | "codec/std", 26 | "scale-info/std", 27 | "sp-std/std", 28 | "frame-support/std", 29 | "frame-system/std", 30 | ] 31 | try-runtime = [] 32 | -------------------------------------------------------------------------------- /pallets/reservoir/src/impls.rs: -------------------------------------------------------------------------------- 1 | use super::*; 2 | use sp_runtime::traits::Zero; 3 | 4 | impl Default for ReservoirInfo { 5 | fn default() -> Self { 6 | ReservoirInfo:: { 7 | free_balance: Balance::zero(), 8 | borrow_balance: Balance::zero(), 9 | store_balance: Balance::zero(), 10 | } 11 | } 12 | } 13 | 14 | impl Default for UserHold { 15 | fn default() -> Self { 16 | UserHold:: { 17 | free: Balance::zero(), 18 | staking: Balance::zero(), 19 | } 20 | } 21 | } -------------------------------------------------------------------------------- /pallets/reservoir/src/types.rs: -------------------------------------------------------------------------------- 1 | use super::*; 2 | 3 | #[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug, MaxEncodedLen, TypeInfo)] 4 | pub struct ReservoirInfo { 5 | pub(super) free_balance: Balance, 6 | pub(super) borrow_balance: Balance, 7 | pub(super) store_balance: Balance, 8 | } 9 | 10 | #[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug, MaxEncodedLen, TypeInfo)] 11 | #[scale_info(skip_type_params(T))] 12 | #[codec(mel_bound())] 13 | pub struct BorrowInfo { 14 | pub(super) free: BalanceOf, 15 | pub(super) lender: AccountOf, 16 | pub(super) staking: BalanceOf, 17 | pub(super) deadline: BlockNumberFor, 18 | } 19 | 20 | #[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug, MaxEncodedLen, TypeInfo)] 21 | pub struct UserHold { 22 | pub(super) free: Balance, 23 | pub(super) staking: Balance, 24 | } 25 | 26 | #[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug, MaxEncodedLen, TypeInfo)] 27 | #[scale_info(skip_type_params(T))] 28 | #[codec(mel_bound())] 29 | pub struct EventInfo { 30 | pub(super) quota: u32, 31 | pub(super) deadline: BlockNumberFor, 32 | pub(super) unit_amount: BalanceOf, 33 | pub(super) borrow_period: BlockNumberFor, 34 | pub(super) use_type: UseType, 35 | } 36 | 37 | #[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug, MaxEncodedLen, TypeInfo)] 38 | pub enum UseType { 39 | MinerStaking, 40 | } -------------------------------------------------------------------------------- /pallets/scheduler-credit/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "pallet-scheduler-credit" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 7 | 8 | [dependencies] 9 | log = { workspace = true } 10 | codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive", "max-encoded-len"] } 11 | scale-info = { workspace = true, features = ["derive"] } 12 | sp-std = { workspace = true } 13 | sp-runtime = { workspace = true } 14 | frame-support = { workspace = true } 15 | frame-system = { workspace = true } 16 | 17 | #lock dependencies 18 | cp-scheduler-credit = { workspace = true } 19 | cessp-consensus-rrsc = { workspace = true } 20 | cp-cess-common = { workspace = true } 21 | 22 | [dev-dependencies] 23 | sp-io = { workspace = true } 24 | sp-core = { workspace = true } 25 | 26 | [features] 27 | default = ["std"] 28 | std = [ 29 | "log/std", 30 | "codec/std", 31 | "scale-info/std", 32 | "sp-std/std", 33 | "sp-runtime/std", 34 | "frame-support/std", 35 | "frame-system/std", 36 | "cp-scheduler-credit/std", 37 | "cessp-consensus-rrsc/std", 38 | ] 39 | try-runtime = [] -------------------------------------------------------------------------------- /pallets/scheduler-credit/README.md: -------------------------------------------------------------------------------- 1 | ## Scheduler Credit Module 2 | 3 | The scheduler reputation module is used to record some operations performed by the scheduler in order to maintain 4 | the chain state, including records of processing files and records of penalties for failing to achieve scheduling goals. 5 | Finally, the system will give a score to the scheduler according to the set algorithm. This score will be used to 6 | decide validators as part of the R2S consensus. 7 | 8 | ### Terminology 9 | 10 | ### Interface 11 | #### Trait -------------------------------------------------------------------------------- /pallets/scheduler-credit/src/mock.rs: -------------------------------------------------------------------------------- 1 | //! Test utilities 2 | 3 | use super::*; 4 | use crate as scheduler_credit; 5 | use frame_support::{parameter_types, traits::ConstU32}; 6 | use sp_core::H256; 7 | use sp_runtime::{ 8 | BuildStorage, 9 | traits::{BlakeTwo256, IdentityLookup}, 10 | }; 11 | use std::marker::PhantomData; 12 | 13 | pub(crate) type AccountId = u32; 14 | type Block = frame_system::mocking::MockBlock; 15 | type BlockNumber = u64; 16 | parameter_types! { 17 | pub const BlockHashCount: u64 = 100; 18 | } 19 | 20 | impl frame_system::Config for Test { 21 | type BaseCallFilter = frame_support::traits::Everything; 22 | type BlockWeights = (); 23 | type BlockLength = (); 24 | type RuntimeOrigin = RuntimeOrigin; 25 | type RuntimeCall = RuntimeCall; 26 | type Block = Block; 27 | type Nonce = u64; 28 | type Hash = H256; 29 | type Hashing = BlakeTwo256; 30 | type AccountId = AccountId; 31 | type Lookup = IdentityLookup; 32 | type RuntimeEvent = RuntimeEvent; 33 | type BlockHashCount = BlockHashCount; 34 | type DbWeight = (); 35 | type Version = (); 36 | type PalletInfo = PalletInfo; 37 | type AccountData = (); 38 | type OnNewAccount = (); 39 | type OnKilledAccount = (); 40 | type SystemWeightInfo = (); 41 | type SS58Prefix = (); 42 | type OnSetCode = (); 43 | type MaxConsumers = ConstU32<16>; 44 | } 45 | 46 | pub struct MockStashAccountFinder(PhantomData); 47 | 48 | impl SchedulerStashAccountFinder 49 | for MockStashAccountFinder 50 | { 51 | fn find_stash_account_id(ctrl_account_id: &AccountId) -> Option { 52 | Some(ctrl_account_id.clone()) 53 | } 54 | } 55 | 56 | parameter_types! { 57 | pub const PeriodDuration: BlockNumber = 3600; 58 | } 59 | 60 | impl Config for Test { 61 | type StashAccountFinder = MockStashAccountFinder; 62 | 63 | type PeriodDuration = PeriodDuration; 64 | } 65 | 66 | frame_support::construct_runtime!( 67 | pub enum Test { 68 | System: frame_system::{Pallet, Call, Config, Storage, Event}, 69 | SchedulerCredit: scheduler_credit::{Pallet, Storage}, 70 | } 71 | ); 72 | 73 | pub struct ExtBuilder; 74 | 75 | impl Default for ExtBuilder { 76 | fn default() -> Self { 77 | Self {} 78 | } 79 | } 80 | 81 | impl ExtBuilder { 82 | fn build(self) -> sp_io::TestExternalities { 83 | let storage = frame_system::GenesisConfig::::default().build_storage().unwrap(); 84 | sp_io::TestExternalities::from(storage) 85 | } 86 | 87 | pub fn build_and_execute(self, test: impl FnOnce() -> ()) { 88 | self.build().execute_with(test); 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /pallets/scheduler-credit/src/tests.rs: -------------------------------------------------------------------------------- 1 | use super::*; 2 | use crate::mock::*; 3 | use cp_scheduler_credit::SchedulerCreditCounter; 4 | use cessp_consensus_rrsc::traits::ValidatorCredits; 5 | 6 | #[test] 7 | fn figure_credit_scores_works() { 8 | ExtBuilder::default().build_and_execute(|| { 9 | let _ = as SchedulerCreditCounter>::record_proceed_block_size(&1, 100); 10 | let _ = as SchedulerCreditCounter>::record_proceed_block_size(&1, 100); 11 | assert_eq!(200, CurrentCounters::::get(1).proceed_block_size); 12 | 13 | let _ = as SchedulerCreditCounter>::record_proceed_block_size(&2, 50); 14 | let _ = as SchedulerCreditCounter>::record_proceed_block_size(&3, 150); 15 | 16 | // switch period 17 | let period_duration = PeriodDuration::get(); 18 | System::set_block_number(period_duration); 19 | Pallet::::on_initialize(System::block_number()); 20 | 21 | // figure credit values works 22 | assert_eq!(HistoryCreditValues::::get(&0, &1), 500); 23 | assert_eq!(HistoryCreditValues::::get(&0, &2), 125); 24 | assert_eq!(HistoryCreditValues::::get(&0, &3), 375); 25 | 26 | // clear CurrentCounters works 27 | assert_eq!(CurrentCounters::::contains_key(&1), false); 28 | assert_eq!(CurrentCounters::::contains_key(&2), false); 29 | assert_eq!(CurrentCounters::::contains_key(&3), false); 30 | 31 | // figure credit scores works 32 | let vc_map = as ValidatorCredits>::credits(0); 33 | assert_eq!(&250, vc_map.get(&1).unwrap()); 34 | assert_eq!(&62, vc_map.get(&2).unwrap()); 35 | assert_eq!(&187, vc_map.get(&3).unwrap()); 36 | }); 37 | } 38 | -------------------------------------------------------------------------------- /pallets/sminer/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "pallet-sminer" 3 | authors = ["CESS LAB"] 4 | version = "0.7.6" 5 | edition = "2021" 6 | license = "Apache-2.0" 7 | repository = "https://github.com/CESSProject/cess" 8 | description = "FRAME pallet for sminer management" 9 | readme = "README.md" 10 | 11 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 12 | 13 | [dependencies] 14 | log = { workspace = true } 15 | serde = { workspace = true, optional = true } 16 | codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive"] } 17 | scale-info = { workspace = true, features = ["derive"] } 18 | rand_chacha = { workspace = true, optional = true } 19 | pallet-preimage = { workspace = true } 20 | 21 | #local crate 22 | pallet-reservoir = { workspace = true } 23 | pallet-cess-treasury = { workspace = true } 24 | pallet-cess-staking = { workspace = true } 25 | pallet-tee-worker = { workspace = true } 26 | pallet-storage-handler = { workspace = true } 27 | ces-types = { workspace = true, features = ["enable_serde"] } 28 | cp-enclave-verify = { workspace = true } 29 | cp-bloom-filter = { workspace = true } 30 | cp-cess-common = { workspace = true } 31 | 32 | # substrate 33 | frame-benchmarking = { workspace = true, optional = true } 34 | frame-support = { workspace = true } 35 | frame-system = { workspace = true } 36 | sp-io = { workspace = true } 37 | sp-std = { workspace = true } 38 | pallet-balances = { workspace = true } 39 | pallet-timestamp = { workspace = true } 40 | sp-core = { workspace = true } 41 | sp-runtime = { workspace = true } 42 | pallet-scheduler = { workspace = true } 43 | sp-staking = { workspace = true, features = ["serde"] } 44 | 45 | [dev-dependencies] 46 | pallet-scheduler = { workspace = true } 47 | pallet-balances = { workspace = true } 48 | 49 | [features] 50 | default = ["std"] 51 | std = [ 52 | "codec/std", 53 | "frame-support/std", 54 | "frame-system/std", 55 | "scale-info/std", 56 | "serde", 57 | "sp-io/std", 58 | "sp-runtime/std", 59 | "sp-std/std", 60 | "pallet-timestamp/std", 61 | "pallet-scheduler/std", 62 | "frame-benchmarking/std", 63 | "cp-cess-common/std", 64 | "pallet-cess-treasury/std", 65 | "pallet-tee-worker/std", 66 | "pallet-reservoir/std", 67 | ] 68 | 69 | runtime-benchmarks = [ 70 | "frame-benchmarking/runtime-benchmarks", 71 | "pallet-cess-staking/runtime-benchmarks", 72 | ] 73 | try-runtime = [] -------------------------------------------------------------------------------- /pallets/sminer/src/constants.rs: -------------------------------------------------------------------------------- 1 | use super::*; 2 | 3 | pub(super) const STATE_NOT_READY: &str = "not ready"; 4 | 5 | pub(super) const STATE_POSITIVE: &str = "positive"; 6 | 7 | pub(super) const STATE_FROZEN: &str = "frozen"; 8 | 9 | pub(super) const STATE_EXIT: &str = "exit"; 10 | 11 | pub(super) const STATE_LOCK: &str = "lock"; 12 | 13 | pub(super) const STATE_OFFLINE: &str = "offline"; 14 | 15 | pub(super) const FAUCET_VALUE: u128 = 2_000_000_000_000_000_000; 16 | 17 | pub(super) const IDLE_MUTI: Perbill = Perbill::from_percent(5); 18 | 19 | pub(super) const SERVICE_MUTI: Perbill = Perbill::from_percent(95); 20 | 21 | pub(super) const RELEASE_NUMBER: u8 = 90; 22 | 23 | pub(super) const AOIR_PERCENT: Perbill = Perbill::from_percent(50); 24 | 25 | pub(super) const IDLE_PUNI_MUTI: Perbill = Perbill::from_percent(10); 26 | 27 | pub(super) const SERVICE_PUNI_MUTI: Perbill = Perbill::from_percent(5); 28 | 29 | pub(super) const BASE_UNIT: u128 = 4_000_000_000_000_000_000_000; -------------------------------------------------------------------------------- /pallets/storage-handler/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "pallet-storage-handler" 3 | authors = ["CESS LAB"] 4 | version = "0.7.1" 5 | edition = "2021" 6 | license = "Apache-2.0" 7 | repository = "https://github.com/CESSProject/cess" 8 | description = "FRAME pallet for sminer management" 9 | readme = "README.md" 10 | 11 | [dependencies] 12 | log = { workspace = true } 13 | codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive"] } 14 | scale-info = { workspace = true, features = ["derive"] } 15 | serde = { workspace = true, optional = true } 16 | 17 | # substrate pallet 18 | frame-support = { workspace = true } 19 | frame-system = { workspace = true } 20 | frame-benchmarking = { workspace = true } 21 | pallet-balances = { workspace = true } 22 | 23 | # substrate primitives 24 | sp-core = { workspace = true } 25 | sp-std = { workspace = true } 26 | sp-runtime = { workspace = true } 27 | 28 | # local dependencies 29 | cp-cess-common = { workspace = true } 30 | pallet-cess-treasury = { workspace = true } 31 | 32 | [features] 33 | default = ["std"] 34 | std = [ 35 | "codec/std", 36 | "scale-info/std", 37 | "serde", 38 | "frame-support/std", 39 | "frame-system/std", 40 | "sp-std/std", 41 | "sp-runtime/std", 42 | "frame-benchmarking/std", 43 | "pallet-cess-treasury/std", 44 | ] 45 | 46 | try-runtime = [ "frame-support/try-runtime" ] 47 | 48 | runtime-benchmarks = [ 49 | "frame-benchmarking/runtime-benchmarks", 50 | ] -------------------------------------------------------------------------------- /pallets/storage-handler/src/types.rs: -------------------------------------------------------------------------------- 1 | use super::*; 2 | 3 | #[derive(PartialEq, Eq, Encode, Decode, Clone, RuntimeDebug, MaxEncodedLen, TypeInfo)] 4 | #[scale_info(skip_type_params(T))] 5 | #[codec(mel_bound())] 6 | pub struct OrderInfo { 7 | pub(super) territory_name: TerrName, 8 | pub(super) pay: BalanceOf, 9 | pub(super) gib_count: u32, 10 | pub(super) days: u32, 11 | pub(super) expired: BlockNumberFor, 12 | pub(super) target_acc: AccountOf, 13 | pub(super) order_type: OrderType, 14 | } 15 | 16 | #[derive(PartialEq, Eq, Encode, Decode, Clone, RuntimeDebug, MaxEncodedLen, TypeInfo)] 17 | pub enum OrderType { 18 | Buy, 19 | Expansion, 20 | Renewal, 21 | } 22 | 23 | #[derive(PartialEq, Eq, Encode, Decode, Clone, RuntimeDebug, MaxEncodedLen, TypeInfo)] 24 | #[scale_info(skip_type_params(T))] 25 | #[codec(mel_bound())] 26 | pub struct TerritoryInfo { 27 | pub(super) token: TokenId, 28 | pub(super) total_space: u128, 29 | pub(super) used_space: u128, 30 | pub(super) locked_space: u128, 31 | pub(super) remaining_space: u128, 32 | pub(super) start: BlockNumberFor, 33 | pub(super) deadline: BlockNumberFor, 34 | pub(super) state: TerritoryState, 35 | } 36 | 37 | #[derive(PartialEq, Eq, Encode, Decode, Clone, RuntimeDebug, MaxEncodedLen, TypeInfo)] 38 | #[scale_info(skip_type_params(T))] 39 | #[codec(mel_bound())] 40 | pub struct ConsignmentInfo { 41 | pub(super) user: AccountOf, 42 | pub(super) price: BalanceOf, 43 | pub(super) buyers: Option>, 44 | pub(super) exec: Option>, 45 | pub(super) locked: bool, 46 | } 47 | 48 | #[derive(PartialEq, Eq, Encode, Decode, Clone, RuntimeDebug, MaxEncodedLen, TypeInfo)] 49 | pub enum TerritoryState { 50 | Active, 51 | Frozen, 52 | Expired, 53 | OnConsignment, 54 | } -------------------------------------------------------------------------------- /pallets/tee-worker/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "pallet-tee-worker" 3 | authors = ["CESS LAB"] 4 | version = "0.7.6" 5 | edition = "2021" 6 | license = "Apache-2.0" 7 | repository = "https://github.com/CESSProject/cess" 8 | description = "FRAME pallet for TEE Worker management" 9 | readme = "README.md" 10 | 11 | [dependencies] 12 | log = { workspace = true } 13 | base64 = { workspace = true } 14 | chrono = { workspace = true } 15 | codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive", "max-encoded-len"] } 16 | frame-benchmarking = { workspace = true, optional = true } 17 | frame-support = { workspace = true } 18 | frame-system = { workspace = true } 19 | scale-info = { workspace = true, features = ['derive'] } 20 | serde = { workspace = true, optional = true } 21 | serde_json = { workspace = true, features = ['alloc'] } 22 | sp-core = { workspace = true } 23 | sp-io = { workspace = true } 24 | sp-runtime = { workspace = true } 25 | sp-std = { workspace = true } 26 | 27 | # local dependencies 28 | cp-cess-common = { workspace = true } 29 | cp-scheduler-credit = { workspace = true } 30 | pallet-cess-staking = { workspace = true } 31 | sgx-attestation = { workspace = true } 32 | ces-types = { workspace = true, features = ["enable_serde"] } 33 | ces-pallet-mq ={ workspace = true } 34 | 35 | 36 | [dev-dependencies] 37 | pallet-balances = { workspace = true } 38 | pallet-timestamp = { workspace = true } 39 | sp-staking = { workspace = true } 40 | sp-npos-elections = { workspace = true } 41 | frame-election-provider-support = { workspace = true } 42 | pallet-session = { workspace = true } 43 | pallet-bags-list = { workspace = true } 44 | pallet-scheduler-credit = { workspace = true } 45 | hex ={ workspace = true } 46 | 47 | [features] 48 | default = ["std"] 49 | std = [ 50 | "ces-types/enable_serde", 51 | "ces-pallet-mq/std", 52 | "codec/std", 53 | "chrono/std", 54 | "cp-cess-common/std", 55 | "frame-benchmarking/std", 56 | "frame-support/std", 57 | "frame-system/std", 58 | "pallet-cess-staking/std", 59 | "pallet-session/std", 60 | "scale-info/std", 61 | "serde", 62 | "sgx-attestation/std", 63 | "sp-core/std", 64 | "sp-io/std", 65 | "sp-runtime/std", 66 | "sp-std/std", 67 | ] 68 | 69 | runtime-benchmarks = [ 70 | "frame-benchmarking/runtime-benchmarks", 71 | ] 72 | native = [] 73 | try-runtime = [] -------------------------------------------------------------------------------- /pallets/tee-worker/src/functions.rs: -------------------------------------------------------------------------------- 1 | use crate::*; 2 | 3 | impl Pallet { 4 | pub fn check_time_unix(signing_time: &u64) -> bool { 5 | let expiration = 4 * 60 * 60 * 1000; // 4 hours 6 | let now = T::UnixTime::now().as_millis().saturated_into::(); 7 | if signing_time < &now && now <= signing_time + expiration { 8 | return true 9 | } else { 10 | return false 11 | } 12 | } 13 | 14 | pub fn clear_mission(now: BlockNumberFor) -> Weight { 15 | let mut weight: Weight = Weight::zero(); 16 | 17 | let least = T::AtLeastWorkBlock::get(); 18 | 19 | for (pubkey, last_block) in LastWork::::iter() { 20 | weight = weight.saturating_add(T::DbWeight::get().reads(1)); 21 | if last_block.saturating_add(least) < now { 22 | if let Ok(temp_weight) = Self::execute_exit(pubkey.clone()) { 23 | weight.saturating_add(temp_weight); 24 | LastWork::::remove(pubkey.clone()); 25 | LastRefresh::::remove(pubkey.clone()); 26 | Self::deposit_event(Event::::ClearInvalidTee{ pubkey }); 27 | } 28 | } 29 | } 30 | 31 | return weight 32 | } 33 | 34 | pub fn execute_exit(pbk: WorkerPublicKey) -> Result { 35 | let mut weight: Weight = Weight::zero(); 36 | 37 | if let Some(first_holder) = MasterKeyFirstHolder::::get() { 38 | ensure!(first_holder != pbk, Error::::CannotExitMasterKeyHolder); 39 | } 40 | weight = weight.saturating_add(T::DbWeight::get().reads(1)); 41 | 42 | Workers::::remove(&pbk); 43 | weight = weight.saturating_add(T::DbWeight::get().writes(1)); 44 | 45 | WorkerAddedAt::::remove(&pbk); 46 | weight = weight.saturating_add(T::DbWeight::get().writes(1)); 47 | 48 | Endpoints::::remove(&pbk); 49 | weight = weight.saturating_add(T::DbWeight::get().writes(1)); 50 | 51 | ValidationTypeList::::mutate(|puk_list| -> DispatchResult { 52 | puk_list.retain(|g| *g != pbk); 53 | Ok(()) 54 | })?; 55 | weight = weight.saturating_add(T::DbWeight::get().reads_writes(1, 1)); 56 | 57 | Ok(weight) 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /pallets/tee-worker/src/mock.rs: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/CESSProject/cess/d9341e49b0e52968ffee9d7d56aeb6ba69c213d5/pallets/tee-worker/src/mock.rs -------------------------------------------------------------------------------- /pallets/tee-worker/src/tests.rs: -------------------------------------------------------------------------------- 1 | 2 | // use super::*; 3 | // use libp2p::core::{ 4 | // multiaddr::{Multiaddr, Protocol}, 5 | // PeerId, 6 | // }; 7 | 8 | // #[test] 9 | // fn cryptos_are_compatible() { 10 | // use sp_core::crypto::Pair; 11 | 12 | // let libp2p_secret = libp2p::identity::Keypair::generate_ed25519(); 13 | // let libp2p_public = libp2p_secret.public(); 14 | 15 | // let sp_core_secret = { 16 | // let libp2p::identity::Keypair::Ed25519(libp2p_ed_secret) = libp2p_secret.clone(); 17 | // sp_core::ed25519::Pair::from_seed_slice(&libp2p_ed_secret.secret().as_ref()).unwrap() 18 | // }; 19 | 20 | // let sp_core_public = sp_core_secret.public(); 21 | 22 | // println!("libp2p_public: {:?}, sp_core public: {:?}", libp2p_public, sp_core_public); 23 | 24 | // let message = b"we are more powerful than not to be better"; 25 | 26 | // let libp2p_signature = libp2p_secret.sign(message).unwrap(); 27 | // let sp_core_signature = sp_core_secret.sign(message); // no error expected... 28 | 29 | // assert!(sp_core::ed25519::Pair::verify( 30 | // &sp_core::ed25519::Signature::from_slice(&libp2p_signature).unwrap(), 31 | // message, 32 | // &sp_core_public 33 | // )); 34 | // assert!(libp2p_public.verify(message, sp_core_signature.as_ref())); 35 | // } 36 | -------------------------------------------------------------------------------- /pallets/tee-worker/src/types.rs: -------------------------------------------------------------------------------- 1 | use super::*; 2 | 3 | #[derive(PartialEq, Eq, Encode, Decode, Clone, RuntimeDebug, MaxEncodedLen, TypeInfo)] 4 | #[scale_info(skip_type_params(T))] 5 | #[codec(mel_bound())] 6 | pub struct TeeWorkerInfo { 7 | pub worker_account: AccountOf, 8 | pub peer_id: PeerId, 9 | pub bond_stash: Option>, 10 | pub end_point: EndPoint, 11 | pub tee_type: TeeType, 12 | } 13 | 14 | #[derive(PartialEq, Eq, Encode, Decode, Clone, RuntimeDebug, Default, MaxEncodedLen, TypeInfo)] 15 | pub struct SgxAttestationReport { 16 | pub report_json_raw: Report, 17 | pub sign: ReportSign, 18 | pub cert_der: Cert, 19 | } 20 | 21 | #[derive(PartialEq, Eq, Encode, Decode, Clone, RuntimeDebug, MaxEncodedLen, TypeInfo)] 22 | pub enum TeeType { 23 | Full, 24 | Verifier, 25 | Marker, 26 | } -------------------------------------------------------------------------------- /rust-toolchain.toml: -------------------------------------------------------------------------------- 1 | [toolchain] 2 | channel = "1.82.0" # rustc 1.82.0 (f6e511eec 2024-10-15) 3 | components = [ 4 | "cargo", 5 | "clippy", 6 | "rust-analyzer", 7 | "rust-src", 8 | "rust-std", 9 | "rustc-dev", 10 | "rustc", 11 | "rustfmt", 12 | ] 13 | targets = [ "wasm32-unknown-unknown" ] 14 | profile = "minimal" 15 | -------------------------------------------------------------------------------- /rustfmt.toml: -------------------------------------------------------------------------------- 1 | # Basic 2 | edition = "2021" 3 | hard_tabs = true 4 | tab_spaces = 4 5 | max_width = 120 6 | use_small_heuristics = "Max" 7 | # Imports 8 | imports_granularity = "Crate" 9 | reorder_imports = true 10 | # Consistency 11 | newline_style = "Unix" 12 | # Format comments 13 | comment_width = 120 14 | wrap_comments = true 15 | # Misc 16 | chain_width = 80 17 | spaces_around_ranges = false 18 | binop_separator = "Back" 19 | reorder_impl_items = false 20 | match_arm_leading_pipes = "Preserve" 21 | match_arm_blocks = false 22 | match_block_trailing_comma = true 23 | trailing_comma = "Vertical" 24 | trailing_semicolon = false 25 | use_field_init_shorthand = true -------------------------------------------------------------------------------- /scripts/docker/cargo-config.toml: -------------------------------------------------------------------------------- 1 | [source.crates-io] 2 | replace-with = 'rsproxy-sparse' 3 | 4 | [source.rsproxy] 5 | registry = "https://rsproxy.cn/crates.io-index" 6 | [source.rsproxy-sparse] 7 | registry = "sparse+https://rsproxy.cn/index/" 8 | 9 | [registries.rsproxy] 10 | index = "https://rsproxy.cn/crates.io-index" 11 | 12 | [net] 13 | git-fetch-with-cli = true -------------------------------------------------------------------------------- /scripts/docker/ceseal/gramine/Dockerfile: -------------------------------------------------------------------------------- 1 | # ====== build ceseal ====== 2 | 3 | FROM cesslab/gramine-rust-env:latest AS builder 4 | 5 | WORKDIR /root 6 | 7 | ARG https_proxy 8 | ARG http_proxy 9 | ARG IAS_API_KEY 10 | ARG IAS_SPID 11 | ARG SGX_ENV 12 | ARG BUILD=release 13 | ARG OA 14 | ARG VC 15 | ARG GIT_SHA 16 | 17 | RUN <> .bashrc && \ 30 | .cargo/bin/rustup component add rust-src rust-analysis clippy && \ 31 | .cargo/bin/rustup target add wasm32-unknown-unknown && \ 32 | rm rustup-init && rm -rf .cargo/registry && rm -rf .cargo/git 33 | 34 | RUN .cargo/bin/rustup install 1.82.0 && \ 35 | .cargo/bin/rustup default 1.82.0 && \ 36 | .cargo/bin/rustup component add cargo clippy rust-analyzer rust-src rust-std rustc-dev rustc rustfmt && \ 37 | .cargo/bin/rustup target add wasm32-unknown-unknown -------------------------------------------------------------------------------- /scripts/docker/env/intel-sgx-deno.Dockerfile: -------------------------------------------------------------------------------- 1 | FROM cesslab/intel-sgx-env:latest 2 | ARG https_proxy 3 | ARG http_proxy 4 | 5 | RUN curl -fsSL https://deno.land/x/install/install.sh | sh 6 | ENV DENO_INSTALL=/root/.deno 7 | ENV PATH=/root/.deno/bin:${PATH} -------------------------------------------------------------------------------- /scripts/docker/env/intel-sgx.Dockerfile: -------------------------------------------------------------------------------- 1 | FROM ubuntu:20.04 AS runtime 2 | 3 | ARG https_proxy 4 | ARG http_proxy 5 | ARG DEBIAN_FRONTEND=noninteractive 6 | ARG TZ=Etc/UTC 7 | 8 | RUN apt-get update && \ 9 | apt-get install -y curl gnupg2 tini libprotobuf-c1 unzip && \ 10 | curl -fsSLo /usr/share/keyrings/intel-sgx-deb.asc https://download.01.org/intel-sgx/sgx_repo/ubuntu/intel-sgx-deb.key && \ 11 | echo "deb [arch=amd64 signed-by=/usr/share/keyrings/intel-sgx-deb.asc] https://download.01.org/intel-sgx/sgx_repo/ubuntu focal main" | tee /etc/apt/sources.list.d/intel-sgx.list && \ 12 | apt-get update && \ 13 | apt-get install -y sgx-aesm-service libsgx-ae-epid libsgx-ae-le libsgx-ae-pce libsgx-aesm-ecdsa-plugin libsgx-aesm-epid-plugin libsgx-aesm-launch-plugin libsgx-aesm-pce-plugin libsgx-aesm-quote-ex-plugin libsgx-enclave-common libsgx-epid libsgx-launch libsgx-quote-ex libsgx-uae-service libsgx-urts libsgx-ae-qe3 libsgx-pce-logic libsgx-qe3-logic libsgx-dcap-default-qpl libsgx-ra-network libsgx-ra-uefi && \ 14 | apt-get clean -y && \ 15 | apt-get autoremove 16 | -------------------------------------------------------------------------------- /scripts/docker/env/rust-chef-protoc.Dockerfile: -------------------------------------------------------------------------------- 1 | FROM lukemathwalker/cargo-chef:latest-rust-1-slim-bullseye AS chef 2 | ARG DEBIAN_FRONTEND='noninteractive' 3 | ARG https_proxy 4 | ARG http_proxy 5 | 6 | WORKDIR /root 7 | 8 | # Use new protobuf version instead of the default on gramine image, since we need the feature that supporting 'optional' keyword in proto3 9 | RUN apt-get update && apt-get install -y gcc llvm clang cmake make git libssl-dev pkg-config wget unzip 10 | RUN wget --show-progress -q https://github.com/protocolbuffers/protobuf/releases/download/v25.2/protoc-25.2-linux-x86_64.zip \ 11 | && unzip protoc-25.2-linux-x86_64.zip \ 12 | && cp bin/protoc /usr/local/bin/protoc \ 13 | && chmod +x /usr/local/bin/protoc \ 14 | && cp -r include/* /usr/local/include \ 15 | && rm -rf ./* \ 16 | && protoc --version 17 | -------------------------------------------------------------------------------- /scripts/docker/node/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM cesslab/rust-chef-protoc-env:latest as chef 2 | WORKDIR /node 3 | COPY ./scripts/docker/cargo-config.toml /usr/local/cargo/config 4 | 5 | FROM chef AS planner 6 | 7 | COPY pallets pallets 8 | COPY crates crates 9 | COPY standalone standalone 10 | COPY Cargo.toml Cargo.lock rustfmt.toml rust-toolchain.toml Makefile ./ 11 | 12 | RUN --mount=type=cache,target=/usr/local/cargo/registry cargo chef prepare --recipe-path recipe.json 13 | 14 | ## build Rust project use caching manner 15 | FROM chef AS builder 16 | ARG https_proxy 17 | ARG http_proxy 18 | ARG BUILD=release 19 | ARG OA 20 | ARG VC 21 | ARG GIT_SHA 22 | 23 | ENV SUBSTRATE_CLI_GIT_COMMIT_HASH=${GIT_SHA} 24 | 25 | COPY --from=planner /node/recipe.json recipe.json 26 | # Build dependencies - this is the caching Docker layer! 27 | RUN --mount=type=cache,target=/usr/local/cargo/registry cargo chef cook --release --recipe-path recipe.json 28 | 29 | # Build application 30 | COPY pallets pallets 31 | COPY crates crates 32 | COPY standalone standalone 33 | COPY Cargo.toml Cargo.lock rustfmt.toml rust-toolchain.toml Makefile ./ 34 | COPY scripts/wasm_overrides ./wasm_overrides 35 | 36 | RUN make node 37 | 38 | ## We do not need the Rust toolchain to run the binary! 39 | FROM ubuntu:20.04 AS runtime 40 | ARG https_proxy 41 | ARG http_proxy 42 | ARG CHAIN_NETWORK 43 | 44 | WORKDIR /opt/cess 45 | 46 | COPY --from=builder /node/target/release/cess-node . 47 | COPY --from=builder /node/wasm_overrides/ .wasm_overrides 48 | RUN if [ "$CHAIN_NETWORK" = "testnet" ]; then ln -s ./.wasm_overrides/testnet ./wasms; else rm -rf .wasm_overrides; fi 49 | RUN apt-get update && apt-get install -y curl && apt-get clean -y && apt-get autoremove 50 | 51 | HEALTHCHECK --interval=30s --timeout=5s --start-period=1800s --retries=10 \ 52 | CMD bash -c 'printf "GET / HTTP/1.1\n\n" > /dev/tcp/127.0.0.1/9944 || exit 1' 53 | 54 | ENTRYPOINT ["./cess-node"] -------------------------------------------------------------------------------- /scripts/run/ceseal.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | inst_seq=${INST_SEQ:-0} 4 | ceseal_port=$((${CESEAL_PORT:-8000} + $inst_seq)) 5 | pub_port=$((${PUB_PORT:-19999} + $inst_seq)) 6 | work_dir="./standalone/teeworker/ceseal/bin" 7 | 8 | export RUST_LOG=debug,ceseal=trace,cestory=trace,h2=info,hyper=info,reqwest=info,tower=info 9 | export RUST_LOG_SANITIZED=false 10 | export RUST_LOG_ANSI_COLOR=true 11 | 12 | purge_data=0 13 | getopts ":p" opt 14 | case ${opt} in 15 | p) 16 | purge_data=1 17 | ;; 18 | *) ;; 19 | esac 20 | 21 | cd $work_dir 22 | 23 | bin="./ceseal" 24 | data_dir="data-$inst_seq" 25 | log_file="$data_dir/ceseal.log" 26 | 27 | if [[ -e $log_file ]]; then 28 | rm $log_file 29 | fi 30 | if [[ $purge_data -eq 1 && -e $data_dir ]]; then 31 | echo "purge data ..." 32 | rm -rf $data_dir 33 | mkdir $data_dir 34 | fi 35 | 36 | $bin \ 37 | --port $ceseal_port \ 38 | --public-port $pub_port \ 39 | --data-dir $data_dir \ 40 | --role full |& 41 | tee $log_file 42 | -------------------------------------------------------------------------------- /scripts/run/cifrost.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | export RUST_LOG=debug,h2=info,hyper=info,reqwest=info,tower=info 4 | export RUST_LOG_SANITIZED=false 5 | export RUST_LOG_ANSI_COLOR=true 6 | export http_proxy= 7 | 8 | inst_seq=${INST_SEQ:-0} 9 | ceseal_port=$((${CESEAL_PORT:-8000} + $inst_seq)) 10 | pub_port=$((${PUB_PORT:-19999} + $inst_seq)) 11 | mnemonic=${MNEMONIC:-//Ferdie} 12 | inject_key=$(printf %064d $(($inst_seq + 1))) 13 | snapshot="--take-checkpoint" 14 | if [[ -z "${SNAPSHOT}" ]]; then 15 | snapshot= 16 | fi 17 | 18 | bin="../cess/target/debug/cifrost" 19 | log_file="./target/cifrost-$inst_seq.log" 20 | 21 | if [[ -e $log_file ]]; then 22 | rm $log_file 23 | fi 24 | 25 | $bin \ 26 | --chain-ws-endpoint ws://127.0.0.1:9944 \ 27 | --internal-endpoint http://127.0.0.1:$ceseal_port \ 28 | --public-endpoint http://127.0.0.1:$pub_port \ 29 | --inject-key $inject_key \ 30 | --mnemonic $mnemonic \ 31 | --attestation-provider none \ 32 | --longevity 16 \ 33 | $snapshot \ 34 | --operator cXjHGCWMUM8gM9YFJUK2rqq2tiFWB4huBKWdQPkWdcXcZHhHA |& 35 | tee $log_file 36 | -------------------------------------------------------------------------------- /scripts/run/node.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | export RUST_LOG=info 4 | 5 | bin=./target/debug/cess-node 6 | work_dir="./local_run" 7 | inst_seq=${INST_SEQ:-0} 8 | rpc_port=$((${RPC_PORT:-9944} + $inst_seq)) 9 | chain_spec=${CHAIN:-dev} 10 | extra_args=${XARGS:---alice} 11 | base_path=$work_dir/chain-$chain_spec-$inst_seq 12 | 13 | $bin key generate-node-key --base-path $base_path --chain $chain_spec > /dev/null 2>&1 14 | 15 | base_path_args="-d $base_path" 16 | getopts ":t" opt 17 | case ${opt} in 18 | t) 19 | base_path_args="--tmp" 20 | ;; 21 | *) ;; 22 | esac 23 | 24 | $bin \ 25 | --chain $chain_spec \ 26 | $base_path_args \ 27 | --rpc-methods=Unsafe \ 28 | --rpc-cors=all \ 29 | --rpc-port $rpc_port \ 30 | --rpc-external \ 31 | --rpc-max-response-size 32 \ 32 | --state-pruning archive $extra_args -------------------------------------------------------------------------------- /scripts/wasm_overrides/testnet/spec_100.wasm: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/CESSProject/cess/d9341e49b0e52968ffee9d7d56aeb6ba69c213d5/scripts/wasm_overrides/testnet/spec_100.wasm -------------------------------------------------------------------------------- /standalone/chain/node/build.rs: -------------------------------------------------------------------------------- 1 | use substrate_build_script_utils::{generate_cargo_keys, rerun_if_git_head_changed}; 2 | 3 | fn main() { 4 | generate_cargo_keys(); 5 | rerun_if_git_head_changed(); 6 | } 7 | -------------------------------------------------------------------------------- /standalone/chain/node/src/cli.rs: -------------------------------------------------------------------------------- 1 | use crate::eth::EthConfiguration; 2 | use polkadot_sdk::*; 3 | 4 | /// An overarching CLI command definition. 5 | #[derive(Debug, clap::Parser)] 6 | pub struct Cli { 7 | /// Possible subcommand with parameters. 8 | #[command(subcommand)] 9 | pub subcommand: Option, 10 | 11 | #[allow(missing_docs)] 12 | #[clap(flatten)] 13 | pub run: sc_cli::RunCmd, 14 | 15 | #[command(flatten)] 16 | pub eth: EthConfiguration, 17 | /// Disable automatic hardware benchmarks. 18 | /// 19 | /// By default these benchmarks are automatically ran at startup and measure 20 | /// the CPU speed, the memory bandwidth and the disk speed. 21 | /// 22 | /// The results are then printed out in the logs, and also sent as part of 23 | /// telemetry, if telemetry is enabled. 24 | #[arg(long)] 25 | pub no_hardware_benchmarks: bool, 26 | 27 | #[allow(missing_docs)] 28 | #[clap(flatten)] 29 | pub storage_monitor: sc_storage_monitor::StorageMonitorParams, 30 | } 31 | 32 | /// Possible subcommands of the main binary. 33 | #[derive(Debug, clap::Subcommand)] 34 | pub enum Subcommand { 35 | /// The custom inspect subcommand for decoding blocks and extrinsics. 36 | #[command( 37 | name = "inspect", 38 | about = "Decode given block or extrinsic using current native runtime." 39 | )] 40 | Inspect(staging_node_inspect::cli::InspectCmd), 41 | 42 | /// Sub-commands concerned with benchmarking. 43 | /// The pallet benchmarking moved to the `pallet` sub-command. 44 | #[command(subcommand)] 45 | Benchmark(frame_benchmarking_cli::BenchmarkCmd), 46 | 47 | /// Key management cli utilities 48 | #[command(subcommand)] 49 | Key(sc_cli::KeySubcommand), 50 | 51 | /// Verify a signature for a message, provided on STDIN, with a given (public or secret) key. 52 | Verify(sc_cli::VerifyCmd), 53 | 54 | /// Generate a seed that provides a vanity address. 55 | Vanity(sc_cli::VanityCmd), 56 | 57 | /// Sign a message, with a given (secret) key. 58 | Sign(sc_cli::SignCmd), 59 | 60 | /// Build a chain specification. 61 | BuildSpec(sc_cli::BuildSpecCmd), 62 | 63 | /// Validate blocks. 64 | CheckBlock(sc_cli::CheckBlockCmd), 65 | 66 | /// Export blocks. 67 | ExportBlocks(sc_cli::ExportBlocksCmd), 68 | 69 | /// Export the state of a given block into a chain spec. 70 | ExportState(sc_cli::ExportStateCmd), 71 | 72 | /// Import blocks. 73 | ImportBlocks(sc_cli::ImportBlocksCmd), 74 | 75 | /// Remove the whole chain. 76 | PurgeChain(sc_cli::PurgeChainCmd), 77 | 78 | /// Revert the chain to a previous state. 79 | Revert(sc_cli::RevertCmd), 80 | 81 | /// Db meta columns information. 82 | ChainInfo(sc_cli::ChainInfoCmd), 83 | 84 | /// Db meta columns information. 85 | FrontierDb(fc_cli::FrontierDbCmd), 86 | } 87 | -------------------------------------------------------------------------------- /standalone/chain/node/src/client.rs: -------------------------------------------------------------------------------- 1 | use polkadot_sdk::*; 2 | use codec::Codec; 3 | // Substrate 4 | use sc_executor::WasmExecutor; 5 | use sp_runtime::traits::{Block as BlockT, MaybeDisplay}; 6 | 7 | use crate::eth::EthCompatRuntimeApiCollection; 8 | use ces_pallet_mq_runtime_api::MqApi; 9 | 10 | /// Full backend. 11 | pub(crate) type FullBackend = sc_service::TFullBackend; 12 | /// Full client. 13 | pub(crate) type FullClient = sc_service::TFullClient>; 14 | 15 | /// A set of APIs that every runtimes must implement. 16 | #[allow(dead_code)] 17 | pub trait BaseRuntimeApiCollection: 18 | sp_api::ApiExt 19 | + sp_api::Metadata 20 | + sp_block_builder::BlockBuilder 21 | + sp_offchain::OffchainWorkerApi 22 | + sp_session::SessionKeys 23 | + sp_transaction_pool::runtime_api::TaggedTransactionQueue 24 | { 25 | } 26 | 27 | impl BaseRuntimeApiCollection for Api 28 | where 29 | Block: BlockT, 30 | Api: sp_api::ApiExt 31 | + sp_api::Metadata 32 | + sp_block_builder::BlockBuilder 33 | + sp_offchain::OffchainWorkerApi 34 | + sp_session::SessionKeys 35 | + sp_transaction_pool::runtime_api::TaggedTransactionQueue 36 | { 37 | } 38 | 39 | /// A set of APIs that template runtime must implement. 40 | #[allow(dead_code)] 41 | pub trait RuntimeApiCollection< 42 | Block: BlockT, 43 | AccountId: Codec, 44 | Nonce: Codec, 45 | Balance: Codec + MaybeDisplay, 46 | >: 47 | BaseRuntimeApiCollection 48 | + EthCompatRuntimeApiCollection 49 | + cessc_consensus_rrsc::RRSCApi 50 | + sp_consensus_grandpa::GrandpaApi 51 | + sp_authority_discovery::AuthorityDiscoveryApi 52 | + frame_system_rpc_runtime_api::AccountNonceApi 53 | + pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi 54 | + MqApi 55 | { 56 | } 57 | 58 | impl 59 | RuntimeApiCollection for Api 60 | where 61 | Block: BlockT, 62 | AccountId: Codec, 63 | Nonce: Codec, 64 | Balance: Codec + MaybeDisplay, 65 | Api: BaseRuntimeApiCollection 66 | + EthCompatRuntimeApiCollection 67 | + cessc_consensus_rrsc::RRSCApi 68 | + sp_consensus_grandpa::GrandpaApi 69 | + sp_authority_discovery::AuthorityDiscoveryApi 70 | + frame_system_rpc_runtime_api::AccountNonceApi 71 | + pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi 72 | + MqApi 73 | { 74 | } 75 | -------------------------------------------------------------------------------- /standalone/chain/node/src/main.rs: -------------------------------------------------------------------------------- 1 | //! Substrate Node Template CLI library. 2 | #![warn(missing_docs)] 3 | 4 | mod benchmarking; 5 | mod chain_spec; 6 | mod cli; 7 | mod client; 8 | mod command; 9 | mod eth; 10 | mod rpc; 11 | mod service; 12 | 13 | fn main() -> polkadot_sdk::sc_cli::Result<()> { 14 | command::run() 15 | } 16 | -------------------------------------------------------------------------------- /standalone/chain/primitives/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "cess-node-primitives" 3 | version = "2.0.0" 4 | authors.workspace = true 5 | description = "CESS node low-level primitives." 6 | edition.workspace = true 7 | license = "Apache-2.0" 8 | homepage = "https://substrate.io" 9 | repository.workspace = true 10 | publish = false 11 | 12 | [package.metadata.docs.rs] 13 | targets = ["x86_64-unknown-linux-gnu"] 14 | 15 | [dependencies] 16 | sp-core = { workspace = true } 17 | sp-runtime = { workspace = true } 18 | 19 | [features] 20 | default = ["std"] 21 | std = ["sp-core/std", "sp-runtime/std"] 22 | -------------------------------------------------------------------------------- /standalone/chain/runtime/build.rs: -------------------------------------------------------------------------------- 1 | 2 | fn main() { 3 | #[cfg(feature = "std")] 4 | { 5 | substrate_wasm_builder::WasmBuilder::build_using_defaults() 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /standalone/chain/runtime/src/assets_api.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Substrate. 2 | 3 | // Copyright (C) Parity Technologies (UK) Ltd. 4 | // SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 5 | 6 | // This program is free software: you can redistribute it and/or modify 7 | // it under the terms of the GNU General Public License as published by 8 | // the Free Software Foundation, either version 3 of the License, or 9 | // (at your option) any later version. 10 | 11 | // This program is distributed in the hope that it will be useful, 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | // GNU General Public License for more details. 15 | 16 | // You should have received a copy of the GNU General Public License 17 | // along with this program. If not, see . 18 | 19 | //! Runtime API definition for assets. 20 | extern crate alloc; 21 | 22 | use polkadot_sdk::*; 23 | use codec::Codec; 24 | use alloc::vec::Vec; 25 | 26 | sp_api::decl_runtime_apis! { 27 | pub trait AssetsApi 28 | where 29 | AccountId: Codec, 30 | AssetBalance: Codec, 31 | AssetId: Codec, 32 | { 33 | /// Returns the list of `AssetId`s and corresponding balance that an `AccountId` has. 34 | fn account_balances(account: AccountId) -> Vec<(AssetId, AssetBalance)>; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /standalone/chain/runtime/src/frontier/precompiles.rs: -------------------------------------------------------------------------------- 1 | use core::marker::PhantomData; 2 | use pallet_evm::{IsPrecompileResult, Precompile, PrecompileHandle, PrecompileResult, PrecompileSet}; 3 | use polkadot_sdk::sp_core::H160; 4 | 5 | use pallet_evm_precompile_modexp::Modexp; 6 | use pallet_evm_precompile_sha3fips::Sha3FIPS256; 7 | use pallet_evm_precompile_simple::{ECRecover, ECRecoverPublicKey, Identity, Ripemd160, Sha256}; 8 | 9 | pub struct FrontierPrecompiles(PhantomData); 10 | 11 | impl FrontierPrecompiles 12 | where 13 | R: pallet_evm::Config, 14 | { 15 | pub fn new() -> Self { 16 | Self(Default::default()) 17 | } 18 | pub fn used_addresses() -> [H160; 7] { 19 | [hash(1), hash(2), hash(3), hash(4), hash(5), hash(1024), hash(1025)] 20 | } 21 | } 22 | impl PrecompileSet for FrontierPrecompiles 23 | where 24 | R: pallet_evm::Config, 25 | { 26 | fn execute(&self, handle: &mut impl PrecompileHandle) -> Option { 27 | match handle.code_address() { 28 | // Ethereum precompiles : 29 | a if a == hash(1) => Some(ECRecover::execute(handle)), 30 | a if a == hash(2) => Some(Sha256::execute(handle)), 31 | a if a == hash(3) => Some(Ripemd160::execute(handle)), 32 | a if a == hash(4) => Some(Identity::execute(handle)), 33 | a if a == hash(5) => Some(Modexp::execute(handle)), 34 | // Non-Frontier specific nor Ethereum precompiles : 35 | a if a == hash(1024) => Some(Sha3FIPS256::execute(handle)), 36 | a if a == hash(1025) => Some(ECRecoverPublicKey::execute(handle)), 37 | _ => None, 38 | } 39 | } 40 | 41 | fn is_precompile(&self, address: H160, _gas: u64) -> IsPrecompileResult { 42 | IsPrecompileResult::Answer { is_precompile: Self::used_addresses().contains(&address), extra_cost: 0 } 43 | } 44 | } 45 | 46 | fn hash(a: u64) -> H160 { 47 | H160::from_low_u64_be(a) 48 | } 49 | -------------------------------------------------------------------------------- /standalone/chain/runtime/src/msg_routing.rs: -------------------------------------------------------------------------------- 1 | use polkadot_sdk::*; 2 | use codec::Decode; 3 | use frame_support::dispatch::DispatchResult; 4 | use sp_runtime::DispatchError; 5 | use ces_types::messaging::{BindTopic, DecodedMessage, Message}; 6 | 7 | pub struct MessageRouteConfig; 8 | 9 | fn try_dispatch(func: Func, message: &Message) -> DispatchResult 10 | where 11 | Msg: Decode + BindTopic, 12 | Func: Fn(DecodedMessage) -> DispatchResult, 13 | { 14 | if message.destination.path() == &Msg::topic() { 15 | let msg: DecodedMessage = message 16 | .decode() 17 | .ok_or(DispatchError::Other("MessageCodecError"))?; 18 | return (func)(msg); 19 | } 20 | Ok(()) 21 | } 22 | 23 | impl ces_pallet_mq::QueueNotifyConfig for MessageRouteConfig { 24 | /// Handles an incoming message 25 | fn on_message_received(message: &Message) -> DispatchResult { 26 | use super::*; 27 | macro_rules! route_handlers { 28 | ($($handler: path,)+) => { 29 | $(try_dispatch($handler, message)?;)+ 30 | } 31 | } 32 | 33 | route_handlers! { 34 | TeeWorker::on_message_received, 35 | }; 36 | Ok(()) 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /standalone/teeworker/ceseal/.gitignore: -------------------------------------------------------------------------------- 1 | # Generated by Cargo 2 | # will have compiled files and executables 3 | **/target/ 4 | 5 | *.swp 6 | **/._* 7 | **/.criterion/ 8 | .vscode 9 | polkadot.* 10 | .DS_Store 11 | nohup.out 12 | rls*.log 13 | *.orig 14 | *.rej 15 | **/wip/*.stderr 16 | *.pyc 17 | *.swo 18 | *.bk 19 | *~ 20 | 21 | # Remove Cargo.lock from gitignore if creating an executable, leave it for libraries 22 | # More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html 23 | #Cargo.lock 24 | !app/Cargo.lock 25 | !enclave/Cargo.lock 26 | 27 | # These are backup files generated by rustfmt 28 | **/*.rs.bk 29 | 30 | # Object files 31 | *.o 32 | 33 | # Libraries 34 | *.a 35 | 36 | # Shared objects 37 | *.so 38 | *.so.* 39 | 40 | # SGX EDL generated stubs 41 | Enclave_u.c 42 | Enclave_u.h 43 | Enclave_t.c 44 | Enclave_t.h 45 | 46 | # Generated and temp files 47 | /app/src/protos/*.rs 48 | /enclave/src/protos/*.rs 49 | /protos/tmp 50 | 51 | # Keep 52 | !.keep 53 | 54 | tmp 55 | SGX_MODE 56 | data 57 | 58 | -------------------------------------------------------------------------------- /standalone/teeworker/ceseal/.rustfmt.toml: -------------------------------------------------------------------------------- 1 | hard_tabs = false -------------------------------------------------------------------------------- /standalone/teeworker/ceseal/Makefile: -------------------------------------------------------------------------------- 1 | BUILD?=release 2 | OA?=1 3 | VC?=1 4 | ifeq ($(BUILD),release) 5 | XARGS=--release 6 | endif 7 | ifeq ($(OA),1) 8 | XARGS += --features only-attestation 9 | endif 10 | ifeq ($(VC),1) 11 | XARGS += --features verify-cesealbin 12 | endif 13 | 14 | .PHONY: all clean run app 15 | 16 | all: app 17 | app: bin/app 18 | run: 19 | ./bin/app -c 0 20 | 21 | bin/app: bin/ceseal 22 | cd bin && ln -sf ceseal app 23 | 24 | bin/ceseal: target/${BUILD}/ceseal 25 | cp $? $@ 26 | 27 | .PHONY: target/${BUILD}/ceseal 28 | target/${BUILD}/ceseal: 29 | cargo build ${XARGS} 30 | 31 | clean: 32 | rm -rf bin/* 33 | cargo clean 34 | 35 | .PHONY: clippy 36 | clippy: 37 | cargo clippy --tests 38 | -------------------------------------------------------------------------------- /standalone/teeworker/ceseal/bin/.gitignore: -------------------------------------------------------------------------------- 1 | * 2 | !.gitignore -------------------------------------------------------------------------------- /standalone/teeworker/ceseal/build.rs: -------------------------------------------------------------------------------- 1 | use std::{env, error::Error}; 2 | use vergen::EmitBuilder; 3 | 4 | fn main() -> Result<(), Box> { 5 | EmitBuilder::builder() 6 | .all_build() 7 | .all_git() 8 | .git_sha(true) 9 | .emit()?; 10 | 11 | let sgx_env = env::var("SGX_ENV").unwrap_or_else(|_| "DEV".to_string()); 12 | match sgx_env.as_ref() { 13 | "PROD" => { 14 | println!("cargo:rustc-env=IAS_HOST=api.trustedservices.intel.com"); 15 | println!("cargo:rustc-env=IAS_SIGRL_ENDPOINT=/sgx/attestation/v4/sigrl/"); 16 | println!("cargo:rustc-env=IAS_REPORT_ENDPOINT=/sgx/attestation/v4/report"); 17 | println!("cargo:rustc-env=DCAP_PCCS_URL=https://dcap.cess.network/sgx/certification/v4/"); 18 | }, 19 | _ => { 20 | // DEV by default 21 | println!("cargo:rustc-env=IAS_HOST=api.trustedservices.intel.com"); 22 | println!("cargo:rustc-env=IAS_SIGRL_ENDPOINT=/sgx/dev/attestation/v4/sigrl/"); 23 | println!("cargo:rustc-env=IAS_REPORT_ENDPOINT=/sgx/dev/attestation/v4/report"); 24 | println!("cargo:rustc-env=DCAP_PCCS_URL=https://dcap.cess.network/sgx/certification/v4/"); 25 | }, 26 | } 27 | if env::var("IAS_API_KEY").is_err() { 28 | println!("cargo:rustc-env=IAS_API_KEY=''"); 29 | } 30 | println!("cargo:rerun-if-env-changed=IAS_API_KEY"); 31 | 32 | Ok(()) 33 | } 34 | -------------------------------------------------------------------------------- /standalone/teeworker/ceseal/gramine-build/.gitignore: -------------------------------------------------------------------------------- 1 | /*.o 2 | /OUTPUT 3 | /ceseal 4 | /ceseal.manifest 5 | /ceseal.manifest.sgx 6 | /ceseal.sig 7 | /ceseal.token 8 | /bin 9 | /data 10 | /cruntime 11 | -------------------------------------------------------------------------------- /standalone/teeworker/ceseal/gramine-build/ceseal.manifest.template: -------------------------------------------------------------------------------- 1 | [libos] 2 | entrypoint = "ceseal" 3 | 4 | [loader] 5 | entrypoint = "file:{{ libos }}" 6 | log_level = "{{ log_level }}" 7 | argv0_override = "ceseal" 8 | insecure__use_cmdline_argv = true 9 | 10 | [sys] 11 | {# 12 | It's required by the tokio networks stack. A false report would cause a noop 13 | poll, so it's safe to enable it. 14 | #} 15 | insecure__allow_eventfd = true 16 | stack.size = "2M" 17 | brk.max_size = "256M" 18 | 19 | [loader.env] 20 | LD_LIBRARY_PATH = "/lib:/lib/x86_64-linux-gnu" 21 | {# Without this, Glibc would allocate a 64MB ARENA for each thread. #} 22 | MALLOC_ARENA_MAX = "1" 23 | {# Chunks over 256K would alloc with mmap. #} 24 | MALLOC_MMAP_THRESHOLD_ = "262144" 25 | {# 26 | The size of the thread pool for the tokio runtime created by rocket that 27 | serving the async tasks. 28 | #} 29 | ROCKET_WORKERS = "8" 30 | {# 31 | When enable, the ceseal will only logs with targets in the hardcoded whitelist. 32 | So, log from thirdparty crates will be ignored to avoid unexpected information leaks. 33 | #} 34 | RUST_LOG_SANITIZED = "true" 35 | RUST_LOG = { passthrough = true } 36 | all_proxy = { passthrough = true } 37 | i2p_proxy = { passthrough = true } 38 | 39 | [[fs.mounts]] 40 | type = "chroot" 41 | path = "/lib" 42 | uri = "file:{{ libdir }}" 43 | 44 | [[fs.mounts]] 45 | path = "/data/protected_files" 46 | uri = "file:{{ seal_dir }}" 47 | type = "encrypted" 48 | key_name = "_sgx_mrenclave" 49 | 50 | [[fs.mounts]] 51 | type = "chroot" 52 | path = "/data/storage_files" 53 | uri = "file:{{ storage_dir }}" 54 | 55 | [[fs.mounts]] 56 | type = "chroot" 57 | path = "/etc" 58 | uri = "file:/etc" 59 | 60 | [sgx] 61 | debug = false 62 | nonpie_binary = true 63 | enclave_size = "2G" 64 | max_threads = 128 65 | remote_attestation = "{{ ra_method }}" 66 | 67 | {% if ra_method == "epid" %} 68 | ra_client_linkable = true 69 | ra_client_spid = "{{ ra_client_spid }}" 70 | {% endif %} 71 | 72 | trusted_files = [ 73 | "file:{{ libos }}", 74 | "file:ceseal", 75 | "file:{{ libdir }}", 76 | ] 77 | 78 | allowed_files = [ 79 | "file:/etc/hosts", 80 | "file:/etc/resolv.conf", 81 | "file:/etc/sgx_default_qcnl.conf", 82 | "file:{{ storage_dir }}/", 83 | ] 84 | -------------------------------------------------------------------------------- /standalone/teeworker/ceseal/gramine-build/conf/aesmd.conf: -------------------------------------------------------------------------------- 1 | #proxy type = direct #direct type means no proxy used 2 | #proxy type = default #system default proxy 3 | #proxy type = manual #aesm proxy should be specified for manual proxy type 4 | #aesm proxy = http://proxy_url:proxy_port 5 | #whitelist url = http://sample_while_list_url/ 6 | #default quoting type = ecdsa_256 7 | #default quoting type = epid_linkable 8 | #default quoting type = epid_unlinkable 9 | #qpl log level = error 10 | #qpl log level = info -------------------------------------------------------------------------------- /standalone/teeworker/ceseal/gramine-build/gramine-dir: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | from argparse import ArgumentParser 4 | 5 | from graminelibos.gen_jinja_env import make_env 6 | 7 | 8 | parser = ArgumentParser() 9 | parser.add_argument("dirtype", default="libs", help="libs, runtime, libos or sgx") 10 | 11 | 12 | def get_libs_dir(dirtype): 13 | tmpl_vars = make_env().globals["gramine"] 14 | if dirtype == "libs": 15 | return tmpl_vars["pkglibdir"] 16 | elif dirtype == "runtime": 17 | return tmpl_vars["runtimedir"]() 18 | elif dirtype == "libos": 19 | return tmpl_vars["libos"] 20 | elif dirtype == "sgx": 21 | return get_libs_dir("libs") / "sgx" 22 | else: 23 | return None 24 | 25 | 26 | if __name__ == "__main__": 27 | args = parser.parse_args() 28 | path = get_libs_dir(args.dirtype) 29 | if path is None: 30 | print("Invalid dirtype") 31 | parser.print_help() 32 | exit(1) 33 | print(path) 34 | -------------------------------------------------------------------------------- /standalone/teeworker/ceseal/gramine-build/gramine-sgx: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | GRAMINE_DIR="$PWD/cruntime" 3 | PAL_CMD="$GRAMINE_DIR/sgx/loader" 4 | LIBPAL_PATH="$GRAMINE_DIR/sgx/libpal.so" 5 | 6 | APPLICATION= 7 | 8 | 9 | while [ "$1" != "" ]; 10 | do 11 | if [ "$APPLICATION" == "" ]; then 12 | APPLICATION=$1 13 | shift 14 | continue 15 | fi 16 | break 17 | done 18 | 19 | if [ "$APPLICATION" == "" ]; then 20 | echo "Usage: $0 [] ..." 21 | exit 2 22 | fi 23 | 24 | if [ ! -e "$APPLICATION.manifest.sgx" ]; then 25 | echo "Invalid application path specified ($APPLICATION.manifest.sgx does not exist)." >&2 26 | echo "The path should point to application configuration files, so that they can be" >&2 27 | echo "found after appending corresponding extensions." >&2 28 | exit 2 29 | fi 30 | 31 | if [ ! -f "$PAL_CMD" ]; then 32 | echo "$PAL_CMD not found" 33 | exit 1 34 | fi 35 | 36 | "$PAL_CMD" "$LIBPAL_PATH" init "$APPLICATION" "$@" 37 | echo "$APPLICATION exited with code $?" 38 | -------------------------------------------------------------------------------- /standalone/teeworker/ceseal/gramine-build/private.dev.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN RSA PRIVATE KEY----- 2 | MIIG4wIBAAKCAYEAolhkaHrm5kUmmopFEntMRhy8z7W542U+bXUZPZ5ngVOCFd0F 3 | l5SnO8vgW7xuAuPZ25e/8zhnupTmgPUEttU5+JyHjRbKweYghPHKn6IYDL2NyS/o 4 | 9uU2S8Uu3VsJcnQz1Ibdp1zcG93UAUe9cVIMp91v7gpLVWa6lLT4FQ9VaZsrL1sy 5 | XA2HzWESvP/UMPYokIkQLiPtJRbjIlV4Jmq1TPFhyg9zRShiPHzMNHNLzo9w4dkT 6 | pUQAWKBcG45IoL0mL8BmM0IXOCcD4nYUC/iX2by0sH2k8lJuHqDzlw2Br3k5PMMy 7 | WC2QY/aWOjHoKSeDSMsQcB2yPFZkPxTbV0OHM4nLsq1tO2xyH6+pHhpoosWWDCfm 8 | IvWPSgN6356t7yr6zq5XDtWre4JwU5BiZ66Sc/HMPhjs6Tv9p3AmHbz53QB3oW9z 9 | tx9okN+fWRkesrAGXJ+Y78l0FY2nBnRrFB5Lvgk2rVRPqaAPEHe9QP/4apzuPNtJ 10 | a/3BzDBHfBUtPLx/AgEDAoIBgGw67Zr8me7YxGcG2Lb83YQTKIp5JpeY1Ej4u35p 11 | mlY3rA6TWQ+4b30ylZJ9nqyX5pJlKqIlmnxjRFX4rc840VBoWl4PMdaZawNL3Gps 12 | EAh+XoYf8KSYzt0uHz48sPb4Io2vPm+TPWfpOADafkuMCG/o9UlcMjjvJw3N+ri0 13 | 45u8x3TndugJBTOWDH3/4stOxbWwtXQX824PQhbjpW7xzjNLloa094NwQX2oiCL3 14 | h98KS0E7Ym4tVZBq6BJe2xXTbbqrecoevNZMuVoCdM1PBlw6vnxAUao5VowfFFtn 15 | QGsBc+my7lgCJfDd/13vOHFLERCEhqhkn7Ew8V39O5UIJAxeYbi7iKFKdsM9QDtg 16 | AfSuLzDS83s7rC9Sd6HMZQCYCaZDN1j9pt/2klekI2CRGC2p4LRIISCyswTJIy96 17 | fpC+GH4s5w8+zReHbRai6KttgyauAAzA9MxoF4ODxu3jGUPKsxzeQ6wxRbwGiEWI 18 | fNV0JcD92DNOUMClBpCSZ2dqOwKBwQDN3frbSY2OV/oNWT7mDszmdd42r9ELGzFE 19 | ARQ66UnN3hPBYLarw91q3LFM0z2uwc0micNanRoQHZbORaJA2oEYvUsHQ8U8tqf8 20 | 4icOu2R7d6rdho7nnd1Uuprb9WteK6z3YvHZmZ7Sw7NZ7yVra32mkE4/gGl4laZq 21 | ohjJnxqYioBRqHMTrELccGkqCCoE/WjjdOw0JnCtSRgNSVQsnnQ7LDN1IcxquU5g 22 | BibbBGhkyRLtfZqhvoVDLfMNLh92xf0CgcEAyeE0qMpuaFvzzhkl8fNBaO64v21Z 23 | Z+E7CHFA0wlXQRj3nNYWKGZ6D8zl4HfV0HUciXqDGOmoom9jY9NfttzQCD7uFlBb 24 | DMYX/fGhtk8BOEikZWTqAn4vrk0skParEBs/XeaSL7+SWMzhdisH62lwiOKs8CxR 25 | v5pKtaBYjOYha1jSkoOmDJTyESQSjRyXrI5YvyWsqIGUNahrs+VsgqsxnSz2jOUd 26 | vJzYFmfJ/a7UxaWireDqfUnDaArKlgtyqtcrAoHBAIk+pzzbs7Q6prOQ1JlfM0RO 27 | lCR1Ngdndi1WDXybhok+t9ZAecfX6PHodjM3fnSBM28GgjxovAq+ZImDwYCRq2XT 28 | h1otLih5xVNBb18nmFJPxz5ZtJppPjh8Zz1OR5QdHfpB9pERFIyCd5FKGPJHqRm1 29 | iX+q8PsObvHBZdu/ZxBcVYvFog0dgehK8MawHANTm0JN8s1u9cjbZV4w4shpotId 30 | d6Nr3Zx7iZVZbzytmu3bYfOpEcEprizJTLN0FPnZUwKBwQCGliMbMZ7wPU00EMP2 31 | oiubSdB/njualida9is3W4+Au0+95A7Fmaa1M0Pq+o6K+L2w/Fdl8RsW9OztN5Uk 32 | kzVa1J65iudd2WVT9mvO31YlhcLuQ0asVB/JiMhgpHIKvNTpRGF1KmGQiJZOx1qc 33 | 8PWwlx31cuEqZtx5FZBd7sDyOzcMV8QIY0wLbWGzaGUdtDsqGR3Fq7gjxZ0imPMB 34 | x3ZoyKRd7hPTEzq5moapHziDw8HJQJxThoJFXIcOskxx5McCgcEAsohPl4s9unUj 35 | fF/eLli6j6BuvM/8xq0Gkr2/bCu5g5oi8BVE/2pwoAUB6AznsxXuFwi0VO5gjuA6 36 | 06FSczlHcqyjidGQbtzMyB++UKfo2kxUe2Ab7t7FEyvOVPL+1YLYINkoLZed3Z2x 37 | dWyLyD0bpY6BifLkTxpTmssLDQZoDCVnCHnfMCBZ6+DfCHzuDvsm/6hcE0X+fpxW 38 | 4FMg0X4CtR+f9CVKzDj31zGDyASgto2hesIH2lqPHyyDciBa1BTQ 39 | -----END RSA PRIVATE KEY----- 40 | -------------------------------------------------------------------------------- /standalone/teeworker/ceseal/src/handover.rs: -------------------------------------------------------------------------------- 1 | use crate::pal_gramine::GraminePlatform; 2 | use anyhow::{Context, Result}; 3 | use cestory::RpcService; 4 | use cestory_api::{ 5 | ceseal_client::CesealClient, crpc::ceseal_api_server::CesealApi, ecall_args::InitArgs, 6 | }; 7 | use tonic::{transport::Channel, Request}; 8 | use tracing::info; 9 | 10 | pub(crate) async fn handover_from(url: &str, args: InitArgs) -> Result<()> { 11 | let this = RpcService::new(GraminePlatform); 12 | this.lock_ceseal(true, false) 13 | .expect("Failed to lock Ceseal") 14 | .init(args); 15 | 16 | let mut from_ceseal = CesealClient::::connect(url.to_string()).await?; 17 | info!("Requesting for challenge"); 18 | let challenge = from_ceseal 19 | .handover_create_challenge(()) 20 | .await 21 | .context("Failed to create challenge")? 22 | .into_inner(); 23 | info!("Challenge received"); 24 | let response = this 25 | .handover_accept_challenge(Request::new(challenge)) 26 | .await 27 | .context("Failed to accept challenge")? 28 | .into_inner(); 29 | info!("Requesting for key"); 30 | let encrypted_key = from_ceseal 31 | .handover_start(response) 32 | .await 33 | .context("Failed to start handover")? 34 | .into_inner(); 35 | info!("Key received"); 36 | this.handover_receive(Request::new(encrypted_key)) 37 | .await 38 | .context("Failed to receive handover result")?; 39 | Ok(()) 40 | } 41 | -------------------------------------------------------------------------------- /standalone/teeworker/cifrost/.rustfmt.toml: -------------------------------------------------------------------------------- 1 | hard_tabs = false -------------------------------------------------------------------------------- /standalone/teeworker/cifrost/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "cifrost" 3 | version = "0.3.1" 4 | authors = ["CESS Network"] 5 | edition = "2021" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | anyhow = { workspace = true } 11 | futures = { workspace = true } 12 | log = { workspace = true } 13 | tokio = { workspace = true, features = ["full"] } 14 | reqwest = { workspace = true, features = ["rustls-tls", "socks"] } 15 | hex = { workspace = true } 16 | base64 = { workspace = true } 17 | serde = { workspace = true, features = ["derive"] } 18 | serde_json = { workspace = true } 19 | rand = { workspace = true } 20 | clap = { workspace = true, features = ["derive"] } 21 | tonic ={ workspace = true } 22 | async-trait = { workspace = true } 23 | 24 | frame-system = { workspace = true } 25 | sp-core = { workspace = true } 26 | sp-runtime = { workspace = true } 27 | sp-consensus-grandpa = { workspace = true } 28 | sp-trie = { workspace = true } 29 | sc-consensus-grandpa = { workspace = true } 30 | parity-scale-codec = { workspace = true } 31 | scale-info = { workspace = true } 32 | hash-db = { workspace = true } 33 | 34 | pallet-grandpa = { workspace = true } 35 | pallet-indices = { workspace = true } 36 | pallet-balances = { workspace = true } 37 | 38 | ces-sanitized-logger ={ workspace = true } 39 | ces-types = { workspace = true } 40 | ces-trie-storage = { workspace = true } 41 | ces-node-rpc-ext = { workspace = true } 42 | ces-mq = { workspace = true } 43 | cestory-api = { workspace = true, features = ["ceseal-client", "std"] } 44 | cesxt = { workspace = true } 45 | 46 | 47 | [features] 48 | only-attestation = [ 49 | "cestory-api/only-attestation" 50 | ] 51 | verify-cesealbin = [ 52 | "cestory-api/verify-cesealbin" 53 | ] -------------------------------------------------------------------------------- /standalone/teeworker/cifrost/src/block_subscribe.rs: -------------------------------------------------------------------------------- 1 | use crate::types::CesealClient; 2 | use anyhow::{Context, Error, Result}; 3 | use cesxt::ChainApi; 4 | use log::{error, info}; 5 | use std::time::Duration; 6 | use tokio::time::sleep; 7 | 8 | pub async fn spawn_subscriber(chain_client: &ChainApi, ceseal_client: CesealClient) -> Result<()> { 9 | let mut blocks_sub = chain_client.blocks().subscribe_finalized().await?; 10 | tokio::spawn(async move { 11 | while let Some(block) = blocks_sub.next().await { 12 | let block = block?; 13 | let block_number = block.header().number; 14 | let extrinsics = block.extrinsics().await?; 15 | for ext in extrinsics.iter() { 16 | let events = ext.events().await?; 17 | for evt in events.iter() { 18 | let evt = evt?; 19 | let pallet_name = evt.pallet_name(); 20 | let event_name = evt.variant_name(); 21 | if pallet_name == "TeeWorker" && event_name == "CesealBinAdded" { 22 | info!("catch event: {pallet_name}_{event_name} on block: #{block_number}"); 23 | handle_checkpoint_take(ceseal_client.clone(), block_number).await; 24 | } 25 | } 26 | } 27 | } 28 | Ok::<(), Error>(()) 29 | }); 30 | Ok(()) 31 | } 32 | 33 | async fn handle_checkpoint_take(mut ceseal_client: CesealClient, block_number: u32) { 34 | info!("handling CesealBinAdded event, waiting ceseal arrive to block: #{block_number}"); 35 | let handler = async move { 36 | loop { 37 | //FIXME: Maybe uniform the ceseal state query as stream fetch 38 | let info = ceseal_client 39 | .get_info(()) 40 | .await 41 | .context("call ceseal.get_info() failed")? 42 | .into_inner(); 43 | if info.blocknum >= block_number { 44 | ceseal_client 45 | .take_checkpoint(()) 46 | .await 47 | .context("call ceseal.take_checkpoint() failed")?; 48 | info!("ceseal has taked checkpoint at block: #{block_number}"); 49 | break; 50 | } 51 | sleep(Duration::from_millis(5000)).await; 52 | } 53 | Ok::<(), Error>(()) 54 | }; 55 | tokio::spawn(async move { 56 | if let Err(error) = handler.await { 57 | error!("handle_checkpoint_take() failed: {error}"); 58 | } 59 | }); 60 | } 61 | -------------------------------------------------------------------------------- /standalone/teeworker/cifrost/src/error.rs: -------------------------------------------------------------------------------- 1 | use std::{error, fmt}; 2 | 3 | #[derive(Debug)] 4 | pub enum Error { 5 | BlockHashNotFound, 6 | BlockNotFound, 7 | SearchSetIdChangeInEmptyRange, 8 | } 9 | 10 | impl fmt::Display for Error { 11 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 12 | match self { 13 | Error::BlockHashNotFound => write!(f, "block hash not found"), 14 | Error::BlockNotFound => write!(f, "block not found"), 15 | Error::SearchSetIdChangeInEmptyRange => write!(f, "list of known blocks is empty"), 16 | } 17 | } 18 | } 19 | 20 | impl error::Error for Error {} 21 | -------------------------------------------------------------------------------- /standalone/teeworker/cifrost/src/main.rs: -------------------------------------------------------------------------------- 1 | #[tokio::main] 2 | async fn main() { 3 | ces_sanitized_logger::init_subscriber(false); 4 | cifrost::run().await; 5 | } 6 | -------------------------------------------------------------------------------- /standalone/teeworker/handover/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "handover" 3 | version = "0.2.0" 4 | edition = "2021" 5 | 6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 7 | 8 | [dependencies] 9 | clap = { workspace = true, features = ["derive"] } 10 | tokio = { workspace = true, features = ["full"] } 11 | walkdir = { workspace = true } -------------------------------------------------------------------------------- /standalone/teeworker/handover/src/arg.rs: -------------------------------------------------------------------------------- 1 | use clap::Parser; 2 | 3 | #[derive(Parser, Debug)] 4 | #[command( 5 | about = "xxx", 6 | version, 7 | author 8 | )] 9 | pub struct Args { 10 | #[arg( 11 | long, 12 | help = "The backup path of the each version of ceseal", 13 | default_value = "/opt/ceseal/backups" 14 | )] 15 | pub previous_version_ceseal_path: String, 16 | 17 | #[arg( 18 | long, 19 | help = "The backup path of the current version of ceseal", 20 | default_value = "/opt/ceseal/releases/current" 21 | )] 22 | pub current_version_ceseal_path: String, 23 | 24 | #[arg( 25 | long, 26 | help = "ceseal home", 27 | default_value = "/opt/ceseal/data" 28 | )] 29 | pub ceseal_data_path: String, 30 | 31 | #[arg( 32 | long, 33 | help = "Ceseal log path for detect the status of previous ceseal", 34 | default_value = "/tmp/pre_ceseal.log" 35 | )] 36 | pub previous_ceseal_log_path: String, 37 | 38 | #[arg( 39 | long, 40 | help = "Ceseal log path for detect the status of new ceseal", 41 | default_value = "/tmp/new_ceseal.log" 42 | )] 43 | pub new_ceseal_log_path: String, 44 | 45 | #[arg( 46 | long, 47 | help = "The relative path where each version of ceseal stores protected files", 48 | default_value = "data/protected_files" 49 | )] 50 | pub ceseal_protected_files_path: String, 51 | 52 | #[arg( 53 | long, 54 | help = "the relative path where each version of ceseal stores checkpoint file", 55 | default_value = "data/storage_files" 56 | )] 57 | pub ceseal_storage_files_path: String, 58 | 59 | #[arg( 60 | long, 61 | help = "old ceseal start on this port", 62 | default_value = "1888" 63 | )] 64 | pub previous_ceseal_port: u64, 65 | 66 | #[arg( 67 | long, 68 | help = "remote attestation type", 69 | )] 70 | pub ra_type: String, 71 | } -------------------------------------------------------------------------------- /standalone/teeworker/handover/src/error.rs: -------------------------------------------------------------------------------- 1 | use std::{error, fmt}; 2 | 3 | #[derive(Debug)] 4 | pub enum Error { 5 | StartCesealFailed(String), 6 | RedirectCesealLogFailed(String), 7 | DetectCesealRunningStatueFailed(String), 8 | PreviousVersionFailed(String), 9 | CopyDirectory(String) 10 | } 11 | 12 | impl fmt::Display for Error { 13 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 14 | match self { 15 | Error::StartCesealFailed(e) => write!(f, "{:?}", e), 16 | Error::RedirectCesealLogFailed(e) => write!(f, "{:?}", e), 17 | Error::DetectCesealRunningStatueFailed(e) => write!(f, "{:?}", e), 18 | Error::PreviousVersionFailed(e) => write!(f, "{:?}", e), 19 | Error::CopyDirectory(e) => write!(f, "{:?}", e), 20 | } 21 | } 22 | } 23 | 24 | impl error::Error for Error {} 25 | --------------------------------------------------------------------------------