diff --git a/.github/file-filter.yml b/.github/file-filter.yml index 0961419a08..e71da10e40 100644 --- a/.github/file-filter.yml +++ b/.github/file-filter.yml @@ -31,21 +31,6 @@ identity_src: &identity_src - 'tee-worker/identity/build.Dockerfile' - 'tee-worker/identity/enclave-runtime/**' -bitacross_src: &bitacross_src - - 'common/**' - - 'tee-worker/Cargo.toml' - - 'tee-worker/Cargo.lock' - - 'tee-worker/bitacross/**/*.rs' - - 'tee-worker/bitacross/**/rust-toolchain.toml' - - 'tee-worker/bitacross/build.Dockerfile' - - 'tee-worker/bitacross/enclave-runtime/**' - -bitacross_test: &bitacross_test - - 'tee-worker/bitacross/ts-tests/**' - - 'tee-worker/bitacross/cli/*.sh' - - 'parachain/docker/**' - - 'tee-worker/bitacross/docker/*.yml' - omni_executor_src: &omni_executor_src - 'tee-worker/omni-executor/Cargo.toml' - 'tee-worker/omni-executor/Cargo.lock' diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 35e0e9cbbc..6958009ede 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -55,11 +55,6 @@ on: description: rebuild-identity required: true default: true - rebuild-bitacross: - type: boolean - description: rebuild-bitacross - required: true - default: true rebuild-omni-executor: type: boolean description: rebuild-omni-executor @@ -99,12 +94,10 @@ jobs: outputs: rebuild_parachain: ${{ steps.env.outputs.rebuild_parachain }} rebuild_identity: ${{ steps.env.outputs.rebuild_identity }} - rebuild_bitacross: ${{ steps.env.outputs.rebuild_bitacross }} rebuild_omni_executor: ${{ steps.env.outputs.rebuild_omni_executor }} push_docker: ${{ steps.env.outputs.push_docker }} run_parachain_test: ${{ steps.env.outputs.run_parachain_test }} run_identity_test: ${{ steps.env.outputs.run_identity_test }} - run_bitacross_test: ${{ steps.env.outputs.run_bitacross_test }} run_omni_executor_test: ${{ steps.env.outputs.run_omni_executor_test }} steps: - uses: actions/checkout@v4 @@ -124,12 +117,10 @@ jobs: run: | rebuild_parachain=false rebuild_identity=false - rebuild_bitacross=false rebuild_omni_executor=false push_docker=false run_parachain_test=false run_identity_test=false - run_bitacross_test=false run_omni_executor_test=false if [ "${{ github.event.inputs.rebuild-parachain }}" = "true" ] || [ "${{ steps.filter.outputs.parachain_src }}" = "true" ]; then rebuild_parachain=true @@ -137,9 +128,6 @@ jobs: if [ "${{ github.event.inputs.rebuild-identity }}" = "true" ] || [ "${{ steps.filter.outputs.identity_src }}" = "true" ]; then rebuild_identity=true fi - if [ "${{ github.event.inputs.rebuild-bitacross }}" = "true" ] || [ "${{ steps.filter.outputs.bitacross_src }}" = "true" ]; then - rebuild_bitacross=true - fi if [ "${{ github.event.inputs.rebuild-omni-executor }}" = "true" ] || [ "${{ steps.filter.outputs.omni_executor_src }}" = "true" ]; then rebuild_omni_executor=true fi @@ -154,20 +142,15 @@ jobs: if [ "${{ steps.filter.outputs.identity_test }}" = "true" ] || [ "$rebuild_parachain" = "true" ] || [ "$rebuild_identity" = "true" ]; then run_identity_test=true fi - if [ "${{ steps.filter.outputs.bitacross_test }}" = "true" ] || [ "$rebuild_parachain" = "true" ] || [ "$rebuild_bitacross" = "true" ]; then - run_bitacross_test=true - fi if [ "${{ steps.filter.outputs.omni_executor_test }}" = "true" ] || [ "$rebuild_parachain" = "true" ] || [ "$rebuild_omni_executor" = "true" ]; then run_omni_executor_test=true fi echo "rebuild_parachain=$rebuild_parachain" | tee -a $GITHUB_OUTPUT echo "rebuild_identity=$rebuild_identity" | tee -a $GITHUB_OUTPUT - echo "rebuild_bitacross=$rebuild_bitacross" | tee -a $GITHUB_OUTPUT echo "rebuild_omni_executor=$rebuild_omni_executor" | tee -a $GITHUB_OUTPUT echo "push_docker=$push_docker" | tee -a $GITHUB_OUTPUT echo "run_parachain_test=$run_parachain_test" | tee -a $GITHUB_OUTPUT echo "run_identity_test=$run_identity_test" | tee -a $GITHUB_OUTPUT - echo "run_bitacross_test=$run_bitacross_test" | tee -a $GITHUB_OUTPUT echo "run_omni_executor_test=$run_omni_executor_test" | tee -a $GITHUB_OUTPUT fmt: @@ -204,11 +187,6 @@ jobs: run: | cargo fmt --all -- --check - - name: bitacross-worker enclave-runtime fmt check - working-directory: ./tee-worker/bitacross/enclave-runtime - run: | - cargo fmt --all -- --check - - name: omni-executor fmt check working-directory: ./tee-worker/omni-executor run: | @@ -292,7 +270,7 @@ jobs: working-directory: ./tee-worker shell: bash run: | - for d in . identity/enclave-runtime bitacross/enclave-runtime; do + for d in . identity/enclave-runtime; do pushd "$d" echo "::group::cargo clippy all" cargo clippy --release -- -D warnings @@ -539,84 +517,6 @@ jobs: if: failure() uses: andymckay/cancel-action@0.5 - bitacross-build: - runs-on: ubuntu-22.04 - needs: - - fmt - - set-condition - - sequentialise - steps: - - uses: actions/checkout@v4 - - - name: Free up disk space - if: startsWith(runner.name, 'GitHub Actions') - uses: ./.github/actions/disk-cleanup - - - name: Set up Docker Buildx - uses: docker/setup-buildx-action@v3 - with: - # use the docker driver to access the local image - # we don't need external caches or multi platforms here - # see https://docs.docker.com/build/drivers/ - driver: docker - - - name: Build local builder - if: needs.set-condition.outputs.rebuild_bitacross == 'true' - uses: docker/build-push-action@v6 - with: - context: . - file: tee-worker/bitacross/build.Dockerfile - tags: local-builder:latest - target: builder - build-args: | - WORKER_MODE_ARG=offchain-worker - ADDITIONAL_FEATURES_ARG= - - - name: Build worker - if: needs.set-condition.outputs.rebuild_bitacross == 'true' - uses: docker/build-push-action@v6 - with: - context: . - file: tee-worker/bitacross/build.Dockerfile - tags: litentry/bitacross-worker:latest - target: deployed-worker - - - name: Build cli - if: needs.set-condition.outputs.rebuild_bitacross == 'true' - uses: docker/build-push-action@v6 - with: - context: . - file: tee-worker/bitacross/build.Dockerfile - tags: litentry/bitacross-cli:latest - target: deployed-client - - - name: Pull and tag worker and cli image optionally - if: needs.set-condition.outputs.rebuild_bitacross == 'false' - run: | - docker pull litentry/bitacross-worker:latest - docker pull litentry/bitacross-cli:latest - - - run: docker images --all - - - name: Test enclave - if: needs.set-condition.outputs.rebuild_bitacross == 'true' - # cargo test is not supported in the enclave - # see https://github.com/apache/incubator-teaclave-sgx-sdk/issues/232 - run: docker run litentry/bitacross-worker:latest test --all - - - name: Save docker images - run: docker save litentry/bitacross-worker:latest litentry/bitacross-cli:latest | gzip > litentry-bitacross.tar.gz - - - name: Upload docker images - uses: actions/upload-artifact@v4 - with: - name: litentry-bitacross - path: litentry-bitacross.tar.gz - if-no-files-found: error - - name: Fail early - if: failure() - uses: andymckay/cancel-action@0.5 - omni-executor-build: runs-on: ubuntu-22.04 needs: @@ -964,86 +864,6 @@ jobs: if-no-files-found: ignore retention-days: 3 - bitacross-worker-test: - runs-on: ubuntu-22.04 - needs: - - set-condition - - parachain-build-dev - - bitacross-build - strategy: - fail-fast: false - matrix: - include: - - test_name: lit-sign-bitcoin - name: ${{ matrix.test_name }} - steps: - - uses: actions/checkout@v4 - - - uses: actions/download-artifact@v4 - with: - name: litentry-parachain-dev - - - uses: actions/download-artifact@v4 - with: - name: litentry-bitacross - - - name: Load docker image - run: | - docker load < litentry-parachain-dev.tar.gz - docker load < litentry-bitacross.tar.gz - docker images - - - name: Enable corepack and pnpm - run: corepack enable && corepack enable pnpm - - - name: Launch parachain network - run: | - make launch-network-litentry - - - name: Integration bitacross worker test ${{ matrix.test_name }} - working-directory: ./tee-worker/bitacross/docker - if: needs.set-condition.outputs.run_bitacross_test == 'true' - timeout-minutes: 40 - run: | - docker compose -f multiworker-docker-compose.yml -f ${{ matrix.test_name }}.yml up --no-build --exit-code-from ${{ matrix.test_name }} ${{ matrix.test_name }} - - - name: Stop integration multi worker docker containers - working-directory: ./tee-worker/bitacross/docker - if: needs.set-condition.outputs.run_bitacross_test == 'true' - run: | - docker compose -f multiworker-docker-compose.yml -f ${{ matrix.test_name }}.yml stop - - - name: Upload zombienet logs if test fails - continue-on-error: true - uses: actions/upload-artifact@v4 - if: failure() - with: - name: ${{ matrix.test_name }}-zombienet-logs - path: | - /tmp/parachain_dev - !/tmp/parachain_dev/polkadot* - !/tmp/parachain_dev/zombienet* - !/tmp/parachain_dev/litentry-collator - if-no-files-found: ignore - retention-days: 3 - - - name: Collect docker logs if test fails - continue-on-error: true - uses: jwalton/gh-docker-logs@v2 - if: failure() - with: - tail: all - dest: docker-logs - - - name: Upload docker logs if test fails - uses: actions/upload-artifact@v4 - if: failure() - with: - name: ${{ matrix.test_name }}-docker-logs - path: docker-logs - if-no-files-found: ignore - retention-days: 3 - omni-executor-test: runs-on: ubuntu-22.04 needs: @@ -1080,12 +900,6 @@ jobs: # run: | # docker compose -f docker-compose.yml -f ${{ matrix.test_name }}.yml up --no-build --exit-code-from ${{ matrix.test_name }} ${{ matrix.test_name }} - # - name: Stop integration omni executor docker containers - # working-directory: ./tee-worker/bitacross/docker - # if: needs.set-condition.outputs.run_omni_executor_test == 'true' - # run: | - # docker compose -f docker-compose.yml -f ${{ matrix.test_name }}.yml stop - - name: Collect docker logs if test fails continue-on-error: true uses: jwalton/gh-docker-logs@v2 @@ -1123,7 +937,6 @@ jobs: - set-condition - parachain-ts-test - identity-single-worker-test - - bitacross-worker-test - omni-executor-test if: ${{ !failure() && needs.set-condition.outputs.push_docker == 'true' }} steps: @@ -1135,10 +948,6 @@ jobs: with: name: litentry-identity - - uses: actions/download-artifact@v4 - with: - name: litentry-bitacross - - uses: actions/download-artifact@v4 with: name: litentry-omni @@ -1163,13 +972,6 @@ jobs: docker push litentry/identity-worker docker push litentry/identity-cli - - name: Push bitacross-worker image - if: needs.set-condition.outputs.rebuild_bitacross == 'true' - run: | - docker load < litentry-bitacross.tar.gz - docker push litentry/bitacross-worker - docker push litentry/bitacross-cli - - name: Push omni-executor image if: needs.set-condition.outputs.rebuild_omni_executor == 'true' run: | diff --git a/.github/workflows/create-release-draft.yml b/.github/workflows/create-release-draft.yml index fe5ebbd5f2..5023b6d5b8 100644 --- a/.github/workflows/create-release-draft.yml +++ b/.github/workflows/create-release-draft.yml @@ -18,11 +18,6 @@ on: description: identity-worker required: true default: true - bitacross_worker: - type: boolean - description: bitacross-worker - required: true - default: true release_tag: description: an existing tag for creating release (e.g. v1.2.0) required: true @@ -57,7 +52,6 @@ jobs: [ "${{ github.event.inputs.parachain_client }}" = "true" ] && t="${t:0:0}1${t:1}" [ "${{ github.event.inputs.parachain_runtime }}" = "true" ] && t="${t:0:1}1${t:2}" [ "${{ github.event.inputs.identity_worker }}" = "true" ] && t="${t:0:2}1${t:3}" - [ "${{ github.event.inputs.bitacross_worker }}" = "true" ] && t="${t:0:3}1${t:4}" if [ $t = "0000"]; then echo "::error::Please select at least one release type." exit 1 @@ -227,74 +221,6 @@ jobs: run: | docker push litentry/identity-worker:${{ env.RELEASE_TAG }} - build-bitacross-worker: - if: ${{ github.event.inputs.bitacross_worker == 'true' }} - runs-on: ubuntu-22.04 - environment: production - steps: - - name: Checkout codes on ${{ env.RELEASE_TAG }} - uses: actions/checkout@v4 - with: - ref: ${{ env.RELEASE_TAG }} - fetch-depth: 0 - - - name: Free up disk space - if: startsWith(runner.name, 'GitHub Actions') - uses: ./.github/actions/disk-cleanup - - - name: Set up Docker Buildx - uses: docker/setup-buildx-action@v3 - with: - # use the docker driver to access the local image - # we don't need external caches or multi platforms here - # see https://docs.docker.com/build/drivers/ - driver: docker - - - name: Write enclave signing key - run: | - cat << EOF > tee-worker/bitacross/enclave_key.pem - ${{ secrets.BITACROSS_ENCLAVE_PROD_SIGNING_KEY }} - EOF - - - name: Build local builder - uses: docker/build-push-action@v6 - env: - DOCKER_BUILD_RECORD_UPLOAD: false - with: - context: . - file: tee-worker/bitacross/build.Dockerfile - tags: local-builder:latest - target: builder - build-args: | - WORKER_MODE_ARG=offchain-worker - ADDITIONAL_FEATURES_ARG= - SGX_PRODUCTION=1 - SGX_MODE=HW - IMAGE_FOR_RELEASE=true - SGX_COMMERCIAL_KEY=enclave_key.pem - - - name: Build worker - uses: docker/build-push-action@v6 - env: - DOCKER_BUILD_RECORD_UPLOAD: false - with: - context: . - file: tee-worker/bitacross/build.Dockerfile - tags: litentry/bitacross-worker:${{ env.RELEASE_TAG }} - target: worker-release - - - run: docker images --all - - - name: Dockerhub login - uses: docker/login-action@v3 - with: - username: ${{ secrets.DOCKERHUB_USERNAME }} - password: ${{ secrets.DOCKERHUB_PASSWORD }} - - - name: Push worker image - run: | - docker push litentry/bitacross-worker:${{ env.RELEASE_TAG }} - parachain-ts-tests: runs-on: ubuntu-22.04 needs: build-parachain-client @@ -361,11 +287,10 @@ jobs: - set-release-type - build-parachain-runtime - build-identity-worker - - build-bitacross-worker - parachain-ts-tests if: | !failure() && - (success('build-parachain-runtime') || success('parachain-ts-tests') || success('build-identity-worker') || success('build-bitacross-worker')) + (success('build-parachain-runtime') || success('parachain-ts-tests') || success('build-identity-worker')) steps: - name: Checkout codes on ${{ env.RELEASE_TAG }} uses: actions/checkout@v4 diff --git a/Makefile b/Makefile index 2fce7c9943..c37805042e 100644 --- a/Makefile +++ b/Makefile @@ -105,7 +105,6 @@ fmt-cargo: @cd parachain && cargo fmt --all @cd tee-worker && cargo fmt --all @cd tee-worker/identity/enclave-runtime && cargo fmt --all - @cd tee-worker/bitacross/enclave-runtime && cargo fmt --all .PHONY: fmt-taplo ## taplo fmt fmt-taplo: diff --git a/common/primitives/core/src/teebag/types.rs b/common/primitives/core/src/teebag/types.rs index ec65014c3b..55190d981d 100644 --- a/common/primitives/core/src/teebag/types.rs +++ b/common/primitives/core/src/teebag/types.rs @@ -42,11 +42,8 @@ pub type EnclaveFingerprint = H256; )] pub enum OperationalMode { #[default] - #[codec(index = 0)] Production, - #[codec(index = 1)] Development, - #[codec(index = 2)] Maintenance, } @@ -71,7 +68,6 @@ pub enum AttestationType { pub enum WorkerType { #[default] Identity, - BitAcross, OmniExecutor, } @@ -85,9 +81,7 @@ pub enum WorkerMode { #[derive(Encode, Decode, Copy, Clone, Default, PartialEq, Eq, RuntimeDebug, TypeInfo)] pub enum SgxBuildMode { #[default] - #[codec(index = 0)] Production, - #[codec(index = 1)] Debug, } diff --git a/local-setup/launch.py b/local-setup/launch.py index 4d6a278c8e..a3275687c1 100755 --- a/local-setup/launch.py +++ b/local-setup/launch.py @@ -195,13 +195,13 @@ def get_flags(index, worker): return list(filter(None, [ "--clean-reset", - "-T", "wss://localhost" if worker == "bitacross" else "ws://localhost", + "-T", "ws://localhost", "-P", ports['trusted_worker_port'], "-w", ports['untrusted_worker_port'], "-r", ports['mura_port'], "-h", ports['untrusted_http_port'], "-p", ports['collator_ws_port'], - "--enable-mock-server" if worker == "identity" else "", + "--enable-mock-server", "--parentchain-start-block", "0", "--enable-metrics" if index == 0 else None ])) @@ -222,14 +222,8 @@ def add_collator_ports(): def main(processes, worker, workers_number, parachain_type, log_config_path, offset, parachain_dir): # Litentry - if worker == "identity": - worker_dir = "tee-worker/identity" - worker_bin = "litentry-worker" - elif worker == "bitacross": - worker_dir = "tee-worker/bitacross" - worker_bin = "bitacross-worker" - else: - sys.exit("Unsupported worker") + worker_dir = "tee-worker/identity" + worker_bin = "litentry-worker" print("Starting litentry parachain in background ...") if parachain_type == "standalone": @@ -306,7 +300,7 @@ def main(processes, worker, workers_number, parachain_type, log_config_path, off parser = argparse.ArgumentParser( description="Run a setup consisting of a node and some workers" ) - parser.add_argument("-w", "--worker", type=str, default="identity", help="Worker to run: identity / bitacross") + parser.add_argument("-w", "--worker", type=str, default="identity", help="Worker to run: identity") parser.add_argument("-wn", "--workers-number", type=int, default=1, help="Number of workers to run") parser.add_argument( "-p", diff --git a/parachain/Cargo.lock b/parachain/Cargo.lock index 10e9bd7cdd..0ab2bf1529 100644 --- a/parachain/Cargo.lock +++ b/parachain/Cargo.lock @@ -5806,7 +5806,6 @@ dependencies = [ "pallet-aura", "pallet-authorship", "pallet-balances", - "pallet-bitacross", "pallet-bounties", "pallet-bridge-transfer", "pallet-chain-bridge", @@ -7480,22 +7479,6 @@ dependencies = [ "sp-state-machine", ] -[[package]] -name = "pallet-bitacross" -version = "0.1.0" -dependencies = [ - "core-primitives", - "frame-benchmarking", - "frame-support", - "frame-system", - "pallet-balances", - "pallet-timestamp", - "parity-scale-codec", - "scale-info", - "sp-io", - "sp-runtime", -] - [[package]] name = "pallet-bounties" version = "36.0.0" @@ -9268,7 +9251,6 @@ dependencies = [ "pallet-aura", "pallet-authorship", "pallet-balances", - "pallet-bitacross", "pallet-bounties", "pallet-bridge-transfer", "pallet-chain-bridge", diff --git a/parachain/Cargo.toml b/parachain/Cargo.toml index 681d1c2a98..9f79774779 100644 --- a/parachain/Cargo.toml +++ b/parachain/Cargo.toml @@ -3,7 +3,6 @@ resolver = "2" members = [ 'node', 'pallets/account-fix', - 'pallets/bitacross', 'pallets/bridge/assets-handler', 'pallets/bridge/chain-bridge', 'pallets/bridge/bridge-transfer', @@ -270,7 +269,6 @@ paseo-parachain-runtime = { path = "runtime/paseo", default-features = false } pallet-account-fix = { path = "pallets/account-fix", default-features = false } pallet-asset-manager = { path = "pallets/xcm-asset-manager", default-features = false } pallet-assets-handler = { path = "pallets/bridge/assets-handler", default-features = false } -pallet-bitacross = { path = "pallets/bitacross", default-features = false } pallet-chain-bridge = { path = "pallets/bridge/chain-bridge", default-features = false } pallet-bridge-common = { path = "pallets/bridge/common", default-features = false } pallet-bridge-transfer = { path = "pallets/bridge/bridge-transfer", default-features = false } diff --git a/parachain/node/src/chain_specs/litentry.rs b/parachain/node/src/chain_specs/litentry.rs index eedad7cdea..0ae572c6fe 100644 --- a/parachain/node/src/chain_specs/litentry.rs +++ b/parachain/node/src/chain_specs/litentry.rs @@ -17,7 +17,7 @@ use super::*; use cumulus_primitives_core::ParaId; use litentry_parachain_runtime::{ - AccountId, AuraId, Balance, BalancesConfig, BitacrossConfig, CouncilMembershipConfig, + AccountId, AuraId, Balance, BalancesConfig, CouncilMembershipConfig, DeveloperCommitteeMembershipConfig, ParachainInfoConfig, ParachainStakingConfig, PolkadotXcmConfig, RuntimeGenesisConfig, SessionConfig, TechnicalCommitteeMembershipConfig, TeebagConfig, TeebagOperationalMode, VCManagementConfig, WASM_BINARY, @@ -238,7 +238,6 @@ fn generate_genesis( admin: None, mode: TeebagOperationalMode::Development, }, - bitacross: BitacrossConfig { admin: None }, score_staking: Default::default(), }; diff --git a/parachain/node/src/chain_specs/paseo.rs b/parachain/node/src/chain_specs/paseo.rs index d72874568d..06346171e2 100644 --- a/parachain/node/src/chain_specs/paseo.rs +++ b/parachain/node/src/chain_specs/paseo.rs @@ -18,7 +18,7 @@ use super::*; use core_primitives::PASEO_PARA_ID; use cumulus_primitives_core::ParaId; use paseo_parachain_runtime::{ - AccountId, AuraId, Balance, BalancesConfig, BitacrossConfig, CouncilMembershipConfig, + AccountId, AuraId, Balance, BalancesConfig, CouncilMembershipConfig, DeveloperCommitteeMembershipConfig, ParachainInfoConfig, ParachainStakingConfig, PolkadotXcmConfig, RuntimeGenesisConfig, SessionConfig, SudoConfig, TechnicalCommitteeMembershipConfig, TeebagConfig, TeebagOperationalMode, VCManagementConfig, @@ -227,7 +227,6 @@ fn generate_genesis( admin: Some(root_key.clone()), mode: TeebagOperationalMode::Development, }, - bitacross: BitacrossConfig { admin: Some(root_key) }, score_staking: Default::default(), }; diff --git a/parachain/pallets/teebag/src/tests.rs b/parachain/pallets/teebag/src/tests.rs index 18e258c244..eb5a96a6be 100644 --- a/parachain/pallets/teebag/src/tests.rs +++ b/parachain/pallets/teebag/src/tests.rs @@ -104,7 +104,6 @@ fn register_enclave_dev_works_with_no_authorized_enclave() { let enclave = default_enclave().with_mrenclave(TEST4_MRENCLAVE); assert_eq!(Teebag::enclave_count(WorkerType::Identity), 1); - assert_eq!(Teebag::enclave_count(WorkerType::BitAcross), 0); assert_eq!(EnclaveRegistry::::get(alice()).unwrap(), enclave); let authorized_enclave = AuthorizedEnclave::::get(WorkerType::default()); assert_eq!(authorized_enclave.len(), 1); @@ -136,7 +135,6 @@ fn register_enclave_dev_works_with_sgx_build_mode_debug() { .with_attestation_type(AttestationType::Ias); assert_eq!(Teebag::enclave_count(WorkerType::Identity), 1); - assert_eq!(Teebag::enclave_count(WorkerType::BitAcross), 0); assert_eq!(EnclaveRegistry::::get(signer4).unwrap(), enclave); }) } @@ -159,7 +157,7 @@ fn parentchain_block_processed_works() { // Ensure that enclave is registered assert_ok!(Teebag::register_enclave( RuntimeOrigin::signed(signer7.clone()), - WorkerType::BitAcross, + WorkerType::Identity, Default::default(), TEST7_CERT.to_vec(), URL.to_vec(), @@ -167,7 +165,7 @@ fn parentchain_block_processed_works() { None, AttestationType::Ias, )); - assert_eq!(Teebag::enclave_count(WorkerType::BitAcross), 1); + assert_eq!(Teebag::enclave_count(WorkerType::Identity), 1); run_to_block(3); Timestamp::set_timestamp(TEST7_TIMESTAMP + 24 * 1000); @@ -309,7 +307,6 @@ fn register_enclave_prod_works_with_sgx_build_mode_debug() { .with_attestation_type(AttestationType::Ias); assert_eq!(Teebag::enclave_count(WorkerType::Identity), 1); - assert_eq!(Teebag::enclave_count(WorkerType::BitAcross), 0); assert_eq!(EnclaveRegistry::::get(signer4).unwrap(), enclave); }) } @@ -350,7 +347,6 @@ fn register_enclave_prod_works_with_sgx_build_mode_production() { .with_attestation_type(AttestationType::Ias); assert_eq!(Teebag::enclave_count(WorkerType::Identity), 1); - assert_eq!(Teebag::enclave_count(WorkerType::BitAcross), 0); assert_eq!(EnclaveRegistry::::get(signer8).unwrap(), enclave); // remove authorized enclave should remove enclave too @@ -419,12 +415,12 @@ fn register_enclave_prod_fails_with_max_limit_reached() { )); assert_ok!(Teebag::force_add_authorized_enclave( RuntimeOrigin::signed(alice()), - WorkerType::BitAcross, + WorkerType::OmniExecutor, TEST4_MRENCLAVE )); assert_ok!(Teebag::force_add_authorized_enclave( RuntimeOrigin::signed(alice()), - WorkerType::BitAcross, + WorkerType::OmniExecutor, TEST6_MRENCLAVE )); @@ -433,7 +429,7 @@ fn register_enclave_prod_fails_with_max_limit_reached() { let signer6: AccountId32 = get_signer(TEST6_SIGNER_PUB); assert_ok!(Teebag::add_enclave_identifier( RuntimeOrigin::signed(admin.clone()), - WorkerType::BitAcross, + WorkerType::OmniExecutor, signer4.clone(), )); assert_ok!(Teebag::add_enclave_identifier( @@ -443,7 +439,7 @@ fn register_enclave_prod_fails_with_max_limit_reached() { )); assert_ok!(Teebag::add_enclave_identifier( RuntimeOrigin::signed(admin.clone()), - WorkerType::BitAcross, + WorkerType::OmniExecutor, signer6.clone(), )); assert_ok!(Teebag::add_enclave_identifier( @@ -455,7 +451,7 @@ fn register_enclave_prod_fails_with_max_limit_reached() { Timestamp::set_timestamp(TEST4_TIMESTAMP); assert_ok!(Teebag::register_enclave( RuntimeOrigin::signed(signer4.clone()), - WorkerType::BitAcross, + WorkerType::OmniExecutor, Default::default(), TEST4_CERT.to_vec(), URL.to_vec(), @@ -467,7 +463,7 @@ fn register_enclave_prod_fails_with_max_limit_reached() { Timestamp::set_timestamp(TEST6_TIMESTAMP); assert_ok!(Teebag::register_enclave( RuntimeOrigin::signed(signer6.clone()), - WorkerType::BitAcross, + WorkerType::OmniExecutor, Default::default(), TEST6_CERT.to_vec(), URL.to_vec(), @@ -522,7 +518,7 @@ fn register_enclave_prod_fails_with_max_limit_reached() { ); assert_eq!(Teebag::enclave_count(WorkerType::Identity), 2); - assert_eq!(Teebag::enclave_count(WorkerType::BitAcross), 1); + assert_eq!(Teebag::enclave_count(WorkerType::OmniExecutor), 1); }) } diff --git a/parachain/runtime/litentry/Cargo.toml b/parachain/runtime/litentry/Cargo.toml index 945fad61a4..d1f8b10039 100644 --- a/parachain/runtime/litentry/Cargo.toml +++ b/parachain/runtime/litentry/Cargo.toml @@ -82,7 +82,6 @@ frame-system-benchmarking = { workspace = true, optional = true } core-primitives = { workspace = true } pallet-account-fix = { workspace = true } pallet-asset-manager = { workspace = true } -pallet-bitacross = { workspace = true } pallet-bridge-transfer = { workspace = true } pallet-chain-bridge = { workspace = true } pallet-evm-assertions = { workspace = true } @@ -151,7 +150,6 @@ runtime-benchmarks = [ "pallet-assets-handler/runtime-benchmarks", "pallet-assets/runtime-benchmarks", "pallet-balances/runtime-benchmarks", - "pallet-bitacross/runtime-benchmarks", "pallet-bounties/runtime-benchmarks", "pallet-bridge-transfer/runtime-benchmarks", "pallet-chain-bridge/runtime-benchmarks", @@ -227,7 +225,6 @@ std = [ "pallet-aura/std", "pallet-authorship/std", "pallet-balances/std", - "pallet-bitacross/std", "pallet-bounties/std", "pallet-bridge-transfer/std", "pallet-chain-bridge/std", @@ -320,7 +317,6 @@ try-runtime = [ "pallet-aura/try-runtime", "pallet-authorship/try-runtime", "pallet-balances/try-runtime", - "pallet-bitacross/try-runtime", "pallet-bounties/try-runtime", "pallet-bridge-transfer/try-runtime", "pallet-chain-bridge/try-runtime", diff --git a/parachain/runtime/litentry/src/lib.rs b/parachain/runtime/litentry/src/lib.rs index 73e79953a5..ff555e4d85 100644 --- a/parachain/runtime/litentry/src/lib.rs +++ b/parachain/runtime/litentry/src/lib.rs @@ -1122,12 +1122,6 @@ impl pallet_omni_account::Config for Runtime { type OmniAccountConverter = DefaultOmniAccountConverter; } -impl pallet_bitacross::Config for Runtime { - type RuntimeEvent = RuntimeEvent; - type TEECallOrigin = EnsureEnclaveSigner; - type SetAdminOrigin = EnsureRootOrHalfCouncil; -} - impl pallet_evm_assertions::Config for Runtime { type RuntimeEvent = RuntimeEvent; type AssertionId = H160; @@ -1246,7 +1240,6 @@ construct_runtime! { ExtrinsicFilter: pallet_extrinsic_filter = 63, AssetManager: pallet_asset_manager = 64, Teebag: pallet_teebag = 65, - Bitacross: pallet_bitacross = 66, AssetsHandler: pallet_assets_handler = 68, EvmAssertions: pallet_evm_assertions = 71, @@ -1350,7 +1343,6 @@ impl Contains for NormalModeFilter { // AccountFix RuntimeCall::AccountFix(_) | RuntimeCall::AssetsHandler(_) | - RuntimeCall::Bitacross(_) | RuntimeCall::EvmAssertions(_) | RuntimeCall::ScoreStaking(_) | RuntimeCall::OmniAccount(_) diff --git a/parachain/runtime/paseo/Cargo.toml b/parachain/runtime/paseo/Cargo.toml index b08d5db88f..3f0cb5a128 100644 --- a/parachain/runtime/paseo/Cargo.toml +++ b/parachain/runtime/paseo/Cargo.toml @@ -82,7 +82,6 @@ pallet-account-fix = { workspace = true } pallet-asset-manager = { workspace = true } pallet-assets = { workspace = true } pallet-assets-handler = { workspace = true } -pallet-bitacross = { workspace = true } pallet-bridge-transfer = { workspace = true } pallet-chain-bridge = { workspace = true } pallet-evm-assertions = { workspace = true } @@ -164,7 +163,6 @@ runtime-benchmarks = [ "pallet-assets-handler/runtime-benchmarks", "pallet-assets/runtime-benchmarks", "pallet-balances/runtime-benchmarks", - "pallet-bitacross/runtime-benchmarks", "pallet-bounties/runtime-benchmarks", "pallet-bridge-transfer/runtime-benchmarks", "pallet-chain-bridge/runtime-benchmarks", @@ -248,7 +246,6 @@ std = [ "pallet-aura/std", "pallet-authorship/std", "pallet-balances/std", - "pallet-bitacross/std", "pallet-bounties/std", "pallet-bridge-transfer/std", "pallet-chain-bridge/std", @@ -352,7 +349,6 @@ try-runtime = [ "pallet-aura/try-runtime", "pallet-authorship/try-runtime", "pallet-balances/try-runtime", - "pallet-bitacross/try-runtime", "pallet-bounties/try-runtime", "pallet-bridge-transfer/try-runtime", "pallet-chain-bridge/try-runtime", diff --git a/parachain/runtime/paseo/src/lib.rs b/parachain/runtime/paseo/src/lib.rs index 7bdbb112d1..ea8c148dc5 100644 --- a/parachain/runtime/paseo/src/lib.rs +++ b/parachain/runtime/paseo/src/lib.rs @@ -1166,12 +1166,6 @@ impl pallet_omni_account::Config for Runtime { type OmniAccountConverter = DefaultOmniAccountConverter; } -impl pallet_bitacross::Config for Runtime { - type RuntimeEvent = RuntimeEvent; - type TEECallOrigin = EnsureEnclaveSigner; - type SetAdminOrigin = EnsureRootOrAllCouncil; -} - impl pallet_evm_assertions::Config for Runtime { type RuntimeEvent = RuntimeEvent; type AssertionId = H160; @@ -1373,7 +1367,6 @@ construct_runtime! { VCManagement: pallet_vc_management = 66, IMPExtrinsicWhitelist: pallet_group:: = 67, VCMPExtrinsicWhitelist: pallet_group:: = 68, - Bitacross: pallet_bitacross = 70, EvmAssertions: pallet_evm_assertions = 71, // Developer council @@ -1497,7 +1490,6 @@ impl Contains for NormalModeFilter { // AccountFix RuntimeCall::AccountFix(_) | RuntimeCall::AssetsHandler(_) | - RuntimeCall::Bitacross(_) | RuntimeCall::EvmAssertions(_) | RuntimeCall::ScoreStaking(_) | RuntimeCall::OmniAccount(_) | diff --git a/tee-worker/Cargo.lock b/tee-worker/Cargo.lock index d7a071eec1..f360290ccd 100644 --- a/tee-worker/Cargo.lock +++ b/tee-worker/Cargo.lock @@ -366,480 +366,6 @@ version = "1.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8c3c1a368f70d6cf7302d78f8f7093da241fb8e8807c05cc9e51a125895a6d5b" -[[package]] -name = "bc-enclave-registry" -version = "0.1.0" -dependencies = [ - "base64 0.13.1", - "itp-settings", - "itp-sgx-io", - "litentry-primitives", - "log 0.4.20", - "parity-scale-codec", - "sgx_tstd", - "sp-std", - "thiserror 1.0.44", - "thiserror 1.0.9", -] - -[[package]] -name = "bc-ita-parentchain-interface" -version = "0.1.0" -dependencies = [ - "bc-enclave-registry", - "bc-ita-sgx-runtime", - "bc-ita-stf", - "bc-itc-parentchain-indirect-calls-executor", - "bc-itp-stf-executor", - "bc-itp-top-pool-author", - "bc-relayer-registry", - "bc-signer-registry", - "env_logger 0.10.2", - "itc-parentchain-test", - "itp-api-client-types", - "itp-node-api", - "itp-sgx-crypto", - "itp-stf-primitives", - "itp-test", - "itp-types", - "litentry-primitives", - "log 0.4.20", - "parity-scale-codec", - "sgx_tstd", - "sp-core", - "sp-runtime", - "sp-std", - "substrate-api-client", -] - -[[package]] -name = "bc-ita-sgx-runtime" -version = "0.1.0" -dependencies = [ - "frame-executive", - "frame-support", - "frame-system", - "itp-sgx-runtime-primitives", - "pallet-balances", - "pallet-parentchain", - "pallet-sudo", - "pallet-timestamp", - "pallet-transaction-payment", - "parity-scale-codec", - "scale-info", - "sp-api", - "sp-core", - "sp-runtime", - "sp-std", - "sp-version", -] - -[[package]] -name = "bc-ita-stf" -version = "0.1.0" -dependencies = [ - "bc-ita-sgx-runtime", - "frame-support", - "frame-system", - "hex", - "hex-literal", - "itp-hashing", - "itp-node-api", - "itp-sgx-externalities", - "itp-stf-interface", - "itp-stf-primitives", - "itp-storage", - "itp-types", - "itp-utils", - "litentry-macros", - "litentry-primitives", - "log 0.4.20", - "pallet-balances", - "pallet-parentchain", - "pallet-sudo", - "parity-scale-codec", - "sgx_tstd", - "sp-core", - "sp-io 7.0.0", - "sp-keyring", - "sp-runtime", - "sp-std", -] - -[[package]] -name = "bc-itc-direct-rpc-client" -version = "0.1.0" -dependencies = [ - "itp-rpc", - "itp-types", - "itp-utils", - "log 0.4.20", - "rustls 0.19.0 (git+https://github.com/mesalock-linux/rustls?tag=sgx_1.1.3)", - "rustls 0.19.1", - "serde_json 1.0.133", - "sgx_tstd", - "tungstenite 0.14.0", - "tungstenite 0.15.0", - "url 2.5.0 (git+https://github.com/domenukk/rust-url?rev=316c868)", - "webpki 0.21.4 (registry+https://github.com/rust-lang/crates.io-index)", - "webpki 0.21.4 (git+https://github.com/mesalock-linux/webpki?branch=mesalock_sgx)", -] - -[[package]] -name = "bc-itc-direct-rpc-server" -version = "0.1.0" -dependencies = [ - "itc-tls-websocket-server", - "itp-rpc", - "itp-types", - "itp-utils", - "jsonrpc-core 18.0.0 (registry+https://github.com/rust-lang/crates.io-index)", - "jsonrpc-core 18.0.0 (git+https://github.com/scs/jsonrpc?branch=no_std_v18)", - "log 0.4.20", - "parity-scale-codec", - "serde_json 1.0.133", - "sgx_tstd", - "sp-runtime", - "thiserror 1.0.44", - "thiserror 1.0.9", -] - -[[package]] -name = "bc-itc-offchain-worker-executor" -version = "0.1.0" -dependencies = [ - "bc-itp-stf-executor", - "bc-itp-top-pool-author", - "itc-parentchain-light-client", - "itp-extrinsics-factory", - "itp-sgx-externalities", - "itp-stf-interface", - "itp-stf-primitives", - "itp-stf-state-handler", - "itp-test", - "itp-types", - "log 0.4.20", - "parity-scale-codec", - "sgx_tstd", - "sp-core", - "sp-runtime", - "thiserror 1.0.44", - "thiserror 1.0.9", -] - -[[package]] -name = "bc-itc-parentchain" -version = "0.1.0" -dependencies = [ - "bc-itc-parentchain-block-import-dispatcher", - "bc-itc-parentchain-block-importer", - "bc-itc-parentchain-indirect-calls-executor", - "itc-parentchain-light-client", - "itp-types", - "parity-scale-codec", - "sp-runtime", -] - -[[package]] -name = "bc-itc-parentchain-block-import-dispatcher" -version = "0.1.0" -dependencies = [ - "bc-itc-parentchain-block-importer", - "itp-import-queue", - "log 0.4.20", - "sgx_tstd", - "sgx_types", - "thiserror 1.0.44", - "thiserror 1.0.9", -] - -[[package]] -name = "bc-itc-parentchain-block-importer" -version = "0.1.0" -dependencies = [ - "bc-ita-stf", - "bc-itc-parentchain-indirect-calls-executor", - "bc-itp-stf-executor", - "itc-parentchain-light-client", - "itp-enclave-metrics", - "itp-extrinsics-factory", - "itp-ocall-api", - "itp-stf-interface", - "itp-types", - "log 0.4.20", - "parity-scale-codec", - "sgx_tstd", - "sgx_types", - "sp-runtime", - "thiserror 1.0.44", - "thiserror 1.0.9", -] - -[[package]] -name = "bc-itc-parentchain-indirect-calls-executor" -version = "0.1.0" -dependencies = [ - "bc-enclave-registry", - "bc-itp-stf-executor", - "bc-itp-top-pool-author", - "bc-relayer-registry", - "bc-signer-registry", - "binary-merkle-tree", - "bs58", - "env_logger 0.10.2", - "futures 0.3.28", - "futures 0.3.8", - "itc-parentchain-test", - "itp-api-client-types", - "itp-node-api", - "itp-sgx-crypto", - "itp-sgx-runtime-primitives", - "itp-stf-primitives", - "itp-test", - "itp-types", - "litentry-primitives", - "log 0.4.20", - "parity-scale-codec", - "sgx_tstd", - "sgx_types", - "sp-runtime", - "thiserror 1.0.44", - "thiserror 1.0.9", -] - -[[package]] -name = "bc-itp-enclave-api" -version = "0.1.0" -dependencies = [ - "bc-itp-enclave-api-ffi", - "frame-support", - "hex", - "itp-settings", - "itp-sgx-crypto", - "itp-stf-interface", - "itp-storage", - "itp-types", - "log 0.4.20", - "parity-scale-codec", - "serde_json 1.0.133", - "sgx_crypto_helper", - "sgx_types", - "sgx_urts", - "sp-core", - "sp-runtime", - "thiserror 1.0.44", -] - -[[package]] -name = "bc-itp-enclave-api-ffi" -version = "0.1.0" -dependencies = [ - "sgx_types", -] - -[[package]] -name = "bc-itp-stf-executor" -version = "0.1.0" -dependencies = [ - "bc-itp-top-pool", - "bc-itp-top-pool-author", - "hex", - "itc-parentchain-test", - "itp-enclave-metrics", - "itp-node-api", - "itp-ocall-api", - "itp-sgx-crypto", - "itp-sgx-externalities", - "itp-stf-interface", - "itp-stf-primitives", - "itp-stf-state-handler", - "itp-stf-state-observer", - "itp-test", - "itp-time-utils", - "itp-types", - "log 0.4.20", - "parity-scale-codec", - "sgx_tstd", - "sgx_types", - "sp-core", - "sp-runtime", - "thiserror 1.0.44", - "thiserror 1.0.9", -] - -[[package]] -name = "bc-itp-top-pool" -version = "0.1.0" -dependencies = [ - "bc-itc-direct-rpc-server", - "byteorder 1.4.3", - "derive_more", - "itp-stf-primitives", - "itp-test", - "itp-types", - "jsonrpc-core 18.0.0 (registry+https://github.com/rust-lang/crates.io-index)", - "jsonrpc-core 18.0.0 (git+https://github.com/scs/jsonrpc?branch=no_std_v18)", - "linked-hash-map 0.5.2", - "linked-hash-map 0.5.6", - "litentry-primitives", - "log 0.4.20", - "parity-scale-codec", - "parity-util-mem", - "serde 1.0.210", - "sgx_tstd", - "sp-application-crypto", - "sp-core", - "sp-runtime", -] - -[[package]] -name = "bc-itp-top-pool-author" -version = "0.1.0" -dependencies = [ - "bc-itp-top-pool", - "derive_more", - "futures 0.3.28", - "itp-enclave-metrics", - "itp-ocall-api", - "itp-sgx-crypto", - "itp-stf-primitives", - "itp-stf-state-handler", - "itp-test", - "itp-types", - "itp-utils", - "jsonrpc-core 18.0.0 (registry+https://github.com/rust-lang/crates.io-index)", - "jsonrpc-core 18.0.0 (git+https://github.com/scs/jsonrpc?branch=no_std_v18)", - "lazy_static", - "litentry-primitives", - "log 0.4.20", - "parity-scale-codec", - "sgx_crypto_helper", - "sgx_tstd", - "sp-core", - "sp-keyring", - "sp-runtime", -] - -[[package]] -name = "bc-musig2-ceremony" -version = "0.1.0" -dependencies = [ - "itp-sgx-crypto", - "k256", - "litentry-primitives", - "log 0.4.20", - "musig2 0.0.8 (git+https://github.com/kziemianek/musig2?branch=master)", - "musig2 0.0.8 (git+https://github.com/kailai-wang/musig2?branch=use-sha2-0.8)", - "parity-scale-codec", - "rand 0.8.5", - "sgx_rand", - "sgx_tstd", - "signature 2.1.0", -] - -[[package]] -name = "bc-musig2-event" -version = "0.1.0" -dependencies = [ - "bc-enclave-registry", - "bc-itc-direct-rpc-client", - "bc-itc-direct-rpc-server", - "bc-musig2-ceremony", - "itp-ocall-api", - "itp-rpc", - "itp-sgx-crypto", - "itp-types", - "itp-utils", - "lc-direct-call", - "litentry-primitives", - "log 0.4.20", - "parity-scale-codec", - "rand 0.8.5", - "sgx_rand", - "sgx_tstd", - "sp-core", - "threadpool 1.8.0", - "threadpool 1.8.1", -] - -[[package]] -name = "bc-relayer-registry" -version = "0.1.0" -dependencies = [ - "base64 0.13.1", - "itp-settings", - "itp-sgx-io", - "litentry-primitives", - "log 0.4.20", - "parity-scale-codec", - "sgx_tstd", - "sp-std", - "thiserror 1.0.44", - "thiserror 1.0.9", -] - -[[package]] -name = "bc-signer-registry" -version = "0.1.0" -dependencies = [ - "base64 0.13.1", - "itp-settings", - "itp-sgx-io", - "litentry-primitives", - "log 0.4.20", - "parity-scale-codec", - "sgx_tstd", - "sp-std", - "thiserror 1.0.44", - "thiserror 1.0.9", -] - -[[package]] -name = "bc-task-processor" -version = "0.1.0" -dependencies = [ - "bc-enclave-registry", - "bc-ita-stf", - "bc-itc-direct-rpc-client", - "bc-itc-direct-rpc-server", - "bc-itp-stf-executor", - "bc-musig2-ceremony", - "bc-musig2-event", - "bc-relayer-registry", - "bc-signer-registry", - "bc-task-sender", - "frame-support", - "futures 0.3.8", - "itp-enclave-metrics", - "itp-ocall-api", - "itp-sgx-crypto", - "itp-sgx-externalities", - "itp-stf-state-handler", - "lc-direct-call", - "litentry-primitives", - "log 0.4.20", - "parity-scale-codec", - "sgx_crypto_helper", - "sgx_tstd", - "sp-core", - "thiserror 1.0.44", - "thiserror 1.0.9", - "threadpool 1.8.0", - "threadpool 1.8.1", -] - -[[package]] -name = "bc-task-sender" -version = "0.1.0" -dependencies = [ - "futures 0.3.28", - "futures 0.3.8", - "lazy_static", - "litentry-primitives", - "parity-scale-codec", - "sgx_tstd", -] - [[package]] name = "bech32" version = "0.10.0-beta" @@ -899,108 +425,6 @@ version = "0.6.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "349f9b6a179ed607305526ca489b34ad0a41aed5f7980fa90eb03160b69598fb" -[[package]] -name = "bitacross-cli" -version = "0.0.1" -dependencies = [ - "base58", - "bc-ita-parentchain-interface", - "bc-ita-stf", - "bc-musig2-ceremony", - "chrono 0.4.26", - "clap 4.1.0", - "env_logger 0.10.2", - "hdrhistogram", - "hex", - "itc-rpc-client", - "itp-node-api", - "itp-rpc", - "itp-sgx-crypto", - "itp-stf-primitives", - "itp-types", - "itp-utils", - "lc-direct-call", - "litentry-primitives", - "log 0.4.20", - "parity-scale-codec", - "rand 0.8.5", - "rayon", - "regex 1.9.5", - "reqwest", - "serde 1.0.210", - "serde_json 1.0.133", - "sgx_crypto_helper", - "sp-application-crypto", - "sp-core", - "sp-keyring", - "sp-keystore", - "sp-runtime", - "substrate-api-client", - "substrate-client-keystore", - "thiserror 1.0.44", - "urlencoding", -] - -[[package]] -name = "bitacross-worker" -version = "0.1.0" -dependencies = [ - "anyhow", - "async-trait", - "base58", - "bc-ita-parentchain-interface", - "bc-itc-parentchain", - "bc-itp-enclave-api", - "clap 2.34.0", - "config", - "dirs", - "env_logger 0.10.2", - "frame-support", - "futures 0.3.28", - "hex", - "humantime", - "ipfs-api", - "itc-parentchain-test", - "itc-rest-client", - "itc-rpc-client", - "itp-api-client-types", - "itp-enclave-metrics", - "itp-node-api", - "itp-settings", - "itp-sgx-crypto", - "itp-stf-interface", - "itp-storage", - "itp-time-utils", - "itp-types", - "itp-utils", - "jsonrpsee", - "lazy_static", - "litentry-primitives", - "log 0.4.20", - "mockall", - "parity-scale-codec", - "parking_lot 0.12.1", - "parse_duration", - "prometheus", - "rayon", - "regex 1.9.5", - "scale-info", - "serde 1.0.210", - "serde_derive 1.0.210", - "serde_json 1.0.133", - "sgx_crypto_helper", - "sgx_types", - "sp-consensus-grandpa", - "sp-core", - "sp-keyring", - "sp-runtime", - "substrate-api-client", - "thiserror 1.0.44", - "tokio", - "url 2.5.0 (registry+https://github.com/rust-lang/crates.io-index)", - "warp", -] - [[package]] name = "bitcoin" version = "0.31.0" @@ -1584,7 +1008,7 @@ checksum = "740fe28e594155f10cfc383984cbefd529d7396050557148f79cb0f621204124" dependencies = [ "generic-array 0.14.7", "rand_core 0.6.4", - "subtle 2.5.0 (registry+https://github.com/rust-lang/crates.io-index)", + "subtle", "zeroize", ] @@ -1605,7 +1029,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b584a330336237c1eecd3e94266efb216c56ed91225d634cb2991c5f3fd1aeab" dependencies = [ "generic-array 0.14.7", - "subtle 2.5.0 (registry+https://github.com/rust-lang/crates.io-index)", + "subtle", ] [[package]] @@ -1615,7 +1039,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "25fab6889090c8133f3deb8f73ba3c65a7f456f66436fc012a1b1e272b1e103e" dependencies = [ "generic-array 0.14.7", - "subtle 2.5.0 (registry+https://github.com/rust-lang/crates.io-index)", + "subtle", ] [[package]] @@ -1636,7 +1060,7 @@ dependencies = [ "byteorder 1.4.3", "digest 0.8.1", "rand_core 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)", - "subtle 2.5.0 (registry+https://github.com/rust-lang/crates.io-index)", + "subtle", "zeroize", ] @@ -1649,7 +1073,7 @@ dependencies = [ "byteorder 1.4.3", "digest 0.9.0", "rand_core 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)", - "subtle 2.5.0 (registry+https://github.com/rust-lang/crates.io-index)", + "subtle", "zeroize", ] @@ -1784,7 +1208,7 @@ dependencies = [ "block-buffer 0.10.4", "const-oid", "crypto-common", - "subtle 2.5.0 (registry+https://github.com/rust-lang/crates.io-index)", + "subtle", ] [[package]] @@ -1922,7 +1346,7 @@ dependencies = [ "pkcs8", "rand_core 0.6.4", "sec1", - "subtle 2.5.0 (registry+https://github.com/rust-lang/crates.io-index)", + "subtle", "zeroize", ] @@ -2249,7 +1673,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ded41244b729663b1e574f1b4fb731469f69f79c17667b5d776b16cda0479449" dependencies = [ "rand_core 0.6.4", - "subtle 2.5.0 (registry+https://github.com/rust-lang/crates.io-index)", + "subtle", ] [[package]] @@ -2708,7 +2132,7 @@ name = "futures-task" version = "0.3.8" source = "git+https://github.com/mesalock-linux/futures-rs-sgx#d54882f24ddf7d61327a067b2f608d6940a36444" dependencies = [ - "once_cell 1.4.0 (git+https://github.com/mesalock-linux/once_cell-sgx)", + "once_cell 1.4.0", "sgx_tstd", ] @@ -2858,7 +2282,7 @@ checksum = "f0f9ef7462f7c099f518d754361858f86d8a07af53ba9af0fe635bbccb151a63" dependencies = [ "ff", "rand_core 0.6.4", - "subtle 2.5.0 (registry+https://github.com/rust-lang/crates.io-index)", + "subtle", ] [[package]] @@ -5080,27 +4504,6 @@ dependencies = [ "url 2.5.0 (git+https://github.com/domenukk/rust-url?rev=316c868)", ] -[[package]] -name = "lc-direct-call" -version = "0.1.0" -dependencies = [ - "bc-enclave-registry", - "bc-musig2-ceremony", - "bc-relayer-registry", - "bc-signer-registry", - "hex", - "itp-sgx-crypto", - "itp-stf-primitives", - "k256", - "litentry-primitives", - "log 0.4.20", - "parity-scale-codec", - "rand 0.7.3 (registry+https://github.com/rust-lang/crates.io-index)", - "sgx_tstd", - "sp-core", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42)", -] - [[package]] name = "lc-dynamic-assertion" version = "0.1.0" @@ -5465,7 +4868,7 @@ checksum = "5be9b9bb642d8522a44d533eab56c16c738301965504753b03ad1de3425d5451" dependencies = [ "crunchy", "digest 0.9.0", - "subtle 2.5.0 (registry+https://github.com/rust-lang/crates.io-index)", + "subtle", ] [[package]] @@ -6047,38 +5450,6 @@ dependencies = [ "synstructure", ] -[[package]] -name = "musig2" -version = "0.0.8" -source = "git+https://github.com/kziemianek/musig2?branch=master#cd5e61ac9ecdf842da58605ac7b07b6e359f08c5" -dependencies = [ - "base16ct", - "hmac 0.12.1", - "k256", - "once_cell 1.19.0", - "secp 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)", - "secp256k1 0.28.0", - "sha2 0.10.8", - "subtle 2.5.0 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "musig2" -version = "0.0.8" -source = "git+https://github.com/kailai-wang/musig2?branch=use-sha2-0.8#93857e52abbe8f9898c9ec743eecb1380132abcb" -dependencies = [ - "base16ct", - "hmac 0.12.1", - "k256", - "once_cell 1.4.0 (git+https://github.com/mesalock-linux/once_cell-sgx?branch=master)", - "secp 0.2.3 (git+https://github.com/kziemianek/secp.git?branch=sgx)", - "secp256k1 0.28.0", - "sgx_tstd", - "sha2 0.10.8", - "sha2_v08_wrapper", - "subtle 2.5.0 (git+https://github.com/kziemianek/subtle-sgx.git?branch=2.5.0-update)", -] - [[package]] name = "nalgebra" version = "0.32.3" @@ -6435,14 +5806,6 @@ dependencies = [ "cipher", ] -[[package]] -name = "once_cell" -version = "1.4.0" -source = "git+https://github.com/mesalock-linux/once_cell-sgx?branch=master#cefcaa03fed4d85276b3235d875f1b45d399cc3c" -dependencies = [ - "sgx_tstd", -] - [[package]] name = "once_cell" version = "1.4.0" @@ -6841,7 +6204,7 @@ version = "0.8.2" source = "git+https://github.com/mesalock-linux/pem-rs-sgx#fdfef4f24a9fb3fa72e8a71bb28bd8ff15feff2f" dependencies = [ "base64 0.13.0 (git+https://github.com/mesalock-linux/rust-base64-sgx)", - "once_cell 1.4.0 (git+https://github.com/mesalock-linux/once_cell-sgx)", + "once_cell 1.4.0", "regex 1.3.1", "sgx_tstd", ] @@ -7474,7 +6837,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8dd2a808d456c4a54e300a23e9f5a67e122c3024119acbfd73e3bf664491cb2" dependencies = [ "hmac 0.12.1", - "subtle 2.5.0 (registry+https://github.com/rust-lang/crates.io-index)", + "subtle", ] [[package]] @@ -7953,7 +7316,7 @@ dependencies = [ "rand 0.7.3 (registry+https://github.com/rust-lang/crates.io-index)", "rand_core 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)", "sha2 0.8.2", - "subtle 2.5.0 (registry+https://github.com/rust-lang/crates.io-index)", + "subtle", "zeroize", ] @@ -7999,36 +7362,10 @@ dependencies = [ "der 0.7.8", "generic-array 0.14.7", "pkcs8", - "subtle 2.5.0 (registry+https://github.com/rust-lang/crates.io-index)", + "subtle", "zeroize", ] -[[package]] -name = "secp" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1507279bb0404bb566f85523e48fcf37a158daa5380577ee0d93f3ef4df39ccc" -dependencies = [ - "base16ct", - "k256", - "once_cell 1.19.0", - "secp256k1 0.28.0", - "subtle 2.5.0 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "secp" -version = "0.2.3" -source = "git+https://github.com/kziemianek/secp.git?branch=sgx#0479a3b12fc204015cdb63c138078fefe7e32341" -dependencies = [ - "base16ct", - "k256", - "once_cell 1.4.0 (git+https://github.com/mesalock-linux/once_cell-sgx?branch=master)", - "secp256k1 0.28.0", - "sgx_tstd", - "subtle 2.5.0 (git+https://github.com/kziemianek/subtle-sgx.git?branch=2.5.0-update)", -] - [[package]] name = "secp256k1" version = "0.24.3" @@ -8444,14 +7781,6 @@ dependencies = [ "digest 0.10.7", ] -[[package]] -name = "sha2_v08_wrapper" -version = "0.1.0" -source = "git+https://github.com/kailai-wang/sha2_v08#c41176becc675e84cd708e8b18ba2cd0c9cf8eb0" -dependencies = [ - "sha2 0.8.2", -] - [[package]] name = "sha3" version = "0.10.8" @@ -9266,14 +8595,6 @@ version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "81cdd64d312baedb58e21336b31bc043b77e01cc99033ce76ef539f78e965ebc" -[[package]] -name = "subtle" -version = "2.5.0" -source = "git+https://github.com/kziemianek/subtle-sgx.git?branch=2.5.0-update#57c424bdb6b98cbf9cfe19879748f20c3525c80e" -dependencies = [ - "sgx_tstd", -] - [[package]] name = "syn" version = "1.0.109" @@ -9412,23 +8733,6 @@ dependencies = [ "once_cell 1.19.0", ] -[[package]] -name = "threadpool" -version = "1.8.0" -source = "git+https://github.com/mesalock-linux/rust-threadpool-sgx?tag=sgx_1.1.3#098d98a85b7e2b02e2bb451a3dec0b027017ff4c" -dependencies = [ - "sgx_tstd", -] - -[[package]] -name = "threadpool" -version = "1.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d050e60b33d41c19108b32cea32164033a9013fe3b46cbd4457559bfbf77afaa" -dependencies = [ - "num_cpus 1.16.0", -] - [[package]] name = "time" version = "0.1.45" diff --git a/tee-worker/Cargo.toml b/tee-worker/Cargo.toml index dc3d1d616a..4ea108a167 100644 --- a/tee-worker/Cargo.toml +++ b/tee-worker/Cargo.toml @@ -69,25 +69,6 @@ members = [ "identity/sidechain/consensus/slots", "identity/sidechain/consensus/common", "identity/sidechain/consensus/aura", - - # bitacross-worker - "bitacross/app-libs/*", - "bitacross/cli", - "bitacross/core/parentchain/block-import-dispatcher", - "bitacross/core/parentchain/block-importer", - "bitacross/core/parentchain/indirect-calls-executor", - "bitacross/core/parentchain/parentchain-crate", - "bitacross/core/direct-rpc-client", - "bitacross/core/direct-rpc-server", - "bitacross/core/offchain-worker-executor", - "bitacross/core-primitives/stf-executor", - "bitacross/core-primitives/top-pool", - "bitacross/core-primitives/top-pool-author", - "bitacross/core-primitives/enclave-api", - "bitacross/core-primitives/enclave-api/ffi", - "bitacross/service", - "bitacross/litentry/core/direct-call", - "bitacross/bitacross/core/*", ] exclude = [ @@ -97,7 +78,6 @@ exclude = [ # enclave-runtime needs to have its own workspace root for patching "identity/enclave-runtime", - "bitacross/enclave-runtime", ] [workspace.dependencies] diff --git a/tee-worker/bitacross/.dockerignore b/tee-worker/bitacross/.dockerignore deleted file mode 100644 index 10a8164af1..0000000000 --- a/tee-worker/bitacross/.dockerignore +++ /dev/null @@ -1,16 +0,0 @@ -# Litentry note: this file is unused -# Please edit the ../.dockerignore directly -.git -.githooks -.github -.idea -ci/ -docker/*yml -docs/ -local-setup/ -scripts/ -target/ -enclave-runtime/target/ -tmp/ -*.Dockerfile -Dockerfile \ No newline at end of file diff --git a/tee-worker/bitacross/.editorconfig b/tee-worker/bitacross/.editorconfig deleted file mode 100644 index de2a30a350..0000000000 --- a/tee-worker/bitacross/.editorconfig +++ /dev/null @@ -1,27 +0,0 @@ -root = true - -[*] -indent_style = tab -indent_size = 4 -tab_width = 4 -end_of_line = lf -charset = utf-8 -trim_trailing_whitespace = true -max_line_length = 100 -insert_final_newline = true - -[*.yml] -indent_style = space -indent_size = 4 -tab_width = 4 -end_of_line = lf - -[*.ts] -indent_style = space -indent_size = 4 -tab_width = 4 -end_of_line = lf - - -[*.toml] -indent_style = space \ No newline at end of file diff --git a/tee-worker/bitacross/.env.dev b/tee-worker/bitacross/.env.dev deleted file mode 100644 index 728ec336c3..0000000000 --- a/tee-worker/bitacross/.env.dev +++ /dev/null @@ -1,11 +0,0 @@ -AliceWSPort=9946 -AlicePort=30336 -BobWSPort=9947 -BobPort=30337 -CollatorWSPort=9944 -CollatorPort=30333 -TrustedWorkerPort=2000 -UntrustedWorkerPort=2001 -MuRaPort=3443 -UntrustedHttpPort=4545 -NODE_ENV=local \ No newline at end of file diff --git a/tee-worker/bitacross/.gitattributes.orig b/tee-worker/bitacross/.gitattributes.orig deleted file mode 100644 index 00c1715114..0000000000 --- a/tee-worker/bitacross/.gitattributes.orig +++ /dev/null @@ -1,18 +0,0 @@ -# TODO: why do we need binary mode for Cargo.lock? -# Cargo.lock linguist-generated=true -diff - -[attr]rust text eol=lf whitespace=tab-in-indent,trailing-space,tabwidth=4 - -* text=auto eol=lf -*.cpp rust -*.h rust -*.rs rust -*.fixed linguist-language=Rust -src/etc/installer/gfx/* binary -*.woff binary -src/vendor/** -text -Cargo.lock -merge linguist-generated=false - -# Older git versions try to fix line endings on images, this prevents it. -*.png binary -*.ico binary diff --git a/tee-worker/bitacross/.githooks/pre-commit b/tee-worker/bitacross/.githooks/pre-commit deleted file mode 100755 index 399188a65d..0000000000 --- a/tee-worker/bitacross/.githooks/pre-commit +++ /dev/null @@ -1,17 +0,0 @@ -#!/bin/bash - -# This pre-commit hook uses cargo fmt to check the code style -# Install it either with `make githooks` or copy the file to .git/hooks - -echo '+cargo fmt -- --check' -cargo fmt -- --check -result=$? - -if [[ ${result} -ne 0 ]] ; then - cat <<\EOF -There are some code style issues, run `cargo fmt` first. -EOF - exit 1 -fi - -exit 0 \ No newline at end of file diff --git a/tee-worker/bitacross/.gitignore b/tee-worker/bitacross/.gitignore deleted file mode 100644 index a14498c6eb..0000000000 --- a/tee-worker/bitacross/.gitignore +++ /dev/null @@ -1,78 +0,0 @@ -# Generated by Cargo -# will have compiled files and executables -**/target/ - -**/__pycache__/ -/log/* -log* -**/tmp/* - -**/node_modules/* - -# These are backup files generated by rustfmt -**/*.rs.bk - -# binaries -bin/*.so -bin/bitacross-* -bin/*.wasm - -# sealed data -bin/*.bin - -# public RSA key -bin/rsa_pubkey.txt -bin/ecc_pubkey.txt - -# VS Code settings -.vscode - -#intelliJ -.idea/ -*.iml - -*.log - -# vim -*.swp - -# keystores -my_keystore/* -my_trusted_keystore/* - -# generated enclave files -service/Enclave_u.* -service/libEnclave_u.* -enclave-runtime/Enclave_t.* -enclave-runtime/enclave.so -lib/libEnclave_u.* -lib/libcompiler-rt-patch.a -lib/libenclave.a - -# certificate, key, spid and generated report for remote attestation -bin/client.crt -bin/client.key -bin/spid.txt -bin/spid_production.txt -bin/key.txt -bin/key_production.txt -bin/attestation_report.json -bin/shards -bin/*.der -bin/enclave-shielding-pubkey.json -bin/sidechain_db -bin/my_trusted_keystore - -# client -cli/my_keystore -cli/my_trusted_keystore -bin/light_client_db.bin.1 - -# generated upstream patch -upstream.patch - -# backup log files -log-backup - -# env files and configs -.env diff --git a/tee-worker/bitacross/DESIGN.md b/tee-worker/bitacross/DESIGN.md deleted file mode 100644 index c49194f57f..0000000000 --- a/tee-worker/bitacross/DESIGN.md +++ /dev/null @@ -1,72 +0,0 @@ -# sidechain startup internal view - -```mermaid -sequenceDiagram - participant integritee_network - participant service - participant slotworker - participant parentsync - participant enclave - participant enclave_rpc - participant provisioningserver - participant isinitializedserver - participant metrics - service ->> enclave: EnclaveBase.get_mrenclave - service ->> provisioningserver: spawn (`--mu-ra-port` | 3443) - activate provisioningserver - service ->> enclave: get_ecc_signing_pubkey - service ->> isinitializedserver: spawn (`--untrusted-http-port | 4545) - activate isinitializedserver - service ->> metrics: spawn (`--metrics-port`| 8787) - activate metrics - service ->> enclave_rpc: spawn (`--trusted-worker-port`| 2000) - activate enclave_rpc - - service ->> enclave: generate_dcap_ra_extrinsic - service ->> integritee_network: send register_sgx_enclave extrinsic - service ->> integritee_network: get ShardStatus - service ->> isinitializedserver: registered_on_parentchain -# schedule teeracle re-registration and updates - loop while blocks to sync - service ->> integritee_network: get_block - service ->> enclave: sync_parentchain(blocks, events, proofs) - end - service ->> slotworker: spawn - loop forever - slotworker ->> enclave: execute_trusted_calls - activate enclave - enclave ->> enclave: propose_sidechain_block - enclave ->> integritee_network: send_extrinsics - deactivate enclave - end - service ->> parentsync: spawn - loop forever - parentsync ->> integritee_network: subscribe new headers - parentsync ->> enclave: sync_parentchain - end - service ->> service: poll worker_for_shard - service ->> isinitializedserver: worker_for_shard_registered - - deactivate enclave_rpc - deactivate metrics - deactivate isinitializedserver - deactivate provisioningserver -``` - -# sidechain lifetime external view - -```mermaid -sequenceDiagram - participant integritee_network - participant validateer_1 - participant validateer_2 - actor alice - - validateer_1 ->> integritee_network: register_sgx_enclave() - - validateer_2 ->> integritee_network: register_sgx_enclave() - - validateer_2 ->> validateer_1: sidechain_fetchBlocksFromPeer() - - validateer_1 ->> validateer_2: sidechain_importBlock() -``` diff --git a/tee-worker/bitacross/Dockerfile b/tee-worker/bitacross/Dockerfile deleted file mode 100644 index 95bd8a9d60..0000000000 --- a/tee-worker/bitacross/Dockerfile +++ /dev/null @@ -1,23 +0,0 @@ -FROM integritee/integritee-dev:0.2.2 -LABEL maintainer="zoltan@integritee.network" - -# By default we warp the service -ARG BINARY_FILE=integritee-service - -COPY bin/enclave.signed.so /usr/local/bin/ -COPY bin/${BINARY_FILE} /usr/local/bin/integritee - -RUN chmod +x /usr/local/bin/integritee - -WORKDIR /usr/local/bin -RUN touch spid.txt key.txt -RUN if [[ "x$BINARY_FILE" != "xintegritee-client" ]] ; then ./integritee init-shard; fi -RUN if [[ "x$BINARY_FILE" != "xintegritee-client" ]] ; then ./integritee shielding-key; fi -RUN if [[ "x$BINARY_FILE" != "xintegritee-client" ]] ; then ./integritee signing-key; fi -RUN if [[ "x$BINARY_FILE" != "xintegritee-client" ]] ; then ./integritee mrenclave > ~/mrenclave.b58; fi - -# checks -RUN ldd /usr/local/bin/integritee && \ - /usr/local/bin/integritee --version - -ENTRYPOINT ["/usr/local/bin/integritee"] diff --git a/tee-worker/bitacross/Jenkinsfile b/tee-worker/bitacross/Jenkinsfile deleted file mode 100755 index 62c9197d68..0000000000 --- a/tee-worker/bitacross/Jenkinsfile +++ /dev/null @@ -1,104 +0,0 @@ -pipeline { - agent { - docker { - image 'integritee/integritee-dev:0.2.2' - args ''' - -u root - --privileged - ''' - } - } - options { - timeout(time: 2, unit: 'HOURS') - buildDiscarder(logRotator(numToKeepStr: '14')) - } - stages { - stage('Init rust') { - steps { - sh 'cargo --version' - sh 'rustup show' - sh 'env' - } - } - stage('Build') { - steps { - sh 'export SGX_SDK=/opt/intel/sgxsdk' - sh 'make' - } - } - stage('Archive build output') { - steps { - archiveArtifacts artifacts: 'bin/enclave.signed.so, bin/integritee-*', caseSensitive: false, fingerprint: true, onlyIfSuccessful: true - } - } - stage('Test') { - steps { - sh 'cd cli && cargo test 2>&1 | tee ${WORKSPACE}/test_client.log' - sh 'cd service && cargo test 2>&1 | tee ${WORKSPACE}/test_server.log' - sh 'cd enclave-runtime && cargo test 2>&1 | tee ${WORKSPACE}/test_enclave.log' - } - } - stage('Clippy') { - steps { - sh 'cargo clean' - catchError(buildResult: 'SUCCESS', stageResult: 'FAILURE') { - sh 'cd cli && cargo clippy 2>&1 | tee ${WORKSPACE}/clippy_client.log' - } - catchError(buildResult: 'SUCCESS', stageResult: 'FAILURE') { - sh 'cd worker && cargo clippy 2>&1 | tee ${WORKSPACE}/clippy_worker.log' - } - catchError(buildResult: 'SUCCESS', stageResult: 'FAILURE') { - sh 'cd enclave && cargo clippy 2>&1 | tee ${WORKSPACE}/clippy_enclave.log' - } - } - } - stage('Formatter') { - steps { - catchError(buildResult: 'SUCCESS', stageResult: 'SUCCESS') { - sh 'cargo fmt -- --check > ${WORKSPACE}/fmt.log' - } - } - } - stage('Results') { - steps { - recordIssues( - aggregatingResults: true, - enabledForFailure: true, - qualityGates: [[threshold: 1, type: 'TOTAL', unstable: true]], - tools: [ - groovyScript( - parserId:'clippy-warnings', - pattern: 'clippy_*.log', - reportEncoding: 'UTF-8' - ), - groovyScript( - parserId:'clippy-errors', - pattern: 'clippy_*.log', - reportEncoding: 'UTF-8' - ) - ] - ) - catchError(buildResult: 'SUCCESS', stageResult: 'SUCCESS') { - sh './ci/check_fmt_log.sh' - } - } - } - stage('Archive logs') { - steps { - archiveArtifacts artifacts: '*.log' - } - } - } - post { - unsuccessful { - emailext ( - subject: "Jenkins Build '${env.JOB_NAME} [${env.BUILD_NUMBER}]' is ${currentBuild.currentResult}", - body: "${env.JOB_NAME} build ${env.BUILD_NUMBER} is ${currentBuild.currentResult}\n\nMore info at: ${env.BUILD_URL}", - to: "${env.RECIPIENTS_SUBSTRATEE}" - ) - } - always { - cleanWs() - } - } -} diff --git a/tee-worker/bitacross/LICENSE b/tee-worker/bitacross/LICENSE deleted file mode 100644 index 261eeb9e9f..0000000000 --- a/tee-worker/bitacross/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/tee-worker/bitacross/Makefile b/tee-worker/bitacross/Makefile deleted file mode 100755 index e3f2901f6c..0000000000 --- a/tee-worker/bitacross/Makefile +++ /dev/null @@ -1,289 +0,0 @@ -# Copyright 2021 Integritee AG and Supercomputing Systems AG -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -######## Update SGX SDK ######## -# use this manually to update sdk -#include UpdateRustSGXSDK.mk - -######## SGX SDK Settings ######## -SGX_SDK ?= /opt/intel/sgxsdk -SGX_MODE ?= HW -SGX_ARCH ?= x64 -SGX_DEBUG ?= 0 -SGX_PRERELEASE ?= 0 -SGX_PRODUCTION ?= 0 - -######## Worker Feature Settings ######## -# Set offchain-worker as default feature mode -WORKER_MODE ?= offchain-worker -RA_METHOD ?= dcap - -SKIP_WASM_BUILD = 1 -# include the build settings from rust-sgx-sdk -include rust-sgx-sdk/buildenv.mk - -ifeq ($(shell getconf LONG_BIT), 32) - SGX_ARCH := x86 -else ifeq ($(findstring -m32, $(CXXFLAGS)), -m32) - SGX_ARCH := x86 -endif - -ifeq ($(SGX_ARCH), x86) - SGX_COMMON_CFLAGS := -m32 - SGX_LIBRARY_PATH := $(SGX_SDK)/lib - SGX_ENCLAVE_SIGNER := $(SGX_SDK)/bin/x86/sgx_sign - SGX_EDGER8R := $(SGX_SDK)/bin/x86/sgx_edger8r -else - SGX_COMMON_CFLAGS := -m64 - SGX_LIBRARY_PATH := $(SGX_SDK)/lib64 - SGX_ENCLAVE_SIGNER := $(SGX_SDK)/bin/x64/sgx_sign - SGX_EDGER8R := $(SGX_SDK)/bin/x64/sgx_edger8r -endif - -ifeq ($(SGX_DEBUG), 1) -ifeq ($(SGX_PRERELEASE), 1) -$(error Cannot set SGX_DEBUG and SGX_PRERELEASE at the same time!!) -endif -ifeq ($(SGX_PRODUCTION), 1) -$(error Cannot set SGX_DEBUG and SGX_PRODUCTION at the same time!!) -endif -endif - -ifeq ($(SGX_DEBUG), 1) - SGX_COMMON_CFLAGS += -O0 -g -ggdb - OUTPUT_PATH := debug - CARGO_TARGET := -else - SGX_COMMON_CFLAGS += -O2 - OUTPUT_PATH := release - CARGO_TARGET := --release -endif - -SGX_COMMON_CFLAGS += -fstack-protector - -ifeq ($(SGX_PRODUCTION), 1) - SGX_ENCLAVE_MODE = "Production Mode" - SGX_ENCLAVE_CONFIG = "enclave-runtime/Enclave.config.production.xml" - SGX_SIGN_KEY = $(SGX_COMMERCIAL_KEY) - SGX_SIGN_PASSFILE = $(SGX_PASSFILE) - WORKER_FEATURES := --features=link-binary,$(WORKER_MODE),$(RA_METHOD),$(WORKER_FEATURES),$(ADDITIONAL_FEATURES) -else - SGX_ENCLAVE_MODE = "Development Mode" - SGX_ENCLAVE_CONFIG = "enclave-runtime/Enclave.config.xml" - SGX_SIGN_KEY = "enclave-runtime/Enclave_private.pem" - SGX_SIGN_PASSFILE = "" - WORKER_FEATURES := --features=default,development,link-binary,$(WORKER_MODE),$(RA_METHOD),$(WORKER_FEATURES),$(ADDITIONAL_FEATURES) - ADDITIONAL_FEATURES := development -endif - -CLIENT_FEATURES = --features=$(WORKER_MODE),$(RA_METHOD),$(ADDITIONAL_FEATURES) - -# check if running on Jenkins -ifdef BUILD_ID - CARGO_TARGET += --verbose -endif - -######## CUSTOM settings ######## -CUSTOM_LIBRARY_PATH := ./lib -CUSTOM_BIN_PATH := ./bin -CUSTOM_EDL_PATH := ./rust-sgx-sdk/edl -CUSTOM_COMMON_PATH := ./rust-sgx-sdk/common - -######## EDL settings ######## -Enclave_EDL_Files := enclave-runtime/Enclave_t.c enclave-runtime/Enclave_t.h service/Enclave_u.c service/Enclave_u.h - -######## bitacross-worker settings ######## -SRC_Files := $(shell find . -type f -name '*.rs') $(shell find . -type f -name 'Cargo.toml') -Worker_Rust_Flags := $(CARGO_TARGET) $(WORKER_FEATURES) -Worker_Include_Paths := -I ./service -I./include -I$(SGX_SDK)/include -I$(CUSTOM_EDL_PATH) -Worker_C_Flags := $(SGX_COMMON_CFLAGS) -fPIC -Wno-attributes $(Worker_Include_Paths) - -Worker_Rust_Path := ../target/$(OUTPUT_PATH) -Worker_Enclave_u_Object :=service/libEnclave_u.a -Worker_Name := bin/app - -######## bitacross-cli settings ######## -Client_Rust_Flags := $(CARGO_TARGET) $(CLIENT_FEATURES) - -Client_Rust_Path := ../target/$(OUTPUT_PATH) -Client_Path := bin -Client_Binary := bitacross-cli -Client_Name := $(Client_Path)/$(Client_Binary) - -######## Enclave settings ######## -ifneq ($(SGX_MODE), HW) - Trts_Library_Name := sgx_trts_sim - Service_Library_Name := sgx_tservice_sim -else - Trts_Library_Name := sgx_trts - Service_Library_Name := sgx_tservice -endif -Crypto_Library_Name := sgx_tcrypto -KeyExchange_Library_Name := sgx_tkey_exchange -ProtectedFs_Library_Name := sgx_tprotected_fs - -RustEnclave_C_Files := $(wildcard ./enclave-runtime/*.c) -RustEnclave_C_Objects := $(RustEnclave_C_Files:.c=.o) -RustEnclave_Include_Paths := -I$(CUSTOM_COMMON_PATH)/inc -I$(CUSTOM_EDL_PATH) -I$(SGX_SDK)/include -I$(SGX_SDK)/include/tlibc -I$(SGX_SDK)/include/stlport -I$(SGX_SDK)/include/epid -I ./enclave-runtime -I./include - -RustEnclave_Link_Libs := -L$(CUSTOM_LIBRARY_PATH) -lenclave -RustEnclave_Compile_Flags := $(SGX_COMMON_CFLAGS) $(ENCLAVE_CFLAGS) $(RustEnclave_Include_Paths) -RustEnclave_Link_Flags := -Wl,--no-undefined -nostdlib -nodefaultlibs -nostartfiles -L$(SGX_LIBRARY_PATH) \ - -Wl,--whole-archive -l$(Trts_Library_Name) -Wl,--no-whole-archive \ - -Wl,--start-group -lsgx_tstdc -lsgx_tcxx -lsgx_dcap_tvl -l$(Crypto_Library_Name) -l$(Service_Library_Name) -l$(ProtectedFs_Library_Name) $(RustEnclave_Link_Libs) -Wl,--end-group \ - -Wl,--version-script=enclave-runtime/Enclave.lds \ - $(ENCLAVE_LDFLAGS) - -RustEnclave_Name := enclave-runtime/enclave.so -Signed_RustEnclave_Name := bin/enclave.signed.so - -######## Targets ######## -.PHONY: all -all: $(Worker_Name) $(Client_Name) $(Signed_RustEnclave_Name) -service: $(Worker_Name) -client: $(Client_Name) -githooks: .git/hooks/pre-commit - -######## EDL objects ######## -$(Enclave_EDL_Files): $(SGX_EDGER8R) enclave-runtime/Enclave.edl - $(SGX_EDGER8R) --trusted enclave-runtime/Enclave.edl --search-path $(SGX_SDK)/include --search-path $(CUSTOM_EDL_PATH) --trusted-dir enclave-runtime - $(SGX_EDGER8R) --untrusted enclave-runtime/Enclave.edl --search-path $(SGX_SDK)/include --search-path $(CUSTOM_EDL_PATH) --untrusted-dir service - @echo "GEN => $(Enclave_EDL_Files)" - -######## bitacross-worker objects ######## -service/Enclave_u.o: $(Enclave_EDL_Files) - @$(CC) $(Worker_C_Flags) -c service/Enclave_u.c -o $@ - @echo "CC <= $<" - -$(Worker_Enclave_u_Object): service/Enclave_u.o - $(AR) rcsD $@ $^ - cp $(Worker_Enclave_u_Object) ./lib - -$(Worker_Name): $(Worker_Enclave_u_Object) $(SRC_Files) - @echo - @echo "Building the bitacross-worker: $(Worker_Rust_Flags)" - @SGX_SDK=$(SGX_SDK) SGX_MODE=$(SGX_MODE) cargo build -p bitacross-worker $(Worker_Rust_Flags) - @echo "Cargo => $@" - cp $(Worker_Rust_Path)/bitacross-worker ./bin - -######## bitacross-client objects ######## -$(Client_Name): $(SRC_Files) - @echo - @echo "Building the bitacross-cli $(Client_Rust_Flags)" - @cargo build -p bitacross-cli $(Client_Rust_Flags) - @echo "Cargo => $@" - cp $(Client_Rust_Path)/$(Client_Binary) ./bin - -######## Enclave objects ######## -enclave-runtime/Enclave_t.o: $(Enclave_EDL_Files) - @$(CC) $(RustEnclave_Compile_Flags) -c enclave-runtime/Enclave_t.c -o $@ - @echo "CC <= $<" - -$(RustEnclave_Name): enclave enclave-runtime/Enclave_t.o - @echo Compiling $(RustEnclave_Name) - @$(CXX) enclave-runtime/Enclave_t.o -o $@ $(RustEnclave_Link_Flags) - @echo "LINK => $@" - -$(Signed_RustEnclave_Name): $(RustEnclave_Name) - @echo - @echo "Signing the enclave: $(SGX_ENCLAVE_MODE)" - @echo "SGX_ENCLAVE_SIGNER: $(SGX_ENCLAVE_SIGNER)" - @echo "RustEnclave_Name: $(RustEnclave_Name)" - @echo "SGX_ENCLAVE_CONFIG: $(SGX_ENCLAVE_CONFIG)" - @echo "SGX_SIGN_PASSFILE: $(SGX_SIGN_PASSFILE)" - @echo "SGX_SIGN_KEY: $(SGX_SIGN_KEY)" - - -# TODO: figure out if/how to use the passphrase file in PROD -ifeq ($(SGX_PRODUCTION), 1) - $(SGX_ENCLAVE_SIGNER) gendata -enclave $(RustEnclave_Name) -out enclave_sig.dat -config $(SGX_ENCLAVE_CONFIG) - openssl rsa -pubout -in $(SGX_SIGN_KEY) -out intel_sgx.pub - openssl dgst -sha256 -sign $(SGX_SIGN_KEY) -out signature.dat enclave_sig.dat - openssl dgst -sha256 -verify intel_sgx.pub -signature signature.dat enclave_sig.dat - $(SGX_ENCLAVE_SIGNER) catsig -enclave $(RustEnclave_Name) -config $(SGX_ENCLAVE_CONFIG) -out $@ -key intel_sgx.pub -sig signature.dat -unsigned enclave_sig.dat -else - $(SGX_ENCLAVE_SIGNER) sign -key $(SGX_SIGN_KEY) -enclave $(RustEnclave_Name) -out $@ -config $(SGX_ENCLAVE_CONFIG) -endif - @echo "SIGN => $@" - @echo - @echo "Enclave is in $(SGX_ENCLAVE_MODE)" - -.PHONY: enclave -enclave: - @echo - @echo "Building the enclave" - $(MAKE) -C ./enclave-runtime/ RA_METHOD=$(RA_METHOD) WORKER_DEV=$(WORKER_DEV) - -.git/hooks/pre-commit: .githooks/pre-commit - @echo "Installing git hooks" - cp .githooks/pre-commit .git/hooks - -.PHONY: clean -clean: - @echo "Removing the compiled files" - @rm -f $(Client_Name) $(Worker_Name) $(RustEnclave_Name) $(Signed_RustEnclave_Name) \ - enclave-runtime/*_t.* \ - service/*_u.* \ - lib/*.a \ - bin/*.bin - @echo "cargo clean in enclave directory" - @cd enclave-runtime && cargo clean - @echo "cargo clean in root directory" - @cargo clean - -.PHONY: fmt -fmt: - @echo "Cargo format all ..." - @cargo fmt --all - @cd enclave-runtime && cargo fmt --all - -.PHONY: pin-sgx -pin-sgx: - @echo "Pin sgx dependencies to 594806f827b57e6c4c9a0611fa4cbf2d83aabd2e" - @cd enclave-runtime && cargo update -p sgx_tstd --precise 594806f827b57e6c4c9a0611fa4cbf2d83aabd2e - @cargo update -p sgx_tstd --precise 594806f827b57e6c4c9a0611fa4cbf2d83aabd2e - -mrenclave: - @$(SGX_ENCLAVE_SIGNER) dump -enclave ./bin/enclave.signed.so -dumpfile df.out && ./extract_identity < df.out && rm df.out - -mrsigner: - @$(SGX_ENCLAVE_SIGNER) dump -enclave ./bin/enclave.signed.so -dumpfile df.out && ./extract_identity --mrsigner < df.out && rm df.out - -.PHONY: identity -identity: mrenclave mrsigner - -.PHONY: release-pkg -release-pkg: - @./scripts/litentry/release/generate_release_pkg.sh - -.PHONY: help -help: - @echo "Available targets" - @echo " all - builds all targets (default)" - @echo " service - builds the bitacross-worker" - @echo " client - builds the bitacross-cli" - @echo " githooks - installs the git hooks (copy .githooks/pre-commit to .git/hooks)" - @echo "" - @echo " clean - cleanup" - @echo "" - @echo "Compilation options. Prepend them to the make command. Example: 'SGX_MODE=SW make'" - @echo " SGX_MODE" - @echo " HW (default): Use SGX hardware" - @echo " SW: Simulation mode" - @echo " SGX_DEBUG" - @echo " 0 (default): No debug information, optimization level 2, cargo release build" - @echo " 1: Debug information, optimization level 0, cargo debug build" - @echo " SGX_PRODUCTION" - @echo " 0 (default): Using SGX development environment" - @echo " 1: Using SGX production environment" diff --git a/tee-worker/bitacross/README.md b/tee-worker/bitacross/README.md deleted file mode 100755 index e614d4be86..0000000000 --- a/tee-worker/bitacross/README.md +++ /dev/null @@ -1,209 +0,0 @@ -# BitAcross worker - -This repository contains code for BitAcross offchain worker. The main responsibility of the worker is to -store custodian wallets and sign transactions submitted by relayers. - -## Wallets - -Supported wallets: -* ethereum (ecdsa based on secp256k1) -* bitcoin (schnorr based on secp256k1) - -Wallets (private keys) are generated during the initialization (on first startup) and sealed to encrypted file using Intel Protected File System while public keys are published on parachain's bitacross pallet in compressed SEC1-encoded format. - - -## Transaction signing - -Signing requests are processed by a dedicated JSON-RPC `bitacross_submitRequest` method and results in raw signature bytes. Only requests signed by registered relayers are permitted. - -Typescript code related to the RPC integration and can be found in [tee-worker's ts-tests](https://github.com/litentry/litentry-parachain/blob/a6b78ed68396280655271f9cd30e17535d54da81/tee-worker/ts-tests/integration-tests/common/di-utils.ts). - -Rust code used in CLI module can also be used as a reference and can be found [here](https://github.com/litentry/litentry-parachain/blob/a6b78ed68396280655271f9cd30e17535d54da81/bitacross-worker/cli/src/trusted_base_cli/commands/bitacross/utils.rs). - - -## Local launch - -```bash -make SGX_MODE=SW -cd ../.. && local-setup/launch.py -w bitacross -wn 3 -p standalone -``` - -### Step by step guide for request preparing/sending and response handling. - -1. Prepare `DirectCall`, for example `SignBitcoin` variant which will reflect bitcoin's transaction signing request. Generate 256-bit AES-GCM as request enc/dec key. The first parameter is relayer identity, second generated aes key and third is transaction payload to sign. - -```rust -pub enum DirectCall { - SignBitcoin(Identity, RequestAesKey, Vec), - SignEthereum(Identity, RequestAesKey, Vec), -} -``` - -2. Prepare `DirectCallSigned`. Scale encode created direct call from step 1, append scale encoded mrenclave and shard identifier (use mrenclave) to it, do a Blake2 256-bit hash of it and sign it using relayer's private key, then prepare struct containing direct call and signature. Mrenclave can be obtained from parachain's teebag pallet enclave registry storage. - -```Rust -#[derive(Encode, Decode, Clone, Debug, PartialEq, Eq)] -pub struct DirectCallSigned { - pub call: DirectCall, - pub signature: LitentryMultiSignature, -} -``` - -3. Prepare `AesRequest`. Fill payload property with aes encrypted scale encoded `DirectCallSigned` prepared in previous step. Get worker's shielding key and use it to encrypt aes key from step 1 and fill `key` property with it. Fill shard identifier (use mrenclave again). Shielding key can be obtained from parachain's teebag pallet enclave registry storage. - -```rust -pub struct AesRequest { - pub shard: ShardIdentifier, - pub key: Vec, - pub payload: AesOutput, -} -``` - -4. Prepare `RpcRequest`. Scale encode `AesRequest` prepared in previous step, turn the bytes into hex representation and put in `params` vec. Generate locally unique `id`. Use following consts for `jsonrpc` and `method`: `"2.0"`, `bitacross_submitRequest` - -```rust -pub struct RpcRequest { - pub jsonrpc: String, - pub method: String, - pub params: Vec, - pub id: Id, -} -``` - -5. Send prepared request to worker's jsonrpc endpoint, in the following example `websocat` is used to send request to locally run bitacross worker. - -```bash -echo '{"jsonrpc":"2.0","method":"bitacross_submitRequest","params":["0x6565c4529cd2af40f89e5d526c6e890019a2fd33cfdc9ee3cd14a0bf1427a61601065c22cde40abe4ad0550a4beba5d05a55380117a57824a57c5949a472fb0639d1ebb1baff0f5453e222418844044ed75352f9a76b4f3fd57f8db4deabf4074eb552784b32c1a881ac27d143148e06a3607455ebafb7dd3ab1669013502bfd7b840d6698363015f55fede5275dfe7d05827315301772e4b75bf745f74b71c443b97b7d22010d54b89fcc1105cbfc72a58dfbd4c10e34ef6019dad859abafdb4f82118f5f339255cb5d2400243bc2e982b4c60341572b6253e0815ed90de74b64145aef8d8304a576ba11c73421b9c86a053619908c475be5d223acc942460afb7e248836f58d2e639d3e32365bbc7ba9fe838b3329db6432fce3427569523f513e7cc82098db4ccaf024a286ad94e6be775ba1f9e918f0867e20a8dbb409232ba297878eff52740e705f59dab2a1c5827d1f8bf7adfa7cdf9e345c16fda757016337f398201af14c820782dac82bc9c5f8df93c917cba29f89e5a1e323dafcf2465e258f1d6dcf9808e5202e6fa3766433981f619c580b831c0d49eed759a0ca1555021c688b72490ffd3f4391c60c04ba904d83aa9497cce62eb6d0e55124692c5124fabfabd70ab366ba81d152f2299ba99021a3705754d64d2b9455229d6ecd730a120a1003abe432a060e40931ad9eb3199cbb09a6b2c84af35735b51628d80210369c0f902905f7e7902d6787673691f2e923b6bc001cfa56f3568e95a95f1f084cd69e658e42c96e317cebc17d54de13f08a0fb007008777e7510d0aa8d124271afe"],"id":1}' | websocat -n1 -k -B 99999999 wss://localhost:2000 -{"jsonrpc":"2.0","result":"0x7d014101d9197274039df1280452819ede02d0867aa57185251d19c9e2c74bd22d1f3b8e1db031b068e3ee7229631a804c1d03e2d9af7055851ac9609dae5e8c7c8dccf4961b31a5cc98bfa356fa262a7376525300a2c03d6f2b59e28578fdcee00000","id":1} -``` - -6. Get result from response `result` field. It's a hex representation of scale encoded `RpcReturnValue`. In case of success, the signature can be obtained from `value` property (it's aes encrypted). - -Types definitions: - -```rust -pub type RequestAesKey = [u8; 32]; - -#[derive( -Encode, Decode, Clone, Debug, PartialEq, Eq, TypeInfo, MaxEncodedLen, EnumIter, Ord, PartialOrd, -)] -pub enum Identity { - // web2 - #[codec(index = 0)] - Twitter(IdentityString), - #[codec(index = 1)] - Discord(IdentityString), - #[codec(index = 2)] - Github(IdentityString), - - // web3 - #[codec(index = 3)] - Substrate(Address32), - #[codec(index = 4)] - Evm(Address20), - // bitcoin addresses are derived (one-way hash) from the pubkey - // by using `Address33` as the Identity handle, it requires that pubkey - // is retrievable by the wallet API when verifying the bitcoin account. - // e.g. unisat-wallet: https://docs.unisat.io/dev/unisat-developer-service/unisat-wallet#getpublickey - #[codec(index = 5)] - Bitcoin(Address33), -} - -pub enum LitentryMultiSignature { - /// An Ed25519 signature. - #[codec(index = 0)] - Ed25519(ed25519::Signature), - /// An Sr25519 signature. - #[codec(index = 1)] - Sr25519(sr25519::Signature), - /// An ECDSA/SECP256k1 signature. - #[codec(index = 2)] - Ecdsa(ecdsa::Signature), - /// An ECDSA/keccak256 signature. An Ethereum signature. hash message with keccak256 - #[codec(index = 3)] - Ethereum(EthereumSignature), - /// Same as above, but the payload bytes are prepended with a readable prefix and `0x` - #[codec(index = 4)] - EthereumPrettified(EthereumSignature), - /// Bitcoin signed message, a hex-encoded string of original &[u8] message, without `0x` prefix - #[codec(index = 5)] - Bitcoin(BitcoinSignature), - /// Same as above, but the payload bytes are prepended with a readable prefix and `0x` - #[codec(index = 6)] - BitcoinPrettified(BitcoinSignature), -} - -#[derive(Encode, Decode, MaxEncodedLen, TypeInfo, PartialEq, Eq, Clone, Debug)] -pub struct EthereumSignature(pub [u8; 65]); - -#[derive(Encode, Decode, MaxEncodedLen, TypeInfo, PartialEq, Eq, Clone, Debug)] -pub struct BitcoinSignature(pub [u8; 65]); - -#[derive( -Encode, Decode, Copy, Clone, Default, PartialEq, Eq, TypeInfo, MaxEncodedLen, Ord, PartialOrd, -)] -pub struct Address20([u8; 20]); - -#[derive( -Encode, Decode, Copy, Clone, Default, PartialEq, Eq, TypeInfo, MaxEncodedLen, Ord, PartialOrd, -)] -pub struct Address32([u8; 32]); - -#[derive(Encode, Decode, Copy, Clone, PartialEq, Eq, TypeInfo, MaxEncodedLen, PartialOrd, Ord)] -pub struct Address33([u8; 33]); - -#[derive(Debug, Default, Clone, Eq, PartialEq, Encode, Decode)] -pub struct AesOutput { - pub ciphertext: Vec, - pub aad: Vec, - pub nonce: RequestAesKeyNonce, // IV -} - -#[derive(Encode, Decode, Debug, Eq, PartialEq)] -pub struct RpcReturnValue { - pub value: Vec, - pub do_watch: bool, - pub status: DirectRequestStatus, -} - -#[derive(Debug, Clone, PartialEq, Encode, Decode, Eq)] -pub enum DirectRequestStatus { - /// Direct request was successfully executed - #[codec(index = 0)] - Ok, - /// Trusted Call Status - /// Litentry: embed the top hash here - TODO - use generic type? - #[codec(index = 1)] - TrustedOperationStatus(TrustedOperationStatus, H256), - /// Direct request could not be executed - #[codec(index = 2)] - Error, - #[codec(index = 3)] - Processing -} -``` - -### Using CLI - -There are two commands related to transaction signing: - -* request-direct-call-sign-bitcoin -* request-direct-call-sign-ethereum - -They take single argument representing raw payload bytes to sign. - -#### Example usage - -```bash -./bitacross-cli trusted -m 7ppBUcnjGir4szRHCG59p2dTnbtRwKRbLZPpR32ACjbK request-direct-call-sign-bitcoin 00 -``` - -### Obtaining data from parachain's teebag pallet - -Mrencalve, worker's url and public shielding key can be obtained during the runtime from parachain's teebag pallet registry. - -The following gif ilustrates how it can be done manually: - -![demo](./assets/teebag_registry.gif) - -These values can also be obtained programmatically using substrate's `state_getStorage` RPC method. See [this](https://docs.substrate.io/build/remote-procedure-calls/) documentation for more information. \ No newline at end of file diff --git a/tee-worker/bitacross/UpdateRustSGXSDK.mk b/tee-worker/bitacross/UpdateRustSGXSDK.mk deleted file mode 100755 index 88c95d5dc6..0000000000 --- a/tee-worker/bitacross/UpdateRustSGXSDK.mk +++ /dev/null @@ -1,33 +0,0 @@ -# helper script to update the files in rust-sgx-sdk to the lastest version - -GIT = git -CP = cp - -REPO = https://github.com/apache/incubator-teaclave-sgx-sdk -SDK_PATH_GIT = rust-sgx-sdk-github -SDK_PATH = rust-sgx-sdk -VERSION_FILE = rust-sgx-sdk/version -LOCAL_VERSION = $(shell cat $(VERSION_FILE)) -COMMAND = git ls-remote $(REPO) HEAD | awk '{ print $$1 }' -REMOTE_VERSION = $(shell $(COMMAND)) -# or specify the exact hash if you need a non-default branch / tag / commit etc. -#REMOTE_VERSION = 9c1bbd52f188f600a212b57c916124245da1b7fd - -# update the SDK files -all: updatesdk - -updatesdk: -# check for already updated version -ifneq ('$(LOCAL_VERSION)','$(REMOTE_VERSION)') - @echo Local version = $(LOCAL_VERSION) - @echo Remote version = $(REMOTE_VERSION) - - @rm -rf $(SDK_PATH_GIT) - @$(GIT) clone $(REPO) $(SDK_PATH_GIT) - @$(GIT) -C $(SDK_PATH_GIT) checkout $(REMOTE_VERSION) - rsync -a $(SDK_PATH_GIT)/edl $(SDK_PATH) - rsync -a $(SDK_PATH_GIT)/common $(SDK_PATH) - rm -rf $(SDK_PATH_GIT) - @echo $(REMOTE_VERSION) > $(VERSION_FILE) - -endif diff --git a/tee-worker/bitacross/app-libs/parentchain-interface/Cargo.toml b/tee-worker/bitacross/app-libs/parentchain-interface/Cargo.toml deleted file mode 100644 index d4b0ccea49..0000000000 --- a/tee-worker/bitacross/app-libs/parentchain-interface/Cargo.toml +++ /dev/null @@ -1,77 +0,0 @@ -[package] -name = "bc-ita-parentchain-interface" -version = "0.1.0" -authors = ["Integritee AG "] -edition = "2021" - -[dependencies] -sgx_tstd = { workspace = true, optional = true } - -ita-sgx-runtime = { package = "bc-ita-sgx-runtime", path = "../sgx-runtime", default-features = false } -ita-stf = { package = "bc-ita-stf", path = "../stf", default-features = false } -itc-parentchain-indirect-calls-executor = { package = "bc-itc-parentchain-indirect-calls-executor", path = "../../core/parentchain/indirect-calls-executor", default-features = false } -itp-api-client-types = { workspace = true } -itp-node-api = { workspace = true } -itp-stf-primitives = { workspace = true } -itp-types = { workspace = true } - -codec = { package = "parity-scale-codec", workspace = true } -log = { workspace = true } - -sp-core = { workspace = true, features = ["full_crypto"] } -sp-runtime = { workspace = true } -substrate-api-client = { workspace = true, optional = true } - -# litentry -bc-enclave-registry = { path = "../../bitacross/core/bc-enclave-registry", default-features = false } -bc-relayer-registry = { path = "../../bitacross/core/bc-relayer-registry", default-features = false } -bc-signer-registry = { path = "../../bitacross/core/bc-signer-registry", default-features = false } -litentry-primitives = { workspace = true } -sp-std = { workspace = true } - -[dev-dependencies] -env_logger = { workspace = true } -itp-node-api = { workspace = true, features = ["std", "mocks"] } -itp-sgx-crypto = { workspace = true, features = ["std", "mocks"] } -itp-test = { workspace = true, features = ["std"] } -itp-stf-executor = { package = "bc-itp-stf-executor", path = "../../core-primitives/stf-executor", features = ["std", "mocks"] } -itp-top-pool-author = { package = "bc-itp-top-pool-author", path = "../../core-primitives/top-pool-author", features = ["std", "mocks"] } -itc-parentchain-test = { workspace = true, features = ["std"] } - -[features] -default = ["std"] -std = [ - "codec/std", - "ita-sgx-runtime/std", - "ita-stf/std", - "itc-parentchain-indirect-calls-executor/std", - "itp-api-client-types/std", - "itp-node-api/std", - "itp-sgx-crypto/std", - "itp-stf-executor/std", - "itp-stf-primitives/std", - "itp-top-pool-author/std", - "itp-types/std", - "log/std", - "sp-core/std", - "sp-runtime/std", - "substrate-api-client", - "litentry-primitives/std", - "sp-std/std", - "bc-enclave-registry/std", - "bc-relayer-registry/std", - "bc-signer-registry/std", -] -sgx = [ - "sgx_tstd", - "ita-stf/sgx", - "itc-parentchain-indirect-calls-executor/sgx", - "itp-node-api/sgx", - "itp-sgx-crypto/sgx", - "itp-stf-executor/sgx", - "itp-top-pool-author/sgx", - "litentry-primitives/sgx", - "bc-enclave-registry/sgx", - "bc-relayer-registry/sgx", - "bc-signer-registry/sgx", -] diff --git a/tee-worker/bitacross/app-libs/parentchain-interface/src/event_subscriber.rs b/tee-worker/bitacross/app-libs/parentchain-interface/src/event_subscriber.rs deleted file mode 100644 index 237a678f06..0000000000 --- a/tee-worker/bitacross/app-libs/parentchain-interface/src/event_subscriber.rs +++ /dev/null @@ -1,60 +0,0 @@ -/* - Copyright 2021 Integritee AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use itp_api_client_types::ParentchainApi; -use itp_types::parentchain::{events::BalanceTransfer, ParentchainId}; -use substrate_api_client::SubscribeEvents; - -pub fn subscribe_to_parentchain_events(api: &ParentchainApi, parentchain_id: ParentchainId) { - println!("[L1Event:{}] Subscribing to selected events", parentchain_id); - let mut subscription = api.subscribe_events().unwrap(); - loop { - let events = subscription.next_events_from_metadata().unwrap().unwrap(); - - for event in events.iter() { - let event = event.unwrap(); - match event.pallet_name() { - "System" => continue, - "ParaInclusion" => continue, - "MessageQueue" => continue, - "TransactionPayment" => continue, - "Treasury" => continue, - "Balances" => match event.variant_name() { - "Deposit" => continue, - "Withdraw" => continue, - "Transfer" => - if let Ok(Some(ev)) = event.as_event::() { - println!("[L1Event:{}] {:?}", parentchain_id, ev); - }, - _ => println!( - "[L1Event:{}] {}::{}", - parentchain_id, - event.pallet_name(), - event.variant_name() - ), - }, - // TODO(Litentry): add important teebag events? - _ => println!( - "[L1Event:{}] {}::{}", - parentchain_id, - event.pallet_name(), - event.variant_name() - ), - } - } - } -} diff --git a/tee-worker/bitacross/app-libs/parentchain-interface/src/integritee/event_filter.rs b/tee-worker/bitacross/app-libs/parentchain-interface/src/integritee/event_filter.rs deleted file mode 100644 index b7ceeb561a..0000000000 --- a/tee-worker/bitacross/app-libs/parentchain-interface/src/integritee/event_filter.rs +++ /dev/null @@ -1,124 +0,0 @@ -/* - Copyright 2021 Integritee AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ -//! Various way to filter Parentchain events - -use itc_parentchain_indirect_calls_executor::event_filter::ToEvents; -use itp_api_client_types::Events; -use itp_node_api::api_client::StaticEvent; - -use itp_types::{ - parentchain::{events::*, FilterEvents}, - H256, -}; -use std::vec::Vec; - -#[derive(Clone)] -pub struct FilterableEvents(pub Events); - -impl FilterableEvents { - fn filter(&self) -> Result, E> { - Ok(self - .to_events() - .iter() - .flatten() - .filter_map(|ev| match ev.as_event::() { - Ok(maybe_event) => maybe_event, - Err(e) => { - log::error!("Could not decode event: {:?}", e); - None - }, - }) - .collect()) - } -} - -// todo: improve: https://github.com/integritee-network/worker/pull/1378#discussion_r1393933766 -impl ToEvents> for FilterableEvents { - fn to_events(&self) -> &Events { - &self.0 - } -} - -impl From> for FilterableEvents { - fn from(ev: Events) -> Self { - Self(ev) - } -} - -impl FilterEvents for FilterableEvents { - type Error = itc_parentchain_indirect_calls_executor::Error; - - fn get_link_identity_events(&self) -> Result, Self::Error> { - self.filter() - } - - fn get_vc_requested_events(&self) -> Result, Self::Error> { - self.filter() - } - - fn get_deactivate_identity_events( - &self, - ) -> Result, Self::Error> { - self.filter() - } - - fn get_activate_identity_events(&self) -> Result, Self::Error> { - self.filter() - } - - fn get_enclave_unauthorized_events(&self) -> Result, Self::Error> { - self.filter() - } - - fn get_opaque_task_posted_events(&self) -> Result, Self::Error> { - self.filter() - } - - fn get_assertion_created_events(&self) -> Result, Self::Error> { - self.filter() - } - - fn get_parentchain_block_proccessed_events( - &self, - ) -> Result, Self::Error> { - self.filter() - } - - fn get_relayer_added_events(&self) -> Result, Self::Error> { - self.filter() - } - - fn get_relayers_removed_events(&self) -> Result, Self::Error> { - self.filter() - } - - fn get_enclave_added_events(&self) -> Result, Self::Error> { - self.filter() - } - - fn get_enclave_removed_events(&self) -> Result, Self::Error> { - self.filter() - } - - fn get_btc_wallet_generated_events(&self) -> Result, Self::Error> { - self.filter() - } - - fn get_account_store_updated_events(&self) -> Result, Self::Error> { - self.filter() - } -} diff --git a/tee-worker/bitacross/app-libs/parentchain-interface/src/integritee/event_handler.rs b/tee-worker/bitacross/app-libs/parentchain-interface/src/integritee/event_handler.rs deleted file mode 100644 index e26c697c32..0000000000 --- a/tee-worker/bitacross/app-libs/parentchain-interface/src/integritee/event_handler.rs +++ /dev/null @@ -1,234 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -pub use ita_sgx_runtime::{Balance, Index}; - -use bc_enclave_registry::{EnclaveRegistry, EnclaveRegistryUpdater}; -use bc_relayer_registry::{RelayerRegistry, RelayerRegistryUpdater}; -use bc_signer_registry::{SignerRegistry, SignerRegistryUpdater}; -use codec::Encode; -use core::str::from_utf8; -use ita_stf::TrustedCallSigned; -use itc_parentchain_indirect_calls_executor::error::Error; -use itp_stf_primitives::traits::IndirectExecutor; -use itp_types::{ - parentchain::{FilterEvents, HandleParentchainEvents, ParentchainEventProcessingError}, - WorkerType, -}; -use litentry_primitives::{Address32, Identity}; -use log::*; -use sp_core::{blake2_256, H256}; -use sp_runtime::traits::{Block as ParentchainBlock, Header as ParentchainHeader}; -use sp_std::vec::Vec; -use std::string::ToString; - -pub struct ParentchainEventHandler {} - -impl ParentchainEventHandler { - fn add_relayer(relayer_registry: &RelayerRegistry, account: Identity) -> Result<(), Error> { - info!("Adding Relayer Account to Registry: {:?}", account); - relayer_registry.update(account).map_err(|e| { - error!("Error adding relayer: {:?}", e); - Error::Other("Error adding relayer".into()) - })?; - - Ok(()) - } - - fn remove_relayer(relayer_registry: &RelayerRegistry, account: Identity) -> Result<(), Error> { - info!("Remove Relayer Account from Registry: {:?}", account); - relayer_registry.remove(account).map_err(|e| { - error!("Error removing relayer: {:?}", e); - Error::Other("Error removing relayer".into()) - })?; - - Ok(()) - } - - fn add_enclave( - enclave_registry: &EnclaveRegistry, - account_id: Address32, - url: Vec, - worker_type: WorkerType, - ) -> Result<(), Error> { - info!("Adding Enclave Account to Registry: {:?}", account_id); - if worker_type != WorkerType::BitAcross { - warn!("Ignore AddEnclave due to wrong worker_type"); - return Ok(()) - } - - let url = from_utf8(&url) - .map_err(|_| Error::Other("Invalid enclave URL".into()))? - .to_string(); - enclave_registry.update(account_id, url).map_err(|e| { - error!("Error adding enclave: {:?}", e); - Error::Other("Error adding enclave".into()) - })?; - - Ok(()) - } - - fn remove_enclave( - enclave_registry: &EnclaveRegistry, - account_id: Address32, - ) -> Result<(), Error> { - info!("Remove Enclave Account from Registry: {:?}", account_id); - enclave_registry.remove(account_id).map_err(|e| { - error!("Error removing enclave: {:?}", e); - Error::Other("Error removing enclave".into()) - })?; - - Ok(()) - } - - fn save_signer( - signer_registry: &SignerRegistry, - account_id: Address32, - pub_key: [u8; 33], - ) -> Result<(), Error> { - info!("Saving Signer Account to Registry: {:?}", account_id); - signer_registry.update(account_id, pub_key).map_err(|e| { - error!("Error saving signer: {:?}", e); - Error::Other("Error saving signer".into()) - })?; - - Ok(()) - } -} - -impl - HandleParentchainEvents< - Executor, - TrustedCallSigned, - Error, - RelayerRegistry, - SignerRegistry, - EnclaveRegistry, - > for ParentchainEventHandler -where - Executor: IndirectExecutor< - TrustedCallSigned, - Error, - RelayerRegistry, - SignerRegistry, - EnclaveRegistry, - >, -{ - type Output = Vec; - - fn handle_events( - &self, - executor: &Executor, - events: impl FilterEvents, - _block_number: <::Header as ParentchainHeader>::Number, - ) -> Result, Error> - where - Block: ParentchainBlock, - { - let mut handled_events: Vec = Vec::new(); - - if let Ok(events) = events.get_relayer_added_events() { - debug!("Handling RelayerAdded events"); - let relayer_registry = executor.get_relayer_registry_updater(); - events - .iter() - .try_for_each(|event| { - debug!("found RelayerAdded event: {:?}", event); - let result = Self::add_relayer(relayer_registry, event.who.clone()); - handled_events.push(hash_of(&event)); - - result - }) - .map_err(|_| ParentchainEventProcessingError::RelayerAddFailure)?; - } - - if let Ok(events) = events.get_relayers_removed_events() { - debug!("Handling RelayerRemoved events"); - let relayer_registry = executor.get_relayer_registry_updater(); - events - .iter() - .try_for_each(|event| { - debug!("found RelayerRemoved event: {:?}", event); - let result = Self::remove_relayer(relayer_registry, event.who.clone()); - handled_events.push(hash_of(&event)); - - result - }) - .map_err(|_| ParentchainEventProcessingError::RelayerRemoveFailure)?; - } - - if let Ok(events) = events.get_enclave_added_events() { - debug!("Handling EnclaveAdded events"); - let enclave_registry = executor.get_enclave_registry_updater(); - events - .iter() - .try_for_each(|event| { - debug!("found EnclaveAdded event: {:?}", event); - let result = Self::add_enclave( - enclave_registry, - event.who, - event.url.clone(), - event.worker_type, - ); - handled_events.push(hash_of(&event)); - - result - }) - .map_err(|_| ParentchainEventProcessingError::EnclaveAddFailure)?; - } - - if let Ok(events) = events.get_enclave_removed_events() { - debug!("Handling EnclaveRemoved events"); - let enclave_registry = executor.get_enclave_registry_updater(); - events - .iter() - .try_for_each(|event| { - debug!("found EnclaveRemoved event: {:?}", event); - let result = Self::remove_enclave(enclave_registry, event.who); - handled_events.push(hash_of(&event)); - - result - }) - .map_err(|_| ParentchainEventProcessingError::EnclaveRemoveFailure)?; - } - - if let Ok(events) = events.get_btc_wallet_generated_events() { - debug!("Handling BtcWalletGenerated events"); - let signer_registry = executor.get_signer_registry_updater(); - events - .iter() - .try_for_each(|event| { - debug!("found BtcWalletGenerated event: {:?}", event); - let result = Self::save_signer( - signer_registry, - event.account_id.clone().into(), - event.pub_key, - ); - handled_events.push(hash_of(&event)); - - result - }) - .map_err(|_| ParentchainEventProcessingError::BtcWalletGeneratedFailure)?; - } - - Ok(handled_events) - } -} - -fn hash_of(ev: &T) -> H256 { - blake2_256(&ev.encode()).into() -} diff --git a/tee-worker/bitacross/app-libs/parentchain-interface/src/integritee/mod.rs b/tee-worker/bitacross/app-libs/parentchain-interface/src/integritee/mod.rs deleted file mode 100644 index ff2bbea146..0000000000 --- a/tee-worker/bitacross/app-libs/parentchain-interface/src/integritee/mod.rs +++ /dev/null @@ -1,31 +0,0 @@ -/* - Copyright 2021 Integritee AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -mod event_filter; -mod event_handler; - -pub use event_filter::FilterableEvents; -pub use event_handler::ParentchainEventHandler; -pub use itp_types::{ - parentchain::{AccountId, Balance, Hash}, - CallIndex, H256, -}; -use sp_runtime::traits::BlakeTwo256; - -pub type BlockNumber = u32; -pub type Header = sp_runtime::generic::Header; -pub type Signature = sp_runtime::MultiSignature; diff --git a/tee-worker/bitacross/app-libs/parentchain-interface/src/lib.rs b/tee-worker/bitacross/app-libs/parentchain-interface/src/lib.rs deleted file mode 100644 index ccaeac9266..0000000000 --- a/tee-worker/bitacross/app-libs/parentchain-interface/src/lib.rs +++ /dev/null @@ -1,54 +0,0 @@ -/* - Copyright 2021 Integritee AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -#![cfg_attr(all(not(target_env = "sgx"), not(feature = "std")), no_std)] -#![cfg_attr(target_env = "sgx", feature(rustc_private))] - -#[cfg(all(not(feature = "std"), feature = "sgx"))] -extern crate sgx_tstd as std; - -use codec::{Decode, Encode}; - -#[cfg(feature = "std")] -pub mod event_subscriber; -pub mod integritee; -pub mod target_a; -pub mod target_b; - -pub trait ParentchainInstance {} - -#[derive(Debug, Clone, Encode, Decode, Eq, PartialEq)] -pub struct Litentry; -impl ParentchainInstance for Litentry {} - -#[derive(Debug, Clone, Encode, Decode, Eq, PartialEq)] -pub struct TargetA; -impl ParentchainInstance for TargetA {} - -#[derive(Debug, Clone, Encode, Decode, Eq, PartialEq)] -pub struct TargetB; -impl ParentchainInstance for TargetB {} - -pub fn decode_and_log_error(encoded: &mut &[u8]) -> Option { - match V::decode(encoded) { - Ok(v) => Some(v), - Err(e) => { - log::warn!("Could not decode. {:?}: raw: {:?}", e, encoded); - None - }, - } -} diff --git a/tee-worker/bitacross/app-libs/parentchain-interface/src/target_a/event_filter.rs b/tee-worker/bitacross/app-libs/parentchain-interface/src/target_a/event_filter.rs deleted file mode 100644 index 33c0278536..0000000000 --- a/tee-worker/bitacross/app-libs/parentchain-interface/src/target_a/event_filter.rs +++ /dev/null @@ -1,122 +0,0 @@ -/* - Copyright 2021 Integritee AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ -//! Various way to filter Parentchain events - -use itc_parentchain_indirect_calls_executor::event_filter::ToEvents; -use itp_api_client_types::Events; -use itp_node_api::api_client::StaticEvent; -use itp_types::{ - parentchain::{events::*, FilterEvents}, - H256, -}; -use std::vec::Vec; - -#[derive(Clone)] -pub struct FilterableEvents(pub Events); - -impl FilterableEvents { - fn filter(&self) -> Result, E> { - Ok(self - .to_events() - .iter() - .flatten() - .filter_map(|ev| match ev.as_event::() { - Ok(maybe_event) => maybe_event, - Err(e) => { - log::error!("Could not decode event: {:?}", e); - None - }, - }) - .collect()) - } -} - -impl ToEvents> for FilterableEvents { - fn to_events(&self) -> &Events { - &self.0 - } -} - -impl From> for FilterableEvents { - fn from(ev: Events) -> Self { - Self(ev) - } -} - -impl FilterEvents for FilterableEvents { - type Error = itc_parentchain_indirect_calls_executor::Error; - - fn get_link_identity_events(&self) -> Result, Self::Error> { - self.filter() - } - - fn get_vc_requested_events(&self) -> Result, Self::Error> { - self.filter() - } - - fn get_deactivate_identity_events( - &self, - ) -> Result, Self::Error> { - self.filter() - } - - fn get_activate_identity_events(&self) -> Result, Self::Error> { - self.filter() - } - - fn get_enclave_unauthorized_events(&self) -> Result, Self::Error> { - self.filter() - } - - fn get_opaque_task_posted_events(&self) -> Result, Self::Error> { - self.filter() - } - - fn get_assertion_created_events(&self) -> Result, Self::Error> { - self.filter() - } - - fn get_parentchain_block_proccessed_events( - &self, - ) -> Result, Self::Error> { - self.filter() - } - - fn get_relayer_added_events(&self) -> Result, Self::Error> { - self.filter() - } - - fn get_relayers_removed_events(&self) -> Result, Self::Error> { - self.filter() - } - - fn get_enclave_added_events(&self) -> Result, Self::Error> { - self.filter() - } - - fn get_enclave_removed_events(&self) -> Result, Self::Error> { - self.filter() - } - - fn get_btc_wallet_generated_events(&self) -> Result, Self::Error> { - self.filter() - } - - fn get_account_store_updated_events(&self) -> Result, Self::Error> { - self.filter() - } -} diff --git a/tee-worker/bitacross/app-libs/parentchain-interface/src/target_a/event_handler.rs b/tee-worker/bitacross/app-libs/parentchain-interface/src/target_a/event_handler.rs deleted file mode 100644 index 12b6eb40a7..0000000000 --- a/tee-worker/bitacross/app-libs/parentchain-interface/src/target_a/event_handler.rs +++ /dev/null @@ -1,68 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -pub use ita_sgx_runtime::{Balance, Index}; - -use bc_enclave_registry::EnclaveRegistry; -use bc_relayer_registry::RelayerRegistry; -use bc_signer_registry::SignerRegistry; -use ita_stf::TrustedCallSigned; -use itc_parentchain_indirect_calls_executor::error::Error; -use itp_stf_primitives::traits::IndirectExecutor; -use itp_types::{ - parentchain::{FilterEvents, HandleParentchainEvents}, - H256, -}; -use log::*; -use sp_runtime::traits::{Block as ParentchainBlock, Header as ParentchainHeader}; -use std::vec::Vec; - -pub struct ParentchainEventHandler {} - -impl - HandleParentchainEvents< - Executor, - TrustedCallSigned, - Error, - RelayerRegistry, - SignerRegistry, - EnclaveRegistry, - > for ParentchainEventHandler -where - Executor: IndirectExecutor< - TrustedCallSigned, - Error, - RelayerRegistry, - SignerRegistry, - EnclaveRegistry, - >, -{ - type Output = Vec; - - fn handle_events( - &self, - _executor: &Executor, - _events: impl FilterEvents, - _block_number: <::Header as ParentchainHeader>::Number, - ) -> Result, Error> - where - Block: ParentchainBlock, - { - debug!("not handling any events for target a"); - Ok(Vec::new()) - } -} diff --git a/tee-worker/bitacross/app-libs/parentchain-interface/src/target_a/mod.rs b/tee-worker/bitacross/app-libs/parentchain-interface/src/target_a/mod.rs deleted file mode 100644 index 0458b6c9ee..0000000000 --- a/tee-worker/bitacross/app-libs/parentchain-interface/src/target_a/mod.rs +++ /dev/null @@ -1,21 +0,0 @@ -/* - Copyright 2021 Integritee AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ -mod event_filter; -mod event_handler; - -pub use event_filter::FilterableEvents; -pub use event_handler::ParentchainEventHandler; diff --git a/tee-worker/bitacross/app-libs/parentchain-interface/src/target_b/event_filter.rs b/tee-worker/bitacross/app-libs/parentchain-interface/src/target_b/event_filter.rs deleted file mode 100644 index 33c0278536..0000000000 --- a/tee-worker/bitacross/app-libs/parentchain-interface/src/target_b/event_filter.rs +++ /dev/null @@ -1,122 +0,0 @@ -/* - Copyright 2021 Integritee AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ -//! Various way to filter Parentchain events - -use itc_parentchain_indirect_calls_executor::event_filter::ToEvents; -use itp_api_client_types::Events; -use itp_node_api::api_client::StaticEvent; -use itp_types::{ - parentchain::{events::*, FilterEvents}, - H256, -}; -use std::vec::Vec; - -#[derive(Clone)] -pub struct FilterableEvents(pub Events); - -impl FilterableEvents { - fn filter(&self) -> Result, E> { - Ok(self - .to_events() - .iter() - .flatten() - .filter_map(|ev| match ev.as_event::() { - Ok(maybe_event) => maybe_event, - Err(e) => { - log::error!("Could not decode event: {:?}", e); - None - }, - }) - .collect()) - } -} - -impl ToEvents> for FilterableEvents { - fn to_events(&self) -> &Events { - &self.0 - } -} - -impl From> for FilterableEvents { - fn from(ev: Events) -> Self { - Self(ev) - } -} - -impl FilterEvents for FilterableEvents { - type Error = itc_parentchain_indirect_calls_executor::Error; - - fn get_link_identity_events(&self) -> Result, Self::Error> { - self.filter() - } - - fn get_vc_requested_events(&self) -> Result, Self::Error> { - self.filter() - } - - fn get_deactivate_identity_events( - &self, - ) -> Result, Self::Error> { - self.filter() - } - - fn get_activate_identity_events(&self) -> Result, Self::Error> { - self.filter() - } - - fn get_enclave_unauthorized_events(&self) -> Result, Self::Error> { - self.filter() - } - - fn get_opaque_task_posted_events(&self) -> Result, Self::Error> { - self.filter() - } - - fn get_assertion_created_events(&self) -> Result, Self::Error> { - self.filter() - } - - fn get_parentchain_block_proccessed_events( - &self, - ) -> Result, Self::Error> { - self.filter() - } - - fn get_relayer_added_events(&self) -> Result, Self::Error> { - self.filter() - } - - fn get_relayers_removed_events(&self) -> Result, Self::Error> { - self.filter() - } - - fn get_enclave_added_events(&self) -> Result, Self::Error> { - self.filter() - } - - fn get_enclave_removed_events(&self) -> Result, Self::Error> { - self.filter() - } - - fn get_btc_wallet_generated_events(&self) -> Result, Self::Error> { - self.filter() - } - - fn get_account_store_updated_events(&self) -> Result, Self::Error> { - self.filter() - } -} diff --git a/tee-worker/bitacross/app-libs/parentchain-interface/src/target_b/event_handler.rs b/tee-worker/bitacross/app-libs/parentchain-interface/src/target_b/event_handler.rs deleted file mode 100644 index f3ab23f2a1..0000000000 --- a/tee-worker/bitacross/app-libs/parentchain-interface/src/target_b/event_handler.rs +++ /dev/null @@ -1,68 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -pub use ita_sgx_runtime::{Balance, Index}; - -use bc_enclave_registry::EnclaveRegistry; -use bc_relayer_registry::RelayerRegistry; -use bc_signer_registry::SignerRegistry; -use ita_stf::TrustedCallSigned; -use itc_parentchain_indirect_calls_executor::error::Error; -use itp_stf_primitives::traits::IndirectExecutor; -use itp_types::{ - parentchain::{FilterEvents, HandleParentchainEvents}, - H256, -}; -use log::*; -use sp_runtime::traits::{Block as ParentchainBlock, Header as ParentchainHeader}; -use std::vec::Vec; - -pub struct ParentchainEventHandler {} - -impl - HandleParentchainEvents< - Executor, - TrustedCallSigned, - Error, - RelayerRegistry, - SignerRegistry, - EnclaveRegistry, - > for ParentchainEventHandler -where - Executor: IndirectExecutor< - TrustedCallSigned, - Error, - RelayerRegistry, - SignerRegistry, - EnclaveRegistry, - >, -{ - type Output = Vec; - - fn handle_events( - &self, - _executor: &Executor, - _events: impl FilterEvents, - _block_number: <::Header as ParentchainHeader>::Number, - ) -> Result, Error> - where - Block: ParentchainBlock, - { - debug!("not handling any events for target B"); - Ok(Vec::new()) - } -} diff --git a/tee-worker/bitacross/app-libs/parentchain-interface/src/target_b/mod.rs b/tee-worker/bitacross/app-libs/parentchain-interface/src/target_b/mod.rs deleted file mode 100644 index 14bedb28cb..0000000000 --- a/tee-worker/bitacross/app-libs/parentchain-interface/src/target_b/mod.rs +++ /dev/null @@ -1,22 +0,0 @@ -/* - Copyright 2021 Integritee AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -mod event_filter; -mod event_handler; - -pub use event_filter::FilterableEvents; -pub use event_handler::ParentchainEventHandler; diff --git a/tee-worker/bitacross/app-libs/sgx-runtime/Cargo.toml b/tee-worker/bitacross/app-libs/sgx-runtime/Cargo.toml deleted file mode 100644 index f49678f57e..0000000000 --- a/tee-worker/bitacross/app-libs/sgx-runtime/Cargo.toml +++ /dev/null @@ -1,57 +0,0 @@ -[package] -name = "bc-ita-sgx-runtime" -version = "0.1.0" -authors = ['Trust Computing GmbH ', 'Integritee AG '] -edition = "2021" - -[package.metadata.docs.rs] -targets = ["x86_64-unknown-linux-gnu"] - -[dependencies] -codec = { package = "parity-scale-codec", workspace = true } -scale-info = { workspace = true } - -itp-sgx-runtime-primitives = { workspace = true } - -frame-executive = { workspace = true } -frame-support = { workspace = true } -frame-system = { workspace = true } -pallet-balances = { workspace = true } -pallet-sudo = { workspace = true } -pallet-timestamp = { workspace = true } -pallet-transaction-payment = { workspace = true } -sp-api = { workspace = true } -sp-core = { workspace = true } -sp-runtime = { workspace = true } -sp-std = { workspace = true } -sp-version = { workspace = true } - -pallet-parentchain = { workspace = true } - -[features] -default = ["std"] -runtime-benchmarks = [ - "frame-support/runtime-benchmarks", - "frame-system/runtime-benchmarks", - "pallet-balances/runtime-benchmarks", - "pallet-timestamp/runtime-benchmarks", - "sp-runtime/runtime-benchmarks", -] -std = [ - "codec/std", - "scale-info/std", - "itp-sgx-runtime-primitives/std", - "frame-executive/std", - "frame-support/std", - "frame-system/std", - "pallet-balances/std", - "pallet-sudo/std", - "pallet-timestamp/std", - "pallet-transaction-payment/std", - "pallet-parentchain/std", - "sp-api/std", - "sp-core/std", - "sp-runtime/std", - "sp-std/std", - "sp-version/std", -] diff --git a/tee-worker/bitacross/app-libs/sgx-runtime/src/lib.rs b/tee-worker/bitacross/app-libs/sgx-runtime/src/lib.rs deleted file mode 100644 index c08002263a..0000000000 --- a/tee-worker/bitacross/app-libs/sgx-runtime/src/lib.rs +++ /dev/null @@ -1,314 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ - -//! The Substrate Node Template sgx-runtime for SGX. -//! This is only meant to be used inside an SGX enclave with `#[no_std]` -//! -//! you should assemble your sgx-runtime to be used with your STF here -//! and get all your needed pallets in - -#![cfg_attr(not(feature = "std"), no_std)] -#![feature(prelude_import)] -#![feature(structural_match)] -#![feature(core_intrinsics)] -#![feature(derive_eq)] -// `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256. -#![recursion_limit = "256"] - -use core::convert::{TryFrom, TryInto}; -use frame_support::{traits::ConstU32, weights::ConstantMultiplier}; -use pallet_transaction_payment::CurrencyAdapter; -use sp_api::impl_runtime_apis; -use sp_core::OpaqueMetadata; -use sp_runtime::{ - create_runtime_str, generic, - traits::{AccountIdLookup, BlakeTwo256, Block as BlockT}, -}; -use sp_std::prelude::*; -use sp_version::RuntimeVersion; - -// Re-exports from itp-sgx-runtime-primitives. -pub use itp_sgx_runtime_primitives::{ - constants::SLOT_DURATION, - types::{ - AccountData, AccountId, Address, Balance, BlockNumber, Hash, Header, Index, Signature, - }, -}; - -// A few exports that help ease life for downstream crates. -pub use frame_support::{ - construct_runtime, parameter_types, - traits::{KeyOwnerProofSystem, Randomness}, - weights::{ - constants::{ - BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_REF_TIME_PER_SECOND, - }, - IdentityFee, Weight, - }, - StorageValue, -}; -use itp_sgx_runtime_primitives::types::Moment; -pub use pallet_balances::Call as BalancesCall; -pub use pallet_timestamp::Call as TimestampCall; -#[cfg(any(feature = "std", test))] -pub use sp_runtime::BuildStorage; -pub use sp_runtime::{Perbill, Permill}; - -/// Block type as expected by this sgx-runtime. -pub type Block = generic::Block; -/// A Block signed with a Justification -pub type SignedBlock = generic::SignedBlock; -/// BlockId type as expected by this sgx-runtime. -pub type BlockId = generic::BlockId; - -/// The SignedExtension to the basic transaction logic. -pub type SignedExtra = ( - frame_system::CheckNonZeroSender, - frame_system::CheckSpecVersion, - frame_system::CheckTxVersion, - frame_system::CheckGenesis, - frame_system::CheckEra, - frame_system::CheckNonce, - frame_system::CheckWeight, - pallet_transaction_payment::ChargeTransactionPayment, -); -/// Unchecked extrinsic type as expected by this sgx-runtime. -pub type UncheckedExtrinsic = - generic::UncheckedExtrinsic; -/// Extrinsic type that has already been checked. -pub type CheckedExtrinsic = generic::CheckedExtrinsic; - -/// Executive: handles dispatch to the various modules. -pub type Executive = frame_executive::Executive< - Runtime, - Block, - frame_system::ChainContext, - Runtime, - AllPalletsWithSystem, ->; - -/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know -/// the specifics of the sgx-runtime. They can then be made to be agnostic over specific formats -/// of data like extrinsics, allowing for them to continue syncing the network through upgrades -/// to even the core data structures. -pub mod opaque { - - use sp_runtime::generic; - pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic; - - /// Opaque block header type. - pub type Header = itp_sgx_runtime_primitives::types::Header; - /// Opaque block type. - pub type Block = super::Block; - /// Opaque block identifier type. - pub type BlockId = generic::BlockId; -} - -pub const VERSION: RuntimeVersion = RuntimeVersion { - spec_name: create_runtime_str!("node-template"), - impl_name: create_runtime_str!("node-template"), - authoring_version: 1, - spec_version: 106, - impl_version: 1, - apis: RUNTIME_API_VERSIONS, - transaction_version: 1, - state_version: 0, -}; - -const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75); - -parameter_types! { - pub const Version: RuntimeVersion = VERSION; - pub const BlockHashCount: BlockNumber = 2400; - /// We allow for 2 seconds of compute with a 6 second average block time. - pub BlockWeights: frame_system::limits::BlockWeights = frame_system::limits::BlockWeights - ::with_sensible_defaults(Weight::from_parts(WEIGHT_REF_TIME_PER_SECOND, u64::MAX), NORMAL_DISPATCH_RATIO); - pub BlockLength: frame_system::limits::BlockLength = frame_system::limits::BlockLength - ::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO); - pub const SS58Prefix: u8 = 42; -} - -// Configure FRAME pallets to include in sgx-runtime. - -impl frame_system::Config for Runtime { - /// The basic call filter to use in dispatchable. - type BaseCallFilter = frame_support::traits::Everything; - /// Block & extrinsics weights: base values and limits. - type BlockWeights = BlockWeights; - /// The maximum length of a block (in bytes). - type BlockLength = BlockLength; - /// The identifier used to distinguish between accounts. - type AccountId = AccountId; - /// The aggregated dispatch type that is available for extrinsics. - type RuntimeCall = RuntimeCall; - /// The lookup mechanism to get account ID from whatever is passed in dispatchers. - type Lookup = AccountIdLookup; - /// The index type for storing how many extrinsics an account has signed. - type Index = Index; - /// The index type for blocks. - type BlockNumber = BlockNumber; - /// The type for hashing blocks and tries. - type Hash = Hash; - /// The hashing algorithm used. - type Hashing = BlakeTwo256; - /// The header type. - type Header = Header; - /// The ubiquitous event type. - type RuntimeEvent = RuntimeEvent; - /// The ubiquitous origin type. - type RuntimeOrigin = RuntimeOrigin; - /// Maximum number of block number to block hash mappings to keep (oldest pruned first). - type BlockHashCount = BlockHashCount; - /// The weight of database operations that the sgx-runtime can invoke. - type DbWeight = RocksDbWeight; - /// Version of the sgx-runtime. - type Version = Version; - /// Converts a module to the index of the module in `construct_runtime!`. - /// - /// This type is being generated by `construct_runtime!`. - type PalletInfo = PalletInfo; - /// What to do if a new account is created. - type OnNewAccount = (); - /// What to do if an account is fully reaped from the system. - type OnKilledAccount = (); - /// The data to be stored in an account. - type AccountData = AccountData; - /// Weight information for the extrinsics of this pallet. - type SystemWeightInfo = (); - /// This is used as an identifier of the chain. 42 is the generic substrate prefix. - type SS58Prefix = SS58Prefix; - /// The set code logic, just the default since we're not a parachain. - type OnSetCode = (); - /// The maximum number of consumers allowed on a single account. - type MaxConsumers = frame_support::traits::ConstU32<16>; -} - -parameter_types! { - pub const MinimumPeriod: u64 = SLOT_DURATION / 2; -} - -impl pallet_timestamp::Config for Runtime { - /// A timestamp: milliseconds since the unix epoch. - type Moment = Moment; - type OnTimestampSet = (); - type MinimumPeriod = MinimumPeriod; - type WeightInfo = (); -} - -parameter_types! { - pub const ExistentialDeposit: u128 = 500; - pub const MaxLocks: u32 = 50; -} - -impl pallet_balances::Config for Runtime { - type MaxLocks = MaxLocks; - type MaxReserves = (); - type ReserveIdentifier = [u8; 8]; - /// The type for recording an account's balance. - type Balance = Balance; - /// The ubiquitous event type. - type RuntimeEvent = RuntimeEvent; - type DustRemoval = (); - type ExistentialDeposit = ExistentialDeposit; - type AccountStore = System; - type WeightInfo = (); - type HoldIdentifier = (); - type FreezeIdentifier = (); - type MaxHolds = ConstU32<0>; - type MaxFreezes = ConstU32<0>; -} - -parameter_types! { - pub const TransactionByteFee: Balance = 1; - pub const OperationalFeeMultiplier: u8 = 5; -} - -impl pallet_transaction_payment::Config for Runtime { - type RuntimeEvent = RuntimeEvent; - type OnChargeTransaction = CurrencyAdapter; - type OperationalFeeMultiplier = OperationalFeeMultiplier; - type WeightToFee = IdentityFee; - type LengthToFee = ConstantMultiplier; - type FeeMultiplierUpdate = (); -} - -impl pallet_sudo::Config for Runtime { - type RuntimeEvent = RuntimeEvent; - type RuntimeCall = RuntimeCall; -} - -pub type ParentchainInstanceLitentry = pallet_parentchain::Instance1; -impl pallet_parentchain::Config for Runtime { - type WeightInfo = (); -} - -pub type ParentchainInstanceTargetA = pallet_parentchain::Instance2; -impl pallet_parentchain::Config for Runtime { - type WeightInfo = (); -} - -pub type ParentchainInstanceTargetB = pallet_parentchain::Instance3; -impl pallet_parentchain::Config for Runtime { - type WeightInfo = (); -} - -construct_runtime!( - pub enum Runtime where - Block = Block, - NodeBlock = opaque::Block, - UncheckedExtrinsic = UncheckedExtrinsic - { - System: frame_system, - Timestamp: pallet_timestamp, - Balances: pallet_balances, - TransactionPayment: pallet_transaction_payment, - Sudo: pallet_sudo, - ParentchainLitentry: pallet_parentchain::, - ParentchainTargetA: pallet_parentchain::, - ParentchainTargetB: pallet_parentchain::, - } -); - -impl_runtime_apis! { - impl sp_api::Core for Runtime { - fn version() -> RuntimeVersion { - VERSION - } - - fn execute_block(block: Block) { - Executive::execute_block(block); - } - - fn initialize_block(header: &::Header) { - Executive::initialize_block(header) - } - } - - impl sp_api::Metadata for Runtime { - fn metadata() -> OpaqueMetadata { - OpaqueMetadata::new(Runtime::metadata().into()) - } - - fn metadata_at_version(version: u32) -> Option { - Runtime::metadata_at_version(version) - } - - fn metadata_versions() -> sp_std::vec::Vec { - Runtime::metadata_versions() - } - } - -} diff --git a/tee-worker/bitacross/app-libs/stf/Cargo.toml b/tee-worker/bitacross/app-libs/stf/Cargo.toml deleted file mode 100644 index d3016c539c..0000000000 --- a/tee-worker/bitacross/app-libs/stf/Cargo.toml +++ /dev/null @@ -1,75 +0,0 @@ -[package] -name = "bc-ita-stf" -version = "0.1.0" -authors = ['Trust Computing GmbH ', 'Integritee AG '] -edition = "2021" - -[dependencies] -codec = { package = "parity-scale-codec", workspace = true } -hex = { workspace = true } -hex-literal = { workspace = true } -log = { workspace = true } - -sgx_tstd = { workspace = true, features = ["untrusted_fs", "net", "backtrace"], optional = true } - -itp-hashing = { workspace = true } -itp-node-api = { workspace = true } -itp-sgx-externalities = { workspace = true } -itp-stf-interface = { workspace = true } -itp-stf-primitives = { workspace = true } -itp-storage = { workspace = true } -itp-types = { workspace = true } -itp-utils = { workspace = true } - -ita-sgx-runtime = { package = "bc-ita-sgx-runtime", path = "../sgx-runtime", default-features = false } -sp-io = { path = "../../../common/core-primitives/substrate-sgx/sp-io", default-features = false, features = ["disable_oom", "disable_panic_handler", "disable_allocator"] } - -frame-support = { workspace = true } -frame-system = { workspace = true } -pallet-balances = { workspace = true } -pallet-sudo = { workspace = true } -sp-core = { workspace = true, features = ["full_crypto"] } -sp-runtime = { workspace = true } -sp-std = { workspace = true } - -litentry-macros = { workspace = true } -litentry-primitives = { workspace = true } -pallet-parentchain = { workspace = true } - -[dev-dependencies] -sp-keyring = { workspace = true } - -[features] -default = ["std"] -sgx = [ - "sgx_tstd", - "itp-sgx-externalities/sgx", - "sp-io/sgx", - "itp-node-api/sgx", - "litentry-primitives/sgx", -] -std = [ - # crates.io - "codec/std", - "log/std", - "ita-sgx-runtime/std", - "itp-hashing/std", - "itp-sgx-externalities/std", - "itp-stf-interface/std", - "itp-storage/std", - "itp-types/std", - "itp-node-api/std", - "sp-core/std", - "pallet-balances/std", - "pallet-sudo/std", - "frame-system/std", - "frame-support/std", - "sp-runtime/std", - "pallet-parentchain/std", - "sp-io/std", - "litentry-primitives/std", -] -test = [] -development = [ - "litentry-macros/development", -] diff --git a/tee-worker/bitacross/app-libs/stf/src/getter.rs b/tee-worker/bitacross/app-libs/stf/src/getter.rs deleted file mode 100644 index 662fa355e5..0000000000 --- a/tee-worker/bitacross/app-libs/stf/src/getter.rs +++ /dev/null @@ -1,215 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use codec::{Decode, Encode}; -use ita_sgx_runtime::System; -use itp_stf_interface::ExecuteGetter; -use itp_stf_primitives::{traits::GetterAuthorization, types::KeyPair}; -use itp_utils::stringify::account_id_to_string; -use litentry_macros::if_development_or; -use litentry_primitives::{Identity, LitentryMultiSignature}; -use log::*; -use sp_std::vec; -use std::prelude::v1::*; - -use itp_stf_primitives::traits::PoolTransactionValidation; -use sp_runtime::transaction_validity::{ - TransactionValidityError, UnknownTransaction, ValidTransaction, -}; - -#[cfg(feature = "development")] -use crate::helpers::ALICE_ACCOUNTID32; - -#[derive(Encode, Decode, Clone, Debug, PartialEq, Eq)] -#[allow(non_camel_case_types)] -pub enum Getter { - #[codec(index = 0)] - public(PublicGetter), - #[codec(index = 1)] - trusted(TrustedGetterSigned), -} - -impl Default for Getter { - fn default() -> Self { - Getter::public(PublicGetter::some_value) - } -} -impl From for Getter { - fn from(item: PublicGetter) -> Self { - Getter::public(item) - } -} - -impl From for Getter { - fn from(item: TrustedGetterSigned) -> Self { - Getter::trusted(item) - } -} - -impl GetterAuthorization for Getter { - fn is_authorized(&self) -> bool { - match self { - Self::trusted(ref getter) => getter.verify_signature(), - Self::public(_) => true, - } - } -} - -impl PoolTransactionValidation for Getter { - fn validate(&self) -> Result { - match self { - Self::public(_) => - Err(TransactionValidityError::Unknown(UnknownTransaction::CannotLookup)), - Self::trusted(trusted_getter_signed) => Ok(ValidTransaction { - priority: 1 << 20, - requires: vec![], - provides: vec![trusted_getter_signed.signature.encode()], - longevity: 64, - propagate: true, - }), - } - } -} - -#[derive(Encode, Decode, Clone, Debug, PartialEq, Eq)] -#[allow(non_camel_case_types)] -pub enum PublicGetter { - #[codec(index = 0)] - some_value, - #[codec(index = 1)] - nonce(Identity), -} - -#[derive(Encode, Decode, Clone, Debug, PartialEq, Eq)] -#[allow(non_camel_case_types)] -pub enum TrustedGetter { - #[codec(index = 0)] - free_balance(Identity), - #[codec(index = 1)] - reserved_balance(Identity), -} - -impl TrustedGetter { - pub fn sender_identity(&self) -> &Identity { - match self { - TrustedGetter::free_balance(sender_identity) => sender_identity, - TrustedGetter::reserved_balance(sender_identity) => sender_identity, - } - } - - pub fn sign(&self, pair: &KeyPair) -> TrustedGetterSigned { - let signature = pair.sign(self.encode().as_slice()); - TrustedGetterSigned { getter: self.clone(), signature } - } -} - -#[derive(Encode, Decode, Clone, Debug, PartialEq, Eq)] -pub struct TrustedGetterSigned { - pub getter: TrustedGetter, - pub signature: LitentryMultiSignature, -} - -impl TrustedGetterSigned { - pub fn new(getter: TrustedGetter, signature: LitentryMultiSignature) -> Self { - TrustedGetterSigned { getter, signature } - } - - pub fn verify_signature(&self) -> bool { - // in non-prod, we accept signature from Alice too - if_development_or!( - { - self.signature - .verify(self.getter.encode().as_slice(), self.getter.sender_identity()) - || self - .signature - .verify(self.getter.encode().as_slice(), &ALICE_ACCOUNTID32.into()) - }, - { - self.signature - .verify(self.getter.encode().as_slice(), self.getter.sender_identity()) - } - ) - } -} - -impl ExecuteGetter for Getter { - fn execute(self) -> Option> { - match self { - Getter::trusted(g) => g.execute(), - Getter::public(g) => g.execute(), - } - } - - fn get_storage_hashes_to_update(self) -> Vec> { - match self { - Getter::trusted(g) => g.get_storage_hashes_to_update(), - Getter::public(g) => g.get_storage_hashes_to_update(), - } - } -} - -impl ExecuteGetter for TrustedGetterSigned { - fn execute(self) -> Option> { - match self.getter { - TrustedGetter::free_balance(who) => - if let Some(account_id) = who.to_native_account() { - let info = System::account(&account_id); - debug!("TrustedGetter free_balance"); - debug!("AccountInfo for {} is {:?}", account_id_to_string(&who), info); - std::println!("⣿STF⣿ 🔍 TrustedGetter query: free balance for ⣿⣿⣿ is ⣿⣿⣿",); - Some(info.data.free.encode()) - } else { - None - }, - TrustedGetter::reserved_balance(who) => - if let Some(account_id) = who.to_native_account() { - let info = System::account(&account_id); - debug!("TrustedGetter reserved_balance"); - debug!("AccountInfo for {} is {:?}", account_id_to_string(&who), info); - debug!("Account reserved balance is {}", info.data.reserved); - Some(info.data.reserved.encode()) - } else { - None - }, - } - } - - fn get_storage_hashes_to_update(self) -> Vec> { - Vec::new() - } -} - -impl ExecuteGetter for PublicGetter { - fn execute(self) -> Option> { - match self { - PublicGetter::some_value => Some(42u32.encode()), - PublicGetter::nonce(identity) => - if let Some(account_id) = identity.to_native_account() { - let nonce = System::account_nonce(&account_id); - debug!("PublicGetter nonce"); - debug!("Account nonce is {}", nonce); - Some(nonce.encode()) - } else { - None - }, - } - } - - fn get_storage_hashes_to_update(self) -> Vec> { - Vec::new() - } -} diff --git a/tee-worker/bitacross/app-libs/stf/src/hash.rs b/tee-worker/bitacross/app-libs/stf/src/hash.rs deleted file mode 100644 index f3cde9fa32..0000000000 --- a/tee-worker/bitacross/app-libs/stf/src/hash.rs +++ /dev/null @@ -1,29 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use crate::TrustedGetter; -use codec::Encode; -pub use itp_hashing::Hash; - -use itp_types::H256; -use sp_core::blake2_256; - -impl Hash for TrustedGetter { - fn hash(&self) -> H256 { - blake2_256(&self.encode()).into() - } -} diff --git a/tee-worker/bitacross/app-libs/stf/src/helpers.rs b/tee-worker/bitacross/app-libs/stf/src/helpers.rs deleted file mode 100644 index 24256aa507..0000000000 --- a/tee-worker/bitacross/app-libs/stf/src/helpers.rs +++ /dev/null @@ -1,165 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ -use crate::ENCLAVE_ACCOUNT_KEY; -use codec::{Decode, Encode}; -use ita_sgx_runtime::{ParentchainLitentry, ParentchainTargetA, ParentchainTargetB}; -use itp_stf_interface::{BlockMetadata, ShardCreationInfo}; -use itp_stf_primitives::error::{StfError, StfResult}; -use itp_storage::{storage_double_map_key, storage_map_key, storage_value_key, StorageHasher}; - -use itp_utils::stringify::account_id_to_string; -use log::*; -use std::prelude::v1::*; - -#[cfg(feature = "development")] -pub use non_prod::*; - -pub fn get_storage_value( - storage_prefix: &'static str, - storage_key_name: &'static str, -) -> Option { - let key = storage_value_key(storage_prefix, storage_key_name); - get_storage_by_key_hash(key) -} - -pub fn get_storage_map( - storage_prefix: &'static str, - storage_key_name: &'static str, - map_key: &K, - hasher: &StorageHasher, -) -> Option { - let key = storage_map_key::(storage_prefix, storage_key_name, map_key, hasher); - get_storage_by_key_hash(key) -} - -pub fn get_storage_double_map( - storage_prefix: &'static str, - storage_key_name: &'static str, - first: &K, - first_hasher: &StorageHasher, - second: &Q, - second_hasher: &StorageHasher, -) -> Option { - let key = storage_double_map_key::( - storage_prefix, - storage_key_name, - first, - first_hasher, - second, - second_hasher, - ); - get_storage_by_key_hash(key) -} - -/// Get value in storage. -pub fn get_storage_by_key_hash(key: Vec) -> Option { - if let Some(value_encoded) = sp_io::storage::get(&key) { - if let Ok(value) = Decode::decode(&mut value_encoded.as_slice()) { - Some(value) - } else { - error!("could not decode state for key {:?}", hex::encode(&key)); - None - } - } else { - info!("key not found in state {:?}", hex::encode(key)); - None - } -} - -/// Get the AccountInfo key where the account is stored. -pub fn account_key_hash(account: &AccountId) -> Vec { - storage_map_key("System", "Account", account, &StorageHasher::Blake2_128Concat) -} - -pub fn enclave_signer_account() -> AccountId { - get_storage_value("Sudo", ENCLAVE_ACCOUNT_KEY).expect("No enclave account") -} - -/// Ensures an account is a registered enclave account. -pub fn ensure_enclave_signer_account( - account: &AccountId, -) -> StfResult<()> { - let expected_enclave_account: AccountId = enclave_signer_account(); - if &expected_enclave_account == account { - Ok(()) - } else { - error!( - "Expected enclave account {}, but found {}", - account_id_to_string(&expected_enclave_account), - account_id_to_string(account) - ); - Err(StfError::RequireEnclaveSignerAccount) - } -} - -pub fn set_block_number(block_number: u32) { - sp_io::storage::set(&storage_value_key("System", "Number"), &block_number.encode()); -} - -pub fn ensure_self(signer: &AccountId, who: &AccountId) -> bool { - signer == who -} - -pub fn ensure_enclave_signer_or_self( - signer: &AccountId, - who: Option, -) -> bool { - match who { - Some(ref who) => - signer == &enclave_signer_account::() || ensure_self(signer, who), - None => false, - } -} - -pub fn shard_creation_info() -> ShardCreationInfo { - let maybe_litentry_info: Option = ParentchainLitentry::creation_block_number() - .and_then(|number| { - ParentchainLitentry::creation_block_hash().map(|hash| BlockMetadata { number, hash }) - }); - let maybe_target_a_info: Option = ParentchainTargetA::creation_block_number() - .and_then(|number| { - ParentchainTargetA::creation_block_hash().map(|hash| BlockMetadata { number, hash }) - }); - let maybe_target_b_info: Option = ParentchainTargetB::creation_block_number() - .and_then(|number| { - ParentchainTargetB::creation_block_hash().map(|hash| BlockMetadata { number, hash }) - }); - - ShardCreationInfo { - litentry: maybe_litentry_info, - target_a: maybe_target_a_info, - target_b: maybe_target_b_info, - } -} - -#[cfg(feature = "development")] -mod non_prod { - use super::*; - use hex_literal::hex; - use sp_runtime::AccountId32; - - pub const ALICE_ACCOUNTID32: AccountId32 = - AccountId32::new(hex!["d43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d"]); - - pub fn ensure_alice(signer: &AccountId32) -> bool { - signer == &ALICE_ACCOUNTID32 - } - - pub fn ensure_enclave_signer_or_alice(signer: &AccountId32) -> bool { - signer == &enclave_signer_account::() || ensure_alice(signer) - } -} diff --git a/tee-worker/bitacross/app-libs/stf/src/lib.rs b/tee-worker/bitacross/app-libs/stf/src/lib.rs deleted file mode 100644 index 4aa3ff1db4..0000000000 --- a/tee-worker/bitacross/app-libs/stf/src/lib.rs +++ /dev/null @@ -1,51 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -///////////////////////////////////////////////////////////////////////////// -#![feature(structural_match)] -#![feature(rustc_attrs)] -#![feature(core_intrinsics)] -#![feature(derive_eq)] -#![cfg_attr(all(not(target_env = "sgx"), not(feature = "std")), no_std)] -#![cfg_attr(target_env = "sgx", feature(rustc_private))] -#![allow(clippy::large_enum_variant)] -#![allow(clippy::result_large_err)] - -extern crate core; -#[cfg(all(not(feature = "std"), feature = "sgx"))] -extern crate sgx_tstd as std; - -pub use getter::*; -pub use stf_sgx_primitives::{types::*, Stf}; -pub use trusted_call::*; - -pub mod getter; -pub mod hash; -pub mod helpers; -pub mod stf_sgx; -pub mod stf_sgx_primitives; -#[cfg(all(feature = "test", feature = "sgx"))] -pub mod stf_sgx_tests; -#[cfg(all(feature = "test", feature = "sgx"))] -pub mod test_genesis; -pub mod trusted_call; -pub mod trusted_call_result; - -pub(crate) const ENCLAVE_ACCOUNT_KEY: &str = "Enclave_Account_Key"; - -// fixme: this if a temporary hack only -pub const STF_TX_FEE: Balance = 100000000; diff --git a/tee-worker/bitacross/app-libs/stf/src/stf_sgx.rs b/tee-worker/bitacross/app-libs/stf/src/stf_sgx.rs deleted file mode 100644 index 6412b5cf78..0000000000 --- a/tee-worker/bitacross/app-libs/stf/src/stf_sgx.rs +++ /dev/null @@ -1,422 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -#[cfg(feature = "test")] -use crate::test_genesis::test_genesis_setup; -use crate::{ - helpers::{enclave_signer_account, shard_creation_info}, - Stf, ENCLAVE_ACCOUNT_KEY, -}; -use codec::{Decode, Encode}; -use frame_support::traits::{OriginTrait, UnfilteredDispatchable}; -use ita_sgx_runtime::{ - Executive, ParentchainInstanceLitentry, ParentchainInstanceTargetA, ParentchainInstanceTargetB, -}; -use itp_node_api::metadata::{provider::AccessNodeMetadata, NodeMetadataTrait}; -use itp_sgx_externalities::SgxExternalitiesTrait; -use itp_stf_interface::{ - parentchain_pallet::ParentchainPalletInstancesInterface, - runtime_upgrade::RuntimeUpgradeInterface, - sudo_pallet::SudoPalletInterface, - system_pallet::{SystemPalletAccountInterface, SystemPalletEventInterface}, - ExecuteCall, ExecuteGetter, InitState, ShardCreationInfo, ShardCreationQuery, - StateCallInterface, StateGetterInterface, UpdateState, -}; -use itp_stf_primitives::{ - error::StfError, traits::TrustedCallVerification, types::ShardIdentifier, -}; -use itp_storage::storage_value_key; -use itp_types::{ - parentchain::{AccountId, ParentchainCall, ParentchainId}, - H256, -}; -use itp_utils::stringify::account_id_to_string; -use log::*; -use sp_runtime::traits::StaticLookup; -use std::{fmt::Debug, format, prelude::v1::*, sync::Arc, vec}; - -impl InitState for Stf -where - State: SgxExternalitiesTrait + Debug, - ::SgxExternalitiesType: core::default::Default, - Runtime: frame_system::Config + pallet_balances::Config, - <::Lookup as StaticLookup>::Source: - std::convert::From, - AccountId: Encode, -{ - fn init_state(enclave_account: AccountId) -> State { - debug!("initializing stf state, account id {}", account_id_to_string(&enclave_account)); - let mut state = State::new(Default::default()); - - state.execute_with(|| { - // Do not set genesis for pallets that are meant to be on-chain - // use get_storage_hashes_to_update instead. - - sp_io::storage::set(&storage_value_key("Balances", "TotalIssuance"), &11u128.encode()); - sp_io::storage::set(&storage_value_key("Balances", "CreationFee"), &1u128.encode()); - sp_io::storage::set(&storage_value_key("Balances", "TransferFee"), &1u128.encode()); - sp_io::storage::set( - &storage_value_key("Balances", "TransactionBaseFee"), - &1u128.encode(), - ); - sp_io::storage::set( - &storage_value_key("Balances", "TransactionByteFee"), - &1u128.encode(), - ); - sp_io::storage::set( - &storage_value_key("Balances", "ExistentialDeposit"), - &1u128.encode(), - ); - }); - - #[cfg(feature = "test")] - test_genesis_setup(&mut state); - - state.execute_with(|| { - sp_io::storage::set( - &storage_value_key("Sudo", ENCLAVE_ACCOUNT_KEY), - &enclave_account.encode(), - ); - - if let Err(e) = create_enclave_self_account::(enclave_account) { - error!("Failed to initialize the enclave signer account: {:?}", e); - } - }); - - trace!("Returning updated state: {:?}", state); - state - } -} - -impl - UpdateState::SgxExternalitiesDiffType> - for Stf -where - State: SgxExternalitiesTrait + Debug, - ::SgxExternalitiesType: core::default::Default, - ::SgxExternalitiesDiffType: - IntoIterator, Option>)>, -{ - fn apply_state_diff( - state: &mut State, - map_update: ::SgxExternalitiesDiffType, - ) { - state.execute_with(|| { - map_update.into_iter().for_each(|(k, v)| { - match v { - Some(value) => sp_io::storage::set(&k, &value), - None => sp_io::storage::clear(&k), - }; - }); - }); - } - - fn storage_hashes_to_update_on_block(parentchain_id: &ParentchainId) -> Vec> { - // Get all shards that are currently registered. - match parentchain_id { - ParentchainId::Litentry => vec![], // shards_key_hash() moved to stf_executor and is currently unused - ParentchainId::TargetA => vec![], - ParentchainId::TargetB => vec![], - } - } -} - -impl - StateCallInterface for Stf -where - TCS: PartialEq - + ExecuteCall - + Encode - + Decode - + Debug - + Clone - + Sync - + Send - + TrustedCallVerification, - State: SgxExternalitiesTrait + Debug, - NodeMetadataRepository: AccessNodeMetadata, - NodeMetadataRepository::MetadataType: NodeMetadataTrait, -{ - type Error = TCS::Error; - type Result = TCS::Result; - - fn execute_call( - state: &mut State, - shard: &ShardIdentifier, - call: TCS, - top_hash: H256, - calls: &mut Vec, - node_metadata_repo: Arc, - ) -> Result { - state.execute_with(|| call.execute(shard, top_hash, calls, node_metadata_repo)) - } -} - -impl StateGetterInterface for Stf -where - G: PartialEq + ExecuteGetter, - State: SgxExternalitiesTrait + Debug, -{ - fn execute_getter(state: &mut State, getter: G) -> Option> { - state.execute_with(|| getter.execute()) - } -} - -impl ShardCreationQuery for Stf -where - State: SgxExternalitiesTrait + Debug, -{ - fn get_shard_creation_info(state: &mut State) -> ShardCreationInfo { - state.execute_with(shard_creation_info) - } -} - -impl SudoPalletInterface for Stf -where - State: SgxExternalitiesTrait, - Runtime: frame_system::Config + pallet_sudo::Config, -{ - type AccountId = Runtime::AccountId; - - fn get_root(state: &mut State) -> Self::AccountId { - state.execute_with(|| pallet_sudo::Pallet::::key().expect("No root account")) - } - - fn get_enclave_account(state: &mut State) -> Self::AccountId { - state.execute_with(enclave_signer_account::) - } -} - -impl SystemPalletAccountInterface - for Stf -where - State: SgxExternalitiesTrait, - Runtime: frame_system::Config, - AccountId: Encode, -{ - type Index = Runtime::Index; - type AccountData = Runtime::AccountData; - - fn get_account_nonce(state: &mut State, account: &AccountId) -> Self::Index { - state.execute_with(|| { - let nonce = frame_system::Pallet::::account_nonce(account); - debug!("Account {} nonce is {:?}", account_id_to_string(account), nonce); - nonce - }) - } - - fn get_account_data(state: &mut State, account: &AccountId) -> Self::AccountData { - state.execute_with(|| frame_system::Pallet::::account(account).data) - } -} - -impl SystemPalletEventInterface for Stf -where - State: SgxExternalitiesTrait, - Runtime: frame_system::Config, -{ - type EventRecord = frame_system::EventRecord; - type EventIndex = u32; // For some reason this is not a pub type in frame_system - type BlockNumber = Runtime::BlockNumber; - type Hash = Runtime::Hash; - - fn get_events(state: &mut State) -> Vec> { - // Fixme: Not nice to have to call collect here, but we can't use impl Iterator<..> - // in trait method return types yet, see: - // https://rust-lang.github.io/impl-trait-initiative/RFCs/rpit-in-traits.html - state.execute_with(|| frame_system::Pallet::::read_events_no_consensus().collect()) - } - - fn get_event_count(state: &mut State) -> Self::EventIndex { - state.execute_with(|| frame_system::Pallet::::event_count()) - } - - fn get_event_topics( - state: &mut State, - topic: &Self::Hash, - ) -> Vec<(Self::BlockNumber, Self::EventIndex)> { - state.execute_with(|| frame_system::Pallet::::event_topics(topic)) - } - - fn reset_events(state: &mut State) { - state.execute_with(|| frame_system::Pallet::::reset_events()) - } -} - -impl - ParentchainPalletInstancesInterface for Stf -where - State: SgxExternalitiesTrait, - Runtime: frame_system::Config
- + pallet_parentchain::Config - + pallet_parentchain::Config - + pallet_parentchain::Config, - <::Lookup as StaticLookup>::Source: From, - ParentchainHeader: Debug, -{ - type Error = StfError; - - fn update_parentchain_litentry_block( - state: &mut State, - header: ParentchainHeader, - ) -> Result<(), Self::Error> { - trace!("updating litentry parentchain block : {:?}", header); - state.execute_with(|| { - pallet_parentchain::Call::::set_block { header } - .dispatch_bypass_filter(Runtime::RuntimeOrigin::root()) - .map_err(|e| { - Self::Error::Dispatch(format!( - "Update parentchain litentry block error: {:?}", - e.error - )) - }) - })?; - Ok(()) - } - - fn update_parentchain_target_a_block( - state: &mut State, - header: ParentchainHeader, - ) -> Result<(), Self::Error> { - trace!("updating target_a parentchain block: {:?}", header); - state.execute_with(|| { - pallet_parentchain::Call::::set_block { header } - .dispatch_bypass_filter(Runtime::RuntimeOrigin::root()) - .map_err(|e| { - Self::Error::Dispatch(format!( - "Update parentchain target_a block error: {:?}", - e.error - )) - }) - })?; - Ok(()) - } - - fn update_parentchain_target_b_block( - state: &mut State, - header: ParentchainHeader, - ) -> Result<(), Self::Error> { - trace!("updating target_b parentchain block: {:?}", header); - state.execute_with(|| { - pallet_parentchain::Call::::set_block { header } - .dispatch_bypass_filter(Runtime::RuntimeOrigin::root()) - .map_err(|e| { - Self::Error::Dispatch(format!( - "Update parentchain target_b block error: {:?}", - e.error - )) - }) - })?; - Ok(()) - } - - fn set_creation_block( - state: &mut State, - header: ParentchainHeader, - parentchain_id: ParentchainId, - ) -> Result<(), Self::Error> { - state.execute_with(|| match parentchain_id { - ParentchainId::Litentry => pallet_parentchain::Call::< - Runtime, - ParentchainInstanceLitentry, - >::set_creation_block { - header, - } - .dispatch_bypass_filter(Runtime::RuntimeOrigin::root()) - .map_err(|e| { - Self::Error::Dispatch(format!("Init shard vault account error: {:?}", e.error)) - }), - ParentchainId::TargetA => pallet_parentchain::Call::< - Runtime, - ParentchainInstanceTargetA, - >::set_creation_block { - header, - } - .dispatch_bypass_filter(Runtime::RuntimeOrigin::root()) - .map_err(|e| { - Self::Error::Dispatch(format!("Init shard vault account error: {:?}", e.error)) - }), - ParentchainId::TargetB => pallet_parentchain::Call::< - Runtime, - ParentchainInstanceTargetB, - >::set_creation_block { - header, - } - .dispatch_bypass_filter(Runtime::RuntimeOrigin::root()) - .map_err(|e| { - Self::Error::Dispatch(format!("Init shard vault account error: {:?}", e.error)) - }), - })?; - Ok(()) - } -} - -impl RuntimeUpgradeInterface for Stf -where - State: SgxExternalitiesTrait, - Runtime: frame_system::Config, -{ - type Error = StfError; - - fn on_runtime_upgrade(state: &mut State) -> Result<(), Self::Error> { - // Returns if the runtime was upgraded since the last time this function was called. - let runtime_upgraded = || -> bool { - let last = frame_system::LastRuntimeUpgrade::::get(); - let current = - <::Version as frame_support::traits::Get<_>>::get( - ); - - if last.as_ref().map(|v| v.was_upgraded(¤t)).unwrap_or(true) { - frame_system::LastRuntimeUpgrade::::put( - frame_system::LastRuntimeUpgradeInfo::from(current.clone()), - ); - debug!("Do some migrations, last: {:?}, current: {:?}", last, current.spec_version); - true - } else { - false - } - }; - - state.execute_with(|| { - if runtime_upgraded() { - Executive::execute_on_runtime_upgrade(); - } - }); - Ok(()) - } -} - -/// Creates valid enclave account with a balance that is above the existential deposit. -/// !! Requires a root to be set. -fn create_enclave_self_account( - enclave_account: AccountId, -) -> Result<(), StfError> -where - Runtime: frame_system::Config + pallet_balances::Config, - <::Lookup as StaticLookup>::Source: From, - Runtime::Balance: From, -{ - pallet_balances::Call::::force_set_balance { - who: enclave_account.into(), - new_free: 1000.into(), - } - .dispatch_bypass_filter(Runtime::RuntimeOrigin::root()) - .map_err(|e| { - StfError::Dispatch(format!("Set Balance for enclave signer account error: {:?}", e.error)) - }) - .map(|_| ()) -} diff --git a/tee-worker/bitacross/app-libs/stf/src/stf_sgx_primitives.rs b/tee-worker/bitacross/app-libs/stf/src/stf_sgx_primitives.rs deleted file mode 100644 index 5c2112d583..0000000000 --- a/tee-worker/bitacross/app-libs/stf/src/stf_sgx_primitives.rs +++ /dev/null @@ -1,29 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use std::marker::PhantomData; - -pub mod types { - pub use itp_types::{AccountData, AccountInfo, BlockNumber, Header as ParentchainHeader}; - pub type State = itp_sgx_externalities::SgxExternalities; - pub type StateType = itp_sgx_externalities::SgxExternalitiesType; - pub type StateDiffType = itp_sgx_externalities::SgxExternalitiesDiffType; -} - -pub struct Stf { - phantom_data: PhantomData<(TCS, G, State, Runtime)>, -} diff --git a/tee-worker/bitacross/app-libs/stf/src/stf_sgx_tests.rs b/tee-worker/bitacross/app-libs/stf/src/stf_sgx_tests.rs deleted file mode 100644 index 479f3b9bb0..0000000000 --- a/tee-worker/bitacross/app-libs/stf/src/stf_sgx_tests.rs +++ /dev/null @@ -1,84 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use crate::{Getter, State, Stf, TrustedCall, TrustedCallSigned}; -use ita_sgx_runtime::Runtime; -use itp_node_api::metadata::{metadata_mocks::NodeMetadataMock, provider::NodeMetadataRepository}; -use itp_stf_interface::{ - sudo_pallet::SudoPalletInterface, system_pallet::SystemPalletAccountInterface, InitState, - StateCallInterface, -}; -use itp_stf_primitives::types::{AccountId, ShardIdentifier}; -use itp_types::parentchain::ParentchainId; -use litentry_primitives::LitentryMultiSignature; -use sp_core::{ - ed25519::{Pair as Ed25519Pair, Signature as Ed25519Signature}, - Pair, -}; -use std::{sync::Arc, vec::Vec}; - -pub type StfState = Stf; - -pub fn enclave_account_initialization_works() { - let enclave_account = AccountId::new([2u8; 32]); - let mut state = StfState::init_state(enclave_account.clone()); - let _root = StfState::get_root(&mut state); - let account_data = StfState::get_account_data(&mut state, &enclave_account); - - assert_eq!(0, StfState::get_account_nonce(&mut state, &enclave_account)); - assert_eq!(enclave_account, StfState::get_enclave_account(&mut state)); - assert_eq!(1000, account_data.free); -} - -pub fn shield_funds_increments_signer_account_nonce() { - let enclave_call_signer = Ed25519Pair::from_seed(b"14672678901234567890123456789012"); - let enclave_signer_account_id: AccountId = enclave_call_signer.public().into(); - let mut state = StfState::init_state(enclave_signer_account_id.clone()); - - let shield_funds_call = TrustedCallSigned::new( - TrustedCall::balance_shield( - enclave_call_signer.public().into(), - AccountId::new([1u8; 32]), - 500u128, - ParentchainId::Litentry, - ), - 0, - LitentryMultiSignature::Ed25519(Ed25519Signature([0u8; 64])), - ); - - let repo = Arc::new(NodeMetadataRepository::new(NodeMetadataMock::new())); - let shard = ShardIdentifier::default(); - StfState::execute_call( - &mut state, - &shard, - shield_funds_call, - Default::default(), - &mut Vec::new(), - repo, - ) - .unwrap(); - assert_eq!(1, StfState::get_account_nonce(&mut state, &enclave_signer_account_id)); -} - -pub fn test_root_account_exists_after_initialization() { - let enclave_account = AccountId::new([2u8; 32]); - let mut state = StfState::init_state(enclave_account); - let root_account = StfState::get_root(&mut state); - - let account_data = StfState::get_account_data(&mut state, &root_account); - assert!(account_data.free > 0); -} diff --git a/tee-worker/bitacross/app-libs/stf/src/test_genesis.rs b/tee-worker/bitacross/app-libs/stf/src/test_genesis.rs deleted file mode 100644 index fd70e4cc72..0000000000 --- a/tee-worker/bitacross/app-libs/stf/src/test_genesis.rs +++ /dev/null @@ -1,95 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ -use frame_support::traits::UnfilteredDispatchable; -use ita_sgx_runtime::{Balance, Runtime, System}; -use itp_sgx_externalities::SgxExternalitiesTrait; -use itp_stf_primitives::error::StfError; -use itp_storage::storage_value_key; -use log::*; -use sgx_tstd as std; -use sp_core::{crypto::AccountId32, ed25519, Pair}; -use sp_runtime::MultiAddress; -use std::{format, vec, vec::Vec}; - -type Seed = [u8; 32]; - -const ALICE_ENCODED: Seed = [ - 212, 53, 147, 199, 21, 253, 211, 28, 97, 20, 26, 189, 4, 169, 159, 214, 130, 44, 133, 88, 133, - 76, 205, 227, 154, 86, 132, 231, 165, 109, 162, 125, -]; - -const ENDOWED_SEED: Seed = *b"12345678901234567890123456789012"; -const SECOND_ENDOWED_SEED: Seed = *b"22345678901234567890123456789012"; -const UNENDOWED_SEED: Seed = *b"92345678901234567890123456789012"; - -const ALICE_FUNDS: Balance = 10_000_000_000_000_000; -pub const ENDOWED_ACC_FUNDS: Balance = 2_000_000_000_000; -pub const SECOND_ENDOWED_ACC_FUNDS: Balance = 1_000_000_000_000; - -pub fn endowed_account() -> ed25519::Pair { - ed25519::Pair::from_seed(&ENDOWED_SEED) -} -pub fn second_endowed_account() -> ed25519::Pair { - ed25519::Pair::from_seed(&SECOND_ENDOWED_SEED) -} - -pub fn unendowed_account() -> ed25519::Pair { - ed25519::Pair::from_seed(&UNENDOWED_SEED) -} - -pub fn test_genesis_setup(state: &mut impl SgxExternalitiesTrait) { - // set alice sudo account - set_sudo_account(state, &ALICE_ENCODED); - trace!("Set new sudo account: {:?}", &ALICE_ENCODED); - - let endowees: Vec<(AccountId32, Balance)> = vec![ - (endowed_account().public().into(), ENDOWED_ACC_FUNDS), - (second_endowed_account().public().into(), SECOND_ENDOWED_ACC_FUNDS), - (ALICE_ENCODED.into(), ALICE_FUNDS), - ]; - - endow(state, endowees); -} - -fn set_sudo_account(state: &mut impl SgxExternalitiesTrait, account_encoded: &[u8]) { - state.execute_with(|| { - sp_io::storage::set(&storage_value_key("Sudo", "Key"), account_encoded); - }) -} - -pub fn endow( - state: &mut impl SgxExternalitiesTrait, - endowees: impl IntoIterator, -) { - state.execute_with(|| { - for e in endowees.into_iter() { - let account = e.0; - - ita_sgx_runtime::BalancesCall::::force_set_balance { - who: MultiAddress::Id(account.clone()), - new_free: e.1, - } - .dispatch_bypass_filter(ita_sgx_runtime::RuntimeOrigin::root()) - .map_err(|e| StfError::Dispatch(format!("Balance Set Balance error: {:?}", e.error))) - .unwrap(); - - let print_public: [u8; 32] = account.clone().into(); - let account_info = System::account(&&print_public.into()); - debug!("{:?} balance is {}", print_public, account_info.data.free); - } - }); -} diff --git a/tee-worker/bitacross/app-libs/stf/src/trusted_call.rs b/tee-worker/bitacross/app-libs/stf/src/trusted_call.rs deleted file mode 100644 index 173a5c4126..0000000000 --- a/tee-worker/bitacross/app-libs/stf/src/trusted_call.rs +++ /dev/null @@ -1,433 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use crate::{ - helpers::{enclave_signer_account, ensure_enclave_signer_account}, - trusted_call_result::TrustedCallResult, - Getter, -}; -use codec::{Decode, Encode}; -use frame_support::{ensure, traits::UnfilteredDispatchable}; -pub use ita_sgx_runtime::{Balance, Index, Runtime, System}; -use itp_node_api::metadata::{provider::AccessNodeMetadata, NodeMetadataTrait}; - -use itp_stf_interface::ExecuteCall; -use itp_stf_primitives::{ - error::StfError, - traits::{TrustedCallSigning, TrustedCallVerification}, - types::{AccountId, KeyPair, ShardIdentifier, TrustedOperation}, -}; -use itp_types::{ - parentchain::{ParentchainCall, ParentchainId}, - Moment, H256, -}; -use itp_utils::stringify::account_id_to_string; -pub use litentry_primitives::{ - aes_encrypt_default, AesOutput, Identity, LitentryMultiSignature, ParentchainBlockNumber, - RequestAesKey, ValidationData, -}; -use log::*; -use sp_core::{ - crypto::{AccountId32, UncheckedFrom}, - ed25519, -}; -use sp_io::hashing::blake2_256; -use sp_runtime::MultiAddress; -use std::{format, prelude::v1::*, sync::Arc}; - -#[derive(Encode, Decode, Clone, Debug, PartialEq, Eq)] -#[allow(non_camel_case_types)] -pub enum TrustedCall { - // original integritee trusted calls, starting from index 50 - #[codec(index = 50)] - noop(Identity), - #[codec(index = 51)] - balance_set_balance(Identity, AccountId, Balance, Balance), - #[codec(index = 52)] - balance_transfer(Identity, AccountId, Balance), - #[codec(index = 53)] - balance_unshield(Identity, AccountId, Balance, ShardIdentifier), // (AccountIncognito, BeneficiaryPublicAccount, Amount, Shard) - #[codec(index = 54)] - balance_shield(Identity, AccountId, Balance, ParentchainId), // (Root, AccountIncognito, Amount, origin parentchain) - #[codec(index = 55)] - timestamp_set(Identity, Moment, ParentchainId), -} - -impl TrustedCall { - pub fn sender_identity(&self) -> &Identity { - match self { - Self::noop(sender_identity) => sender_identity, - Self::balance_set_balance(sender_identity, ..) => sender_identity, - Self::balance_transfer(sender_identity, ..) => sender_identity, - Self::balance_unshield(sender_identity, ..) => sender_identity, - Self::balance_shield(sender_identity, ..) => sender_identity, - Self::timestamp_set(sender_identity, ..) => sender_identity, - } - } -} - -impl TrustedCallSigning for TrustedCall { - fn sign( - &self, - pair: &KeyPair, - nonce: Index, - mrenclave: &[u8; 32], - shard: &ShardIdentifier, - ) -> TrustedCallSigned { - let mut payload = self.encode(); - payload.append(&mut nonce.encode()); - payload.append(&mut mrenclave.encode()); - payload.append(&mut shard.encode()); - - // use blake2_256 hash to shorten the payload - see `verify_signature` below - TrustedCallSigned { call: self.clone(), nonce, signature: pair.sign(&blake2_256(&payload)) } - } -} - -#[derive(Encode, Decode, Clone, Debug, PartialEq, Eq)] -pub struct TrustedCallSigned { - pub call: TrustedCall, - pub nonce: Index, - pub signature: LitentryMultiSignature, -} - -impl TrustedCallSigned { - pub fn new(call: TrustedCall, nonce: Index, signature: LitentryMultiSignature) -> Self { - TrustedCallSigned { call, nonce, signature } - } - - pub fn into_trusted_operation( - self, - direct: bool, - ) -> TrustedOperation { - match direct { - true => TrustedOperation::direct_call(self), - false => TrustedOperation::indirect_call(self), - } - } -} - -impl Default for TrustedCallSigned { - fn default() -> Self { - Self { - call: TrustedCall::noop(AccountId32::unchecked_from([0u8; 32].into()).into()), - nonce: 0, - signature: LitentryMultiSignature::Ed25519(ed25519::Signature::unchecked_from( - [0u8; 64], - )), - } - } -} -impl TrustedCallVerification for TrustedCallSigned { - fn sender_identity(&self) -> &Identity { - self.call.sender_identity() - } - - fn nonce(&self) -> Index { - self.nonce - } - - fn verify_signature(&self, mrenclave: &[u8; 32], shard: &ShardIdentifier) -> bool { - let mut payload = self.call.encode(); - payload.append(&mut self.nonce.encode()); - payload.append(&mut mrenclave.encode()); - payload.append(&mut shard.encode()); - - self.signature.verify(&blake2_256(&payload), self.call.sender_identity()) - || self.signature.verify(&payload, self.call.sender_identity()) - } - - fn metric_name(&self) -> &'static str { - "unsupported_trusted_call" - } -} - -impl ExecuteCall for TrustedCallSigned -where - NodeMetadataRepository: AccessNodeMetadata, - NodeMetadataRepository::MetadataType: NodeMetadataTrait, -{ - type Error = StfError; - type Result = TrustedCallResult; - - // TODO(Kai@litentry): - // If this function returns Err(), it will feed the executor with Ok(ExecutedOperation::failed()), - // which will remove the failed op from its **own** top pool while preventing it from being included - // in a sidechain block - see `execute_trusted_call_on_stf`. - // - // As a result, when other workers import sidechain blocks, they will treat the op as - // "not yet executed" (before it's not recorded in the sidechain block) and try to execute it again from - // its own top pool (if the op is added to the top pool upon e.g. parentchain block import). - // - // The execution will most likely fail again. However, the state could have been changed already by applying - // the state diff from the imported sidechain block. This could cause an inconsistent/mismatching state, - // for example, the nonce. See the nonce handling below: we increased the nonce no matter the STF is executed - // successfully or not. - // - // This is probably the reason why the nonce-handling test in `demo_shielding_unshielding.sh` sometimes fails. - // - // Update: - // see discussion in https://github.com/integritee-network/worker/issues/1232 - // my current thoughts are: - // - we should return Err() if the STF execution fails, the parentchain effect will get applied regardless - // - the failed top should be removed from the pool - // - however, the failed top hash needs to be included in the sidechain block (still TODO) - // - // Almost every (Litentry) trusted call has a `H256` as parameter, this is used as the request identifier. - // It should be generated by the client (requester), and checked against when getting the response. - // It might seem redundant for direct invocation (DI) as the response is synchronous, however, we do need it - // when the request is handled asynchronously interanlly, which leads to streamed responses. Without it, it's - // impossible to pair the request and response. `top_hash` won't suffice as you can't know all hashes from - // client side beforehand (e.g. those trusted calls signed by enclave signer). - // - // TODO: - // - shall we add `req_ext_hash` in RpcReturnValue and use it to find streamed trustedCalls? - // - show error details for "Invalid" synchronous responses - fn execute( - self, - _shard: &ShardIdentifier, - _top_hash: H256, - _calls: &mut Vec, - _node_metadata_repo: Arc, - ) -> Result { - let sender = self.call.sender_identity().clone(); - let account_id: AccountId = - sender.to_native_account().ok_or(Self::Error::InvalidAccount)?; - let system_nonce = System::account_nonce(&account_id); - ensure!(self.nonce == system_nonce, Self::Error::InvalidNonce(self.nonce, system_nonce)); - - // Increment the nonce no matter if the call succeeds or fails. - // We consider the call "valid" once it reaches here (= it entered the tx pool) - System::inc_account_nonce(&account_id); - - // TODO: maybe we can further simplify this by effacing the duplicate code - match self.call { - TrustedCall::noop(who) => { - debug!("noop called by {}", account_id_to_string(&who),); - Ok(TrustedCallResult::Empty) - }, - TrustedCall::balance_set_balance(root, who, free_balance, reserved_balance) => { - let root_account_id: AccountId = - root.to_native_account().ok_or(Self::Error::InvalidAccount)?; - ensure!( - is_root::(&root_account_id), - Self::Error::MissingPrivileges(root_account_id) - ); - debug!( - "balance_set_balance({}, {}, {})", - account_id_to_string(&who), - free_balance, - reserved_balance - ); - ita_sgx_runtime::BalancesCall::::force_set_balance { - who: MultiAddress::Id(who), - new_free: free_balance, - } - .dispatch_bypass_filter(ita_sgx_runtime::RuntimeOrigin::root()) - .map_err(|e| { - Self::Error::Dispatch(format!("Balance Set Balance error: {:?}", e.error)) - })?; - // This explicit Error type is somehow still needed, otherwise the compiler complains - // multiple `impl`s satisfying `StfError: std::convert::From<_>` - // note: and another `impl` found in the `core` crate: `impl std::convert::From for T;` - // the impl From<..> for StfError conflicts with the standard convert - // - // Alternatively, removing the customised "impl From<..> for StfError" and use map_err directly - // would also work - Ok(TrustedCallResult::Empty) - }, - TrustedCall::balance_transfer(from, to, value) => { - let origin = ita_sgx_runtime::RuntimeOrigin::signed( - from.to_native_account().ok_or(Self::Error::InvalidAccount)?, - ); - std::println!("⣿STF⣿ 🔄 balance_transfer from ⣿⣿⣿ to ⣿⣿⣿ amount ⣿⣿⣿"); - // endow fee to enclave (self) - let fee_recipient: AccountId = enclave_signer_account(); - // fixme: apply fees through standard frame process and tune it - let fee = crate::STF_TX_FEE; - info!( - "from {}, to {}, amount {}, fee {}", - account_id_to_string(&from), - account_id_to_string(&to), - value, - fee - ); - ita_sgx_runtime::BalancesCall::::transfer { - dest: MultiAddress::Id(fee_recipient), - value: fee, - } - .dispatch_bypass_filter(origin.clone()) - .map_err(|e| { - Self::Error::Dispatch(format!("Balance Transfer error: {:?}", e.error)) - })?; - ita_sgx_runtime::BalancesCall::::transfer { - dest: MultiAddress::Id(to), - value, - } - .dispatch_bypass_filter(origin) - .map_err(|e| { - Self::Error::Dispatch(format!("Balance Transfer error: {:?}", e.error)) - })?; - Ok(TrustedCallResult::Empty) - }, - TrustedCall::balance_unshield(account_incognito, beneficiary, value, shard) => { - std::println!( - "⣿STF⣿ 🛡👐 balance_unshield from ⣿⣿⣿ to {}, amount {}", - account_id_to_string(&beneficiary), - value - ); - // endow fee to enclave (self) - let fee_recipient: AccountId = enclave_signer_account(); - // fixme: apply fees through standard frame process and tune it. has to be at least two L1 transfer's fees - let fee = crate::STF_TX_FEE * 3; - - info!( - "balance_unshield(from (L2): {}, to (L1): {}, amount {} (+fee: {}), shard {})", - account_id_to_string(&account_incognito), - account_id_to_string(&beneficiary), - value, - fee, - shard - ); - - let origin = ita_sgx_runtime::RuntimeOrigin::signed( - account_incognito.to_native_account().ok_or(StfError::InvalidAccount)?, - ); - ita_sgx_runtime::BalancesCall::::transfer { - dest: MultiAddress::Id(fee_recipient), - value: fee, - } - .dispatch_bypass_filter(origin) - .map_err(|e| { - Self::Error::Dispatch(format!("Balance Unshielding error: {:?}", e.error)) - })?; - burn_funds( - account_incognito.to_native_account().ok_or(StfError::InvalidAccount)?, - value, - )?; - Ok(TrustedCallResult::Empty) - }, - TrustedCall::balance_shield(enclave_account, who, value, parentchain_id) => { - let account_id: AccountId32 = - enclave_account.to_native_account().ok_or(Self::Error::InvalidAccount)?; - ensure_enclave_signer_account(&account_id)?; - debug!( - "balance_shield({}, {}, {:?})", - account_id_to_string(&who), - value, - parentchain_id - ); - std::println!("⣿STF⣿ 🛡 will shield to {}", account_id_to_string(&who)); - shield_funds(who, value)?; - - Ok(TrustedCallResult::Empty) - }, - TrustedCall::timestamp_set(enclave_account, now, parentchain_id) => { - let account_id: AccountId32 = - enclave_account.to_native_account().ok_or(Self::Error::InvalidAccount)?; - ensure_enclave_signer_account(&account_id)?; - // Litentry: we don't actually set the timestamp, see `BlockMetadata` - warn!("unused timestamp_set({}, {:?})", now, parentchain_id); - Ok(TrustedCallResult::Empty) - }, - } - } - - fn get_storage_hashes_to_update(self) -> Vec> { - debug!("No storage updates needed..."); - Vec::new() - } -} - -fn burn_funds(account: AccountId, amount: u128) -> Result<(), StfError> { - let account_info = System::account(&account); - if account_info.data.free < amount { - return Err(StfError::MissingFunds) - } - - ita_sgx_runtime::BalancesCall::::force_set_balance { - who: MultiAddress::Id(account), - new_free: account_info.data.free - amount, - } - .dispatch_bypass_filter(ita_sgx_runtime::RuntimeOrigin::root()) - .map_err(|e| StfError::Dispatch(format!("Burn funds error: {:?}", e.error)))?; - Ok(()) -} - -fn shield_funds(account: AccountId, amount: u128) -> Result<(), StfError> { - //fixme: make fee configurable and send fee to vault account on L2 - let fee = amount / 571; // approx 0.175% - - // endow fee to enclave (self) - let fee_recipient: AccountId = enclave_signer_account(); - - let account_info = System::account(&fee_recipient); - ita_sgx_runtime::BalancesCall::::force_set_balance { - who: MultiAddress::Id(fee_recipient), - new_free: account_info.data.free + fee, - } - .dispatch_bypass_filter(ita_sgx_runtime::RuntimeOrigin::root()) - .map_err(|e| StfError::Dispatch(format!("Shield funds error: {:?}", e.error)))?; - - // endow shieding amount - fee to beneficiary - let account_info = System::account(&account); - ita_sgx_runtime::BalancesCall::::force_set_balance { - who: MultiAddress::Id(account), - new_free: account_info.data.free + amount - fee, - } - .dispatch_bypass_filter(ita_sgx_runtime::RuntimeOrigin::root()) - .map_err(|e| StfError::Dispatch(format!("Shield funds error: {:?}", e.error)))?; - - Ok(()) -} - -pub(crate) fn is_root(account: &AccountId) -> bool -where - Runtime: frame_system::Config + pallet_sudo::Config, - AccountId: PartialEq, -{ - pallet_sudo::Pallet::::key().map_or(false, |k| account == &k) -} - -#[cfg(test)] -mod tests { - use super::*; - use itp_stf_primitives::types::KeyPair; - use sp_keyring::AccountKeyring; - - #[test] - fn verify_signature_works() { - let nonce = 21; - let mrenclave = [0u8; 32]; - let shard = ShardIdentifier::default(); - - let call = TrustedCall::balance_set_balance( - AccountKeyring::Alice.public().into(), - AccountKeyring::Alice.public().into(), - 42, - 42, - ); - let signed_call = call.sign( - &KeyPair::Sr25519(Box::new(AccountKeyring::Alice.pair())), - nonce, - &mrenclave, - &shard, - ); - - assert!(signed_call.verify_signature(&mrenclave, &shard)); - } -} diff --git a/tee-worker/bitacross/app-libs/stf/src/trusted_call_result.rs b/tee-worker/bitacross/app-libs/stf/src/trusted_call_result.rs deleted file mode 100644 index 60e303ce3b..0000000000 --- a/tee-worker/bitacross/app-libs/stf/src/trusted_call_result.rs +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright 2020-2024 Trust Computing GmbH. -// This file is part of Litentry. -// -// Litentry is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// Litentry is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with Litentry. If not, see . - -// This file contain the RPC response struct which will be encoded and -// passed back to the requester of trustedCall direct invocation (DI). - -use codec::{Decode, Encode}; -use itp_stf_interface::StfExecutionResult; -use std::vec::Vec; - -#[derive(Encode, Decode, Debug)] -pub enum TrustedCallResult { - #[codec(index = 0)] - Empty, - #[codec(index = 1)] - Streamed, -} - -impl StfExecutionResult for TrustedCallResult { - fn get_encoded_result(self) -> Vec { - match self { - Self::Empty => Vec::default(), - Self::Streamed => Vec::default(), - } - } - - fn force_connection_wait(&self) -> bool { - matches!(self, Self::Streamed) - } -} diff --git a/tee-worker/bitacross/assets/teebag_registry.gif b/tee-worker/bitacross/assets/teebag_registry.gif deleted file mode 100644 index b337fb6c3a..0000000000 Binary files a/tee-worker/bitacross/assets/teebag_registry.gif and /dev/null differ diff --git a/tee-worker/bitacross/bin/README.md b/tee-worker/bitacross/bin/README.md deleted file mode 100644 index 9cf10b5eb8..0000000000 --- a/tee-worker/bitacross/bin/README.md +++ /dev/null @@ -1 +0,0 @@ -Output directory for the binaries \ No newline at end of file diff --git a/tee-worker/bitacross/bitacross/core/bc-enclave-registry/Cargo.toml b/tee-worker/bitacross/bitacross/core/bc-enclave-registry/Cargo.toml deleted file mode 100644 index f9fdf7f312..0000000000 --- a/tee-worker/bitacross/bitacross/core/bc-enclave-registry/Cargo.toml +++ /dev/null @@ -1,39 +0,0 @@ -[package] -name = "bc-enclave-registry" -authors = ["Trust Computing GmbH "] -version = "0.1.0" -edition = "2021" - -[dependencies] -codec = { package = "parity-scale-codec", workspace = true } -log = { workspace = true } -sp-std = { workspace = true } - -sgx_tstd = { workspace = true, features = ["net", "thread"], optional = true } - -thiserror = { workspace = true, optional = true } -thiserror_sgx = { workspace = true, optional = true } - -itp-settings = { workspace = true } -itp-sgx-io = { workspace = true } -litentry-primitives = { workspace = true } - -[dev-dependencies] -base64 = { workspace = true, features = ["alloc"] } - -[features] -default = ["std"] -production = [] -sgx = [ - "sgx_tstd", - "thiserror_sgx", - "itp-sgx-io/sgx", - "litentry-primitives/sgx", -] -std = [ - "sp-std/std", - "log/std", - "thiserror", - "itp-sgx-io/std", - "litentry-primitives/std", -] diff --git a/tee-worker/bitacross/bitacross/core/bc-enclave-registry/src/lib.rs b/tee-worker/bitacross/bitacross/core/bc-enclave-registry/src/lib.rs deleted file mode 100644 index b08c7b65c4..0000000000 --- a/tee-worker/bitacross/bitacross/core/bc-enclave-registry/src/lib.rs +++ /dev/null @@ -1,246 +0,0 @@ -// Copyright 2020-2024 Trust Computing GmbH. -// This file is part of Litentry. -// -// Litentry is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// Litentry is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with Litentry. If not, see . - -#![cfg_attr(not(feature = "std"), no_std)] - -extern crate core; -#[cfg(all(not(feature = "std"), feature = "sgx"))] -extern crate sgx_tstd as std; - -#[cfg(all(feature = "std", feature = "sgx"))] -compile_error!("feature \"std\" and feature \"sgx\" cannot be enabled at the same time"); - -use sp_std::{boxed::Box, fmt::Debug}; - -use log::error; -use std::{collections::BTreeMap, error::Error, path::PathBuf, string::String, vec::Vec}; - -#[cfg(feature = "std")] -use std::sync::RwLock; -#[cfg(feature = "sgx")] -use std::sync::SgxRwLock as RwLock; - -pub type EnclaveRegistryMap = BTreeMap; - -#[derive(Default)] -pub struct EnclaveRegistry { - pub registry: RwLock, - pub seal_path: PathBuf, -} - -impl EnclaveRegistry { - pub fn new(base_dir: PathBuf) -> Self { - EnclaveRegistry { registry: Default::default(), seal_path: base_dir } - } -} - -pub type RegistryResult = Result; - -use litentry_primitives::Address32; -#[cfg(feature = "sgx")] -use thiserror_sgx as thiserror; - -#[derive(Debug, thiserror::Error)] -pub enum RegistryError { - #[error("poison lock")] - PoisonLock, - #[error("empty Enclave registry")] - EmptyRegistry, - #[error(transparent)] - Other(#[from] Box), -} - -impl From for RegistryError { - fn from(e: std::io::Error) -> Self { - Self::Other(e.into()) - } -} - -impl From for RegistryError { - #[cfg(feature = "std")] - fn from(e: codec::Error) -> Self { - Self::Other(e.into()) - } - - #[cfg(feature = "sgx")] - fn from(e: codec::Error) -> Self { - Self::Other(std::format!("{:?}", e).into()) - } -} - -#[cfg(feature = "sgx")] -mod sgx { - use crate::{EnclaveRegistryMap, RegistryError as Error, RegistryResult as Result}; - pub use codec::{Decode, Encode}; - pub use itp_settings::files::ENCLAVE_REGISTRY_FILE; - pub use itp_sgx_io::{seal, unseal, SealedIO}; - pub use log::*; - pub use std::{boxed::Box, fs, path::PathBuf, sgxfs::SgxFile, sync::Arc}; - - #[derive(Clone, Debug)] - pub struct EnclaveRegistrySeal { - base_path: PathBuf, - } - - impl EnclaveRegistrySeal { - pub fn new(base_path: PathBuf) -> Self { - Self { base_path } - } - - pub fn path(&self) -> PathBuf { - self.base_path.join(ENCLAVE_REGISTRY_FILE) - } - } - - impl SealedIO for EnclaveRegistrySeal { - type Error = Error; - type Unsealed = EnclaveRegistryMap; - - fn unseal(&self) -> Result { - Ok(unseal(self.path()).map(|b| Decode::decode(&mut b.as_slice()))??) - } - - fn seal(&self, unsealed: &Self::Unsealed) -> Result<()> { - info!("Seal enclave registry to file: {:?}", unsealed); - Ok(unsealed.using_encoded(|bytes| seal(bytes, self.path()))?) - } - } -} - -#[cfg(feature = "sgx")] -use sgx::*; - -pub trait EnclaveRegistrySealer { - fn seal(&self, state: EnclaveRegistryMap) -> RegistryResult<()>; - fn unseal(&self) -> RegistryResult; -} - -pub trait EnclaveRegistryUpdater { - fn init(&self) -> RegistryResult<()>; - fn update(&self, account: Address32, worker_url: String) -> RegistryResult<()>; - fn remove(&self, account: Address32) -> RegistryResult<()>; -} - -pub trait EnclaveRegistryLookup { - fn contains_key(&self, account: &Address32) -> bool; - fn get_all(&self) -> Vec<(Address32, String)>; - fn get_worker_url(&self, account: &Address32) -> Option; -} - -impl EnclaveRegistrySealer for EnclaveRegistry { - #[cfg(feature = "std")] - fn seal(&self, _state: EnclaveRegistryMap) -> RegistryResult<()> { - Ok(()) - } - - #[cfg(feature = "std")] - fn unseal(&self) -> RegistryResult { - Ok(Default::default()) - } - - #[cfg(feature = "sgx")] - fn seal(&self, mut state: EnclaveRegistryMap) -> RegistryResult<()> { - let mut registry = self.registry.write().map_err(|_| RegistryError::PoisonLock)?; - while let Some((key, val)) = state.pop_first() { - registry.insert(key, val); - } - - let enclave_seal = EnclaveRegistrySeal::new(self.seal_path.clone()); - enclave_seal.seal(®istry) - } - - #[cfg(feature = "sgx")] - fn unseal(&self) -> RegistryResult { - let enclave_seal = EnclaveRegistrySeal::new(self.seal_path.clone()); - enclave_seal.unseal() - } -} - -impl EnclaveRegistryUpdater for EnclaveRegistry { - #[cfg(feature = "std")] - fn init(&self) -> RegistryResult<()> { - Ok(()) - } - - #[cfg(feature = "std")] - fn update(&self, account: Address32, worker_url: String) -> RegistryResult<()> { - let mut registry = self.registry.write().unwrap(); - registry.insert(account, worker_url); - Ok(()) - } - - #[cfg(feature = "std")] - fn remove(&self, _account: Address32) -> RegistryResult<()> { - Ok(()) - } - - // if `ENCLAVE_REGISTRY_FILE` exists, unseal and init from it - // otherwise create a new instance and seal to static file - #[cfg(feature = "sgx")] - fn init(&self) -> RegistryResult<()> { - let enclave_seal = EnclaveRegistrySeal::new(self.seal_path.clone()); - if SgxFile::open(ENCLAVE_REGISTRY_FILE).is_err() { - info!( - "[Enclave] EnclaveRegistry file not found, creating new! {}", - ENCLAVE_REGISTRY_FILE - ); - let registry = self.registry.write().map_err(|_| RegistryError::PoisonLock)?; - enclave_seal.seal(&*registry) - } else { - let m = enclave_seal.unseal()?; - info!("[Enclave] EnclaveRegistry unsealed from file: {:?}", m); - let mut registry = self.registry.write().map_err(|_| RegistryError::PoisonLock)?; - *registry = m; - Ok(()) - } - } - - #[cfg(feature = "sgx")] - fn update(&self, account: Address32, worker_url: String) -> RegistryResult<()> { - let mut registry = self.registry.write().map_err(|_| RegistryError::PoisonLock)?; - registry.insert(account, worker_url); - EnclaveRegistrySeal::new(self.seal_path.clone()).seal(&*registry) - } - - #[cfg(feature = "sgx")] - fn remove(&self, account: Address32) -> RegistryResult<()> { - let mut registry = self.registry.write().map_err(|_| RegistryError::PoisonLock)?; - let old_value = registry.remove(&account); - if old_value.is_some() { - return EnclaveRegistrySeal::new(self.seal_path.clone()).seal(&*registry) - } - Ok(()) - } -} - -impl EnclaveRegistryLookup for EnclaveRegistry { - fn get_all(&self) -> Vec<(Address32, String)> { - let registry = self.registry.read().unwrap(); - registry.iter().map(|(k, v)| (*k, v.clone())).collect() - } - - fn contains_key(&self, account: &Address32) -> bool { - // Using unwrap becaused poisoned locks are unrecoverable errors - let registry = self.registry.read().unwrap(); - registry.contains_key(account) - } - - fn get_worker_url(&self, account: &Address32) -> Option { - // Using unwrap becaused poisoned locks are unrecoverable errors - let registry = self.registry.read().unwrap(); - registry.get(account).cloned() - } -} diff --git a/tee-worker/bitacross/bitacross/core/bc-musig2-ceremony/Cargo.toml b/tee-worker/bitacross/bitacross/core/bc-musig2-ceremony/Cargo.toml deleted file mode 100644 index 352e059c92..0000000000 --- a/tee-worker/bitacross/bitacross/core/bc-musig2-ceremony/Cargo.toml +++ /dev/null @@ -1,43 +0,0 @@ -[package] -name = "bc-musig2-ceremony" -authors = ["Trust Computing GmbH "] -version = "0.1.0" -edition = "2021" - -[dependencies] -musig2 = { workspace = true, optional = true } -rand = { version = "0.8.5", optional = true } - -# sgx dependencies -musig2_sgx = { workspace = true, optional = true } -sgx_rand = { workspace = true, optional = true } -sgx_tstd = { workspace = true, features = ["net", "thread"], optional = true } - -codec = { package = "parity-scale-codec", workspace = true } -k256 = { workspace = true, features = ["ecdsa-core", "schnorr", "alloc"] } -log = { workspace = true } - -itp-sgx-crypto = { workspace = true } -litentry-primitives = { workspace = true } - -[dev-dependencies] -rand = { version = "0.8.5" } -signature = "2.1.0" - -[features] -default = ["std"] -sgx-test = ["sgx"] -std = [ - "musig2", - "log/std", - "litentry-primitives/std", - "itp-sgx-crypto/std", - "rand", -] -sgx = [ - "sgx_tstd", - "musig2_sgx", - "litentry-primitives/sgx", - "itp-sgx-crypto/sgx", - "sgx_rand", -] diff --git a/tee-worker/bitacross/bitacross/core/bc-musig2-ceremony/src/lib.rs b/tee-worker/bitacross/bitacross/core/bc-musig2-ceremony/src/lib.rs deleted file mode 100644 index f30563f526..0000000000 --- a/tee-worker/bitacross/bitacross/core/bc-musig2-ceremony/src/lib.rs +++ /dev/null @@ -1,807 +0,0 @@ -// Copyright 2020-2024 Trust Computing GmbH. -// This file is part of Litentry. -// -// Litentry is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// Litentry is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with Litentry. If not, see . - -#![cfg_attr(not(feature = "std"), no_std)] - -extern crate alloc; -extern crate core; -#[cfg(all(not(feature = "std"), feature = "sgx"))] -extern crate sgx_tstd as std; - -#[cfg(all(not(feature = "std"), feature = "sgx"))] -use musig2_sgx as musig2; -use std::{format, string::String, sync::Arc}; - -#[cfg(all(feature = "std", feature = "sgx"))] -compile_error!("feature \"std\" and feature \"sgx\" cannot be enabled at the same time"); - -#[cfg(feature = "std")] -use std::sync::RwLock; - -#[cfg(feature = "sgx")] -use std::sync::SgxRwLock as RwLock; - -use codec::{Decode, Encode}; -use itp_sgx_crypto::{key_repository::AccessKey, schnorr::Pair as SchnorrPair}; -use k256::SecretKey; -pub use k256::{elliptic_curve::sec1::FromEncodedPoint, PublicKey}; -use log::*; -use musig2::{ - secp::{Point, Scalar}, - verify_single, BinaryEncoding, CompactSignature, KeyAggContext, LiftedSignature, - SecNonceSpices, -}; -pub use musig2::{PartialSignature, PubNonce}; -use std::{ - collections::HashMap, - time::{SystemTime, UNIX_EPOCH}, - vec, - vec::Vec, -}; - -pub type CeremonyId = SignBitcoinPayload; -pub type SignaturePayload = Vec; -pub type Signers = Vec; -pub type CeremonyRegistry = HashMap>>, u64)>; -pub type CeremonyCommandTmp = HashMap>>, u64)>; -// enclave public key is used as signer identifier -pub type SignerId = [u8; 32]; -pub type SignersWithKeys = Vec<(SignerId, PublicKey)>; - -#[derive(Debug, Eq, PartialEq, Encode)] -pub enum CeremonyError { - CeremonyInitError(CeremonyErrorReason), - NonceReceivingError(CeremonyErrorReason), - PartialSignatureReceivingError(CeremonyErrorReason), -} - -#[derive(Debug, Eq, PartialEq, Encode)] -pub enum CeremonyErrorReason { - AlreadyExist, - CreateCeremonyError, - SignerNotFound, - ContributionError, - IncorrectRound, - RoundFinalizationError, -} - -#[derive(Debug, PartialEq, Eq, Clone)] -pub enum CeremonyCommand { - InitCeremony(SignersWithKeys, SignBitcoinPayload, bool), - SaveNonce(SignerId, PubNonce), - SavePartialSignature(SignerId, PartialSignature), - KillCeremony, -} - -// events are created by ceremony and executed by runner -#[derive(Debug, Eq, PartialEq)] -pub enum CeremonyEvent { - FirstRoundStarted(Signers, CeremonyId, PubNonce), - SecondRoundStarted(Signers, CeremonyId, PartialSignature), - CeremonyEnded([u8; 64], bool, bool), - CeremonyError(Signers, CeremonyError), -} - -#[derive(Encode, Decode, Clone, Debug, PartialEq, Eq, Hash)] -pub enum SignBitcoinPayload { - Derived(SignaturePayload), - TaprootUnspendable(SignaturePayload), - TaprootSpendable(SignaturePayload, [u8; 32]), - WithTweaks(SignaturePayload, Vec<([u8; 32], bool)>), -} - -pub fn generate_aggregated_public_key(mut public_keys: Vec) -> PublicKey { - public_keys.sort(); - KeyAggContext::new(public_keys).unwrap().aggregated_pubkey() -} - -pub struct MuSig2CeremonyData> { - payload: SignBitcoinPayload, - me: SignerId, - signers: SignersWithKeys, - signing_key_access: Arc, - agg_key: PublicKey, - // indicates whether it's check run - signature verification result is returned instead of signature - check_run: bool, -} - -pub struct MuSig2CeremonyState { - first_round: Option, - second_round: Option>, -} - -pub struct MuSig2Ceremony> { - ceremony_data: MuSig2CeremonyData, - ceremony_state: MuSig2CeremonyState, -} - -impl> MuSig2Ceremony { - // Creates new ceremony - pub fn new( - me: SignerId, - mut signers: SignersWithKeys, - payload: SignBitcoinPayload, - signing_key_access: Arc, - check_run: bool, - ) -> Result<(Self, CeremonyEvent), String> { - info!("Creating new ceremony {:?}", payload); - if signers.len() < 3 { - return Err(format!("Not enough signers, minimum: {:?}, actual {:?}", 3, signers.len())) - } - - signers.sort_by_key(|k| k.1); - // we are always the first key in the vector - let my_index = signers.iter().position(|r| r.0 == me).ok_or("Could not determine index")?; - let all_keys = signers.iter().map(|p| p.1).collect::>(); - let key_context = match &payload { - SignBitcoinPayload::TaprootSpendable(_, root_hash) => - KeyAggContext::new(all_keys.iter().map(|p| Point::from(*p))) - .map_err(|e| format!("Key context creation error: {:?}", e))? - .with_taproot_tweak(root_hash) - .map_err(|e| format!("Key context creation error: {:?}", e))?, - SignBitcoinPayload::TaprootUnspendable(_) => - KeyAggContext::new(all_keys.iter().map(|p| Point::from(*p))) - .map_err(|e| format!("Key context creation error: {:?}", e))? - .with_unspendable_taproot_tweak() - .map_err(|e| format!("Key context creation error: {:?}", e))?, - SignBitcoinPayload::Derived(_) => - KeyAggContext::new(all_keys.iter().map(|p| Point::from(*p))) - .map_err(|e| format!("Key context creation error: {:?}", e))?, - SignBitcoinPayload::WithTweaks(_, tweaks) => { - let mut prepared_tweaks = vec![]; - for (tweak_bytes, is_x_only) in tweaks.iter() { - let scalar: Scalar = tweak_bytes.try_into().map_err(|e| { - format!("Key context creation error, could not parse scalar: {:?}", e) - })?; - prepared_tweaks.push((scalar, *is_x_only)); - } - KeyAggContext::new(all_keys.iter().map(|p| Point::from(*p))) - .map_err(|e| format!("Key context creation error: {:?}", e))? - .with_tweaks(prepared_tweaks) - .map_err(|e| format!("Key context creation error: {:?}", e))? - }, - }; - - info!( - "Ceremony aggregated public key: {:?}", - key_context.aggregated_pubkey::().to_sec1_bytes().to_vec() - ); - let agg_key = key_context.aggregated_pubkey::(); - let nonce_seed = random_seed(); - let first_round = - musig2::FirstRound::new(key_context, nonce_seed, my_index, SecNonceSpices::new()) - .map_err(|e| format!("First round creation error: {:?}", e))?; - - let ceremony = Self { - ceremony_data: MuSig2CeremonyData { - payload, - me, - signers, - signing_key_access, - agg_key, - check_run, - }, - ceremony_state: MuSig2CeremonyState { - first_round: Some(first_round), - second_round: None, - }, - }; - let event = ceremony.start_first_round(); - Ok((ceremony, event)) - } - - fn start_first_round(&self) -> CeremonyEvent { - self.ceremony_state - .first_round - .as_ref() - .map(|f| { - CeremonyEvent::FirstRoundStarted( - self.get_signers_except_self(), - self.ceremony_data.payload.clone(), - f.our_public_nonce(), - ) - }) - .unwrap() - } - - // Saves signer's nonce - pub fn receive_nonce( - &mut self, - signer: SignerId, - nonce: PubNonce, - ) -> Result, CeremonyError> { - info!("Saving nonce from signer: {:?}", signer); - let peer_index = self - .ceremony_data - .signers - .iter() - .position(|p| p.0 == signer) - .ok_or(CeremonyError::NonceReceivingError(CeremonyErrorReason::SignerNotFound))?; - - if let Some(ref mut r) = self.ceremony_state.first_round { - r.receive_nonce(peer_index, nonce).map_err(|e| { - error!("Nonce receiving error: {:?}", e); - CeremonyError::NonceReceivingError(CeremonyErrorReason::ContributionError) - })?; - if r.is_complete() { - let secret_key = SecretKey::from_slice( - &self - .ceremony_data - .signing_key_access - .retrieve_key() - .map_err(|e| { - error!("Nonce receiving error: {:?}", e); - CeremonyError::NonceReceivingError( - CeremonyErrorReason::RoundFinalizationError, - ) - })? - .private_bytes(), - ) - .map_err(|e| { - error!("Nonce receiving error: {:?}", e); - CeremonyError::NonceReceivingError(CeremonyErrorReason::RoundFinalizationError) - })?; - self.start_second_round(secret_key).map(Some) - } else { - Ok(None) - } - } else { - Err(CeremonyError::NonceReceivingError(CeremonyErrorReason::IncorrectRound)) - } - } - - // Starts the second round - fn start_second_round( - &mut self, - private_key: SecretKey, - ) -> Result { - let first_round = self - .ceremony_state - .first_round - .take() - .ok_or(CeremonyError::NonceReceivingError(CeremonyErrorReason::IncorrectRound))?; - - let message = match &self.ceremony_data.payload { - SignBitcoinPayload::TaprootSpendable(message, _) => message.clone(), - SignBitcoinPayload::Derived(message) => message.clone(), - SignBitcoinPayload::TaprootUnspendable(message) => message.clone(), - SignBitcoinPayload::WithTweaks(message, _) => message.clone(), - }; - let second_round = first_round.finalize(private_key, message).map_err(|e| { - error!("Could not start second round: {:?}", e); - CeremonyError::NonceReceivingError(CeremonyErrorReason::RoundFinalizationError) - })?; - - let partial_signature: PartialSignature = second_round.our_signature(); - - self.ceremony_state.second_round = Some(second_round); - - Ok(CeremonyEvent::SecondRoundStarted( - self.get_signers_except_self(), - self.get_id_ref().clone(), - partial_signature, - )) - } - - // Saves signer's partial signature - pub fn receive_partial_sign( - &mut self, - signer: SignerId, - partial_signature: impl Into, - ) -> Result, CeremonyError> { - info!("Saving partial signature from signer: {:?}", signer); - let peer_index = self.ceremony_data.signers.iter().position(|p| p.0 == signer).ok_or( - CeremonyError::PartialSignatureReceivingError(CeremonyErrorReason::SignerNotFound), - )?; - - if let Some(ref mut r) = self.ceremony_state.second_round { - r.receive_signature(peer_index, partial_signature).map_err(|e| { - error!("Signature receiving error: {:?}", e); - CeremonyError::PartialSignatureReceivingError( - CeremonyErrorReason::ContributionError, - ) - })?; - if r.is_complete() { - if let Some(r) = self.ceremony_state.second_round.take() { - let signature: CompactSignature = r - .finalize::() - .map_err(|e| { - error!("Could not finish second round: {:?}", e); - CeremonyError::PartialSignatureReceivingError( - CeremonyErrorReason::RoundFinalizationError, - ) - })? - .compact(); - - info!("Ceremony {:?} `has ended`", self.get_id_ref()); - info!("Aggregated public key {:?}", self.ceremony_data.agg_key.to_sec1_bytes()); - info!("Signature {:?}", signature.to_bytes()); - - let message = match &self.ceremony_data.payload { - SignBitcoinPayload::Derived(p) => p, - SignBitcoinPayload::TaprootUnspendable(p) => p, - SignBitcoinPayload::TaprootSpendable(p, _) => p, - SignBitcoinPayload::WithTweaks(p, _) => p, - }; - - let result = - verify_single(self.ceremony_data.agg_key, signature, message).is_ok(); - Ok(Some(CeremonyEvent::CeremonyEnded( - signature.to_bytes(), - self.ceremony_data.check_run, - result, - ))) - } else { - Err(CeremonyError::PartialSignatureReceivingError( - CeremonyErrorReason::IncorrectRound, - )) - } - } else { - Ok(None) - } - } else { - Err(CeremonyError::PartialSignatureReceivingError(CeremonyErrorReason::IncorrectRound)) - } - } - - pub fn get_signers_except_self(&self) -> Signers { - self.ceremony_data - .signers - .iter() - .filter(|e| e.0 != self.ceremony_data.me) - .map(|s| s.0) - .collect() - } - - pub fn get_id_ref(&self) -> &CeremonyId { - &self.ceremony_data.payload - } - - pub fn is_first_round(&self) -> bool { - self.ceremony_state.first_round.is_some() - } -} - -pub fn get_current_timestamp() -> u64 { - SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs() -} - -#[cfg(feature = "std")] -fn random_seed() -> [u8; 32] { - use rand::{thread_rng, RngCore}; - - let mut seed = [0u8; 32]; - let mut rand = thread_rng(); - rand.fill_bytes(&mut seed); - seed -} - -#[cfg(feature = "sgx")] -fn random_seed() -> [u8; 32] { - use sgx_rand::{Rng, StdRng}; - let mut seed = [0u8; 32]; - let mut rand = StdRng::new().unwrap(); - rand.fill_bytes(&mut seed); - seed -} - -#[cfg(test)] -pub mod test { - use crate::{ - CeremonyError, CeremonyErrorReason, CeremonyEvent, MuSig2Ceremony, SignBitcoinPayload, - SignerId, SignersWithKeys, - }; - use alloc::sync::Arc; - use itp_sgx_crypto::{key_repository::AccessKey, schnorr::Pair as SchnorrPair}; - use k256::{elliptic_curve::PublicKey, schnorr::SigningKey}; - use musig2::SecNonce; - - pub const MY_SIGNER_ID: SignerId = [0u8; 32]; - - fn my_priv_key() -> SigningKey { - SigningKey::from_bytes(&[ - 252, 240, 35, 85, 243, 83, 129, 54, 7, 155, 24, 114, 254, 0, 134, 251, 207, 83, 177, 9, - 92, 118, 222, 5, 202, 239, 188, 215, 132, 113, 127, 94, - ]) - .unwrap() - } - - fn signer1_priv_key() -> SigningKey { - SigningKey::from_bytes(&[ - 42, 82, 57, 169, 208, 130, 125, 141, 62, 185, 167, 41, 142, 217, 252, 135, 158, 128, - 44, 129, 222, 71, 55, 86, 230, 183, 54, 111, 152, 83, 85, 155, - ]) - .unwrap() - } - - pub const SIGNER_1_ID: SignerId = [1u8; 32]; - pub const SIGNER_1_SEC_NONCE: [u8; 64] = [ - 57, 232, 181, 133, 43, 97, 251, 79, 229, 110, 26, 121, 197, 2, 249, 237, 222, 207, 129, - 232, 8, 227, 120, 202, 127, 61, 209, 41, 92, 54, 8, 91, 80, 31, 9, 126, 14, 137, 126, 143, - 98, 223, 254, 134, 9, 190, 5, 157, 133, 254, 18, 119, 117, 25, 65, 179, 35, 130, 156, 109, - 233, 51, 18, 32, - ]; - - pub const SIGNER_2_ID: SignerId = [2u8; 32]; - - fn signer2_priv_key() -> SigningKey { - SigningKey::from_bytes(&[ - 117, 130, 176, 36, 185, 53, 187, 61, 123, 86, 24, 38, 174, 143, 129, 73, 245, 210, 127, - 148, 115, 136, 32, 98, 62, 47, 26, 196, 57, 211, 171, 185, - ]) - .unwrap() - } - - pub const SIGNER_2_SEC_NONCE: [u8; 64] = [ - 78, 229, 109, 189, 246, 169, 247, 85, 184, 199, 144, 135, 45, 60, 71, 109, 214, 121, 165, - 206, 185, 246, 120, 52, 228, 49, 155, 9, 160, 129, 171, 252, 69, 160, 122, 66, 151, 147, - 141, 118, 226, 189, 100, 94, 74, 163, 158, 245, 111, 99, 108, 202, 224, 110, 71, 106, 178, - 255, 89, 34, 16, 10, 195, 107, - ]; - - fn signers_with_keys() -> SignersWithKeys { - vec![ - (MY_SIGNER_ID, PublicKey::from(my_priv_key().verifying_key())), - (SIGNER_1_ID, PublicKey::from(signer1_priv_key().verifying_key())), - (SIGNER_2_ID, PublicKey::from(signer2_priv_key().verifying_key())), - ] - } - - pub const SAMPLE_SIGNATURE_PAYLOAD: [u8; 32] = [0u8; 32]; - - struct MockedSigningKeyAccess { - signing_key: SigningKey, - } - - impl AccessKey for MockedSigningKeyAccess { - type KeyType = SchnorrPair; - - fn retrieve_key(&self) -> itp_sgx_crypto::Result { - Ok(SchnorrPair::new(self.signing_key.clone())) - } - } - - #[test] - fn it_should_create_ceremony_in_firstround() { - // given - let signing_key_access = MockedSigningKeyAccess { signing_key: my_priv_key() }; - - // when - let result = MuSig2Ceremony::new( - MY_SIGNER_ID, - signers_with_keys(), - SignBitcoinPayload::Derived(SAMPLE_SIGNATURE_PAYLOAD.to_vec()), - Arc::new(signing_key_access), - false, - ); - - // then - assert!(result.is_ok()); - assert!(result.unwrap().0.is_first_round()) - } - - #[test] - fn it_should_prevent_from_creating_ceremony_without_sufficient_signers() { - // given - let signing_key_access = MockedSigningKeyAccess { signing_key: my_priv_key() }; - - // when - let result = MuSig2Ceremony::new( - MY_SIGNER_ID, - signers_with_keys()[0..1].to_vec(), - SignBitcoinPayload::Derived(SAMPLE_SIGNATURE_PAYLOAD.to_vec()), - Arc::new(signing_key_access), - false, - ); - - // then - assert!(result.is_err()); - } - - #[test] - fn it_should_produce_error_due_to_nonce_from_unknown_signer() { - // given - let signing_key_access = MockedSigningKeyAccess { signing_key: my_priv_key() }; - let mut ceremony = MuSig2Ceremony::new( - MY_SIGNER_ID, - signers_with_keys(), - SignBitcoinPayload::Derived(SAMPLE_SIGNATURE_PAYLOAD.to_vec()), - Arc::new(signing_key_access), - false, - ) - .unwrap() - .0; - - assert!(ceremony.ceremony_state.first_round.is_some()); - assert!(ceremony.ceremony_state.second_round.is_none()); - - let event = ceremony.receive_nonce( - [10u8; 32], - SecNonce::from_bytes(&SIGNER_2_SEC_NONCE).unwrap().public_nonce(), - ); - assert!(ceremony.ceremony_state.first_round.is_some()); - assert!(ceremony.ceremony_state.second_round.is_none()); - assert!(event.is_err()); - assert!(matches!( - event.unwrap_err(), - CeremonyError::NonceReceivingError(CeremonyErrorReason::SignerNotFound) - )); - } - - #[test] - fn it_should_complete_successfully() { - // given - let signing_key_access = MockedSigningKeyAccess { signing_key: my_priv_key() }; - let mut ceremony = MuSig2Ceremony::new( - MY_SIGNER_ID, - signers_with_keys(), - SignBitcoinPayload::Derived(SAMPLE_SIGNATURE_PAYLOAD.to_vec()), - Arc::new(signing_key_access), - false, - ) - .unwrap() - .0; - - assert!(ceremony.ceremony_state.first_round.is_some()); - assert!(ceremony.ceremony_state.second_round.is_none()); - - let event = ceremony.receive_nonce( - SIGNER_1_ID, - SecNonce::from_bytes(&SIGNER_1_SEC_NONCE).unwrap().public_nonce(), - ); - assert!(ceremony.ceremony_state.first_round.is_some()); - assert!(ceremony.ceremony_state.second_round.is_none()); - assert!(event.is_ok()); - assert!(event.unwrap().is_none()); - - let event = ceremony.receive_nonce( - SIGNER_2_ID, - SecNonce::from_bytes(&SIGNER_2_SEC_NONCE).unwrap().public_nonce(), - ); - assert!(ceremony.ceremony_state.first_round.is_none()); - assert!(ceremony.ceremony_state.second_round.is_some()); - assert!(event.is_ok()); - let event = event.unwrap(); - assert!(event.is_some()); - assert_eq!( - event.unwrap(), - CeremonyEvent::SecondRoundStarted( - vec![SIGNER_1_ID, SIGNER_2_ID], - SignBitcoinPayload::Derived(SAMPLE_SIGNATURE_PAYLOAD.to_vec()), - ceremony.ceremony_state.second_round.as_ref().unwrap().our_signature(), - ) - ); - } -} - -#[cfg(feature = "sgx-test")] -pub mod sgx_tests { - use super::*; - use crate::{ - generate_aggregated_public_key, CeremonyEvent, MuSig2Ceremony, SignBitcoinPayload, - }; - use alloc::sync::Arc; - use k256::schnorr::SigningKey; - use musig2::verify_single; - - pub const MY_SIGNER_ID: SignerId = [0u8; 32]; - pub const SIGNER_1_ID: SignerId = [1u8; 32]; - pub const SIGNER_2_ID: SignerId = [2u8; 32]; - pub const SAMPLE_SIGNATURE_PAYLOAD: [u8; 32] = [0u8; 32]; - - struct MockedSigningKeyAccess { - pub signing_key: SigningKey, - } - - impl AccessKey for MockedSigningKeyAccess { - type KeyType = SchnorrPair; - - fn retrieve_key(&self) -> itp_sgx_crypto::Result { - Ok(SchnorrPair::new(self.signing_key.clone())) - } - } - - pub fn test_full_flow_with_3_ceremonies() { - // given - let ceremony_id = SignBitcoinPayload::Derived(SAMPLE_SIGNATURE_PAYLOAD.to_vec()); - //my signer - let my_signer_key_access = MockedSigningKeyAccess { signing_key: my_priv_key() }; - let mut my_ceremony = MuSig2Ceremony::new( - MY_SIGNER_ID, - signers_with_keys(), - ceremony_id.clone(), - Arc::new(my_signer_key_access), - false, - ) - .unwrap() - .0; - // signer 1 - let signer1_key_access = MockedSigningKeyAccess { signing_key: signer1_priv_key() }; - let mut signer1_ceremony = MuSig2Ceremony::new( - SIGNER_1_ID, - signers_with_keys(), - ceremony_id.clone(), - Arc::new(signer1_key_access), - false, - ) - .unwrap() - .0; - // signer 2 - let signer2_key_access = MockedSigningKeyAccess { signing_key: signer2_priv_key() }; - let mut signer2_ceremony = MuSig2Ceremony::new( - SIGNER_2_ID, - signers_with_keys(), - ceremony_id.clone(), - Arc::new(signer2_key_access), - false, - ) - .unwrap() - .0; - - let my_ceremony_nonce = - my_ceremony.ceremony_state.first_round.as_ref().unwrap().our_public_nonce(); - let signer1_ceremony_nonce = - signer1_ceremony.ceremony_state.first_round.as_ref().unwrap().our_public_nonce(); - let signer2_ceremony_nonce = - signer2_ceremony.ceremony_state.first_round.as_ref().unwrap().our_public_nonce(); - - // my signer receive nonce - let my_ceremony_receive_first_nonce_ev = - my_ceremony.receive_nonce(SIGNER_1_ID, signer1_ceremony_nonce.clone()).unwrap(); - match my_ceremony_receive_first_nonce_ev { - None => {}, - ev => panic!("except None but get: {:?}", ev), - } - let my_ceremony_second_round_started_ev = - my_ceremony.receive_nonce(SIGNER_2_ID, signer2_ceremony_nonce.clone()).unwrap(); - let my_ceremony_partial_sign = match my_ceremony_second_round_started_ev { - Some(CeremonyEvent::SecondRoundStarted(_, _, partial_sign)) => partial_sign, - ev => panic!("except Some(CeremonyEvent::SecondRoundStarted) but get: {:?}", ev), - }; - - // signer 1 receive nonce - let signer1_ceremony_receive_first_nonce_ev = - signer1_ceremony.receive_nonce(MY_SIGNER_ID, my_ceremony_nonce.clone()).unwrap(); - match signer1_ceremony_receive_first_nonce_ev { - None => {}, - ev => panic!("except None but get: {:?}", ev), - } - let signer1_ceremony_second_round_started_ev = signer1_ceremony - .receive_nonce(SIGNER_2_ID, signer2_ceremony_nonce.clone()) - .unwrap(); - let signer1_ceremony_partial_sign = match signer1_ceremony_second_round_started_ev { - Some(CeremonyEvent::SecondRoundStarted(_, _, partial_sign)) => partial_sign, - ev => panic!("except Some(CeremonyEvent::SecondRoundStarted) but get: {:?}", ev), - }; - - // signer 2 receive nonce - let signer2_ceremony_receive_first_nonce_ev = - signer2_ceremony.receive_nonce(MY_SIGNER_ID, my_ceremony_nonce.clone()).unwrap(); - match signer2_ceremony_receive_first_nonce_ev { - None => {}, - ev => panic!("except None but get: {:?}", ev), - } - let signer2_ceremony_second_round_started_ev = signer2_ceremony - .receive_nonce(SIGNER_1_ID, signer1_ceremony_nonce.clone()) - .unwrap(); - let signer2_ceremony_partial_sign = match signer2_ceremony_second_round_started_ev { - Some(CeremonyEvent::SecondRoundStarted(_, _, partial_sign)) => partial_sign, - ev => panic!("except Some(CeremonyEvent::SecondRoundStarted) but get: {:?}", ev), - }; - - // my signer receive partial_sign - let my_ceremony_receive_first_partial_sign_ev = my_ceremony - .receive_partial_sign(SIGNER_1_ID, signer1_ceremony_partial_sign) - .unwrap(); - match my_ceremony_receive_first_partial_sign_ev { - None => {}, - ev => panic!("except None but get: {:?}", ev), - } - let my_ceremony_ended_ev = my_ceremony - .receive_partial_sign(SIGNER_2_ID, signer2_ceremony_partial_sign) - .unwrap(); - let my_ceremony_final_signature = match my_ceremony_ended_ev { - Some(CeremonyEvent::CeremonyEnded(signature, _, _)) => signature, - ev => panic!("except Some(CeremonyEvent::CeremonyEnded) but get: {:?}", ev), - }; - - // signer 1 receive partial_sign - let signer1_receive_first_partial_sign_ev = signer1_ceremony - .receive_partial_sign(MY_SIGNER_ID, my_ceremony_partial_sign) - .unwrap(); - match signer1_receive_first_partial_sign_ev { - None => {}, - ev => panic!("except None but get: {:?}", ev), - } - let signer1_ceremony_ended_ev = signer1_ceremony - .receive_partial_sign(SIGNER_2_ID, signer2_ceremony_partial_sign) - .unwrap(); - let signer1_ceremony_final_signature = match signer1_ceremony_ended_ev { - Some(CeremonyEvent::CeremonyEnded(signature, _, _)) => signature, - ev => panic!("except Some(CeremonyEvent::CeremonyEnded) but get: {:?}", ev), - }; - - // signer 2 receive partial_sign - let signer2_receive_first_partial_sign_ev = signer2_ceremony - .receive_partial_sign(MY_SIGNER_ID, my_ceremony_partial_sign) - .unwrap(); - match signer2_receive_first_partial_sign_ev { - None => {}, - ev => panic!("except None but get: {:?}", ev), - } - let signer2_ceremony_ended_ev = signer2_ceremony - .receive_partial_sign(SIGNER_1_ID, signer1_ceremony_partial_sign) - .unwrap(); - let signer2_ceremony_final_signature = match signer2_ceremony_ended_ev { - Some(CeremonyEvent::CeremonyEnded(signature, _, _)) => signature, - ev => panic!("except Some(CeremonyEvent::CeremonyEnded) but get: {:?}", ev), - }; - - assert_eq!(my_ceremony_final_signature, signer1_ceremony_final_signature); - assert_eq!(my_ceremony_final_signature, signer2_ceremony_final_signature); - - // let signature = - // k256::schnorr::Signature::try_from(signer1_ceremony_final_signature.as_slice()) - // .unwrap(); - let agg_key = - generate_aggregated_public_key(signers_with_keys().iter().map(|sk| sk.1).collect()); - // let ver_key = k256::schnorr::VerifyingKey::try_from(agg_key).unwrap(); - - // this pass - verify_single(agg_key, signer1_ceremony_final_signature, SAMPLE_SIGNATURE_PAYLOAD).unwrap(); - - // this not pass - // ver_key.verify(&SAMPLE_SIGNATURE_PAYLOAD, &signature).unwrap() - } - - fn signers_with_keys() -> SignersWithKeys { - vec![ - (MY_SIGNER_ID, k256::elliptic_curve::PublicKey::from(my_priv_key().verifying_key())), - ( - SIGNER_1_ID, - k256::elliptic_curve::PublicKey::from(signer1_priv_key().verifying_key()), - ), - ( - SIGNER_2_ID, - k256::elliptic_curve::PublicKey::from(signer2_priv_key().verifying_key()), - ), - ] - } - - fn my_priv_key() -> SigningKey { - SigningKey::from_bytes(&[ - 252, 240, 35, 85, 243, 83, 129, 54, 7, 155, 24, 114, 254, 0, 134, 251, 207, 83, 177, 9, - 92, 118, 222, 5, 202, 239, 188, 215, 132, 113, 127, 94, - ]) - .unwrap() - } - - fn signer1_priv_key() -> SigningKey { - SigningKey::from_bytes(&[ - 42, 82, 57, 169, 208, 130, 125, 141, 62, 185, 167, 41, 142, 217, 252, 135, 158, 128, - 44, 129, 222, 71, 55, 86, 230, 183, 54, 111, 152, 83, 85, 155, - ]) - .unwrap() - } - - fn signer2_priv_key() -> SigningKey { - SigningKey::from_bytes(&[ - 117, 130, 176, 36, 185, 53, 187, 61, 123, 86, 24, 38, 174, 143, 129, 73, 245, 210, 127, - 148, 115, 136, 32, 98, 62, 47, 26, 196, 57, 211, 171, 185, - ]) - .unwrap() - } -} diff --git a/tee-worker/bitacross/bitacross/core/bc-musig2-event/Cargo.toml b/tee-worker/bitacross/bitacross/core/bc-musig2-event/Cargo.toml deleted file mode 100644 index 3d90c0819c..0000000000 --- a/tee-worker/bitacross/bitacross/core/bc-musig2-event/Cargo.toml +++ /dev/null @@ -1,64 +0,0 @@ -[package] -name = "bc-musig2-event" -authors = ["Trust Computing GmbH "] -version = "0.1.0" -edition = "2021" - -[dependencies] -threadpool = { workspace = true, optional = true } - -# sgx dependencies -sgx_tstd = { workspace = true, features = ["net", "thread"], optional = true } -threadpool_sgx = { workspace = true, optional = true } - -bc-enclave-registry = { path = "../bc-enclave-registry", default-features = false } -bc-musig2-ceremony = { path = "../bc-musig2-ceremony", default-features = false } -lc-direct-call = { path = "../../../litentry/core/direct-call", default-features = false } - -itc-direct-rpc-client = { package = "bc-itc-direct-rpc-client", path = "../../../core/direct-rpc-client", default-features = false } -itc-direct-rpc-server = { package = "bc-itc-direct-rpc-server", path = "../../../core/direct-rpc-server", default-features = false } -itp-ocall-api = { workspace = true } -itp-rpc = { workspace = true } -itp-sgx-crypto = { workspace = true } -itp-types = { workspace = true } -itp-utils = { workspace = true } -litentry-primitives = { workspace = true } -rand = { version = "0.8.5", optional = true } -sgx_rand = { workspace = true, optional = true } -sp-core = { workspace = true, features = ["full_crypto"] } - -codec = { package = "parity-scale-codec", workspace = true } -log = { workspace = true } - -[dev-dependencies] -rand = { version = "0.8.5" } - -[features] -default = ["std"] -std = [ - "itc-direct-rpc-client/std", - "itc-direct-rpc-server/std", - "log/std", - "itp-types/std", - "litentry-primitives/std", - "itp-rpc/std", - "bc-musig2-ceremony/std", - "bc-enclave-registry/std", - "lc-direct-call/std", - "itp-sgx-crypto/std", - "rand", - "threadpool", -] -sgx = [ - "sgx_tstd", - "itc-direct-rpc-client/sgx", - "itc-direct-rpc-server/sgx", - "litentry-primitives/sgx", - "itp-rpc/sgx", - "bc-musig2-ceremony/sgx", - "bc-enclave-registry/sgx", - "lc-direct-call/sgx", - "itp-sgx-crypto/sgx", - "sgx_rand", - "threadpool_sgx", -] diff --git a/tee-worker/bitacross/bitacross/core/bc-musig2-event/src/lib.rs b/tee-worker/bitacross/bitacross/core/bc-musig2-event/src/lib.rs deleted file mode 100644 index af9ca183d4..0000000000 --- a/tee-worker/bitacross/bitacross/core/bc-musig2-event/src/lib.rs +++ /dev/null @@ -1,274 +0,0 @@ -// Copyright 2020-2024 Trust Computing GmbH. -// This file is part of Litentry. -// -// Litentry is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// Litentry is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with Litentry. If not, see . - -#![cfg_attr(not(feature = "std"), no_std)] - -extern crate core; -#[cfg(all(not(feature = "std"), feature = "sgx"))] -extern crate sgx_tstd as std; - -#[cfg(all(feature = "std", feature = "sgx"))] -compile_error!("feature \"std\" and feature \"sgx\" cannot be enabled at the same time"); - -use core::time::Duration; -#[cfg(feature = "std")] -use threadpool::ThreadPool; - -#[cfg(feature = "sgx")] -use threadpool_sgx::ThreadPool; - -#[cfg(feature = "std")] -use std::sync::Mutex; - -#[cfg(feature = "sgx")] -use std::sync::SgxMutex as Mutex; - -#[cfg(feature = "std")] -use std::sync::RwLock; - -#[cfg(feature = "sgx")] -use std::sync::SgxRwLock as RwLock; - -use bc_enclave_registry::EnclaveRegistryLookup; -use bc_musig2_ceremony::{CeremonyEvent, CeremonyId, CeremonyRegistry, SignerId}; -use codec::Encode; -use itc_direct_rpc_client::{DirectRpcClient, DirectRpcClientFactory, RpcClient, RpcClientFactory}; -use itc_direct_rpc_server::SendRpcResponse; -use itp_ocall_api::EnclaveAttestationOCallApi; -use itp_rpc::{Id, RpcRequest}; -use itp_sgx_crypto::{key_repository::AccessKey, schnorr::Pair as SchnorrPair}; -pub use itp_types::{DirectRequestStatus, Hash}; -use itp_utils::hex::ToHexPrefixed; -use lc_direct_call::CeremonyRoundCall; -use litentry_primitives::{Address32, Identity, PlainRequest, ShardIdentifier}; -use log::*; -use sp_core::{blake2_256, ed25519, Pair as SpCorePair, H256}; -use std::{collections::HashMap, string::ToString, sync::Arc, thread::sleep, vec}; - -#[allow(clippy::too_many_arguments)] -pub fn process_event( - signing_key_access: Arc, - ocall_api: Arc, - responder: Arc, - enclave_registry_lookup: Arc, - event: CeremonyEvent, - ceremony_id: CeremonyId, - event_threads_pool: ThreadPool, - peers_map: Arc>>, - ceremony_registry: Arc>>, -) where - OCallApi: EnclaveAttestationOCallApi + 'static, - SIGNINGAK: AccessKey + Send + Sync + 'static, - Responder: SendRpcResponse + 'static, - ECL: EnclaveRegistryLookup + Send + Sync + 'static, - BKR: AccessKey + Send + Sync + 'static, -{ - let my_identity: Address32 = signing_key_access.retrieve_key().unwrap().public().0.into(); - let identity = Identity::Substrate(my_identity); - let mr_enclave = ocall_api.get_mrenclave_of_self().unwrap().m; - - match event { - CeremonyEvent::FirstRoundStarted(signers, message, nonce) => { - let direct_call = CeremonyRoundCall::NonceShare(identity, message, nonce.serialize()); - let request = prepare_request(signing_key_access.as_ref(), mr_enclave, direct_call); - - signers.iter().for_each(|signer_id| { - debug!( - "Sharing nonce with signer: {:?} for ceremony: {:?}", - signer_id, ceremony_id - ); - - let signer_id = *signer_id; - let peers_map_clone = peers_map.clone(); - let request = request.clone(); - let enclave_lookup_cloned = enclave_registry_lookup.clone(); - let ceremony_registry_cloned = ceremony_registry.clone(); - let ceremony_id_cloned = ceremony_id.clone(); - event_threads_pool.execute(move || { - send_request( - signer_id, - &ceremony_id_cloned, - request, - peers_map_clone, - enclave_lookup_cloned, - ceremony_registry_cloned, - ); - }); - }); - }, - CeremonyEvent::SecondRoundStarted(signers, message, signature) => { - let direct_call = - CeremonyRoundCall::PartialSignatureShare(identity, message, signature.serialize()); - let request = prepare_request(signing_key_access.as_ref(), mr_enclave, direct_call); - - signers.iter().for_each(|signer_id| { - debug!( - "Sharing partial signature with signer: {:?} for ceremony: {:?}", - signer_id, ceremony_id - ); - - let signer_id = *signer_id; - let peers_map_clone = peers_map.clone(); - let request = request.clone(); - let enclave_lookup_cloned = enclave_registry_lookup.clone(); - let ceremony_registry_cloned = ceremony_registry.clone(); - let ceremony_id_cloned = ceremony_id.clone(); - event_threads_pool.execute(move || { - send_request( - signer_id, - &ceremony_id_cloned, - request, - peers_map_clone, - enclave_lookup_cloned, - ceremony_registry_cloned, - ); - }); - }); - }, - CeremonyEvent::CeremonyEnded(signature, is_check_run, verification_result) => { - debug!("Ceremony {:?} ended, signature {:?}", ceremony_id, signature); - let hash = blake2_256(&ceremony_id.encode()); - let result = if is_check_run { - verification_result.encode() - } else { - let result = signature; - result.encode() - }; - event_threads_pool.execute(move || { - if let Err(e) = responder.send_state_with_status( - Hash::from_slice(&hash), - result, - DirectRequestStatus::Ok, - ) { - error!("Could not send response to {:?}, reason: {:?}", &hash, e); - } - }); - }, - CeremonyEvent::CeremonyError(signers, error) => { - debug!("Ceremony {:?} error {:?}", ceremony_id, error); - let hash = blake2_256(&ceremony_id.encode()); - let encoded_result = error.encode(); - event_threads_pool.execute(move || { - if let Err(e) = responder.send_state_with_status( - Hash::from_slice(&hash), - encoded_result, - DirectRequestStatus::Error, - ) { - error!("Could not send response to {:?}, reason: {:?}", &hash, e); - } - }); - - let direct_call = CeremonyRoundCall::KillCeremony(identity, ceremony_id.clone()); - let request = prepare_request(signing_key_access.as_ref(), mr_enclave, direct_call); - - //kill ceremonies on other workers - signers.iter().for_each(|signer_id| { - debug!( - "Requesting ceremony kill on signer: {:?} for ceremony: {:?}", - signer_id, ceremony_id - ); - - let signer_id = *signer_id; - let peers_map_clone = peers_map.clone(); - let request = request.clone(); - let enclave_lookup_cloned = enclave_registry_lookup.clone(); - let ceremony_registry_cloned = ceremony_registry.clone(); - let ceremony_id_cloned = ceremony_id.clone(); - event_threads_pool.execute(move || { - send_request( - signer_id, - &ceremony_id_cloned, - request, - peers_map_clone, - enclave_lookup_cloned, - ceremony_registry_cloned, - ); - }); - }); - }, - } -} - -// it will try to send request until it succeeds, the peer is removed from registry or ceremony is removed -fn send_request( - signer_id: SignerId, - ceremony_id: &CeremonyId, - request: RpcRequest, - peers_map: Arc>>, - enclave_registry_lookup: Arc, - ceremony_registry: Arc>>, -) where - ECL: EnclaveRegistryLookup, - BKR: AccessKey, -{ - loop { - let client = peers_map.lock().unwrap().get(&signer_id).cloned(); - if let Some(mut client) = client { - if let Err(e) = client.send(&request) { - error!("Could not send request to signer: {:?}, reason: {:?}", signer_id, e); - sleep(Duration::from_secs(5)); - let mut peers_lock = peers_map.lock().unwrap(); - peers_lock.remove(&signer_id); - } else { - // finish if request was sent - break - } - } else { - // check if ceremony still exists, if not stop - if !ceremony_registry.read().unwrap().contains_key(ceremony_id) { - break - } - - if let Some(url) = enclave_registry_lookup.get_worker_url(&Address32::from(signer_id)) { - match (DirectRpcClientFactory {}).create(&url) { - Ok(new_client) => { - peers_map.lock().unwrap().insert(signer_id, new_client.clone()); - }, - Err(e) => { - error!("Could not connect to peer {}, reason: {:?}", url, e); - sleep(Duration::from_secs(5)); - }, - } - } else { - error!("Could not find {:?} in registry", signer_id.to_hex()); - // stop if peer is not found in registry - break - } - } - } -} - -fn prepare_request( - signing_key_access: &SIGNINGAK, - mr_enclave: [u8; 32], - ceremony_round_call: CeremonyRoundCall, -) -> RpcRequest -where - SIGNINGAK: AccessKey + Send + Sync + 'static, -{ - let shard = ShardIdentifier::from_slice(&mr_enclave); - // same as above - let dc_signed_encoded = ceremony_round_call - .sign(&signing_key_access.retrieve_key().unwrap().into(), &mr_enclave, &shard) - .encode(); - let request = PlainRequest { shard, payload: dc_signed_encoded }; - RpcRequest { - jsonrpc: "2.0".to_string(), - method: "bitacross_btcDataShare".to_string(), - params: vec![request.to_hex()], - id: Id::Number(1), - } -} diff --git a/tee-worker/bitacross/bitacross/core/bc-relayer-registry/Cargo.toml b/tee-worker/bitacross/bitacross/core/bc-relayer-registry/Cargo.toml deleted file mode 100644 index 6ce57e3e91..0000000000 --- a/tee-worker/bitacross/bitacross/core/bc-relayer-registry/Cargo.toml +++ /dev/null @@ -1,38 +0,0 @@ -[package] -name = "bc-relayer-registry" -authors = ["Trust Computing GmbH "] -version = "0.1.0" -edition = "2021" - -[dependencies] -codec = { package = "parity-scale-codec", workspace = true } -log = { workspace = true } -sp-std = { workspace = true } -thiserror = { workspace = true, optional = true } - -sgx_tstd = { workspace = true, features = ["net", "thread"], optional = true } -thiserror_sgx = { workspace = true, optional = true } - -itp-settings = { workspace = true } -itp-sgx-io = { workspace = true } -litentry-primitives = { workspace = true } - -[dev-dependencies] -base64 = { workspace = true, features = ["alloc"] } - -[features] -default = ["std"] -development = [] -sgx = [ - "sgx_tstd", - "thiserror_sgx", - "itp-sgx-io/sgx", - "litentry-primitives/sgx", -] -std = [ - "sp-std/std", - "log/std", - "thiserror", - "itp-sgx-io/std", - "litentry-primitives/std", -] diff --git a/tee-worker/bitacross/bitacross/core/bc-relayer-registry/src/lib.rs b/tee-worker/bitacross/bitacross/core/bc-relayer-registry/src/lib.rs deleted file mode 100644 index 337b958a82..0000000000 --- a/tee-worker/bitacross/bitacross/core/bc-relayer-registry/src/lib.rs +++ /dev/null @@ -1,206 +0,0 @@ -// Copyright 2020-2024 Trust Computing GmbH. -// This file is part of Litentry. -// -// Litentry is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// Litentry is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with Litentry. If not, see . - -#![cfg_attr(not(feature = "std"), no_std)] - -extern crate core; -#[cfg(all(not(feature = "std"), feature = "sgx"))] -extern crate sgx_tstd as std; - -#[cfg(all(feature = "std", feature = "sgx"))] -compile_error!("feature \"std\" and feature \"sgx\" cannot be enabled at the same time"); - -use sp_std::{boxed::Box, fmt::Debug}; - -use litentry_primitives::Identity; -use log::error; -use std::{collections::BTreeMap, path::PathBuf}; - -#[cfg(feature = "std")] -use std::sync::RwLock; -#[cfg(feature = "sgx")] -use std::sync::SgxRwLock as RwLock; - -pub type RelayerRegistryMap = BTreeMap; - -#[derive(Default)] -pub struct RelayerRegistry { - pub registry: RwLock, - pub seal_path: PathBuf, -} - -impl RelayerRegistry { - pub fn new(base_dir: PathBuf) -> Self { - RelayerRegistry { registry: Default::default(), seal_path: base_dir } - } -} - -pub type RegistryResult = core::result::Result; - -#[cfg(feature = "sgx")] -use thiserror_sgx as thiserror; - -#[derive(Debug, thiserror::Error)] -pub enum RegistryError { - #[error("poison lock")] - PoisonLock, - #[error("empty Relayer registry")] - EmptyRegistry, - #[error(transparent)] - Other(#[from] Box), -} - -impl From for RegistryError { - fn from(e: std::io::Error) -> Self { - Self::Other(e.into()) - } -} - -impl From for RegistryError { - #[cfg(feature = "std")] - fn from(e: codec::Error) -> Self { - Self::Other(e.into()) - } - - #[cfg(feature = "sgx")] - fn from(e: codec::Error) -> Self { - Self::Other(std::format!("{:?}", e).into()) - } -} - -#[cfg(feature = "sgx")] -mod sgx { - use crate::{RegistryError as Error, RegistryResult as Result, RelayerRegistryMap}; - pub use codec::{Decode, Encode}; - pub use itp_settings::files::RELAYER_REGISTRY_FILE; - pub use itp_sgx_io::{seal, unseal, SealedIO}; - pub use log::*; - pub use std::{boxed::Box, fs, path::PathBuf, sgxfs::SgxFile, sync::Arc}; - - #[derive(Clone, Debug)] - pub struct RelayerRegistrySeal { - base_path: PathBuf, - } - - impl RelayerRegistrySeal { - pub fn new(base_path: PathBuf) -> Self { - Self { base_path } - } - - pub fn path(&self) -> PathBuf { - self.base_path.join(RELAYER_REGISTRY_FILE) - } - } - - impl SealedIO for RelayerRegistrySeal { - type Error = Error; - type Unsealed = RelayerRegistryMap; - - fn unseal(&self) -> Result { - Ok(unseal(self.path()).map(|b| Decode::decode(&mut b.as_slice()))??) - } - - fn seal(&self, unsealed: &Self::Unsealed) -> Result<()> { - info!("Seal relayer registry to file: {:?}", unsealed); - Ok(unsealed.using_encoded(|bytes| seal(bytes, self.path()))?) - } - } -} - -#[cfg(feature = "sgx")] -use sgx::*; - -pub trait RelayerRegistryUpdater { - fn init(&self) -> RegistryResult<()>; - fn update(&self, account: Identity) -> RegistryResult<()>; - fn remove(&self, account: Identity) -> RegistryResult<()>; -} - -pub trait RelayerRegistryLookup { - fn contains_key(&self, account: &Identity) -> bool; -} - -impl RelayerRegistryUpdater for RelayerRegistry { - #[cfg(feature = "std")] - fn init(&self) -> RegistryResult<()> { - Ok(()) - } - - #[cfg(feature = "std")] - fn update(&self, account: Identity) -> RegistryResult<()> { - let mut registry = self.registry.write().unwrap(); - registry.insert(account, ()); - Ok(()) - } - - #[cfg(feature = "std")] - fn remove(&self, _account: Identity) -> RegistryResult<()> { - Ok(()) - } - - // if `RELAYER_REGISTRY_FILE` exists, unseal and init from it - // otherwise create a new instance and seal to static file - #[cfg(feature = "sgx")] - fn init(&self) -> RegistryResult<()> { - let enclave_seal = RelayerRegistrySeal::new(self.seal_path.clone()); - if SgxFile::open(RELAYER_REGISTRY_FILE).is_err() { - info!( - "[Enclave] RelayerRegistry file not found, creating new! {}", - RELAYER_REGISTRY_FILE - ); - let registry = self.registry.write().map_err(|_| RegistryError::PoisonLock)?; - enclave_seal.seal(&*registry) - } else { - let m = enclave_seal.unseal()?; - info!("[Enclave] RelayerRegistry unsealed from file: {:?}", m); - let mut registry = self.registry.write().map_err(|_| RegistryError::PoisonLock)?; - *registry = m; - Ok(()) - } - } - - #[cfg(feature = "sgx")] - fn update(&self, account: Identity) -> RegistryResult<()> { - let mut registry = self.registry.write().map_err(|_| RegistryError::PoisonLock)?; - registry.insert(account, ()); - RelayerRegistrySeal::new(self.seal_path.clone()).seal(&*registry) - } - - #[cfg(feature = "sgx")] - fn remove(&self, account: Identity) -> RegistryResult<()> { - let mut registry = self.registry.write().map_err(|_| RegistryError::PoisonLock)?; - let old_value = registry.remove(&account); - if old_value.is_some() { - return RelayerRegistrySeal::new(self.seal_path.clone()).seal(&*registry) - } - Ok(()) - } -} - -impl RelayerRegistryLookup for RelayerRegistry { - #[cfg(feature = "std")] - fn contains_key(&self, account: &Identity) -> bool { - let registry = self.registry.read().unwrap(); - registry.contains_key(account) - } - - #[cfg(feature = "sgx")] - fn contains_key(&self, account: &Identity) -> bool { - // Using unwrap becaused poisoned locks are unrecoverable errors - let registry = self.registry.read().unwrap(); - registry.contains_key(account) - } -} diff --git a/tee-worker/bitacross/bitacross/core/bc-signer-registry/Cargo.toml b/tee-worker/bitacross/bitacross/core/bc-signer-registry/Cargo.toml deleted file mode 100644 index 7aaf9887d2..0000000000 --- a/tee-worker/bitacross/bitacross/core/bc-signer-registry/Cargo.toml +++ /dev/null @@ -1,39 +0,0 @@ -[package] -name = "bc-signer-registry" -authors = ["Trust Computing GmbH "] -version = "0.1.0" -edition = "2021" - -[dependencies] -codec = { package = "parity-scale-codec", workspace = true } -log = { workspace = true } -sp-std = { workspace = true } -thiserror = { workspace = true, optional = true } - -sgx_tstd = { workspace = true, features = ["net", "thread"], optional = true } -thiserror_sgx = { workspace = true, optional = true } - -itp-settings = { workspace = true } -itp-sgx-io = { workspace = true } -litentry-primitives = { workspace = true } - -[dev-dependencies] -base64 = { workspace = true, features = ["alloc"] } - -[features] -default = ["std"] -production = [ -] -sgx = [ - "sgx_tstd", - "thiserror_sgx", - "itp-sgx-io/sgx", - "litentry-primitives/sgx", -] -std = [ - "sp-std/std", - "log/std", - "thiserror", - "itp-sgx-io/std", - "litentry-primitives/std", -] diff --git a/tee-worker/bitacross/bitacross/core/bc-signer-registry/src/lib.rs b/tee-worker/bitacross/bitacross/core/bc-signer-registry/src/lib.rs deleted file mode 100644 index 5cd6efb6de..0000000000 --- a/tee-worker/bitacross/bitacross/core/bc-signer-registry/src/lib.rs +++ /dev/null @@ -1,253 +0,0 @@ -// Copyright 2020-2024 Trust Computing GmbH. -// This file is part of Litentry. -// -// Litentry is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// Litentry is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with Litentry. If not, see . - -#![cfg_attr(not(feature = "std"), no_std)] - -extern crate core; -#[cfg(all(not(feature = "std"), feature = "sgx"))] -extern crate sgx_tstd as std; - -#[cfg(all(feature = "std", feature = "sgx"))] -compile_error!("feature \"std\" and feature \"sgx\" cannot be enabled at the same time"); - -use sp_std::{boxed::Box, fmt::Debug}; - -use log::error; -use std::{collections::BTreeMap, error::Error, path::PathBuf, vec::Vec}; - -#[cfg(feature = "std")] -use std::sync::RwLock; -#[cfg(feature = "sgx")] -use std::sync::SgxRwLock as RwLock; - -pub type PubKey = [u8; 33]; - -pub type SignerRegistryMap = BTreeMap; - -#[derive(Default)] -pub struct SignerRegistry { - pub registry: RwLock, - pub seal_path: PathBuf, -} - -impl SignerRegistry { - pub fn new(base_dir: PathBuf) -> Self { - SignerRegistry { registry: Default::default(), seal_path: base_dir } - } -} - -pub type RegistryResult = Result; - -use litentry_primitives::Address32; -#[cfg(feature = "sgx")] -use thiserror_sgx as thiserror; - -#[derive(Debug, thiserror::Error)] -pub enum RegistryError { - #[error("poison lock")] - PoisonLock, - #[error("empty Signer registry")] - EmptyRegistry, - #[error(transparent)] - Other(#[from] Box), -} - -impl From for RegistryError { - fn from(e: std::io::Error) -> Self { - Self::Other(e.into()) - } -} - -impl From for RegistryError { - #[cfg(feature = "std")] - fn from(e: codec::Error) -> Self { - Self::Other(e.into()) - } - - #[cfg(feature = "sgx")] - fn from(e: codec::Error) -> Self { - Self::Other(std::format!("{:?}", e).into()) - } -} - -#[cfg(feature = "sgx")] -mod sgx { - use crate::{RegistryError as Error, RegistryResult as Result, SignerRegistryMap}; - pub use codec::{Decode, Encode}; - pub use itp_settings::files::SIGNER_REGISTRY_FILE; - pub use itp_sgx_io::{seal, unseal, SealedIO}; - pub use log::*; - pub use std::{boxed::Box, fs, path::PathBuf, sgxfs::SgxFile, sync::Arc}; - - #[derive(Clone, Debug)] - pub struct SignerRegistrySeal { - base_path: PathBuf, - } - - impl SignerRegistrySeal { - pub fn new(base_path: PathBuf) -> Self { - Self { base_path } - } - - pub fn path(&self) -> PathBuf { - self.base_path.join(SIGNER_REGISTRY_FILE) - } - } - - impl SealedIO for SignerRegistrySeal { - type Error = Error; - type Unsealed = SignerRegistryMap; - - fn unseal(&self) -> Result { - Ok(unseal(self.path()).map(|b| Decode::decode(&mut b.as_slice()))??) - } - - fn seal(&self, unsealed: &Self::Unsealed) -> Result<()> { - info!("Seal signer registry to file: {:?}", unsealed); - Ok(unsealed.using_encoded(|bytes| seal(bytes, self.path()))?) - } - } -} - -#[cfg(feature = "sgx")] -use sgx::*; - -pub trait SignerRegistrySealer { - fn seal(&self, state: SignerRegistryMap) -> RegistryResult<()>; - fn unseal(&self) -> RegistryResult; -} - -pub trait SignerRegistryUpdater { - fn init(&self) -> RegistryResult<()>; - fn update(&self, account: Address32, key: PubKey) -> RegistryResult<()>; - fn remove(&self, account: Address32) -> RegistryResult<()>; -} - -pub trait SignerRegistryLookup { - fn contains_key(&self, account: &Address32) -> bool; - fn get_all(&self) -> Vec<(Address32, PubKey)>; -} - -impl SignerRegistrySealer for SignerRegistry { - #[cfg(feature = "std")] - fn seal(&self, _state: SignerRegistryMap) -> RegistryResult<()> { - Ok(()) - } - - #[cfg(feature = "std")] - fn unseal(&self) -> RegistryResult { - Ok(Default::default()) - } - - #[cfg(feature = "sgx")] - fn seal(&self, mut state: SignerRegistryMap) -> RegistryResult<()> { - let mut registry = self.registry.write().map_err(|_| RegistryError::PoisonLock)?; - while let Some((key, val)) = state.pop_first() { - registry.insert(key, val); - } - - let signer_seal = SignerRegistrySeal::new(self.seal_path.clone()); - signer_seal.seal(®istry) - } - - #[cfg(feature = "sgx")] - fn unseal(&self) -> RegistryResult { - let signer_seal = SignerRegistrySeal::new(self.seal_path.clone()); - signer_seal.unseal() - } -} - -impl SignerRegistryUpdater for SignerRegistry { - #[cfg(feature = "std")] - fn init(&self) -> RegistryResult<()> { - Ok(()) - } - - #[cfg(feature = "std")] - fn update(&self, account: Address32, key: PubKey) -> RegistryResult<()> { - let mut registry = self.registry.write().unwrap(); - registry.insert(account, key); - Ok(()) - } - - #[cfg(feature = "std")] - fn remove(&self, _account: Address32) -> RegistryResult<()> { - Ok(()) - } - - // if `SIGNER_REGISTRY_FILE` exists, unseal and init from it - // otherwise create a new instance and seal to static file - #[cfg(feature = "sgx")] - fn init(&self) -> RegistryResult<()> { - let enclave_seal = SignerRegistrySeal::new(self.seal_path.clone()); - if SgxFile::open(SIGNER_REGISTRY_FILE).is_err() { - info!("[Signer] SignerRegistry file not found, creating new! {}", SIGNER_REGISTRY_FILE); - let registry = self.registry.write().map_err(|_| RegistryError::PoisonLock)?; - enclave_seal.seal(&*registry) - } else { - let m = enclave_seal.unseal()?; - info!("[Signer] SignerRegistry unsealed from file: {:?}", m); - let mut registry = self.registry.write().map_err(|_| RegistryError::PoisonLock)?; - *registry = m; - Ok(()) - } - } - - #[cfg(feature = "sgx")] - fn update(&self, account: Address32, key: PubKey) -> RegistryResult<()> { - let mut registry = self.registry.write().map_err(|_| RegistryError::PoisonLock)?; - registry.insert(account, key); - SignerRegistrySeal::new(self.seal_path.clone()).seal(&*registry) - } - - #[cfg(feature = "sgx")] - fn remove(&self, account: Address32) -> RegistryResult<()> { - let mut registry = self.registry.write().map_err(|_| RegistryError::PoisonLock)?; - let old_value = registry.remove(&account); - if old_value.is_some() { - return SignerRegistrySeal::new(self.seal_path.clone()).seal(&*registry) - } - Ok(()) - } -} - -impl SignerRegistryLookup for SignerRegistry { - #[cfg(feature = "std")] - fn contains_key(&self, account: &Address32) -> bool { - let registry = self.registry.read().unwrap(); - registry.contains_key(account) - } - - #[cfg(feature = "std")] - fn get_all(&self) -> Vec<(Address32, PubKey)> { - let registry = self.registry.read().unwrap(); - registry.iter().map(|(k, v)| (*k, *v)).collect() - } - - #[cfg(feature = "sgx")] - fn contains_key(&self, account: &Address32) -> bool { - // Using unwrap because poisoned locks are unrecoverable errors - let registry = self.registry.read().unwrap(); - registry.contains_key(account) - } - - #[cfg(feature = "sgx")] - fn get_all(&self) -> Vec<(Address32, PubKey)> { - // Using unwrap because poisoned locks are unrecoverable errors - let registry = self.registry.read().unwrap(); - registry.iter().map(|(k, v)| (k.clone(), v.clone())).collect() - } -} diff --git a/tee-worker/bitacross/bitacross/core/bc-task-processor/Cargo.toml b/tee-worker/bitacross/bitacross/core/bc-task-processor/Cargo.toml deleted file mode 100644 index f315dc434a..0000000000 --- a/tee-worker/bitacross/bitacross/core/bc-task-processor/Cargo.toml +++ /dev/null @@ -1,90 +0,0 @@ -[package] -name = "bc-task-processor" -authors = ["Trust Computing GmbH "] -version = "0.1.0" -edition = "2021" - -[dependencies] -futures_sgx = { workspace = true, optional = true } -thiserror = { workspace = true, optional = true } -thiserror_sgx = { workspace = true, optional = true } -threadpool = { workspace = true, optional = true } - -sgx_tstd = { workspace = true, features = ["net", "thread"], optional = true } -threadpool_sgx = { workspace = true, optional = true } - -codec = { package = "parity-scale-codec", workspace = true } -frame-support = { workspace = true } -log = { workspace = true } - -ita-stf = { package = "bc-ita-stf", path = "../../../app-libs/stf", default-features = false } -itp-enclave-metrics = { workspace = true } -itp-ocall-api = { workspace = true } -itp-sgx-crypto = { workspace = true } -itp-sgx-externalities = { workspace = true } -itp-stf-executor = { package = "bc-itp-stf-executor", path = "../../../core-primitives/stf-executor", default-features = false } -itp-stf-state-handler = { workspace = true } - -bc-enclave-registry = { path = "../bc-enclave-registry", default-features = false } -bc-musig2-ceremony = { path = "../bc-musig2-ceremony", default-features = false } -bc-musig2-event = { path = "../bc-musig2-event", default-features = false } -bc-relayer-registry = { path = "../bc-relayer-registry", default-features = false } -bc-signer-registry = { path = "../bc-signer-registry", default-features = false } -bc-task-sender = { path = "../bc-task-sender", default-features = false } -itc-direct-rpc-client = { package = "bc-itc-direct-rpc-client", path = "../../../core/direct-rpc-client", default-features = false } -itc-direct-rpc-server = { package = "bc-itc-direct-rpc-server", path = "../../../core/direct-rpc-server", default-features = false } -lc-direct-call = { path = "../../../litentry/core/direct-call", default-features = false } -litentry-primitives = { workspace = true } - -sgx_crypto_helper = { workspace = true } -sp-core = { workspace = true, features = ["full_crypto"] } - -[features] -default = ["std"] -sgx = [ - "threadpool_sgx", - "sgx_tstd", - "bc-musig2-ceremony/sgx", - "bc-musig2-event/sgx", - "bc-task-sender/sgx", - "bc-enclave-registry/sgx", - "bc-relayer-registry/sgx", - "bc-signer-registry/sgx", - "lc-direct-call/sgx", - "litentry-primitives/sgx", - "ita-stf/sgx", - "itp-enclave-metrics/sgx", - "itp-sgx-crypto/sgx", - "itp-sgx-externalities/sgx", - "itp-stf-executor/sgx", - "itp-stf-state-handler/sgx", - "thiserror_sgx", - "futures_sgx", - "itc-direct-rpc-server/sgx", - "itc-direct-rpc-client/sgx", - "sgx_crypto_helper/mesalock_sgx", -] -std = [ - "threadpool", - "log/std", - "bc-musig2-ceremony/std", - "bc-musig2-event/std", - "bc-task-sender/std", - "bc-enclave-registry/std", - "bc-relayer-registry/std", - "bc-signer-registry/std", - "lc-direct-call/std", - "litentry-primitives/std", - "ita-stf/std", - "itp-enclave-metrics/std", - "itp-ocall-api/std", - "itp-sgx-crypto/std", - "itp-sgx-externalities/std", - "itp-stf-executor/std", - "itp-stf-state-handler/std", - "thiserror", - "itc-direct-rpc-server/std", - "itc-direct-rpc-client/std", - "sgx_crypto_helper/default", -] -development = [] diff --git a/tee-worker/bitacross/bitacross/core/bc-task-processor/src/lib.rs b/tee-worker/bitacross/bitacross/core/bc-task-processor/src/lib.rs deleted file mode 100644 index 64171055bf..0000000000 --- a/tee-worker/bitacross/bitacross/core/bc-task-processor/src/lib.rs +++ /dev/null @@ -1,769 +0,0 @@ -// Copyright 2020-2024 Trust Computing GmbH. -// This file is part of Litentry. -// -// Litentry is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// Litentry is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with Litentry. If not, see . - -#![cfg_attr(not(feature = "std"), no_std)] - -extern crate core; -#[cfg(all(not(feature = "std"), feature = "sgx"))] -extern crate sgx_tstd as std; - -// re-export module to properly feature gate sgx and regular std environment -#[cfg(all(not(feature = "std"), feature = "sgx"))] -pub mod sgx_reexport_prelude { - pub use futures_sgx as futures; - pub use thiserror_sgx as thiserror; - pub use threadpool_sgx as threadpool; -} - -#[cfg(all(feature = "std", feature = "sgx"))] -compile_error!("feature \"std\" and feature \"sgx\" cannot be enabled at the same time"); - -#[cfg(all(not(feature = "std"), feature = "sgx"))] -pub use crate::sgx_reexport_prelude::*; - -#[cfg(feature = "std")] -use std::sync::RwLock; - -#[cfg(feature = "sgx")] -use std::sync::SgxRwLock as RwLock; - -#[cfg(feature = "std")] -use std::sync::Mutex; - -#[cfg(feature = "sgx")] -use std::sync::SgxMutex as Mutex; - -use bc_enclave_registry::EnclaveRegistryLookup; -use bc_musig2_ceremony::{ - get_current_timestamp, CeremonyCommand, CeremonyCommandTmp, CeremonyError, CeremonyErrorReason, - CeremonyEvent, CeremonyId, CeremonyRegistry, MuSig2Ceremony, SignBitcoinPayload, -}; -use bc_musig2_event::{process_event, DirectRequestStatus, Hash}; -use bc_relayer_registry::RelayerRegistryLookup; -use bc_signer_registry::SignerRegistryLookup; -use bc_task_sender::{ - init_bit_across_task_sender_storage, BitAcrossProcessingResult, BitAcrossRequest, -}; -use codec::{Decode, Encode}; -use core::{ops::Deref, time::Duration}; -use frame_support::{ensure, sp_runtime::app_crypto::sp_core::blake2_256}; -use ita_stf::TrustedCallSigned; -use itc_direct_rpc_client::{DirectRpcClient, DirectRpcClientFactory, RpcClientFactory}; -use itc_direct_rpc_server::SendRpcResponse; -use itp_enclave_metrics::EnclaveMetric; -use itp_ocall_api::{EnclaveAttestationOCallApi, EnclaveMetricsOCallApi, EnclaveOnChainOCallApi}; -use itp_sgx_crypto::{ - ecdsa::Pair as EcdsaPair, - key_repository::{AccessKey, AccessPubkey}, - schnorr::Pair as SchnorrPair, - ShieldingCryptoDecrypt, ShieldingCryptoEncrypt, -}; -use itp_sgx_externalities::SgxExternalitiesTrait; -use itp_stf_executor::traits::StfEnclaveSigning; -use itp_stf_state_handler::handle_state::HandleState; -use lc_direct_call::{ - handler::{ - kill_ceremony, nonce_share, partial_signature_share, - sign_bitcoin::{self, SignBitcoinError}, - sign_ethereum, sign_ton, - }, - CeremonyRoundCall, CeremonyRoundCallSigned, DirectCall, DirectCallSigned, -}; -use litentry_primitives::{Address32, PlainRequest}; -use log::*; -use sgx_crypto_helper::rsa3072::Rsa3072PubKey; -use sp_core::{ed25519, Pair, H256}; -use std::{ - collections::HashMap, - string::{String, ToString}, - sync::Arc, - vec, - vec::Vec, -}; -use threadpool::ThreadPool; - -#[derive(Debug, thiserror::Error, Clone)] -pub enum Error { - #[error("Request error: {0}")] - RequestError(String), - - #[error("Other error: {0}")] - OtherError(String), -} - -pub struct BitAcrossTaskContext< - SKR, - SIGNINGAK, - EKR, - BKR, - TKR, - S: StfEnclaveSigning, - H: HandleState, - O: EnclaveOnChainOCallApi, - RRL: RelayerRegistryLookup, - ERL: EnclaveRegistryLookup, - SRL: SignerRegistryLookup, - Responder, -> where - SKR: AccessKey + AccessPubkey, - SIGNINGAK: AccessKey, - EKR: AccessKey, - BKR: AccessKey, - TKR: AccessKey, - ::KeyType: ShieldingCryptoEncrypt + 'static, - Responder: SendRpcResponse, -{ - pub shielding_key: Arc, - pub signing_key_access: Arc, - pub ethereum_key_repository: Arc, - pub bitcoin_key_repository: Arc, - pub ton_key_repository: Arc, - pub enclave_signer: Arc, - pub state_handler: Arc, - pub ocall_api: Arc, - pub relayer_registry_lookup: Arc, - pub enclave_registry_lookup: Arc, - pub signer_registry_lookup: Arc, - pub signing_key_pub: [u8; 32], - pub responder: Arc, - pub ceremony_registry: Arc>>, - pub ceremony_command_tmp: Arc>, -} - -impl< - SKR, - SIGNINGAK, - EKR, - BKR, - TKR, - S: StfEnclaveSigning, - H: HandleState, - O: EnclaveOnChainOCallApi, - RRL: RelayerRegistryLookup, - ERL: EnclaveRegistryLookup, - SRL: SignerRegistryLookup, - Responder, - > BitAcrossTaskContext -where - SKR: AccessKey + AccessPubkey, - SIGNINGAK: AccessKey, - EKR: AccessKey, - BKR: AccessKey, - TKR: AccessKey, - ::KeyType: ShieldingCryptoEncrypt + 'static, - H::StateT: SgxExternalitiesTrait, - Responder: SendRpcResponse, -{ - #[allow(clippy::too_many_arguments)] - pub fn new( - shielding_key: Arc, - signing_key_access: Arc, - ethereum_key_repository: Arc, - bitcoin_key_repository: Arc, - ton_key_repository: Arc, - enclave_signer: Arc, - state_handler: Arc, - ocall_api: Arc, - relayer_registry_lookup: Arc, - enclave_registry_lookup: Arc, - signer_registry_lookup: Arc, - signing_key_pub: [u8; 32], - ceremony_registry: Arc>>, - ceremony_command_tmp: Arc>, - responder: Arc, - ) -> Self { - Self { - shielding_key, - signing_key_access, - ethereum_key_repository, - bitcoin_key_repository, - ton_key_repository, - enclave_signer, - state_handler, - ocall_api, - relayer_registry_lookup, - enclave_registry_lookup, - signer_registry_lookup, - signing_key_pub, - ceremony_registry, - ceremony_command_tmp, - responder, - } - } -} - -#[allow(clippy::type_complexity)] -pub fn run_bit_across_handler_runner< - SKR, - SIGNINGAK, - EKR, - BKR, - TKR, - S, - H, - O, - RRL, - ERL, - SRL, - Responder, ->( - context: Arc< - BitAcrossTaskContext, - >, - ceremony_commands_thread_count: u8, - ceremony_events_thread_count: u8, -) where - SKR: AccessKey + AccessPubkey + Send + Sync + 'static, - SIGNINGAK: AccessKey + Send + Sync + 'static, - EKR: AccessKey + Send + Sync + 'static, - BKR: AccessKey + Send + Sync + 'static, - TKR: AccessKey + Send + Sync + 'static, - ::KeyType: ShieldingCryptoEncrypt + ShieldingCryptoDecrypt + 'static, - S: StfEnclaveSigning + Send + Sync + 'static, - H: HandleState + Send + Sync + 'static, - H::StateT: SgxExternalitiesTrait, - O: EnclaveOnChainOCallApi + EnclaveMetricsOCallApi + EnclaveAttestationOCallApi + 'static, - RRL: RelayerRegistryLookup + Send + Sync + 'static, - ERL: EnclaveRegistryLookup + Send + Sync + 'static, - SRL: SignerRegistryLookup + Send + Sync + 'static, - Responder: SendRpcResponse + Send + Sync + 'static, -{ - // timeout tick - let ceremony_registry = context.ceremony_registry.clone(); - let ceremony_command_tmp = context.ceremony_command_tmp.clone(); - let responder = context.responder.clone(); - let time_to_live = 30u64; - let cloned_ocall_api = context.ocall_api.clone(); - std::thread::spawn(move || loop { - std::thread::sleep(Duration::from_secs(3)); - let now = get_current_timestamp(); - let mut timed_out_count: u8 = 0; - { - let mut ceremony_registry_write = ceremony_registry.write().unwrap(); - ceremony_registry_write.retain(|_, (ceremony, create_time)| { - let if_retain = now - *create_time < time_to_live; - if !if_retain { - let ceremony_rwlock = ceremony.clone(); - let ceremony = ceremony_rwlock.read().unwrap(); - let hash = blake2_256(&ceremony.get_id_ref().encode()); - let encrypted_result = SignBitcoinError::CeremonyError.encode(); - if let Err(e) = responder.send_state_with_status( - Hash::from_slice(&hash), - encrypted_result, - DirectRequestStatus::Error, - ) { - error!("Could not send response to {:?}, reason: {:?}", &hash, e); - } - timed_out_count += 1; - } - if_retain - }); - } - { - let mut command_tmp_write = ceremony_command_tmp.write().unwrap(); - command_tmp_write.retain(|_, &mut (_, create_time)| now - create_time < time_to_live); - } - if timed_out_count > 0 { - let _ = cloned_ocall_api - .update_metric(EnclaveMetric::Musig2CeremonyTimedout(timed_out_count)); - } - }); - - let bit_across_task_receiver = init_bit_across_task_sender_storage(); - let peers_map = Arc::new(Mutex::new(HashMap::<[u8; 32], DirectRpcClient>::new())); - let command_threads_pool = ThreadPool::new(ceremony_commands_thread_count.into()); - let event_threads_pool = ThreadPool::new(ceremony_events_thread_count.into()); - - while let Ok(req) = bit_across_task_receiver.recv() { - let context = context.clone(); - let event_threads_pool = event_threads_pool.clone(); - let peers_map = peers_map.clone(); - command_threads_pool.execute(move || { - if let Some((ceremony_id, command)) = handle_request(req, context.clone()) { - handle_ceremony_command( - context, - ceremony_id, - command, - event_threads_pool, - peers_map, - ); - } - }); - } - - command_threads_pool.join(); - event_threads_pool.join(); - warn!("bit_across_handler_runner loop terminated"); -} - -#[allow(clippy::type_complexity)] -fn handle_ceremony_command( - context: Arc< - BitAcrossTaskContext, - >, - ceremony_id: CeremonyId, - command: CeremonyCommand, - event_threads_pool: ThreadPool, - peers_map: Arc>>, -) where - SKR: AccessKey + AccessPubkey + Send + Sync + 'static, - SIGNINGAK: AccessKey + Send + Sync + 'static, - EKR: AccessKey + Send + Sync + 'static, - BKR: AccessKey + Send + Sync + 'static, - TKR: AccessKey + Send + Sync + 'static, - ::KeyType: ShieldingCryptoEncrypt + ShieldingCryptoDecrypt + 'static, - S: StfEnclaveSigning + Send + Sync + 'static, - H: HandleState + Send + Sync + 'static, - H::StateT: SgxExternalitiesTrait, - O: EnclaveOnChainOCallApi + EnclaveMetricsOCallApi + EnclaveAttestationOCallApi + 'static, - RRL: RelayerRegistryLookup + Send + Sync + 'static, - ERL: EnclaveRegistryLookup + Send + Sync + 'static, - SRL: SignerRegistryLookup + Send + Sync + 'static, - Responder: SendRpcResponse + Send + Sync + 'static, -{ - // check whether to store command to tmp - let is_first_round = { - context - .ceremony_registry - .read() - .unwrap() - .get(&ceremony_id) - .map(|(c, _)| c.read().unwrap().is_first_round()) - }; - match (is_first_round, &command) { - (None, CeremonyCommand::InitCeremony(_, _, _)) - | (Some(true), CeremonyCommand::SaveNonce(_, _)) - | (Some(false), CeremonyCommand::SavePartialSignature(_, _)) - | (_, CeremonyCommand::KillCeremony) => {}, - (None, CeremonyCommand::SaveNonce(_, _)) - | (Some(true), CeremonyCommand::SavePartialSignature(_, _)) => { - context - .ceremony_command_tmp - .write() - .unwrap() - .entry(ceremony_id) - .and_modify(|(command_tmp, _)| command_tmp.write().unwrap().push(command.clone())) - .or_insert((Arc::new(RwLock::new(vec![command])), get_current_timestamp())); - return - }, - (is_first_round, command) => { - error!( - "receive wrong command: is_first_round: {:?}, command: {:?}, drop it", - is_first_round, command - ); - return - }, - } - - // try to udpate peers_map - let my_identity: Address32 = - context.signing_key_access.retrieve_key().unwrap().public().0.into(); - context - .enclave_registry_lookup - .get_all() - .iter() - .for_each(|(identity, address)| { - if my_identity != *identity - && !peers_map.lock().unwrap().contains_key(identity.as_ref()) - { - info!("creating new connection to peer: {:?}", address); - match (DirectRpcClientFactory {}).create(address) { - Ok(client) => { - peers_map.lock().unwrap().insert(*identity.as_ref(), client); - }, - Err(e) => error!("Could not connect to peer {}, reason: {:?}", address, e), - } - } - }); - - // process commands and events - let mut commands_to_process = vec![command]; - while !commands_to_process.is_empty() { - let command = commands_to_process.pop().unwrap(); - - let event = process_command(context.clone(), ceremony_id.clone(), command); - - if let Some(event) = event { - // update metrics - match event { - CeremonyEvent::FirstRoundStarted(_, _, _) => { - let _ = context.ocall_api.update_metric(EnclaveMetric::Musig2CeremonyStarted); - }, - CeremonyEvent::CeremonyError(_, _) => { - let _ = context.ocall_api.update_metric(EnclaveMetric::Musig2CeremonyFailed); - }, - CeremonyEvent::CeremonyEnded(_, _, _) => { - let ceremony_start_time = - context.ceremony_registry.read().unwrap().get(&ceremony_id).unwrap().1; - let _ = context.ocall_api.update_metric(EnclaveMetric::Musig2CeremonyDuration( - Duration::from_millis(get_current_timestamp() - ceremony_start_time), - )); - }, - _ => {}, - } - - match event { - CeremonyEvent::FirstRoundStarted(_, _, _) - | CeremonyEvent::SecondRoundStarted(_, _, _) => { - // get all ceremony_command_tmp - let mut ceremony_command_tmp_write = - context.ceremony_command_tmp.write().unwrap(); - if let Some((ceremony_command_tmp, _)) = - ceremony_command_tmp_write.remove(&ceremony_id) - { - commands_to_process = ceremony_command_tmp.read().unwrap().clone(); - } - }, - CeremonyEvent::CeremonyEnded(_, _, _) | CeremonyEvent::CeremonyError(_, _) => { - // remove ceremony - { - let mut registry_write = context.ceremony_registry.write().unwrap(); - registry_write.remove(&ceremony_id); - } - { - context.ceremony_command_tmp.write().unwrap().remove(&ceremony_id); - } - }, - } - - process_event( - context.signing_key_access.clone(), - context.ocall_api.clone(), - context.responder.clone(), - context.enclave_registry_lookup.clone(), - event, - ceremony_id.clone(), - event_threads_pool.clone(), - peers_map.clone(), - context.ceremony_registry.clone(), - ); - } - } -} - -#[allow(clippy::type_complexity)] -fn process_command( - context: Arc< - BitAcrossTaskContext, - >, - ceremony_id: CeremonyId, - command: CeremonyCommand, -) -> Option -where - SKR: AccessKey + AccessPubkey + Send + Sync + 'static, - SIGNINGAK: AccessKey + Send + Sync + 'static, - EKR: AccessKey + Send + Sync + 'static, - BKR: AccessKey + Send + Sync + 'static, - TKR: AccessKey + Send + Sync + 'static, - ::KeyType: ShieldingCryptoEncrypt + ShieldingCryptoDecrypt + 'static, - S: StfEnclaveSigning + Send + Sync + 'static, - H: HandleState + Send + Sync + 'static, - H::StateT: SgxExternalitiesTrait, - O: EnclaveOnChainOCallApi + EnclaveMetricsOCallApi + EnclaveAttestationOCallApi + 'static, - RRL: RelayerRegistryLookup + Send + Sync + 'static, - ERL: EnclaveRegistryLookup + Send + Sync + 'static, - SRL: SignerRegistryLookup + Send + Sync + 'static, - Responder: SendRpcResponse + Send + Sync + 'static, -{ - match command { - CeremonyCommand::InitCeremony(signers, payload, check_run) => { - // InitCeremony should create ceremony first - let result = MuSig2Ceremony::new( - context.signing_key_pub, - signers, - payload, - context.bitcoin_key_repository.clone(), - check_run, - ); - - match result { - Ok((ceremony, event)) => { - { - let mut registry_write = context.ceremony_registry.write().unwrap(); - if registry_write.contains_key(&ceremony_id) { - let error = - CeremonyError::CeremonyInitError(CeremonyErrorReason::AlreadyExist); - return Some(CeremonyEvent::CeremonyError(vec![], error)) - } - registry_write.insert( - ceremony_id, - (Arc::new(RwLock::new(ceremony)), get_current_timestamp()), - ); - } - Some(event) - }, - Err(e) => { - error!("Could not start ceremony, error: {:?}", e); - let error = - CeremonyError::CeremonyInitError(CeremonyErrorReason::CreateCeremonyError); - Some(CeremonyEvent::CeremonyError(vec![], error)) - }, - } - }, - CeremonyCommand::SaveNonce(signer, nonce) => { - let ceremony_rwlock = - context.ceremony_registry.read().unwrap().get(&ceremony_id).cloned(); - if let Some(ceremony_rwlock) = ceremony_rwlock { - let mut ceremony_write_lock = ceremony_rwlock.0.write().unwrap(); - let event_ret = ceremony_write_lock.receive_nonce(signer, nonce); - match event_ret { - Ok(event) => event, - Err(e) => Some(CeremonyEvent::CeremonyError( - ceremony_write_lock.get_signers_except_self(), - e, - )), - } - } else { - None - } - }, - CeremonyCommand::SavePartialSignature(signer, partial_signature) => { - let ceremony_rwlock = - context.ceremony_registry.read().unwrap().get(&ceremony_id).cloned(); - if let Some(ceremony_rwlock) = ceremony_rwlock { - let mut ceremony_write_lock = ceremony_rwlock.0.write().unwrap(); - let event_ret = ceremony_write_lock.receive_partial_sign(signer, partial_signature); - match event_ret { - Ok(event) => event, - Err(e) => Some(CeremonyEvent::CeremonyError( - ceremony_write_lock.get_signers_except_self(), - e, - )), - } - } else { - None - } - }, - CeremonyCommand::KillCeremony => { - { - context.ceremony_registry.write().unwrap().remove(&ceremony_id); - } - { - context.ceremony_command_tmp.write().unwrap().remove(&ceremony_id); - } - None - }, - } -} - -#[allow(clippy::type_complexity)] -fn handle_request( - request: BitAcrossRequest, - context: Arc< - BitAcrossTaskContext, - >, -) -> Option<(CeremonyId, CeremonyCommand)> -where - SKR: AccessKey + AccessPubkey, - SIGNINGAK: AccessKey, - EKR: AccessKey, - BKR: AccessKey, - TKR: AccessKey + Send + Sync + 'static, - ::KeyType: ShieldingCryptoEncrypt + ShieldingCryptoDecrypt + 'static, - S: StfEnclaveSigning + Send + Sync + 'static, - H: HandleState + Send + Sync + 'static, - O: EnclaveOnChainOCallApi + EnclaveMetricsOCallApi + EnclaveAttestationOCallApi + 'static, - RRL: RelayerRegistryLookup + 'static, - ERL: EnclaveRegistryLookup + 'static, - SRL: SignerRegistryLookup + 'static, - Responder: SendRpcResponse + Send + Sync + 'static, -{ - match request { - BitAcrossRequest::Request(request, sender) => match handle_direct_call(request, context) { - Ok((processing_ret, to_process)) => { - if let Some(processing_ret) = processing_ret { - if let Err(e) = sender.send(Ok(processing_ret)) { - warn!("Unable to submit response back to the handler: {:?}", e); - } - } - to_process - }, - Err(e) => { - if let Err(e) = sender.send(Err(e)) { - warn!("Unable to submit response back to the handler: {:?}", e); - } - None - }, - }, - BitAcrossRequest::ShareCeremonyData(request) => - handle_ceremony_round_call(request, context).unwrap_or_default(), - } -} - -#[allow(clippy::type_complexity)] -fn handle_direct_call( - request: PlainRequest, - context: Arc< - BitAcrossTaskContext, - >, -) -> Result<(Option, Option<(CeremonyId, CeremonyCommand)>), Vec> -where - SKR: AccessKey + AccessPubkey, - SIGNINGAK: AccessKey, - EKR: AccessKey, - BKR: AccessKey, - TKR: AccessKey + Send + Sync + 'static, - ::KeyType: ShieldingCryptoEncrypt + ShieldingCryptoDecrypt + 'static, - S: StfEnclaveSigning + Send + Sync + 'static, - H: HandleState + Send + Sync + 'static, - O: EnclaveOnChainOCallApi + EnclaveMetricsOCallApi + EnclaveAttestationOCallApi + 'static, - RRL: RelayerRegistryLookup + 'static, - ERL: EnclaveRegistryLookup + 'static, - SRL: SignerRegistryLookup + 'static, - Responder: SendRpcResponse + Send + Sync + 'static, -{ - let dc = DirectCallSigned::decode(&mut request.payload.as_slice()).map_err(|e| { - error!("{}", e); - "Failed to decode payload".to_string() - })?; - - let mrenclave = match context.ocall_api.get_mrenclave_of_self() { - Ok(m) => m.m, - Err(_) => { - let err = "Failed to get mrenclave"; - error!("{}", err); - return Err(err.encode()) - }, - }; - debug!("Direct call is: {:?}", dc); - ensure!(dc.verify_signature(&mrenclave, &request.shard), "Failed to verify sig".to_string()); - match dc.call { - DirectCall::SignBitcoin(signer, payload) => { - let hash = blake2_256(&payload.encode()); - let command = sign_bitcoin::handle( - signer, - payload.clone(), - context.relayer_registry_lookup.deref(), - context.signer_registry_lookup.clone(), - context.enclave_registry_lookup.as_ref(), - false, - ) - .map_err(|e| { - error!("SignBitcoin error: {:?}", e); - e.encode() - })?; - let ret = BitAcrossProcessingResult::Submitted(hash); - Ok((Some(ret), Some((payload, command)))) - }, - DirectCall::CheckSignBitcoin(signer) => { - let payload = SignBitcoinPayload::Derived([0u8; 32].to_vec()); - let hash = blake2_256(&payload.encode()); - let command = sign_bitcoin::handle( - signer, - payload.clone(), - context.relayer_registry_lookup.deref(), - context.signer_registry_lookup.clone(), - context.enclave_registry_lookup.as_ref(), - true, - ) - .map_err(|e| { - error!("SignBitcoinCheck error: {:?}", e); - e.encode() - })?; - let ret = BitAcrossProcessingResult::Submitted(hash); - Ok((Some(ret), Some((payload, command)))) - }, - DirectCall::SignEthereum(signer, msg) => sign_ethereum::handle( - signer, - msg, - context.relayer_registry_lookup.deref(), - context.ethereum_key_repository.deref(), - ) - .map_err(|e| { - error!("SignEthereum error: {:?}", e); - e.encode() - }) - .map(|r| (Some(BitAcrossProcessingResult::Ok(r.encode())), None)), - DirectCall::SignTon(signer, payload) => sign_ton::handle( - signer, - payload, - context.relayer_registry_lookup.deref(), - context.ton_key_repository.deref(), - ) - .map_err(|e| { - error!("SignTon error: {:?}", e); - e.encode() - }) - .map(|r| (Some(BitAcrossProcessingResult::Ok(r.encode())), None)), - } -} - -#[allow(clippy::type_complexity)] -fn handle_ceremony_round_call( - request: PlainRequest, - context: Arc< - BitAcrossTaskContext, - >, -) -> Result, Vec> -where - SKR: AccessKey + AccessPubkey, - SIGNINGAK: AccessKey, - EKR: AccessKey, - BKR: AccessKey, - TKR: AccessKey + Send + Sync + 'static, - ::KeyType: ShieldingCryptoEncrypt + ShieldingCryptoDecrypt + 'static, - S: StfEnclaveSigning + Send + Sync + 'static, - H: HandleState + Send + Sync + 'static, - O: EnclaveOnChainOCallApi + EnclaveMetricsOCallApi + EnclaveAttestationOCallApi + 'static, - RRL: RelayerRegistryLookup + 'static, - ERL: EnclaveRegistryLookup + 'static, - SRL: SignerRegistryLookup + 'static, - Responder: SendRpcResponse + Send + Sync + 'static, -{ - let crc = CeremonyRoundCallSigned::decode(&mut request.payload.as_slice()).map_err(|e| { - error!("{}", e); - "Failed to decode payload".to_string() - })?; - - let mrenclave = match context.ocall_api.get_mrenclave_of_self() { - Ok(m) => m.m, - Err(_) => { - let err = "Failed to get mrenclave"; - error!("{}", err); - return Err(err.encode()) - }, - }; - debug!("Ceremony round call is: {:?}", crc); - ensure!(crc.verify_signature(&mrenclave, &request.shard), "Failed to verify sig".to_string()); - match crc.call { - CeremonyRoundCall::NonceShare(signer, message, nonce) => - nonce_share::handle(signer, &message, nonce, context.enclave_registry_lookup.clone()) - .map_err(|e| { - error!("NonceShare error: {:?}", e); - e.encode() - }) - .map(|command| Some((message, command))), - CeremonyRoundCall::PartialSignatureShare(signer, message, signature) => - partial_signature_share::handle( - signer, - &message, - signature, - context.enclave_registry_lookup.clone(), - ) - .map_err(|e| { - error!("PartialSignatureShare error: {:?}", e); - e.encode() - }) - .map(|command| Some((message, command))), - CeremonyRoundCall::KillCeremony(signer, message) => - kill_ceremony::handle(signer, context.enclave_registry_lookup.as_ref()) - .map_err(|e| { - error!("KillCeremony error: {:?}", e); - e.encode() - }) - .map(|command| Some((message, command))), - } -} diff --git a/tee-worker/bitacross/bitacross/core/bc-task-sender/Cargo.toml b/tee-worker/bitacross/bitacross/core/bc-task-sender/Cargo.toml deleted file mode 100644 index 6d0233f459..0000000000 --- a/tee-worker/bitacross/bitacross/core/bc-task-sender/Cargo.toml +++ /dev/null @@ -1,30 +0,0 @@ -[package] -name = "bc-task-sender" -authors = ["Trust Computing GmbH "] -version = "0.1.0" -edition = "2021" - -[dependencies] -futures = { workspace = true, optional = true } - -futures_sgx = { workspace = true, optional = true } -sgx_tstd = { workspace = true, features = ["net", "thread"], optional = true } - -codec = { package = "parity-scale-codec", workspace = true } -lazy_static = { workspace = true } - -litentry-primitives = { workspace = true } - -[features] -default = ["std"] -sgx = [ - "futures_sgx", - "sgx_tstd", - "futures_sgx", - "litentry-primitives/sgx", -] -std = [ - "futures", - "futures", - "litentry-primitives/std", -] diff --git a/tee-worker/bitacross/bitacross/core/bc-task-sender/src/lib.rs b/tee-worker/bitacross/bitacross/core/bc-task-sender/src/lib.rs deleted file mode 100644 index 6cbc693766..0000000000 --- a/tee-worker/bitacross/bitacross/core/bc-task-sender/src/lib.rs +++ /dev/null @@ -1,134 +0,0 @@ -// Copyright 2020-2024 Trust Computing GmbH. -// This file is part of Litentry. -// -// Litentry is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// Litentry is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with Litentry. If not, see . - -#![feature(trait_alias)] -#![cfg_attr(not(feature = "std"), no_std)] - -#[cfg(all(feature = "std", feature = "sgx"))] -compile_error!("feature \"std\" and feature \"sgx\" cannot be enabled at the same time"); - -#[cfg(all(not(feature = "std"), feature = "sgx"))] -extern crate sgx_tstd as std; - -// re-export module to properly feature gate sgx and regular std environment -#[cfg(all(not(feature = "std"), feature = "sgx"))] -pub mod sgx_reexport_prelude { - pub use futures_sgx as futures; -} - -#[cfg(all(not(feature = "std"), feature = "sgx"))] -pub use crate::sgx_reexport_prelude::*; - -use codec::{Decode, Encode}; -use futures::channel::oneshot; -use lazy_static::lazy_static; -use litentry_primitives::PlainRequest; -#[cfg(feature = "std")] -use std::sync::Mutex; -#[cfg(feature = "sgx")] -use std::sync::SgxMutex as Mutex; -use std::{ - format, - string::String, - sync::{ - mpsc::{channel, Receiver, Sender as MpscSender}, - Arc, - }, - vec::Vec, -}; - -#[derive(Debug)] -pub enum BitAcrossRequest { - Request(PlainRequest, oneshot::Sender>>), - ShareCeremonyData(PlainRequest), -} - -#[derive(Encode, Decode, Clone, Debug)] -pub enum BitAcrossProcessingResult { - // we got immediate response - Ok(Vec), - // the response will be produced in the future - Submitted([u8; 32]), -} - -#[derive(Encode, Decode, Clone)] -pub struct BitAcrossResponse { - pub payload: Vec, -} - -pub type BitAcrossSender = MpscSender; - -// Global storage of the sender. Should not be accessed directly. -lazy_static! { - static ref GLOBAL_BIT_ACROSS_TASK_SENDER: Arc>> = - Arc::new(Mutex::new(Default::default())); -} - -pub struct BitAcrossRequestSender {} -impl BitAcrossRequestSender { - pub fn new() -> Self { - Self {} - } -} - -impl Default for BitAcrossRequestSender { - fn default() -> Self { - Self::new() - } -} - -impl BitAcrossRequestSender { - pub fn send(&self, request: BitAcrossRequest) -> Result<(), String> { - // Acquire lock on extrinsic sender - let mutex_guard = GLOBAL_BIT_ACROSS_TASK_SENDER.lock().unwrap(); - let bit_across_task_sender = mutex_guard.clone().unwrap(); - // Release mutex lock, so we don't block the lock longer than necessary. - drop(mutex_guard); - - // Send the request to the receiver loop. - bit_across_task_sender.send(request)?; - - Ok(()) - } -} - -/// Initialization of the task sender. Needs to be called before any sender access. -pub fn init_bit_across_task_sender_storage() -> Receiver { - let (sender, receiver) = channel(); - // It makes no sense to handle the unwrap, as this statement fails only if the lock has been poisoned - // I believe at that point it is an unrecoverable error - let mut bit_across_task_storage = GLOBAL_BIT_ACROSS_TASK_SENDER.lock().unwrap(); - *bit_across_task_storage = Some(BitAcrossTaskSender::new(sender)); - receiver -} - -/// Wrapping struct around the actual sender. Should not be accessed directly. (unnecessary) -#[derive(Clone, Debug)] -pub struct BitAcrossTaskSender { - sender: BitAcrossSender, -} - -impl BitAcrossTaskSender { - pub fn new(sender: BitAcrossSender) -> Self { - Self { sender } - } - - fn send(&self, request: BitAcrossRequest) -> Result<(), String> { - self.sender - .send(request) - .map_err(|e| format!("Failed to send message to BitAcross Handler: {:?}", e)) - } -} diff --git a/tee-worker/bitacross/build.Dockerfile b/tee-worker/bitacross/build.Dockerfile deleted file mode 100644 index d3f5fda9d3..0000000000 --- a/tee-worker/bitacross/build.Dockerfile +++ /dev/null @@ -1,179 +0,0 @@ -# syntax=docker/dockerfile:1 -# Copyright 2021 Integritee AG -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# This is a multi-stage docker file, where the first stage is used -# for building and the second deploys the built application. - -### Builder Stage -################################################## -# todo: we might need to change this image in future -FROM litentry/litentry-tee-dev:latest AS builder -LABEL maintainer="Trust Computing GmbH " - -# set environment variables -ENV SGX_SDK=/opt/sgxsdk -ENV PATH="$PATH:${SGX_SDK}/bin:${SGX_SDK}/bin/x64:/opt/rust/bin" -ENV PKG_CONFIG_PATH="${PKG_CONFIG_PATH}:${SGX_SDK}/pkgconfig" -ENV LD_LIBRARY_PATH="${LD_LIBRARY_PATH}:${SGX_SDK}/sdk_libs" -ENV CARGO_NET_GIT_FETCH_WITH_CLI=true - -ENV SCCACHE_CACHE_SIZE="20G" -ENV SCCACHE_DIR="/opt/rust/sccache" -ENV RUSTC_WRAPPER="/opt/rust/bin/sccache" - -# Default SGX MODE is software mode -ARG SGX_MODE=SW -ENV SGX_MODE=$SGX_MODE - -ARG SGX_PRODUCTION=0 -ENV SGX_PRODUCTION=$SGX_PRODUCTION - -ENV HOME=/home/ubuntu - -ARG WORKER_MODE_ARG -ENV WORKER_MODE=$WORKER_MODE_ARG - -ARG ADDITIONAL_FEATURES_ARG -ENV ADDITIONAL_FEATURES=$ADDITIONAL_FEATURES_ARG - -ARG IMAGE_FOR_RELEASE=false -ENV IMAGE_FOR_RELEASE=$IMAGE_FOR_RELEASE - -ARG FINGERPRINT=none - -ARG SGX_COMMERCIAL_KEY -ENV SGX_COMMERCIAL_KEY=$SGX_COMMERCIAL_KEY - -WORKDIR $HOME/tee-worker/bitacross -COPY . $HOME - -RUN unset RUSTC_WRAPPER; -RUN make -RUN make mrenclave 2>&1 | grep MRENCLAVE | awk '{print $2}' > mrenclave.txt -RUN cargo test --release - - -### Base Runner Stage -################################################## -FROM node:18-bookworm-slim AS runner - -RUN apt update && apt install -y libssl-dev iproute2 jq curl protobuf-compiler -RUN corepack enable && corepack prepare pnpm@8.7.6 --activate && corepack enable pnpm - - -### Deployed CLI client -################################################## -FROM runner AS deployed-client -LABEL maintainer="Trust Computing GmbH " - -ARG SCRIPT_DIR=/usr/local/worker-cli -ARG LOG_DIR=/usr/local/log - -ENV SCRIPT_DIR=${SCRIPT_DIR} -ENV LOG_DIR=${LOG_DIR} - -COPY --from=local-builder:latest /home/ubuntu/tee-worker/bitacross/bin/bitacross-cli /usr/local/bin -COPY --from=local-builder:latest /home/ubuntu/tee-worker/bitacross/cli/*.sh /usr/local/worker-cli/ - -RUN chmod +x /usr/local/bin/bitacross-cli ${SCRIPT_DIR}/*.sh -RUN mkdir ${LOG_DIR} - -RUN ldd /usr/local/bin/bitacross-cli && /usr/local/bin/bitacross-cli --version - -ENTRYPOINT ["/usr/local/bin/bitacross-cli"] - - -### Deployed worker service -################################################## -FROM runner AS deployed-worker -LABEL maintainer="Trust Computing GmbH " - -WORKDIR /usr/local/bin - -COPY --from=local-builder:latest /opt/sgxsdk /opt/sgxsdk -COPY --from=local-builder:latest /home/ubuntu/tee-worker/bitacross/bin/* /usr/local/bin -COPY --from=local-builder:latest /home/ubuntu/tee-worker/bitacross/cli/*.sh /usr/local/worker-cli/ -COPY --from=local-builder:latest /lib/x86_64-linux-gnu/libsgx* /lib/x86_64-linux-gnu/ -COPY --from=local-builder:latest /lib/x86_64-linux-gnu/libdcap* /lib/x86_64-linux-gnu/ -COPY --from=local-builder:latest /lib/x86_64-linux-gnu/libprotobuf* /lib/x86_64-linux-gnu/ - -RUN touch spid.txt key.txt -RUN chmod +x /usr/local/bin/bitacross-worker -RUN ls -al /usr/local/bin - -# checks -ENV SGX_SDK=/opt/sgxsdk -ENV SGX_ENCLAVE_SIGNER=$SGX_SDK/bin/x64/sgx_sign -ENV LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/opt/intel/sgx-aesm-service/aesm:$SGX_SDK/sdk_libs -ENV AESM_PATH=/opt/intel/sgx-aesm-service/aesm - -RUN ldd /usr/local/bin/bitacross-worker && /usr/local/bin/bitacross-worker --version - -# TODO: use entrypoint and aesm service launch, see P-295 too -ENTRYPOINT ["/usr/local/bin/bitacross-worker"] - - -### Release worker image -################################################## -FROM ubuntu:22.04 AS worker-release -LABEL maintainer="Trust Computing GmbH " - -RUN apt update && apt install -y libssl-dev iproute2 curl protobuf-compiler - -# Adding default user litentry with uid 1000 -ARG UID=1000 -RUN adduser -u ${UID} --disabled-password --gecos '' litentry -RUN adduser -u ${UID} litentry sudo -RUN echo '%sudo ALL=(ALL) NOPASSWD:ALL' >> /etc/sudoers -# to fix Multi-node distributed worker encounters SGX permission errors. -RUN groupadd -g 121 sgx_prv && \ - groupadd -g 108 sgx && \ - usermod -aG sgx litentry && \ - usermod -aG sgx_prv litentry - -COPY --from=local-builder:latest /opt/sgxsdk /opt/sgxsdk -COPY --from=local-builder:latest /lib/x86_64-linux-gnu/libsgx* /lib/x86_64-linux-gnu/ -COPY --from=local-builder:latest /lib/x86_64-linux-gnu/libdcap* /lib/x86_64-linux-gnu/ -COPY --from=local-builder:latest /lib/x86_64-linux-gnu/libprotobuf* /lib/x86_64-linux-gnu/ - -ENV DEBIAN_FRONTEND=noninteractive -ENV TERM=xterm -ENV SGX_SDK=/opt/sgxsdk -ENV PATH="$PATH:${SGX_SDK}/bin:${SGX_SDK}/bin/x64:/opt/rust/bin" -ENV PKG_CONFIG_PATH="${PKG_CONFIG_PATH}:${SGX_SDK}/pkgconfig" -ENV LD_LIBRARY_PATH="${LD_LIBRARY_PATH}:${SGX_SDK}/sdk_libs" - -RUN mkdir -p /origin /data - -COPY --from=local-builder:latest /home/ubuntu/tee-worker/bitacross/bin/* /origin -COPY --from=local-builder:latest /home/ubuntu/tee-worker/bitacross/mrenclave.txt /origin -COPY --from=local-builder:latest /home/ubuntu/tee-worker/bitacross/entrypoint.sh /usr/local/bin/entrypoint.sh - -WORKDIR /origin - -RUN touch spid.txt key.txt && \ - cp ./bitacross-* /usr/local/bin/ && \ - chmod +x /usr/local/bin/bitacross-* && \ - chmod +x /usr/local/bin/entrypoint.sh && \ - ls -al /usr/local/bin - -RUN ldd /usr/local/bin/bitacross-worker && /usr/local/bin/bitacross-worker --version - -ENV DATA_DIR=/data - -USER litentry -WORKDIR /data - -ENTRYPOINT ["/usr/local/bin/entrypoint.sh"] \ No newline at end of file diff --git a/tee-worker/bitacross/cli/Cargo.toml b/tee-worker/bitacross/cli/Cargo.toml deleted file mode 100644 index 86bcdb8911..0000000000 --- a/tee-worker/bitacross/cli/Cargo.toml +++ /dev/null @@ -1,54 +0,0 @@ -[package] -name = "bitacross-cli" -version = "0.0.1" -authors = ['Trust Computing GmbH ', 'Integritee AG '] -edition = "2021" - -[dependencies] -base58 = { workspace = true } -chrono = "*" -clap = { version = "=4.1.0", features = ["derive"] } -codec = { package = "parity-scale-codec", workspace = true, features = ["std"] } -env_logger = { workspace = true } -hdrhistogram = "7.5.0" -hex = { workspace = true, features = ["std"] } -log = { workspace = true, features = ["std"] } -rand = "0.8.5" -rayon = "1.5.1" -regex = "1.9.5" -reqwest = { version = "0.11", features = ["blocking", "json"] } -serde = { workspace = true, features = ["std"] } -serde_json = { workspace = true, features = ["std"] } -thiserror = { workspace = true } -urlencoding = "2.1.3" - -sgx_crypto_helper = { workspace = true, features = ["ucrypto_help"] } -substrate-api-client = { workspace = true } -substrate-client-keystore = { workspace = true } - -sp-application-crypto = { workspace = true, features = ["std"] } -sp-core = { workspace = true, features = ["std"] } -sp-keyring = { workspace = true } -sp-keystore = { workspace = true, features = ["std"] } -sp-runtime = { workspace = true, features = ["std"] } - -bc-musig2-ceremony = { path = "../bitacross/core/bc-musig2-ceremony" } -ita-parentchain-interface = { package = "bc-ita-parentchain-interface", path = "../app-libs/parentchain-interface" } -ita-stf = { package = "bc-ita-stf", path = "../app-libs/stf" } -lc-direct-call = { path = "../litentry/core/direct-call" } - -itc-rpc-client = { workspace = true } -itp-node-api = { workspace = true, features = ["std"] } -itp-rpc = { workspace = true, features = ["std"] } -itp-sgx-crypto = { workspace = true, features = ["std"] } -itp-stf-primitives = { workspace = true, features = ["std"] } -itp-types = { workspace = true, features = ["std"] } -itp-utils = { workspace = true, features = ["std"] } -litentry-primitives = { workspace = true, features = ["std"] } - -[features] -default = [] -offchain-worker = [] -development = [] -# dcap feature flag is not used in this crate, but for easier build purposes only it present here as well -dcap = [] diff --git a/tee-worker/bitacross/cli/README.md b/tee-worker/bitacross/cli/README.md deleted file mode 100644 index a1eb6463f5..0000000000 --- a/tee-worker/bitacross/cli/README.md +++ /dev/null @@ -1,35 +0,0 @@ -# Integritee CLI client -Interact with the Integritee chain and workers from the command line - -Includes -* keystore (incompatible with polkadot js app json) -* basic balance transfer -* Integritee-specific calls - -## examples -``` -> ./bitacross-cli transfer //Bob //Alice 12345 -> ./bitacross-cli -u ws://127.0.0.1 list-workers -number of workers registered: 1 -Enclave 1 - AccountId: 5HN8RGEiJuc9iNA3vfiYj7Lk6ULWzBZXvSDheohBu3usSUqn - MRENCLAVE: 4GMb72Acyg8hnnnGEJ89jZK5zxNC4LvSe2ME96wLRV6J - RA timestamp: 2022-03-16 10:43:12.001 UTC - URL: wss://127.0.0.1:2345 -> ./bitacross-cli -P 2345 trusted --direct --mrenclave 4GMb72Acyg8hnnn -GE4LvSe2ME96wLRV6J unshield-funds //Bob //Alice 12345 -from ss58 is 5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty -to ss58 is 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY -send trusted call unshield_funds from 5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty to 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY: 12345 -Trusted call 0x69ddfd1698bd2d629180c2dca34ce7add087526c51f43cf68245241b3f13154e is Submitted -Trusted call 0x69ddfd1698bd2d629180c2dca34ce7add087526c51f43cf68245241b3f13154e is Invalid - -``` - -## housekeeping tasks - -populate all TCBinfo's Intel has published -``` -../target/release/bitacross-cli register-tcb-info //Alice --fmspc 00606a000000 -../target/release/bitacross-cli register-tcb-info //Alice --all -``` diff --git a/tee-worker/bitacross/cli/benchmark.sh b/tee-worker/bitacross/cli/benchmark.sh deleted file mode 100755 index 080651fdc6..0000000000 --- a/tee-worker/bitacross/cli/benchmark.sh +++ /dev/null @@ -1,61 +0,0 @@ -#!/bin/bash - -while getopts ":m:p:A:u:V:C:" opt; do - case $opt in - m) - READMRENCLAVE=$OPTARG - ;; - p) - NPORT=$OPTARG - ;; - A) - WORKER1PORT=$OPTARG - ;; - u) - NODEURL=$OPTARG - ;; - V) - WORKER1URL=$OPTARG - ;; - C) - CLIENT_BIN=$OPTARG - ;; - *) - ;; - esac -done - -# using default port if none given as arguments -NPORT=${NPORT:-9944} -NODEURL=${NODEURL:-"ws://127.0.0.1"} - -WORKER1PORT=${WORKER1PORT:-2000} -WORKER1URL=${WORKER1URL:-"wss://127.0.0.1"} - -CLIENT_BIN=${CLIENT_BIN:-"./../bin/bitacross-cli"} - -echo "Using client binary ${CLIENT_BIN}" -echo "Using node uri ${NODEURL}:${NPORT}" -echo "Using trusted-worker uri ${WORKER1URL}:${WORKER1PORT}" - -CLIENTWORKER1="${CLIENT_BIN} -p ${NPORT} -P ${WORKER1PORT} -u ${NODEURL} -U ${WORKER1URL}" - -if [ "$READMRENCLAVE" = "file" ] -then - read -r MRENCLAVE <<< "$(cat ~/mrenclave.b58)" - echo "Reading MRENCLAVE from file: ${MRENCLAVE}" -else - # this will always take the first MRENCLAVE found in the registry !! - read -r MRENCLAVE <<< "$($CLIENTWORKER1 list-workers | awk '/ MRENCLAVE: / { print $2; exit }')" - echo "Reading MRENCLAVE from worker list: ${MRENCLAVE}" -fi -[[ -z $MRENCLAVE ]] && { echo "MRENCLAVE is empty. cannot continue" ; exit 1; } - -# needed when many clients are started -ulimit -S -n 4096 - -echo "Starting benchmark" -${CLIENTWORKER1} trusted --direct --mrenclave "${MRENCLAVE}" benchmark 20 100 -w -echo "" - -exit 0 diff --git a/tee-worker/bitacross/cli/lit_parentchain_nonce.sh b/tee-worker/bitacross/cli/lit_parentchain_nonce.sh deleted file mode 100755 index 95eda7d275..0000000000 --- a/tee-worker/bitacross/cli/lit_parentchain_nonce.sh +++ /dev/null @@ -1,69 +0,0 @@ -#!/bin/bash - -# Copyright 2020-2023 Trust Computing GmbH. - -while getopts ":p:A:B:u:W:V:C:" opt; do - case $opt in - p) - NPORT=$OPTARG - ;; - A) - WORKER1PORT=$OPTARG - ;; - u) - NODEURL=$OPTARG - ;; - V) - WORKER1URL=$OPTARG - ;; - C) - CLIENT_BIN=$OPTARG - ;; - esac -done - -# Using default port if none given as arguments. -NPORT=${NPORT:-9944} -NODEURL=${NODEURL:-"ws://litentry-node"} - -WORKER1PORT=${WORKER1PORT:-2000} -WORKER1URL=${WORKER1URL:-"wss://litentry-node"} - -CLIENT_BIN=${CLIENT_BIN:-"./../bin/bitacross-cli"} - -echo "Using client binary $CLIENT_BIN" -echo "Using node uri $NODEURL:$NPORT" -echo "Using trusted-worker uri $WORKER1URL:$WORKER1PORT" -echo "" - -CLIENT="$CLIENT_BIN -p $NPORT -P $WORKER1PORT -u $NODEURL -U $WORKER1URL" -echo "CLIENT is: $CLIENT" - -echo "* Query on-chain enclave registry:" -WORKERS=$($CLIENT list-workers) -echo "WORKERS: " -echo "${WORKERS}" -echo "" - -if [ "$READMRENCLAVE" = "file" ] -then - read MRENCLAVE <<< $(cat ~/mrenclave.b58) - echo "Reading MRENCLAVE from file: ${MRENCLAVE}" -else - # This will always take the first MRENCLAVE found in the registry !! - read MRENCLAVE <<< $(echo "$WORKERS" | awk '/ MRENCLAVE: / { print $2; exit }') - echo "Reading MRENCLAVE from worker list: ${MRENCLAVE}" -fi -[[ -z $MRENCLAVE ]] && { echo "MRENCLAVE is empty. cannot continue" ; exit 1; } - -sleep 10 -echo "* Send wrong parentchain extrinsic" -${CLIENT} trusted --mrenclave $MRENCLAVE --direct send-erroneous-parentchain-call -echo "" - -sleep 20 -# wait for 10 `ParentchainBlockProcessed` events, which should take around 2 min (1 worker) -# if the incoming parentchain extrinsic is blocked (due to the wrong nonce), there won't be -# such many events. -set -e -timeout -v --foreground 150s $CLIENT listen -e 10 diff --git a/tee-worker/bitacross/cli/lit_ts_integration_test.sh b/tee-worker/bitacross/cli/lit_ts_integration_test.sh deleted file mode 100755 index 04c297a7c3..0000000000 --- a/tee-worker/bitacross/cli/lit_ts_integration_test.sh +++ /dev/null @@ -1,59 +0,0 @@ -#!/bin/bash - -# Copyright 2020-2024 Trust Computing GmbH. - -set -euo pipefail - -while getopts ":p:A:u:W:V:C:" opt; do - case $opt in - p) - NPORT=$OPTARG - ;; - A) - WORKER1PORT=$OPTARG - ;; - u) - NODEURL=$OPTARG - ;; - W) - NODEHTTPURL=$OPTARG - ;; - V) - WORKER1URL=$OPTARG - ;; - C) - CLIENT_BIN=$OPTARG - ;; - esac -done - -# Using default port if none given as arguments. -NPORT=${NPORT:-9944} -NODEURL=${NODEURL:-"ws://litentry-node"} -NODEHTTPURL=${NODEHTTPURL:-"http://litentry-node"} -WORKER1PORT=${WORKER1PORT:-2011} -WORKER1URL=${WORKER1URL:-"ws://bitacross-worker-1"} - -CLIENT_BIN=${CLIENT_BIN:-"/usr/local/bin/bitacross-cli"} - -CLIENT="${CLIENT_BIN} -p ${NPORT} -P ${WORKER1PORT} -u ${NODEURL} -U ${WORKER1URL}" - -function usage() { - echo "" - echo "This is a script for bitacross-worker integration ts tests. Pass test name as first argument" - echo "" -} - -[ $# -ne 1 ] && (usage; exit 1) -TEST=$1 - -echo "Using client binary $CLIENT_BIN" -echo "Using node uri $NODEURL:$NPORT" -echo "Using trusted-worker uri $WORKER1URL:$WORKER1PORT" -echo "Using node http uri $NODEHTTPURL:$NPORT" -echo "" - -cd /ts-tests -pnpm install - -NODE_ENV=staging pnpm --filter integration-tests run test $TEST diff --git a/tee-worker/bitacross/cli/src/attesteer/commands/mod.rs b/tee-worker/bitacross/cli/src/attesteer/commands/mod.rs deleted file mode 100644 index 70119bf399..0000000000 --- a/tee-worker/bitacross/cli/src/attesteer/commands/mod.rs +++ /dev/null @@ -1,23 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -mod send_dcap_quote; -mod send_ias_attestation; - -pub use self::{ - send_dcap_quote::SendDcapQuoteCmd, send_ias_attestation::SendIasAttestationReportCmd, -}; diff --git a/tee-worker/bitacross/cli/src/attesteer/commands/send_dcap_quote.rs b/tee-worker/bitacross/cli/src/attesteer/commands/send_dcap_quote.rs deleted file mode 100644 index 6ee0baf02f..0000000000 --- a/tee-worker/bitacross/cli/src/attesteer/commands/send_dcap_quote.rs +++ /dev/null @@ -1,65 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use crate::{command_utils::get_worker_api_direct, Cli}; -use itc_rpc_client::direct_client::DirectApi; -use itp_rpc::{Id, RpcRequest, RpcResponse, RpcReturnValue}; -use itp_types::DirectRequestStatus; -use itp_utils::FromHexPrefixed; -use log::*; -use std::fs::read_to_string; - -/// Forward DCAP quote for verification. -#[derive(Debug, Clone, Parser)] -pub struct SendDcapQuoteCmd { - /// Hex encoded DCAP quote filename. - quote: String, -} - -impl SendDcapQuoteCmd { - pub fn run(&self, cli: &Cli) { - let direct_api = get_worker_api_direct(cli); - let hex_encoded_quote = match read_to_string(&self.quote) { - Ok(hex_encoded_quote) => hex_encoded_quote, - Err(e) => panic!("Opening hex encoded DCAP quote file failed: {:?}", e), - }; - - let rpc_method = "attesteer_forwardDcapQuote".to_owned(); - let jsonrpc_call: String = RpcRequest::compose_jsonrpc_call( - Id::Text("1".to_string()), - rpc_method, - vec![hex_encoded_quote], - ) - .unwrap(); - - let rpc_response_str = direct_api.get(&jsonrpc_call).unwrap(); - - // Decode RPC response. - let Ok(rpc_response) = serde_json::from_str::(&rpc_response_str) else { - panic!("Can't parse RPC response: '{rpc_response_str}'"); - }; - let rpc_return_value = match RpcReturnValue::from_hex(&rpc_response.result) { - Ok(rpc_return_value) => rpc_return_value, - Err(e) => panic!("Failed to decode RpcReturnValue: {:?}", e), - }; - - match rpc_return_value.status { - DirectRequestStatus::Ok => println!("DCAP quote verification succeded."), - _ => error!("DCAP quote verification failed"), - } - } -} diff --git a/tee-worker/bitacross/cli/src/attesteer/commands/send_ias_attestation.rs b/tee-worker/bitacross/cli/src/attesteer/commands/send_ias_attestation.rs deleted file mode 100644 index af4128b138..0000000000 --- a/tee-worker/bitacross/cli/src/attesteer/commands/send_ias_attestation.rs +++ /dev/null @@ -1,66 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use itc_rpc_client::direct_client::DirectApi; -use itp_rpc::{Id, RpcRequest, RpcResponse, RpcReturnValue}; -use itp_types::DirectRequestStatus; -use itp_utils::FromHexPrefixed; -use log::*; -use std::fs::read_to_string; - -use crate::{command_utils::get_worker_api_direct, Cli}; - -/// Forward IAS attestation report for verification. -#[derive(Debug, Clone, Parser)] -pub struct SendIasAttestationReportCmd { - /// Hex encoded IAS attestation report filename. - report: String, -} - -impl SendIasAttestationReportCmd { - pub fn run(&self, cli: &Cli) { - let direct_api = get_worker_api_direct(cli); - let hex_encoded_report = match read_to_string(&self.report) { - Ok(hex_encoded_report) => hex_encoded_report, - Err(e) => panic!("Opening hex encoded IAS attestation report file failed: {:?}", e), - }; - - let rpc_method = "attesteer_forwardIasAttestationReport".to_owned(); - let jsonrpc_call: String = RpcRequest::compose_jsonrpc_call( - Id::Text("1".to_string()), - rpc_method, - vec![hex_encoded_report], - ) - .unwrap(); - - let rpc_response_str = direct_api.get(&jsonrpc_call).unwrap(); - - // Decode RPC response. - let Ok(rpc_response) = serde_json::from_str::(&rpc_response_str) else { - panic!("Can't parse RPC response: '{rpc_response_str}'"); - }; - let rpc_return_value = match RpcReturnValue::from_hex(&rpc_response.result) { - Ok(rpc_return_value) => rpc_return_value, - Err(e) => panic!("Failed to decode RpcReturnValue: {:?}", e), - }; - - match rpc_return_value.status { - DirectRequestStatus::Ok => println!("IAS attestation report verification succeded."), - _ => error!("IAS attestation report verification failed"), - } - } -} diff --git a/tee-worker/bitacross/cli/src/attesteer/mod.rs b/tee-worker/bitacross/cli/src/attesteer/mod.rs deleted file mode 100644 index 9f03c59065..0000000000 --- a/tee-worker/bitacross/cli/src/attesteer/mod.rs +++ /dev/null @@ -1,41 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use crate::Cli; - -use self::commands::{SendDcapQuoteCmd, SendIasAttestationReportCmd}; - -mod commands; - -/// Attesteer subcommands for the CLI. -#[derive(Debug, clap::Subcommand)] -pub enum AttesteerCommand { - /// Forward DCAP quote for verification. - SendDCAPQuote(SendDcapQuoteCmd), - - /// Forward IAS attestation report for verification. - SendIASAttestationReport(SendIasAttestationReportCmd), -} - -impl AttesteerCommand { - pub fn run(&self, cli: &Cli) { - match self { - AttesteerCommand::SendDCAPQuote(cmd) => cmd.run(cli), - AttesteerCommand::SendIASAttestationReport(cmd) => cmd.run(cli), - } - } -} diff --git a/tee-worker/bitacross/cli/src/base_cli/commands/balance.rs b/tee-worker/bitacross/cli/src/base_cli/commands/balance.rs deleted file mode 100644 index cea86ae48b..0000000000 --- a/tee-worker/bitacross/cli/src/base_cli/commands/balance.rs +++ /dev/null @@ -1,39 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use crate::{ - command_utils::{get_accountid_from_str, get_chain_api}, - Cli, CliResult, CliResultOk, -}; -use substrate_api_client::GetAccountInformation; - -#[derive(Parser)] -pub struct BalanceCommand { - /// AccountId in ss58check format - account: String, -} - -impl BalanceCommand { - pub(crate) fn run(&self, cli: &Cli) -> CliResult { - let api = get_chain_api(cli); - let accountid = get_accountid_from_str(&self.account); - let balance = - if let Some(data) = api.get_account_data(&accountid).unwrap() { data.free } else { 0 }; - println!("{}", balance); - Ok(CliResultOk::Balance { balance }) - } -} diff --git a/tee-worker/bitacross/cli/src/base_cli/commands/faucet.rs b/tee-worker/bitacross/cli/src/base_cli/commands/faucet.rs deleted file mode 100644 index 256b59a72e..0000000000 --- a/tee-worker/bitacross/cli/src/base_cli/commands/faucet.rs +++ /dev/null @@ -1,65 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use crate::{ - command_utils::{get_accountid_from_str, get_chain_api}, - Cli, CliResult, CliResultOk, -}; -use codec::Compact; -use itp_types::{parentchain::AccountId, OpaqueCall}; -use sp_keyring::AccountKeyring; -use sp_runtime::MultiAddress; -use std::vec::Vec; -use substrate_api_client::{ - ac_compose_macros::{compose_call, compose_extrinsic_offline}, - SubmitExtrinsic, -}; - -const PREFUNDING_AMOUNT: u128 = 1_000_000_000; - -#[derive(Parser)] -pub struct FaucetCommand { - /// Account(s) to be funded, ss58check encoded - #[clap(num_args = 1.., required = true)] - accounts: Vec, -} - -impl FaucetCommand { - pub(crate) fn run(&self, cli: &Cli) -> CliResult { - let mut api = get_chain_api(cli); - api.set_signer(AccountKeyring::Alice.pair().into()); - let mut nonce = api.get_nonce().unwrap(); - for account in &self.accounts { - let to = get_accountid_from_str(account); - let call = OpaqueCall::from_tuple(&compose_call!( - api.metadata(), - "Balances", - "transfer_keep_alive", - MultiAddress::::Id(to.clone()), - Compact(PREFUNDING_AMOUNT) - )); - #[allow(clippy::redundant_clone)] - let xt = compose_extrinsic_offline!(api.signer().unwrap(), call, api.extrinsic_params(nonce)); - // send and watch extrinsic until finalized - println!("Faucet drips to {} (Alice's nonce={})", to, nonce); - let _blockh = api.submit_extrinsic(xt).unwrap(); - nonce += 1; - } - - Ok(CliResultOk::None) - } -} diff --git a/tee-worker/bitacross/cli/src/base_cli/commands/listen.rs b/tee-worker/bitacross/cli/src/base_cli/commands/listen.rs deleted file mode 100644 index 9213b45f76..0000000000 --- a/tee-worker/bitacross/cli/src/base_cli/commands/listen.rs +++ /dev/null @@ -1,88 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use crate::{command_utils::get_chain_api, Cli, CliResult, CliResultOk}; - -use itp_types::parentchain::events::{BalanceTransfer, ParentchainBlockProcessed}; -use log::*; -use substrate_api_client::{GetChainInfo, SubscribeEvents}; - -#[derive(Parser)] -pub struct ListenCommand { - /// exit after given number of parentchain events - #[clap(short, long = "exit-after")] - events: Option, - - /// exit after given number of blocks - #[clap(short, long = "await-blocks")] - blocks: Option, -} - -impl ListenCommand { - pub(crate) fn run(&self, cli: &Cli) -> CliResult { - println!("{:?} {:?}", self.events, self.blocks); - let api = get_chain_api(cli); - info!("Subscribing to events (solo or para)"); - let mut count = 0u32; - let mut blocks = 0u32; - let mut subscription = api.subscribe_events().unwrap(); - loop { - if let Some(e) = self.events { - if count >= e { - return Ok(CliResultOk::None) - } - }; - if let Some(b) = self.blocks { - if blocks >= b { - return Ok(CliResultOk::None) - } - }; - - let events = subscription.next_events_from_metadata().unwrap().unwrap(); - blocks += 1; - let header = api.get_header(None).unwrap().unwrap(); - println!("block number (HEAD): {}", header.number); - for event in events.iter() { - let event = event.unwrap(); - count += 1; - match event.pallet_name() { - "System" => continue, - "TransactionPayment" => continue, - "Treasury" => continue, - "Balances" => match event.variant_name() { - "Deposit" => continue, - "Withdraw" => continue, - "Transfer" => - if let Ok(Some(ev)) = event.as_event::() { - println!("{:?}", ev); - }, - _ => println!("{}::{}", event.pallet_name(), event.variant_name()), - }, - "Teebag" => match event.variant_name() { - "ParentchainBlockProcessed" => { - if let Ok(Some(ev)) = event.as_event::() { - println!("{:?}", ev); - } - }, - _ => println!("{}::{}", event.pallet_name(), event.variant_name()), - }, - _ => println!("{}::{}", event.pallet_name(), event.variant_name()), - } - } - } - } -} diff --git a/tee-worker/bitacross/cli/src/base_cli/commands/litentry/mod.rs b/tee-worker/bitacross/cli/src/base_cli/commands/litentry/mod.rs deleted file mode 100644 index 20182fa371..0000000000 --- a/tee-worker/bitacross/cli/src/base_cli/commands/litentry/mod.rs +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright 2020-2024 Trust Computing GmbH. -// This file is part of Litentry. -// -// Litentry is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// Litentry is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with Litentry. If not, see . diff --git a/tee-worker/bitacross/cli/src/base_cli/commands/mod.rs b/tee-worker/bitacross/cli/src/base_cli/commands/mod.rs deleted file mode 100644 index 033b15b253..0000000000 --- a/tee-worker/bitacross/cli/src/base_cli/commands/mod.rs +++ /dev/null @@ -1,6 +0,0 @@ -pub mod balance; -pub mod faucet; -pub mod listen; -pub mod litentry; -pub mod register_tcb_info; -pub mod transfer; diff --git a/tee-worker/bitacross/cli/src/base_cli/commands/register_tcb_info.rs b/tee-worker/bitacross/cli/src/base_cli/commands/register_tcb_info.rs deleted file mode 100644 index 4ab9b55a45..0000000000 --- a/tee-worker/bitacross/cli/src/base_cli/commands/register_tcb_info.rs +++ /dev/null @@ -1,146 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use crate::{ - command_utils::{get_chain_api, *}, - Cli, CliResult, CliResultOk, -}; -use itp_node_api::api_client::TEEBAG; -use itp_types::{parentchain::Hash, OpaqueCall}; -use itp_utils::ToHexPrefixed; -use log::*; -use regex::Regex; -use serde::Deserialize; -use substrate_api_client::{ - ac_compose_macros::{compose_call, compose_extrinsic_offline}, - SubmitAndWatch, XtStatus, -}; -use urlencoding; - -#[derive(Debug, Deserialize)] -struct Platform { - fmspc: String, - #[serde(rename = "platform")] - _platform: String, -} - -#[derive(Parser)] -pub struct RegisterTcbInfoCommand { - /// Sender's parentchain AccountId in ss58check format. - sender: String, - /// Intel's Family-Model-Stepping-Platform-Custom SKU. 6-Byte non-prefixed hex value - #[clap(short, long, action, conflicts_with = "all")] - fmspc: Option, - /// registers all fmspc currently published by Intel - #[clap(short, long, action)] - all: bool, -} - -impl RegisterTcbInfoCommand { - pub(crate) fn run(&self, cli: &Cli) -> CliResult { - let mut chain_api = get_chain_api(cli); - - // Get the sender. - let from = get_pair_from_str(&self.sender); - chain_api.set_signer(from.into()); - - let fmspcs = if self.all { - trace!("fetching all fmspc's from api.trustedservices.intel.com"); - let fmspcs = reqwest::blocking::get( - "https://api.trustedservices.intel.com/sgx/certification/v4/fmspcs", - ) - .unwrap(); - let fmspcs: Vec = fmspcs.json().expect("Error parsing JSON"); - println!("{:?}", fmspcs); - fmspcs.into_iter().map(|f| f.fmspc).collect() - } else if let Some(fmspc) = self.fmspc.clone() { - vec![fmspc] - } else { - panic!("must specify either '--all' or '--fmspc'"); - }; - let mut nonce = chain_api.get_nonce().unwrap(); - let xt_hashes: Vec<(String, Option)> = fmspcs - .into_iter() - .map(|fmspc| { - println!( - "fetching tcb info for fmspc {} from api.trustedservices.intel.com", - fmspc - ); - let response = reqwest::blocking::get(format!( - "https://api.trustedservices.intel.com/sgx/certification/v4/tcb?fmspc={}", - fmspc - )) - .unwrap(); - //extract certificate chain from header - let certificate_chain = urlencoding::decode( - response.headers().get("TCB-Info-Issuer-Chain").unwrap().to_str().unwrap(), - ) - .unwrap() - .to_string(); - trace!("certificate chain: \n{}", certificate_chain); - - let body = response.text().unwrap(); - trace!("raw json: \n{}", body); - let re = Regex::new(r#"tcbInfo\"\s?:(\{.*\}),\s?\"signature"#).unwrap(); - let tcb_info = &re.captures(&body).unwrap()[1]; - let re = Regex::new(r#"\"signature\"\s?:\s?\"(.*)\"\}"#).unwrap(); - let intel_signature_hex = &re.captures(&body).unwrap()[1]; - trace!("TCB info: {}", tcb_info); - trace!("signature: {}", intel_signature_hex); - - let intel_signature = hex::decode(intel_signature_hex).unwrap(); - - let call = OpaqueCall::from_tuple(&compose_call!( - chain_api.metadata(), - TEEBAG, - "register_tcb_info", - tcb_info, - intel_signature, - certificate_chain - )); - - trace!( - "encoded call to be sent as extrinsic with nonce {}: {}", - nonce, - call.to_hex() - ); - - let xt = compose_extrinsic_offline!( - chain_api.clone().signer().unwrap(), - call, - chain_api.extrinsic_params(nonce) - ); - nonce += 1; - match chain_api.submit_and_watch_extrinsic_until(xt, XtStatus::InBlock) { - Ok(xt_report) => { - println!( - "[+] register_tcb_info. extrinsic hash: {:?} / status: {:?}", - xt_report.extrinsic_hash, xt_report.status, - ); - (fmspc, Some(xt_report.extrinsic_hash)) - }, - Err(e) => { - error!("register_tcb_info extrinsic failed {:?}", e); - (fmspc, None) - }, - } - }) - .collect(); - println!("{:?}", xt_hashes); - Ok(CliResultOk::None) - } -} diff --git a/tee-worker/bitacross/cli/src/base_cli/commands/transfer.rs b/tee-worker/bitacross/cli/src/base_cli/commands/transfer.rs deleted file mode 100644 index d8b26f0b90..0000000000 --- a/tee-worker/bitacross/cli/src/base_cli/commands/transfer.rs +++ /dev/null @@ -1,61 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use crate::{ - command_utils::{get_accountid_from_str, get_chain_api, *}, - Cli, CliResult, CliResultOk, -}; -use ita_parentchain_interface::integritee::Balance; -use log::*; -use sp_core::{crypto::Ss58Codec, Pair}; -use substrate_api_client::{ - extrinsic::BalancesExtrinsics, GetAccountInformation, SubmitAndWatch, XtStatus, -}; - -#[derive(Parser)] -pub struct TransferCommand { - /// sender's AccountId in ss58check format - from: String, - - /// recipient's AccountId in ss58check format - to: String, - - /// amount to be transferred - amount: Balance, -} - -impl TransferCommand { - pub(crate) fn run(&self, cli: &Cli) -> CliResult { - let from_account = get_pair_from_str(&self.from); - let to_account = get_accountid_from_str(&self.to); - info!("from ss58 is {}", from_account.public().to_ss58check()); - info!("to ss58 is {}", to_account.to_ss58check()); - let mut api = get_chain_api(cli); - api.set_signer(from_account.into()); - let xt = api.balance_transfer_allow_death(to_account.clone().into(), self.amount); - let tx_report = api.submit_and_watch_extrinsic_until(xt, XtStatus::InBlock).unwrap(); - println!( - "[+] L1 extrinsic success. extrinsic hash: {:?} / status: {:?}", - tx_report.extrinsic_hash, tx_report.status - ); - let result = api.get_account_data(&to_account).unwrap().unwrap(); - let balance = result.free; - println!("balance for {} is now {}", to_account, balance); - - Ok(CliResultOk::Balance { balance }) - } -} diff --git a/tee-worker/bitacross/cli/src/base_cli/mod.rs b/tee-worker/bitacross/cli/src/base_cli/mod.rs deleted file mode 100644 index d74d538f2f..0000000000 --- a/tee-worker/bitacross/cli/src/base_cli/mod.rs +++ /dev/null @@ -1,176 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use crate::{ - base_cli::commands::{ - balance::BalanceCommand, faucet::FaucetCommand, listen::ListenCommand, - register_tcb_info::RegisterTcbInfoCommand, transfer::TransferCommand, - }, - command_utils::*, - Cli, CliResult, CliResultOk, ED25519_KEY_TYPE, SR25519_KEY_TYPE, -}; -use base58::ToBase58; -use chrono::{DateTime, Utc}; -use clap::Subcommand; -use itc_rpc_client::direct_client::DirectApi; -use itp_node_api::api_client::PalletTeebagApi; -use itp_types::WorkerType; -use sp_core::crypto::Ss58Codec; -use sp_keystore::Keystore; -use std::{ - path::PathBuf, - time::{Duration, UNIX_EPOCH}, -}; -use substrate_client_keystore::LocalKeystore; - -mod commands; - -#[derive(Subcommand)] -pub enum BaseCommand { - /// query parentchain balance for AccountId - Balance(BalanceCommand), - - /// generates a new account for the integritee chain in your local keystore - NewAccount, - - /// lists all accounts in your local keystore for the integritee chain - ListAccounts, - - /// query node metadata and print it as json to stdout - PrintMetadata, - - /// query sgx-runtime metadata and print it as json to stdout - PrintSgxMetadata, - - /// send some bootstrapping funds to supplied account(s) - Faucet(FaucetCommand), - - /// transfer funds from one parentchain account to another - Transfer(TransferCommand), - - /// query enclave registry and list all workers - ListWorkers, - - /// listen to parentchain events - Listen(ListenCommand), - - /// Register TCB info for FMSPC - RegisterTcbInfo(RegisterTcbInfoCommand), - - // Litentry's commands below - /// query sgx-runtime metadata and print the raw (hex-encoded) metadata to stdout - /// we could have added a parameter like `--raw` to `PrintSgxMetadata`, but - /// we want to keep our changes isolated - PrintSgxMetadataRaw, -} - -impl BaseCommand { - pub fn run(&self, cli: &Cli) -> CliResult { - match self { - BaseCommand::Balance(cmd) => cmd.run(cli), - BaseCommand::NewAccount => new_account(), - BaseCommand::ListAccounts => list_accounts(), - BaseCommand::PrintMetadata => print_metadata(cli), - BaseCommand::PrintSgxMetadata => print_sgx_metadata(cli), - BaseCommand::Faucet(cmd) => cmd.run(cli), - BaseCommand::Transfer(cmd) => cmd.run(cli), - BaseCommand::ListWorkers => list_workers(cli), - BaseCommand::Listen(cmd) => cmd.run(cli), - BaseCommand::RegisterTcbInfo(cmd) => cmd.run(cli), - // Litentry's commands below - BaseCommand::PrintSgxMetadataRaw => print_sgx_metadata_raw(cli), - } - } -} - -fn new_account() -> CliResult { - let store = LocalKeystore::open(PathBuf::from(&KEYSTORE_PATH), None).unwrap(); - let key = LocalKeystore::sr25519_generate_new(&store, SR25519_KEY_TYPE, None).unwrap(); - let key_base58 = key.to_ss58check(); - drop(store); - println!("{}", key_base58); - Ok(CliResultOk::PubKeysBase58 { - pubkeys_sr25519: Some(vec![key_base58]), - pubkeys_ed25519: None, - }) -} - -fn list_accounts() -> CliResult { - let store = LocalKeystore::open(PathBuf::from(&KEYSTORE_PATH), None).unwrap(); - println!("sr25519 keys:"); - let mut keys_sr25519 = vec![]; - for pubkey in store.sr25519_public_keys(SR25519_KEY_TYPE).into_iter() { - let key_ss58 = pubkey.to_ss58check(); - println!("{}", key_ss58); - keys_sr25519.push(key_ss58); - } - println!("ed25519 keys:"); - let mut keys_ed25519 = vec![]; - for pubkey in store.ed25519_public_keys(ED25519_KEY_TYPE).into_iter() { - let key_ss58 = pubkey.to_ss58check(); - println!("{}", key_ss58); - keys_ed25519.push(key_ss58); - } - drop(store); - - Ok(CliResultOk::PubKeysBase58 { - pubkeys_sr25519: Some(keys_sr25519), - pubkeys_ed25519: Some(keys_ed25519), - }) -} - -fn print_metadata(cli: &Cli) -> CliResult { - let api = get_chain_api(cli); - let meta = api.metadata(); - println!("Metadata:\n {}", &meta.pretty_format().unwrap()); - Ok(CliResultOk::Metadata { metadata: meta.clone() }) -} -fn print_sgx_metadata(cli: &Cli) -> CliResult { - let worker_api_direct = get_worker_api_direct(cli); - let metadata = worker_api_direct.get_state_metadata().unwrap(); - println!("Metadata:\n {}", metadata.pretty_format().unwrap()); - Ok(CliResultOk::Metadata { metadata }) -} - -fn print_sgx_metadata_raw(cli: &Cli) -> CliResult { - let worker_api_direct = get_worker_api_direct(cli); - let metadata = worker_api_direct.get_state_metadata_raw().unwrap(); - println!("{metadata}"); - Ok(CliResultOk::None) -} - -fn list_workers(cli: &Cli) -> CliResult { - let api = get_chain_api(cli); - let enclaves = api.all_enclaves(WorkerType::BitAcross, None).unwrap(); - println!("number of enclaves registered: {}", enclaves.len()); - - let mr_enclaves = enclaves - .iter() - .map(|enclave| { - println!("Enclave"); - println!(" MRENCLAVE: {}", enclave.mrenclave.to_base58()); - let timestamp = DateTime::::from( - UNIX_EPOCH + Duration::from_millis(enclave.last_seen_timestamp), - ); - println!(" Last seen: {}", timestamp); - println!(" URL: {}", String::from_utf8_lossy(enclave.url.as_slice())); - enclave.mrenclave.to_base58() - }) - .collect(); - - Ok(CliResultOk::MrEnclaveBase58 { mr_enclaves }) -} diff --git a/tee-worker/bitacross/cli/src/benchmark/mod.rs b/tee-worker/bitacross/cli/src/benchmark/mod.rs deleted file mode 100644 index e46887084e..0000000000 --- a/tee-worker/bitacross/cli/src/benchmark/mod.rs +++ /dev/null @@ -1,378 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use crate::{ - command_utils::get_worker_api_direct, - get_layer_two_nonce, - trusted_cli::TrustedCli, - trusted_command_utils::{get_identifiers, get_keystore_path, get_pair_from_str}, - trusted_operation::{get_json_request, get_state, wait_until}, - Cli, CliResult, CliResultOk, SR25519_KEY_TYPE, -}; -use codec::Decode; -use hdrhistogram::Histogram; -use ita_stf::{ - Getter, Index, PublicGetter, TrustedCall, TrustedCallSigned, TrustedGetter, STF_TX_FEE, -}; -use itc_rpc_client::direct_client::{DirectApi, DirectClient}; -use itp_stf_primitives::{ - traits::TrustedCallSigning, - types::{KeyPair, TrustedOperation}, -}; -use itp_types::{ - Balance, ShardIdentifier, TrustedOperationStatus, - TrustedOperationStatus::{InSidechainBlock, Submitted}, -}; -use log::*; -use rand::Rng; -use rayon::prelude::*; -use sgx_crypto_helper::rsa3072::Rsa3072PubKey; -use sp_application_crypto::sr25519; -use sp_core::{sr25519 as sr25519_core, Pair}; -use sp_keystore::Keystore; -use std::{ - boxed::Box, - string::ToString, - sync::mpsc::{channel, Receiver}, - thread, time, - time::Instant, - vec::Vec, -}; -use substrate_client_keystore::LocalKeystore; - -// Needs to be above the existential deposit minimum, otherwise an account will not -// be created and the state is not increased. -const EXISTENTIAL_DEPOSIT: Balance = 1000; - -#[derive(Parser)] -pub struct BenchmarkCommand { - /// The number of clients (=threads) to be used in the benchmark - #[clap(default_value_t = 10)] - number_clients: u32, - - /// The number of iterations to execute for each client - #[clap(default_value_t = 30)] - number_iterations: u128, - - /// Adds a random wait before each transaction. This is the lower bound for the interval in ms. - #[clap(default_value_t = 0)] - random_wait_before_transaction_min_ms: u32, - - /// Adds a random wait before each transaction. This is the upper bound for the interval in ms. - #[clap(default_value_t = 0)] - random_wait_before_transaction_max_ms: u32, - - /// Whether to wait for "InSidechainBlock" confirmation for each transaction - #[clap(short, long)] - wait_for_confirmation: bool, - - /// Account to be used for initial funding of generated accounts used in benchmark - #[clap(default_value_t = String::from("//Alice"))] - funding_account: String, -} - -struct BenchmarkClient { - account: sr25519_core::Pair, - current_balance: u128, - client_api: DirectClient, - receiver: Receiver, -} - -impl BenchmarkClient { - fn new( - account: sr25519_core::Pair, - initial_balance: u128, - initial_request: String, - cli: &Cli, - ) -> Self { - debug!("get direct api"); - let client_api = get_worker_api_direct(cli); - - debug!("setup sender and receiver"); - let (sender, receiver) = channel(); - client_api.watch(initial_request, sender); - BenchmarkClient { account, current_balance: initial_balance, client_api, receiver } - } -} - -/// Stores timing information about a specific transaction -struct BenchmarkTransaction { - started: Instant, - submitted: Instant, - confirmed: Option, -} - -impl BenchmarkCommand { - pub(crate) fn run(&self, cli: &Cli, trusted_args: &TrustedCli) -> CliResult { - let random_wait_before_transaction_ms: (u32, u32) = ( - self.random_wait_before_transaction_min_ms, - self.random_wait_before_transaction_max_ms, - ); - let store = LocalKeystore::open(get_keystore_path(trusted_args, cli), None).unwrap(); - let funding_account_keys = get_pair_from_str(trusted_args, &self.funding_account, cli); - - let (mrenclave, shard) = get_identifiers(trusted_args, cli); - - // Get shielding pubkey. - let worker_api_direct = get_worker_api_direct(cli); - let shielding_pubkey: Rsa3072PubKey = match worker_api_direct.get_rsa_pubkey() { - Ok(key) => key, - Err(err_msg) => panic!("{}", err_msg.to_string()), - }; - - let nonce_start = get_layer_two_nonce!(funding_account_keys, cli, trusted_args); - println!("Nonce for account {}: {}", self.funding_account, nonce_start); - - let mut accounts = Vec::new(); - let initial_balance = (self.number_iterations + 1) * (STF_TX_FEE + EXISTENTIAL_DEPOSIT); - // Setup new accounts and initialize them with money from Alice. - for i in 0..self.number_clients { - let nonce = i + nonce_start; - println!("Initializing account {} with initial amount {:?}", i, initial_balance); - - // Create new account to use. - let a = LocalKeystore::sr25519_generate_new(&store, SR25519_KEY_TYPE, None).unwrap(); - let account = get_pair_from_str(trusted_args, a.to_string().as_str(), cli); - - // Transfer amount from Alice to new account. - let top: TrustedOperation = TrustedCall::balance_transfer( - funding_account_keys.public().into(), - account.public().into(), - initial_balance, - ) - .sign( - &KeyPair::Sr25519(Box::new(funding_account_keys.clone())), - nonce, - &mrenclave, - &shard, - ) - .into_trusted_operation(trusted_args.direct); - - // For the last account we wait for confirmation in order to ensure all accounts were setup correctly - let wait_for_confirmation = i == self.number_clients - 1; - let account_funding_request = get_json_request(shard, &top, shielding_pubkey); - - let client = - BenchmarkClient::new(account, initial_balance, account_funding_request, cli); - let _result = wait_for_top_confirmation(wait_for_confirmation, &client); - accounts.push(client); - } - - rayon::ThreadPoolBuilder::new() - .num_threads(self.number_clients as usize) - .build_global() - .unwrap(); - - let overall_start = Instant::now(); - - // Run actual benchmark logic, in parallel, for each account initialized above. - let outputs: Vec> = accounts - .into_par_iter() - .map(move |mut client| { - let mut output: Vec = Vec::new(); - - for i in 0..self.number_iterations { - println!("Iteration: {}", i); - - if random_wait_before_transaction_ms.1 > 0 { - random_wait(random_wait_before_transaction_ms); - } - - // Create new account. - let account_keys = LocalKeystore::sr25519_generate_new(&store, SR25519_KEY_TYPE, None).unwrap(); - - let new_account = - get_pair_from_str(trusted_args, account_keys.to_string().as_str(), cli); - - println!(" Transfer amount: {}", EXISTENTIAL_DEPOSIT); - println!(" From: {:?}", client.account.public()); - println!(" To: {:?}", new_account.public()); - - // Get nonce of account. - let nonce = get_nonce(client.account.clone(), shard, &client.client_api); - - // Transfer money from client account to new account. - let top: TrustedOperation = TrustedCall::balance_transfer( - client.account.public().into(), - new_account.public().into(), - EXISTENTIAL_DEPOSIT, - ) - .sign(&KeyPair::Sr25519(Box::new(client.account.clone())), nonce, &mrenclave, &shard) - .into_trusted_operation(trusted_args.direct); - - let last_iteration = i == self.number_iterations - 1; - let jsonrpc_call = get_json_request(shard, &top, shielding_pubkey); - client.client_api.send(&jsonrpc_call).unwrap(); - let result = wait_for_top_confirmation( - self.wait_for_confirmation || last_iteration, - &client, - ); - - client.current_balance -= EXISTENTIAL_DEPOSIT; - - let balance = get_balance(client.account.clone(), shard, &client.client_api); - println!("Balance: {}", balance.unwrap_or_default()); - assert_eq!(client.current_balance, balance.unwrap_or_default()); - - output.push(result); - - // FIXME: We probably should re-fund the account in this case. - if client.current_balance <= EXISTENTIAL_DEPOSIT + STF_TX_FEE { - error!("Account {:?} does not have enough balance anymore. Finishing benchmark early", client.account.public()); - break; - } - } - - client.client_api.close().unwrap(); - - output - }) - .collect(); - - println!( - "Finished benchmark with {} clients and {} transactions in {} ms", - self.number_clients, - self.number_iterations, - overall_start.elapsed().as_millis() - ); - - print_benchmark_statistic(outputs, self.wait_for_confirmation); - - Ok(CliResultOk::None) - } -} - -fn get_balance( - account: sr25519::Pair, - shard: ShardIdentifier, - direct_client: &DirectClient, -) -> Option { - let getter = Getter::trusted( - TrustedGetter::free_balance(account.public().into()) - .sign(&KeyPair::Sr25519(Box::new(account.clone()))), - ); - - let getter_start_timer = Instant::now(); - let getter_result = get_state(direct_client, shard, &getter).ok().unwrap_or_default(); - let getter_execution_time = getter_start_timer.elapsed().as_millis(); - - let balance = decode_balance(getter_result); - info!("Balance getter execution took {} ms", getter_execution_time,); - debug!("Retrieved {:?} Balance for {:?}", balance.unwrap_or_default(), account.public()); - balance -} - -fn get_nonce( - account: sr25519::Pair, - shard: ShardIdentifier, - direct_client: &DirectClient, -) -> Index { - let getter = Getter::public(PublicGetter::nonce(account.public().into())); - - let getter_start_timer = Instant::now(); - let nonce = get_state::(direct_client, shard, &getter).ok().unwrap_or_default(); - let getter_execution_time = getter_start_timer.elapsed().as_millis(); - info!("Nonce getter execution took {} ms", getter_execution_time,); - debug!("Retrieved {:?} nonce for {:?}", nonce, account.public()); - nonce -} - -fn print_benchmark_statistic(outputs: Vec>, wait_for_confirmation: bool) { - let mut hist = Histogram::::new(1).unwrap(); - for output in outputs { - for t in output { - let benchmarked_timestamp = - if wait_for_confirmation { t.confirmed } else { Some(t.submitted) }; - if let Some(confirmed) = benchmarked_timestamp { - hist += confirmed.duration_since(t.started).as_millis() as u64; - } else { - println!("Missing measurement data"); - } - } - } - - for i in (5..=100).step_by(5) { - let text = format!( - "{} percent are done within {} ms", - i, - hist.value_at_quantile(i as f64 / 100.0) - ); - println!("{}", text); - } -} - -fn random_wait(random_wait_before_transaction_ms: (u32, u32)) { - let mut rng = rand::thread_rng(); - let sleep_time = time::Duration::from_millis( - rng.gen_range(random_wait_before_transaction_ms.0..=random_wait_before_transaction_ms.1) - .into(), - ); - println!("Sleep for: {}ms", sleep_time.as_millis()); - thread::sleep(sleep_time); -} - -fn wait_for_top_confirmation( - wait_for_sidechain_block: bool, - client: &BenchmarkClient, -) -> BenchmarkTransaction { - let started = Instant::now(); - - let submitted = wait_until(&client.receiver, is_submitted); - - let confirmed = if wait_for_sidechain_block { - // We wait for the transaction hash that actually matches the submitted hash - loop { - let transaction_information = wait_until(&client.receiver, is_sidechain_block); - if let Some((hash, _)) = transaction_information { - if hash == submitted.unwrap().0 { - break transaction_information - } - } - } - } else { - None - }; - if let (Some(s), Some(c)) = (submitted, confirmed) { - // Assert the two hashes are identical - assert_eq!(s.0, c.0); - } - - BenchmarkTransaction { - started, - submitted: submitted.unwrap().1, - confirmed: confirmed.map(|v| v.1), - } -} - -fn is_submitted(s: TrustedOperationStatus) -> bool { - matches!(s, Submitted) -} - -fn is_sidechain_block(s: TrustedOperationStatus) -> bool { - matches!(s, InSidechainBlock(_)) -} - -fn decode_balance(maybe_encoded_balance: Option>) -> Option { - maybe_encoded_balance.and_then(|encoded_balance| { - if let Ok(vd) = Balance::decode(&mut encoded_balance.as_slice()) { - Some(vd) - } else { - warn!("Could not decode balance. maybe hasn't been set? {:x?}", encoded_balance); - None - } - }) -} diff --git a/tee-worker/bitacross/cli/src/command_utils.rs b/tee-worker/bitacross/cli/src/command_utils.rs deleted file mode 100644 index 09a046af35..0000000000 --- a/tee-worker/bitacross/cli/src/command_utils.rs +++ /dev/null @@ -1,87 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use crate::Cli; -use base58::FromBase58; -use ita_parentchain_interface::integritee::{AccountId, Signature}; -use itc_rpc_client::direct_client::{DirectApi, DirectClient as DirectWorkerApi}; -use itp_node_api::api_client::{ParentchainApi, TungsteniteRpcClient}; -use log::*; -use sgx_crypto_helper::rsa3072::Rsa3072PubKey; -use sp_application_crypto::sr25519; -use sp_core::{crypto::Ss58Codec, Pair}; -use sp_runtime::traits::{IdentifyAccount, Verify}; -use std::path::PathBuf; -use substrate_client_keystore::LocalKeystore; - -type AccountPublic = ::Signer; -pub(crate) const KEYSTORE_PATH: &str = "my_keystore"; - -/// Retrieves the public shielding key via the enclave websocket server. -pub(crate) fn get_shielding_key(cli: &Cli) -> Result { - let worker_api_direct = get_worker_api_direct(cli); - worker_api_direct.get_rsa_pubkey().map_err(|e| e.to_string()) -} - -pub(crate) fn get_chain_api(cli: &Cli) -> ParentchainApi { - let url = format!("{}:{}", cli.node_url, cli.node_port); - info!("connecting to {}", url); - ParentchainApi::new(TungsteniteRpcClient::new(&url, 5).unwrap()).unwrap() -} - -pub(crate) fn get_accountid_from_str(account: &str) -> AccountId { - match &account[..2] { - "//" => AccountPublic::from(sr25519::Pair::from_string(account, None).unwrap().public()) - .into_account(), - _ => AccountPublic::from(sr25519::Public::from_ss58check(account).unwrap()).into_account(), - } -} - -pub(crate) fn get_worker_api_direct(cli: &Cli) -> DirectWorkerApi { - let url = format!("{}:{}", cli.worker_url, cli.trusted_worker_port); - info!("Connecting to bitacross-worker-direct-port on '{}'", url); - DirectWorkerApi::new(url) -} - -/// get a pair either form keyring (well known keys) or from the store -pub(crate) fn get_pair_from_str(account: &str) -> sr25519::AppPair { - info!("getting pair for {}", account); - match &account[..2] { - "//" => sr25519::AppPair::from_string(account, None).unwrap(), - _ => { - info!("fetching from keystore at {}", &KEYSTORE_PATH); - // open store without password protection - let store = LocalKeystore::open(PathBuf::from(&KEYSTORE_PATH), None) - .expect("store should exist"); - info!("store opened"); - let _pair = store - .key_pair::( - &sr25519::Public::from_ss58check(account).unwrap().into(), - ) - .unwrap() - .unwrap(); - drop(store); - _pair - }, - } -} - -pub(crate) fn mrenclave_from_base58(src: &str) -> [u8; 32] { - let mut mrenclave = [0u8; 32]; - mrenclave.copy_from_slice(&src.from_base58().expect("mrenclave has to be base58 encoded")); - mrenclave -} diff --git a/tee-worker/bitacross/cli/src/commands.rs b/tee-worker/bitacross/cli/src/commands.rs deleted file mode 100644 index 17b5ea42c4..0000000000 --- a/tee-worker/bitacross/cli/src/commands.rs +++ /dev/null @@ -1,47 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -extern crate chrono; -use crate::{base_cli::BaseCommand, trusted_cli::TrustedCli, Cli, CliResult, CliResultOk}; -use clap::Subcommand; - -use crate::attesteer::AttesteerCommand; - -#[derive(Subcommand)] -pub enum Commands { - #[clap(flatten)] - Base(BaseCommand), - - /// trusted calls to worker enclave - #[clap(after_help = "stf subcommands depend on the stf crate this has been built against")] - Trusted(TrustedCli), - - /// Subcommand for the attesteer. - #[clap(subcommand)] - Attesteer(AttesteerCommand), -} - -pub fn match_command(cli: &Cli) -> CliResult { - match &cli.command { - Commands::Base(cmd) => cmd.run(cli), - Commands::Trusted(trusted_cli) => trusted_cli.run(cli), - Commands::Attesteer(cmd) => { - cmd.run(cli); - Ok(CliResultOk::None) - }, - } -} diff --git a/tee-worker/bitacross/cli/src/lib.rs b/tee-worker/bitacross/cli/src/lib.rs deleted file mode 100644 index 9ee0f5f7fd..0000000000 --- a/tee-worker/bitacross/cli/src/lib.rs +++ /dev/null @@ -1,112 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -//! an RPC client to Integritee using websockets -//! -//! examples -//! litentry_cli 127.0.0.1:9944 transfer //Alice 5G9RtsTbiYJYQYMHbWfyPoeuuxNaCbC16tZ2JGrZ4gRKwz14 1000 -//! -#![feature(rustc_private)] -#[macro_use] -extern crate clap; -extern crate chrono; - -extern crate env_logger; -extern crate log; - -mod attesteer; -mod base_cli; -mod benchmark; -mod command_utils; -mod trusted_base_cli; -mod trusted_cli; -mod trusted_command_utils; -mod trusted_operation; - -pub mod commands; - -use crate::commands::Commands; -use clap::Parser; -use itp_node_api::api_client::Metadata; -use sp_application_crypto::KeyTypeId; -use sp_core::H256; -use thiserror::Error; - -const VERSION: &str = env!("CARGO_PKG_VERSION"); - -pub(crate) const SR25519_KEY_TYPE: KeyTypeId = KeyTypeId(*b"sr25"); -pub(crate) const ED25519_KEY_TYPE: KeyTypeId = KeyTypeId(*b"ed25"); - -#[derive(Parser)] -#[clap(name = "bitacross-cli")] -#[clap(version = VERSION)] -#[clap(author = "Trust Computing GmbH ")] -#[clap(about = "cli tool to interact with litentry-parachain and workers", long_about = None)] -#[clap(after_help = "stf subcommands depend on the stf crate this has been built against")] -pub struct Cli { - /// node url - #[clap(short = 'u', long, default_value_t = String::from("ws://127.0.0.1"))] - node_url: String, - - /// node port - #[clap(short = 'p', long, default_value_t = String::from("9944"))] - node_port: String, - - /// worker url - #[clap(short = 'U', long, default_value_t = String::from("wss://127.0.0.1"))] - worker_url: String, - - /// worker direct invocation port - #[clap(short = 'P', long, default_value_t = String::from("2000"))] - trusted_worker_port: String, - - #[clap(subcommand)] - command: Commands, -} - -pub enum CliResultOk { - PubKeysBase58 { pubkeys_sr25519: Option>, pubkeys_ed25519: Option> }, - Balance { balance: u128 }, - MrEnclaveBase58 { mr_enclaves: Vec }, - Metadata { metadata: Metadata }, - H256 { hash: H256 }, - // TODO should ideally be removed; or at least drastically less used - // We WANT all commands exposed by the cli to return something useful for the caller(ie instead of printing) - None, -} - -#[derive(Debug, Error)] -pub enum CliError { - #[error("extrinsic error: {:?}", msg)] - Extrinsic { msg: String }, - #[error("trusted operation error: {:?}", msg)] - TrustedOp { msg: String }, - #[error("worker rpc api error: {:?}", msg)] - WorkerRpcApi { msg: String }, -} - -pub type CliResult = Result; - -/// This is used for the commands that directly call `perform_trusted_operation` -/// which typically return `CliResultOk::None` -/// -/// eg: `SetBalanceCommand`,`TransferCommand`,`UnshieldFundsCommand` -impl From for CliError { - fn from(value: trusted_operation::TrustedOperationError) -> Self { - CliError::TrustedOp { msg: value.to_string() } - } -} diff --git a/tee-worker/bitacross/cli/src/main.rs b/tee-worker/bitacross/cli/src/main.rs deleted file mode 100644 index 625b4f0aa0..0000000000 --- a/tee-worker/bitacross/cli/src/main.rs +++ /dev/null @@ -1,29 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use bitacross_cli::{commands, Cli}; -use clap::Parser; - -fn main() { - env_logger::builder() - .format_timestamp(Some(env_logger::TimestampPrecision::Millis)) - .init(); - - let cli = Cli::parse(); - - commands::match_command(&cli).unwrap(); -} diff --git a/tee-worker/bitacross/cli/src/trusted_base_cli/commands/balance.rs b/tee-worker/bitacross/cli/src/trusted_base_cli/commands/balance.rs deleted file mode 100644 index 3b5b9f4f33..0000000000 --- a/tee-worker/bitacross/cli/src/trusted_base_cli/commands/balance.rs +++ /dev/null @@ -1,34 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use crate::{ - trusted_cli::TrustedCli, trusted_command_utils::get_balance, Cli, CliResult, CliResultOk, -}; - -#[derive(Parser)] -pub struct BalanceCommand { - /// AccountId in ss58check format - account: String, -} - -impl BalanceCommand { - pub(crate) fn run(&self, cli: &Cli, trusted_args: &TrustedCli) -> CliResult { - let balance = get_balance(cli, trusted_args, &self.account).unwrap_or_default(); - println!("{}", balance); - Ok(CliResultOk::Balance { balance }) - } -} diff --git a/tee-worker/bitacross/cli/src/trusted_base_cli/commands/bitacross/direct_call_sign_bitcoin.rs b/tee-worker/bitacross/cli/src/trusted_base_cli/commands/bitacross/direct_call_sign_bitcoin.rs deleted file mode 100644 index 748b1d2a79..0000000000 --- a/tee-worker/bitacross/cli/src/trusted_base_cli/commands/bitacross/direct_call_sign_bitcoin.rs +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright 2020-2024 Trust Computing GmbH. -// This file is part of Litentry. -// -// Litentry is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// Litentry is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with Litentry. If not, see . - -use crate::{ - trusted_base_cli::commands::bitacross::utils::send_direct_request_and_watch, - trusted_cli::TrustedCli, - trusted_command_utils::{get_identifiers, get_pair_from_str}, - Cli, CliResult, CliResultOk, -}; -use bc_musig2_ceremony::SignBitcoinPayload; -use itp_stf_primitives::types::KeyPair; -use lc_direct_call::DirectCall; -use sp_core::Pair; - -#[derive(Parser)] -pub struct RequestDirectCallSignBitcoinCommand { - payload: Vec, - merkle_root: String, -} - -impl RequestDirectCallSignBitcoinCommand { - pub(crate) fn run(&self, cli: &Cli, trusted_cli: &TrustedCli) -> CliResult { - let alice = get_pair_from_str(trusted_cli, "//Alice", cli); - let (mrenclave, shard) = get_identifiers(trusted_cli, cli); - - let merkle_root_bytes = hex::decode(self.merkle_root.clone()).unwrap(); - - let dc = DirectCall::SignBitcoin( - alice.public().into(), - SignBitcoinPayload::TaprootSpendable( - self.payload.clone(), - merkle_root_bytes.try_into().unwrap(), - ), - ) - .sign(&KeyPair::Sr25519(Box::new(alice)), &mrenclave, &shard); - - let signature: Vec = send_direct_request_and_watch(cli, trusted_cli, dc).unwrap(); - println!("Got signature: {:?}", signature); - - Ok(CliResultOk::None) - } -} diff --git a/tee-worker/bitacross/cli/src/trusted_base_cli/commands/bitacross/direct_call_sign_ethereum.rs b/tee-worker/bitacross/cli/src/trusted_base_cli/commands/bitacross/direct_call_sign_ethereum.rs deleted file mode 100644 index ff6cac9a76..0000000000 --- a/tee-worker/bitacross/cli/src/trusted_base_cli/commands/bitacross/direct_call_sign_ethereum.rs +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright 2020-2024 Trust Computing GmbH. -// This file is part of Litentry. -// -// Litentry is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// Litentry is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with Litentry. If not, see . - -use crate::{ - trusted_base_cli::commands::bitacross::utils::send_direct_request, - trusted_cli::TrustedCli, - trusted_command_utils::{get_identifiers, get_pair_from_str}, - Cli, CliResult, CliResultOk, -}; -use itp_rpc::{RpcResponse, RpcReturnValue}; -use itp_stf_primitives::types::KeyPair; -use itp_utils::FromHexPrefixed; -use lc_direct_call::{DirectCall, PrehashedEthereumMessage}; -use sp_core::Pair; - -#[derive(Parser)] -pub struct RequestDirectCallSignEthereumCommand { - payload: Vec, -} - -impl RequestDirectCallSignEthereumCommand { - pub(crate) fn run(&self, cli: &Cli, trusted_cli: &TrustedCli) -> CliResult { - let alice = get_pair_from_str(trusted_cli, "//Alice", cli); - let (mrenclave, shard) = get_identifiers(trusted_cli, cli); - let msg: PrehashedEthereumMessage = - self.payload.clone().try_into().expect("Unable to convert payload to [u8; 32]"); - - let dc = DirectCall::SignEthereum(alice.public().into(), msg).sign( - &KeyPair::Sr25519(Box::new(alice)), - &mrenclave, - &shard, - ); - - let result: String = send_direct_request(cli, trusted_cli, dc).unwrap(); - let response: RpcResponse = serde_json::from_str(&result).unwrap(); - if let Ok(return_value) = RpcReturnValue::from_hex(&response.result) { - println!("Got return value: {:?}", return_value); - } else { - println!("Could not decode return value: {:?}", response.result); - } - println!("Got result: {:?}", result); - - Ok(CliResultOk::None) - } -} diff --git a/tee-worker/bitacross/cli/src/trusted_base_cli/commands/bitacross/mod.rs b/tee-worker/bitacross/cli/src/trusted_base_cli/commands/bitacross/mod.rs deleted file mode 100644 index 149e066e59..0000000000 --- a/tee-worker/bitacross/cli/src/trusted_base_cli/commands/bitacross/mod.rs +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright 2020-2024 Trust Computing GmbH. -// This file is part of Litentry. -// -// Litentry is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// Litentry is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with Litentry. If not, see . - -pub mod direct_call_sign_bitcoin; -pub mod direct_call_sign_ethereum; - -pub mod utils; diff --git a/tee-worker/bitacross/cli/src/trusted_base_cli/commands/bitacross/utils.rs b/tee-worker/bitacross/cli/src/trusted_base_cli/commands/bitacross/utils.rs deleted file mode 100644 index 4ed145405b..0000000000 --- a/tee-worker/bitacross/cli/src/trusted_base_cli/commands/bitacross/utils.rs +++ /dev/null @@ -1,127 +0,0 @@ -// Copyright 2020-2024 Trust Computing GmbH. -// This file is part of Litentry. -// -// Litentry is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// Litentry is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with Litentry. If not, see . - -use crate::{ - command_utils::get_worker_api_direct, trusted_cli::TrustedCli, trusted_operation::read_shard, - Cli, -}; -use codec::{Decode, Encode, Input}; -use itc_rpc_client::direct_client::DirectApi; -use itp_rpc::{Id, RpcRequest, RpcResponse, RpcReturnValue}; -use itp_stf_primitives::error::StfError; -use itp_types::{parentchain::Hash, DirectRequestStatus, TrustedOperationStatus}; -use itp_utils::{FromHexPrefixed, ToHexPrefixed}; -use lc_direct_call::DirectCallSigned; -use litentry_primitives::{PlainRequest, ShardIdentifier}; -use log::{debug, error}; -use std::sync::mpsc::channel; - -pub fn send_direct_request( - cli: &Cli, - trusted_args: &TrustedCli, - call: DirectCallSigned, -) -> Result { - let shard = read_shard(trusted_args, cli).unwrap(); - let jsonrpc_call: String = get_bitacross_json_request(shard, call); - let direct_api = get_worker_api_direct(cli); - direct_api.get(&jsonrpc_call).map_err(|e| e.to_string()) -} - -pub fn send_direct_request_and_watch( - cli: &Cli, - trusted_args: &TrustedCli, - call: DirectCallSigned, -) -> Result { - let shard = read_shard(trusted_args, cli).unwrap(); - let jsonrpc_call: String = get_bitacross_json_request(shard, call); - let direct_api = get_worker_api_direct(cli); - - let (sender, receiver) = channel(); - direct_api.watch(jsonrpc_call, sender); - - debug!("waiting for rpc response"); - loop { - match receiver.recv() { - Ok(response) => { - debug!("received response"); - let response: RpcResponse = serde_json::from_str(&response).unwrap(); - if let Ok(return_value) = RpcReturnValue::from_hex(&response.result) { - match return_value.status { - DirectRequestStatus::Error => { - debug!("request status is error"); - if let Ok(value) = String::decode(&mut return_value.value.as_slice()) { - error!("{}", value); - } - direct_api.close().unwrap(); - return Err("[Error] DirectRequestStatus::Error".to_string()) - }, - DirectRequestStatus::TrustedOperationStatus(status, top_hash) => { - debug!("request status is: {:?}, top_hash: {:?}", status, top_hash); - - if matches!(status, TrustedOperationStatus::Invalid) { - let error = StfError::decode(&mut return_value.value.as_slice()) - .map_err(|e| { - format!("Could not decode error value: {:?}", e) - })?; - return Err(format!( - "[Error] Error occurred while executing trusted call: {:?}", - error - )) - } - if let Ok(value) = Hash::decode(&mut return_value.value.as_slice()) { - println!("Trusted call {:?} is {:?}", value, status); - } - if !return_value.do_watch { - direct_api.close().unwrap(); - let value = - decode_response_value(&mut return_value.value.as_slice())?; - return Ok(value) - } - }, - DirectRequestStatus::Processing(_hash) => { - println!("Request is processing..."); - }, - DirectRequestStatus::Ok => { - debug!("request status is ignored"); - direct_api.close().unwrap(); - return Err("Unexpected status: DirectRequestStatus::Ok".to_string()) - }, - } - }; - }, - Err(e) => { - error!("failed to receive rpc response: {:?}", e); - direct_api.close().unwrap(); - return Err("failed to receive rpc response".to_string()) - }, - }; - } -} - -pub fn get_bitacross_json_request(shard: ShardIdentifier, call: DirectCallSigned) -> String { - // compose jsonrpc call - let request = PlainRequest { shard, payload: call.encode() }; - RpcRequest::compose_jsonrpc_call( - Id::Number(1), - "bitacross_submitRequest".to_string(), - vec![request.to_hex()], - ) - .unwrap() -} - -fn decode_response_value(value: &mut I) -> Result { - T::decode(value).map_err(|e| format!("Could not decode result value: {:?}", e)) -} diff --git a/tee-worker/bitacross/cli/src/trusted_base_cli/commands/get_shard.rs b/tee-worker/bitacross/cli/src/trusted_base_cli/commands/get_shard.rs deleted file mode 100644 index 5a1df5032b..0000000000 --- a/tee-worker/bitacross/cli/src/trusted_base_cli/commands/get_shard.rs +++ /dev/null @@ -1,69 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use crate::{ - command_utils::get_worker_api_direct, trusted_cli::TrustedCli, Cli, CliError, CliResult, - CliResultOk, -}; -use base58::ToBase58; -use codec::{Decode, Encode}; - -use itc_rpc_client::direct_client::DirectApi; -use itp_rpc::{Id, RpcRequest, RpcResponse, RpcReturnValue}; - -use itp_types::DirectRequestStatus; -use itp_utils::FromHexPrefixed; -use log::*; - -use sp_core::H256; - -#[derive(Parser)] -pub struct GetShardCommand {} - -impl GetShardCommand { - pub(crate) fn run(&self, cli: &Cli, _trusted_args: &TrustedCli) -> CliResult { - let direct_api = get_worker_api_direct(cli); - let rpc_method = "author_getShard".to_owned(); - let jsonrpc_call: String = - RpcRequest::compose_jsonrpc_call(Id::Text("1".to_string()), rpc_method, vec![]) - .unwrap(); - let rpc_response_str = direct_api.get(&jsonrpc_call).unwrap(); - // Decode RPC response. - let rpc_response: RpcResponse = serde_json::from_str(&rpc_response_str) - .map_err(|err| CliError::WorkerRpcApi { msg: err.to_string() })?; - let rpc_return_value = RpcReturnValue::from_hex(&rpc_response.result) - // Replace with `inspect_err` once it's stable. - .map_err(|err| { - error!("Failed to decode RpcReturnValue: {:?}", err); - CliError::WorkerRpcApi { msg: "failed to decode RpcReturnValue".to_string() } - })?; - - if rpc_return_value.status == DirectRequestStatus::Error { - error!("{}", String::decode(&mut rpc_return_value.value.as_slice()).unwrap()); - return Err(CliError::WorkerRpcApi { msg: "rpc error".to_string() }) - } - - let shard = H256::decode(&mut rpc_return_value.value.as_slice()) - // Replace with `inspect_err` once it's stable. - .map_err(|err| { - error!("Failed to decode shard: {:?}", err); - CliError::WorkerRpcApi { msg: err.to_string() } - })?; - println!("{}", shard.encode().to_base58()); - Ok(CliResultOk::H256 { hash: shard }) - } -} diff --git a/tee-worker/bitacross/cli/src/trusted_base_cli/commands/mod.rs b/tee-worker/bitacross/cli/src/trusted_base_cli/commands/mod.rs deleted file mode 100644 index 3ed5fd5b08..0000000000 --- a/tee-worker/bitacross/cli/src/trusted_base_cli/commands/mod.rs +++ /dev/null @@ -1,7 +0,0 @@ -pub mod balance; -pub mod bitacross; -pub mod get_shard; -pub mod nonce; -pub mod set_balance; -pub mod transfer; -pub mod unshield_funds; diff --git a/tee-worker/bitacross/cli/src/trusted_base_cli/commands/nonce.rs b/tee-worker/bitacross/cli/src/trusted_base_cli/commands/nonce.rs deleted file mode 100644 index f8abee5519..0000000000 --- a/tee-worker/bitacross/cli/src/trusted_base_cli/commands/nonce.rs +++ /dev/null @@ -1,44 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use crate::{ - command_utils::get_worker_api_direct, - trusted_cli::TrustedCli, - trusted_command_utils::{get_identifiers, get_pair_from_str}, - Cli, CliResult, CliResultOk, -}; -use itc_rpc_client::direct_client::DirectApi; -use sp_core::Pair; - -#[derive(Parser)] -pub struct NonceCommand { - /// AccountId in ss58check format - account: String, -} - -impl NonceCommand { - pub(crate) fn run(&self, cli: &Cli, trusted_args: &TrustedCli) -> CliResult { - let (_mrenclave, shard) = get_identifiers(trusted_args, cli); - let who = get_pair_from_str(trusted_args, &self.account, cli); - let worker_api_direct = get_worker_api_direct(cli); - let nonce_ret = worker_api_direct.get_next_nonce(&shard, &(who.public().into())); - let nonce = nonce_ret.expect("get nonce error!"); - println!("{}", nonce); - worker_api_direct.close().unwrap(); - Ok(CliResultOk::None) - } -} diff --git a/tee-worker/bitacross/cli/src/trusted_base_cli/commands/set_balance.rs b/tee-worker/bitacross/cli/src/trusted_base_cli/commands/set_balance.rs deleted file mode 100644 index d549a67fd1..0000000000 --- a/tee-worker/bitacross/cli/src/trusted_base_cli/commands/set_balance.rs +++ /dev/null @@ -1,64 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use crate::{ - get_layer_two_nonce, - trusted_cli::TrustedCli, - trusted_command_utils::{get_identifiers, get_pair_from_str}, - trusted_operation::perform_trusted_operation, - Cli, CliResult, CliResultOk, -}; -use ita_parentchain_interface::integritee::Balance; -use ita_stf::{Getter, Index, TrustedCall, TrustedCallSigned}; -use itp_stf_primitives::{ - traits::TrustedCallSigning, - types::{KeyPair, TrustedOperation}, -}; -use log::*; -use sp_core::{crypto::Ss58Codec, Pair}; -use std::boxed::Box; - -#[derive(Parser)] -pub struct SetBalanceCommand { - /// sender's AccountId in ss58check format - account: String, - - /// amount to be transferred - amount: Balance, -} - -impl SetBalanceCommand { - pub(crate) fn run(&self, cli: &Cli, trusted_args: &TrustedCli) -> CliResult { - let who = get_pair_from_str(trusted_args, &self.account, cli); - let signer = get_pair_from_str(trusted_args, "//Alice", cli); - info!("account ss58 is {}", who.public().to_ss58check()); - - println!("send trusted call set-balance({}, {})", who.public(), self.amount); - - let (mrenclave, shard) = get_identifiers(trusted_args, cli); - let nonce = get_layer_two_nonce!(signer, cli, trusted_args); - let top: TrustedOperation = TrustedCall::balance_set_balance( - signer.public().into(), - who.public().into(), - self.amount, - self.amount, - ) - .sign(&KeyPair::Sr25519(Box::new(signer)), nonce, &mrenclave, &shard) - .into_trusted_operation(trusted_args.direct); - Ok(perform_trusted_operation::<()>(cli, trusted_args, &top).map(|_| CliResultOk::None)?) - } -} diff --git a/tee-worker/bitacross/cli/src/trusted_base_cli/commands/transfer.rs b/tee-worker/bitacross/cli/src/trusted_base_cli/commands/transfer.rs deleted file mode 100644 index 0b6e093395..0000000000 --- a/tee-worker/bitacross/cli/src/trusted_base_cli/commands/transfer.rs +++ /dev/null @@ -1,72 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use crate::{ - get_layer_two_nonce, - trusted_cli::TrustedCli, - trusted_command_utils::{get_accountid_from_str, get_identifiers, get_pair_from_str}, - trusted_operation::perform_trusted_operation, - Cli, CliResult, CliResultOk, -}; -use ita_parentchain_interface::integritee::Balance; -use ita_stf::{Getter, Index, TrustedCall, TrustedCallSigned}; -use itp_stf_primitives::{ - traits::TrustedCallSigning, - types::{KeyPair, TrustedOperation}, -}; -use log::*; -use sp_core::{crypto::Ss58Codec, Pair}; -use std::boxed::Box; - -#[derive(Parser)] -pub struct TransferCommand { - /// sender's AccountId in ss58check format - from: String, - - /// recipient's AccountId in ss58check format - to: String, - - /// amount to be transferred - amount: Balance, -} - -impl TransferCommand { - pub(crate) fn run(&self, cli: &Cli, trusted_args: &TrustedCli) -> CliResult { - let from = get_pair_from_str(trusted_args, &self.from, cli); - let to = get_accountid_from_str(&self.to); - info!("from ss58 is {}", from.public().to_ss58check()); - info!("to ss58 is {}", to.to_ss58check()); - - let (mrenclave, shard) = get_identifiers(trusted_args, cli); - let nonce = get_layer_two_nonce!(from, cli, trusted_args); - println!( - "send trusted call transfer from {} to {}: {}, nonce: {}", - from.public(), - to, - self.amount, - nonce - ); - let top: TrustedOperation = - TrustedCall::balance_transfer(from.public().into(), to, self.amount) - .sign(&KeyPair::Sr25519(Box::new(from)), nonce, &mrenclave, &shard) - .into_trusted_operation(trusted_args.direct); - let res = - perform_trusted_operation::<()>(cli, trusted_args, &top).map(|_| CliResultOk::None)?; - info!("trusted call transfer executed"); - Ok(res) - } -} diff --git a/tee-worker/bitacross/cli/src/trusted_base_cli/commands/unshield_funds.rs b/tee-worker/bitacross/cli/src/trusted_base_cli/commands/unshield_funds.rs deleted file mode 100644 index 9133315136..0000000000 --- a/tee-worker/bitacross/cli/src/trusted_base_cli/commands/unshield_funds.rs +++ /dev/null @@ -1,67 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use crate::{ - get_layer_two_nonce, - trusted_cli::TrustedCli, - trusted_command_utils::{get_accountid_from_str, get_identifiers, get_pair_from_str}, - trusted_operation::perform_trusted_operation, - Cli, CliResult, CliResultOk, -}; -use ita_parentchain_interface::integritee::Balance; -use ita_stf::{Getter, Index, TrustedCall, TrustedCallSigned}; -use itp_stf_primitives::{ - traits::TrustedCallSigning, - types::{KeyPair, TrustedOperation}, -}; -use sp_core::{crypto::Ss58Codec, Pair}; -use std::boxed::Box; -#[derive(Parser)] -pub struct UnshieldFundsCommand { - /// Sender's incognito AccountId in ss58check format - from: String, - - /// Recipient's parentchain AccountId in ss58check format - to: String, - - /// amount to be transferred - amount: Balance, -} - -impl UnshieldFundsCommand { - pub(crate) fn run(&self, cli: &Cli, trusted_args: &TrustedCli) -> CliResult { - let from = get_pair_from_str(trusted_args, &self.from, cli); - let to = get_accountid_from_str(&self.to); - println!("from ss58 is {}", from.public().to_ss58check()); - println!("to ss58 is {}", to.to_ss58check()); - - println!( - "send trusted call unshield_funds from {} to {}: {}", - from.public(), - to, - self.amount - ); - - let (mrenclave, shard) = get_identifiers(trusted_args, cli); - let nonce = get_layer_two_nonce!(from, cli, trusted_args); - let top: TrustedOperation = - TrustedCall::balance_unshield(from.public().into(), to, self.amount, shard) - .sign(&KeyPair::Sr25519(Box::new(from)), nonce, &mrenclave, &shard) - .into_trusted_operation(trusted_args.direct); - Ok(perform_trusted_operation::<()>(cli, trusted_args, &top).map(|_| CliResultOk::None)?) - } -} diff --git a/tee-worker/bitacross/cli/src/trusted_base_cli/mod.rs b/tee-worker/bitacross/cli/src/trusted_base_cli/mod.rs deleted file mode 100644 index 77ea62abca..0000000000 --- a/tee-worker/bitacross/cli/src/trusted_base_cli/mod.rs +++ /dev/null @@ -1,122 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use crate::{ - trusted_base_cli::commands::{ - balance::BalanceCommand, - bitacross::{ - direct_call_sign_bitcoin::RequestDirectCallSignBitcoinCommand, - direct_call_sign_ethereum::RequestDirectCallSignEthereumCommand, - }, - get_shard::GetShardCommand, - nonce::NonceCommand, - set_balance::SetBalanceCommand, - transfer::TransferCommand, - unshield_funds::UnshieldFundsCommand, - }, - trusted_cli::TrustedCli, - trusted_command_utils::get_keystore_path, - Cli, CliResult, CliResultOk, ED25519_KEY_TYPE, SR25519_KEY_TYPE, -}; -use log::*; -use sp_core::crypto::Ss58Codec; -use sp_keystore::Keystore; -use substrate_client_keystore::LocalKeystore; - -mod commands; - -#[derive(Subcommand)] -pub enum TrustedBaseCommand { - /// generates a new incognito account for the given shard - NewAccount, - - /// lists all incognito accounts in a given shard - ListAccounts, - - /// send funds from one incognito account to another - Transfer(TransferCommand), - - /// ROOT call to set some account balance to an arbitrary number - SetBalance(SetBalanceCommand), - - /// query balance for incognito account in keystore - Balance(BalanceCommand), - - /// Transfer funds from an incognito account to an parentchain account - UnshieldFunds(UnshieldFundsCommand), - - /// gets the nonce of a given account, taking the pending trusted calls - /// in top pool in consideration - Nonce(NonceCommand), - - /// get shard for this worker - GetShard(GetShardCommand), - - /// sign bitcoin transaction using custodian wallet - RequestDirectCallSignBitcoin(RequestDirectCallSignBitcoinCommand), - - /// sign ethereum transaction using custodian wallet - RequestDirectCallSignEthereum(RequestDirectCallSignEthereumCommand), -} - -impl TrustedBaseCommand { - pub fn run(&self, cli: &Cli, trusted_cli: &TrustedCli) -> CliResult { - match self { - TrustedBaseCommand::NewAccount => new_account(trusted_cli, cli), - TrustedBaseCommand::ListAccounts => list_accounts(trusted_cli, cli), - TrustedBaseCommand::Transfer(cmd) => cmd.run(cli, trusted_cli), - TrustedBaseCommand::SetBalance(cmd) => cmd.run(cli, trusted_cli), - TrustedBaseCommand::Balance(cmd) => cmd.run(cli, trusted_cli), - TrustedBaseCommand::UnshieldFunds(cmd) => cmd.run(cli, trusted_cli), - TrustedBaseCommand::Nonce(cmd) => cmd.run(cli, trusted_cli), - TrustedBaseCommand::GetShard(cmd) => cmd.run(cli, trusted_cli), - TrustedBaseCommand::RequestDirectCallSignBitcoin(cmd) => cmd.run(cli, trusted_cli), - TrustedBaseCommand::RequestDirectCallSignEthereum(cmd) => cmd.run(cli, trusted_cli), - } - } -} - -fn new_account(trusted_args: &TrustedCli, cli: &Cli) -> CliResult { - let store = LocalKeystore::open(get_keystore_path(trusted_args, cli), None).unwrap(); - let key = LocalKeystore::sr25519_generate_new(&store, SR25519_KEY_TYPE, None).unwrap(); - drop(store); - info!("new account {}", key.to_ss58check()); - let key_str = key.to_ss58check(); - println!("{}", key_str); - - Ok(CliResultOk::PubKeysBase58 { pubkeys_sr25519: Some(vec![key_str]), pubkeys_ed25519: None }) -} - -fn list_accounts(trusted_args: &TrustedCli, cli: &Cli) -> CliResult { - let store = LocalKeystore::open(get_keystore_path(trusted_args, cli), None).unwrap(); - info!("sr25519 keys:"); - for pubkey in store.sr25519_public_keys(SR25519_KEY_TYPE).into_iter() { - println!("{}", pubkey.to_ss58check()); - } - info!("ed25519 keys:"); - let pubkeys: Vec = store - .ed25519_public_keys(ED25519_KEY_TYPE) - .into_iter() - .map(|pubkey| pubkey.to_ss58check()) - .collect(); - for pubkey in &pubkeys { - println!("{}", pubkey); - } - drop(store); - - Ok(CliResultOk::PubKeysBase58 { pubkeys_sr25519: None, pubkeys_ed25519: Some(pubkeys) }) -} diff --git a/tee-worker/bitacross/cli/src/trusted_cli.rs b/tee-worker/bitacross/cli/src/trusted_cli.rs deleted file mode 100644 index f0fffe8b96..0000000000 --- a/tee-worker/bitacross/cli/src/trusted_cli.rs +++ /dev/null @@ -1,60 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use crate::{benchmark::BenchmarkCommand, Cli, CliResult}; - -use crate::trusted_base_cli::TrustedBaseCommand; - -#[derive(Args)] -pub struct TrustedCli { - /// targeted worker MRENCLAVE - #[clap(short, long)] - pub(crate) mrenclave: Option, - - /// shard identifier - #[clap(short, long)] - pub(crate) shard: Option, - - /// signer for publicly observable extrinsic - #[clap(short='a', long, default_value_t = String::from("//Alice"))] - pub(crate) xt_signer: String, - - /// insert if direct invocation call is desired - #[clap(short, long)] - pub(crate) direct: bool, - - #[clap(subcommand)] - pub(crate) command: TrustedCommand, -} - -#[derive(Subcommand)] -pub enum TrustedCommand { - #[clap(flatten)] - BaseTrusted(TrustedBaseCommand), - - /// Run Benchmark - Benchmark(BenchmarkCommand), -} - -impl TrustedCli { - pub(crate) fn run(&self, cli: &Cli) -> CliResult { - match &self.command { - TrustedCommand::BaseTrusted(cmd) => cmd.run(cli, self), - TrustedCommand::Benchmark(cmd) => cmd.run(cli, self), - } - } -} diff --git a/tee-worker/bitacross/cli/src/trusted_command_utils.rs b/tee-worker/bitacross/cli/src/trusted_command_utils.rs deleted file mode 100644 index 5df8008302..0000000000 --- a/tee-worker/bitacross/cli/src/trusted_command_utils.rs +++ /dev/null @@ -1,169 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use crate::{ - command_utils::{get_worker_api_direct, mrenclave_from_base58}, - trusted_cli::TrustedCli, - trusted_operation::{perform_trusted_operation, read_shard}, - Cli, -}; -use base58::{FromBase58, ToBase58}; -use codec::{Decode, Encode}; -use ita_parentchain_interface::integritee::Balance; -use ita_stf::{Getter, TrustedCallSigned, TrustedGetter}; -use itc_rpc_client::direct_client::DirectApi; -use itp_rpc::{Id, RpcRequest, RpcResponse, RpcReturnValue}; -use itp_stf_primitives::types::{AccountId, KeyPair, ShardIdentifier, TrustedOperation}; -use itp_types::DirectRequestStatus; -use itp_utils::{FromHexPrefixed, ToHexPrefixed}; -use log::*; -use sp_application_crypto::sr25519; -use sp_core::{crypto::Ss58Codec, sr25519 as sr25519_core, Pair}; -use sp_runtime::traits::IdentifyAccount; -use std::{boxed::Box, path::PathBuf}; -use substrate_client_keystore::LocalKeystore; - -#[macro_export] -macro_rules! get_layer_two_nonce { - ($signer_pair:ident, $cli: ident, $trusted_args:ident ) => {{ - use ita_stf::{Getter, PublicGetter, TrustedCallSigned}; - use itp_stf_primitives::types::TrustedOperation; - use litentry_primitives::Identity; - use $crate::{ - trusted_command_utils::get_pending_trusted_calls_for, - trusted_operation::perform_trusted_operation, - }; - let top = TrustedOperation::::get(Getter::public( - PublicGetter::nonce(Identity::Substrate($signer_pair.public().into())), - )); - // final nonce = current system nonce + pending tx count, panic early - let nonce = perform_trusted_operation::($cli, $trusted_args, &top) - .ok() - .unwrap_or_default(); - log::debug!("got system nonce: {:?}", nonce); - let pending_tx_count = - get_pending_trusted_calls_for($cli, $trusted_args, &$signer_pair.public().into()).len(); - let pending_tx_count = Index::try_from(pending_tx_count).unwrap(); - nonce + pending_tx_count - }}; -} - -const TRUSTED_KEYSTORE_PATH: &str = "my_trusted_keystore"; - -pub(crate) fn get_balance(cli: &Cli, trusted_args: &TrustedCli, arg_who: &str) -> Option { - debug!("arg_who = {:?}", arg_who); - let who = get_pair_from_str(trusted_args, arg_who, cli); - let top = TrustedOperation::::get(Getter::trusted( - TrustedGetter::free_balance(who.public().into()).sign(&KeyPair::Sr25519(Box::new(who))), - )); - perform_trusted_operation::(cli, trusted_args, &top).ok() -} - -pub(crate) fn get_keystore_path(trusted_args: &TrustedCli, cli: &Cli) -> PathBuf { - let (_mrenclave, shard) = get_identifiers(trusted_args, cli); - PathBuf::from(&format!("{}/{}", TRUSTED_KEYSTORE_PATH, shard.encode().to_base58())) -} - -pub(crate) fn get_identifiers(trusted_args: &TrustedCli, cli: &Cli) -> ([u8; 32], ShardIdentifier) { - let mrenclave = if let Some(mrenclave) = &trusted_args.mrenclave { - mrenclave_from_base58(mrenclave) - } else { - let direct_api = get_worker_api_direct(cli); - match direct_api.get_state_mrenclave() { - Ok(mrenclave) => mrenclave, - Err(e) => panic!("Unable to retrieve MRENCLAVE from endpoint: {:?}", e), - } - }; - let shard = match &trusted_args.shard { - Some(val) => - ShardIdentifier::from_slice(&val.from_base58().expect("shard has to be base58 encoded")), - None => ShardIdentifier::from_slice(&mrenclave), - }; - (mrenclave, shard) -} - -// TODO this function is redundant with client::main -pub(crate) fn get_accountid_from_str(account: &str) -> AccountId { - match &account[..2] { - "//" => sr25519::Pair::from_string(account, None) - .unwrap() - .public() - .into_account() - .into(), - _ => sr25519::Public::from_ss58check(account).unwrap().into_account().into(), - } -} - -// TODO this function is ALMOST redundant with client::main -// get a pair either form keyring (well known keys) or from the store -pub(crate) fn get_pair_from_str( - trusted_args: &TrustedCli, - account: &str, - cli: &Cli, -) -> sr25519_core::Pair { - info!("getting pair for {}", account); - match &account[..2] { - "//" => { - let pair = sr25519_core::Pair::from_string(account, None).unwrap(); - info!("public_key: {:?}", &pair.public().to_hex()); - pair - }, - _ => { - info!("fetching from keystore at {}", &TRUSTED_KEYSTORE_PATH); - // open store without password protection - let store = LocalKeystore::open(get_keystore_path(trusted_args, cli), None) - .expect("store should exist"); - info!("store opened"); - let public_key = &sr25519::AppPublic::from_ss58check(account).unwrap(); - info!("public_key: {:?}", &public_key); - let _pair = store.key_pair::(public_key).unwrap().unwrap(); - info!("key pair fetched"); - drop(store); - _pair.into() - }, - } -} - -// helper method to get the pending trusted calls for a given account via direct RPC -pub(crate) fn get_pending_trusted_calls_for( - cli: &Cli, - trusted_args: &TrustedCli, - who: &AccountId, -) -> Vec> { - let shard = read_shard(trusted_args, cli).unwrap(); - let direct_api = get_worker_api_direct(cli); - let rpc_method = "author_pendingTrustedCallsFor".to_owned(); - let jsonrpc_call: String = RpcRequest::compose_jsonrpc_call( - Id::Text("1".to_string()), - rpc_method, - vec![shard.encode().to_base58(), who.to_hex()], - ) - .unwrap(); - - let rpc_response_str = direct_api.get(&jsonrpc_call).unwrap(); - let rpc_response: RpcResponse = serde_json::from_str(&rpc_response_str).unwrap(); - let rpc_return_value = RpcReturnValue::from_hex(&rpc_response.result).unwrap(); - - if rpc_return_value.status == DirectRequestStatus::Error { - error!("{}", String::decode(&mut rpc_return_value.value.as_slice()).unwrap()); - direct_api.close().unwrap(); - return vec![] - } - - direct_api.close().unwrap(); - Decode::decode(&mut rpc_return_value.value.as_slice()).unwrap_or_default() -} diff --git a/tee-worker/bitacross/cli/src/trusted_operation.rs b/tee-worker/bitacross/cli/src/trusted_operation.rs deleted file mode 100644 index e3cdcacb11..0000000000 --- a/tee-worker/bitacross/cli/src/trusted_operation.rs +++ /dev/null @@ -1,443 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use crate::{ - command_utils::{get_chain_api, get_pair_from_str, get_shielding_key, get_worker_api_direct}, - trusted_cli::TrustedCli, - Cli, -}; -use base58::{FromBase58, ToBase58}; -use codec::{Decode, Encode, Input}; -use ita_stf::{Getter, TrustedCallSigned}; -use itc_rpc_client::direct_client::{DirectApi, DirectClient}; -use itp_node_api::api_client::{ApiClientError, TEEBAG}; -use itp_rpc::{Id, RpcRequest, RpcResponse, RpcReturnValue}; -use itp_sgx_crypto::ShieldingCryptoEncrypt; -use itp_stf_primitives::{ - error::StfError, - types::{ShardIdentifier, TrustedOperation}, -}; -use itp_types::{ - parentchain::{events::ParentchainBlockProcessed, BlockHash, BlockNumber, Hash}, - DirectRequestStatus, RsaRequest, TrustedOperationStatus, -}; -use itp_utils::{FromHexPrefixed, ToHexPrefixed}; -use log::*; -use sp_core::H256; -use std::{ - fmt::Debug, - result::Result as StdResult, - sync::mpsc::{channel, Receiver}, - time::Instant, -}; -use substrate_api_client::{ - ac_compose_macros::compose_extrinsic, GetChainInfo, SubmitAndWatch, SubscribeEvents, XtStatus, -}; -use thiserror::Error; - -const TIMEOUT_BLOCKS: BlockNumber = 10; - -#[derive(Debug, Error)] -pub(crate) enum TrustedOperationError { - #[error("{0:?}")] - ApiClient(ApiClientError), - #[error("Could not retrieve Header from node")] - MissingBlock, - #[error("confirmation timed out after ({0:?}) blocks")] - ConfirmationTimedOut(BlockNumber), - #[error("Confirmed Block Number ({0:?}) exceeds expected one ({0:?})")] - ConfirmedBlockNumberTooHigh( - itp_types::parentchain::BlockNumber, - itp_types::parentchain::BlockNumber, - ), - #[error("Confirmed Block Hash ({0:?}) does not match expected one ({0:?})")] - ConfirmedBlockHashDoesNotMatchExpected(BlockHash, BlockHash), - #[error("invocation extrinsic L1 error: {msg:?}")] - IndirectInvocationFailed { msg: String }, - #[error("default error: {msg:?}")] - Default { msg: String }, -} - -impl From for TrustedOperationError { - fn from(error: ApiClientError) -> Self { - Self::ApiClient(error) - } -} - -pub(crate) type TrustedOpResult = StdResult; - -pub(crate) fn perform_trusted_operation( - cli: &Cli, - trusted_args: &TrustedCli, - top: &TrustedOperation, -) -> TrustedOpResult { - match top { - TrustedOperation::indirect_call(_) => send_indirect_request::(cli, trusted_args, top), - TrustedOperation::direct_call(_) => send_direct_request::(cli, trusted_args, top), - TrustedOperation::get(getter) => - execute_getter_from_cli_args::(cli, trusted_args, getter), - } -} - -fn execute_getter_from_cli_args( - cli: &Cli, - trusted_args: &TrustedCli, - getter: &Getter, -) -> TrustedOpResult { - let shard = read_shard(trusted_args, cli).unwrap(); - let direct_api = get_worker_api_direct(cli); - get_state(&direct_api, shard, getter) -} - -pub(crate) fn get_state( - direct_api: &DirectClient, - shard: ShardIdentifier, - getter: &Getter, -) -> TrustedOpResult { - // Compose jsonrpc call. - let data = RsaRequest::new(shard, getter.encode()); - let rpc_method = "state_executeGetter".to_owned(); - let jsonrpc_call: String = RpcRequest::compose_jsonrpc_call( - Id::Text("1".to_string()), - rpc_method, - vec![data.to_hex()], - ) - .unwrap(); - - let rpc_response_str = direct_api.get(&jsonrpc_call).unwrap(); - - // Decode RPC response. - let rpc_response: RpcResponse = serde_json::from_str(&rpc_response_str) - .map_err(|err| TrustedOperationError::Default { msg: err.to_string() })?; - let rpc_return_value = RpcReturnValue::from_hex(&rpc_response.result) - // Replace with `inspect_err` once it's stable. - .map_err(|err| { - error!("Failed to decode RpcReturnValue: {:?}", err); - TrustedOperationError::Default { msg: "RpcReturnValue::from_hex".to_string() } - })?; - - if rpc_return_value.status == DirectRequestStatus::Error { - error!("{}", String::decode(&mut rpc_return_value.value.as_slice()).unwrap()); - return Err(TrustedOperationError::Default { - msg: "[Error] DirectRequestStatus::Error".to_string(), - }) - } - - let maybe_state: Option> = Option::decode(&mut rpc_return_value.value.as_slice()) - // Replace with `inspect_err` once it's stable. - .map_err(|err| { - error!("Failed to decode return value: {:?}", err); - TrustedOperationError::Default { msg: "Option::decode".to_string() } - })?; - - match maybe_state { - Some(state) => { - let decoded = decode_response_value(&mut state.as_slice())?; - Ok(decoded) - }, - None => Err(TrustedOperationError::Default { msg: "Value not present".to_string() }), - } -} - -fn send_indirect_request( - cli: &Cli, - trusted_args: &TrustedCli, - trusted_operation: &TrustedOperation, -) -> TrustedOpResult { - let mut chain_api = get_chain_api(cli); - let encryption_key = get_shielding_key(cli).unwrap(); - let call_encrypted = encryption_key.encrypt(&trusted_operation.encode()).unwrap(); - - let shard = read_shard(trusted_args, cli).unwrap(); - debug!( - "invoke indirect send_request: trusted operation: {:?}, shard: {}", - trusted_operation, - shard.encode().to_base58() - ); - let arg_signer = &trusted_args.xt_signer; - let signer = get_pair_from_str(arg_signer); - chain_api.set_signer(signer.into()); - - let request = RsaRequest::new(shard, call_encrypted); - let xt = compose_extrinsic!(&chain_api, TEEBAG, "post_opaque_task", request); - - let invocation_block_hash = match chain_api - .submit_and_watch_extrinsic_until(xt, XtStatus::InBlock) - { - Ok(xt_report) => { - println!( - "[+] invoke TrustedOperation extrinsic success. extrinsic hash: {:?} / status: {:?} / block hash: {:?}", - xt_report.extrinsic_hash, xt_report.status, xt_report.block_hash.unwrap() - ); - xt_report.block_hash.unwrap() - }, - Err(e) => { - error!("invoke TrustedOperation extrinsic failed {:?}", e); - return Err(TrustedOperationError::IndirectInvocationFailed { msg: format!("{:?}", e) }) - }, - }; - let invocation_block_number = chain_api - .get_header(Some(invocation_block_hash))? - .ok_or(TrustedOperationError::MissingBlock)? - .number; - info!( - "Trusted call extrinsic sent for shard {} and successfully included in parentchain block {} with hash {:?}.", - shard.encode().to_base58(), invocation_block_number, invocation_block_hash - ); - info!("Waiting for execution confirmation from enclave..."); - let mut blocks = 0u32; - let mut subscription = chain_api.subscribe_events().unwrap(); - loop { - let events = subscription.next_events_from_metadata().unwrap().unwrap(); - blocks += 1; - if blocks > TIMEOUT_BLOCKS { - return Err(TrustedOperationError::ConfirmationTimedOut(blocks)) - } - for event in events.iter() { - let event = event.unwrap(); - match event.pallet_name() { - "Teebag" => match event.variant_name() { - "ParentchainBlockProcessed" => { - if let Ok(Some(ev)) = event.as_event::() { - println!("Teebag::{:?}", ev); - debug!( - "Invocation block Number we're waiting for: {:?}", - invocation_block_number - ); - debug!("Confirmed block Number: {:?}", ev.block_number); - // The returned block number belongs to a subsequent event. We missed our event and can break the loop. - if ev.block_number > invocation_block_number { - return Err(TrustedOperationError::ConfirmedBlockNumberTooHigh( - ev.block_number, - invocation_block_number, - )) - } - // The block number is correct, but the block hash does not fit. - if invocation_block_number == ev.block_number - && invocation_block_hash != ev.block_hash - { - return Err( - TrustedOperationError::ConfirmedBlockHashDoesNotMatchExpected( - ev.block_hash, - invocation_block_hash, - ), - ) - } - if ev.block_hash == invocation_block_hash { - let value = decode_response_value( - &mut invocation_block_hash.encode().as_slice(), - )?; - return Ok(value) - } - } - }, - _ => continue, - }, - _ => continue, - } - } - } -} - -pub fn read_shard( - trusted_args: &TrustedCli, - cli: &Cli, -) -> StdResult { - match &trusted_args.shard { - Some(s) => match s.from_base58() { - Ok(s) => ShardIdentifier::decode(&mut &s[..]), - _ => panic!("shard argument must be base58 encoded"), - }, - None => match trusted_args.mrenclave.clone() { - Some(mrenclave) => - if let Ok(s) = mrenclave.from_base58() { - ShardIdentifier::decode(&mut &s[..]) - } else { - panic!("Mrenclave argument must be base58 encoded") - }, - None => { - // Fetch mrenclave from worker - let direct_api = get_worker_api_direct(cli); - if let Ok(s) = direct_api.get_state_mrenclave() { - ShardIdentifier::decode(&mut &s[..]) - } else { - panic!("Unable to fetch MRENCLAVE from worker endpoint"); - } - }, - }, - } -} - -/// sends a rpc watch request to the worker api server -fn send_direct_request( - cli: &Cli, - trusted_args: &TrustedCli, - top: &TrustedOperation, -) -> TrustedOpResult { - let encryption_key = get_shielding_key(cli).unwrap(); - let shard = read_shard(trusted_args, cli).unwrap(); - let jsonrpc_call: String = get_json_request(shard, top, encryption_key); - - debug!("get direct api"); - let direct_api = get_worker_api_direct(cli); - - debug!("setup sender and receiver"); - let (sender, receiver) = channel(); - direct_api.watch(jsonrpc_call, sender); - - debug!("waiting for rpc response"); - loop { - match receiver.recv() { - Ok(response) => { - debug!("received response"); - let response: RpcResponse = serde_json::from_str(&response).unwrap(); - if let Ok(return_value) = RpcReturnValue::from_hex(&response.result) { - match return_value.status { - DirectRequestStatus::Error => { - debug!("request status is error"); - if let Ok(value) = String::decode(&mut return_value.value.as_slice()) { - error!("{}", value); - } - direct_api.close().unwrap(); - return Err(TrustedOperationError::Default { - msg: "[Error] DirectRequestStatus::Error".to_string(), - }) - }, - DirectRequestStatus::TrustedOperationStatus(status, top_hash) => { - debug!("request status is: {:?}, top_hash: {:?}", status, top_hash); - - if matches!(status, TrustedOperationStatus::Invalid) { - let error = StfError::decode(&mut return_value.value.as_slice()) - .map_err(|e| TrustedOperationError::Default { - msg: format!("Could not decode error value: {:?}", e), - })?; - return Err(TrustedOperationError::Default { - msg: format!( - "[Error] Error occurred while executing trusted call: {:?}", - error - ), - }) - } - if let Ok(value) = Hash::decode(&mut return_value.value.as_slice()) { - println!("Trusted call {:?} is {:?}", value, status); - } - if !return_value.do_watch { - direct_api.close().unwrap(); - let value = - decode_response_value(&mut return_value.value.as_slice())?; - return Ok(value) - } - }, - DirectRequestStatus::Ok | DirectRequestStatus::Processing(_) => { - debug!("request status is ignored"); - direct_api.close().unwrap(); - return Err(TrustedOperationError::Default { - msg: "Unexpected status: DirectRequestStatus::Ok".to_string(), - }) - }, - } - }; - }, - Err(e) => { - error!("failed to receive rpc response: {:?}", e); - direct_api.close().unwrap(); - return Err(TrustedOperationError::Default { - msg: "failed to receive rpc response".to_string(), - }) - }, - }; - } -} - -fn decode_response_value( - value: &mut I, -) -> StdResult { - T::decode(value).map_err(|e| TrustedOperationError::Default { - msg: format!("Could not decode result value: {:?}", e), - }) -} - -pub(crate) fn get_json_request( - shard: ShardIdentifier, - top: &TrustedOperation, - shielding_pubkey: sgx_crypto_helper::rsa3072::Rsa3072PubKey, -) -> String { - let encrypted_top = shielding_pubkey.encrypt(&top.encode()).unwrap(); - - // compose jsonrpc call - let request = RsaRequest::new(shard, encrypted_top); - RpcRequest::compose_jsonrpc_call( - Id::Text("1".to_string()), - "author_submitAndWatchRsaRequest".to_string(), - vec![request.to_hex()], - ) - .unwrap() -} - -pub(crate) fn wait_until( - receiver: &Receiver, - until: impl Fn(TrustedOperationStatus) -> bool, -) -> Option<(H256, Instant)> { - debug!("waiting for rpc response"); - loop { - match receiver.recv() { - Ok(response) => { - debug!("received response: {}", response); - let parse_result: Result = serde_json::from_str(&response); - if let Ok(response) = parse_result { - if let Ok(return_value) = RpcReturnValue::from_hex(&response.result) { - debug!("successfully decoded rpc response: {:?}", return_value); - match return_value.status { - DirectRequestStatus::Error => { - debug!("request status is error"); - if let Ok(value) = - String::decode(&mut return_value.value.as_slice()) - { - error!("{}", value); - } - return None - }, - DirectRequestStatus::TrustedOperationStatus(status, top_hash) => { - debug!("request status is: {:?}, top_hash: {:?}", status, top_hash); - if let Ok(value) = Hash::decode(&mut return_value.value.as_slice()) - { - println!("Trusted call {:?} is {:?}", value, status); - if until(status.clone()) { - return Some((top_hash, Instant::now())) - } else if status == TrustedOperationStatus::Invalid { - error!("Invalid request"); - return None - } - } - }, - DirectRequestStatus::Ok | DirectRequestStatus::Processing(_) => { - debug!("request status is ignored"); - return None - }, - } - }; - } else { - error!("Could not parse response"); - }; - }, - Err(e) => { - error!("failed to receive rpc response: {:?}", e); - return None - }, - }; - } -} diff --git a/tee-worker/bitacross/cli/test_auto_shielding_with_transfer_bob.sh b/tee-worker/bitacross/cli/test_auto_shielding_with_transfer_bob.sh deleted file mode 100644 index 255d3f5bbc..0000000000 --- a/tee-worker/bitacross/cli/test_auto_shielding_with_transfer_bob.sh +++ /dev/null @@ -1,141 +0,0 @@ -#!/bin/bash -set -euo pipefail - -# Verifies that auto shielding transfers sent to vault account: //Alice are verified from sender //Bob -# - -while getopts ":m:p:A:u:V:w:x:y:z:C:" opt; do - case $opt in - p) - INTEGRITEE_RPC_PORT=$OPTARG - ;; - A) - WORKER_1_PORT=$OPTARG - ;; - u) - INTEGRITEE_RPC_URL=$OPTARG - ;; - V) - WORKER_1_URL=$OPTARG - ;; - w) - TARGET_A_PARENTCHAIN_RPC_URL=$OPTARG - ;; - x) - TARGET_A_PARENTCHAIN_RPC_PORT=$OPTARG - ;; - C) - CLIENT_BIN=$OPTARG - ;; - *) - echo "invalid arg ${OPTARG}" - exit 1 - esac -done - -# Using default port if none given as arguments. -INTEGRITEE_RPC_PORT=${INTEGRITEE_RPC_PORT:-9944} -INTEGRITEE_RPC_URL=${INTEGRITEE_RPC_URL:-"ws://127.0.0.1"} -TARGET_A_PARENTCHAIN_RPC_PORT=${TARGET_A_PARENTCHAIN_RPC_PORT:-9966} -TARGET_A_PARENTCHAIN_RPC_URL=${TARGET_A_PARENTCHAIN_RPC_URL:-"ws://127.0.0.1"} - -WORKER_1_PORT=${WORKER_1_PORT:-2000} -WORKER_1_URL=${WORKER_1_URL:-"wss://127.0.0.1"} - -CLIENT_BIN=${CLIENT_BIN:-"./../bin/integritee-cli"} - -echo "Using client binary ${CLIENT_BIN}" -${CLIENT_BIN} --version -echo "Using Integritee RPC uri ${INTEGRITEE_RPC_URL}:${INTEGRITEE_RPC_PORT}" -echo "Using Target A RPC uri ${TARGET_A_PARENTCHAIN_RPC_URL}:${TARGET_A_PARENTCHAIN_RPC_PORT}" -echo "Using trusted-worker 1 uri ${WORKER_1_URL}:${WORKER_1_PORT}" -echo "" - -# the parentchain token is 12 decimal -UNIT=$(( 10 ** 12 )) -FEE_TOLERANCE=$((10 ** 11)) - -# make these amounts greater than ED -AMOUNT_SHIELD=$(( 6 * UNIT )) - -CLIENT="${CLIENT_BIN} -p ${INTEGRITEE_RPC_PORT} -P ${WORKER_1_PORT} -u ${INTEGRITEE_RPC_URL} -U ${WORKER_1_URL}" -CLIENT2="${CLIENT_BIN} -p ${TARGET_A_PARENTCHAIN_RPC_PORT} -P ${WORKER_1_PORT} -u ${TARGET_A_PARENTCHAIN_RPC_URL} -U ${WORKER_1_URL}" - -# interval and max rounds to wait to check the given account balance in sidechain -WAIT_INTERVAL_SECONDS=10 -WAIT_ROUNDS=20 - -# Poll and assert the given account's state is equal to expected, -# with timeout WAIT_INTERVAL_SECONDS * WAIT_ROUNDS -# usage: -# wait_assert_state -# the `state-name` has to be the supported subcommand, e.g. `balance`, `nonce` -function wait_assert_state() -{ - for i in $(seq 1 $WAIT_ROUNDS); do - sleep $WAIT_INTERVAL_SECONDS - state=$(${CLIENT} trusted --mrenclave "$1" "$3" "$2") - if (( $4 >= state ? $4 - state < FEE_TOLERANCE : state - $4 < FEE_TOLERANCE)); then - return - else - : - fi - done - echo - echo "Assert $2 $3 failed, expected = $4, actual = $state, tolerance = $FEE_TOLERANCE" - exit 1 -} - -# Do a live query and assert the given account's state is equal to expected -# usage: -# assert_state -function assert_state() -{ - state=$(${CLIENT} trusted --mrenclave "$1" "$3" "$2") - if [ -z "$state" ]; then - echo "Query $2 $3 failed" - exit 1 - fi - - if [ $state -eq "$4" ]; then - return - fi - echo - echo "Assert $2 $3 failed, expected = $4, actual = $state" - exit 1 -} - -echo "* Query on-chain enclave registry:" -${CLIENT} list-workers -echo "" - -# this will always take the first MRENCLAVE found in the registry !! -read MRENCLAVE <<< $($CLIENT list-workers | awk '/ MRENCLAVE: / { print $2; exit }') -echo "Reading MRENCLAVE from worker list: ${MRENCLAVE}" - -[[ -z $MRENCLAVE ]] && { echo "MRENCLAVE is empty. cannot continue" ; exit 1; } - -VAULTACCOUNT=//Alice -## Sender account to shield for -BOBTRUSTEDACCOUNT=//Bob -echo " Bob's trusted account (same as public account) = ${BOBTRUSTEDACCOUNT}" -echo "" - -# Assert the initial trusted balance of Alice incognito -TRUSTED_BALANCE_BOB=1000000000000000 -wait_assert_state ${MRENCLAVE} ${BOBTRUSTEDACCOUNT} balance ${TRUSTED_BALANCE_BOB} - - -echo "* Send ${AMOUNT_SHIELD} from //Bob to //Alice on the Target A parentchain, which should trigger the shield process" -${CLIENT2} transfer //Bob ${VAULTACCOUNT} ${AMOUNT_SHIELD} -echo "" - -echo "* Wait and assert Bob's incognito account balance, should be $(( TRUSTED_BALANCE_BOB + AMOUNT_SHIELD ))" -wait_assert_state ${MRENCLAVE} ${BOBTRUSTEDACCOUNT} balance $(( TRUSTED_BALANCE_BOB + AMOUNT_SHIELD )) -echo "✔ ok" - -echo "" -echo "-----------------------" -echo "✔ The test passed!" -echo "-----------------------" -echo "" diff --git a/tee-worker/bitacross/cli/test_shield_on_target_nodes_with_transfer_to_alice.sh b/tee-worker/bitacross/cli/test_shield_on_target_nodes_with_transfer_to_alice.sh deleted file mode 100755 index b1670e5bb8..0000000000 --- a/tee-worker/bitacross/cli/test_shield_on_target_nodes_with_transfer_to_alice.sh +++ /dev/null @@ -1,159 +0,0 @@ -#!/bin/bash -set -euo pipefail - -# Verifies that shielding from the Target A and B parentchains works by sending a transfer to //Alice. -# -# Note: This test does not do anything meaningful. It only verifies the basic functionality of the Target parentchain -# connections. - -while getopts ":m:p:A:u:V:w:x:y:z:C:" opt; do - case $opt in - p) - LITENTRY_RPC_PORT=$OPTARG - ;; - A) - WORKER_1_PORT=$OPTARG - ;; - u) - LITENTRY_RPC_URL=$OPTARG - ;; - V) - WORKER_1_URL=$OPTARG - ;; - w) - TARGET_A_PARENTCHAIN_RPC_URL=$OPTARG - ;; - x) - TARGET_A_PARENTCHAIN_RPC_PORT=$OPTARG - ;; - y) - TARGET_B_PARENTCHAIN_RPC_URL=$OPTARG - ;; - z) - TARGET_B_PARENTCHAIN_RPC_PORT=$OPTARG - ;; - C) - CLIENT_BIN=$OPTARG - ;; - *) - echo "invalid arg ${OPTARG}" - exit 1 - esac -done - -# Using default port if none given as arguments. -LITENTRY_RPC_PORT=${LITENTRY_RPC_PORT:-9944} -LITENTRY_RPC_URL=${LITENTRY_RPC_URL:-"ws://127.0.0.1"} -TARGET_A_PARENTCHAIN_RPC_PORT=${TARGET_A_PARENTCHAIN_RPC_PORT:-9966} -TARGET_A_PARENTCHAIN_RPC_URL=${TARGET_A_PARENTCHAIN_RPC_URL:-"ws://127.0.0.1"} -TARGET_B_PARENTCHAIN_RPC_PORT=${TARGET_B_PARENTCHAIN_RPC_PORT:-9988} -TARGET_B_PARENTCHAIN_RPC_URL=${TARGET_B_PARENTCHAIN_RPC_URL:-"ws://127.0.0.1"} - -WORKER_1_PORT=${WORKER_1_PORT:-2000} -WORKER_1_URL=${WORKER_1_URL:-"wss://127.0.0.1"} - -CLIENT_BIN=${CLIENT_BIN:-"./../bin/bitacross-cli"} - -echo "Using client binary ${CLIENT_BIN}" -${CLIENT_BIN} --version -echo "Using Integritee RPC uri ${LITENTRY_RPC_URL}:${LITENTRY_RPC_PORT}" -echo "Using Target A RPC uri ${TARGET_A_PARENTCHAIN_RPC_URL}:${TARGET_A_PARENTCHAIN_RPC_PORT}" -echo "Using Target B RPC uri ${TARGET_B_PARENTCHAIN_RPC_URL}:${TARGET_B_PARENTCHAIN_RPC_PORT}" -echo "Using trusted-worker 1 uri ${WORKER_1_URL}:${WORKER_1_PORT}" -echo "" - -# the parentchain token is 12 decimal -UNIT=$(( 10 ** 12 )) -FEE_TOLERANCE=$((10 ** 11)) - -# make these amounts greater than ED -AMOUNT_SHIELD=$(( 6 * UNIT )) - -CLIENT="${CLIENT_BIN} -p ${LITENTRY_RPC_PORT} -P ${WORKER_1_PORT} -u ${LITENTRY_RPC_URL} -U ${WORKER_1_URL}" -CLIENT2="${CLIENT_BIN} -p ${TARGET_A_PARENTCHAIN_RPC_PORT} -P ${WORKER_1_PORT} -u ${TARGET_A_PARENTCHAIN_RPC_URL} -U ${WORKER_1_URL}" -CLIENT3="${CLIENT_BIN} -p ${TARGET_B_PARENTCHAIN_RPC_PORT} -P ${WORKER_1_PORT} -u ${TARGET_B_PARENTCHAIN_RPC_URL} -U ${WORKER_1_URL}" - -# interval and max rounds to wait to check the given account balance in sidechain -WAIT_INTERVAL_SECONDS=10 -WAIT_ROUNDS=20 - -# Poll and assert the given account's state is equal to expected, -# with timeout WAIT_INTERVAL_SECONDS * WAIT_ROUNDS -# usage: -# wait_assert_state -# the `state-name` has to be the supported subcommand, e.g. `balance`, `nonce` -function wait_assert_state() -{ - for i in $(seq 1 $WAIT_ROUNDS); do - sleep $WAIT_INTERVAL_SECONDS - state=$(${CLIENT} trusted --mrenclave "$1" "$3" "$2") - if (( $4 >= state ? $4 - state < FEE_TOLERANCE : state - $4 < FEE_TOLERANCE)); then - return - else - : - fi - done - echo - echo "Assert $2 $3 failed, expected = $4, actual = $state, tolerance = $FEE_TOLERANCE" - exit 1 -} - -# Do a live query and assert the given account's state is equal to expected -# usage: -# assert_state -function assert_state() -{ - state=$(${CLIENT} trusted --mrenclave "$1" "$3" "$2") - if [ -z "$state" ]; then - echo "Query $2 $3 failed" - exit 1 - fi - - if [ $state -eq "$4" ]; then - return - fi - echo - echo "Assert $2 $3 failed, expected = $4, actual = $state" - exit 1 -} - -echo "* Query on-chain enclave registry:" -${CLIENT} list-workers -echo "" - -# this will always take the first MRENCLAVE found in the registry !! -read MRENCLAVE <<< $($CLIENT list-workers | awk '/ MRENCLAVE: / { print $2; exit }') -echo "Reading MRENCLAVE from worker list: ${MRENCLAVE}" - -[[ -z $MRENCLAVE ]] && { echo "MRENCLAVE is empty. cannot continue" ; exit 1; } - -ALICETRUSTEDACCOUNT=//Alice -echo " Alice's trusted account (same as public account) = ${ALICETRUSTEDACCOUNT}" -echo "" - -# Assert the initial trusted balance of Alice incognito -TRUSTED_BALANCE_ALICE=1000000000000000 -wait_assert_state ${MRENCLAVE} ${ALICETRUSTEDACCOUNT} balance ${TRUSTED_BALANCE_ALICE} - - -echo "* Send ${AMOUNT_SHIELD} from //Alice to //Alice on the Target A parentchain, which should trigger the shield process" -${CLIENT2} transfer //Alice ${ALICETRUSTEDACCOUNT} ${AMOUNT_SHIELD} -echo "" - -echo "* Wait and assert Alice's incognito account balance, should be $(( TRUSTED_BALANCE_ALICE + AMOUNT_SHIELD ))" -wait_assert_state ${MRENCLAVE} ${ALICETRUSTEDACCOUNT} balance $(( TRUSTED_BALANCE_ALICE + AMOUNT_SHIELD )) -echo "✔ ok" - -echo "* Send ${AMOUNT_SHIELD} from //Alice to //Alice on the Target B Parentchain, which should trigger the shield process again" -${CLIENT3} transfer //Alice ${ALICETRUSTEDACCOUNT} ${AMOUNT_SHIELD} -echo "" - -echo "* Wait and assert Alice's incognito account balance, should be $(( TRUSTED_BALANCE_ALICE + 2*AMOUNT_SHIELD ))" -wait_assert_state ${MRENCLAVE} ${ALICETRUSTEDACCOUNT} balance $(( TRUSTED_BALANCE_ALICE + 2*AMOUNT_SHIELD )) -echo "✔ ok" - -echo "" -echo "-----------------------" -echo "✔ The test passed!" -echo "-----------------------" -echo "" diff --git a/tee-worker/bitacross/cli/tests/basic_tests.rs b/tee-worker/bitacross/cli/tests/basic_tests.rs deleted file mode 100644 index e01d318681..0000000000 --- a/tee-worker/bitacross/cli/tests/basic_tests.rs +++ /dev/null @@ -1,24 +0,0 @@ -use bitacross_cli::Cli; -use clap::Parser; - -fn init() { - let _ = env_logger::try_init(); -} - -#[test] -fn test_version() { - init(); - - let res = Cli::try_parse_from(vec!["placeholder_cli_path", "--version"]); - let _err = clap::Error::new(clap::error::ErrorKind::DisplayVersion); - assert!(matches!(res, Err(_err))); -} - -#[test] -fn test_help() { - init(); - - let res = Cli::try_parse_from(vec!["placeholder_cli_path", "--help"]); - let _err = clap::Error::new(clap::error::ErrorKind::DisplayHelp); - assert!(matches!(res, Err(_err))); -} diff --git a/tee-worker/bitacross/core-primitives/enclave-api/Cargo.toml b/tee-worker/bitacross/core-primitives/enclave-api/Cargo.toml deleted file mode 100644 index ca364fa05d..0000000000 --- a/tee-worker/bitacross/core-primitives/enclave-api/Cargo.toml +++ /dev/null @@ -1,34 +0,0 @@ -[package] -name = "bc-itp-enclave-api" -version = "0.1.0" -authors = ['Trust Computing GmbH ', 'Integritee AG '] -edition = "2021" - -[dependencies] -codec = { package = "parity-scale-codec", workspace = true } -hex = { workspace = true } -log = { workspace = true } -serde_json = { workspace = true } -thiserror = { workspace = true } - -sgx_crypto_helper = { workspace = true } -sgx_types = { workspace = true } -sgx_urts = { workspace = true, optional = true } - -frame-support = { workspace = true } -sp-core = { workspace = true } -sp-runtime = { workspace = true } - -itp-enclave-api-ffi = { package = "bc-itp-enclave-api-ffi", path = "ffi" } -itp-settings = { workspace = true } -itp-sgx-crypto = { workspace = true } -itp-stf-interface = { workspace = true } -itp-storage = { workspace = true } -itp-types = { workspace = true } - -[features] -default = [] -implement-ffi = [ - "sgx_urts", - "itp-enclave-api-ffi/link-sgx-libs", -] diff --git a/tee-worker/bitacross/core-primitives/enclave-api/build.rs b/tee-worker/bitacross/core-primitives/enclave-api/build.rs deleted file mode 100644 index 1c20ea4c84..0000000000 --- a/tee-worker/bitacross/core-primitives/enclave-api/build.rs +++ /dev/null @@ -1,24 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - http://www.apache.org/licenses/LICENSE-2.0 - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ - -fn main() { - // If the linker failed to find libsgx_dcap_ql.so, please make sure that - // (1) libsgx-dcap-ql is installed - // (2) libsgx_dcap_ql.so exists. typicall at /usr/lib/x86_64-linux-gnu - // if libsgx_dcap_ql.so.1 is there, but no libsgx-dcap_ql, - // just create a symlink by - // ln -s libsgx_dcap_ql.so.1 libsgx_dcap_ql.so - println!("cargo:rustc-link-lib=dylib=sgx_dcap_ql"); - println!("cargo:rustc-link-lib=dylib=sgx_dcap_quoteverify"); - println!("cargo:rustc-link-lib=dylib=dcap_quoteprov"); -} diff --git a/tee-worker/bitacross/core-primitives/enclave-api/ffi/Cargo.toml b/tee-worker/bitacross/core-primitives/enclave-api/ffi/Cargo.toml deleted file mode 100644 index 1daa3ab730..0000000000 --- a/tee-worker/bitacross/core-primitives/enclave-api/ffi/Cargo.toml +++ /dev/null @@ -1,12 +0,0 @@ -[package] -name = "bc-itp-enclave-api-ffi" -version = "0.1.0" -edition = "2021" - -[dependencies] -sgx_types = { workspace = true } - -[features] -# necessary to run cargo tests without any preliminaries -# See: https://github.com/rust-lang/cargo/issues/2549 -link-sgx-libs = [] diff --git a/tee-worker/bitacross/core-primitives/enclave-api/ffi/build.rs b/tee-worker/bitacross/core-primitives/enclave-api/ffi/build.rs deleted file mode 100644 index 09ccb3b707..0000000000 --- a/tee-worker/bitacross/core-primitives/enclave-api/ffi/build.rs +++ /dev/null @@ -1,44 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - Copyright (C) 2017-2019 Baidu, Inc. All Rights Reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -fn main() { - if cfg!(feature = "link-sgx-libs") { - use std::env; - - let sdk_dir = env::var("SGX_SDK").unwrap_or_else(|_| "/opt/intel/sgxsdk".to_string()); - let is_sim = env::var("SGX_MODE").unwrap_or_else(|_| "HW".to_string()); - - // NOTE: if the crate is a workspace member rustc-paths are relative from the root directory - println!("cargo:rustc-link-search=native=./bitacross/lib"); - println!("cargo:rustc-link-lib=static=Enclave_u"); - - println!("cargo:rustc-link-search=native={}/lib64", sdk_dir); - println!("cargo:rustc-link-lib=static=sgx_uprotected_fs"); - match is_sim.as_ref() { - "SW" => { - println!("cargo:rustc-link-lib=dylib=sgx_urts_sim"); - println!("cargo:rustc-link-lib=dylib=sgx_uae_service_sim"); - }, - _ => { - // HW by default - println!("cargo:rustc-link-lib=dylib=sgx_urts"); - println!("cargo:rustc-link-lib=dylib=sgx_uae_service"); - }, - } - } -} diff --git a/tee-worker/bitacross/core-primitives/enclave-api/ffi/src/lib.rs b/tee-worker/bitacross/core-primitives/enclave-api/ffi/src/lib.rs deleted file mode 100644 index 339aa7bb97..0000000000 --- a/tee-worker/bitacross/core-primitives/enclave-api/ffi/src/lib.rs +++ /dev/null @@ -1,270 +0,0 @@ -///! FFI's that call into the enclave. These functions need to be added to the -/// enclave edl file and be implemented within the enclave. -use sgx_types::{ - c_int, sgx_enclave_id_t, sgx_ql_qve_collateral_t, sgx_quote_sign_type_t, sgx_status_t, - sgx_target_info_t, -}; - -extern "C" { - - pub fn generate_dcap_ra_extrinsic_from_quote( - eid: sgx_enclave_id_t, - retval: *mut sgx_status_t, - w_url: *const u8, - w_url_size: u32, - quote: *const u8, - quote_size: u32, - unchecked_extrinsic: *mut u8, - unchecked_extrinsic_max_size: u32, - unchecked_extrinsic_size: *mut u32, - ) -> sgx_status_t; - - pub fn init( - eid: sgx_enclave_id_t, - retval: *mut sgx_status_t, - mu_ra_addr: *const u8, - mu_ra_addr_size: u32, - untrusted_worker_addr: *const u8, - untrusted_worker_addr_size: u32, - encoded_base_dir_str: *const u8, - encoded_base_dir_size: u32, - ceremony_commands_thread_count: u8, - ceremony_events_thread_count: u8, - ) -> sgx_status_t; - - pub fn init_direct_invocation_server( - eid: sgx_enclave_id_t, - retval: *mut sgx_status_t, - server_addr: *const u8, - server_addr_size: u32, - ) -> sgx_status_t; - - pub fn init_parentchain_components( - eid: sgx_enclave_id_t, - retval: *mut sgx_status_t, - params: *const u8, - params_size: usize, - latest_header: *mut u8, - latest_header_size: usize, - ) -> sgx_status_t; - - pub fn init_shard( - eid: sgx_enclave_id_t, - retval: *mut sgx_status_t, - shard: *const u8, - shard_size: u32, - ) -> sgx_status_t; - - pub fn init_shard_creation_parentchain_header( - eid: sgx_enclave_id_t, - retval: *mut sgx_status_t, - shard: *const u8, - shard_size: u32, - parentchain_id: *const u8, - parentchain_id_size: u32, - header: *const u8, - header_size: u32, - ) -> sgx_status_t; - - pub fn get_shard_creation_info( - eid: sgx_enclave_id_t, - retval: *mut sgx_status_t, - shard: *const u8, - shard_size: u32, - creation: *mut u8, - creation_size: u32, - ) -> sgx_status_t; - - pub fn sync_parentchain( - eid: sgx_enclave_id_t, - retval: *mut sgx_status_t, - blocks: *const u8, - blocks_size: usize, - events: *const u8, - events_size: usize, - events_proofs: *const u8, - events_proofs_size: usize, - parentchain_id: *const u8, - parentchain_id_size: u32, - immediate_import: c_int, - ) -> sgx_status_t; - - pub fn set_nonce( - eid: sgx_enclave_id_t, - retval: *mut sgx_status_t, - nonce: *const u32, - parentchain_id: *const u8, - parentchain_id_size: u32, - ) -> sgx_status_t; - - pub fn set_node_metadata( - eid: sgx_enclave_id_t, - retval: *mut sgx_status_t, - node_metadata: *const u8, - node_metadata_size: u32, - parentchain_id: *const u8, - parentchain_id_size: u32, - ) -> sgx_status_t; - - pub fn get_rsa_encryption_pubkey( - eid: sgx_enclave_id_t, - retval: *mut sgx_status_t, - pubkey: *mut u8, - pubkey_size: u32, - ) -> sgx_status_t; - - pub fn get_ecc_signing_pubkey( - eid: sgx_enclave_id_t, - retval: *mut sgx_status_t, - pubkey: *mut u8, - pubkey_size: u32, - ) -> sgx_status_t; - - pub fn get_bitcoin_wallet_pair( - eid: sgx_enclave_id_t, - retval: *mut sgx_status_t, - pair: *mut u8, - pair_size: u32, - ) -> sgx_status_t; - - pub fn get_ethereum_wallet_pair( - eid: sgx_enclave_id_t, - retval: *mut sgx_status_t, - pair: *mut u8, - pair_size: u32, - ) -> sgx_status_t; - - pub fn get_ton_wallet_pair( - eid: sgx_enclave_id_t, - retval: *mut sgx_status_t, - pair: *mut u8, - pair_size: u32, - ) -> sgx_status_t; - - pub fn get_mrenclave( - eid: sgx_enclave_id_t, - retval: *mut sgx_status_t, - mrenclave: *mut u8, - mrenclave_size: u32, - ) -> sgx_status_t; - - pub fn generate_ias_ra_extrinsic( - eid: sgx_enclave_id_t, - retval: *mut sgx_status_t, - w_url: *const u8, - w_url_size: u32, - unchecked_extrinsic: *mut u8, - unchecked_extrinsic_max_size: u32, - unchecked_extrinsic_size: *mut u32, - skip_ra: c_int, - ) -> sgx_status_t; - - pub fn generate_dcap_ra_extrinsic( - eid: sgx_enclave_id_t, - retval: *mut sgx_status_t, - w_url: *const u8, - w_url_size: u32, - unchecked_extrinsic: *mut u8, - unchecked_extrinsic_max_size: u32, - unchecked_extrinsic_size: *mut u32, - skip_ra: c_int, - quoting_enclave_target_info: Option<&sgx_target_info_t>, - quote_size: Option<&u32>, - ) -> sgx_status_t; - - pub fn generate_dcap_ra_quote( - eid: sgx_enclave_id_t, - retval: *mut sgx_status_t, - skip_ra: c_int, - quoting_enclave_target_info: &sgx_target_info_t, - quote_size: u32, - dcap_quote_p: *mut u8, - dcap_quote_size: u32, - ) -> sgx_status_t; - - pub fn generate_register_quoting_enclave_extrinsic( - eid: sgx_enclave_id_t, - retval: *mut sgx_status_t, - collateral: *const sgx_ql_qve_collateral_t, - unchecked_extrinsic: *mut u8, - unchecked_extrinsic_max_size: u32, - unchecked_extrinsic_size: *mut u32, - ) -> sgx_status_t; - - pub fn generate_register_tcb_info_extrinsic( - eid: sgx_enclave_id_t, - retval: *mut sgx_status_t, - collateral: *const sgx_ql_qve_collateral_t, - unchecked_extrinsic: *mut u8, - unchecked_extrinsic_max_size: u32, - unchecked_extrinsic_size: *mut u32, - ) -> sgx_status_t; - - pub fn dump_ias_ra_cert_to_disk( - eid: sgx_enclave_id_t, - retval: *mut sgx_status_t, - ) -> sgx_status_t; - - pub fn dump_dcap_ra_cert_to_disk( - eid: sgx_enclave_id_t, - retval: *mut sgx_status_t, - quoting_enclave_target_info: &sgx_target_info_t, - quote_size: u32, - ) -> sgx_status_t; - - pub fn dump_dcap_collateral_to_disk( - eid: sgx_enclave_id_t, - retval: *mut sgx_status_t, - collateral: *const sgx_ql_qve_collateral_t, - ) -> sgx_status_t; - - pub fn test_main_entrance(eid: sgx_enclave_id_t, retval: *mut sgx_status_t) -> sgx_status_t; - - pub fn run_state_provisioning_server( - eid: sgx_enclave_id_t, - retval: *mut sgx_status_t, - socket_fd: c_int, - sign_type: sgx_quote_sign_type_t, - quoting_enclave_target_info: Option<&sgx_target_info_t>, - quote_size: Option<&u32>, - skip_ra: c_int, - ) -> sgx_status_t; - - pub fn request_state_provisioning( - eid: sgx_enclave_id_t, - retval: *mut sgx_status_t, - socket_fd: c_int, - sign_type: sgx_quote_sign_type_t, - quoting_enclave_target_info: Option<&sgx_target_info_t>, - quote_size: Option<&u32>, - shard: *const u8, - shard_size: u32, - skip_ra: c_int, - ) -> sgx_status_t; - - // litentry - pub fn migrate_shard( - eid: sgx_enclave_id_t, - retval: *mut sgx_status_t, - new_shard: *const u8, - shard_size: u32, - ) -> sgx_status_t; - - pub fn ignore_parentchain_block_import_validation_until( - eid: sgx_enclave_id_t, - retval: *mut sgx_status_t, - until: *const u32, - ) -> sgx_status_t; - - pub fn publish_wallets(eid: sgx_enclave_id_t, retval: *mut sgx_status_t) -> sgx_status_t; - - pub fn finish_enclave_init(eid: sgx_enclave_id_t, retval: *mut sgx_status_t) -> sgx_status_t; - - pub fn init_wallets( - eid: sgx_enclave_id_t, - retval: *mut sgx_status_t, - encoded_base_dir_str: *const u8, - encoded_base_dir_size: u32, - ) -> sgx_status_t; - -} diff --git a/tee-worker/bitacross/core-primitives/enclave-api/src/enclave_base.rs b/tee-worker/bitacross/core-primitives/enclave-api/src/enclave_base.rs deleted file mode 100644 index 61ce8f2ba9..0000000000 --- a/tee-worker/bitacross/core-primitives/enclave-api/src/enclave_base.rs +++ /dev/null @@ -1,510 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - Copyright (C) 2017-2019 Baidu, Inc. All Rights Reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use crate::EnclaveResult; -use codec::Decode; -use core::fmt::Debug; -use itp_sgx_crypto::{ecdsa, schnorr}; -use itp_stf_interface::ShardCreationInfo; -use itp_types::{ - parentchain::{Header, ParentchainId, ParentchainInitParams}, - EnclaveFingerprint, ShardIdentifier, -}; -use sgx_crypto_helper::rsa3072::Rsa3072PubKey; -use sp_core::ed25519; - -/// Trait for base/common Enclave API functions -pub trait EnclaveBase: Send + Sync + 'static { - /// Initialize the enclave (needs to be called once at application startup). - fn init( - &self, - mu_ra_addr: &str, - untrusted_worker_addr: &str, - base_dir: &str, - ceremony_commands_thread_count: u8, - ceremony_events_thread_count: u8, - ) -> EnclaveResult<()>; - /// Initialize the direct invocation RPC server. - fn init_direct_invocation_server(&self, rpc_server_addr: String) -> EnclaveResult<()>; - - /// Initialize the light client (needs to be called once at application startup). - fn init_parentchain_components( - &self, - params: ParentchainInitParams, - ) -> EnclaveResult
; - - /// Initialize a new shard. - fn init_shard(&self, shard: Vec) -> EnclaveResult<()>; - - /// Initialize parentchain checkpoint after which invocations will be processed - fn init_shard_creation_parentchain_header( - &self, - shard: &ShardIdentifier, - parentchain_id: &ParentchainId, - header: &Header, - ) -> EnclaveResult<()>; - - fn get_shard_creation_info(&self, shard: &ShardIdentifier) -> EnclaveResult; - - fn set_nonce(&self, nonce: u32, parentchain_id: ParentchainId) -> EnclaveResult<()>; - - fn set_node_metadata( - &self, - metadata: Vec, - parentchain_id: ParentchainId, - ) -> EnclaveResult<()>; - - fn get_rsa_shielding_pubkey(&self) -> EnclaveResult; - - fn get_ecc_signing_pubkey(&self) -> EnclaveResult; - - /// retrieve the btc wallet key pair, only works in non-prod - fn get_bitcoin_wallet_pair(&self) -> EnclaveResult; - - /// retrieve the eth wallet key pair, only works in non-prod - fn get_ethereum_wallet_pair(&self) -> EnclaveResult; - - /// retrieve the ton wallet key pair, only works in non-prod - fn get_ton_wallet_pair(&self) -> EnclaveResult; - - fn get_fingerprint(&self) -> EnclaveResult; - - // litentry - fn migrate_shard(&self, new_shard: Vec) -> EnclaveResult<()>; - - /// Publish generated wallets on parachain - fn publish_wallets(&self) -> EnclaveResult<()>; - - /// finish enclave initialization - fn finish_enclave_init(&self) -> EnclaveResult<()>; - - /// init custodian wallets - fn init_wallets(&self, base_dir: &str) -> EnclaveResult<()>; -} - -/// EnclaveApi implementation for Enclave struct -#[cfg(feature = "implement-ffi")] -mod impl_ffi { - use super::{ecdsa, schnorr, EnclaveBase}; - use crate::{error::Error, Enclave, EnclaveResult}; - use codec::{Decode, Encode}; - use core::fmt::Debug; - use frame_support::ensure; - use itp_enclave_api_ffi as ffi; - use itp_settings::worker::{ - HEADER_MAX_SIZE, MR_ENCLAVE_SIZE, SHIELDING_KEY_SIZE, SIGNING_KEY_SIZE, - }; - use itp_stf_interface::ShardCreationInfo; - use itp_types::{ - parentchain::{Header, ParentchainId, ParentchainInitParams}, - EnclaveFingerprint, ShardIdentifier, - }; - use log::*; - use sgx_crypto_helper::rsa3072::Rsa3072PubKey; - use sgx_types::*; - use sp_core::{ed25519, Pair}; - - impl EnclaveBase for Enclave { - fn init( - &self, - mu_ra_addr: &str, - untrusted_worker_addr: &str, - base_dir: &str, - ceremony_commands_thread_count: u8, - ceremony_events_thread_count: u8, - ) -> EnclaveResult<()> { - let mut retval = sgx_status_t::SGX_SUCCESS; - - let encoded_mu_ra_addr = mu_ra_addr.encode(); - let encoded_untrusted_worker_addr = untrusted_worker_addr.encode(); - let encoded_base_dir = base_dir.encode(); - - let result = unsafe { - ffi::init( - self.eid, - &mut retval, - encoded_mu_ra_addr.as_ptr(), - encoded_mu_ra_addr.len() as u32, - encoded_untrusted_worker_addr.as_ptr(), - encoded_untrusted_worker_addr.len() as u32, - encoded_base_dir.as_ptr(), - encoded_base_dir.len() as u32, - ceremony_commands_thread_count, - ceremony_events_thread_count, - ) - }; - - ensure!(result == sgx_status_t::SGX_SUCCESS, Error::Sgx(result)); - ensure!(retval == sgx_status_t::SGX_SUCCESS, Error::Sgx(retval)); - - Ok(()) - } - - fn init_direct_invocation_server(&self, rpc_server_addr: String) -> EnclaveResult<()> { - let mut retval = sgx_status_t::SGX_SUCCESS; - - let encoded_rpc_server_addr = rpc_server_addr.encode(); - - let result = unsafe { - ffi::init_direct_invocation_server( - self.eid, - &mut retval, - encoded_rpc_server_addr.as_ptr(), - encoded_rpc_server_addr.len() as u32, - ) - }; - - ensure!(result == sgx_status_t::SGX_SUCCESS, Error::Sgx(result)); - ensure!(retval == sgx_status_t::SGX_SUCCESS, Error::Sgx(retval)); - - Ok(()) - } - - fn init_parentchain_components( - &self, - params: ParentchainInitParams, - ) -> EnclaveResult
{ - let latest_header_encoded = init_parentchain_components_ffi(self.eid, params.encode())?; - - let latest = Header::decode(&mut latest_header_encoded.as_slice())?; - info!("Latest Header {:?}", latest); - - Ok(latest) - } - - fn init_shard(&self, shard: Vec) -> EnclaveResult<()> { - let mut retval = sgx_status_t::SGX_SUCCESS; - - let result = unsafe { - ffi::init_shard(self.eid, &mut retval, shard.as_ptr(), shard.len() as u32) - }; - - ensure!(result == sgx_status_t::SGX_SUCCESS, Error::Sgx(result)); - ensure!(retval == sgx_status_t::SGX_SUCCESS, Error::Sgx(retval)); - - Ok(()) - } - - fn init_shard_creation_parentchain_header( - &self, - shard: &ShardIdentifier, - parentchain_id: &ParentchainId, - header: &Header, - ) -> EnclaveResult<()> { - let mut retval = sgx_status_t::SGX_SUCCESS; - let parentchain_id_enc = parentchain_id.encode(); - let header_bytes = header.encode(); - let shard_bytes = shard.encode(); - let result = unsafe { - ffi::init_shard_creation_parentchain_header( - self.eid, - &mut retval, - shard_bytes.as_ptr(), - shard_bytes.len() as u32, - parentchain_id_enc.as_ptr(), - parentchain_id_enc.len() as u32, - header_bytes.as_ptr(), - header_bytes.len() as u32, - ) - }; - - ensure!(result == sgx_status_t::SGX_SUCCESS, Error::Sgx(result)); - ensure!(retval == sgx_status_t::SGX_SUCCESS, Error::Sgx(retval)); - - Ok(()) - } - - fn get_shard_creation_info( - &self, - shard: &ShardIdentifier, - ) -> EnclaveResult { - let mut retval = sgx_status_t::SGX_SUCCESS; - let mut creation_info = [0u8; std::mem::size_of::()]; - let shard_bytes = shard.encode(); - - let result = unsafe { - ffi::get_shard_creation_info( - self.eid, - &mut retval, - shard_bytes.as_ptr(), - shard_bytes.len() as u32, - creation_info.as_mut_ptr(), - creation_info.len() as u32, - ) - }; - - ensure!(result == sgx_status_t::SGX_SUCCESS, Error::Sgx(result)); - ensure!(retval == sgx_status_t::SGX_SUCCESS, Error::Sgx(retval)); - Decode::decode(&mut creation_info.as_slice()).map_err(|e| Error::Codec(e.into())) - } - - fn set_nonce(&self, nonce: u32, parentchain_id: ParentchainId) -> EnclaveResult<()> { - let mut retval = sgx_status_t::SGX_SUCCESS; - - let parentchain_id_enc = parentchain_id.encode(); - - let result = unsafe { - ffi::set_nonce( - self.eid, - &mut retval, - &nonce, - parentchain_id_enc.as_ptr(), - parentchain_id_enc.len() as u32, - ) - }; - - ensure!(result == sgx_status_t::SGX_SUCCESS, Error::Sgx(result)); - ensure!(retval == sgx_status_t::SGX_SUCCESS, Error::Sgx(retval)); - - Ok(()) - } - - fn set_node_metadata( - &self, - metadata: Vec, - parentchain_id: ParentchainId, - ) -> EnclaveResult<()> { - let mut retval = sgx_status_t::SGX_SUCCESS; - - let parentchain_id_enc = parentchain_id.encode(); - - let result = unsafe { - ffi::set_node_metadata( - self.eid, - &mut retval, - metadata.as_ptr(), - metadata.len() as u32, - parentchain_id_enc.as_ptr(), - parentchain_id_enc.len() as u32, - ) - }; - - ensure!(result == sgx_status_t::SGX_SUCCESS, Error::Sgx(result)); - ensure!(retval == sgx_status_t::SGX_SUCCESS, Error::Sgx(retval)); - - Ok(()) - } - - fn get_rsa_shielding_pubkey(&self) -> EnclaveResult { - let mut retval = sgx_status_t::SGX_SUCCESS; - - let pubkey_size = SHIELDING_KEY_SIZE; - let mut pubkey = vec![0u8; pubkey_size]; - - let result = unsafe { - ffi::get_rsa_encryption_pubkey( - self.eid, - &mut retval, - pubkey.as_mut_ptr(), - pubkey.len() as u32, - ) - }; - - ensure!(result == sgx_status_t::SGX_SUCCESS, Error::Sgx(result)); - ensure!(retval == sgx_status_t::SGX_SUCCESS, Error::Sgx(retval)); - - let rsa_pubkey: Rsa3072PubKey = - serde_json::from_slice(pubkey.as_slice()).expect("Invalid public key"); - debug!("got RSA pubkey {:?}", rsa_pubkey); - Ok(rsa_pubkey) - } - - fn get_ecc_signing_pubkey(&self) -> EnclaveResult { - let mut retval = sgx_status_t::SGX_SUCCESS; - let mut pubkey = [0u8; SIGNING_KEY_SIZE]; - - let result = unsafe { - ffi::get_ecc_signing_pubkey( - self.eid, - &mut retval, - pubkey.as_mut_ptr(), - pubkey.len() as u32, - ) - }; - - ensure!(result == sgx_status_t::SGX_SUCCESS, Error::Sgx(result)); - ensure!(retval == sgx_status_t::SGX_SUCCESS, Error::Sgx(retval)); - - Ok(ed25519::Public::from_raw(pubkey)) - } - - fn get_bitcoin_wallet_pair(&self) -> EnclaveResult { - let mut retval = sgx_status_t::SGX_SUCCESS; - let mut private_key = [0u8; 32]; - - let result = unsafe { - ffi::get_bitcoin_wallet_pair( - self.eid, - &mut retval, - private_key.as_mut_ptr(), - private_key.len() as u32, - ) - }; - - ensure!(result == sgx_status_t::SGX_SUCCESS, Error::Sgx(result)); - ensure!(retval == sgx_status_t::SGX_SUCCESS, Error::Sgx(retval)); - - schnorr::Pair::from_bytes(&private_key) - .map_err(|e| Error::Other(format!("{:?}", e).into())) - } - - fn get_ethereum_wallet_pair(&self) -> EnclaveResult { - let mut retval = sgx_status_t::SGX_SUCCESS; - let mut private_key = [0u8; 32]; - - let result = unsafe { - ffi::get_ethereum_wallet_pair( - self.eid, - &mut retval, - private_key.as_mut_ptr(), - private_key.len() as u32, - ) - }; - - ensure!(result == sgx_status_t::SGX_SUCCESS, Error::Sgx(result)); - ensure!(retval == sgx_status_t::SGX_SUCCESS, Error::Sgx(retval)); - - ecdsa::Pair::from_bytes(&private_key) - .map_err(|e| Error::Other(format!("{:?}", e).into())) - } - - fn get_ton_wallet_pair(&self) -> EnclaveResult { - let mut retval = sgx_status_t::SGX_SUCCESS; - let mut private_key = [0u8; 32]; - - let result = unsafe { - ffi::get_ton_wallet_pair( - self.eid, - &mut retval, - private_key.as_mut_ptr(), - private_key.len() as u32, - ) - }; - - ensure!(result == sgx_status_t::SGX_SUCCESS, Error::Sgx(result)); - ensure!(retval == sgx_status_t::SGX_SUCCESS, Error::Sgx(retval)); - - Ok(ed25519::Pair::from_seed(&private_key)) - } - - fn get_fingerprint(&self) -> EnclaveResult { - let mut retval = sgx_status_t::SGX_SUCCESS; - let mut mr_enclave = [0u8; MR_ENCLAVE_SIZE]; - - let result = unsafe { - ffi::get_mrenclave( - self.eid, - &mut retval, - mr_enclave.as_mut_ptr(), - mr_enclave.len() as u32, - ) - }; - - ensure!(result == sgx_status_t::SGX_SUCCESS, Error::Sgx(result)); - ensure!(retval == sgx_status_t::SGX_SUCCESS, Error::Sgx(retval)); - - Ok(mr_enclave.into()) - } - - fn migrate_shard(&self, new_shard: Vec) -> EnclaveResult<()> { - let mut retval = sgx_status_t::SGX_SUCCESS; - - let result = unsafe { - ffi::migrate_shard( - self.eid, - &mut retval, - new_shard.as_ptr(), - new_shard.len() as u32, - ) - }; - - ensure!(result == sgx_status_t::SGX_SUCCESS, Error::Sgx(result)); - ensure!(retval == sgx_status_t::SGX_SUCCESS, Error::Sgx(retval)); - - Ok(()) - } - - fn publish_wallets(&self) -> EnclaveResult<()> { - let mut retval = sgx_status_t::SGX_SUCCESS; - - let result = unsafe { ffi::publish_wallets(self.eid, &mut retval) }; - - ensure!(result == sgx_status_t::SGX_SUCCESS, Error::Sgx(result)); - ensure!(retval == sgx_status_t::SGX_SUCCESS, Error::Sgx(retval)); - - Ok(()) - } - - fn finish_enclave_init(&self) -> EnclaveResult<()> { - let mut retval = sgx_status_t::SGX_SUCCESS; - - let result = unsafe { ffi::finish_enclave_init(self.eid, &mut retval) }; - - ensure!(result == sgx_status_t::SGX_SUCCESS, Error::Sgx(result)); - ensure!(retval == sgx_status_t::SGX_SUCCESS, Error::Sgx(retval)); - - Ok(()) - } - - fn init_wallets(&self, base_dir: &str) -> EnclaveResult<()> { - let mut retval = sgx_status_t::SGX_SUCCESS; - - let encoded_base_dir = base_dir.encode(); - - let result = unsafe { - ffi::init_wallets( - self.eid, - &mut retval, - encoded_base_dir.as_ptr(), - encoded_base_dir.len() as u32, - ) - }; - - ensure!(result == sgx_status_t::SGX_SUCCESS, Error::Sgx(result)); - ensure!(retval == sgx_status_t::SGX_SUCCESS, Error::Sgx(retval)); - - Ok(()) - } - } - - fn init_parentchain_components_ffi( - enclave_id: sgx_enclave_id_t, - params: Vec, - ) -> EnclaveResult> { - let mut retval = sgx_status_t::SGX_SUCCESS; - - let latest_header_size = HEADER_MAX_SIZE; - let mut latest_header = vec![0u8; latest_header_size]; - - let result = unsafe { - ffi::init_parentchain_components( - enclave_id, - &mut retval, - params.as_ptr(), - params.len(), - latest_header.as_mut_ptr(), - latest_header.len(), - ) - }; - - ensure!(result == sgx_status_t::SGX_SUCCESS, Error::Sgx(result)); - ensure!(retval == sgx_status_t::SGX_SUCCESS, Error::Sgx(retval)); - - Ok(latest_header) - } -} diff --git a/tee-worker/bitacross/core-primitives/enclave-api/src/enclave_test.rs b/tee-worker/bitacross/core-primitives/enclave-api/src/enclave_test.rs deleted file mode 100644 index aaf3a8e97d..0000000000 --- a/tee-worker/bitacross/core-primitives/enclave-api/src/enclave_test.rs +++ /dev/null @@ -1,48 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - Copyright (C) 2017-2019 Baidu, Inc. All Rights Reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use crate::EnclaveResult; - -pub trait EnclaveTest: Send + Sync + 'static { - fn test_main_entrance(&self) -> EnclaveResult<()>; -} - -#[cfg(feature = "implement-ffi")] -mod impl_ffi { - use super::EnclaveTest; - use crate::{error::Error, Enclave, EnclaveResult}; - use frame_support::ensure; - use itp_enclave_api_ffi as ffi; - use log::*; - use sgx_types::sgx_status_t; - - impl EnclaveTest for Enclave { - fn test_main_entrance(&self) -> EnclaveResult<()> { - let mut retval = sgx_status_t::SGX_SUCCESS; - - let result = unsafe { ffi::test_main_entrance(self.eid, &mut retval) }; - - ensure!(result == sgx_status_t::SGX_SUCCESS, Error::Sgx(result)); - ensure!(retval == sgx_status_t::SGX_SUCCESS, Error::Sgx(retval)); - - debug!("[+] successfully executed enclave test main"); - - Ok(()) - } - } -} diff --git a/tee-worker/bitacross/core-primitives/enclave-api/src/error.rs b/tee-worker/bitacross/core-primitives/enclave-api/src/error.rs deleted file mode 100644 index d510c56db4..0000000000 --- a/tee-worker/bitacross/core-primitives/enclave-api/src/error.rs +++ /dev/null @@ -1,14 +0,0 @@ -use codec::Error as CodecError; -use sgx_types::{sgx_quote3_error_t, sgx_status_t}; - -#[derive(Debug, thiserror::Error)] -pub enum Error { - #[error("{0}")] - Codec(#[from] CodecError), - #[error("Enclave Error: {0}")] - Sgx(sgx_status_t), - #[error("Enclave Quote Error: {0}")] - SgxQuote(sgx_quote3_error_t), - #[error("Error, other: {0}")] - Other(Box), -} diff --git a/tee-worker/bitacross/core-primitives/enclave-api/src/lib.rs b/tee-worker/bitacross/core-primitives/enclave-api/src/lib.rs deleted file mode 100644 index 131f4e9b7a..0000000000 --- a/tee-worker/bitacross/core-primitives/enclave-api/src/lib.rs +++ /dev/null @@ -1,47 +0,0 @@ -//! Some definitions and traits that facilitate interaction with the enclave. -//! -//! This serves as a proof of concept on how we could design the interface between the worker and -//! the enclave. -//! -//! Design principle here should be to keep the traits as slim as possible - because then the -//! worker can also define slim interfaces with less demanding trait bounds. -//! -//! This can further be simplified once https://github.com/integritee-network/worker/issues/254 -//! is implemented. Then we can replace the several ffi:: and the boilerplate code -//! around it with a simple `fn ecall(call: CallEnum) -> Result`, which wraps one single -//! ffi function. - -use crate::error::Error; - -pub mod enclave_base; -pub mod enclave_test; -pub mod error; -pub mod remote_attestation; -pub mod sidechain; -pub mod utils; - -#[cfg(feature = "implement-ffi")] -pub use sgx_urts::SgxEnclave; - -#[cfg(feature = "implement-ffi")] -use sgx_types::sgx_enclave_id_t; - -pub type EnclaveResult = Result; - -#[cfg(feature = "implement-ffi")] -#[derive(Clone, Debug, Default)] -pub struct Enclave { - eid: sgx_enclave_id_t, - sgx_enclave: SgxEnclave, -} - -#[cfg(feature = "implement-ffi")] -impl Enclave { - pub fn new(sgx_enclave: SgxEnclave) -> Self { - Enclave { eid: sgx_enclave.geteid(), sgx_enclave } - } - - pub fn destroy(self) { - self.sgx_enclave.destroy() - } -} diff --git a/tee-worker/bitacross/core-primitives/enclave-api/src/remote_attestation.rs b/tee-worker/bitacross/core-primitives/enclave-api/src/remote_attestation.rs deleted file mode 100644 index 15691f7172..0000000000 --- a/tee-worker/bitacross/core-primitives/enclave-api/src/remote_attestation.rs +++ /dev/null @@ -1,870 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - Copyright (C) 2017-2019 Baidu, Inc. All Rights Reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use crate::EnclaveResult; -use itp_types::{Fmspc, ShardIdentifier}; -use sgx_types::*; - -/// Struct that unites all relevant data reported by the QVE -pub struct QveReport { - pub supplemental_data: Vec, - pub qve_report_info_return_value: sgx_ql_qe_report_info_t, - pub quote_verification_result: sgx_ql_qv_result_t, - pub collateral_expiration_status: u32, -} - -/// general remote attestation methods -pub trait RemoteAttestation { - fn generate_ias_ra_extrinsic(&self, w_url: &str, skip_ra: bool) -> EnclaveResult>; - - fn generate_dcap_ra_extrinsic(&self, w_url: &str, skip_ra: bool) -> EnclaveResult>; - fn generate_dcap_ra_extrinsic_from_quote( - &self, - url: String, - quote: &[u8], - ) -> EnclaveResult>; - fn generate_dcap_ra_quote(&self, skip_ra: bool) -> EnclaveResult>; - - fn generate_register_quoting_enclave_extrinsic(&self, fmspc: Fmspc) -> EnclaveResult>; - - fn generate_register_tcb_info_extrinsic(&self, fmspc: Fmspc) -> EnclaveResult>; - - fn dump_ias_ra_cert_to_disk(&self) -> EnclaveResult<()>; - - fn dump_dcap_ra_cert_to_disk(&self) -> EnclaveResult<()>; - - fn dump_dcap_collateral_to_disk(&self, fmspc: Fmspc) -> EnclaveResult<()>; - - fn set_ql_qe_enclave_paths(&self) -> EnclaveResult<()>; - - fn set_sgx_qpl_logging(&self) -> EnclaveResult<()>; - - fn qe_get_target_info(&self) -> EnclaveResult; - - fn qe_get_quote_size(&self) -> EnclaveResult; - - fn get_dcap_collateral(&self, fmspc: Fmspc) -> EnclaveResult<*const sgx_ql_qve_collateral_t>; -} - -/// call-backs that are made from inside the enclave (using o-call), to e-calls again inside the enclave -pub trait RemoteAttestationCallBacks { - fn init_quote(&self) -> EnclaveResult<(sgx_target_info_t, sgx_epid_group_id_t)>; - - fn calc_quote_size(&self, revocation_list: Vec) -> EnclaveResult; - - fn get_quote( - &self, - revocation_list: Vec, - report: sgx_report_t, - quote_type: sgx_quote_sign_type_t, - spid: sgx_spid_t, - quote_nonce: sgx_quote_nonce_t, - quote_length: u32, - ) -> EnclaveResult<(sgx_report_t, Vec)>; - - fn get_dcap_quote(&self, report: sgx_report_t, quote_size: u32) -> EnclaveResult>; - - fn get_qve_report_on_quote( - &self, - quote: Vec, - current_time: i64, - quote_collateral: &sgx_ql_qve_collateral_t, - qve_report_info: sgx_ql_qe_report_info_t, - supplemental_data_size: u32, - ) -> EnclaveResult; - - fn get_update_info( - &self, - platform_blob: sgx_platform_info_t, - enclave_trusted: i32, - ) -> EnclaveResult; -} - -/// TLS remote attestations methods -pub trait TlsRemoteAttestation { - fn run_state_provisioning_server( - &self, - socket_fd: c_int, - sign_type: sgx_quote_sign_type_t, - quoting_enclave_target_info: Option<&sgx_target_info_t>, - quote_size: Option<&u32>, - skip_ra: bool, - ) -> EnclaveResult<()>; - - fn request_state_provisioning( - &self, - socket_fd: c_int, - sign_type: sgx_quote_sign_type_t, - quoting_enclave_target_info: Option<&sgx_target_info_t>, - quote_size: Option<&u32>, - shard: &ShardIdentifier, - skip_ra: bool, - ) -> EnclaveResult<()>; -} - -#[cfg(feature = "implement-ffi")] -mod impl_ffi { - use super::{QveReport, RemoteAttestation, RemoteAttestationCallBacks, TlsRemoteAttestation}; - use crate::{error::Error, utils, Enclave, EnclaveResult}; - use codec::Encode; - use frame_support::ensure; - use itp_enclave_api_ffi as ffi; - use itp_settings::worker::EXTRINSIC_MAX_SIZE; - use itp_types::{Fmspc, ShardIdentifier}; - use log::*; - use sgx_types::*; - - const OS_SYSTEM_PATH: &str = "/usr/lib/x86_64-linux-gnu/"; - const C_STRING_ENDING: &str = "\0"; - const PCE_ENCLAVE: &str = "libsgx_pce.signed.so.1"; - const QE3_ENCLAVE: &str = "libsgx_qe3.signed.so.1"; - const ID_ENCLAVE: &str = "libsgx_id_enclave.signed.so.1"; - const LIBDCAP_QUOTEPROV: &str = "libdcap_quoteprov.so.1"; - const QVE_ENCLAVE: &str = "libsgx_qve.signed.so.1"; - - impl RemoteAttestation for Enclave { - fn generate_ias_ra_extrinsic(&self, w_url: &str, skip_ra: bool) -> EnclaveResult> { - let mut retval = sgx_status_t::SGX_SUCCESS; - - let mut unchecked_extrinsic: Vec = vec![0u8; EXTRINSIC_MAX_SIZE]; - let mut unchecked_extrinsic_size: u32 = 0; - - trace!("Generating ias_ra_extrinsic with URL: {}", w_url); - - let url = w_url.encode(); - - let result = unsafe { - ffi::generate_ias_ra_extrinsic( - self.eid, - &mut retval, - url.as_ptr(), - url.len() as u32, - unchecked_extrinsic.as_mut_ptr(), - unchecked_extrinsic.len() as u32, - &mut unchecked_extrinsic_size as *mut u32, - skip_ra.into(), - ) - }; - - ensure!(result == sgx_status_t::SGX_SUCCESS, Error::Sgx(result)); - ensure!(retval == sgx_status_t::SGX_SUCCESS, Error::Sgx(retval)); - ensure!( - (unchecked_extrinsic_size as usize) < unchecked_extrinsic.len(), - Error::Sgx(sgx_status_t::SGX_ERROR_INVALID_PARAMETER) - ); - Ok(Vec::from(&unchecked_extrinsic[..unchecked_extrinsic_size as usize])) - } - fn generate_dcap_ra_extrinsic_from_quote( - &self, - url: String, - quote: &[u8], - ) -> EnclaveResult> { - let mut retval = sgx_status_t::SGX_SUCCESS; - let mut unchecked_extrinsic: Vec = vec![0u8; EXTRINSIC_MAX_SIZE]; - let mut unchecked_extrinsic_size: u32 = 0; - let url = url.encode(); - - let result = unsafe { - ffi::generate_dcap_ra_extrinsic_from_quote( - self.eid, - &mut retval, - url.as_ptr(), - url.len() as u32, - quote.as_ptr(), - quote.len() as u32, - unchecked_extrinsic.as_mut_ptr(), - unchecked_extrinsic.len() as u32, - &mut unchecked_extrinsic_size as *mut u32, - ) - }; - - ensure!(result == sgx_status_t::SGX_SUCCESS, Error::Sgx(result)); - ensure!(retval == sgx_status_t::SGX_SUCCESS, Error::Sgx(retval)); - ensure!( - (unchecked_extrinsic_size as usize) < unchecked_extrinsic.len(), - Error::Sgx(sgx_status_t::SGX_ERROR_INVALID_PARAMETER) - ); - Ok(Vec::from(&unchecked_extrinsic[..unchecked_extrinsic_size as usize])) - } - - fn generate_dcap_ra_quote(&self, skip_ra: bool) -> EnclaveResult> { - let mut retval = sgx_status_t::SGX_SUCCESS; - let quoting_enclave_target_info = self.qe_get_target_info()?; - let quote_size = self.qe_get_quote_size()?; - - let mut dcap_quote_vec: Vec = vec![0; quote_size as usize]; - let (dcap_quote_p, dcap_quote_size) = - (dcap_quote_vec.as_mut_ptr(), dcap_quote_vec.len() as u32); - - let result = unsafe { - ffi::generate_dcap_ra_quote( - self.eid, - &mut retval, - skip_ra.into(), - "ing_enclave_target_info, - quote_size, - dcap_quote_p, - dcap_quote_size, - ) - }; - - ensure!(result == sgx_status_t::SGX_SUCCESS, Error::Sgx(result)); - ensure!(retval == sgx_status_t::SGX_SUCCESS, Error::Sgx(retval)); - - unsafe { - trace!("Generating DCAP RA Quote: {}", *dcap_quote_p); - } - - Ok(dcap_quote_vec) - } - - fn generate_dcap_ra_extrinsic(&self, w_url: &str, skip_ra: bool) -> EnclaveResult> { - let mut retval = sgx_status_t::SGX_SUCCESS; - - self.set_ql_qe_enclave_paths()?; - let quoting_enclave_target_info = if !skip_ra { - match self.qe_get_target_info() { - Ok(target_info) => Some(target_info), - Err(e) => return Err(e), - } - } else { - None - }; - let quote_size = if !skip_ra { - match self.qe_get_quote_size() { - Ok(quote_size) => Some(quote_size), - Err(e) => return Err(e), - } - } else { - None - }; - info!("Retrieved quote size of {:?}", quote_size); - - trace!("Generating dcap_ra_extrinsic with URL: {}", w_url); - - let mut unchecked_extrinsic: Vec = vec![0u8; EXTRINSIC_MAX_SIZE]; - let mut unchecked_extrinsic_size: u32 = 0; - let url = w_url.encode(); - - let result = unsafe { - ffi::generate_dcap_ra_extrinsic( - self.eid, - &mut retval, - url.as_ptr(), - url.len() as u32, - unchecked_extrinsic.as_mut_ptr(), - unchecked_extrinsic.len() as u32, - &mut unchecked_extrinsic_size as *mut u32, - skip_ra.into(), - quoting_enclave_target_info.as_ref(), - quote_size.as_ref(), - ) - }; - - ensure!(result == sgx_status_t::SGX_SUCCESS, Error::Sgx(result)); - ensure!(retval == sgx_status_t::SGX_SUCCESS, Error::Sgx(retval)); - ensure!( - (unchecked_extrinsic_size as usize) < unchecked_extrinsic.len(), - Error::Sgx(sgx_status_t::SGX_ERROR_INVALID_PARAMETER) - ); - Ok(Vec::from(&unchecked_extrinsic[..unchecked_extrinsic_size as usize])) - } - - fn generate_register_quoting_enclave_extrinsic( - &self, - fmspc: Fmspc, - ) -> EnclaveResult> { - let mut retval = sgx_status_t::SGX_SUCCESS; - let mut unchecked_extrinsic: Vec = vec![0u8; EXTRINSIC_MAX_SIZE]; - let mut unchecked_extrinsic_size: u32 = 0; - - trace!("Generating register quoting enclave"); - - let collateral_ptr = self.get_dcap_collateral(fmspc)?; - - let result = unsafe { - ffi::generate_register_quoting_enclave_extrinsic( - self.eid, - &mut retval, - collateral_ptr, - unchecked_extrinsic.as_mut_ptr(), - unchecked_extrinsic.len() as u32, - &mut unchecked_extrinsic_size as *mut u32, - ) - }; - let free_status = unsafe { sgx_ql_free_quote_verification_collateral(collateral_ptr) }; - ensure!(result == sgx_status_t::SGX_SUCCESS, Error::Sgx(result)); - ensure!(retval == sgx_status_t::SGX_SUCCESS, Error::Sgx(retval)); - ensure!( - free_status == sgx_quote3_error_t::SGX_QL_SUCCESS, - Error::SgxQuote(free_status) - ); - ensure!( - (unchecked_extrinsic_size as usize) < unchecked_extrinsic.len(), - Error::Sgx(sgx_status_t::SGX_ERROR_INVALID_PARAMETER) - ); - Ok(Vec::from(&unchecked_extrinsic[..unchecked_extrinsic_size as usize])) - } - - fn generate_register_tcb_info_extrinsic(&self, fmspc: Fmspc) -> EnclaveResult> { - let mut retval = sgx_status_t::SGX_SUCCESS; - let mut unchecked_extrinsic: Vec = vec![0u8; EXTRINSIC_MAX_SIZE]; - let mut unchecked_extrinsic_size: u32 = 0; - - trace!("Generating tcb_info registration"); - - let collateral_ptr = self.get_dcap_collateral(fmspc)?; - - let result = unsafe { - ffi::generate_register_tcb_info_extrinsic( - self.eid, - &mut retval, - collateral_ptr, - unchecked_extrinsic.as_mut_ptr(), - unchecked_extrinsic.len() as u32, - &mut unchecked_extrinsic_size as *mut u32, - ) - }; - let free_status = unsafe { sgx_ql_free_quote_verification_collateral(collateral_ptr) }; - ensure!(result == sgx_status_t::SGX_SUCCESS, Error::Sgx(result)); - ensure!(retval == sgx_status_t::SGX_SUCCESS, Error::Sgx(retval)); - ensure!( - free_status == sgx_quote3_error_t::SGX_QL_SUCCESS, - Error::SgxQuote(free_status) - ); - ensure!( - (unchecked_extrinsic_size as usize) < unchecked_extrinsic.len(), - Error::Sgx(sgx_status_t::SGX_ERROR_INVALID_PARAMETER) - ); - Ok(Vec::from(&unchecked_extrinsic[..unchecked_extrinsic_size as usize])) - } - - fn dump_ias_ra_cert_to_disk(&self) -> EnclaveResult<()> { - let mut retval = sgx_status_t::SGX_SUCCESS; - - let result = unsafe { ffi::dump_ias_ra_cert_to_disk(self.eid, &mut retval) }; - - ensure!(result == sgx_status_t::SGX_SUCCESS, Error::Sgx(result)); - ensure!(retval == sgx_status_t::SGX_SUCCESS, Error::Sgx(retval)); - - Ok(()) - } - - fn dump_dcap_ra_cert_to_disk(&self) -> EnclaveResult<()> { - let mut retval = sgx_status_t::SGX_SUCCESS; - - self.set_ql_qe_enclave_paths()?; - let quoting_enclave_target_info = self.qe_get_target_info()?; - let quote_size = self.qe_get_quote_size()?; - - let result = unsafe { - ffi::dump_dcap_ra_cert_to_disk( - self.eid, - &mut retval, - "ing_enclave_target_info, - quote_size, - ) - }; - - ensure!(result == sgx_status_t::SGX_SUCCESS, Error::Sgx(result)); - ensure!(retval == sgx_status_t::SGX_SUCCESS, Error::Sgx(retval)); - - Ok(()) - } - - fn set_ql_qe_enclave_paths(&self) -> EnclaveResult<()> { - set_ql_path(sgx_ql_path_type_t::SGX_QL_PCE_PATH, PCE_ENCLAVE)?; - set_ql_path(sgx_ql_path_type_t::SGX_QL_QE3_PATH, QE3_ENCLAVE)?; - set_ql_path(sgx_ql_path_type_t::SGX_QL_IDE_PATH, ID_ENCLAVE)?; - if set_ql_path(sgx_ql_path_type_t::SGX_QL_QPL_PATH, LIBDCAP_QUOTEPROV).is_err() { - // Ignore the error, because user may want to get cert type=3 quote. - warn!("Cannot set QPL directory, you may get ECDSA quote with `Encrypted PPID` cert type.\n"); - }; - set_qv_path(sgx_qv_path_type_t::SGX_QV_QVE_PATH, QVE_ENCLAVE)?; - - Ok(()) - } - - fn set_sgx_qpl_logging(&self) -> EnclaveResult<()> { - let log_level = sgx_ql_log_level_t::SGX_QL_LOG_INFO; - let res = unsafe { sgx_ql_set_logging_callback(forward_qpl_log, log_level) }; - if res == sgx_quote3_error_t::SGX_QL_SUCCESS { - Ok(()) - } else { - error!("Setting logging function failed with: {:?}", res); - Err(Error::SgxQuote(res)) - } - } - - fn qe_get_target_info(&self) -> EnclaveResult { - let mut quoting_enclave_target_info: sgx_target_info_t = sgx_target_info_t::default(); - let qe3_ret = - unsafe { sgx_qe_get_target_info(&mut quoting_enclave_target_info as *mut _) }; - ensure!(qe3_ret == sgx_quote3_error_t::SGX_QL_SUCCESS, Error::SgxQuote(qe3_ret)); - - Ok(quoting_enclave_target_info) - } - - fn qe_get_quote_size(&self) -> EnclaveResult { - let mut quote_size: u32 = 0; - let qe3_ret = unsafe { sgx_qe_get_quote_size(&mut quote_size as *mut _) }; - ensure!(qe3_ret == sgx_quote3_error_t::SGX_QL_SUCCESS, Error::SgxQuote(qe3_ret)); - - Ok(quote_size) - } - - fn dump_dcap_collateral_to_disk(&self, fmspc: Fmspc) -> EnclaveResult<()> { - let mut retval = sgx_status_t::SGX_SUCCESS; - let collateral_ptr = self.get_dcap_collateral(fmspc)?; - let result = - unsafe { ffi::dump_dcap_collateral_to_disk(self.eid, &mut retval, collateral_ptr) }; - let free_status = unsafe { sgx_ql_free_quote_verification_collateral(collateral_ptr) }; - ensure!(result == sgx_status_t::SGX_SUCCESS, Error::Sgx(result)); - ensure!(retval == sgx_status_t::SGX_SUCCESS, Error::Sgx(result)); - ensure!( - free_status == sgx_quote3_error_t::SGX_QL_SUCCESS, - Error::SgxQuote(free_status) - ); - Ok(()) - } - - fn get_dcap_collateral( - &self, - fmspc: Fmspc, - ) -> EnclaveResult<*const sgx_ql_qve_collateral_t> { - let pck_ra = b"processor\x00"; - - // SAFETY: Just get a nullptr for the FFI to overwrite later - let mut collateral_ptr: *mut sgx_ql_qve_collateral_t = unsafe { std::mem::zeroed() }; - - let collateral_ptr_ptr: *mut *mut sgx_ql_qve_collateral_t = &mut collateral_ptr; - // SAFETY: All parameters are properly initialized so the FFI call should be fine - let sgx_status = unsafe { - sgx_ql_get_quote_verification_collateral( - fmspc.as_ptr(), - fmspc.len() as uint16_t, //fmspc len is fixed in the function signature - pck_ra.as_ptr() as _, - collateral_ptr_ptr, - ) - }; - - trace!("FMSPC: {:?}", hex::encode(fmspc)); - - if collateral_ptr.is_null() { - error!("PCK quote collateral data is null, sgx_status is: {}", sgx_status); - return Err(Error::SgxQuote(sgx_status)) - } - - trace!("collateral:"); - // SAFETY: the previous block checks for `collateral_ptr` being null. - // SAFETY: the fields should be nul terminated C strings. - unsafe { - let collateral = &*collateral_ptr; - trace!( - "version: {}\n, \ - tee_type: {}\n, \ - pck_crl_issuer_chain: {:?}\n, \ - pck_crl_issuer_chain_size: {}\n, \ - root_ca_crl: {:?}\n, \ - root_ca_crl_size: {}\n, \ - pck_crl: {:?}\n, \ - pck_crl_size: {}\n, \ - tcb_info_issuer_chain: {:?}\n, \ - tcb_info_issuer_chain_size: {}\n, \ - tcb_info: {}\n, \ - tcb_info_size: {}\n, \ - qe_identity_issuer_chain: {:?}\n, \ - qe_identity_issuer_chain_size: {}\n, \ - qe_identity: {}\n, \ - qe_identity_size: {}\n", - collateral.version, - collateral.tee_type, - std::ffi::CStr::from_ptr(collateral.pck_crl_issuer_chain).to_string_lossy(), - collateral.pck_crl_issuer_chain_size, - std::ffi::CStr::from_ptr(collateral.root_ca_crl).to_string_lossy(), - collateral.root_ca_crl_size, - std::ffi::CStr::from_ptr(collateral.pck_crl).to_string_lossy(), - collateral.pck_crl_size, - std::ffi::CStr::from_ptr(collateral.tcb_info_issuer_chain).to_string_lossy(), - collateral.tcb_info_issuer_chain_size, - std::ffi::CStr::from_ptr(collateral.tcb_info).to_string_lossy(), - collateral.tcb_info_size, - std::ffi::CStr::from_ptr(collateral.qe_identity_issuer_chain).to_string_lossy(), - collateral.qe_identity_issuer_chain_size, - std::ffi::CStr::from_ptr(collateral.qe_identity).to_string_lossy(), - collateral.qe_identity_size, - ); - }; - - ensure!(sgx_status == sgx_quote3_error_t::SGX_QL_SUCCESS, Error::SgxQuote(sgx_status)); - Ok(collateral_ptr) - } - } - - #[cfg(feature = "implement-ffi")] - impl RemoteAttestationCallBacks for Enclave { - fn init_quote(&self) -> EnclaveResult<(sgx_target_info_t, sgx_epid_group_id_t)> { - let mut ti: sgx_target_info_t = sgx_target_info_t::default(); - let mut eg: sgx_epid_group_id_t = sgx_epid_group_id_t::default(); - - let result = unsafe { - sgx_init_quote( - &mut ti as *mut sgx_target_info_t, - &mut eg as *mut sgx_epid_group_id_t, - ) - }; - - ensure!(result == sgx_status_t::SGX_SUCCESS, Error::Sgx(result)); - - Ok((ti, eg)) - } - - fn calc_quote_size(&self, revocation_list: Vec) -> EnclaveResult { - let mut real_quote_len: u32 = 0; - - let (p_sig_rl, sig_rl_size) = utils::vec_to_c_pointer_with_len(revocation_list); - - let result = unsafe { - sgx_calc_quote_size(p_sig_rl, sig_rl_size, &mut real_quote_len as *mut u32) - }; - - ensure!(result == sgx_status_t::SGX_SUCCESS, Error::Sgx(result)); - - Ok(real_quote_len) - } - - fn get_quote( - &self, - revocation_list: Vec, - report: sgx_report_t, - quote_type: sgx_quote_sign_type_t, - spid: sgx_spid_t, - quote_nonce: sgx_quote_nonce_t, - quote_length: u32, - ) -> EnclaveResult<(sgx_report_t, Vec)> { - let (p_sig_rl, sig_rl_size) = utils::vec_to_c_pointer_with_len(revocation_list); - let p_report = &report as *const sgx_report_t; - let p_spid = &spid as *const sgx_spid_t; - let p_nonce = "e_nonce as *const sgx_quote_nonce_t; - - let mut qe_report = sgx_report_t::default(); - let p_qe_report = &mut qe_report as *mut sgx_report_t; - - let mut return_quote_buf = vec![0u8; quote_length as usize]; - let p_quote = return_quote_buf.as_mut_ptr(); - - let ret = unsafe { - sgx_get_quote( - p_report, - quote_type, - p_spid, - p_nonce, - p_sig_rl, - sig_rl_size, - p_qe_report, - p_quote as *mut sgx_quote_t, - quote_length, - ) - }; - - ensure!(ret == sgx_status_t::SGX_SUCCESS, Error::Sgx(ret)); - - Ok((qe_report, return_quote_buf)) - } - - fn get_dcap_quote(&self, report: sgx_report_t, quote_size: u32) -> EnclaveResult> { - let mut quote_vec: Vec = vec![0; quote_size as usize]; - let qe3_ret = - unsafe { sgx_qe_get_quote(&report, quote_size, quote_vec.as_mut_ptr() as _) }; - - ensure!(qe3_ret == sgx_quote3_error_t::SGX_QL_SUCCESS, Error::SgxQuote(qe3_ret)); - - Ok(quote_vec) - } - - fn get_qve_report_on_quote( - &self, - quote: Vec, - current_time: i64, - quote_collateral: &sgx_ql_qve_collateral_t, - qve_report_info: sgx_ql_qe_report_info_t, - supplemental_data_size: u32, - ) -> EnclaveResult { - let mut collateral_expiration_status = 1u32; - let mut quote_verification_result = sgx_ql_qv_result_t::SGX_QL_QV_RESULT_OK; - let mut supplemental_data: Vec = vec![0; supplemental_data_size as usize]; - let mut qve_report_info_return_value: sgx_ql_qe_report_info_t = qve_report_info; - - // Set QvE (Quote verification Enclave) loading policy. - let dcap_ret = unsafe { - sgx_qv_set_enclave_load_policy(sgx_ql_request_policy_t::SGX_QL_EPHEMERAL) - }; - - if dcap_ret != sgx_quote3_error_t::SGX_QL_SUCCESS { - error!("sgx_qv_set_enclave_load_policy failed: {:#04x}", dcap_ret as u32); - return Err(Error::SgxQuote(dcap_ret)) - } - - // Retrieve supplemental data size from QvE. - let mut qve_supplemental_data_size = 0u32; - let dcap_ret = - unsafe { sgx_qv_get_quote_supplemental_data_size(&mut qve_supplemental_data_size) }; - - if dcap_ret != sgx_quote3_error_t::SGX_QL_SUCCESS { - error!("sgx_qv_get_quote_supplemental_data_size failed: {:?}", dcap_ret); - return Err(Error::SgxQuote(dcap_ret)) - } - if qve_supplemental_data_size != supplemental_data_size { - warn!("Quote supplemental data size is different between DCAP QVL and QvE, please make sure you installed DCAP QVL and QvE from same release."); - return Err(Error::Sgx(sgx_status_t::SGX_ERROR_INVALID_PARAMETER)) - } - - // Check if a collateral has been given, or if it's a simple zero assignment. - // If it's zero, let the pointer point to null. The collateral will then be retrieved - // directly by the QvE in `sgx_qv_verify_quote`. - let p_quote_collateral: *const sgx_ql_qve_collateral_t = - if quote_collateral.version == 0 { - std::ptr::null() - } else { - quote_collateral as *const sgx_ql_qve_collateral_t - }; - - // Call the QvE for quote verification - // here you can choose 'trusted' or 'untrusted' quote verification by specifying parameter '&qve_report_info' - // if '&qve_report_info' is NOT NULL, this API will call Intel QvE to verify quote - // if '&qve_report_info' is NULL, this API will call 'untrusted quote verify lib' to verify quote, - // this mode doesn't rely on SGX capable system, but the results can not be cryptographically authenticated - let dcap_ret = unsafe { - sgx_qv_verify_quote( - quote.as_ptr(), - quote.len() as u32, - p_quote_collateral, - current_time, - &mut collateral_expiration_status as *mut u32, - &mut quote_verification_result as *mut sgx_ql_qv_result_t, - &mut qve_report_info_return_value as *mut sgx_ql_qe_report_info_t, - supplemental_data_size, - supplemental_data.as_mut_ptr(), - ) - }; - - if sgx_quote3_error_t::SGX_QL_SUCCESS != dcap_ret { - error!("sgx_qv_verify_quote failed: {:?}", dcap_ret); - error!("quote_verification_result: {:?}", quote_verification_result); - return Err(Error::SgxQuote(dcap_ret)) - } - - // Check and print verification result. - match quote_verification_result { - sgx_ql_qv_result_t::SGX_QL_QV_RESULT_OK => { - // Check verification collateral expiration status. - // This value should be considered in your own attestation/verification policy. - if 0u32 == collateral_expiration_status { - info!("QvE verification completed successfully."); - } else { - warn!("QvE verification completed, but collateral is out of date based on 'expiration_check_date' you provided."); - } - }, - sgx_ql_qv_result_t::SGX_QL_QV_RESULT_CONFIG_NEEDED - | sgx_ql_qv_result_t::SGX_QL_QV_RESULT_OUT_OF_DATE - | sgx_ql_qv_result_t::SGX_QL_QV_RESULT_OUT_OF_DATE_CONFIG_NEEDED - | sgx_ql_qv_result_t::SGX_QL_QV_RESULT_SW_HARDENING_NEEDED - | sgx_ql_qv_result_t::SGX_QL_QV_RESULT_CONFIG_AND_SW_HARDENING_NEEDED => { - warn!( - "QvE verification completed with Non-terminal result: {:?}", - quote_verification_result - ); - }, - _ => { - error!( - "QvE verification completed with Terminal result: {:?}", - quote_verification_result - ); - }, - } - - // Check supplemental data. - if supplemental_data_size > 0 { - // For now we simply print it, no checks done. - let p_supplemental_data: *const sgx_ql_qv_supplemental_t = - supplemental_data.as_ptr() as *const sgx_ql_qv_supplemental_t; - let qv_supplemental_data: sgx_ql_qv_supplemental_t = - unsafe { *p_supplemental_data }; - info!( - "QvE verification: Supplemental data version: {}", - qv_supplemental_data.version - ); - } - - Ok(QveReport { - collateral_expiration_status, - quote_verification_result, - qve_report_info_return_value, - supplemental_data, - }) - } - - fn get_update_info( - &self, - platform_blob: sgx_platform_info_t, - enclave_trusted: i32, - ) -> EnclaveResult { - let mut update_info: sgx_update_info_bit_t = sgx_update_info_bit_t::default(); - - let result = unsafe { - sgx_report_attestation_status( - &platform_blob as *const sgx_platform_info_t, - enclave_trusted, - &mut update_info as *mut sgx_update_info_bit_t, - ) - }; - - ensure!(result == sgx_status_t::SGX_SUCCESS, Error::Sgx(result)); - - Ok(update_info) - } - } - - #[cfg(feature = "implement-ffi")] - impl TlsRemoteAttestation for Enclave { - fn run_state_provisioning_server( - &self, - socket_fd: c_int, - sign_type: sgx_quote_sign_type_t, - quoting_enclave_target_info: Option<&sgx_target_info_t>, - quote_size: Option<&u32>, - skip_ra: bool, - ) -> EnclaveResult<()> { - let mut retval = sgx_status_t::SGX_SUCCESS; - - let result = unsafe { - ffi::run_state_provisioning_server( - self.eid, - &mut retval, - socket_fd, - sign_type, - quoting_enclave_target_info, - quote_size, - skip_ra.into(), - ) - }; - - ensure!(result == sgx_status_t::SGX_SUCCESS, Error::Sgx(result)); - ensure!(retval == sgx_status_t::SGX_SUCCESS, Error::Sgx(retval)); - - Ok(()) - } - - fn request_state_provisioning( - &self, - socket_fd: c_int, - sign_type: sgx_quote_sign_type_t, - quoting_enclave_target_info: Option<&sgx_target_info_t>, - quote_size: Option<&u32>, - shard: &ShardIdentifier, - skip_ra: bool, - ) -> EnclaveResult<()> { - let mut retval = sgx_status_t::SGX_SUCCESS; - - let encoded_shard = shard.encode(); - - let result = unsafe { - ffi::request_state_provisioning( - self.eid, - &mut retval, - socket_fd, - sign_type, - quoting_enclave_target_info, - quote_size, - encoded_shard.as_ptr(), - encoded_shard.len() as u32, - skip_ra.into(), - ) - }; - - ensure!(result == sgx_status_t::SGX_SUCCESS, Error::Sgx(result)); - ensure!(retval == sgx_status_t::SGX_SUCCESS, Error::Sgx(retval)); - - Ok(()) - } - } - - fn create_system_path(file_name: &str) -> String { - trace!("create_system_path:: file_name={}", &file_name); - let default_path = format!("{}{}", OS_SYSTEM_PATH, file_name); - - let full_path = find_library_by_name(file_name).unwrap_or(default_path); - - let c_terminated_path = format!("{}{}", full_path, C_STRING_ENDING); - trace!("create_system_path:: created path={}", &c_terminated_path); - c_terminated_path - } - - fn find_library_by_name(lib_name: &str) -> Option { - use std::process::Command; - // ldconfig -p | grep libsgx_pce_logic.so.1 - - let ldconfig_output = Command::new("ldconfig").args(["-p"]).output().ok()?; - let possible_path = String::from_utf8(ldconfig_output.stdout) - .ok()? - .lines() - .filter(|line| line.contains(lib_name)) - .map(|lib_name_and_path| { - lib_name_and_path - .rsplit_once("=>") - .map(|(_, lib_path)| lib_path.trim().to_owned()) - }) - .next()?; - - possible_path - } - - fn set_ql_path(path_type: sgx_ql_path_type_t, path: &str) -> EnclaveResult<()> { - let ret_val = unsafe { sgx_ql_set_path(path_type, create_system_path(path).as_ptr() as _) }; - if ret_val != sgx_quote3_error_t::SGX_QL_SUCCESS { - error!("Could not set {:?}", path_type); - return Err(Error::SgxQuote(ret_val)) - } - Ok(()) - } - - fn set_qv_path(path_type: sgx_qv_path_type_t, path: &str) -> EnclaveResult<()> { - let ret_val = unsafe { sgx_qv_set_path(path_type, create_system_path(path).as_ptr() as _) }; - if ret_val != sgx_quote3_error_t::SGX_QL_SUCCESS { - error!("Could not set {:?}", path_type); - return Err(Error::SgxQuote(ret_val)) - } - Ok(()) - } - - #[allow(clippy::not_unsafe_ptr_arg_deref)] - /// Make sure that the `log_slice_ptr` points to a null terminated string. - // This function must not be marked as `unsafe`, because `sgx_ql_set_logging_callback` expects a safe (i.e. not `unsafe`) function. - pub extern "C" fn forward_qpl_log(log_level: sgx_ql_log_level_t, log_slice_ptr: *const c_char) { - if log_slice_ptr.is_null() { - error!("[QPL - ERROR], slice to print was NULL"); - return - } - // This is safe, as the previous block checks for `NULL` pointer. - let slice = unsafe { core::ffi::CStr::from_ptr(log_slice_ptr) }; - match log_level { - sgx_ql_log_level_t::SGX_QL_LOG_INFO => info!("[QPL - INFO], {:?}", slice), - sgx_ql_log_level_t::SGX_QL_LOG_ERROR => error!("[QPL - ERROR], {:?}", slice), - } - } -} diff --git a/tee-worker/bitacross/core-primitives/enclave-api/src/sidechain.rs b/tee-worker/bitacross/core-primitives/enclave-api/src/sidechain.rs deleted file mode 100644 index 9dee8e3bb4..0000000000 --- a/tee-worker/bitacross/core-primitives/enclave-api/src/sidechain.rs +++ /dev/null @@ -1,109 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - Copyright (C) 2017-2019 Baidu, Inc. All Rights Reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use crate::EnclaveResult; -use codec::Encode; -use itp_storage::StorageProof; -use itp_types::parentchain::ParentchainId; -use sp_runtime::generic::SignedBlock; - -/// trait for handling blocks on the side chain -pub trait Sidechain: Send + Sync + 'static { - /// Sync parentchain blocks and events. Execute pending tops - /// and events proof in the enclave. - fn sync_parentchain( - &self, - blocks: &[SignedBlock], - events: &[Vec], - events_proofs: &[StorageProof], - parentchain_id: &ParentchainId, - is_syncing: bool, - ) -> EnclaveResult<()>; - - // litentry - /// Ignore the parentchain block import validation until the given block number - /// TODO: use the generic Header::Number trait - fn ignore_parentchain_block_import_validation_until(&self, until: u32) -> EnclaveResult<()>; -} - -#[cfg(feature = "implement-ffi")] -mod impl_ffi { - use super::Sidechain; - use crate::{error::Error, Enclave, EnclaveResult}; - use codec::Encode; - use frame_support::ensure; - use itp_enclave_api_ffi as ffi; - use itp_storage::StorageProof; - use itp_types::parentchain::ParentchainId; - use sgx_types::sgx_status_t; - use sp_runtime::generic::SignedBlock; - - impl Sidechain for Enclave { - fn sync_parentchain( - &self, - blocks: &[SignedBlock], - events: &[Vec], - events_proofs: &[StorageProof], - parentchain_id: &ParentchainId, - is_syncing: bool, - ) -> EnclaveResult<()> { - let mut retval = sgx_status_t::SGX_SUCCESS; - let blocks_enc = blocks.encode(); - let events_enc = events.encode(); - let events_proofs_enc = events_proofs.encode(); - let parentchain_id_enc = parentchain_id.encode(); - - let result = unsafe { - ffi::sync_parentchain( - self.eid, - &mut retval, - blocks_enc.as_ptr(), - blocks_enc.len(), - events_enc.as_ptr(), - events_enc.len(), - events_proofs_enc.as_ptr(), - events_proofs_enc.len(), - parentchain_id_enc.as_ptr(), - parentchain_id_enc.len() as u32, - is_syncing.into(), - ) - }; - - ensure!(result == sgx_status_t::SGX_SUCCESS, Error::Sgx(result)); - ensure!(retval == sgx_status_t::SGX_SUCCESS, Error::Sgx(retval)); - - Ok(()) - } - - fn ignore_parentchain_block_import_validation_until( - &self, - until: u32, - ) -> EnclaveResult<()> { - let mut retval = sgx_status_t::SGX_SUCCESS; - - let result = unsafe { - ffi::ignore_parentchain_block_import_validation_until(self.eid, &mut retval, &until) - }; - - ensure!(result == sgx_status_t::SGX_SUCCESS, Error::Sgx(result)); - ensure!(retval == sgx_status_t::SGX_SUCCESS, Error::Sgx(retval)); - - Ok(()) - } - } -} diff --git a/tee-worker/bitacross/core-primitives/enclave-api/src/utils.rs b/tee-worker/bitacross/core-primitives/enclave-api/src/utils.rs deleted file mode 100644 index e36764f7ac..0000000000 --- a/tee-worker/bitacross/core-primitives/enclave-api/src/utils.rs +++ /dev/null @@ -1,27 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - Copyright (C) 2017-2019 Baidu, Inc. All Rights Reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use std::ptr; - -pub fn vec_to_c_pointer_with_len(input: Vec) -> (*const A, u32) { - if input.is_empty() { - (ptr::null(), 0) - } else { - (input.as_ptr(), input.len() as u32) - } -} diff --git a/tee-worker/bitacross/core-primitives/stf-executor/Cargo.toml b/tee-worker/bitacross/core-primitives/stf-executor/Cargo.toml deleted file mode 100644 index 06d777cebf..0000000000 --- a/tee-worker/bitacross/core-primitives/stf-executor/Cargo.toml +++ /dev/null @@ -1,81 +0,0 @@ -[package] -name = "bc-itp-stf-executor" -version = "0.1.0" -authors = ['Trust Computing GmbH ', 'Integritee AG '] -edition = "2021" - -[dependencies] -hex = { workspace = true } - -sgx_tstd = { workspace = true, features = ["untrusted_time"], optional = true } -sgx_types = { workspace = true } - -itp-enclave-metrics = { workspace = true } -itp-node-api = { workspace = true } -itp-ocall-api = { workspace = true } -itp-sgx-crypto = { workspace = true } -itp-sgx-externalities = { workspace = true } -itp-stf-interface = { workspace = true } -itp-stf-primitives = { workspace = true } -itp-stf-state-handler = { workspace = true } -itp-stf-state-observer = { workspace = true } -itp-time-utils = { workspace = true } -itp-top-pool-author = { package = "bc-itp-top-pool-author", path = "../top-pool-author", default-features = false } -itp-types = { workspace = true } - -thiserror = { workspace = true, optional = true } -thiserror_sgx = { workspace = true, optional = true } - -codec = { package = "parity-scale-codec", workspace = true } -log = { workspace = true } - -# substrate dependencies -sp-core = { workspace = true, features = ["full_crypto"] } -sp-runtime = { workspace = true } - -# dev dependencies -itc-parentchain-test = { workspace = true, optional = true } -itp-test = { workspace = true, optional = true } - -[dev-dependencies] -itp-stf-state-observer = { workspace = true, features = ["std", "mocks"] } -itp-stf-interface = { workspace = true, features = ["std", "mocks"] } -itp-top-pool = { package = "bc-itp-top-pool", path = "../top-pool", features = ["std", "mocks"] } -itp-test = { workspace = true, features = ["std"] } - -[features] -default = ["std"] -std = [ - "itp-node-api/std", - "itp-ocall-api/std", - "itp-sgx-crypto/std", - "itp-sgx-externalities/std", - "itp-stf-interface/std", - "itp-stf-state-handler/std", - "itp-stf-state-observer/std", - "itp-top-pool-author/std", - "itp-types/std", - "itp-time-utils/std", - "log/std", - "codec/std", - "sp-core/std", - "sp-runtime/std", - "thiserror", -] -sgx = [ - "sgx_tstd", - "itp-node-api/sgx", - "itp-sgx-crypto/sgx", - "itp-sgx-externalities/sgx", - "itp-stf-state-handler/sgx", - "itp-stf-state-observer/sgx", - "itp-top-pool-author/sgx", - "itp-time-utils/sgx", - "thiserror_sgx", -] -test = [ - "itc-parentchain-test", - "itp-node-api/mocks", - "itp-test", -] -mocks = [] diff --git a/tee-worker/bitacross/core-primitives/stf-executor/src/enclave_signer.rs b/tee-worker/bitacross/core-primitives/stf-executor/src/enclave_signer.rs deleted file mode 100644 index a4d4fd8c01..0000000000 --- a/tee-worker/bitacross/core-primitives/stf-executor/src/enclave_signer.rs +++ /dev/null @@ -1,151 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use crate::{ - error::{Error, Result}, - traits::StfEnclaveSigning, - H256, -}; -use codec::{Decode, Encode}; -use core::{fmt::Debug, marker::PhantomData}; -use itp_ocall_api::EnclaveAttestationOCallApi; -use itp_sgx_crypto::{ed25519_derivation::DeriveEd25519, key_repository::AccessKey}; -use itp_sgx_externalities::SgxExternalitiesTrait; -use itp_stf_interface::system_pallet::SystemPalletAccountInterface; -use itp_stf_primitives::{ - traits::TrustedCallSigning, - types::{AccountId, KeyPair}, -}; -use itp_stf_state_observer::traits::ObserveState; -use itp_top_pool_author::traits::AuthorApi; -use itp_types::{Index, MrEnclave, ShardIdentifier}; -use sp_core::{ed25519::Pair as Ed25519Pair, Pair}; -use std::{boxed::Box, sync::Arc, vec::Vec}; - -pub struct StfEnclaveSigner< - OCallApi, - StateObserver, - ShieldingKeyRepository, - Stf, - TopPoolAuthor, - TCS, - G, -> { - state_observer: Arc, - pub ocall_api: Arc, - shielding_key_repo: Arc, - top_pool_author: Arc, - _phantom: PhantomData<(Stf, TCS, G)>, -} - -impl - StfEnclaveSigner -where - OCallApi: EnclaveAttestationOCallApi, - StateObserver: ObserveState, - StateObserver::StateType: SgxExternalitiesTrait, - ShieldingKeyRepository: AccessKey, - ::KeyType: DeriveEd25519, - Stf: SystemPalletAccountInterface, - Stf::Index: Into, - TopPoolAuthor: AuthorApi + Send + Sync + 'static, - TCS: PartialEq + Encode + Decode + Debug + Send + Sync, - G: PartialEq + Encode + Decode + Debug + Send + Sync, -{ - pub fn new( - state_observer: Arc, - ocall_api: Arc, - shielding_key_repo: Arc, - top_pool_author: Arc, - ) -> Self { - Self { - state_observer, - ocall_api, - shielding_key_repo, - top_pool_author, - _phantom: Default::default(), - } - } - - fn get_enclave_account_nonce(&self, shard: &ShardIdentifier) -> Result { - let enclave_account = self.get_enclave_account()?; - let nonce = self - .state_observer - .observe_state(shard, move |state| Stf::get_account_nonce(state, &enclave_account))?; - - Ok(nonce) - } - - fn get_enclave_call_signing_key(&self) -> Result { - let shielding_key = self.shielding_key_repo.retrieve_key()?; - shielding_key.derive_ed25519().map_err(|e| e.into()) - } -} - -impl - StfEnclaveSigning - for StfEnclaveSigner -where - OCallApi: EnclaveAttestationOCallApi, - StateObserver: ObserveState, - StateObserver::StateType: SgxExternalitiesTrait, - ShieldingKeyRepository: AccessKey, - ::KeyType: DeriveEd25519, - Stf: SystemPalletAccountInterface, - Stf::Index: Into, - TopPoolAuthor: AuthorApi + Send + Sync + 'static, - TCS: PartialEq + Encode + Decode + Debug + Send + Sync, - G: PartialEq + Encode + Decode + Debug + Send + Sync, -{ - fn get_enclave_account(&self) -> Result { - self.get_enclave_call_signing_key().map(|key| key.public().into()) - } - - fn get_mrenclave(&self) -> Result { - Ok(self.ocall_api.get_mrenclave_of_self().map(|m| m.m)?) - } - - fn sign_call_with_self>( - &self, - trusted_call: &TC, - shard: &ShardIdentifier, - ) -> Result { - let mrenclave = self.get_mrenclave()?; - let enclave_account = self.get_enclave_account()?; - let enclave_call_signing_key = self.get_enclave_call_signing_key()?; - - let current_nonce = self.get_enclave_account_nonce(shard)?; - let pending_tx_count = self - .top_pool_author - .get_pending_trusted_calls_for(*shard, &enclave_account) - .len(); - let pending_tx_count = - Index::try_from(pending_tx_count).map_err(|e| Error::Other(e.into()))?; - let adjusted_nonce: Index = current_nonce.into() + pending_tx_count; - - Ok(trusted_call.sign( - &KeyPair::Ed25519(Box::new(enclave_call_signing_key)), - adjusted_nonce, - &mrenclave, - shard, - )) - } - - fn sign(&self, payload: &[u8]) -> Result> { - self.get_enclave_call_signing_key().map(|key| key.sign(payload).0.to_vec()) - } -} diff --git a/tee-worker/bitacross/core-primitives/stf-executor/src/error.rs b/tee-worker/bitacross/core-primitives/stf-executor/src/error.rs deleted file mode 100644 index ec46defdcd..0000000000 --- a/tee-worker/bitacross/core-primitives/stf-executor/src/error.rs +++ /dev/null @@ -1,88 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -#[cfg(all(not(feature = "std"), feature = "sgx"))] -use crate::sgx_reexport_prelude::*; - -use itp_stf_primitives::error::StfError; -use sgx_types::sgx_status_t; -use std::{boxed::Box, format}; - -pub type Result = core::result::Result; - -/// STF-Executor error -#[derive(Debug, thiserror::Error)] -pub enum Error { - #[error("Trusted operation has invalid signature")] - GetterIsNotAuthorized, - #[error("Invalid or unsupported trusted call type")] - InvalidTrustedCallType, - #[error("SGX error, status: {0}")] - Sgx(sgx_status_t), - #[error("State handling error: {0}")] - StateHandler(#[from] itp_stf_state_handler::error::Error), - #[error("State observer error: {0}")] - StateObserver(#[from] itp_stf_state_observer::error::Error), - #[error("Node metadata error: {0:?}")] - NodeMetadata(itp_node_api::metadata::Error), - #[error("Node metadata provider error: {0:?}")] - NodeMetadataProvider(#[from] itp_node_api::metadata::provider::Error), - #[error("STF error: {0}")] - Stf(StfError), - #[error("Ocall Api error: {0}")] - OcallApi(itp_ocall_api::Error), - #[error("Crypto error: {0}")] - Crypto(itp_sgx_crypto::error::Error), - #[error(transparent)] - Other(#[from] Box), -} - -impl From for Error { - fn from(sgx_status: sgx_status_t) -> Self { - Self::Sgx(sgx_status) - } -} - -impl From for Error { - fn from(e: codec::Error) -> Self { - Self::Other(format!("{:?}", e).into()) - } -} - -impl From for Error { - fn from(error: StfError) -> Self { - Self::Stf(error) - } -} - -impl From for Error { - fn from(error: itp_ocall_api::Error) -> Self { - Self::OcallApi(error) - } -} - -impl From for Error { - fn from(error: itp_sgx_crypto::error::Error) -> Self { - Self::Crypto(error) - } -} - -impl From for Error { - fn from(e: itp_node_api::metadata::Error) -> Self { - Self::NodeMetadata(e) - } -} diff --git a/tee-worker/bitacross/core-primitives/stf-executor/src/executor.rs b/tee-worker/bitacross/core-primitives/stf-executor/src/executor.rs deleted file mode 100644 index ffc6d92fce..0000000000 --- a/tee-worker/bitacross/core-primitives/stf-executor/src/executor.rs +++ /dev/null @@ -1,393 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use crate::{ - error::{Error, Result}, - traits::{StatePostProcessing, StateUpdateProposer, StfUpdateState}, - BatchExecutionResult, ExecutedOperation, -}; -use codec::{Decode, Encode}; -use itp_enclave_metrics::EnclaveMetric; -use itp_node_api::metadata::{provider::AccessNodeMetadata, NodeMetadataTrait}; -use itp_ocall_api::{EnclaveAttestationOCallApi, EnclaveMetricsOCallApi, EnclaveOnChainOCallApi}; -use itp_sgx_externalities::{SgxExternalitiesTrait, StateHash}; -use itp_stf_interface::{ - parentchain_pallet::ParentchainPalletInstancesInterface, - runtime_upgrade::RuntimeUpgradeInterface, StateCallInterface, StfExecutionResult, UpdateState, -}; -use itp_stf_primitives::{ - traits::TrustedCallVerification, - types::{ShardIdentifier, TrustedOperation, TrustedOperationOrHash}, -}; -use itp_stf_state_handler::{handle_state::HandleState, query_shard_state::QueryShardState}; -use itp_time_utils::duration_now; -use itp_types::{ - parentchain::{Header as ParentchainHeader, ParentchainCall, ParentchainId}, - storage::StorageEntryVerified, - H256, -}; -use log::*; -use sp_runtime::traits::Header as HeaderTrait; -use std::{ - collections::BTreeMap, fmt::Debug, marker::PhantomData, string::ToString, sync::Arc, - time::Duration, vec, vec::Vec, -}; - -pub struct StfExecutor -where - TCS: PartialEq + Encode + Decode + Debug + Clone + Send + Sync + TrustedCallVerification, - G: PartialEq + Encode + Decode + Debug + Clone + Send + Sync, -{ - ocall_api: Arc, - state_handler: Arc, - node_metadata_repo: Arc, - _phantom: PhantomData<(Stf, TCS, G)>, -} - -impl - StfExecutor -where - OCallApi: EnclaveAttestationOCallApi + EnclaveOnChainOCallApi + EnclaveMetricsOCallApi, - StateHandler: HandleState, - StateHandler::StateT: SgxExternalitiesTrait + Encode, - NodeMetadataRepository: AccessNodeMetadata, - NodeMetadataRepository::MetadataType: NodeMetadataTrait, - Stf: UpdateState< - StateHandler::StateT, - ::SgxExternalitiesDiffType, - > + StateCallInterface, - ::SgxExternalitiesDiffType: - IntoIterator, Option>)> + From, Option>>>, - >::Error: Debug, - TCS: PartialEq + Encode + Decode + Debug + Clone + Send + Sync + TrustedCallVerification, - G: PartialEq + Encode + Decode + Debug + Clone + Send + Sync, -{ - pub fn new( - ocall_api: Arc, - state_handler: Arc, - node_metadata_repo: Arc, - ) -> Self { - StfExecutor { ocall_api, state_handler, node_metadata_repo, _phantom: PhantomData } - } - - /// Execute a trusted call on the STF - /// - /// We distinguish between an error in the execution, which maps to `Err` and - /// an invalid trusted call, which results in `Ok(ExecutionStatus::Failure)`. The latter - /// can be used to remove the trusted call from a queue. In the former case we might keep the - /// trusted call and just re-try the operation. - fn execute_trusted_call_on_stf( - &self, - state: &mut StateHandler::StateT, - trusted_operation: &TrustedOperation, - _header: &PH, - shard: &ShardIdentifier, - post_processing: StatePostProcessing, - ) -> Result> - where - PH: HeaderTrait, - { - debug!("query mrenclave of self"); - let mrenclave = self.ocall_api.get_mrenclave_of_self()?; - - let top_or_hash = TrustedOperationOrHash::from_top(trusted_operation.clone()); - let operation_hash = trusted_operation.hash(); - debug!("Operation hash {:?}", operation_hash); - - // TODO(Litentry): do we need to send any error notification to parachain? - let trusted_call = match trusted_operation.to_call().ok_or(Error::InvalidTrustedCallType) { - Ok(c) => c, - Err(e) => { - error!("Error: {:?}", e); - return Ok(ExecutedOperation::failed(operation_hash, top_or_hash, vec![], vec![])) - }, - }; - - if !trusted_call.verify_signature(&mrenclave.m, &shard) { - error!("TrustedCallSigned: bad signature"); - return Ok(ExecutedOperation::failed(operation_hash, top_or_hash, vec![], vec![])) - } - - debug!("execute on STF, call with nonce {}", trusted_call.nonce()); - - let mut extrinsic_call_backs: Vec = Vec::new(); - return match Stf::execute_call( - state, - shard, - trusted_call.clone(), - trusted_operation.hash(), - &mut extrinsic_call_backs, - self.node_metadata_repo.clone(), - ) { - Err(e) => { - if let Err(e) = - self.ocall_api.update_metric(EnclaveMetric::FailedTrustedOperationIncrement( - trusted_call.metric_name().to_string(), - )) { - warn!("Failed to update metric for failed trusted operations: {:?}", e); - } - error!("Stf execute failed: {:?}", e); - let rpc_response_value: Vec = e.encode(); - Ok(ExecutedOperation::failed( - operation_hash, - top_or_hash, - extrinsic_call_backs, - rpc_response_value, - )) - }, - Ok(result) => { - if let Err(e) = self.ocall_api.update_metric( - EnclaveMetric::SuccessfulTrustedOperationIncrement( - trusted_call.metric_name().to_string(), - ), - ) { - warn!("Failed to update metric for succesfull trusted operations: {:?}", e); - } - let force_connection_wait = result.force_connection_wait(); - let rpc_response_value = result.get_encoded_result(); - if let StatePostProcessing::Prune = post_processing { - state.prune_state_diff(); - } - for call in extrinsic_call_backs.clone() { - trace!( - "trusted_call wants to send encoded call: 0x{}", - hex::encode(call.encode()) - ); - } - Ok(ExecutedOperation::success( - operation_hash, - top_or_hash, - extrinsic_call_backs, - rpc_response_value, - force_connection_wait, - )) - }, - } - } -} - -impl - StfUpdateState - for StfExecutor -where - OCallApi: EnclaveAttestationOCallApi + EnclaveOnChainOCallApi, - StateHandler: HandleState + QueryShardState, - StateHandler::StateT: SgxExternalitiesTrait + Encode, - NodeMetadataRepository: AccessNodeMetadata, - Stf: UpdateState< - StateHandler::StateT, - ::SgxExternalitiesDiffType, - > + ParentchainPalletInstancesInterface, - ::SgxExternalitiesDiffType: - IntoIterator, Option>)>, - >::Error: - Debug, - ::SgxExternalitiesDiffType: - From, Option>>>, - TCS: PartialEq + Encode + Decode + Debug + Clone + Send + Sync + TrustedCallVerification, - G: PartialEq + Encode + Decode + Debug + Clone + Send + Sync, -{ - fn update_states( - &self, - header: &ParentchainHeader, - parentchain_id: &ParentchainId, - ) -> Result<()> { - debug!("Update STF storage upon block import!"); - let storage_hashes = Stf::storage_hashes_to_update_on_block(parentchain_id); - - // global requests they are the same for every shard - let state_diff_update = self - .ocall_api - .get_multiple_storages_verified(storage_hashes, header, parentchain_id) - .map(into_map)?; - - // Update parentchain block on all states. - // TODO: Investigate if this is still necessary. We load and clone the entire state here, - // which scales badly for increasing state size. - let shards = self.state_handler.list_shards()?; - for shard_id in shards { - let (state_lock, mut state) = self.state_handler.load_for_mutation(&shard_id)?; - match Stf::update_parentchain_litentry_block(&mut state, header.clone()) { - Ok(_) => { - self.state_handler.write_after_mutation(state, state_lock, &shard_id)?; - }, - Err(e) => error!("Could not update parentchain block. {:?}: {:?}", shard_id, e), - } - } - - if parentchain_id != &ParentchainId::Litentry { - // nothing else to do - return Ok(()) - } - - // look for new shards and initialize them - if let Some(maybe_shards) = state_diff_update.get(&shards_key_hash()) { - match maybe_shards { - Some(shards) => self.initialize_new_shards(header, &state_diff_update, &shards)?, - None => debug!("No shards are on the chain yet"), - }; - }; - Ok(()) - } -} - -impl - StfExecutor -where - ::SgxExternalitiesDiffType: - From, Option>>> + IntoIterator, Option>)>, - >::Error: - Debug, - NodeMetadataRepository: AccessNodeMetadata, - OCallApi: EnclaveAttestationOCallApi + EnclaveOnChainOCallApi, - StateHandler: HandleState + QueryShardState, - StateHandler::StateT: Encode + SgxExternalitiesTrait, - Stf: ParentchainPalletInstancesInterface - + UpdateState< - StateHandler::StateT, - ::SgxExternalitiesDiffType, - >, - TCS: PartialEq + Encode + Decode + Debug + Clone + Send + Sync + TrustedCallVerification, - G: PartialEq + Encode + Decode + Debug + Clone + Send + Sync, -{ - fn initialize_new_shards( - &self, - header: &ParentchainHeader, - state_diff_update: &BTreeMap, Option>>, - shards: &Vec, - ) -> Result<()> { - let shards: Vec = Decode::decode(&mut shards.as_slice())?; - - for shard_id in shards { - let (state_lock, mut state) = self.state_handler.load_for_mutation(&shard_id)?; - trace!("Successfully loaded state, updating states ..."); - - // per shard (cid) requests - let per_shard_hashes = storage_hashes_to_update_per_shard(&shard_id); - let per_shard_update = self - .ocall_api - .get_multiple_storages_verified(per_shard_hashes, header, &ParentchainId::Litentry) - .map(into_map)?; - - Stf::apply_state_diff(&mut state, per_shard_update.into()); - Stf::apply_state_diff(&mut state, state_diff_update.clone().into()); - if let Err(e) = Stf::update_parentchain_litentry_block(&mut state, header.clone()) { - error!("Could not update parentchain block. {:?}: {:?}", shard_id, e) - } - - self.state_handler.write_after_mutation(state, state_lock, &shard_id)?; - } - Ok(()) - } -} - -impl StateUpdateProposer - for StfExecutor -where - OCallApi: EnclaveAttestationOCallApi + EnclaveOnChainOCallApi + EnclaveMetricsOCallApi, - StateHandler: HandleState, - StateHandler::StateT: SgxExternalitiesTrait + Encode + StateHash, - ::SgxExternalitiesType: Encode, - NodeMetadataRepository: AccessNodeMetadata, - NodeMetadataRepository::MetadataType: NodeMetadataTrait, - Stf: UpdateState< - StateHandler::StateT, - ::SgxExternalitiesDiffType, - > + StateCallInterface - + RuntimeUpgradeInterface, - ::SgxExternalitiesDiffType: - IntoIterator, Option>)>, - ::SgxExternalitiesDiffType: - From, Option>>>, - >::Error: Debug, - >::Error: Debug, - TCS: PartialEq + Encode + Decode + Debug + Clone + Send + Sync + TrustedCallVerification, - G: PartialEq + Encode + Decode + Debug + Clone + Send + Sync, -{ - type Externalities = StateHandler::StateT; - - fn propose_state_update( - &self, - trusted_calls: &[TrustedOperation], - header: &PH, - shard: &ShardIdentifier, - max_exec_duration: Duration, - prepare_state_function: F, - ) -> Result> - where - PH: HeaderTrait, - F: FnOnce(Self::Externalities) -> Self::Externalities, - { - let ends_at = duration_now() + max_exec_duration; - - let (state, state_hash_before_execution) = self.state_handler.load_cloned(shard)?; - - // Execute any pre-processing steps. - let mut state = prepare_state_function(state); - let mut executed_and_failed_calls = Vec::>::new(); - - // TODO: maybe we can move it to `prepare_state_function`. It seems more reasonable. - let _ = Stf::on_runtime_upgrade(&mut state); - - // Iterate through all calls until time is over. - for trusted_call_signed in trusted_calls.into_iter() { - // Break if allowed time window is over. - if ends_at < duration_now() { - info!("Aborting execution of trusted calls because slot time is up"); - break - } - - match self.execute_trusted_call_on_stf( - &mut state, - &trusted_call_signed, - header, - shard, - StatePostProcessing::None, - ) { - Ok(executed_or_failed_call) => { - executed_and_failed_calls.push(executed_or_failed_call); - }, - Err(e) => { - error!("Fatal Error. Failed to attempt call execution: {:?}", e); - }, - }; - } - - Ok(BatchExecutionResult { - executed_operations: executed_and_failed_calls, - state_hash_before_execution, - state_after_execution: state, - }) - } -} - -fn into_map( - storage_entries: Vec>>, -) -> BTreeMap, Option>> { - storage_entries.into_iter().map(|e| e.into_tuple()).collect() -} - -// todo: we need to clarify where these functions belong and if we need them at all. moved them from ita-stf but we can no longer depend on that -pub fn storage_hashes_to_update_per_shard(_shard: &ShardIdentifier) -> Vec> { - Vec::new() -} - -pub fn shards_key_hash() -> Vec { - // here you have to point to a storage value containing a Vec of - // ShardIdentifiers the enclave uses this to autosubscribe to no shards - vec![] -} diff --git a/tee-worker/bitacross/core-primitives/stf-executor/src/executor_tests.rs b/tee-worker/bitacross/core-primitives/stf-executor/src/executor_tests.rs deleted file mode 100644 index 2eb0185bcd..0000000000 --- a/tee-worker/bitacross/core-primitives/stf-executor/src/executor_tests.rs +++ /dev/null @@ -1,279 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use crate::{executor::StfExecutor, traits::StateUpdateProposer}; -use codec::Encode; -use itc_parentchain_test::ParentchainHeaderBuilder; -use itp_node_api::metadata::{metadata_mocks::NodeMetadataMock, provider::NodeMetadataRepository}; -use itp_ocall_api::EnclaveAttestationOCallApi; -use itp_sgx_externalities::{SgxExternalities as State, SgxExternalitiesTrait}; -use itp_stf_primitives::{traits::TrustedCallSigning, types::ShardIdentifier}; -use itp_stf_state_handler::handle_state::HandleState; -use itp_test::mock::{ - handle_state_mock::HandleStateMock, - onchain_mock::OnchainMock, - stf_mock::{GetterMock, StfMock, TrustedCallMock, TrustedCallSignedMock}, -}; -use itp_types::H256; -use sp_core::{ed25519, Pair}; -use sp_runtime::app_crypto::sp_core::blake2_256; -use std::{sync::Arc, time::Duration, vec}; -// FIXME: Create unit tests for update_states, execute_trusted_call, execute_trusted_call_on_stf #554 - -pub fn propose_state_update_executes_all_calls_given_enough_time() { - // given - let (stf_executor, ocall_api, state_handler) = stf_executor(); - let mrenclave = ocall_api.get_mrenclave_of_self().unwrap().m; - let (_, shard) = init_state_and_shard_with_state_handler(state_handler.as_ref()); - let sender = endowed_account(); - let signed_call_1 = TrustedCallMock::balance_transfer( - sender.public().into(), - sender.public().into(), - 42, - ) - .sign(&sender.clone().into(), 0, &mrenclave, &shard); - let trusted_operation_1 = signed_call_1.into_trusted_operation(true); - let call_operation_hash_1: H256 = blake2_256(&trusted_operation_1.encode()).into(); - let signed_call_2 = - TrustedCallMock::balance_transfer(sender.public().into(), sender.public().into(), 100) - .sign(&sender.clone().into(), 1, &mrenclave, &shard); - let trusted_operation_2 = signed_call_2.into_trusted_operation(true); - let call_operation_hash_2: H256 = blake2_256(&trusted_operation_2.encode()).into(); - - let (_, old_state_hash) = state_handler.load_cloned(&shard).unwrap(); - - // when - let batch_execution_result = stf_executor - .propose_state_update( - &vec![trusted_operation_1, trusted_operation_2], - &ParentchainHeaderBuilder::default().build(), - &shard, - Duration::from_secs(1000), - |state| state, - ) - .unwrap(); - - // then - assert_eq!(old_state_hash, batch_execution_result.state_hash_before_execution); - assert_eq!(batch_execution_result.executed_operations.len(), 2); - assert_eq!( - batch_execution_result.get_executed_operation_hashes(), - vec![call_operation_hash_1, call_operation_hash_2] - ); - // Ensure that state has been updated and not actually written. - assert_ne!( - state_handler.load_cloned(&shard).unwrap().0, - batch_execution_result.state_after_execution - ); -} - -pub fn propose_state_update_executes_only_one_trusted_call_given_not_enough_time() { - // given - let (stf_executor, ocall_api, state_handler) = stf_executor(); - let mrenclave = ocall_api.get_mrenclave_of_self().unwrap().m; - let (_, shard) = init_state_and_shard_with_state_handler(state_handler.as_ref()); - let sender = endowed_account(); - let signed_call_1 = TrustedCallMock::waste_time_ms(sender.public().into(), 10).sign( - &sender.clone().into(), - 0, - &mrenclave, - &shard, - ); - let trusted_operation_1 = signed_call_1.into_trusted_operation(true); - let call_operation_hash_1: H256 = blake2_256(&trusted_operation_1.encode()).into(); - - let signed_call_2 = TrustedCallMock::waste_time_ms(sender.public().into(), 10).sign( - &sender.clone().into(), - 0, - &mrenclave, - &shard, - ); - let trusted_operation_2 = signed_call_2.into_trusted_operation(true); - - let (_, old_state_hash) = state_handler.load_cloned(&shard).unwrap(); - // when - let batch_execution_result = stf_executor - .propose_state_update( - &vec![trusted_operation_1.clone(), trusted_operation_2.clone()], - &ParentchainHeaderBuilder::default().build(), - &shard, - Duration::from_millis(5), - |state| state, - ) - .unwrap(); - - // then - assert_eq!(old_state_hash, batch_execution_result.state_hash_before_execution); - assert_eq!(batch_execution_result.executed_operations.len(), 1); - assert_eq!(batch_execution_result.get_executed_operation_hashes(), vec![call_operation_hash_1]); - // Ensure that state has been updated and not actually written. - assert_ne!( - state_handler.load_cloned(&shard).unwrap().0, - batch_execution_result.state_after_execution - ); -} - -pub fn propose_state_update_executes_noop_leaving_state_untouched() { - // given - let (stf_executor, ocall_api, state_handler) = stf_executor(); - let mrenclave = ocall_api.get_mrenclave_of_self().unwrap().m; - let (_, shard) = init_state_and_shard_with_state_handler(state_handler.as_ref()); - let sender = endowed_account(); - let signed_call_1 = TrustedCallMock::noop(sender.public().into()).sign( - &sender.clone().into(), - 0, - &mrenclave, - &shard, - ); - let trusted_operation_1 = signed_call_1.into_trusted_operation(true); - let call_operation_hash_1: H256 = blake2_256(&trusted_operation_1.encode()).into(); - - let (_, old_state_hash) = state_handler.load_cloned(&shard).unwrap(); - // when - let batch_execution_result = stf_executor - .propose_state_update( - &vec![trusted_operation_1.clone()], - &ParentchainHeaderBuilder::default().build(), - &shard, - Duration::from_millis(5), // 1000 yields 0, 2000 yields 1, 4000 yields 1, 25_000 yields 2 - |state| state, - ) - .unwrap(); - - // then - assert_eq!(old_state_hash, batch_execution_result.state_hash_before_execution); - assert_eq!(batch_execution_result.executed_operations.len(), 1); - assert_eq!(batch_execution_result.get_executed_operation_hashes(), vec![call_operation_hash_1]); - assert_eq!( - state_handler.load_cloned(&shard).unwrap().0, - batch_execution_result.state_after_execution - ); -} - -pub fn propose_state_update_executes_no_trusted_calls_given_no_time() { - // given - let (stf_executor, ocall_api, state_handler) = stf_executor(); - let mrenclave = ocall_api.get_mrenclave_of_self().unwrap().m; - let (_, shard) = init_state_and_shard_with_state_handler(state_handler.as_ref()); - let sender = endowed_account(); - let signed_call_1 = TrustedCallMock::balance_transfer( - sender.public().into(), - sender.public().into(), - 42, - ) - .sign(&sender.clone().into(), 0, &mrenclave, &shard); - let trusted_operation_1 = signed_call_1.into_trusted_operation(true); - - let signed_call_2 = - TrustedCallMock::balance_transfer(sender.public().into(), sender.public().into(), 100) - .sign(&sender.clone().into(), 0, &mrenclave, &shard); - let trusted_operation_2 = signed_call_2.into_trusted_operation(true); - - let (_, old_state_hash) = state_handler.load_cloned(&shard).unwrap(); - - // when - let batch_execution_result = stf_executor - .propose_state_update( - &vec![trusted_operation_1.clone(), trusted_operation_2.clone()], - &ParentchainHeaderBuilder::default().build(), - &shard, - Duration::ZERO, - |state| state, - ) - .unwrap(); - - // then - assert_eq!(old_state_hash, batch_execution_result.state_hash_before_execution); - assert_eq!(batch_execution_result.executed_operations.len(), 0); - assert_eq!(batch_execution_result.get_executed_operation_hashes(), vec![]); -} - -pub fn propose_state_update_always_executes_preprocessing_step() { - // given - let shard = ShardIdentifier::default(); - let (stf_executor, _, state_handler) = stf_executor(); - let _init_hash = state_handler.initialize_shard(shard).unwrap(); - let key = "my_key".encode(); - let value = "my_value".encode(); - let (old_state, old_state_hash) = state_handler.load_cloned(&shard).unwrap(); - - // when - let batch_execution_result = stf_executor - .propose_state_update( - &vec![], - &ParentchainHeaderBuilder::default().build(), - &shard, - Duration::ZERO, - |mut state| { - state.insert(key.clone(), value.clone()); - state - }, - ) - .unwrap(); - - // then - assert_eq!(old_state_hash, batch_execution_result.state_hash_before_execution); - - // Ensure that state has been updated. - let retrieved_value = batch_execution_result.state_after_execution.get(key.as_slice()).unwrap(); - assert_eq!(*retrieved_value, value); - // Ensure that state has not been actually written. - assert_ne!(old_state, batch_execution_result.state_after_execution); -} - -// Helper Functions -fn stf_executor() -> ( - StfExecutor< - OnchainMock, - HandleStateMock, - NodeMetadataRepository, - StfMock, - TrustedCallSignedMock, - GetterMock, - >, - Arc, - Arc, -) { - let ocall_api = Arc::new(OnchainMock::default()); - let state_handler = Arc::new(HandleStateMock::default()); - let node_metadata_repo = Arc::new(NodeMetadataRepository::new(NodeMetadataMock::new())); - let executor = StfExecutor::new(ocall_api.clone(), state_handler.clone(), node_metadata_repo); - (executor, ocall_api, state_handler) -} - -/// Returns a test setup initialized `State` with the corresponding `ShardIdentifier`. -pub(crate) fn init_state_and_shard_with_state_handler>( - state_handler: &S, -) -> (State, ShardIdentifier) { - let shard = ShardIdentifier::default(); - let _hash = state_handler.initialize_shard(shard).unwrap(); - - let (lock, mut state) = state_handler.load_for_mutation(&shard).unwrap(); - test_genesis_setup(&mut state); - - state_handler.write_after_mutation(state.clone(), lock, &shard).unwrap(); - - (state, shard) -} - -pub fn endowed_account() -> ed25519::Pair { - ed25519::Pair::from_seed(&[42u8; 32].into()) -} - -pub fn test_genesis_setup(_state: &mut impl SgxExternalitiesTrait) { - // set alice sudo account -} diff --git a/tee-worker/bitacross/core-primitives/stf-executor/src/getter_executor.rs b/tee-worker/bitacross/core-primitives/stf-executor/src/getter_executor.rs deleted file mode 100644 index b968efc18b..0000000000 --- a/tee-worker/bitacross/core-primitives/stf-executor/src/getter_executor.rs +++ /dev/null @@ -1,137 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -//! Getter executor uses the state observer to get the most recent state and runs the getter on it. -//! The getter is verified (signature verfification) inside the `GetState` implementation. - -use crate::{error::Result, state_getter::GetState}; -use codec::Decode; -use itp_stf_primitives::traits::GetterAuthorization; -use itp_stf_state_observer::traits::ObserveState; -use itp_types::ShardIdentifier; -use log::*; -use std::{marker::PhantomData, sync::Arc, time::Instant, vec::Vec}; - -/// Trait to execute a getter for a specific shard. -pub trait ExecuteGetter { - fn execute_getter( - &self, - shard: &ShardIdentifier, - encoded_signed_getter: Vec, - ) -> Result>>; -} - -pub struct GetterExecutor -where - G: PartialEq, -{ - state_observer: Arc, - _phantom: PhantomData, - _phantom_getter: PhantomData, -} - -impl GetterExecutor -where - G: PartialEq, -{ - pub fn new(state_observer: Arc) -> Self { - Self { state_observer, _phantom: Default::default(), _phantom_getter: Default::default() } - } -} - -impl ExecuteGetter for GetterExecutor -where - StateObserver: ObserveState, - StateGetter: GetState, - G: PartialEq + Decode + GetterAuthorization, -{ - fn execute_getter( - &self, - shard: &ShardIdentifier, - encoded_signed_getter: Vec, - ) -> Result>> { - let getter = G::decode(&mut encoded_signed_getter.as_slice())?; - trace!("Successfully decoded trusted getter"); - - let getter_timer_start = Instant::now(); - let state_result = self - .state_observer - .observe_state(shard, |state| StateGetter::get_state(getter, state))??; - - debug!("Getter executed in {} ms", getter_timer_start.elapsed().as_millis()); - - Ok(state_result) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use codec::{Decode, Encode}; - - use itp_stf_state_observer::mock::ObserveStateMock; - use itp_test::mock::stf_mock::{ - GetterMock, PublicGetterMock, TrustedGetterMock, TrustedGetterSignedMock, - }; - - type TestState = u64; - type TestStateObserver = ObserveStateMock; - - struct TestStateGetter; - impl GetState for TestStateGetter { - fn get_state(_getter: GetterMock, state: &mut TestState) -> Result>> { - Ok(Some(state.encode())) - } - } - - type TestGetterExecutor = GetterExecutor; - - #[test] - fn executing_getters_works() { - let test_state = 23489u64; - let state_observer = Arc::new(TestStateObserver::new(test_state)); - let getter_executor = TestGetterExecutor::new(state_observer); - let getter = GetterMock::trusted(dummy_trusted_getter()); - - let state_result = getter_executor - .execute_getter(&ShardIdentifier::default(), getter.encode()) - .unwrap() - .unwrap(); - let decoded_state: TestState = Decode::decode(&mut state_result.as_slice()).unwrap(); - assert_eq!(decoded_state, test_state); - } - - #[test] - fn executing_public_getter_works() { - let test_state = 23489u64; - let state_observer = Arc::new(TestStateObserver::new(test_state)); - let getter_executor = TestGetterExecutor::new(state_observer); - let getter = GetterMock::public(PublicGetterMock::some_value); - - let state_result = getter_executor - .execute_getter(&ShardIdentifier::default(), getter.encode()) - .unwrap() - .unwrap(); - let decoded_state: TestState = Decode::decode(&mut state_result.as_slice()).unwrap(); - assert_eq!(decoded_state, test_state); - } - fn dummy_trusted_getter() -> TrustedGetterSignedMock { - TrustedGetterSignedMock { getter: TrustedGetterMock::some_value, signature: true } - // TrustedGetter::nonce(AccountId::new([0u8; 32])), - // MultiSignature::Ed25519(Signature::from_raw([0u8; 64])), - } -} diff --git a/tee-worker/bitacross/core-primitives/stf-executor/src/lib.rs b/tee-worker/bitacross/core-primitives/stf-executor/src/lib.rs deleted file mode 100644 index 6e1c8e21e8..0000000000 --- a/tee-worker/bitacross/core-primitives/stf-executor/src/lib.rs +++ /dev/null @@ -1,305 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -#![cfg_attr(not(feature = "std"), no_std)] -#![cfg_attr(test, feature(assert_matches))] - -#[cfg(all(feature = "std", feature = "sgx"))] -compile_error!("feature \"std\" and feature \"sgx\" cannot be enabled at the same time"); - -#[cfg(all(not(feature = "std"), feature = "sgx"))] -extern crate sgx_tstd as std; - -use codec::{Decode, Encode}; -use core::fmt::Debug; -use itp_sgx_externalities::SgxExternalitiesTrait; -use itp_stf_primitives::types::TrustedOperationOrHash; -use itp_types::{parentchain::ParentchainCall, H256}; -use std::vec::Vec; - -// re-export module to properly feature gate sgx and regular std environment -#[cfg(all(not(feature = "std"), feature = "sgx"))] -pub mod sgx_reexport_prelude { - pub use thiserror_sgx as thiserror; -} - -pub mod error; -pub mod getter_executor; -pub mod state_getter; -pub mod traits; - -#[cfg(feature = "sgx")] -pub mod executor; - -#[cfg(feature = "sgx")] -pub mod enclave_signer; - -#[cfg(all(feature = "sgx", feature = "test"))] -pub mod executor_tests; - -#[cfg(feature = "mocks")] -pub mod mocks; - -pub type RpcResponseValue = Vec; - -/// Execution status of a trusted operation -/// -/// In case of success, it includes the operation hash, as well as -/// any extrinsic callbacks (e.g. unshield extrinsics) that need to be executed on-chain -/// -/// Litentry: -/// we have made a few changes: -/// - we add the encoded rpc response that will be passed back to the requester -/// - for failed top, we apply the parachain effects too -#[derive(Clone, Debug, PartialEq)] -pub enum ExecutionStatus { - Success(H256, Vec, RpcResponseValue, bool), - Failure(H256, Vec, RpcResponseValue), -} - -impl ExecutionStatus { - pub fn get_extrinsic_callbacks(&self) -> Vec { - match self { - ExecutionStatus::Success(_, opaque_calls, _, _) => opaque_calls.clone(), - ExecutionStatus::Failure(_, opaque_calls, _) => opaque_calls.clone(), - } - } - - pub fn get_executed_operation_hash(&self) -> Option { - match self { - ExecutionStatus::Success(operation_hash, ..) => Some(*operation_hash), - _ => None, - } - } - - pub fn get_operation_hash(&self) -> H256 { - match self { - ExecutionStatus::Success(operation_hash, ..) => *operation_hash, - ExecutionStatus::Failure(operation_hash, ..) => *operation_hash, - } - } - - pub fn get_rpc_response_value(&self) -> RpcResponseValue { - match self { - ExecutionStatus::Success(_, _, res, _) => res.clone(), - ExecutionStatus::Failure(_, _, res) => res.clone(), - } - } - - pub fn get_force_wait(&self) -> bool { - match self { - ExecutionStatus::Success(_, _, _, wait) => *wait, - _ => false, - } - } -} - -/// Information about an executed trusted operation -/// -/// -#[derive(Clone, Debug, PartialEq)] -pub struct ExecutedOperation -where - TCS: PartialEq + Encode + Decode + Debug + Send + Sync, - G: PartialEq + Encode + Decode + Debug + Send + Sync, -{ - pub status: ExecutionStatus, - pub trusted_operation_or_hash: TrustedOperationOrHash, -} - -impl ExecutedOperation -where - TCS: PartialEq + Encode + Decode + Debug + Send + Sync, - G: PartialEq + Encode + Decode + Debug + Send + Sync, -{ - /// Constructor for a successfully executed trusted operation. - pub fn success( - operation_hash: H256, - trusted_operation_or_hash: TrustedOperationOrHash, - extrinsic_call_backs: Vec, - rpc_response_value: RpcResponseValue, - force_connection_wait: bool, - ) -> Self { - ExecutedOperation { - status: ExecutionStatus::Success( - operation_hash, - extrinsic_call_backs, - rpc_response_value, - force_connection_wait, - ), - trusted_operation_or_hash, - } - } - - /// Constructor for a failed trusted operation execution. - pub fn failed( - operation_hash: H256, - trusted_operation_or_hash: TrustedOperationOrHash, - extrinsic_call_backs: Vec, - rpc_response_value: RpcResponseValue, - ) -> Self { - ExecutedOperation { - status: ExecutionStatus::Failure( - operation_hash, - extrinsic_call_backs, - rpc_response_value, - ), - trusted_operation_or_hash, - } - } - - /// Returns true if the executed operation was a success. - pub fn is_success(&self) -> bool { - matches!(self.status, ExecutionStatus::Success(..)) - } -} - -/// Result of an execution on the STF -/// -/// Contains multiple executed operations -#[derive(Clone, Debug)] -pub struct BatchExecutionResult -where - TCS: PartialEq + Encode + Decode + Debug + Send + Sync, - G: PartialEq + Encode + Decode + Debug + Send + Sync, -{ - pub state_hash_before_execution: H256, - pub executed_operations: Vec>, - pub state_after_execution: Externalities, -} - -impl BatchExecutionResult -where - Externalities: SgxExternalitiesTrait + Encode, - TCS: PartialEq + Encode + Decode + Debug + Clone + Send + Sync, - G: PartialEq + Encode + Decode + Debug + Clone + Send + Sync, -{ - pub fn get_extrinsic_callbacks(&self) -> Vec { - self.executed_operations - .iter() - .flat_map(|e| e.status.get_extrinsic_callbacks()) - .collect() - } - - /// Returns all successfully exectued operation hashes. - pub fn get_executed_operation_hashes(&self) -> Vec { - self.executed_operations - .iter() - .flat_map(|ec| ec.status.get_executed_operation_hash()) - .collect() - } - - /// Returns all operations that were not executed. - pub fn get_failed_operations(&self) -> Vec> { - self.executed_operations.iter().filter(|ec| !ec.is_success()).cloned().collect() - } - - // Litentry: returns all (top_hash, (rpc_response_value, force_wait) tuples - pub fn get_connection_updates(&self) -> Vec<(H256, (RpcResponseValue, bool))> { - self.executed_operations - .iter() - .map(|ec| { - ( - ec.status.get_operation_hash(), - (ec.status.get_rpc_response_value(), ec.status.get_force_wait()), - ) - }) - .collect() - } -} - -#[cfg(test)] -mod tests { - use super::*; - use itp_sgx_externalities::SgxExternalities; - use itp_test::mock::stf_mock::{GetterMock, TrustedCallSignedMock}; - use itp_types::OpaqueCall; - - #[test] - fn is_success_works() { - let (success, _) = create_success_operation_from_u8(1); - let failed = create_failed_operation_from_u8(7); - - assert!(success.is_success()); - assert!(!failed.is_success()); - } - - #[test] - fn get_executed_operation_hashes_works() { - let (success_one, hash_success_one) = create_success_operation_from_u8(1); - let (success_two, hash_success_two) = create_success_operation_from_u8(3); - let failed = create_failed_operation_from_u8(7); - let result = batch_execution_result(vec![success_one, failed, success_two]); - - let success_operations = result.get_executed_operation_hashes(); - - assert_eq!(success_operations.len(), 2); - assert!(success_operations.contains(&hash_success_one)); - assert!(success_operations.contains(&hash_success_two)); - } - - #[test] - fn get_failed_operations_works() { - let failed_one = create_failed_operation_from_u8(1); - let failed_two = create_failed_operation_from_u8(3); - let (success, _) = create_success_operation_from_u8(10); - let result = batch_execution_result(vec![failed_one.clone(), failed_two.clone(), success]); - - let failed_operations = result.get_failed_operations(); - - assert_eq!(failed_operations.len(), 2); - assert!(failed_operations.contains(&failed_one)); - assert!(failed_operations.contains(&failed_two)); - } - - fn batch_execution_result( - executed_calls: Vec>, - ) -> BatchExecutionResult { - BatchExecutionResult { - executed_operations: executed_calls, - state_hash_before_execution: H256::default(), - state_after_execution: SgxExternalities::default(), - } - } - - fn create_failed_operation_from_u8( - int: u8, - ) -> ExecutedOperation { - ExecutedOperation::failed( - H256::from([int; 32]), - TrustedOperationOrHash::Hash(H256::from([int; 32])), - vec![], - vec![], - ) - } - - fn create_success_operation_from_u8( - int: u8, - ) -> (ExecutedOperation, H256) { - let hash = H256::from([int; 32]); - let opaque_call: Vec = - vec![ParentchainCall::Litentry(OpaqueCall(vec![int; 10]))]; - let operation = ExecutedOperation::success( - hash, - TrustedOperationOrHash::Hash(hash), - opaque_call, - vec![], - false, - ); - (operation, hash) - } -} diff --git a/tee-worker/bitacross/core-primitives/stf-executor/src/mocks.rs b/tee-worker/bitacross/core-primitives/stf-executor/src/mocks.rs deleted file mode 100644 index d328a2e24e..0000000000 --- a/tee-worker/bitacross/core-primitives/stf-executor/src/mocks.rs +++ /dev/null @@ -1,168 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use crate::{ - error::Result, - state_getter::GetState, - traits::{StateUpdateProposer, StfEnclaveSigning}, - BatchExecutionResult, ExecutedOperation, -}; -use codec::{Decode, Encode}; -use core::fmt::Debug; -use itp_sgx_externalities::SgxExternalitiesTrait; -use itp_stf_primitives::{ - traits::TrustedCallSigning, - types::{AccountId, KeyPair, ShardIdentifier, TrustedOperationOrHash}, -}; -use itp_types::{MrEnclave, H256}; -use sp_core::Pair; -use sp_runtime::traits::Header as HeaderTrait; -#[cfg(feature = "std")] -use std::sync::RwLock; -use std::{boxed::Box, marker::PhantomData, ops::Deref, time::Duration, vec::Vec}; - -use itp_stf_primitives::{ - traits::{GetterAuthorization, TrustedCallVerification}, - types::TrustedOperation, -}; - -#[cfg(feature = "sgx")] -use std::sync::SgxRwLock as RwLock; - -/// Mock for the StfExecutor. -#[derive(Default)] -pub struct StfExecutorMock { - pub state: RwLock, -} - -impl StfExecutorMock { - pub fn new(state: State) -> Self { - Self { state: RwLock::new(state) } - } - - pub fn get_state(&self) -> State { - (*self.state.read().unwrap().deref()).clone() - } -} - -impl StateUpdateProposer for StfExecutorMock -where - State: SgxExternalitiesTrait + Encode + Clone, - TCS: PartialEq + Encode + Decode + Clone + Debug + Send + Sync + TrustedCallVerification, - G: PartialEq + Encode + Decode + Clone + Debug + Send + Sync, -{ - type Externalities = State; - - fn propose_state_update( - &self, - trusted_calls: &[TrustedOperation], - _header: &PH, - _shard: &ShardIdentifier, - _max_exec_duration: Duration, - prepare_state_function: F, - ) -> Result> - where - PH: HeaderTrait, - F: FnOnce(Self::Externalities) -> Self::Externalities, - { - let mut lock = self.state.write().unwrap(); - - let updated_state = prepare_state_function((*lock.deref()).clone()); - - *lock = updated_state.clone(); - - let executed_operations: Vec> = trusted_calls - .iter() - .map(|c| { - let operation_hash = c.hash(); - let top_or_hash = TrustedOperationOrHash::::from_top(c.clone()); - ExecutedOperation::success( - operation_hash, - top_or_hash, - Vec::new(), - Vec::new(), - false, - ) - }) - .collect(); - - Ok(BatchExecutionResult { - executed_operations, - state_hash_before_execution: H256::default(), - state_after_execution: updated_state, - }) - } -} - -/// Enclave signer mock. -pub struct StfEnclaveSignerMock { - mr_enclave: [u8; 32], - signer: sp_core::ed25519::Pair, -} - -impl StfEnclaveSignerMock { - pub fn new(mr_enclave: [u8; 32]) -> Self { - type Seed = [u8; 32]; - const TEST_SEED: Seed = *b"42345678901234567890123456789012"; - - Self { mr_enclave, signer: sp_core::ed25519::Pair::from_seed(&TEST_SEED) } - } -} - -impl Default for StfEnclaveSignerMock { - fn default() -> Self { - Self::new([0u8; 32]) - } -} - -impl StfEnclaveSigning for StfEnclaveSignerMock { - fn get_enclave_account(&self) -> Result { - Ok(self.signer.public().into()) - } - - fn get_mrenclave(&self) -> Result { - Ok(self.mr_enclave) - } - - fn sign_call_with_self>( - &self, - trusted_call: &TC, - shard: &ShardIdentifier, - ) -> Result { - Ok(trusted_call.sign(&KeyPair::Ed25519(Box::new(self.signer)), 1, &self.mr_enclave, shard)) - } - - fn sign(&self, _payload: &[u8]) -> Result> { - Ok([0u8; 32].to_vec()) - } -} - -/// GetState mock -#[derive(Default)] -pub struct GetStateMock { - _phantom: PhantomData, -} - -impl GetState for GetStateMock -where - StateType: Encode, - G: PartialEq + Decode + GetterAuthorization, -{ - fn get_state(_getter: G, state: &mut StateType) -> Result>> { - Ok(Some(state.encode())) - } -} diff --git a/tee-worker/bitacross/core-primitives/stf-executor/src/state_getter.rs b/tee-worker/bitacross/core-primitives/stf-executor/src/state_getter.rs deleted file mode 100644 index ca047a36eb..0000000000 --- a/tee-worker/bitacross/core-primitives/stf-executor/src/state_getter.rs +++ /dev/null @@ -1,85 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use crate::error::{Error, Result}; -use codec::Decode; -use core::marker::PhantomData; -use itp_sgx_externalities::SgxExternalities; -use itp_stf_interface::StateGetterInterface; -use itp_stf_primitives::traits::GetterAuthorization; -use log::*; -use std::vec::Vec; - -/// Abstraction for accessing state with a getter. -pub trait GetState { - /// Executes a trusted getter on a state and return its value, if available. - /// - /// Also verifies the signature of the trusted getter and returns an error - /// if it's invalid. - fn get_state(getter: G, state: &mut StateType) -> Result>>; -} - -pub struct StfStateGetter { - _phantom: PhantomData, -} - -impl GetState for StfStateGetter -where - Stf: StateGetterInterface, - G: PartialEq + Decode + GetterAuthorization, -{ - fn get_state(getter: G, state: &mut SgxExternalities) -> Result>> { - if !getter.is_authorized() { - error!("getter authorization failed"); - return Err(Error::GetterIsNotAuthorized) - } - debug!("getter authorized. calling into STF to get state"); - Ok(Stf::execute_getter(state, getter)) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use core::assert_matches::assert_matches; - - use itp_test::mock::stf_mock::{ - GetterMock, StfMock, TrustedGetterMock, TrustedGetterSignedMock, - }; - - type TestStateGetter = StfStateGetter; - - #[test] - fn upon_false_signature_get_stf_state_errs() { - let getter = - TrustedGetterSignedMock { getter: TrustedGetterMock::some_value, signature: false }; - let mut state = SgxExternalities::default(); - - assert_matches!( - TestStateGetter::get_state(GetterMock::trusted(getter), &mut state), - Err(Error::GetterIsNotAuthorized) - ); - } - - #[test] - fn state_getter_is_executed_if_signature_is_correct() { - let getter = - TrustedGetterSignedMock { getter: TrustedGetterMock::some_value, signature: true }; - let mut state = SgxExternalities::default(); - assert!(TestStateGetter::get_state(GetterMock::trusted(getter), &mut state).is_ok()); - } -} diff --git a/tee-worker/bitacross/core-primitives/stf-executor/src/traits.rs b/tee-worker/bitacross/core-primitives/stf-executor/src/traits.rs deleted file mode 100644 index 62e788141a..0000000000 --- a/tee-worker/bitacross/core-primitives/stf-executor/src/traits.rs +++ /dev/null @@ -1,87 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use crate::{error::Result, BatchExecutionResult}; -use codec::{Decode, Encode}; -use core::fmt::Debug; -use itp_sgx_externalities::SgxExternalitiesTrait; -use itp_stf_primitives::{ - traits::TrustedCallSigning, - types::{AccountId, ShardIdentifier, TrustedOperation}, -}; -use itp_types::{MrEnclave, H256}; -use sp_runtime::traits::Header as HeaderTrait; -use std::{time::Duration, vec::Vec}; - -/// Post-processing steps after executing STF -pub enum StatePostProcessing { - None, - Prune, -} - -/// Allows signing of a trusted call or a raw bytes with the enclave account that is registered in the STF. -/// -/// The signing key is derived from the shielding key, which guarantees that all enclaves sign the same key. -pub trait StfEnclaveSigning -where - TCS: PartialEq + Encode + Debug, -{ - fn get_enclave_account(&self) -> Result; - - fn get_mrenclave(&self) -> Result; - - fn sign_call_with_self>( - &self, - trusted_call: &TC, - shard: &ShardIdentifier, - ) -> Result; - - // litentry: sign an opaque payload - fn sign(&self, payload: &[u8]) -> Result>; -} - -/// Proposes a state update to `Externalities`. -pub trait StateUpdateProposer -where - TCS: PartialEq + Encode + Decode + Debug + Send + Sync, - G: PartialEq + Encode + Decode + Debug + Send + Sync, -{ - type Externalities: SgxExternalitiesTrait + Encode; - - /// Executes trusted calls within a given time frame without permanent state mutation. - /// - /// All executed call hashes and the mutated state are returned. - /// If the time expires, any remaining trusted calls within the batch will be ignored. - fn propose_state_update( - &self, - trusted_calls: &[TrustedOperation], - header: &PH, - shard: &ShardIdentifier, - max_exec_duration: Duration, - prepare_state_function: F, - ) -> Result> - where - PH: HeaderTrait, - F: FnOnce(Self::Externalities) -> Self::Externalities; -} - -/// Updates the STF state for a specific header. -/// -/// Cannot be implemented for a generic header currently, because the runtime expects a ParentchainHeader. -pub trait StfUpdateState { - fn update_states(&self, header: &PCH, parentchain_id: &PCID) -> Result<()>; -} diff --git a/tee-worker/bitacross/core-primitives/top-pool-author/Cargo.toml b/tee-worker/bitacross/core-primitives/top-pool-author/Cargo.toml deleted file mode 100644 index dbfa28d14f..0000000000 --- a/tee-worker/bitacross/core-primitives/top-pool-author/Cargo.toml +++ /dev/null @@ -1,68 +0,0 @@ -[package] -name = "bc-itp-top-pool-author" -version = "0.1.0" -authors = ['Trust Computing GmbH ', 'Integritee AG '] -edition = "2021" - -[dependencies] -sgx_tstd = { workspace = true, optional = true } - -itp-enclave-metrics = { workspace = true } -itp-ocall-api = { workspace = true } -itp-sgx-crypto = { workspace = true } -itp-stf-primitives = { workspace = true } -itp-stf-state-handler = { workspace = true } -itp-test = { workspace = true, optional = true } -itp-top-pool = { package = "bc-itp-top-pool", path = "../top-pool", default-features = false } -itp-types = { workspace = true } -itp-utils = { workspace = true } -litentry-primitives = { workspace = true } - -jsonrpc-core = { workspace = true, optional = true } -jsonrpc-core_sgx = { workspace = true, optional = true } - -codec = { package = "parity-scale-codec", workspace = true } -derive_more = { workspace = true } -lazy_static = { workspace = true, optional = true } -log = { workspace = true } - -sp-core = { workspace = true, features = ["full_crypto"] } -sp-runtime = { workspace = true } - -[dev-dependencies] -futures = { workspace = true } -itp-sgx-crypto = { workspace = true, features = ["mocks"] } -itp-test = { workspace = true, features = ["std"] } -itp-top-pool = { package = "bc-itp-top-pool", path = "../top-pool", features = ["std", "mocks"] } -sgx_crypto_helper = { workspace = true } -sp-keyring = { workspace = true } - -[features] -default = ["std"] -std = [ - "itp-sgx-crypto/std", - "itp-enclave-metrics/std", - "itp-ocall-api/std", - "itp-stf-state-handler/std", - "itp-top-pool/std", - "itp-types/std", - "jsonrpc-core", - "log/std", - "litentry-primitives/std", - "itp-utils/std", - "sgx_crypto_helper/default", -] -sgx = [ - "sgx_tstd", - "jsonrpc-core_sgx", - "itp-enclave-metrics/sgx", - "itp-sgx-crypto/sgx", - "itp-stf-state-handler/sgx", - "itp-top-pool/sgx", - "litentry-primitives/sgx", - "sgx_crypto_helper/mesalock_sgx", -] -test = ["itp-test/sgx", "itp-top-pool/mocks"] -mocks = ["lazy_static"] -sidechain = [] -offchain-worker = [] diff --git a/tee-worker/bitacross/core-primitives/top-pool-author/src/api.rs b/tee-worker/bitacross/core-primitives/top-pool-author/src/api.rs deleted file mode 100644 index 7a133dca40..0000000000 --- a/tee-worker/bitacross/core-primitives/top-pool-author/src/api.rs +++ /dev/null @@ -1,171 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -//! Chain api required for the operation pool. - -#[cfg(all(not(feature = "std"), feature = "sgx"))] -use crate::sgx_reexport_prelude::*; -use core::fmt::Debug; - -use crate::error; -use codec::Encode; -use itp_stf_primitives::{ - traits::{PoolTransactionValidation, TrustedCallVerification}, - types::ShardIdentifier, -}; -use itp_top_pool::{ - pool::{ChainApi, NumberFor}, - primitives::{TrustedOperationSource, TxHash}, -}; -use itp_types::BlockHash as SidechainBlockHash; -use jsonrpc_core::futures::future::{ready, Future, Ready}; -use log::*; -use sp_runtime::{ - generic::BlockId, - traits::{BlakeTwo256, Block as BlockT, Hash as HashT}, - transaction_validity::TransactionValidity, -}; -use std::{boxed::Box, marker::PhantomData, pin::Pin}; - -/// Future that resolves to account nonce. -pub type Result = core::result::Result; - -/// The operation pool logic for full client. -pub struct SidechainApi { - _marker: PhantomData<(Block, TCS)>, -} - -impl SidechainApi -where - TCS: PartialEq + TrustedCallVerification + Debug, -{ - /// Create new operation pool logic. - pub fn new() -> Self { - SidechainApi { _marker: Default::default() } - } -} - -impl Default for SidechainApi -where - TCS: PartialEq + TrustedCallVerification + Debug + Sync + Send, -{ - fn default() -> Self { - Self::new() - } -} - -impl ChainApi for SidechainApi -where - Block: BlockT, - TCS: PartialEq + TrustedCallVerification + Sync + Send + Debug, -{ - type Block = Block; - type Error = error::Error; - type ValidationFuture = - Pin> + Send>>; - type BodyFuture = Ready>>; - - fn validate_transaction( - &self, - _source: TrustedOperationSource, - uxt: TOP, - _shard: ShardIdentifier, - ) -> Self::ValidationFuture { - let operation = uxt.validate(); - Box::pin(ready(Ok(operation))) - } - - fn block_id_to_number( - &self, - at: &BlockId, - ) -> error::Result>> { - Ok(match at { - BlockId::Number(num) => Some(*num), - BlockId::Hash(_) => None, - }) - } - - fn block_id_to_hash( - &self, - at: &BlockId, - ) -> error::Result> { - Ok(match at { - //BlockId::Hash(x) => Some(x.clone()), - BlockId::Hash(_x) => None, - // dummy - BlockId::Number(_num) => None, - }) - } - - fn hash_and_length(&self, ex: &TOP) -> (TxHash, usize) { - debug!("[Pool] creating hash of {:?}", ex); - ex.using_encoded(|x| (BlakeTwo256::hash(x), x.len())) - } - - fn block_body(&self, _id: &BlockId) -> Self::BodyFuture { - ready(Ok(None)) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use futures::executor; - use itp_stf_primitives::types::ShardIdentifier; - use itp_test::mock::stf_mock::{ - mock_top_indirect_trusted_call_signed, mock_top_public_getter, TrustedCallSignedMock, - }; - use itp_types::{AccountId, Block as ParentchainBlock}; - use sp_core::{ed25519, Pair}; - - type TestChainApi = SidechainApi; - - pub fn endowed_account() -> ed25519::Pair { - ed25519::Pair::from_seed(&[42u8; 32].into()) - } - - #[test] - fn indirect_calls_are_valid() { - let chain_api = TestChainApi::default(); - let _account: AccountId = endowed_account().public().into(); - let operation = mock_top_indirect_trusted_call_signed(); - - let validation = executor::block_on(chain_api.validate_transaction( - TrustedOperationSource::Local, - operation, - ShardIdentifier::default(), - )) - .unwrap(); - - assert!(validation.is_ok()); - } - - #[test] - fn public_getters_are_not_valid() { - let chain_api = TestChainApi::default(); - let public_getter = mock_top_public_getter(); - - let validation = executor::block_on(chain_api.validate_transaction( - TrustedOperationSource::Local, - public_getter, - ShardIdentifier::default(), - )) - .unwrap(); - - assert!(validation.is_err()); - } -} diff --git a/tee-worker/bitacross/core-primitives/top-pool-author/src/author.rs b/tee-worker/bitacross/core-primitives/top-pool-author/src/author.rs deleted file mode 100644 index 4c7b7363d2..0000000000 --- a/tee-worker/bitacross/core-primitives/top-pool-author/src/author.rs +++ /dev/null @@ -1,407 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -#[cfg(all(not(feature = "std"), feature = "sgx"))] -use crate::sgx_reexport_prelude::*; -use core::fmt::Debug; - -use crate::{ - client_error::Error as ClientError, - error::{Error as StateRpcError, Result}, - top_filter::Filter, - traits::{AuthorApi, OnBlockImported}, -}; -use codec::{Decode, Encode}; -use itp_sgx_crypto::{key_repository::AccessKey, ShieldingCryptoDecrypt}; -use itp_stf_primitives::{ - traits::{PoolTransactionValidation, TrustedCallVerification}, - types::{AccountId, Hash, TrustedOperation as StfTrustedOperation, TrustedOperationOrHash}, -}; -use itp_stf_state_handler::query_shard_state::QueryShardState; -use itp_top_pool::{ - error::{Error as PoolError, IntoPoolError}, - primitives::{ - BlockHash, InPoolOperation, PoolFuture, PoolStatus, TrustedOperationPool, - TrustedOperationSource, TxHash, - }, -}; -use itp_types::{BlockHash as SidechainBlockHash, DecryptableRequest, ShardIdentifier}; -use jsonrpc_core::{ - futures::future::{ready, TryFutureExt}, - Error as RpcError, -}; -use log::*; -use sp_runtime::generic; -use std::{boxed::Box, string::String, sync::Arc, vec::Vec}; - -/// Define type of TOP filter that is used in the Author -pub type AuthorTopFilter = crate::top_filter::IndirectCallsOnlyFilter; - -/// Currently we treat all RPC operations as externals. -/// -/// Possibly in the future we could allow opt-in for special treatment -/// of such operations, so that the block authors can inject -/// some unique operations via RPC and have them included in the pool. -const TX_SOURCE: TrustedOperationSource = TrustedOperationSource::External; - -// remove duplication of this type definiton ? -pub type RequestIdWithParamsAndMethod = Option<(Hash, Vec)>; - -/// Authoring API for RPC calls -/// -/// -pub struct Author -where - TopPool: TrustedOperationPool> + Sync + Send + 'static, - TopFilter: Filter>, - StateFacade: QueryShardState, - ShieldingKeyRepository: AccessKey, - ::KeyType: ShieldingCryptoDecrypt + 'static, - TCS: PartialEq + Encode + Clone + Debug + Send + Sync, - G: PartialEq + Encode + Clone + PoolTransactionValidation + Debug + Send + Sync, -{ - top_pool: Arc, - top_filter: TopFilter, - state_facade: Arc, - shielding_key_repo: Arc, -} - -impl - Author -where - TopPool: TrustedOperationPool> + Sync + Send + 'static, - TopFilter: Filter>, - StateFacade: QueryShardState, - ShieldingKeyRepository: AccessKey, - ::KeyType: ShieldingCryptoDecrypt + 'static, - TCS: PartialEq + Encode + Clone + Debug + Send + Sync, - G: PartialEq + Encode + Clone + PoolTransactionValidation + Debug + Send + Sync, -{ - /// Create new instance of Authoring API. - pub fn new( - top_pool: Arc, - top_filter: TopFilter, - state_facade: Arc, - encryption_key: Arc, - ) -> Self { - Author { top_pool, top_filter, state_facade, shielding_key_repo: encryption_key } - } -} - -enum TopSubmissionMode { - Submit, - SubmitWatch, -} - -impl - Author -where - TopPool: TrustedOperationPool> + Sync + Send + 'static, - TopFilter: Filter>, - StateFacade: QueryShardState, - ShieldingKeyRepository: AccessKey, - ::KeyType: ShieldingCryptoDecrypt + 'static, - TCS: PartialEq - + Encode - + Decode - + Clone - + Debug - + Send - + Sync - + TrustedCallVerification - + 'static, - G: PartialEq - + Encode - + Decode - + Clone - + PoolTransactionValidation - + Debug - + Send - + Sync - + 'static, -{ - fn process_top( - &self, - mut request: R, - submission_mode: TopSubmissionMode, - ) -> PoolFuture { - let shard = request.shard(); - - // check if shard exists - match self.state_facade.shard_exists(&shard) { - Err(_) => return Box::pin(ready(Err(ClientError::InvalidShard.into()))), - Ok(shard_exists) => - if !shard_exists { - return Box::pin(ready(Err(ClientError::InvalidShard.into()))) - }, - }; - - // decrypt call - let shielding_key = match self.shielding_key_repo.retrieve_key() { - Ok(k) => k, - Err(_) => return Box::pin(ready(Err(ClientError::BadFormatDecipher.into()))), - }; - let request_vec = match request.decrypt(Box::new(shielding_key)) { - Ok(req) => req, - Err(_) => return Box::pin(ready(Err(ClientError::BadFormatDecipher.into()))), - }; - // decode call - let trusted_operation = - match StfTrustedOperation::::decode(&mut request_vec.as_slice()) { - Ok(op) => op, - Err(_) => return Box::pin(ready(Err(ClientError::BadFormat.into()))), - }; - - trace!("decrypted indirect invocation: {:?}", trusted_operation); - - // apply top filter - return error if this specific type of trusted operation - // is not allowed by the filter - if !self.top_filter.filter(&trusted_operation) { - warn!("unsupported operation"); - return Box::pin(ready(Err(ClientError::UnsupportedOperation.into()))) - } - - //let best_block_hash = self.client.info().best_hash; - // dummy block hash - let best_block_hash = Default::default(); - - if let Some(trusted_call_signed) = trusted_operation.to_call() { - debug!( - "Submitting trusted call to TOP pool: {:?}, TOP hash: {:?}", - trusted_call_signed, - self.hash_of(&trusted_operation) - ); - } else if let StfTrustedOperation::::get(ref getter) = trusted_operation { - debug!( - "Submitting trusted or public getter to TOP pool: {:?}, TOP hash: {:?}", - getter, - self.hash_of(&trusted_operation) - ); - } - - match submission_mode { - TopSubmissionMode::Submit => Box::pin( - self.top_pool - .submit_one( - &generic::BlockId::hash(best_block_hash), - TX_SOURCE, - trusted_operation, - shard, - ) - .map_err(map_top_error::), - ), - - TopSubmissionMode::SubmitWatch => Box::pin( - self.top_pool - .submit_and_watch( - &generic::BlockId::hash(best_block_hash), - TX_SOURCE, - trusted_operation, - shard, - ) - .map_err(map_top_error::), - ), - } - } - - fn remove_top( - &self, - bytes_or_hash: TrustedOperationOrHash, - shard: ShardIdentifier, - inblock: bool, - ) -> Result { - let hash = match bytes_or_hash { - TrustedOperationOrHash::Hash(h) => Ok(h), - TrustedOperationOrHash::OperationEncoded(bytes) => { - match Decode::decode(&mut bytes.as_slice()) { - Ok(op) => Ok(self.top_pool.hash_of(&op)), - Err(e) => { - error!("Failed to decode trusted operation: {:?}, operation will not be removed from pool", e); - Err(StateRpcError::CodecError(e)) - }, - } - }, - TrustedOperationOrHash::Operation(op) => Ok(self.top_pool.hash_of(&op)), - }?; - - debug!("removing {:?} from top pool", hash); - - let removed_op_hash = self - .top_pool - .remove_invalid(&[hash], shard, inblock) - // Only remove a single element, so first should return Ok(). - .first() - .map(|o| o.hash()) - .ok_or(PoolError::InvalidTrustedOperation)?; - - Ok(removed_op_hash) - } -} - -fn map_top_error>, TCS, G>( - error: P::Error, -) -> RpcError -where - TCS: PartialEq + Encode + Debug, - G: PartialEq + Encode + Debug, -{ - StateRpcError::PoolError( - error - .into_pool_error() - .map(Into::into) - .unwrap_or_else(|_error| PoolError::Verification), - ) - .into() -} - -impl - AuthorApi - for Author -where - TopPool: TrustedOperationPool> + Sync + Send + 'static, - TopFilter: Filter>, - StateFacade: QueryShardState, - ShieldingKeyRepository: AccessKey, - ::KeyType: ShieldingCryptoDecrypt + 'static, - G: PartialEq - + Encode - + Decode - + Clone - + PoolTransactionValidation - + Debug - + Send - + Sync - + 'static, - TCS: PartialEq - + Encode - + Decode - + Clone - + Debug - + Send - + Sync - + TrustedCallVerification - + 'static, -{ - fn submit_top(&self, req: R) -> PoolFuture { - self.process_top(req, TopSubmissionMode::Submit) - } - - /// Get hash of TrustedOperation - fn hash_of(&self, xt: &StfTrustedOperation) -> TxHash { - self.top_pool.hash_of(xt) - } - - fn pending_tops(&self, shard: ShardIdentifier) -> Result>> { - Ok(self.top_pool.ready(shard).map(|top| top.data().encode()).collect()) - } - - fn get_pending_getters(&self, shard: ShardIdentifier) -> Vec> { - self.top_pool - .ready(shard) - .filter_map(|o| match o.data() { - StfTrustedOperation::::get(_) => Some(o.data().clone()), - StfTrustedOperation::::direct_call(_) - | StfTrustedOperation::::indirect_call(_) => None, - }) - .collect() - } - - fn get_pending_trusted_calls( - &self, - shard: ShardIdentifier, - ) -> Vec> { - self.top_pool - .ready(shard) - .filter_map(|o| match o.data() { - StfTrustedOperation::::direct_call(_) - | StfTrustedOperation::::indirect_call(_) => Some(o.data().clone()), - StfTrustedOperation::::get(_) => None, - }) - .collect() - } - - fn get_status(&self, shard: ShardIdentifier) -> PoolStatus { - self.top_pool.status(shard) - } - - fn get_pending_trusted_calls_for( - &self, - shard: ShardIdentifier, - account: &AccountId, - ) -> Vec> { - self.get_pending_trusted_calls(shard) - .into_iter() - .filter(|o| o.signed_caller_account().as_ref() == Some(account)) - .collect() - } - - fn get_shards(&self) -> Vec { - self.top_pool.shards() - } - - fn list_handled_shards(&self) -> Vec { - self.state_facade.list_shards().unwrap_or_default() - } - - fn remove_calls_from_pool( - &self, - shard: ShardIdentifier, - executed_calls: Vec<(TrustedOperationOrHash, bool)>, - ) -> Vec> { - let mut failed_to_remove = Vec::new(); - for (executed_call, inblock) in executed_calls { - if let Err(e) = self.remove_top(executed_call.clone(), shard, inblock) { - // We don't want to return here before all calls have been iterated through, - // hence log message and collect failed calls in vec. - debug!("Error removing trusted call from top pool: {:?}", e); - failed_to_remove.push(executed_call); - } - } - failed_to_remove - } - - fn watch_top( - &self, - request: R, - ) -> PoolFuture { - self.process_top(request, TopSubmissionMode::SubmitWatch) - } - - fn update_connection_state(&self, updates: Vec<(TxHash, (Vec, bool))>) { - self.top_pool.update_connection_state(updates) - } - - fn swap_rpc_connection_hash(&self, old_hash: TxHash, new_hash: TxHash) { - self.top_pool.swap_rpc_connection_hash(old_hash, new_hash) - } -} - -impl OnBlockImported - for Author -where - TopPool: TrustedOperationPool> + Sync + Send + 'static, - TopFilter: Filter>, - StateFacade: QueryShardState, - ShieldingKeyRepository: AccessKey, - ::KeyType: ShieldingCryptoDecrypt + 'static, - G: PartialEq + Encode + Clone + PoolTransactionValidation + Debug + Send + Sync, - TCS: PartialEq + Encode + Clone + Debug + Send + Sync, -{ - type Hash = TxHash; - - fn on_block_imported(&self, _hashes: &[Self::Hash], _block_hash: SidechainBlockHash) {} -} diff --git a/tee-worker/bitacross/core-primitives/top-pool-author/src/author_tests.rs b/tee-worker/bitacross/core-primitives/top-pool-author/src/author_tests.rs deleted file mode 100644 index a354ea772b..0000000000 --- a/tee-worker/bitacross/core-primitives/top-pool-author/src/author_tests.rs +++ /dev/null @@ -1,141 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use crate::{ - author::Author, - test_fixtures::shard_id, - test_utils::submit_operation_to_top_pool, - top_filter::{AllowAllTopsFilter, Filter, GettersOnlyFilter}, - traits::AuthorApi, -}; -use codec::{Decode, Encode}; -use itp_sgx_crypto::{mocks::KeyRepositoryMock, ShieldingCryptoDecrypt, ShieldingCryptoEncrypt}; - -use itp_stf_state_handler::handle_state::HandleState; -use itp_test::mock::{ - handle_state_mock::HandleStateMock, - shielding_crypto_mock::ShieldingCryptoMock, - stf_mock::{ - mock_top_direct_trusted_call_signed, mock_top_indirect_trusted_call_signed, - mock_top_trusted_getter_signed, GetterMock, TrustedCallSignedMock, TrustedOperationMock, - }, -}; -use itp_top_pool::mocks::trusted_operation_pool_mock::TrustedOperationPoolMock; - -use sgx_crypto_helper::{rsa3072::Rsa3072KeyPair, RsaKeyPair}; -use std::sync::Arc; - -type TestAuthor = Author< - TrustedOperationPoolMock, - Filter, - HandleStateMock, - KeyRepositoryMock, - TrustedCallSignedMock, - GetterMock, ->; - -#[test] -fn top_encryption_works() { - let top_call = mock_top_direct_trusted_call_signed(); - let top_getter = mock_top_trusted_getter_signed(); - assert_eq!(top_call, encrypt_and_decrypt_top(&top_call)); - assert_eq!(top_getter, encrypt_and_decrypt_top(&top_getter)); -} - -fn encrypt_and_decrypt_top(top: &TrustedOperationMock) -> TrustedOperationMock { - let encryption_key = Rsa3072KeyPair::new().unwrap(); - let encrypted_top = encryption_key.encrypt(top.encode().as_slice()).unwrap(); - let decrypted_top = encryption_key.decrypt(encrypted_top.as_slice()).unwrap(); - - TrustedOperationMock::decode(&mut decrypted_top.as_slice()).unwrap() -} - -#[test] -fn submitting_to_author_inserts_in_pool() { - let (author, top_pool, shielding_key) = create_author_with_filter(AllowAllTopsFilter::new()); - let top_getter = mock_top_trusted_getter_signed(); - - let submit_response = - submit_operation_to_top_pool(&author, &top_getter, &shielding_key, shard_id()).unwrap(); - - assert!(!submit_response.0.is_zero()); - - let submitted_transactions = top_pool.get_last_submitted_transactions(); - assert_eq!(1, submitted_transactions.len()); -} - -#[test] -fn submitting_call_to_author_when_top_is_filtered_returns_error() { - let (author, top_pool, shielding_key) = create_author_with_filter(GettersOnlyFilter::new()); - let top_call = mock_top_direct_trusted_call_signed(); - let submit_response = - submit_operation_to_top_pool(&author, &top_call, &shielding_key, shard_id()); - - assert!(submit_response.is_err()); - assert!(top_pool.get_last_submitted_transactions().is_empty()); -} - -#[test] -fn submitting_getter_to_author_when_top_is_filtered_inserts_in_pool() { - let (author, top_pool, shielding_key) = create_author_with_filter(GettersOnlyFilter::new()); - let top_getter = mock_top_trusted_getter_signed(); - let submit_response = - submit_operation_to_top_pool(&author, &top_getter, &shielding_key, shard_id()).unwrap(); - - assert!(!submit_response.0.is_zero()); - assert_eq!(1, top_pool.get_last_submitted_transactions().len()); -} - -#[test] -fn submitting_direct_call_works() { - let (author, top_pool, shielding_key) = create_author_with_filter(AllowAllTopsFilter::new()); - let top_call = mock_top_direct_trusted_call_signed(); - let _ = submit_operation_to_top_pool(&author, &top_call, &shielding_key, shard_id()).unwrap(); - - assert_eq!(1, top_pool.get_last_submitted_transactions().len()); - assert_eq!(1, author.get_pending_trusted_calls(shard_id()).len()); -} - -#[test] -fn submitting_indirect_call_works() { - let (author, top_pool, shielding_key) = create_author_with_filter(AllowAllTopsFilter::new()); - let top_call = mock_top_indirect_trusted_call_signed(); - let _ = submit_operation_to_top_pool(&author, &top_call, &shielding_key, shard_id()).unwrap(); - - assert_eq!(1, top_pool.get_last_submitted_transactions().len()); - assert_eq!(1, author.get_pending_trusted_calls(shard_id()).len()); -} - -fn create_author_with_filter>( - filter: F, -) -> (TestAuthor, Arc>, ShieldingCryptoMock) { - let top_pool = Arc::new(TrustedOperationPoolMock::default()); - - let shard_id = shard_id(); - let state_facade = HandleStateMock::from_shard(shard_id).unwrap(); - state_facade.load_cloned(&shard_id).unwrap(); - - let encryption_key = ShieldingCryptoMock::default(); - let shielding_key_repo = - Arc::new(KeyRepositoryMock::::new(encryption_key.clone())); - - ( - Author::new(top_pool.clone(), filter, Arc::new(state_facade), shielding_key_repo), - top_pool, - encryption_key, - ) -} diff --git a/tee-worker/bitacross/core-primitives/top-pool-author/src/client_error.rs b/tee-worker/bitacross/core-primitives/top-pool-author/src/client_error.rs deleted file mode 100644 index badd278008..0000000000 --- a/tee-worker/bitacross/core-primitives/top-pool-author/src/client_error.rs +++ /dev/null @@ -1,183 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -//! Authoring RPC module client errors. - -#[cfg(all(not(feature = "std"), feature = "sgx"))] -use crate::sgx_reexport_prelude::*; - -use derive_more::{Display, From}; -use jsonrpc_core as rpc_core; -use std::{boxed::Box, format}; - -/// Author RPC Result type. -pub type Result = core::result::Result; - -/// Author RPC errors. -#[derive(Debug, Display, From)] -pub enum Error { - /// Client error. - #[display(fmt = "Client error: {}", _0)] - #[from(ignore)] - Client(Box), - /// TrustedOperation pool error, - #[display(fmt = "TrustedOperation pool error: {}", _0)] - Pool(itp_top_pool::error::Error), - /// Verification error - #[display(fmt = "Extrinsic verification error")] - #[from(ignore)] - Verification, - /// Incorrect extrinsic format. - #[display(fmt = "Invalid trusted call format")] - BadFormat, - // Incorrect enciphered trusted call format. - #[display(fmt = "Invalid enciphered trusted call format")] - BadFormatDecipher, - /// Incorrect seed phrase. - #[display(fmt = "Invalid seed phrase/SURI")] - BadSeedPhrase, - /// Key type ID has an unknown format. - #[display(fmt = "Invalid key type ID format (should be of length four)")] - BadKeyType, - /// Key type ID has some unsupported crypto. - #[display(fmt = "The crypto of key type ID is unknown")] - UnsupportedKeyType, - /// Some random issue with the key store. Shouldn't happen. - #[display(fmt = "The key store is unavailable")] - KeyStoreUnavailable, - /// Invalid session keys encoding. - #[display(fmt = "Session keys are not encoded correctly")] - InvalidSessionKeys, - /// Shard does not exist. - #[display(fmt = "Shard does not exist")] - InvalidShard, - /// Unsupported trusted operation (in case we allow only certain types of operations, using filters) - #[display(fmt = "Unsupported operation type")] - UnsupportedOperation, -} - -impl std::error::Error for Error { - fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { - match self { - Error::Client(ref err) => Some(&**err), - //Error::Pool(ref err) => Some(err), - //Error::Verification(ref err) => Some(&**err), - _ => None, - } - } -} - -/// Base code for all authorship errors. -const BASE_ERROR: i64 = 1000; -/// Extrinsic has an invalid format. -const BAD_FORMAT: i64 = BASE_ERROR + 1; -/// Error during operation verification in runtime. -const VERIFICATION_ERROR: i64 = BASE_ERROR + 2; - -/// Pool rejected the operation as invalid -const POOL_INVALID_TX: i64 = BASE_ERROR + 10; -/// Cannot determine operation validity. -const POOL_UNKNOWN_VALIDITY: i64 = POOL_INVALID_TX + 1; -/// The operation is temporarily banned. -const POOL_TEMPORARILY_BANNED: i64 = POOL_INVALID_TX + 2; -/// The operation is already in the pool -const POOL_ALREADY_IMPORTED: i64 = POOL_INVALID_TX + 3; -/// TrustedOperation has too low priority to replace existing one in the pool. -const POOL_TOO_LOW_PRIORITY: i64 = POOL_INVALID_TX + 4; -/// Including this operation would cause a dependency cycle. -const POOL_CYCLE_DETECTED: i64 = POOL_INVALID_TX + 5; -/// The operation was not included to the pool because of the limits. -const POOL_IMMEDIATELY_DROPPED: i64 = POOL_INVALID_TX + 6; -/// The key type crypto is not known. -const UNSUPPORTED_KEY_TYPE: i64 = POOL_INVALID_TX + 7; - -impl From for rpc_core::Error { - fn from(e: Error) -> Self { - use itp_top_pool::error::Error as PoolError; - - match e { - Error::BadFormat => rpc_core::Error { - code: rpc_core::ErrorCode::ServerError(BAD_FORMAT), - message: "Trusted operation has invalid format".into(), - data: None, - }, - Error::BadFormatDecipher => rpc_core::Error { - code: rpc_core::ErrorCode::ServerError(BAD_FORMAT), - message: "Trusted operation could not be deciphered".into(), - data: None, - }, - Error::Verification => rpc_core::Error { - code: rpc_core::ErrorCode::ServerError(VERIFICATION_ERROR), - message: "Verification Error".into(), - data: Some(format!("{:?}", e).into()), - }, - Error::InvalidShard => rpc_core::Error { - code: rpc_core::ErrorCode::ServerError(VERIFICATION_ERROR), - message: "Shard does not exist".into(), - data: Some(format!("{:?}", e).into()), - }, - Error::Pool(PoolError::InvalidTrustedOperation) => rpc_core::Error { - code: rpc_core::ErrorCode::ServerError(POOL_INVALID_TX), - message: "Invalid Trusted Operation".into(), - data: None, - }, - Error::Pool(PoolError::UnknownTrustedOperation) => rpc_core::Error { - code: rpc_core::ErrorCode::ServerError(POOL_UNKNOWN_VALIDITY), - message: "Unknown Trusted Operation Validity".into(), - data: None, - }, - Error::Pool(PoolError::TemporarilyBanned) => rpc_core::Error { - code: rpc_core::ErrorCode::ServerError(POOL_TEMPORARILY_BANNED), - message: "Trusted Operation is temporarily banned".into(), - data: None, - }, - Error::Pool(PoolError::AlreadyImported) => rpc_core::Error { - code: rpc_core::ErrorCode::ServerError(POOL_ALREADY_IMPORTED), - message: "Trusted Operation Already Imported".into(), - data: None, - }, - Error::Pool(PoolError::TooLowPriority(new)) => rpc_core::Error { - code: rpc_core::ErrorCode::ServerError(POOL_TOO_LOW_PRIORITY), - message: format!("Priority is too low: {}", new), - data: Some("The Trusted Operation has too low priority to replace another Trusted Operation already in the pool.".into()), - }, - Error::Pool(PoolError::CycleDetected) => rpc_core::Error { - code: rpc_core::ErrorCode::ServerError(POOL_CYCLE_DETECTED), - message: "Cycle Detected".into(), - data: None, - }, - Error::Pool(PoolError::ImmediatelyDropped) => rpc_core::Error { - code: rpc_core::ErrorCode::ServerError(POOL_IMMEDIATELY_DROPPED), - message: "Immediately Dropped".into(), - data: Some("The Trusted Operation couldn't enter the pool because of the limit".into()), - }, - Error::UnsupportedKeyType => rpc_core::Error { - code: rpc_core::ErrorCode::ServerError(UNSUPPORTED_KEY_TYPE), - message: "Unknown key type crypto" .into(), - data: Some( - "The crypto for the given key type is unknown, please add the public key to the \ - request to insert the key successfully.".into() - ), - }, - e => rpc_core::Error { - code: rpc_core::ErrorCode::InternalError, - message: "Unknown error occurred".into(), - data: Some(format!("{:?}", e).into()), - }, - } - } -} diff --git a/tee-worker/bitacross/core-primitives/top-pool-author/src/error.rs b/tee-worker/bitacross/core-primitives/top-pool-author/src/error.rs deleted file mode 100644 index 1c967a1b82..0000000000 --- a/tee-worker/bitacross/core-primitives/top-pool-author/src/error.rs +++ /dev/null @@ -1,111 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -#[cfg(all(not(feature = "std"), feature = "sgx"))] -use crate::sgx_reexport_prelude::*; - -use crate::client_error::Error as ClientError; -use core::pin::Pin; -use derive_more::{Display, From}; -use itp_top_pool::error::{Error as PoolError, IntoPoolError}; -use jsonrpc_core as rpc; -use std::{boxed::Box, error, format, string::String}; - -/// State RPC Result type. -pub type Result = core::result::Result; - -/// State RPC future Result type. -pub type FutureResult = - Pin> + Send>>; - -/// State RPC errors. -#[derive(Debug, Display, From)] -pub enum Error { - /// Client error. - #[display(fmt = "Client error: {}", _0)] - Client(Box), - /// Provided block range couldn't be resolved to a list of blocks. - #[display(fmt = "Cannot resolve a block range ['{:?}' ... '{:?}]. {}", from, to, details)] - InvalidBlockRange { - /// Beginning of the block range. - from: String, - /// End of the block range. - to: String, - /// Details of the error message. - details: String, - }, - /// Provided count exceeds maximum value. - #[display(fmt = "count exceeds maximum value. value: {}, max: {}", value, max)] - InvalidCount { - /// Provided value - value: u32, - /// Maximum allowed value - max: u32, - }, - - /// Wrapping of PoolError to RPC Error - PoolError(PoolError), - - /// Wrapping of ClientError to RPC Error - ClientError(ClientError), - - #[display(fmt = "Codec error: {}", _0)] - CodecError(codec::Error), -} - -impl error::Error for Error { - fn source(&self) -> Option<&(dyn error::Error + 'static)> { - match self { - Error::Client(ref err) => Some(&**err), - _ => None, - } - } -} - -impl IntoPoolError for Error { - fn into_pool_error(self) -> std::result::Result { - match self { - Error::PoolError(e) => Ok(e), - e => Err(e), - } - } -} - -/// Base code for all state errors. -const BASE_ERROR: i64 = 4000; - -impl From for rpc::Error { - fn from(e: Error) -> Self { - match e { - Error::InvalidBlockRange { .. } => rpc::Error { - code: rpc::ErrorCode::ServerError(BASE_ERROR + 1), - message: format!("{}", e), - data: None, - }, - Error::InvalidCount { .. } => rpc::Error { - code: rpc::ErrorCode::ServerError(BASE_ERROR + 2), - message: format!("{}", e), - data: None, - }, - e => rpc::Error { - code: rpc::ErrorCode::ServerError(BASE_ERROR + 4), - message: format!("{}", e), - data: None, - }, - } - } -} diff --git a/tee-worker/bitacross/core-primitives/top-pool-author/src/lib.rs b/tee-worker/bitacross/core-primitives/top-pool-author/src/lib.rs deleted file mode 100644 index b0b84b992c..0000000000 --- a/tee-worker/bitacross/core-primitives/top-pool-author/src/lib.rs +++ /dev/null @@ -1,51 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -#![feature(trait_alias)] -#![cfg_attr(feature = "mocks", feature(drain_filter))] -#![cfg_attr(not(feature = "std"), no_std)] - -#[cfg(all(feature = "std", feature = "sgx"))] -compile_error!("feature \"std\" and feature \"sgx\" cannot be enabled at the same time"); - -#[cfg(all(not(feature = "std"), feature = "sgx"))] -extern crate sgx_tstd as std; - -// re-export module to properly feature gate sgx and regular std environment -#[cfg(all(not(feature = "std"), feature = "sgx"))] -pub mod sgx_reexport_prelude { - pub use jsonrpc_core_sgx as jsonrpc_core; -} - -pub mod api; -pub mod author; -pub mod client_error; -pub mod error; -pub mod top_filter; -pub mod traits; - -#[cfg(test)] -mod author_tests; - -#[cfg(test)] -mod test_fixtures; - -#[cfg(any(test, feature = "test"))] -pub mod test_utils; - -#[cfg(feature = "mocks")] -pub mod mocks; diff --git a/tee-worker/bitacross/core-primitives/top-pool-author/src/mocks.rs b/tee-worker/bitacross/core-primitives/top-pool-author/src/mocks.rs deleted file mode 100644 index 061852e9f9..0000000000 --- a/tee-worker/bitacross/core-primitives/top-pool-author/src/mocks.rs +++ /dev/null @@ -1,306 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -#[cfg(all(not(feature = "std"), feature = "sgx"))] -use crate::sgx_reexport_prelude::*; -use core::fmt::Debug; - -#[cfg(feature = "sgx")] -use std::sync::SgxRwLock as RwLock; - -#[cfg(feature = "std")] -use std::sync::RwLock; - -use crate::{ - error::Result, - traits::{AuthorApi, OnBlockImported}, -}; -use codec::{Decode, Encode}; -use itp_stf_primitives::{ - traits::TrustedCallVerification, - types::{AccountId, TrustedOperation as StfTrustedOperation, TrustedOperationOrHash}, -}; -use itp_top_pool::primitives::{PoolFuture, PoolStatus}; -use itp_types::{DecryptableRequest, ShardIdentifier}; -use jsonrpc_core::{futures::future::ready, Error as RpcError}; -use lazy_static::lazy_static; -use sp_core::{blake2_256, H256}; -#[cfg(feature = "sgx")] -use std::sync::SgxMutex as Mutex; -use std::{ - boxed::Box, - collections::HashMap, - marker::PhantomData, - sync::{mpsc::Sender, Arc}, - vec, - vec::Vec, -}; - -#[cfg(all(feature = "std", feature = "sgx"))] -compile_error!("feature \"std\" and feature \"sgx\" cannot be enabled at the same time"); - -#[cfg(feature = "std")] -use std::sync::Mutex; - -lazy_static! { - pub static ref GLOBAL_MOCK_AUTHOR_API: Arc>>>> = - Arc::new(Mutex::new(None)); -} - -#[derive(Default)] -pub struct AuthorApiMock -where - TCS: PartialEq + Encode + Decode + Debug + Send + Sync + TrustedCallVerification, - G: PartialEq + Encode + Decode + Debug + Send + Sync, -{ - tops: RwLock>>>, - _phantom: PhantomData<(Hash, BlockHash, TCS, G)>, - pub remove_attempts: RwLock, -} - -impl AuthorApiMock -where - TCS: PartialEq + Encode + Decode + Debug + Send + Sync + TrustedCallVerification, - G: PartialEq + Encode + Decode + Debug + Send + Sync, -{ - fn remove_top( - &self, - bytes_or_hash: Vec>, - shard: ShardIdentifier, - _inblock: bool, - ) -> Result> { - let hashes = bytes_or_hash - .into_iter() - .map(|x| match x { - TrustedOperationOrHash::Hash(h) => h, - TrustedOperationOrHash::OperationEncoded(bytes) => { - let top: StfTrustedOperation = - StfTrustedOperation::::decode(&mut bytes.as_slice()).unwrap(); - top.hash() - }, - TrustedOperationOrHash::Operation(op) => op.hash(), - }) - .collect::>(); - - let mut tops_lock = self.tops.write().unwrap(); - - match tops_lock.get_mut(&shard) { - Some(tops_encoded) => { - let removed_tops = tops_encoded - .drain_filter(|t| hashes.contains(&blake2_256(t).into())) - .map(|t| blake2_256(&t).into()) - .collect::>(); - Ok(removed_tops) - }, - None => Ok(Vec::new()), - } - } -} - -impl AuthorApi for AuthorApiMock -where - TCS: PartialEq + Encode + Decode + Debug + Clone + TrustedCallVerification + Send + Sync, - G: PartialEq + Encode + Decode + Debug + Clone + Send + Sync, -{ - fn submit_top(&self, req: R) -> PoolFuture { - let mut write_lock = self.tops.write().unwrap(); - let extrinsics = write_lock.entry(req.shard()).or_default(); - extrinsics.push(req.payload().to_vec()); - Box::pin(ready(Ok(H256::default()))) - } - - fn hash_of(&self, xt: &StfTrustedOperation) -> H256 { - xt.hash() - } - - fn pending_tops(&self, shard: ShardIdentifier) -> Result>> { - let extrinsics = self.tops.read().unwrap().get(&shard).cloned(); - Ok(extrinsics.unwrap_or_default()) - } - - fn get_pending_getters(&self, shard: ShardIdentifier) -> Vec> { - self.tops - .read() - .unwrap() - .get(&shard) - .map(|encoded_operations| { - let mut trusted_getters: Vec> = Vec::new(); - for encoded_operation in encoded_operations { - if let Ok(g) = G::decode(&mut encoded_operation.as_slice()) { - trusted_getters.push(StfTrustedOperation::::get(g)); - } - } - trusted_getters - }) - .unwrap_or_default() - } - - fn get_pending_trusted_calls( - &self, - shard: ShardIdentifier, - ) -> Vec> { - self.tops - .read() - .unwrap() - .get(&shard) - .map(|encoded_operations| { - let mut trusted_operations: Vec> = Vec::new(); - for encoded_operation in encoded_operations { - if let Ok(o) = StfTrustedOperation::decode(&mut encoded_operation.as_slice()) { - trusted_operations.push(o); - } - } - trusted_operations - }) - .unwrap_or_default() - } - - fn get_status(&self, shard: ShardIdentifier) -> PoolStatus { - self.tops - .read() - .unwrap() - .get(&shard) - .map(|encoded_operations| { - let mut trusted_operations: Vec> = Vec::new(); - for encoded_operation in encoded_operations { - if let Ok(o) = StfTrustedOperation::decode(&mut encoded_operation.as_slice()) { - trusted_operations.push(o); - } - } - PoolStatus { - ready: trusted_operations.len(), - ready_bytes: trusted_operations.encode().len(), - future: 0, - future_bytes: 0, - } - }) - .unwrap_or_default() - } - - fn get_pending_trusted_calls_for( - &self, - shard: ShardIdentifier, - account: &AccountId, - ) -> Vec> { - self.tops - .read() - .unwrap() - .get(&shard) - .map(|encoded_operations| { - let mut trusted_operations: Vec> = Vec::new(); - for encoded_operation in encoded_operations { - if let Ok(top) = StfTrustedOperation::decode(&mut encoded_operation.as_slice()) - { - if top.signed_caller_account().as_ref() == Some(account) { - trusted_operations.push(top); - } - } - } - trusted_operations - }) - .unwrap_or_default() - } - - fn get_shards(&self) -> Vec { - self.tops.read().unwrap().keys().cloned().collect() - } - - fn list_handled_shards(&self) -> Vec { - //dummy - self.tops.read().unwrap().keys().cloned().collect() - } - - fn remove_calls_from_pool( - &self, - shard: ShardIdentifier, - executed_calls: Vec<(TrustedOperationOrHash, bool)>, - ) -> Vec> { - let mut remove_attempts_lock = self.remove_attempts.write().unwrap(); - *remove_attempts_lock += 1; - - let mut failed_to_remove = Vec::new(); - for (executed_call, inblock) in executed_calls { - if self.remove_top(vec![executed_call.clone()], shard, inblock).is_err() { - failed_to_remove.push(executed_call); - } - } - failed_to_remove - } - - fn watch_top(&self, request: R) -> PoolFuture { - // Note: The below implementation is specific for litentry/core/stf-task/receiver/test.rs - let sender_guard = GLOBAL_MOCK_AUTHOR_API.lock().unwrap(); - let sender = &*sender_guard; - sender - .as_ref() - .expect("Not yet initialized") - .send(request.payload().to_vec()) - .unwrap(); - Box::pin(ready(Ok([0u8; 32].into()))) - } - - fn update_connection_state(&self, _updates: Vec<(H256, (Vec, bool))>) {} - - fn swap_rpc_connection_hash(&self, _old_hash: H256, _new_hash: H256) {} -} - -impl OnBlockImported for AuthorApiMock -where - TCS: PartialEq + Encode + Decode + Debug + Send + Sync + TrustedCallVerification, - G: PartialEq + Encode + Decode + Debug + Send + Sync, -{ - type Hash = H256; - - fn on_block_imported(&self, _hashes: &[Self::Hash], _block_hash: H256) {} -} - -#[cfg(test)] -mod tests { - - use super::*; - use crate::test_fixtures::shard_id; - use codec::Encode; - use futures::executor::block_on; - use itp_test::mock::stf_mock::{ - mock_top_indirect_trusted_call_signed, GetterMock, TrustedCallSignedMock, - }; - use itp_types::RsaRequest; - use std::vec; - - #[test] - fn submitted_tops_can_be_removed_again() { - let author = AuthorApiMock::::default(); - let shard = shard_id(); - let trusted_operation = mock_top_indirect_trusted_call_signed(); - - let _ = block_on(author.submit_top(RsaRequest::new(shard, trusted_operation.encode()))) - .unwrap(); - - assert_eq!(1, author.pending_tops(shard).unwrap().len()); - assert_eq!(1, author.get_pending_trusted_calls(shard).len()); - assert_eq!(0, author.get_pending_getters(shard).len()); - - let trusted_operation_or_hash = - TrustedOperationOrHash::::from_top( - trusted_operation.clone(), - ); - let removed_tops = author.remove_top(vec![trusted_operation_or_hash], shard, true).unwrap(); - - assert_eq!(1, removed_tops.len()); - assert!(author.tops.read().unwrap().get(&shard).unwrap().is_empty()); - } -} diff --git a/tee-worker/bitacross/core-primitives/top-pool-author/src/test_fixtures.rs b/tee-worker/bitacross/core-primitives/top-pool-author/src/test_fixtures.rs deleted file mode 100644 index d5c83341d5..0000000000 --- a/tee-worker/bitacross/core-primitives/top-pool-author/src/test_fixtures.rs +++ /dev/null @@ -1,26 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use codec::Encode; -use itp_stf_primitives::types::ShardIdentifier; - -use sp_runtime::traits::{BlakeTwo256, Hash}; -use std::vec; - -pub(crate) fn shard_id() -> ShardIdentifier { - BlakeTwo256::hash(vec![1u8, 2u8, 3u8].as_slice().encode().as_slice()) -} diff --git a/tee-worker/bitacross/core-primitives/top-pool-author/src/test_utils.rs b/tee-worker/bitacross/core-primitives/top-pool-author/src/test_utils.rs deleted file mode 100644 index 20f8bd0dd7..0000000000 --- a/tee-worker/bitacross/core-primitives/top-pool-author/src/test_utils.rs +++ /dev/null @@ -1,49 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -#[cfg(all(not(feature = "std"), feature = "sgx"))] -use crate::sgx_reexport_prelude::*; - -use crate::traits::AuthorApi; -use codec::Encode; -use itp_sgx_crypto::ShieldingCryptoEncrypt; -use itp_stf_primitives::types::{ShardIdentifier, TrustedOperation as StfTrustedOperation}; -use itp_types::RsaRequest; -use jsonrpc_core::futures::executor; -use sp_core::H256; -use std::fmt::Debug; - -/// Test utility function to submit a trusted operation on an RPC author -pub fn submit_operation_to_top_pool( - author: &R, - top: &StfTrustedOperation, - shielding_key: &S, - shard: ShardIdentifier, -) -> Result<(H256, RsaRequest), jsonrpc_core::Error> -where - R: AuthorApi, - S: ShieldingCryptoEncrypt, - S::Error: Debug, - TCS: PartialEq + Encode + Debug + Send + Sync, - G: PartialEq + Encode + Debug + Send + Sync, -{ - let top_encrypted = shielding_key.encrypt(&top.encode()).unwrap(); - let submit_future = - async { author.watch_top(RsaRequest::new(shard, top_encrypted.clone())).await }; - let hash = executor::block_on(submit_future)?; - Ok((hash, RsaRequest::new(shard, top_encrypted))) -} diff --git a/tee-worker/bitacross/core-primitives/top-pool-author/src/top_filter.rs b/tee-worker/bitacross/core-primitives/top-pool-author/src/top_filter.rs deleted file mode 100644 index 25b3574870..0000000000 --- a/tee-worker/bitacross/core-primitives/top-pool-author/src/top_filter.rs +++ /dev/null @@ -1,320 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use codec::Encode; -use core::{fmt::Debug, marker::PhantomData}; -use itp_stf_primitives::types::TrustedOperation as StfTrustedOperation; - -/// Trait for filtering values -/// -/// Returns `Some` if a value should be included and `None` if discarded -pub trait Filter { - type Value; - - fn filter(&self, value: &Self::Value) -> bool; -} - -/// Filter for calls only (no getters). -pub struct CallsOnlyFilter { - _phantom: PhantomData<(TCS, G)>, -} - -impl CallsOnlyFilter { - pub fn new() -> Self { - Self { _phantom: Default::default() } - } -} - -impl Default for CallsOnlyFilter { - fn default() -> Self { - Self::new() - } -} - -impl Filter for CallsOnlyFilter -where - TCS: PartialEq + Encode + Debug, - G: PartialEq + Encode + Debug, -{ - type Value = StfTrustedOperation; - - fn filter(&self, value: &Self::Value) -> bool { - matches!(value, Self::Value::direct_call(_)) - || matches!(value, Self::Value::indirect_call(_)) - } -} - -/// Filter for direct calls only. -pub struct DirectCallsOnlyFilter { - _phantom: PhantomData<(TCS, G)>, -} - -impl DirectCallsOnlyFilter { - pub fn new() -> Self { - Self { _phantom: Default::default() } - } -} - -impl Default for DirectCallsOnlyFilter { - fn default() -> Self { - Self::new() - } -} - -impl Filter for DirectCallsOnlyFilter -where - TCS: PartialEq + Encode + Debug, - G: PartialEq + Encode + Debug, -{ - type Value = StfTrustedOperation; - - fn filter(&self, value: &Self::Value) -> bool { - matches!(value, Self::Value::direct_call(_)) - } -} - -/// Filter that allows all TOPs (i.e. not filter at all) -pub struct AllowAllTopsFilter { - _phantom: PhantomData<(TCS, G)>, -} - -impl AllowAllTopsFilter { - pub fn new() -> Self { - Self { _phantom: Default::default() } - } -} - -impl Default for AllowAllTopsFilter { - fn default() -> Self { - Self::new() - } -} - -impl Filter for AllowAllTopsFilter -where - TCS: PartialEq + Encode + Debug, - G: PartialEq + Encode + Debug, -{ - type Value = StfTrustedOperation; - - fn filter(&self, _value: &Self::Value) -> bool { - true - } -} - -/// Filter that allows only trusted getters -pub struct GettersOnlyFilter { - _phantom: PhantomData<(TCS, G)>, -} - -impl GettersOnlyFilter { - pub fn new() -> Self { - Self { _phantom: Default::default() } - } -} - -impl Default for GettersOnlyFilter { - fn default() -> Self { - Self::new() - } -} - -impl Filter for GettersOnlyFilter -where - TCS: PartialEq + Encode + Debug, - G: PartialEq + Encode + Debug, -{ - type Value = StfTrustedOperation; - - fn filter(&self, value: &Self::Value) -> bool { - matches!(value, Self::Value::get(_)) - } -} - -/// Filter for indirect calls only (no getters, no direct calls). -pub struct IndirectCallsOnlyFilter { - _phantom: PhantomData<(TCS, G)>, -} - -impl IndirectCallsOnlyFilter { - pub fn new() -> Self { - Self { _phantom: Default::default() } - } -} - -impl Default for IndirectCallsOnlyFilter { - fn default() -> Self { - Self::new() - } -} - -impl Filter for IndirectCallsOnlyFilter -where - TCS: PartialEq + Encode + Debug, - G: PartialEq + Encode + Debug, -{ - type Value = StfTrustedOperation; - - fn filter(&self, value: &Self::Value) -> bool { - matches!(value, Self::Value::indirect_call(_)) - } -} - -/// Filter that allows no direct calls, only indirect and getters. -pub struct NoDirectCallsFilter { - _phantom: PhantomData<(TCS, G)>, -} - -impl NoDirectCallsFilter { - pub fn new() -> Self { - Self { _phantom: Default::default() } - } -} - -impl Default for NoDirectCallsFilter { - fn default() -> Self { - Self::new() - } -} - -impl Filter for NoDirectCallsFilter -where - TCS: PartialEq + Encode + Debug, - G: PartialEq + Encode + Debug, -{ - type Value = StfTrustedOperation; - - fn filter(&self, value: &Self::Value) -> bool { - !matches!(value, Self::Value::direct_call(_)) - } -} - -/// Filter to deny all trusted operations. -pub struct DenyAllFilter { - _phantom: PhantomData<(TCS, G)>, -} - -impl DenyAllFilter { - pub fn new() -> Self { - Self { _phantom: Default::default() } - } -} - -impl Default for DenyAllFilter { - fn default() -> Self { - Self::new() - } -} - -impl Filter for DenyAllFilter -where - TCS: PartialEq + Encode + Debug, - G: PartialEq + Encode + Debug, -{ - type Value = StfTrustedOperation; - - fn filter(&self, _value: &Self::Value) -> bool { - false - } -} - -#[cfg(test)] -mod tests { - - use super::*; - - use itp_test::mock::stf_mock::{ - mock_top_direct_trusted_call_signed, mock_top_indirect_trusted_call_signed, - mock_top_trusted_getter_signed, - }; - - use std::string::{String, ToString}; - - #[test] - fn filter_returns_none_if_values_is_filtered_out() { - struct WorldFilter; - impl Filter for WorldFilter { - type Value = String; - - fn filter(&self, value: &Self::Value) -> bool { - if value.eq(&String::from("world")) { - return true - } - false - } - } - - let filter = WorldFilter; - - assert!(!filter.filter(&"hello".to_string())); - assert!(filter.filter(&"world".to_string())); - } - - #[test] - fn allow_all_tops_filter_works() { - let filter = AllowAllTopsFilter::new(); - - assert!(filter.filter(&mock_top_trusted_getter_signed())); - assert!(filter.filter(&mock_top_indirect_trusted_call_signed())); - assert!(filter.filter(&mock_top_direct_trusted_call_signed())); - } - - #[test] - fn getters_only_filter_works() { - let filter = GettersOnlyFilter::new(); - - assert!(filter.filter(&mock_top_trusted_getter_signed())); - assert!(!filter.filter(&mock_top_indirect_trusted_call_signed())); - assert!(!filter.filter(&mock_top_direct_trusted_call_signed())); - } - - #[test] - fn no_direct_calls_filter_works() { - let filter = NoDirectCallsFilter::new(); - - assert!(!filter.filter(&mock_top_direct_trusted_call_signed())); - assert!(filter.filter(&mock_top_indirect_trusted_call_signed())); - assert!(filter.filter(&mock_top_trusted_getter_signed())); - } - - #[test] - fn indirect_calls_only_filter_works() { - let filter = IndirectCallsOnlyFilter::new(); - - assert!(!filter.filter(&mock_top_direct_trusted_call_signed())); - assert!(filter.filter(&mock_top_indirect_trusted_call_signed())); - assert!(!filter.filter(&mock_top_trusted_getter_signed())); - } - - #[test] - fn calls_only_filter_works() { - let filter = CallsOnlyFilter::new(); - - assert!(filter.filter(&mock_top_direct_trusted_call_signed())); - assert!(filter.filter(&mock_top_indirect_trusted_call_signed())); - assert!(!filter.filter(&mock_top_trusted_getter_signed())); - } - - #[test] - fn direct_calls_only_filter_works() { - let filter = DirectCallsOnlyFilter::new(); - - assert!(filter.filter(&mock_top_direct_trusted_call_signed())); - assert!(!filter.filter(&mock_top_indirect_trusted_call_signed())); - assert!(!filter.filter(&mock_top_trusted_getter_signed())); - } -} diff --git a/tee-worker/bitacross/core-primitives/top-pool-author/src/traits.rs b/tee-worker/bitacross/core-primitives/top-pool-author/src/traits.rs deleted file mode 100644 index 132245d404..0000000000 --- a/tee-worker/bitacross/core-primitives/top-pool-author/src/traits.rs +++ /dev/null @@ -1,102 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -#[cfg(all(not(feature = "std"), feature = "sgx"))] -use crate::sgx_reexport_prelude::*; -use codec::Encode; -use core::fmt::Debug; - -use crate::error::Result; -use itp_stf_primitives::types::{ - AccountId, TrustedOperation as StfTrustedOperation, TrustedOperationOrHash, -}; -use itp_top_pool::primitives::{PoolFuture, PoolStatus}; -use itp_types::{BlockHash as SidechainBlockHash, DecryptableRequest, ShardIdentifier, H256}; -use jsonrpc_core::Error as RpcError; -use std::vec::Vec; - -/// Trait alias for a full STF author API -pub trait FullAuthor< - TCS: PartialEq + Encode + Debug + Send + Sync + 'static, - G: PartialEq + Encode + Debug + Send + Sync + 'static, -> = AuthorApi + OnBlockImported + Send + Sync + 'static; - -/// Authoring RPC API -pub trait AuthorApi -where - TCS: PartialEq + Encode + Debug + Send + Sync, - G: PartialEq + Encode + Debug + Send + Sync, -{ - /// Submit encoded extrinsic for inclusion in block. - fn submit_top(&self, req: R) -> PoolFuture; - - /// Return hash of Trusted Operation - fn hash_of(&self, xt: &StfTrustedOperation) -> Hash; - - /// Returns all pending operations, potentially grouped by sender. - fn pending_tops(&self, shard: ShardIdentifier) -> Result>>; - - /// Returns all pending trusted getters. - fn get_pending_getters(&self, shard: ShardIdentifier) -> Vec>; - - /// Returns all pending trusted calls (in ready state). - fn get_pending_trusted_calls(&self, shard: ShardIdentifier) - -> Vec>; - - /// Returns pool status - fn get_status(&self, shard: ShardIdentifier) -> PoolStatus; - - /// Returns all pending trusted calls for a given `account` - fn get_pending_trusted_calls_for( - &self, - shard: ShardIdentifier, - account: &AccountId, - ) -> Vec>; - - /// returns all shards which are currently present in the tops in the pool - fn get_shards(&self) -> Vec; - - /// returns all shards which are handled by our worker - fn list_handled_shards(&self) -> Vec; - - /// Remove a collection of trusted operations from the pool. - /// Return operations that were not successfully removed. - fn remove_calls_from_pool( - &self, - shard: ShardIdentifier, - executed_calls: Vec<(TrustedOperationOrHash, bool)>, - ) -> Vec>; - - /// Submit a request to watch. - /// - /// See [`TrustedOperationStatus`](sp_transaction_pool::TrustedOperationStatus) for details on transaction - /// life cycle. - fn watch_top(&self, request: R) -> PoolFuture; - - /// Litentry: set the rpc response value - fn update_connection_state(&self, updates: Vec<(Hash, (Vec, bool))>); - - /// Litentry: swap the old hash with the new one in rpc connection registry - fn swap_rpc_connection_hash(&self, old_hash: Hash, new_hash: Hash); -} - -/// Trait to notify listeners/observer of a newly created block -pub trait OnBlockImported { - type Hash; - - fn on_block_imported(&self, hashes: &[Self::Hash], block_hash: SidechainBlockHash); -} diff --git a/tee-worker/bitacross/core-primitives/top-pool/Cargo.toml b/tee-worker/bitacross/core-primitives/top-pool/Cargo.toml deleted file mode 100644 index fda8d7cc4f..0000000000 --- a/tee-worker/bitacross/core-primitives/top-pool/Cargo.toml +++ /dev/null @@ -1,55 +0,0 @@ -[package] -name = "bc-itp-top-pool" -version = "0.1.0" -authors = ['Trust Computing GmbH ', 'Integritee AG '] -edition = "2021" - -[dependencies] -sgx_tstd = { workspace = true, features = ["net", "thread", "untrusted_time"], optional = true } - -itc-direct-rpc-server = { package = "bc-itc-direct-rpc-server", path = "../../core/direct-rpc-server", default-features = false } -itp-stf-primitives = { workspace = true } -itp-types = { workspace = true } - -jsonrpc-core_sgx = { workspace = true, optional = true } -linked-hash-map_sgx = { workspace = true, optional = true } - -jsonrpc-core = { workspace = true, optional = true } -linked-hash-map = { workspace = true, optional = true } - -byteorder = { workspace = true } -codec = { package = "parity-scale-codec", workspace = true } -derive_more = { workspace = true } -log = { workspace = true } -sp-core = { workspace = true, features = ["full_crypto"] } -sp-runtime = { workspace = true } - -[dev-dependencies] -parity-util-mem = { workspace = true, features = ["primitive-types"] } -itp-test = { workspace = true } -serde = { workspace = true } -sp-application-crypto = { workspace = true } -litentry-primitives = { workspace = true } - -[features] -default = ["std"] -sgx = [ - "sgx_tstd", - "itc-direct-rpc-server/sgx", - "jsonrpc-core_sgx", - "linked-hash-map_sgx", - "litentry-primitives/sgx", -] -std = [ - "itc-direct-rpc-server/std", - "itp-types/std", - "jsonrpc-core", - "linked-hash-map", - "log/std", - "serde/std", - "sp-core/std", - "sp-runtime/std", - "sp-application-crypto/std", - "litentry-primitives/std", -] -mocks = [] diff --git a/tee-worker/bitacross/core-primitives/top-pool/src/base_pool.rs b/tee-worker/bitacross/core-primitives/top-pool/src/base_pool.rs deleted file mode 100644 index a6cb0628a0..0000000000 --- a/tee-worker/bitacross/core-primitives/top-pool/src/base_pool.rs +++ /dev/null @@ -1,1379 +0,0 @@ -// This file is part of Substrate. - -// Copyright (C) 2018-2021 Parity Technologies (UK) Ltd. -// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 - -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with this program. If not, see . - -//! A basic version of the dependency graph. -//! -//! For a more full-featured pool, have a look at the `pool` module. - -pub extern crate alloc; -use crate::{ - error, - future::{FutureTrustedOperations, WaitingTrustedOperations}, - primitives::{InPoolOperation, PoolStatus, TrustedOperationSource as Source, TxHash}, - ready::ReadyOperations, -}; -use alloc::{fmt, sync::Arc, vec, vec::Vec}; -use core::iter; -use itp_stf_primitives::types::ShardIdentifier; -use log::{debug, trace, warn}; -use sp_core::hexdisplay::HexDisplay; -use sp_runtime::transaction_validity::{ - TransactionLongevity as Longevity, TransactionPriority as Priority, TransactionTag as Tag, -}; -use std::collections::HashSet; - -/// Successful import result. -#[derive(Debug, PartialEq, Eq)] -pub enum Imported { - /// TrustedOperation was successfully imported to Ready queue. - Ready { - /// Hash of operation that was successfully imported. - hash: TxHash, - /// operations that got promoted from the Future queue. - promoted: Vec, - /// operations that failed to be promoted from the Future queue and are now discarded. - failed: Vec, - /// operations removed from the Ready pool (replaced). - removed: Vec>>, - }, - /// TrustedOperation was successfully imported to Future queue. - Future { - /// Hash of operation that was successfully imported. - hash: TxHash, - }, -} - -impl Imported { - /// Returns the hash of imported operation. - pub fn hash(&self) -> &TxHash { - use self::Imported::*; - match *self { - Ready { ref hash, .. } => hash, - Future { ref hash, .. } => hash, - } - } -} - -/// Status of pruning the queue. -#[derive(Debug)] -pub struct PruneStatus { - /// A list of imports that satisfying the tag triggered. - pub promoted: Vec>, - /// A list of operations that failed to be promoted and now are discarded. - pub failed: Vec, - /// A list of operations that got pruned from the ready queue. - pub pruned: Vec>>, -} - -/// Immutable operation -#[derive(PartialEq, Eq, Clone)] -pub struct TrustedOperation { - /// Raw extrinsic representing that operation. - pub data: Extrinsic, - /// Number of bytes encoding of the operation requires. - pub bytes: usize, - /// TrustedOperation hash (unique) - pub hash: TxHash, - /// TrustedOperation priority (higher = better) - pub priority: Priority, - /// At which block the operation becomes invalid? - pub valid_till: Longevity, - /// Tags required by the operation. - pub requires: Vec, - /// Tags that this operation provides. - pub provides: Vec, - /// Should that operation be propagated. - pub propagate: bool, - /// Source of that operation. - pub source: Source, -} - -impl AsRef for TrustedOperation { - fn as_ref(&self) -> &Extrinsic { - &self.data - } -} - -impl InPoolOperation for TrustedOperation { - type TrustedOperation = Extrinsic; - - fn data(&self) -> &Extrinsic { - &self.data - } - - fn hash(&self) -> TxHash { - self.hash - } - - fn priority(&self) -> &Priority { - &self.priority - } - - fn longevity(&self) -> &Longevity { - &self.valid_till - } - - fn requires(&self) -> &[Tag] { - &self.requires - } - - fn provides(&self) -> &[Tag] { - &self.provides - } - - fn is_propagable(&self) -> bool { - self.propagate - } -} - -impl TrustedOperation { - /// Explicit operation clone. - /// - /// TrustedOperation should be cloned only if absolutely necessary && we want - /// every reason to be commented. That's why we `TrustedOperation` is not `Clone`, - /// but there's explicit `duplicate` method. - pub fn duplicate(&self) -> Self { - TrustedOperation { - data: self.data.clone(), - bytes: self.bytes, - hash: self.hash, - priority: self.priority, - source: self.source, - valid_till: self.valid_till, - requires: self.requires.clone(), - provides: self.provides.clone(), - propagate: self.propagate, - } - } -} - -impl fmt::Debug for TrustedOperation -where - Extrinsic: fmt::Debug, -{ - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - fn print_tags(fmt: &mut fmt::Formatter, tags: &[Tag]) -> fmt::Result { - let mut it = tags.iter(); - if let Some(t) = it.next() { - write!(fmt, "{}", HexDisplay::from(t))?; - } - for t in it { - write!(fmt, ",{}", HexDisplay::from(t))?; - } - Ok(()) - } - - write!(fmt, "TrustedOperation {{ ")?; - write!(fmt, "hash: {:?}, ", &self.hash)?; - write!(fmt, "priority: {:?}, ", &self.priority)?; - write!(fmt, "valid_till: {:?}, ", &self.valid_till)?; - write!(fmt, "bytes: {:?}, ", &self.bytes)?; - write!(fmt, "propagate: {:?}, ", &self.propagate)?; - write!(fmt, "source: {:?}, ", &self.source)?; - write!(fmt, "requires: [")?; - print_tags(fmt, &self.requires)?; - write!(fmt, "], provides: [")?; - print_tags(fmt, &self.provides)?; - write!(fmt, "], ")?; - write!(fmt, "data: {:?}", &self.data)?; - write!(fmt, "}}")?; - Ok(()) - } -} - -/// Store last pruned tags for given number of invocations. -const RECENTLY_PRUNED_TAGS: usize = 2; - -/// TrustedOperation pool. -/// -/// Builds a dependency graph for all operations in the pool and returns -/// the ones that are currently ready to be executed. -/// -/// General note: -/// If function returns some operations it usually means that importing them -/// as-is for the second time will fail or produce unwanted results. -/// Most likely it is required to revalidate them and recompute set of -/// required tags. -#[derive(Debug)] -pub struct BasePool { - reject_future_operations: bool, - future: FutureTrustedOperations, - ready: ReadyOperations, - /// Store recently pruned tags (for last two invocations). - /// - /// This is used to make sure we don't accidentally put - /// operations to future in case they were just stuck in verification. - recently_pruned: [HashSet; RECENTLY_PRUNED_TAGS], - recently_pruned_index: usize, -} - -impl Default for BasePool { - fn default() -> Self { - Self::new(false) - } -} - -impl BasePool { - /// Create new pool given reject_future_operations flag. - pub fn new(reject_future_operations: bool) -> Self { - BasePool { - reject_future_operations, - future: Default::default(), - ready: Default::default(), - recently_pruned: Default::default(), - recently_pruned_index: 0, - } - } - - /// Temporary enables future operations, runs closure and then restores - /// `reject_future_operations` flag back to previous value. - /// - /// The closure accepts the mutable reference to the pool and original value - /// of the `reject_future_operations` flag. - pub(crate) fn with_futures_enabled( - &mut self, - closure: impl FnOnce(&mut Self, bool) -> T, - ) -> T { - let previous = self.reject_future_operations; - self.reject_future_operations = false; - let return_value = closure(self, previous); - self.reject_future_operations = previous; - return_value - } - - /// Returns if the operation for the given hash is already imported. - pub fn is_imported(&self, tx_hash: &TxHash, shard: ShardIdentifier) -> bool { - self.future.contains(tx_hash, shard) || self.ready.contains(tx_hash, shard) - } - - /// Imports operations to the pool. - /// - /// The pool consists of two parts: Future and Ready. - /// The former contains operations that require some tags that are not yet provided by - /// other operations in the pool. - /// The latter contains operations that have all the requirements satisfied and are - /// ready to be included in the block. - pub fn import( - &mut self, - tx: TrustedOperation, - shard: ShardIdentifier, - ) -> error::Result> { - if self.is_imported(&tx.hash, shard) { - return Err(error::Error::AlreadyImported) - } - - let tx = WaitingTrustedOperations::new( - tx, - self.ready.provided_tags(shard), - &self.recently_pruned, - ); - trace!(target: "txpool", "[{:?}] {:?}", tx.operation.hash, tx); - debug!( - target: "txpool", - "[{:?}] Importing to {}", - tx.operation.hash, - if tx.is_ready() { "ready" } else { "future" } - ); - - // If all tags are not satisfied import to future. - if !tx.is_ready() { - if self.reject_future_operations { - return Err(error::Error::RejectedFutureTrustedOperation) - } - - let hash = tx.operation.hash; - self.future.import(tx, shard); - return Ok(Imported::Future { hash }) - } - - self.import_to_ready(tx, shard) - } - - /// Imports operations to ready queue. - /// - /// NOTE the operation has to have all requirements satisfied. - fn import_to_ready( - &mut self, - tx: WaitingTrustedOperations, - shard: ShardIdentifier, - ) -> error::Result> { - let hash = tx.operation.hash; - let mut promoted = vec![]; - let mut failed = vec![]; - let mut removed = vec![]; - - let mut first = true; - let mut to_import = vec![tx]; - - while let Some(tx) = to_import.pop() { - // find operation in Future that it unlocks - to_import.append(&mut self.future.satisfy_tags(&tx.operation.provides, shard)); - - // import this operation - let current_hash = tx.operation.hash; - match self.ready.import(tx, shard) { - Ok(mut replaced) => { - if !first { - promoted.push(current_hash); - } - // The operations were removed from the ready pool. We might attempt to re-import them. - removed.append(&mut replaced); - }, - // operation failed to be imported. - Err(e) => - if first { - debug!(target: "txpool", "[{:?}] Error importing", current_hash,); - return Err(e) - } else { - failed.push(current_hash); - }, - } - first = false; - } - - // An edge case when importing operation caused - // some future operations to be imported and that - // future operations pushed out current operation. - // This means that there is a cycle and the operations should - // be moved back to future, since we can't resolve it. - if removed.iter().any(|tx| tx.hash == hash) { - // We still need to remove all operations that we promoted - // since they depend on each other and will never get to the best iterator. - self.ready.remove_subtree(&promoted, shard); - - debug!(target: "txpool", "[{:?}] Cycle detected, bailing.", hash); - return Err(error::Error::CycleDetected) - } - - Ok(Imported::Ready { hash, promoted, failed, removed }) - } - - /// Returns an iterator over ready operations in the pool. - pub fn ready(&self, shard: ShardIdentifier) -> impl Iterator>> { - self.ready.get(shard) - } - - /// Returns an iterator over all shards in the pool. - pub fn get_shards(&self) -> impl Iterator { - self.ready.get_shards() - } - - /// Returns an iterator over future operations in the pool. - pub fn futures(&self, shard: ShardIdentifier) -> impl Iterator> { - self.future.all(shard) - } - - /// Returns pool operations given list of hashes. - /// - /// Includes both ready and future pool. For every hash in the `hashes` - /// iterator an `Option` is produced (so the resulting `Vec` always have the same length). - pub fn by_hashes( - &self, - hashes: &[TxHash], - shard: ShardIdentifier, - ) -> Vec>>> { - let ready = self.ready.by_hashes(hashes, shard); - let future = self.future.by_hashes(hashes, shard); - - ready.into_iter().zip(future).map(|(a, b)| a.or(b)).collect() - } - - /// Returns pool operation by hash. - pub fn ready_by_hash( - &self, - hash: &TxHash, - shard: ShardIdentifier, - ) -> Option>> { - self.ready.by_hash(hash, shard) - } - - /// Makes sure that the operations in the queues stay within provided limits. - /// - /// Removes and returns worst operations from the queues and all operations that depend on them. - /// Technically the worst operation should be evaluated by computing the entire pending set. - /// We use a simplified approach to remove the operation that occupies the pool for the longest time. - pub fn enforce_limits( - &mut self, - ready: &Limit, - future: &Limit, - shard: ShardIdentifier, - ) -> Vec>> { - let mut removed = vec![]; - - while ready.is_exceeded(self.ready.len(shard), self.ready.bytes(shard)) { - // find the worst operation - let minimal = self.ready.fold( - |minimal, current| { - let operation = ¤t.operation; - match minimal { - None => Some(operation.clone()), - Some(ref tx) if tx.insertion_id > operation.insertion_id => - Some(operation.clone()), - other => other, - } - }, - shard, - ); - - if let Some(minimal) = minimal { - removed.append(&mut self.remove_subtree(&[minimal.operation.hash], shard)) - } else { - break - } - } - - while future.is_exceeded(self.future.len(shard), self.future.bytes(shard)) { - // find the worst operation - let minimal = self.future.fold( - |minimal, current| { - match minimal { - None => Some(current.clone()), - /*Some(ref tx) if tx.imported_at > current.imported_at => { - Some(current.clone()) - },*/ - other => other, - } - }, - shard, - ); - - if let Some(minimal) = minimal { - removed.append(&mut self.remove_subtree(&[minimal.operation.hash], shard)) - } else { - break - } - } - - removed - } - - /// Removes all operations represented by the hashes and all other operations - /// that depend on them. - /// - /// Returns a list of actually removed operations. - /// NOTE some operations might still be valid, but were just removed because - /// they were part of a chain, you may attempt to re-import them later. - /// NOTE If you want to remove ready operations that were already used - /// and you don't want them to be stored in the pool use `prune_tags` method. - pub fn remove_subtree( - &mut self, - hashes: &[TxHash], - shard: ShardIdentifier, - ) -> Vec>> { - let mut removed = self.ready.remove_subtree(hashes, shard); - removed.extend(self.future.remove(hashes, shard)); - removed - } - - /// Removes and returns all operations from the future queue. - pub fn clear_future(&mut self, shard: ShardIdentifier) -> Vec>> { - self.future.clear(shard) - } - - /// Prunes operations that provide given list of tags. - /// - /// This will cause all operations that provide these tags to be removed from the pool, - /// but unlike `remove_subtree`, dependent operations are not touched. - /// Additional operations from future queue might be promoted to ready if you satisfy tags - /// that the pool didn't previously know about. - pub fn prune_tags( - &mut self, - tags: impl IntoIterator, - shard: ShardIdentifier, - ) -> PruneStatus { - let mut to_import = vec![]; - let mut pruned = vec![]; - let recently_pruned = &mut self.recently_pruned[self.recently_pruned_index]; - self.recently_pruned_index = (self.recently_pruned_index + 1) % RECENTLY_PRUNED_TAGS; - recently_pruned.clear(); - - for tag in tags { - // make sure to promote any future operations that could be unlocked - to_import.append(&mut self.future.satisfy_tags(iter::once(&tag), shard)); - // and actually prune operations in ready queue - pruned.append(&mut self.ready.prune_tags(tag.clone(), shard)); - // store the tags for next submission - recently_pruned.insert(tag); - } - - let mut promoted = vec![]; - let mut failed = vec![]; - for tx in to_import { - let hash = tx.operation.hash; - match self.import_to_ready(tx, shard) { - Ok(res) => promoted.push(res), - Err(_e) => { - warn!(target: "txpool", "[{:?}] Failed to promote during pruning", hash); - failed.push(hash) - }, - } - } - - PruneStatus { promoted, failed, pruned } - } - - /// Get pool status. - pub fn status(&self, shard: ShardIdentifier) -> PoolStatus { - PoolStatus { - ready: self.ready.len(shard), - ready_bytes: self.ready.bytes(shard), - future: self.future.len(shard), - future_bytes: self.future.bytes(shard), - } - } -} - -/// Queue limits -#[derive(Debug, Clone)] -pub struct Limit { - /// Maximal number of operations in the queue. - pub count: usize, - /// Maximal size of encodings of all operations in the queue. - pub total_bytes: usize, -} - -impl Limit { - /// Returns true if any of the provided values exceeds the limit. - pub fn is_exceeded(&self, count: usize, bytes: usize) -> bool { - self.count < count || self.total_bytes < bytes - } -} - -#[cfg(test)] -pub mod tests { - - use super::*; - use alloc::borrow::ToOwned; - use itp_types::H256; - - fn hash(index: u8) -> H256 { - [index; 32].into() - } - - fn test_pool() -> BasePool> { - BasePool::default() - } - - #[test] - pub fn test_should_import_transaction_to_ready() { - // given - let mut pool = test_pool(); - let shard = ShardIdentifier::default(); - - // when - pool.import( - TrustedOperation { - data: vec![1u8], - bytes: 1, - hash: hash(1), - priority: 5u64, - valid_till: 64u64, - requires: vec![], - provides: vec![vec![1]], - propagate: true, - source: Source::External, - }, - shard, - ) - .unwrap(); - - // then - assert_eq!(pool.ready(shard).count(), 1); - assert_eq!(pool.ready.len(shard), 1); - } - - #[test] - pub fn test_should_not_import_same_transaction_twice() { - // given - let mut pool = test_pool(); - let shard = ShardIdentifier::default(); - - // when - pool.import( - TrustedOperation { - data: vec![1u8], - bytes: 1, - hash: hash(1), - priority: 5u64, - valid_till: 64u64, - requires: vec![], - provides: vec![vec![1]], - propagate: true, - source: Source::External, - }, - shard, - ) - .unwrap(); - pool.import( - TrustedOperation { - data: vec![1u8], - bytes: 1, - hash: hash(1), - priority: 5u64, - valid_till: 64u64, - requires: vec![], - provides: vec![vec![1]], - propagate: true, - source: Source::External, - }, - shard, - ) - .unwrap_err(); - - // then - assert_eq!(pool.ready(shard).count(), 1); - assert_eq!(pool.ready.len(shard), 1); - } - - #[test] - pub fn test_should_import_transaction_to_future_and_promote_it_later() { - // given - let mut pool = test_pool(); - let shard = ShardIdentifier::default(); - - // when - pool.import( - TrustedOperation { - data: vec![1u8], - bytes: 1, - hash: hash(1), - priority: 5u64, - valid_till: 64u64, - requires: vec![vec![0]], - provides: vec![vec![1]], - propagate: true, - source: Source::External, - }, - shard, - ) - .unwrap(); - assert_eq!(pool.ready(shard).count(), 0); - assert_eq!(pool.ready.len(shard), 0); - pool.import( - TrustedOperation { - data: vec![2u8], - bytes: 1, - hash: hash(2), - priority: 5u64, - valid_till: 64u64, - requires: vec![], - provides: vec![vec![0]], - propagate: true, - source: Source::External, - }, - shard, - ) - .unwrap(); - - // then - assert_eq!(pool.ready(shard).count(), 2); - assert_eq!(pool.ready.len(shard), 2); - } - - #[test] - pub fn test_should_promote_a_subgraph() { - // given - let mut pool = test_pool(); - let shard = ShardIdentifier::default(); - - // when - pool.import( - TrustedOperation { - data: vec![1u8], - bytes: 1, - hash: hash(1), - priority: 5u64, - valid_till: 64u64, - requires: vec![vec![0]], - provides: vec![vec![1]], - propagate: true, - source: Source::External, - }, - shard, - ) - .unwrap(); - pool.import( - TrustedOperation { - data: vec![3u8], - bytes: 1, - hash: hash(3), - priority: 5u64, - valid_till: 64u64, - requires: vec![vec![2]], - provides: vec![], - propagate: true, - source: Source::External, - }, - shard, - ) - .unwrap(); - pool.import( - TrustedOperation { - data: vec![2u8], - bytes: 1, - hash: hash(2), - priority: 5u64, - valid_till: 64u64, - requires: vec![vec![1]], - provides: vec![vec![3], vec![2]], - propagate: true, - source: Source::External, - }, - shard, - ) - .unwrap(); - pool.import( - TrustedOperation { - data: vec![4u8], - bytes: 1, - hash: hash(4), - priority: 1_000u64, - valid_till: 64u64, - requires: vec![vec![3], vec![4]], - provides: vec![], - propagate: true, - source: Source::External, - }, - shard, - ) - .unwrap(); - assert_eq!(pool.ready(shard).count(), 0); - assert_eq!(pool.ready.len(shard), 0); - - let res = pool - .import( - TrustedOperation { - data: vec![5u8], - bytes: 1, - hash: hash(5), - priority: 5u64, - valid_till: 64u64, - requires: vec![], - provides: vec![vec![0], vec![4]], - propagate: true, - source: Source::External, - }, - shard, - ) - .unwrap(); - - // then - let mut it = pool.ready(shard).into_iter().map(|tx| tx.data[0]); - - assert_eq!(it.next(), Some(5)); - assert_eq!(it.next(), Some(1)); - assert_eq!(it.next(), Some(2)); - assert_eq!(it.next(), Some(4)); - assert_eq!(it.next(), Some(3)); - assert_eq!(it.next(), None); - assert_eq!( - res, - Imported::Ready { - hash: hash(5), - promoted: vec![hash(1), hash(2), hash(3), hash(4)], - failed: vec![], - removed: vec![] - } - ); - } - - #[test] - pub fn test_should_handle_a_cycle() { - // given - let shard = ShardIdentifier::default(); - let mut pool = test_pool(); - pool.import( - TrustedOperation { - data: vec![1u8], - bytes: 1, - hash: hash(1), - priority: 5u64, - valid_till: 64u64, - requires: vec![vec![0]], - provides: vec![vec![1]], - propagate: true, - source: Source::External, - }, - shard, - ) - .unwrap(); - pool.import( - TrustedOperation { - data: vec![3u8], - bytes: 1, - hash: hash(3), - priority: 5u64, - valid_till: 64u64, - requires: vec![vec![1]], - provides: vec![vec![2]], - propagate: true, - source: Source::External, - }, - shard, - ) - .unwrap(); - assert_eq!(pool.ready(shard).count(), 0); - assert_eq!(pool.ready.len(shard), 0); - - // when - pool.import( - TrustedOperation { - data: vec![2u8], - bytes: 1, - hash: hash(2), - priority: 5u64, - valid_till: 64u64, - requires: vec![vec![2]], - provides: vec![vec![0]], - propagate: true, - source: Source::External, - }, - shard, - ) - .unwrap(); - - // then - { - let mut it = pool.ready(shard).into_iter().map(|tx| tx.data[0]); - assert_eq!(it.next(), None); - } - // all operations occupy the Future queue - it's fine - assert_eq!(pool.future.len(shard), 3); - - // let's close the cycle with one additional operation - let res = pool - .import( - TrustedOperation { - data: vec![4u8], - bytes: 1, - hash: hash(4), - priority: 50u64, - valid_till: 64u64, - requires: vec![], - provides: vec![vec![0]], - propagate: true, - source: Source::External, - }, - shard, - ) - .unwrap(); - let mut it = pool.ready(shard).into_iter().map(|tx| tx.data[0]); - assert_eq!(it.next(), Some(4)); - assert_eq!(it.next(), Some(1)); - assert_eq!(it.next(), Some(3)); - assert_eq!(it.next(), None); - assert_eq!( - res, - Imported::Ready { - hash: hash(4), - promoted: vec![hash(1), hash(3)], - failed: vec![hash(2)], - removed: vec![] - } - ); - assert_eq!(pool.future.len(shard), 0); - } - - #[test] - pub fn test_should_handle_a_cycle_with_low_priority() { - // given - let mut pool = test_pool(); - let shard = ShardIdentifier::default(); - pool.import( - TrustedOperation { - data: vec![1u8], - bytes: 1, - hash: hash(1), - priority: 5u64, - valid_till: 64u64, - requires: vec![vec![0]], - provides: vec![vec![1]], - propagate: true, - source: Source::External, - }, - shard, - ) - .unwrap(); - pool.import( - TrustedOperation { - data: vec![3u8], - bytes: 1, - hash: hash(3), - priority: 5u64, - valid_till: 64u64, - requires: vec![vec![1]], - provides: vec![vec![2]], - propagate: true, - source: Source::External, - }, - shard, - ) - .unwrap(); - assert_eq!(pool.ready(shard).count(), 0); - assert_eq!(pool.ready.len(shard), 0); - - // when - pool.import( - TrustedOperation { - data: vec![2u8], - bytes: 1, - hash: hash(2), - priority: 5u64, - valid_till: 64u64, - requires: vec![vec![2]], - provides: vec![vec![0]], - propagate: true, - source: Source::External, - }, - shard, - ) - .unwrap(); - - // then - { - let mut it = pool.ready(shard).into_iter().map(|tx| tx.data[0]); - assert_eq!(it.next(), None); - } - // all operations occupy the Future queue - it's fine - assert_eq!(pool.future.len(shard), 3); - - // let's close the cycle with one additional operation - let err = pool - .import( - TrustedOperation { - data: vec![4u8], - bytes: 1, - hash: hash(4), - priority: 1u64, // lower priority than Tx(2) - valid_till: 64u64, - requires: vec![], - provides: vec![vec![0]], - propagate: true, - source: Source::External, - }, - shard, - ) - .unwrap_err(); - let mut it = pool.ready(shard).into_iter().map(|tx| tx.data[0]); - assert_eq!(it.next(), None); - assert_eq!(pool.ready.len(shard), 0); - assert_eq!(pool.future.len(shard), 0); - if let error::Error::CycleDetected = err { - } else { - assert!(false, "Invalid error kind: {:?}", err); - } - } - - #[test] - pub fn test_can_track_heap_size() { - let mut pool = test_pool(); - let shard = ShardIdentifier::default(); - pool.import( - TrustedOperation { - data: vec![5u8; 1024], - bytes: 1, - hash: hash(5), - priority: 5u64, - valid_till: 64u64, - requires: vec![], - provides: vec![vec![0], vec![4]], - propagate: true, - source: Source::External, - }, - shard, - ) - .expect("import 1 should be ok"); - pool.import( - TrustedOperation { - data: vec![3u8; 1024], - bytes: 1, - hash: hash(7), - priority: 5u64, - valid_till: 64u64, - requires: vec![], - provides: vec![vec![2], vec![7]], - propagate: true, - source: Source::External, - }, - shard, - ) - .expect("import 2 should be ok"); - - //assert!(parity_util_mem::malloc_size(&pool) > 5000); - } - - #[test] - pub fn test_should_remove_invalid_transactions() { - // given - let shard = ShardIdentifier::default(); - let mut pool = test_pool(); - pool.import( - TrustedOperation { - data: vec![5u8], - bytes: 1, - hash: hash(5), - priority: 5u64, - valid_till: 64u64, - requires: vec![], - provides: vec![vec![0], vec![4]], - propagate: true, - source: Source::External, - }, - shard, - ) - .unwrap(); - pool.import( - TrustedOperation { - data: vec![1u8], - bytes: 1, - hash: hash(1), - priority: 5u64, - valid_till: 64u64, - requires: vec![vec![0]], - provides: vec![vec![1]], - propagate: true, - source: Source::External, - }, - shard, - ) - .unwrap(); - pool.import( - TrustedOperation { - data: vec![3u8], - bytes: 1, - hash: hash(3), - priority: 5u64, - valid_till: 64u64, - requires: vec![vec![2]], - provides: vec![], - propagate: true, - source: Source::External, - }, - shard, - ) - .unwrap(); - pool.import( - TrustedOperation { - data: vec![2u8], - bytes: 1, - hash: hash(2), - priority: 5u64, - valid_till: 64u64, - requires: vec![vec![1]], - provides: vec![vec![3], vec![2]], - propagate: true, - source: Source::External, - }, - shard, - ) - .unwrap(); - pool.import( - TrustedOperation { - data: vec![4u8], - bytes: 1, - hash: hash(4), - priority: 1_000u64, - valid_till: 64u64, - requires: vec![vec![3], vec![4]], - provides: vec![], - propagate: true, - source: Source::External, - }, - shard, - ) - .unwrap(); - // future - pool.import( - TrustedOperation { - data: vec![6u8], - bytes: 1, - hash: hash(6), - priority: 1_000u64, - valid_till: 64u64, - requires: vec![vec![11]], - provides: vec![], - propagate: true, - source: Source::External, - }, - shard, - ) - .unwrap(); - assert_eq!(pool.ready(shard).count(), 5); - assert_eq!(pool.future.len(shard), 1); - - // when - pool.remove_subtree(&[hash(6), hash(1)], shard); - - // then - assert_eq!(pool.ready(shard).count(), 1); - assert_eq!(pool.future.len(shard), 0); - } - - #[test] - pub fn test_should_prune_ready_transactions() { - // given - let mut pool = test_pool(); - let shard = ShardIdentifier::default(); - // future (waiting for 0) - pool.import( - TrustedOperation { - data: vec![5u8], - bytes: 1, - hash: hash(5), - priority: 5u64, - valid_till: 64u64, - requires: vec![vec![0]], - provides: vec![vec![100]], - propagate: true, - source: Source::External, - }, - shard, - ) - .unwrap(); - // ready - pool.import( - TrustedOperation { - data: vec![1u8], - bytes: 1, - hash: hash(1), - priority: 5u64, - valid_till: 64u64, - requires: vec![], - provides: vec![vec![1]], - propagate: true, - source: Source::External, - }, - shard, - ) - .unwrap(); - pool.import( - TrustedOperation { - data: vec![2u8], - bytes: 1, - hash: hash(2), - priority: 5u64, - valid_till: 64u64, - requires: vec![vec![2]], - provides: vec![vec![3]], - propagate: true, - source: Source::External, - }, - shard, - ) - .unwrap(); - pool.import( - TrustedOperation { - data: vec![3u8], - bytes: 1, - hash: hash(3), - priority: 5u64, - valid_till: 64u64, - requires: vec![vec![1]], - provides: vec![vec![2]], - propagate: true, - source: Source::External, - }, - shard, - ) - .unwrap(); - pool.import( - TrustedOperation { - data: vec![4u8], - bytes: 1, - hash: hash(4), - priority: 1_000u64, - valid_till: 64u64, - requires: vec![vec![3], vec![2]], - provides: vec![vec![4]], - propagate: true, - source: Source::External, - }, - shard, - ) - .unwrap(); - - assert_eq!(pool.ready(shard).count(), 4); - assert_eq!(pool.future.len(shard), 1); - - // when - let result = pool.prune_tags(vec![vec![0], vec![2]], shard); - - // then - assert_eq!(result.pruned.len(), 2); - assert_eq!(result.failed.len(), 0); - assert_eq!( - result.promoted[0], - Imported::Ready { hash: hash(5), promoted: vec![], failed: vec![], removed: vec![] } - ); - assert_eq!(result.promoted.len(), 1); - assert_eq!(pool.future.len(shard), 0); - assert_eq!(pool.ready.len(shard), 3); - assert_eq!(pool.ready(shard).count(), 3); - } - - #[test] - pub fn test_transaction_debug() { - assert_eq!( - format!( - "{:?}", - TrustedOperation { - data: vec![4u8], - bytes: 1, - hash: hash(4), - priority: 1_000u64, - valid_till: 64u64, - requires: vec![vec![3], vec![2]], - provides: vec![vec![4]], - propagate: true, - source: Source::External, - } - ), - "TrustedOperation { \ -hash: 0x0404040404040404040404040404040404040404040404040404040404040404, priority: 1000, valid_till: 64, bytes: 1, propagate: true, \ -source: External, requires: [03,02], provides: [04], data: [4]}" - .to_owned() - ); - } - - #[test] - pub fn test_transaction_propagation() { - assert!(TrustedOperation { - data: vec![4u8], - bytes: 1, - hash: hash(4), - priority: 1_000u64, - valid_till: 64u64, - requires: vec![vec![3], vec![2]], - provides: vec![vec![4]], - propagate: true, - source: Source::External, - } - .is_propagable()); - - assert!(!TrustedOperation { - data: vec![4u8], - bytes: 1, - hash: hash(4), - priority: 1_000u64, - valid_till: 64u64, - requires: vec![vec![3], vec![2]], - provides: vec![vec![4]], - propagate: false, - source: Source::External, - } - .is_propagable()); - } - - #[test] - pub fn test_should_reject_future_transactions() { - // given - let mut pool = test_pool(); - let shard = ShardIdentifier::default(); - - // when - pool.reject_future_operations = true; - - // then - let err = pool.import( - TrustedOperation { - data: vec![5u8], - bytes: 1, - hash: hash(5), - priority: 5u64, - valid_till: 64u64, - requires: vec![vec![0]], - provides: vec![], - propagate: true, - source: Source::External, - }, - shard, - ); - - if let Err(error::Error::RejectedFutureTrustedOperation) = err { - } else { - assert!(false, "Invalid error kind: {:?}", err); - } - } - - #[test] - pub fn test_should_clear_future_queue() { - // given - let mut pool = test_pool(); - let shard = ShardIdentifier::default(); - - // when - pool.import( - TrustedOperation { - data: vec![5u8], - bytes: 1, - hash: hash(5), - priority: 5u64, - valid_till: 64u64, - requires: vec![vec![0]], - provides: vec![], - propagate: true, - source: Source::External, - }, - shard, - ) - .unwrap(); - - // then - assert_eq!(pool.future.len(shard), 1); - - // and then when - assert_eq!(pool.clear_future(shard).len(), 1); - - // then - assert_eq!(pool.future.len(shard), 0); - } - - #[test] - pub fn test_should_accept_future_transactions_when_explicitly_asked_to() { - // given - let mut pool = test_pool(); - pool.reject_future_operations = true; - let shard = ShardIdentifier::default(); - - // when - let flag_value = pool.with_futures_enabled(|pool, flag| { - pool.import( - TrustedOperation { - data: vec![5u8], - bytes: 1, - hash: hash(5), - priority: 5u64, - valid_till: 64u64, - requires: vec![vec![0]], - provides: vec![], - propagate: true, - source: Source::External, - }, - shard, - ) - .unwrap(); - - flag - }); - - // then - assert!(flag_value); - assert!(pool.reject_future_operations); - assert_eq!(pool.future.len(shard), 1); - } -} diff --git a/tee-worker/bitacross/core-primitives/top-pool/src/basic_pool.rs b/tee-worker/bitacross/core-primitives/top-pool/src/basic_pool.rs deleted file mode 100644 index d046fa72b6..0000000000 --- a/tee-worker/bitacross/core-primitives/top-pool/src/basic_pool.rs +++ /dev/null @@ -1,253 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -pub extern crate alloc; - -#[cfg(all(not(feature = "std"), feature = "sgx"))] -use crate::sgx_reexport_prelude::*; - -#[cfg(all(not(feature = "std"), feature = "sgx"))] -use std::sync::SgxMutex as Mutex; - -#[cfg(feature = "std")] -use std::sync::Mutex; - -use crate::{ - base_pool::TrustedOperation, - error::IntoPoolError, - pool::{ChainApi, Options as PoolOptions, Pool}, - primitives::{ - ImportNotificationStream, PoolFuture, PoolStatus, TrustedOperationPool, - TrustedOperationSource, TxHash, - }, -}; -use alloc::{boxed::Box, string::String, sync::Arc}; -use codec::Encode; -use core::{marker::PhantomData, pin::Pin}; -use itc_direct_rpc_server::SendRpcResponse; -use itp_stf_primitives::{traits::PoolTransactionValidation, types::ShardIdentifier}; -use jsonrpc_core::futures::{ - channel::oneshot, - future::{ready, Future, FutureExt}, -}; -use sp_runtime::{ - generic::BlockId, - traits::{Block as BlockT, NumberFor, Zero}, -}; -use std::{collections::HashMap, vec, vec::Vec}; - -type BoxedReadyIterator = Box>> + Send>; - -type ReadyIteratorFor = BoxedReadyIterator; - -type PolledIterator = Pin> + Send>>; - -struct ReadyPoll { - updated_at: NumberFor, - pollers: Vec<(NumberFor, oneshot::Sender)>, -} - -impl Default for ReadyPoll { - fn default() -> Self { - Self { updated_at: NumberFor::::zero(), pollers: Default::default() } - } -} - -impl ReadyPoll { - #[allow(unused)] - fn trigger(&mut self, number: NumberFor, iterator_factory: impl Fn() -> T) { - self.updated_at = number; - - let mut idx = 0; - while idx < self.pollers.len() { - if self.pollers[idx].0 <= number { - let poller_sender = self.pollers.swap_remove(idx); - let _ = poller_sender.1.send(iterator_factory()); - } else { - idx += 1; - } - } - } - - fn add(&mut self, number: NumberFor) -> oneshot::Receiver { - let (sender, receiver) = oneshot::channel(); - self.pollers.push((number, sender)); - receiver - } - - fn updated_at(&self) -> NumberFor { - self.updated_at - } -} - -/// Basic implementation of operation pool that can be customized by providing PoolApi. -pub struct BasicPool -where - Block: BlockT, - PoolApi: ChainApi + 'static, - RpcResponse: SendRpcResponse, -{ - pool: Arc>, - _api: Arc, - ready_poll: Arc, Block>>>, - _phantom: PhantomData, -} - -impl BasicPool -where - Block: BlockT, - PoolApi: ChainApi + 'static, - RpcResponse: SendRpcResponse, - TOP: Clone + Encode + PoolTransactionValidation + core::fmt::Debug + Sync + Send, -{ - /// Create new basic operation pool with provided api and custom - /// revalidation type. - pub fn create( - options: PoolOptions, - pool_api: Arc, - rpc_response_sender: Arc, - //prometheus: Option<&PrometheusRegistry>, - //revalidation_type: RevalidationType, - //spawner: impl SpawnNamed, - ) -> Self - where - ::Error: IntoPoolError, - { - let pool = Arc::new(Pool::new(options, pool_api.clone(), rpc_response_sender)); - BasicPool { - _api: pool_api, - pool, - ready_poll: Default::default(), - _phantom: Default::default(), - } - } -} - -// FIXME: obey clippy -#[allow(clippy::type_complexity)] -impl TrustedOperationPool - for BasicPool -where - Block: BlockT, - PoolApi: ChainApi + 'static, - ::Error: IntoPoolError, - RpcResponse: SendRpcResponse + 'static, - TOP: Send + Sync + PoolTransactionValidation + core::fmt::Debug + Encode + Clone + 'static, -{ - type Block = PoolApi::Block; - type InPoolOperation = TrustedOperation; - type Error = PoolApi::Error; - - fn submit_at( - &self, - at: &BlockId, - source: TrustedOperationSource, - ops: Vec, - shard: ShardIdentifier, - ) -> PoolFuture>, Self::Error> { - let pool = self.pool.clone(); - let at = *at; - async move { pool.submit_at(&at, source, ops, shard).await }.boxed() - } - - fn submit_one( - &self, - at: &BlockId, - source: TrustedOperationSource, - op: TOP, - shard: ShardIdentifier, - ) -> PoolFuture { - let pool = self.pool.clone(); - let at = *at; - async move { pool.submit_one(&at, source, op, shard).await }.boxed() - } - - fn submit_and_watch( - &self, - at: &BlockId, - source: TrustedOperationSource, - xt: TOP, - shard: ShardIdentifier, - ) -> PoolFuture { - let at = *at; - let pool = self.pool.clone(); - async move { pool.submit_and_watch(&at, source, xt, shard).await }.boxed() - } - - fn ready_at(&self, at: NumberFor, shard: ShardIdentifier) -> PolledIterator { - if self.ready_poll.lock().unwrap().updated_at() >= at { - let iterator: ReadyIteratorFor = Box::new(self.pool.validated_pool().ready(shard)); - return Box::pin(ready(iterator)) - } - - Box::pin(self.ready_poll.lock().unwrap().add(at).map(|received| { - received.unwrap_or_else(|e| { - log::warn!("Error receiving pending set: {:?}", e); - Box::new(vec![].into_iter()) - }) - })) - } - - fn ready(&self, shard: ShardIdentifier) -> ReadyIteratorFor { - Box::new(self.pool.validated_pool().ready(shard)) - } - - fn shards(&self) -> Vec { - self.pool.validated_pool().shards() - } - - fn remove_invalid( - &self, - hashes: &[TxHash], - shard: ShardIdentifier, - inblock: bool, - ) -> Vec> { - self.pool.validated_pool().remove_invalid(hashes, shard, inblock) - } - - fn status(&self, shard: ShardIdentifier) -> PoolStatus { - self.pool.validated_pool().status(shard) - } - - fn import_notification_stream(&self) -> ImportNotificationStream { - self.pool.validated_pool().import_notification_stream() - } - - fn on_broadcasted(&self, propagations: HashMap>) { - self.pool.validated_pool().on_broadcasted(propagations) - } - - fn hash_of(&self, xt: &TOP) -> TxHash { - self.pool.hash_of(xt) - } - - fn ready_transaction( - &self, - hash: &TxHash, - shard: ShardIdentifier, - ) -> Option> { - self.pool.validated_pool().ready_by_hash(hash, shard) - } - - fn update_connection_state(&self, updates: Vec<(TxHash, (Vec, bool))>) { - self.pool.validated_pool().update_connection_state(updates); - } - - fn swap_rpc_connection_hash(&self, old_hash: TxHash, new_hash: TxHash) { - self.pool.validated_pool().swap_rpc_connection_hash(old_hash, new_hash); - } -} diff --git a/tee-worker/bitacross/core-primitives/top-pool/src/error.rs b/tee-worker/bitacross/core-primitives/top-pool/src/error.rs deleted file mode 100644 index 47029b30e1..0000000000 --- a/tee-worker/bitacross/core-primitives/top-pool/src/error.rs +++ /dev/null @@ -1,95 +0,0 @@ -// This file is part of Substrate. - -// Copyright (C) 2018-2020 Parity Technologies (UK) Ltd. -// SPDX-License-Identifier: Apache-2.0 - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//! TrustedOperation pool errors. - -use derive_more::{Display, From}; -use sp_runtime::transaction_validity::TransactionPriority as Priority; -use std::string::String; - -/// TrustedOperation pool result. -pub type Result = std::result::Result; - -/// TrustedOperation pool error type. -#[derive(Debug, From, Display)] -#[allow(missing_docs)] -pub enum Error { - #[display(fmt = "Unknown trusted operation")] - UnknownTrustedOperation, - - #[display(fmt = "Invalid trusted operation")] - InvalidTrustedOperation, - - /// Incorrect extrinsic format. - - /// The operation validity returned no "provides" tag. - /// - /// Such operations are not accepted to the pool, since we use those tags - /// to define identity of operations (occupance of the same "slot"). - #[display(fmt = "Trusted Operation does not provide any tags, so the pool can't identify it")] - NoTagsProvided, - - #[display(fmt = "Trusted Operation temporarily Banned")] - TemporarilyBanned, - - #[display(fmt = "Already imported")] - AlreadyImported, - - #[display(fmt = "Too low priority")] - TooLowPriority(Priority), - - #[display(fmt = "TrustedOperation with cyclic dependency")] - CycleDetected, - - #[display(fmt = "TrustedOperation couldn't enter the pool because of the limit")] - ImmediatelyDropped, - - #[from(ignore)] - #[display(fmt = "Invalid Block")] - InvalidBlockId(String), - - #[display(fmt = "The pool is not accepting future trusted operations")] - RejectedFutureTrustedOperation, - - #[display(fmt = "Extrinsic verification error")] - #[from(ignore)] - Verification, - - #[display(fmt = "Failed to send result of trusted operation to RPC client")] - FailedToSendUpdateToRpcClient(String), - - #[display(fmt = "Failed to unlock pool (mutex)")] - UnlockError, -} - -/// TrustedOperation pool error conversion. -pub trait IntoPoolError: Send + Sized { - /// Try to extract original `Error` - /// - /// This implementation is optional and used only to - /// provide more descriptive error messages for end users - /// of RPC API. - fn into_pool_error(self) -> std::result::Result { - Err(self) - } -} - -impl IntoPoolError for Error { - fn into_pool_error(self) -> std::result::Result { - Ok(self) - } -} diff --git a/tee-worker/bitacross/core-primitives/top-pool/src/future.rs b/tee-worker/bitacross/core-primitives/top-pool/src/future.rs deleted file mode 100644 index 2ceb34827e..0000000000 --- a/tee-worker/bitacross/core-primitives/top-pool/src/future.rs +++ /dev/null @@ -1,316 +0,0 @@ -// This file is part of Substrate. - -// Copyright (C) 2018-2021 Parity Technologies (UK) Ltd. -// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 - -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with this program. If not, see . - -pub extern crate alloc; - -use crate::{base_pool::TrustedOperation, primitives::TxHash}; -use alloc::{boxed::Box, fmt, sync::Arc, vec, vec::Vec}; - -use itp_stf_primitives::types::ShardIdentifier; -use sp_core::hexdisplay::HexDisplay; -use sp_runtime::transaction_validity::TransactionTag as Tag; -use std::{ - collections::{HashMap, HashSet}, - time::Instant, -}; - -/// TrustedOperation with partially satisfied dependencies. -pub struct WaitingTrustedOperations { - /// TrustedOperation details. - pub operation: Arc>, - /// Tags that are required and have not been satisfied yet by other operations in the pool. - pub missing_tags: HashSet, - /// Time of import to the Future Queue. - pub imported_at: Instant, -} - -impl fmt::Debug for WaitingTrustedOperations { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - write!(fmt, "WaitingTrustedOperations {{ ")?; - //write!(fmt, "imported_at: {:?}, ", self.imported_at)?; - write!(fmt, "operation: {:?}, ", self.operation)?; - write!(fmt, "missing_tags: {{")?; - let mut it = self.missing_tags.iter().map(HexDisplay::from); - if let Some(tag) = it.next() { - write!(fmt, "{}", tag)?; - } - for tag in it { - write!(fmt, ", {}", tag)?; - } - write!(fmt, " }}}}") - } -} - -impl Clone for WaitingTrustedOperations { - fn clone(&self) -> Self { - WaitingTrustedOperations { - operation: self.operation.clone(), - missing_tags: self.missing_tags.clone(), - imported_at: self.imported_at, - } - } -} - -impl WaitingTrustedOperations { - /// Creates a new `WaitingTrustedOperations`. - /// - /// Computes the set of missing tags based on the requirements and tags that - /// are provided by all operations in the ready queue. - pub fn new( - operation: TrustedOperation, - provided: Option<&HashMap>, - recently_pruned: &[HashSet], - ) -> Self { - let missing_tags = operation - .requires - .iter() - .filter(|tag| { - // is true if the tag is already satisfied either via operation in the pool - // or one that was recently included. - - let is_provided = recently_pruned.iter().any(|x| x.contains(&**tag)) - || match provided { - Some(tags) => tags.contains_key(&**tag), - None => false, - }; - - !is_provided - }) - .cloned() - .collect(); - - WaitingTrustedOperations { - operation: Arc::new(operation), - missing_tags, - imported_at: Instant::now(), - } - } - - /// Marks the tag as satisfied. - // FIXME: obey clippy - #[allow(clippy::ptr_arg)] - pub fn satisfy_tag(&mut self, tag: &Tag) { - self.missing_tags.remove(tag); - } - - /// Returns true if operation has all requirements satisfied. - pub fn is_ready(&self) -> bool { - self.missing_tags.is_empty() - } -} - -/// A pool of operations that are not yet ready to be included in the block. -/// -/// Contains operations that are still awaiting for some other operations that -/// could provide a tag that they require. -#[derive(Debug)] -pub struct FutureTrustedOperations { - /// tags that are not yet provided by any operation and we await for them - wanted_tags: HashMap>>, - /// Transactions waiting for a particular other operation - waiting: HashMap>>, -} - -impl Default for FutureTrustedOperations { - fn default() -> Self { - FutureTrustedOperations { wanted_tags: Default::default(), waiting: Default::default() } - } -} - -const WAITING_PROOF: &str = r"# -In import we always insert to `waiting` if we push to `wanted_tags`; -when removing from `waiting` we always clear `wanted_tags`; -every hash from `wanted_tags` is always present in `waiting`; -qed -#"; - -#[allow(clippy::len_without_is_empty)] -impl FutureTrustedOperations { - /// Import operation to Future queue. - /// - /// Only operations that don't have all their tags satisfied should occupy - /// the Future queue. - /// As soon as required tags are provided by some other operations that are ready - /// we should remove the operations from here and move them to the Ready queue. - pub fn import(&mut self, tx: WaitingTrustedOperations, shard: ShardIdentifier) { - assert!(!tx.is_ready(), "TrustedOperation is ready."); - if let Some(tx_pool_waiting) = self.waiting.get(&shard) { - assert!( - !tx_pool_waiting.contains_key(&tx.operation.hash), - "TrustedOperation is already imported." - ); - } - - let tx_pool_waiting_map = self.waiting.entry(shard).or_insert_with(HashMap::new); - let tx_pool_wanted_map = self.wanted_tags.entry(shard).or_insert_with(HashMap::new); - // Add all tags that are missing - for tag in &tx.missing_tags { - let entry = tx_pool_wanted_map.entry(tag.clone()).or_insert_with(HashSet::new); - entry.insert(tx.operation.hash); - } - - // Add the operation to a by-hash waiting map - tx_pool_waiting_map.insert(tx.operation.hash, tx); - } - - /// Returns true if given hash is part of the queue. - pub fn contains(&self, hash: &TxHash, shard: ShardIdentifier) -> bool { - if let Some(tx_pool_waiting) = self.waiting.get(&shard) { - return tx_pool_waiting.contains_key(hash) - } - false - } - - /// Returns a list of known operations - pub fn by_hashes( - &self, - hashes: &[TxHash], - shard: ShardIdentifier, - ) -> Vec>>> { - if let Some(tx_pool_waiting) = self.waiting.get(&shard) { - return hashes - .iter() - .map(|h| tx_pool_waiting.get(h).map(|x| x.operation.clone())) - .collect() - } - vec![] - } - - /// Satisfies provided tags in operations that are waiting for them. - /// - /// Returns (and removes) operations that became ready after their last tag got - /// satisfied and now we can remove them from Future and move to Ready queue. - pub fn satisfy_tags>( - &mut self, - tags: impl IntoIterator, - shard: ShardIdentifier, - ) -> Vec> { - let mut became_ready = vec![]; - - for tag in tags { - if let Some(tx_pool_wanted) = self.wanted_tags.get_mut(&shard) { - if let Some(hashes) = tx_pool_wanted.remove(tag.as_ref()) { - if let Some(tx_pool_waiting) = self.waiting.get_mut(&shard) { - for hash in hashes { - let is_ready = { - let tx = tx_pool_waiting.get_mut(&hash).expect(WAITING_PROOF); - tx.satisfy_tag(tag.as_ref()); - tx.is_ready() - }; - - if is_ready { - let tx = tx_pool_waiting.remove(&hash).expect(WAITING_PROOF); - became_ready.push(tx); - } - } - } - } - } - } - - became_ready - } - - /// Removes operations for given list of hashes. - /// - /// Returns a list of actually removed operations. - pub fn remove( - &mut self, - hashes: &[TxHash], - shard: ShardIdentifier, - ) -> Vec>> { - let mut removed = vec![]; - if let Some(tx_pool_waiting) = self.waiting.get_mut(&shard) { - if let Some(tx_pool_wanted) = self.wanted_tags.get_mut(&shard) { - for hash in hashes { - if let Some(waiting_tx) = tx_pool_waiting.remove(hash) { - // remove from wanted_tags as well - for tag in waiting_tx.missing_tags { - let remove = if let Some(wanted) = tx_pool_wanted.get_mut(&tag) { - wanted.remove(hash); - wanted.is_empty() - } else { - false - }; - if remove { - tx_pool_wanted.remove(&tag); - } - } - // add to result - removed.push(waiting_tx.operation) - } - } - } - } - removed - } - - /// Fold a list of future operations to compute a single value. - pub fn fold, &WaitingTrustedOperations) -> Option>( - &mut self, - f: F, - shard: ShardIdentifier, - ) -> Option { - if let Some(tx_pool) = self.waiting.get(&shard) { - return tx_pool.values().fold(None, f) - } - None - } - - /// Returns iterator over all future operations - pub fn all( - &self, - shard: ShardIdentifier, - ) -> Box> + '_> { - if let Some(tx_pool) = self.waiting.get(&shard) { - return Box::new(tx_pool.values().map(|waiting| &*waiting.operation)) - } - Box::new(core::iter::empty()) - } - - /// Removes and returns all future operations. - pub fn clear(&mut self, shard: ShardIdentifier) -> Vec>> { - if let Some(wanted_tx_pool) = self.wanted_tags.get_mut(&shard) { - wanted_tx_pool.clear(); - return self - .waiting - .get_mut(&shard) - .unwrap() - .drain() - .map(|(_, tx)| tx.operation) - .collect() - } - vec![] - } - - /// Returns number of operations in the Future queue. - pub fn len(&self, shard: ShardIdentifier) -> usize { - if let Some(tx_pool) = self.waiting.get(&shard) { - return tx_pool.len() - } - 0 - } - - /// Returns sum of encoding lengths of all operations in this queue. - pub fn bytes(&self, shard: ShardIdentifier) -> usize { - if let Some(tx_pool) = self.waiting.get(&shard) { - return tx_pool.values().fold(0, |acc, tx| acc + tx.operation.bytes) - } - 0 - } -} diff --git a/tee-worker/bitacross/core-primitives/top-pool/src/lib.rs b/tee-worker/bitacross/core-primitives/top-pool/src/lib.rs deleted file mode 100644 index fdd46ff9fe..0000000000 --- a/tee-worker/bitacross/core-primitives/top-pool/src/lib.rs +++ /dev/null @@ -1,47 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -#![cfg_attr(not(feature = "std"), no_std)] - -#[cfg(all(feature = "std", feature = "sgx"))] -compile_error!("feature \"std\" and feature \"sgx\" cannot be enabled at the same time"); - -#[cfg(all(not(feature = "std"), feature = "sgx"))] -extern crate sgx_tstd as std; - -// re-export module to properly feature gate sgx and regular std environment -#[cfg(all(not(feature = "std"), feature = "sgx"))] -pub mod sgx_reexport_prelude { - pub use jsonrpc_core_sgx as jsonrpc_core; - pub use linked_hash_map_sgx as linked_hash_map; -} - -pub mod base_pool; -pub mod basic_pool; -pub mod error; -pub mod future; -pub mod listener; -pub mod pool; -pub mod primitives; -pub mod ready; -pub mod rotator; -pub mod tracked_map; -pub mod validated_pool; -pub mod watcher; - -#[cfg(any(test, feature = "mocks"))] -pub mod mocks; diff --git a/tee-worker/bitacross/core-primitives/top-pool/src/listener.rs b/tee-worker/bitacross/core-primitives/top-pool/src/listener.rs deleted file mode 100644 index 0e069597cb..0000000000 --- a/tee-worker/bitacross/core-primitives/top-pool/src/listener.rs +++ /dev/null @@ -1,185 +0,0 @@ -// This file is part of Substrate. - -// Copyright (C) 2018-2020 Parity Technologies (UK) Ltd. -// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 - -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with this program. If not, see . - -#[cfg(all(not(feature = "std"), feature = "sgx"))] -use crate::sgx_reexport_prelude::*; - -use crate::{primitives::TxHash, watcher::Watcher}; - -use itc_direct_rpc_server::SendRpcResponse; -use itp_types::BlockHash as SidechainBlockHash; -use linked_hash_map::LinkedHashMap; -use log::{debug, trace}; - -use std::{collections::HashMap, string::String, sync::Arc, vec, vec::Vec}; - -/// Extrinsic pool default listener. -#[derive(Default)] -pub struct Listener -where - R: SendRpcResponse, -{ - watchers: HashMap>, - finality_watchers: LinkedHashMap>, - rpc_response_sender: Arc, -} - -/// Maximum number of blocks awaiting finality at any time. -const MAX_FINALITY_WATCHERS: usize = 512; - -impl Listener -where - R: SendRpcResponse, -{ - pub fn new(rpc_response_sender: Arc) -> Self { - Listener { - watchers: Default::default(), - finality_watchers: Default::default(), - rpc_response_sender, - } - } - - fn fire(&mut self, hash: &TxHash, fun: F) - where - F: FnOnce(&mut Watcher), - { - let clean = if let Some(h) = self.watchers.get_mut(hash) { - fun(h); - h.is_done() - } else { - false - }; - - if clean { - self.watchers.remove(hash); - } - } - - /// Creates a new watcher for given verified extrinsic. - /// - /// The watcher can be used to subscribe to life-cycle events of that extrinsic. - pub fn create_watcher(&mut self, hash: TxHash) { - let new_watcher = Watcher::new_watcher(hash, self.rpc_response_sender.clone()); - self.watchers.insert(hash, new_watcher); - } - - /// Notify the listeners about extrinsic broadcast. - pub fn broadcasted(&mut self, hash: &TxHash, peers: Vec) { - trace!(target: "txpool", "[{:?}] Broadcasted", hash); - self.fire(hash, |watcher| watcher.broadcast(peers)); - } - - /// Notify listeners about top execution. - pub fn top_executed(&mut self, hash: &TxHash, response: &[u8], force_wait: bool) { - trace!(target: "txpool", "[{:?}] Top Executed", hash); - self.fire(hash, |watcher| watcher.top_executed(response, force_wait)); - } - - /// New operation was added to the ready pool or promoted from the future pool. - pub fn ready(&mut self, tx: &TxHash, old: Option<&TxHash>) { - trace!(target: "txpool", "[{:?}] Ready (replaced with {:?})", tx, old); - self.fire(tx, |watcher| watcher.ready()); - if let Some(old) = old { - self.fire(old, |watcher| watcher.usurped()); - } - } - - /// New operation was added to the future pool. - pub fn future(&mut self, tx: &TxHash) { - trace!(target: "txpool", "[{:?}] Future", tx); - self.fire(tx, |watcher| watcher.future()); - } - - /// TrustedOperation was dropped from the pool because of the limit. - pub fn dropped(&mut self, tx: &TxHash, by: Option<&TxHash>) { - trace!(target: "txpool", "[{:?}] Dropped (replaced with {:?})", tx, by); - self.fire(tx, |watcher| match by { - Some(_) => watcher.usurped(), - None => watcher.dropped(), - }) - } - - /// TrustedOperation was removed as invalid. - pub fn invalid(&mut self, tx: &TxHash) { - self.fire(tx, |watcher| watcher.invalid()); - } - - /// TrustedOperation was pruned from the pool. - #[allow(clippy::or_fun_call)] - pub fn pruned(&mut self, block_hash: SidechainBlockHash, tx: &TxHash) { - debug!(target: "txpool", "[{:?}] Pruned at {:?}", tx, block_hash); - self.fire(tx, |s| s.in_block(block_hash)); - self.finality_watchers.entry(block_hash).or_insert(vec![]).push(*tx); - - while self.finality_watchers.len() > MAX_FINALITY_WATCHERS { - if let Some((_hash, txs)) = self.finality_watchers.pop_front() { - for tx in txs { - self.fire(&tx, |s| s.finality_timeout()); - } - } - } - } - - /// TrustedOperation in block. - pub fn in_block(&mut self, tx: &TxHash, block_hash: SidechainBlockHash) { - self.fire(tx, |s| s.in_block(block_hash)); - } - - /// The block this operation was included in has been retracted. - pub fn retracted(&mut self, block_hash: SidechainBlockHash) { - if let Some(hashes) = self.finality_watchers.remove(&block_hash) { - for hash in hashes { - self.fire(&hash, |s| s.retracted()) - } - } - } - - /// Notify all watchers that operations have been finalized - pub fn finalized(&mut self, block_hash: SidechainBlockHash) { - if let Some(hashes) = self.finality_watchers.remove(&block_hash) { - for hash in hashes { - log::debug!(target: "txpool", "[{:?}] Sent finalization event (block {:?})", hash, block_hash); - self.fire(&hash, |s| s.finalized()) - } - } - } - - /// Litentry: set the rpc response value and force_wait flag for a given TrustedOperation `tx`. - pub fn update_connection_state( - &mut self, - tx: &TxHash, - encoded_value: Vec, - force_wait: bool, - ) { - self.fire(tx, |s| s.update_connection_state(encoded_value, force_wait)); - } - - /// Litentry: swap the old hash with the new one in rpc connection registry - pub fn swap_rpc_connection_hash(&mut self, old_hash: TxHash, new_hash: TxHash) { - log::debug!("Swapping connection {:?} to {:?}", &old_hash, &new_hash); - // It's possible that the old top (hash) is already removed from the pool when we - // request to swap hashes, in this case we just create one to facilitate the swap - if let Some(w) = self.watchers.get(&old_hash) { - w.swap_rpc_connection_hash(new_hash); - } else { - // do not insert it to `watchers`, will be deallocated if it goes out of scope - Watcher::new_watcher(old_hash, self.rpc_response_sender.clone()) - .swap_rpc_connection_hash(new_hash); - } - } -} diff --git a/tee-worker/bitacross/core-primitives/top-pool/src/mocks/mod.rs b/tee-worker/bitacross/core-primitives/top-pool/src/mocks/mod.rs deleted file mode 100644 index 81b1c65ebe..0000000000 --- a/tee-worker/bitacross/core-primitives/top-pool/src/mocks/mod.rs +++ /dev/null @@ -1,22 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -#[cfg(any(test, feature = "mocks"))] -pub mod rpc_responder_mock; - -#[cfg(feature = "mocks")] -pub mod trusted_operation_pool_mock; diff --git a/tee-worker/bitacross/core-primitives/top-pool/src/mocks/rpc_responder_mock.rs b/tee-worker/bitacross/core-primitives/top-pool/src/mocks/rpc_responder_mock.rs deleted file mode 100644 index d4d99e18bf..0000000000 --- a/tee-worker/bitacross/core-primitives/top-pool/src/mocks/rpc_responder_mock.rs +++ /dev/null @@ -1,85 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use itc_direct_rpc_server::{DirectRpcResult, RpcHash, SendRpcResponse}; -use itp_types::{DirectRequestStatus, TrustedOperationStatus}; -use std::{marker::PhantomData, vec::Vec}; - -pub struct RpcResponderMock { - _hash: PhantomData, -} - -impl RpcResponderMock { - pub fn new() -> Self { - RpcResponderMock { _hash: PhantomData } - } -} - -impl Default for RpcResponderMock { - fn default() -> Self { - Self::new() - } -} - -impl SendRpcResponse for RpcResponderMock -where - Hash: RpcHash, -{ - type Hash = Hash; - - fn update_status_event( - &self, - _hash: Self::Hash, - _status_update: TrustedOperationStatus, - ) -> DirectRpcResult<()> { - Ok(()) - } - - fn send_state(&self, _hash: Self::Hash, _state_encoded: Vec) -> DirectRpcResult<()> { - Ok(()) - } - - fn send_state_with_status( - &self, - _hash: Self::Hash, - _state_encoded: Vec, - _status: DirectRequestStatus, - ) -> DirectRpcResult<()> { - Ok(()) - } - - fn update_force_wait(&self, _hash: Self::Hash, _force_wait: bool) -> DirectRpcResult<()> { - Ok(()) - } - - fn update_connection_state( - &self, - _hash: Self::Hash, - _encoded_value: Vec, - _force_wait: bool, - ) -> DirectRpcResult<()> { - Ok(()) - } - - fn swap_hash(&self, _old_hash: Self::Hash, _new_hash: Self::Hash) -> DirectRpcResult<()> { - Ok(()) - } - - fn is_force_wait(&self, _hash: Self::Hash) -> bool { - false - } -} diff --git a/tee-worker/bitacross/core-primitives/top-pool/src/mocks/trusted_operation_pool_mock.rs b/tee-worker/bitacross/core-primitives/top-pool/src/mocks/trusted_operation_pool_mock.rs deleted file mode 100644 index 1e515d612d..0000000000 --- a/tee-worker/bitacross/core-primitives/top-pool/src/mocks/trusted_operation_pool_mock.rs +++ /dev/null @@ -1,225 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - Copyright (C) 2017-2019 Baidu, Inc. All Rights Reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -#[cfg(all(not(feature = "std"), feature = "sgx"))] -use crate::sgx_reexport_prelude::*; - -#[cfg(feature = "sgx")] -use std::sync::SgxRwLock as RwLock; - -#[cfg(feature = "std")] -use std::sync::RwLock; - -use crate::{ - base_pool::TrustedOperation, - error::Error, - primitives::{ - ImportNotificationStream, PoolFuture, PoolStatus, TrustedOperationPool, - TrustedOperationSource, TxHash, - }, -}; -use codec::Encode; -use core::{future::Future, pin::Pin}; - -use itp_types::{Block, ShardIdentifier, H256}; -use jsonrpc_core::futures::future::ready; -use sp_runtime::{ - generic::BlockId, - traits::{BlakeTwo256, Hash, NumberFor}, -}; -use std::{boxed::Box, collections::HashMap, string::String, sync::Arc, vec, vec::Vec}; - -/// Mock for the trusted operation pool -/// -/// To be used in unit tests -pub struct TrustedOperationPoolMock { - submitted_transactions: RwLock>>, -} - -/// Transaction payload -#[derive(Clone, PartialEq)] -pub struct TxPayload { - pub block_id: BlockId< as TrustedOperationPool>::Block>, - pub source: TrustedOperationSource, - pub xts: Vec, - pub shard: ShardIdentifier, -} - -impl Default for TrustedOperationPoolMock { - fn default() -> Self { - TrustedOperationPoolMock:: { submitted_transactions: RwLock::new(HashMap::new()) } - } -} - -impl TrustedOperationPoolMock { - pub fn get_last_submitted_transactions(&self) -> HashMap> { - let transactions = self.submitted_transactions.read().unwrap(); - transactions.clone() - } - - fn map_stf_top_to_tx(stf_top: &TOP) -> Arc> { - Arc::new(TrustedOperation:: { - data: stf_top.clone(), - bytes: 0, - hash: hash_of_top(stf_top), - priority: 0u64, - valid_till: 0u64, - requires: vec![], - provides: vec![], - propagate: false, - source: TrustedOperationSource::External, - }) - } -} - -impl TrustedOperationPool for TrustedOperationPoolMock -where - TOP: Encode + Clone + Sync + Send + 'static, -{ - type Block = Block; - type InPoolOperation = TrustedOperation; - type Error = Error; - - #[allow(clippy::type_complexity)] - fn submit_at( - &self, - at: &BlockId, - source: TrustedOperationSource, - xts: Vec, - shard: ShardIdentifier, - ) -> PoolFuture>, Self::Error> { - let mut transactions = self.submitted_transactions.write().unwrap(); - transactions.insert(shard, TxPayload { block_id: *at, source, xts: xts.clone(), shard }); - - let top_hashes: Vec> = - xts.iter().map(|top| Ok(hash_of_top(top))).collect(); - - Box::pin(ready(Ok(top_hashes))) - } - - fn submit_one( - &self, - at: &BlockId, - source: TrustedOperationSource, - xt: TOP, - shard: ShardIdentifier, - ) -> PoolFuture { - let mut transactions = self.submitted_transactions.write().unwrap(); - transactions - .insert(shard, TxPayload { block_id: *at, source, xts: vec![xt.clone()], shard }); - - let top_hash = hash_of_top(&xt); - - Box::pin(ready(Ok(top_hash))) - } - - fn submit_and_watch( - &self, - at: &BlockId, - source: TrustedOperationSource, - xt: TOP, - shard: ShardIdentifier, - ) -> PoolFuture { - self.submit_one(at, source, xt, shard) - } - - #[allow(clippy::type_complexity)] - fn ready_at( - &self, - _at: NumberFor, - _shard: ShardIdentifier, - ) -> Pin< - Box< - dyn Future> + Send>> + Send, - >, - > { - unimplemented!() - } - - #[allow(clippy::type_complexity)] - fn ready( - &self, - shard: ShardIdentifier, - ) -> Box> + Send> { - let transactions = self.submitted_transactions.read().unwrap(); - let ready_transactions = transactions - .get(&shard) - .map(|payload| payload.xts.iter().map(Self::map_stf_top_to_tx).collect()) - .unwrap_or_else(Vec::new); - Box::new(ready_transactions.into_iter()) - } - - fn shards(&self) -> Vec { - let transactions = self.submitted_transactions.read().unwrap(); - transactions.iter().map(|(shard, _)| *shard).collect() - } - - fn remove_invalid( - &self, - _hashes: &[TxHash], - _shard: ShardIdentifier, - _inblock: bool, - ) -> Vec> { - Vec::new() - } - - fn status(&self, shard: ShardIdentifier) -> PoolStatus { - let transactions = self.submitted_transactions.read().unwrap(); - transactions - .get(&shard) - .map(|payload| PoolStatus { - ready: payload.xts.len(), - ready_bytes: 0, - future: 0, - future_bytes: 0, - }) - .unwrap_or_else(default_pool_status) - } - - fn import_notification_stream(&self) -> ImportNotificationStream { - unimplemented!() - } - - fn on_broadcasted(&self, _propagations: HashMap>) { - unimplemented!() - } - - fn hash_of(&self, xt: &TOP) -> TxHash { - hash_of_top(xt) - } - - fn ready_transaction( - &self, - _hash: &TxHash, - _shard: ShardIdentifier, - ) -> Option> { - unimplemented!() - } - - fn update_connection_state(&self, _updates: Vec<(TxHash, (Vec, bool))>) {} - - fn swap_rpc_connection_hash(&self, _old_hash: TxHash, _new_hash: TxHash) {} -} - -fn default_pool_status() -> PoolStatus { - PoolStatus { ready: 0, ready_bytes: 0, future: 0, future_bytes: 0 } -} - -fn hash_of_top(top: &TOP) -> H256 { - top.using_encoded(|x| BlakeTwo256::hash(x)) -} diff --git a/tee-worker/bitacross/core-primitives/top-pool/src/pool.rs b/tee-worker/bitacross/core-primitives/top-pool/src/pool.rs deleted file mode 100644 index 42f43c645b..0000000000 --- a/tee-worker/bitacross/core-primitives/top-pool/src/pool.rs +++ /dev/null @@ -1,810 +0,0 @@ -// This file is part of Substrate. - -// Copyright (C) 2018-2020 Parity Technologies (UK) Ltd. -// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 - -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with this program. If not, see . - -#[cfg(all(not(feature = "std"), feature = "sgx"))] -use crate::sgx_reexport_prelude::*; -use core::{fmt::Debug, marker::PhantomData}; - -use crate::{ - base_pool as base, error, - primitives::{TrustedOperationSource, TxHash}, - validated_pool::{ValidatedOperation, ValidatedPool}, -}; -use codec::Encode; -use core::matches; -use itc_direct_rpc_server::SendRpcResponse; -use itp_stf_primitives::{traits::PoolTransactionValidation, types::ShardIdentifier}; -use itp_types::BlockHash as SidechainBlockHash; -use jsonrpc_core::futures::{channel::mpsc::Receiver, future, Future}; -use sp_runtime::{ - generic::BlockId, - traits::{self, Block as BlockT, SaturatedConversion}, - transaction_validity::{TransactionTag as Tag, TransactionValidity, TransactionValidityError}, -}; -use std::{collections::HashMap, format, sync::Arc, time::Instant, vec::Vec}; - -/// Modification notification event stream type; -pub type EventStream = Receiver; - -/// Block hash type for a pool. -pub type BlockHash = <::Block as traits::Block>::Hash; -/// Extrinsic hash type for a pool. -pub type ExtrinsicHash = <::Block as traits::Block>::Hash; -/// Extrinsic type for a pool. -//pub type ExtrinsicFor = <::Block as traits::Block>::Extrinsic; -/// Block number type for the ChainApi -pub type NumberFor = traits::NumberFor<::Block>; -/// A type of operation stored in the pool -pub type TransactionFor = Arc>; -/// A type of validated operation stored in the pool. -pub type ValidatedOperationFor = ValidatedOperation::Error>; - -/// Concrete extrinsic validation and query logic. -pub trait ChainApi: Send + Sync { - /// Block type. - type Block: BlockT; - /// Error type. - type Error: From; - /// Validate operation future. - type ValidationFuture: Future> + Send + Unpin; - /// Body future (since block body might be remote) - type BodyFuture: Future, Self::Error>> + Unpin + Send + 'static; - - /// Verify extrinsic at given block. - fn validate_transaction( - &self, - source: TrustedOperationSource, - uxt: TOP, - shard: ShardIdentifier, - ) -> Self::ValidationFuture; - - /// Returns a block number given the block id. - fn block_id_to_number( - &self, - at: &BlockId, - ) -> Result>, Self::Error>; - - /// Returns a block hash given the block id. - fn block_id_to_hash( - &self, - at: &BlockId, - ) -> Result, Self::Error>; - - /// Returns hash and encoding length of the extrinsic. - fn hash_and_length(&self, uxt: &TOP) -> (TxHash, usize); - - /// Returns a block body given the block id. - fn block_body(&self, at: &BlockId) -> Self::BodyFuture; -} - -/// Pool configuration options. -#[derive(Debug, Clone)] -pub struct Options { - /// Ready queue limits. - pub ready: base::Limit, - /// Future queue limits. - pub future: base::Limit, - /// Reject future operations. - pub reject_future_operations: bool, -} - -impl Default for Options { - fn default() -> Self { - Options { - ready: base::Limit { count: 8192, total_bytes: 20 * 1024 * 1024 }, - future: base::Limit { count: 512, total_bytes: 1024 * 1024 }, - reject_future_operations: false, - } - } -} - -/// Should we check that the operation is banned -/// in the pool, before we verify it? -#[derive(Copy, Clone)] -enum CheckBannedBeforeVerify { - Yes, - No, -} - -/// Extrinsics pool that performs validation. -pub struct Pool -where - R: SendRpcResponse, -{ - validated_pool: Arc>, - _phantom: PhantomData, -} - -impl Pool -where - ::Error: error::IntoPoolError, - R: SendRpcResponse, - TOP: Encode + Clone + PoolTransactionValidation + core::fmt::Debug + Send + Sync, -{ - /// Create a new operation pool. - pub fn new(options: Options, api: Arc, rpc_response_sender: Arc) -> Self { - Pool { - validated_pool: Arc::new(ValidatedPool::new(options, api, rpc_response_sender)), - _phantom: Default::default(), - } - } - - /// Imports a bunch of unverified extrinsics to the pool - pub async fn submit_at( - &self, - at: &BlockId, - source: TrustedOperationSource, - xts: impl IntoIterator, - shard: ShardIdentifier, - ) -> Result>, B::Error> { - let xts = xts.into_iter().map(|xt| (source, xt)); - let validated_transactions = - self.verify(at, xts, CheckBannedBeforeVerify::Yes, shard).await?; - Ok(self.validated_pool.submit(validated_transactions.into_values(), shard)) - } - - /// Resubmit the given extrinsics to the pool. - /// - /// This does not check if a operation is banned, before we verify it again. - pub async fn resubmit_at( - &self, - at: &BlockId, - source: TrustedOperationSource, - xts: impl IntoIterator, - shard: ShardIdentifier, - ) -> Result>, B::Error> { - let xts = xts.into_iter().map(|xt| (source, xt)); - let validated_transactions = - self.verify(at, xts, CheckBannedBeforeVerify::No, shard).await?; - Ok(self.validated_pool.submit(validated_transactions.into_values(), shard)) - } - - /// Imports one unverified extrinsic to the pool - pub async fn submit_one( - &self, - at: &BlockId, - source: TrustedOperationSource, - xt: TOP, - shard: ShardIdentifier, - ) -> Result { - let res = self.submit_at(at, source, std::iter::once(xt), shard).await?.pop(); - res.expect("One extrinsic passed; one result returned; qed") - } - - /// Import a single extrinsic and starts to watch their progress in the pool. - pub async fn submit_and_watch( - &self, - at: &BlockId, - source: TrustedOperationSource, - xt: TOP, - shard: ShardIdentifier, - ) -> Result { - //TODO - //let block_number = self.resolve_block_number(at)?; - // dummy value: - let block_number = 0; - let (_, tx) = self - .verify_one(at, block_number, source, xt, CheckBannedBeforeVerify::Yes, shard) - .await; - self.validated_pool.submit_and_watch(tx, shard) - } - - /// Resubmit some operation that were validated elsewhere. - pub fn resubmit( - &self, - revalidated_transactions: HashMap>, - shard: ShardIdentifier, - ) { - let now = Instant::now(); - self.validated_pool.resubmit(revalidated_transactions, shard); - log::debug!(target: "txpool", - "Resubmitted. Took {} ms. Status: {:?}", - now.elapsed().as_millis(), - self.validated_pool.status(shard) - ); - } - - /// Prunes known ready operations. - /// - /// Used to clear the pool from operations that were part of recently imported block. - /// The main difference from the `prune` is that we do not revalidate any operations - /// and ignore unknown passed hashes. - pub fn prune_known( - &self, - at: &BlockId, - hashes: &[TxHash], - shard: ShardIdentifier, - ) -> Result<(), B::Error> { - // Get details of all extrinsics that are already in the pool - #[allow(clippy::filter_map_identity)] - // false positive. Filter map does filter because x is an option - let in_pool_tags = self - .validated_pool - .extrinsics_tags(hashes, shard) - .into_iter() - .filter_map(|x| x) - .flatten(); - - // Prune all operations that provide given tags - let prune_status = self.validated_pool.prune_tags(in_pool_tags, shard)?; - let pruned_transactions = - hashes.iter().cloned().chain(prune_status.pruned.iter().map(|tx| tx.hash)); - self.validated_pool.fire_pruned(at, pruned_transactions) - } - - /// Prunes ready operations. - /// - /// Used to clear the pool from operations that were part of recently imported block. - /// To perform pruning we need the tags that each extrinsic provides and to avoid calling - /// into runtime too often we first lookup all extrinsics that are in the pool and get - /// their provided tags from there. Otherwise we query the runtime at the `parent` block. - pub async fn prune( - &self, - at: &BlockId, - _parent: &BlockId, - extrinsics: &[TOP], - shard: ShardIdentifier, - ) -> Result<(), B::Error> { - log::debug!( - target: "txpool", - "Starting pruning of block {:?} (extrinsics: {})", - at, - extrinsics.len() - ); - // Get details of all extrinsics that are already in the pool - let in_pool_hashes = - extrinsics.iter().map(|extrinsic| self.hash_of(extrinsic)).collect::>(); - let in_pool_tags = self.validated_pool.extrinsics_tags(&in_pool_hashes, shard); - - // Zip the ones from the pool with the full list (we get pairs `(Extrinsic, Option>)`) - let all = extrinsics.iter().zip(in_pool_tags.into_iter()); - - let mut future_tags = Vec::new(); - for (extrinsic, in_pool_tags) in all { - match in_pool_tags { - // reuse the tags for extrinsics that were found in the pool - Some(tags) => future_tags.extend(tags), - // if it's not found in the pool query the runtime at parent block - // to get validity info and tags that the extrinsic provides. - None => { - let validity = self - .validated_pool - .api() - .validate_transaction( - TrustedOperationSource::InBlock, - extrinsic.clone(), - shard, - ) - .await; - - if let Ok(Ok(validity)) = validity { - future_tags.extend(validity.provides); - } - }, - } - } - - self.prune_tags(at, future_tags, in_pool_hashes, shard).await - } - - /// Prunes ready operations that provide given list of tags. - /// - /// Given tags are assumed to be always provided now, so all operations - /// in the Future Queue that require that particular tag (and have other - /// requirements satisfied) are promoted to Ready Queue. - /// - /// Moreover for each provided tag we remove operations in the pool that: - /// 1. Provide that tag directly - /// 2. Are a dependency of pruned operation. - /// - /// Returns operations that have been removed from the pool and must be reverified - /// before reinserting to the pool. - /// - /// By removing predecessor operations as well we might actually end up - /// pruning too much, so all removed operations are reverified against - /// the runtime (`validate_transaction`) to make sure they are invalid. - /// - /// However we avoid revalidating operations that are contained within - /// the second parameter of `known_imported_hashes`. These operations - /// (if pruned) are not revalidated and become temporarily banned to - /// prevent importing them in the (near) future. - pub async fn prune_tags( - &self, - at: &BlockId, - tags: impl IntoIterator, - known_imported_hashes: impl IntoIterator + Clone, - shard: ShardIdentifier, - ) -> Result<(), B::Error> { - log::debug!(target: "txpool", "Pruning at {:?}", at); - // Prune all operations that provide given tags - let prune_status = match self.validated_pool.prune_tags(tags, shard) { - Ok(prune_status) => prune_status, - Err(e) => return Err(e), - }; - - // Make sure that we don't revalidate extrinsics that were part of the recently - // imported block. This is especially important for UTXO-like chains cause the - // inputs are pruned so such operation would go to future again. - self.validated_pool - .ban(&Instant::now(), known_imported_hashes.clone().into_iter()); - - // Try to re-validate pruned operations since some of them might be still valid. - // note that `known_imported_hashes` will be rejected here due to temporary ban. - let pruned_hashes = prune_status.pruned.iter().map(|tx| tx.hash).collect::>(); - let pruned_transactions = - prune_status.pruned.into_iter().map(|tx| (tx.source, tx.data.clone())); - - let reverified_transactions = self - .verify(at, pruned_transactions, CheckBannedBeforeVerify::Yes, shard) - .await?; - - log::trace!(target: "txpool", "Pruning at {:?}. Resubmitting operations.", at); - // And finally - submit reverified operations back to the pool - - self.validated_pool.resubmit_pruned( - at, - known_imported_hashes, - pruned_hashes, - reverified_transactions.into_values().collect(), - shard, - ) - } - - /// Returns operation hash - pub fn hash_of(&self, xt: &TOP) -> TxHash { - self.validated_pool.api().hash_and_length(xt).0 - } - - /// Resolves block number by id. - fn _resolve_block_number(&self, at: &BlockId) -> Result, B::Error> { - self.validated_pool.api().block_id_to_number(at).and_then(|number| { - number.ok_or_else(|| error::Error::InvalidBlockId(format!("{:?}", at)).into()) - }) - } - - /// Returns future that validates a bunch of operations at given block. - async fn verify( - &self, - at: &BlockId, - xts: impl IntoIterator, - check: CheckBannedBeforeVerify, - shard: ShardIdentifier, - ) -> Result>, B::Error> { - //FIXME: Nicer verify - // we need a block number to compute tx validity - //let block_number = self.resolve_block_number(at)?; - // dummy blocknumber - //pub type NumberFor = traits::NumberFor<::Block>; - let block_number = 0; - - let res = future::join_all( - xts.into_iter() - .map(|(source, xt)| self.verify_one(at, block_number, source, xt, check, shard)), - ) - .await - .into_iter() - .collect::>(); - - Ok(res) - } - - /// Returns future that validates single operation at given block. - async fn verify_one( - &self, - _block_id: &BlockId, - //block_number: NumberFor, - block_number: i8, - source: TrustedOperationSource, - xt: TOP, - check: CheckBannedBeforeVerify, - shard: ShardIdentifier, - ) -> (TxHash, ValidatedOperationFor) { - let (hash, bytes) = self.validated_pool.api().hash_and_length(&xt); - - let ignore_banned = matches!(check, CheckBannedBeforeVerify::No); - if let Err(err) = self.validated_pool.check_is_known(&hash, ignore_banned, shard) { - return (hash, ValidatedOperation::Invalid(hash, err)) - } - - //FIXME: - // no runtime validation check for now. - let validation_result = - self.validated_pool.api().validate_transaction(source, xt.clone(), shard).await; - - let status = match validation_result { - Ok(status) => status, - Err(e) => return (hash, ValidatedOperation::Invalid(hash, e)), - }; - - let validity = match status { - Ok(validity) => - if validity.provides.is_empty() { - ValidatedOperation::Invalid(hash, error::Error::NoTagsProvided.into()) - } else { - ValidatedOperation::valid_at( - block_number.saturated_into::(), - hash, - source, - xt, - bytes, - validity, - ) - }, - Err(TransactionValidityError::Invalid(_e)) => - ValidatedOperation::Invalid(hash, error::Error::InvalidTrustedOperation.into()), - Err(TransactionValidityError::Unknown(_e)) => - ValidatedOperation::Unknown(hash, error::Error::UnknownTrustedOperation.into()), - }; - - (hash, validity) - } - - /// get a reference to the underlying validated pool. - pub fn validated_pool(&self) -> &ValidatedPool { - &self.validated_pool - } -} - -impl Clone for Pool -where - ::Error: error::IntoPoolError, - R: SendRpcResponse, -{ - fn clone(&self) -> Self { - Self { validated_pool: self.validated_pool.clone(), _phantom: Default::default() } - } -} - -#[cfg(test)] -pub mod tests { - use super::*; - use crate::{ - base_pool::Limit, mocks::rpc_responder_mock::RpcResponderMock, - primitives::from_low_u64_to_be_h256, - }; - use codec::{Decode, Encode}; - use itp_test::mock::stf_mock::{ - mock_top_direct_trusted_call_signed, mock_trusted_call_signed, TrustedOperationMock, - }; - use itp_types::Header; - use jsonrpc_core::{ - futures, - futures::{executor::block_on, future::ready}, - }; - use parity_util_mem::MallocSizeOf; - use serde::Serialize; - use sp_application_crypto::ed25519; - use sp_core::hash::H256; - use sp_runtime::traits::{BlakeTwo256, Extrinsic as ExtrinsicT, Hash, Verify}; - - #[derive(Clone, PartialEq, Eq, Encode, Decode, core::fmt::Debug, Serialize, MallocSizeOf)] - pub enum Extrinsic { - #[codec(index = 0)] - IncludeData(Vec), - #[codec(index = 1)] - StorageChange(Vec, Option>), - #[codec(index = 2)] - OffchainIndexSet(Vec, Vec), - #[codec(index = 3)] - OffchainIndexClear(Vec), - } - - impl ExtrinsicT for Extrinsic { - type Call = Extrinsic; - type SignaturePayload = (); - - fn is_signed(&self) -> Option { - if let Extrinsic::IncludeData(_) = *self { - Some(false) - } else { - Some(true) - } - } - - fn new( - call: Self::Call, - _signature_payload: Option, - ) -> Option { - Some(call) - } - } - - /// The signature type used by accounts/transactions. - pub type AccountSignature = ed25519::Signature; - /// An identifier for an account on this system. - pub type AccountId = ::Signer; - /// The hashing algorithm used. - pub type Hashing = BlakeTwo256; - /// The item of a block digest. - pub type DigestItem = sp_runtime::generic::DigestItem; - /// The digest of a block. - pub type Digest = sp_runtime::generic::Digest; - /// A test block. - pub type Block = sp_runtime::generic::Block; - /// Test RPC responder - pub type TestRpcResponder = RpcResponderMock; - - const SOURCE: TrustedOperationSource = TrustedOperationSource::External; - - #[derive(Clone, Debug, Default)] - struct TestApi {} - - impl ChainApi for TestApi { - type Block = tests::Block; - type Error = error::Error; - type ValidationFuture = futures::future::Ready>; - type BodyFuture = futures::future::Ready>>; - - /// Verify extrinsic at given block. - fn validate_transaction( - &self, - _source: TrustedOperationSource, - uxt: TOP, - _shard: ShardIdentifier, - ) -> Self::ValidationFuture { - let operation = uxt.validate(); - ready(Ok(operation)) - } - - /// Returns a block number given the block id. - fn block_id_to_number( - &self, - at: &BlockId, - ) -> Result>, Self::Error> { - Ok(match at { - BlockId::Number(num) => Some(*num), - BlockId::Hash(_) => None, - }) - } - - /// Returns a block hash given the block id. - fn block_id_to_hash( - &self, - at: &BlockId, - ) -> Result, Self::Error> { - Ok(match at { - BlockId::Number(num) => Some(from_low_u64_to_be_h256((*num).into())), - BlockId::Hash(_) => None, - }) - } - - /// Hash the extrinsic. - fn hash_and_length(&self, uxt: &TOP) -> (SidechainBlockHash, usize) { - let encoded = uxt.encode(); - let len = encoded.len(); - (tests::Hashing::hash_of(&encoded), len) - } - - fn block_body(&self, _id: &BlockId) -> Self::BodyFuture { - futures::future::ready(Ok(None)) - } - } - - fn test_pool() -> Pool, TrustedOperationMock> { - Pool::new( - Default::default(), - TestApi::default().into(), - Arc::new(RpcResponderMock::::new()), - ) - } - - #[test] - pub fn test_should_validate_and_import_transaction() { - // given - let pool = test_pool(); - let shard = ShardIdentifier::default(); - - // when - let hash = block_on(pool.submit_one( - &BlockId::Number(0), - SOURCE, - mock_top_direct_trusted_call_signed(), - shard, - )) - .unwrap(); - - // then - assert_eq!( - pool.validated_pool().ready(shard).map(|v| v.hash).collect::>(), - vec![hash] - ); - } - - #[test] - pub fn test_should_reject_if_temporarily_banned() { - // given - let pool = test_pool(); - let shard = ShardIdentifier::default(); - let top = mock_top_direct_trusted_call_signed(); - - // when - pool.validated_pool.rotator().ban(&Instant::now(), vec![pool.hash_of(&top)]); - let res = block_on(pool.submit_one(&BlockId::Number(0), SOURCE, top, shard)); - assert_eq!(pool.validated_pool().status(shard).ready, 0); - assert_eq!(pool.validated_pool().status(shard).future, 0); - - // then - assert!(matches!(res.unwrap_err(), error::Error::TemporarilyBanned)); - } - - #[test] - pub fn test_should_notify_about_pool_events() { - let (stream, hash0, hash1) = { - // given - let pool = test_pool(); - let shard = ShardIdentifier::default(); - let stream = pool.validated_pool().import_notification_stream(); - - // when - let hash0 = block_on(pool.submit_one( - &BlockId::Number(0), - SOURCE, - TrustedOperationMock::direct_call(mock_trusted_call_signed(0)), - shard, - )) - .unwrap(); - let hash1 = block_on(pool.submit_one( - &BlockId::Number(0), - SOURCE, - TrustedOperationMock::direct_call(mock_trusted_call_signed(1)), - shard, - )) - .unwrap(); - /* this fails because of #1488 - // future doesn't count - let _hash = block_on(pool.submit_one( - &BlockId::Number(0), - SOURCE, - TrustedOperationMock::direct_call(mock_trusted_call_signed(3)), - shard, - )) - .unwrap(); - assert_eq!(pool.validated_pool().status(shard).future, 1); - */ - assert_eq!(pool.validated_pool().status(shard).ready, 2); - - (stream, hash0, hash1) - }; - - // then - let mut it = futures::executor::block_on_stream(stream); - assert_eq!(it.next(), Some(hash0)); - assert_eq!(it.next(), Some(hash1)); - assert_eq!(it.next(), None); - } - - #[test] - pub fn test_should_clear_stale_transactions() { - // given - let pool = test_pool(); - let shard = ShardIdentifier::default(); - let hash1 = block_on(pool.submit_one( - &BlockId::Number(0), - SOURCE, - TrustedOperationMock::direct_call(mock_trusted_call_signed(0)), - shard, - )) - .unwrap(); - let hash2 = block_on(pool.submit_one( - &BlockId::Number(0), - SOURCE, - TrustedOperationMock::direct_call(mock_trusted_call_signed(1)), - shard, - )) - .unwrap(); - let hash3 = block_on(pool.submit_one( - &BlockId::Number(0), - SOURCE, - TrustedOperationMock::direct_call(mock_trusted_call_signed(3)), - shard, - )) - .unwrap(); - // when - pool.validated_pool.clear_stale(&BlockId::Number(65), shard).unwrap(); - - // then - assert_eq!(pool.validated_pool().ready(shard).count(), 0); - assert_eq!(pool.validated_pool().status(shard).future, 0); - assert_eq!(pool.validated_pool().status(shard).ready, 0); - // make sure they are temporarily banned as well - assert!(pool.validated_pool.rotator().is_banned(&hash1)); - assert!(pool.validated_pool.rotator().is_banned(&hash2)); - assert!(pool.validated_pool.rotator().is_banned(&hash3)); - } - - #[test] - pub fn test_should_ban_mined_transactions() { - // given - let pool = test_pool(); - let shard = ShardIdentifier::default(); - let hash1 = block_on(pool.submit_one( - &BlockId::Number(0), - SOURCE, - TrustedOperationMock::direct_call(mock_trusted_call_signed(0)), - shard, - )) - .unwrap(); - - // when - block_on(pool.prune_tags(&BlockId::Number(1), vec![vec![0]], vec![hash1], shard)).unwrap(); - - // then - assert!(pool.validated_pool.rotator().is_banned(&hash1)); - } - - #[test] - #[ignore] // flaky, fails sometimes - pub fn test_should_limit_futures() { - // given - let shard = ShardIdentifier::default(); - let limit = Limit { count: 100, total_bytes: 300 }; - let pool = Pool::new( - Options { ready: limit.clone(), future: limit, ..Default::default() }, - TestApi::default().into(), - Arc::new(TestRpcResponder::new()), - ); - - let hash1 = block_on(pool.submit_one( - &BlockId::Number(0), - SOURCE, - TrustedOperationMock::direct_call(mock_trusted_call_signed(1)), - shard, - )) - .unwrap(); - assert_eq!(pool.validated_pool().status(shard).future, 1); - - // when - let hash2 = block_on(pool.submit_one( - &BlockId::Number(0), - SOURCE, - TrustedOperationMock::direct_call(mock_trusted_call_signed(10)), - shard, - )) - .unwrap(); - - // then - assert_eq!(pool.validated_pool().status(shard).future, 1); - assert!(pool.validated_pool.rotator().is_banned(&hash1)); - assert!(!pool.validated_pool.rotator().is_banned(&hash2)); - } - - #[test] - pub fn test_should_error_if_reject_immediately() { - // given - let shard = ShardIdentifier::default(); - let limit = Limit { count: 100, total_bytes: 10 }; - let pool = Pool::new( - Options { ready: limit.clone(), future: limit, ..Default::default() }, - TestApi::default().into(), - Arc::new(TestRpcResponder::new()), - ); - - // when - block_on(pool.submit_one( - &BlockId::Number(0), - SOURCE, - TrustedOperationMock::direct_call(mock_trusted_call_signed(1)), - shard, - )) - .unwrap_err(); - - // then - assert_eq!(pool.validated_pool().status(shard).ready, 0); - assert_eq!(pool.validated_pool().status(shard).future, 0); - } -} diff --git a/tee-worker/bitacross/core-primitives/top-pool/src/primitives.rs b/tee-worker/bitacross/core-primitives/top-pool/src/primitives.rs deleted file mode 100644 index acd24bb317..0000000000 --- a/tee-worker/bitacross/core-primitives/top-pool/src/primitives.rs +++ /dev/null @@ -1,346 +0,0 @@ -// File replacing substrate crate sp_transaction_pool::{error, PoolStatus}; - -#[cfg(all(not(feature = "std"), feature = "sgx"))] -use crate::sgx_reexport_prelude::*; - -extern crate alloc; -use crate::error; -use alloc::{boxed::Box, string::String, sync::Arc, vec::Vec}; -use byteorder::{BigEndian, ByteOrder}; -use codec::{Decode, Encode}; -use core::pin::Pin; -use itp_stf_primitives::types::ShardIdentifier; -use jsonrpc_core::futures::{channel::mpsc::Receiver, Future, Stream}; -use sp_core::H256; -use sp_runtime::{ - generic::BlockId, - traits::{Block as BlockT, NumberFor}, - transaction_validity::{TransactionLongevity, TransactionPriority, TransactionTag}, -}; -use std::collections::HashMap; - -/// TrustedOperation pool status. -#[derive(Debug, Default)] -pub struct PoolStatus { - /// Number of operations in the ready queue. - pub ready: usize, - /// Sum of bytes of ready operation encodings. - pub ready_bytes: usize, - /// Number of operations in the future queue. - pub future: usize, - /// Sum of bytes of ready operation encodings. - pub future_bytes: usize, -} - -impl PoolStatus { - /// Returns true if the are no operations in the pool. - pub fn is_empty(&self) -> bool { - self.ready == 0 && self.future == 0 - } -} - -/// Possible operation status events. -/// -/// This events are being emitted by `TrustedOperationPool` watchers, -/// which are also exposed over RPC. -/// -/// The status events can be grouped based on their kinds as: -/// 1. Entering/Moving within the pool: -/// - `Future` -/// - `Ready` -/// 2. Inside `Ready` queue: -/// - `Broadcast` -/// 3. Leaving the pool: -/// - `InBlock` -/// - `Invalid` -/// - `Usurped` -/// - `Dropped` -/// 4. Re-entering the pool: -/// - `Retracted` -/// 5. Block finalized: -/// - `Finalized` -/// - `FinalityTimeout` -/// -/// The events will always be received in the order described above, however -/// there might be cases where operations alternate between `Future` and `Ready` -/// pool, and are `Broadcast` in the meantime. -/// -/// There is also only single event causing the operation to leave the pool. -/// I.e. only one of the listed ones should be triggered. -/// -/// Note that there are conditions that may cause operations to reappear in the pool. -/// 1. Due to possible forks, the operation that ends up being in included -/// in one block, may later re-enter the pool or be marked as invalid. -/// 2. TrustedOperation `Dropped` at one point, may later re-enter the pool if some other -/// operations are removed. -/// 3. `Invalid` operation may become valid at some point in the future. -/// (Note that runtimes are encouraged to use `UnknownValidity` to inform the pool about -/// such case). -/// 4. `Retracted` operations might be included in some next block. -/// -/// The stream is considered finished only when either `Finalized` or `FinalityTimeout` -/// event is triggered. You are however free to unsubscribe from notifications at any point. -/// The first one will be emitted when the block, in which operation was included gets -/// finalized. The `FinalityTimeout` event will be emitted when the block did not reach finality -/// within 512 blocks. This either indicates that finality is not available for your chain, -/// or that finality gadget is lagging behind. If you choose to wait for finality longer, you can -/// re-subscribe for a particular operation hash manually again. -#[derive(Debug, Clone, PartialEq)] -pub enum TrustedOperationStatus { - /// TrustedOperation is part of the future queue. - Future, - /// TrustedOperation is part of the ready queue. - Ready, - /// The operation has been broadcast to the given peers. - Broadcast(Vec), - /// TrustedOperation has been included in block with given hash. - InBlock(BlockHash), - /// The block this operation was included in has been retracted. - Retracted(BlockHash), - /// Maximum number of finality watchers has been reached, - /// old watchers are being removed. - FinalityTimeout(BlockHash), - /// TrustedOperation has been finalized by a finality-gadget, e.g GRANDPA - Finalized(BlockHash), - /// TrustedOperation has been replaced in the pool, by another operation - /// that provides the same tags. (e.g. same (sender, nonce)). - Usurped(Hash), - /// TrustedOperation has been dropped from the pool because of the limit. - Dropped, - /// TrustedOperation is no longer valid in the current state. - Invalid, -} - -/// The stream of operation events. -pub type TrustedOperationStatusStream = - dyn Stream> + Send + Unpin; - -/// The import notification event stream. -pub type ImportNotificationStream = Receiver; - -/// TrustedOperation hash type for a pool. -pub type TxHash = H256; -/// Block hash type for a pool. -pub type BlockHash = H256; -/// Type of operations event stream for a pool. -pub type TrustedOperationStatusStreamFor = TrustedOperationStatusStream; - -/// Typical future type used in operation pool api. -pub type PoolFuture = Pin> + Send>>; - -/// In-pool operation interface. -/// -/// The pool is container of operations that are implementing this trait. -/// See `sp_runtime::ValidTransaction` for details about every field. -pub trait InPoolOperation { - /// TrustedOperation type. - type TrustedOperation; - - /// Get the reference to the operation data. - fn data(&self) -> &Self::TrustedOperation; - /// Get hash of the operation. - fn hash(&self) -> TxHash; - /// Get priority of the operation. - fn priority(&self) -> &TransactionPriority; - /// Get longevity of the operation. - fn longevity(&self) -> &TransactionLongevity; - /// Get operation dependencies. - fn requires(&self) -> &[TransactionTag]; - /// Get tags that operation provides. - fn provides(&self) -> &[TransactionTag]; - /// Return a flag indicating if the operation should be propagated to other peers. - fn is_propagable(&self) -> bool; -} - -/// TrustedOperation pool interface. -pub trait TrustedOperationPool: Send + Sync { - /// Block type. - type Block: BlockT; - /// In-pool operation type. - type InPoolOperation: InPoolOperation; - /// Error type. - type Error: From + error::IntoPoolError; - - // *** RPC - - /// Returns a future that imports a bunch of unverified operations to the pool. - // FIXME: obey clippy - #[allow(clippy::type_complexity)] - fn submit_at( - &self, - at: &BlockId, - source: TrustedOperationSource, - xts: Vec, - shard: ShardIdentifier, - ) -> PoolFuture>, Self::Error>; - - /// Returns a future that imports one unverified operation to the pool. - fn submit_one( - &self, - at: &BlockId, - source: TrustedOperationSource, - xt: TOP, - shard: ShardIdentifier, - ) -> PoolFuture; - - /// Returns a future that import a single operation and starts to watch their progress in the pool. - fn submit_and_watch( - &self, - at: &BlockId, - source: TrustedOperationSource, - xt: TOP, - shard: ShardIdentifier, - ) -> PoolFuture; - - // *** Block production / Networking - /// Get an iterator for ready operations ordered by priority. - /// - /// Guarantees to return only when operation pool got updated at `at` block. - /// Guarantees to return immediately when `None` is passed. - // FIXME: obey clippy - #[allow(clippy::type_complexity)] - fn ready_at( - &self, - at: NumberFor, - shard: ShardIdentifier, - ) -> Pin< - Box< - dyn Future> + Send>> + Send, - >, - >; - - /// Get an iterator for ready operations ordered by priority. - fn ready( - &self, - shard: ShardIdentifier, - ) -> Box> + Send>; - - /// Get an iterator over all shards. - fn shards(&self) -> Vec; - - // *** Block production - /// Remove operations identified by given hashes (and dependent operations) from the pool. - fn remove_invalid( - &self, - hashes: &[TxHash], - shard: ShardIdentifier, - inblock: bool, - ) -> Vec>; - - // *** logging - /// Returns pool status. - fn status(&self, shard: ShardIdentifier) -> PoolStatus; - - // *** logging / RPC / networking - /// Return an event stream of operations imported to the pool. - fn import_notification_stream(&self) -> ImportNotificationStream; - - // *** networking - /// Notify the pool about operations broadcast. - fn on_broadcasted(&self, propagations: HashMap>); - - /// Returns operation hash - fn hash_of(&self, xt: &TOP) -> TxHash; - - /// Return specific ready operation by hash, if there is one. - fn ready_transaction( - &self, - hash: &TxHash, - shard: ShardIdentifier, - ) -> Option>; - - /// Litentry: set the rpc response value - #[allow(clippy::type_complexity)] - fn update_connection_state(&self, updates: Vec<(TxHash, (Vec, bool))>); - - /// Litentry: swap the old hash with the new one in rpc connection registry - fn swap_rpc_connection_hash(&self, old_hash: TxHash, new_hash: TxHash); -} - -/// The source of the transaction. -/// -/// Depending on the source we might apply different validation schemes. -/// For instance we can disallow specific kinds of transactions if they were not produced -/// by our local node (for instance off-chain workers). -#[derive(Copy, Clone, PartialEq, Eq, Encode, Decode, Debug)] -pub enum TrustedOperationSource { - /// Transaction is already included in block. - /// - /// This means that we can't really tell where the transaction is coming from, - /// since it's already in the received block. Note that the custom validation logic - /// using either `Local` or `External` should most likely just allow `InBlock` - /// transactions as well. - #[codec(index = 0)] - InBlock, - - /// Transaction is coming from a local source. - /// - /// This means that the transaction was produced internally by the node - /// (for instance an Off-Chain Worker, or an Off-Chain Call), as opposed - /// to being received over the network. - #[codec(index = 1)] - Local, - - /// Transaction has been received externally. - /// - /// This means the transaction has been received from (usually) "untrusted" source, - /// for instance received over the network or RPC. - #[codec(index = 2)] - External, -} - -// Replacement of primitive function from_low_u64_be -pub fn from_low_u64_to_be_h256(val: u64) -> H256 { - let mut buf = [0x0; 8]; - BigEndian::write_u64(&mut buf, val); - let capped = core::cmp::min(H256::len_bytes(), 8); - let mut bytes = [0x0; core::mem::size_of::()]; - bytes[(H256::len_bytes() - capped)..].copy_from_slice(&buf[..capped]); - H256::from_slice(&bytes) -} - -#[cfg(test)] -pub mod tests { - - use super::*; - use alloc::string::ToString; - - #[test] - pub fn test_h256() { - let tests = vec![ - ( - from_low_u64_to_be_h256(0), - "0x0000000000000000000000000000000000000000000000000000000000000000", - ), - ( - from_low_u64_to_be_h256(2), - "0x0000000000000000000000000000000000000000000000000000000000000002", - ), - ( - from_low_u64_to_be_h256(15), - "0x000000000000000000000000000000000000000000000000000000000000000f", - ), - ( - from_low_u64_to_be_h256(16), - "0x0000000000000000000000000000000000000000000000000000000000000010", - ), - ( - from_low_u64_to_be_h256(1_000), - "0x00000000000000000000000000000000000000000000000000000000000003e8", - ), - ( - from_low_u64_to_be_h256(100_000), - "0x00000000000000000000000000000000000000000000000000000000000186a0", - ), - ( - from_low_u64_to_be_h256(u64::max_value()), - "0x000000000000000000000000000000000000000000000000ffffffffffffffff", - ), - ]; - - for (number, expected) in tests { - // workaround, as H256 in no_std does not implement (de)serialize - assert_eq!(expected.to_string(), format!("{:?}", number)); - } - } -} diff --git a/tee-worker/bitacross/core-primitives/top-pool/src/ready.rs b/tee-worker/bitacross/core-primitives/top-pool/src/ready.rs deleted file mode 100644 index c3dbf5afbb..0000000000 --- a/tee-worker/bitacross/core-primitives/top-pool/src/ready.rs +++ /dev/null @@ -1,800 +0,0 @@ -// This file is part of Substrate. - -// Copyright (C) 2018-2021 Parity Technologies (UK) Ltd. -// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 - -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with this program. If not, see . - -pub extern crate alloc; -use crate::{ - base_pool::TrustedOperation, - error, - future::WaitingTrustedOperations, - primitives::TxHash, - tracked_map::{self, ReadOnlyTrackedMap, TrackedMap}, -}; -use alloc::{boxed::Box, collections::BTreeSet, sync::Arc, vec, vec::Vec}; -use core::{cmp, cmp::Ord, default::Default}; -use itp_stf_primitives::types::ShardIdentifier; -use log::trace; -use sp_runtime::transaction_validity::TransactionTag as Tag; -use std::collections::{HashMap, HashSet}; - -type TopErrorResult = error::Result<(Vec>>, Vec)>; - -/// An in-pool operation reference. -/// -/// Should be cheap to clone. -#[derive(Debug)] -pub struct OperationRef { - /// The actual operation data. - pub operation: Arc>, - /// Unique id when operation was inserted into the pool. - pub insertion_id: u64, -} - -impl Clone for OperationRef { - fn clone(&self) -> Self { - OperationRef { operation: self.operation.clone(), insertion_id: self.insertion_id } - } -} - -impl Ord for OperationRef { - fn cmp(&self, other: &Self) -> cmp::Ordering { - self.operation - .priority - .cmp(&other.operation.priority) - .then_with(|| other.operation.valid_till.cmp(&self.operation.valid_till)) - .then_with(|| other.insertion_id.cmp(&self.insertion_id)) - } -} - -impl PartialOrd for OperationRef { - fn partial_cmp(&self, other: &Self) -> Option { - Some(self.cmp(other)) - } -} - -impl PartialEq for OperationRef { - fn eq(&self, other: &Self) -> bool { - self.cmp(other) == cmp::Ordering::Equal - } -} -impl Eq for OperationRef {} - -#[derive(Debug)] -pub struct ReadyTx { - /// A reference to a operation - pub operation: OperationRef, - /// A list of operations that get unlocked by this one - pub unlocks: Vec, - /// How many required tags are provided inherently - /// - /// Some operations might be already pruned from the queue, - /// so when we compute ready set we may consider this operations ready earlier. - pub requires_offset: usize, -} - -impl Clone for ReadyTx { - fn clone(&self) -> Self { - ReadyTx { - operation: self.operation.clone(), - unlocks: self.unlocks.clone(), - requires_offset: self.requires_offset, - } - } -} - -const HASH_READY: &str = r#" -Every time operation is imported its hash is placed in `ready` map and tags in `provided_tags`; -Every time operation is removed from the queue we remove the hash from `ready` map and from `provided_tags`; -Hence every hash retrieved from `provided_tags` is always present in `ready`; -qed -"#; - -#[derive(Debug)] -pub struct ReadyOperations { - /// Insertion id - insertion_id: HashMap, - /// tags that are provided by Ready operations - provided_tags: HashMap>, - /// Trusted Operations that are ready (i.e. don't have any requirements external to the pool) - ready: HashMap>>, - /// Best operations that are ready to be included to the block without any other previous operation. - best: HashMap>>, -} - -impl tracked_map::Size for ReadyTx { - fn size(&self) -> usize { - self.operation.operation.bytes - } -} - -impl Default for ReadyOperations { - fn default() -> Self { - ReadyOperations { - insertion_id: Default::default(), - provided_tags: Default::default(), - ready: Default::default(), - best: Default::default(), - } - } -} - -impl ReadyOperations { - /// Borrows a map of tags that are provided by operations in this queue. - pub fn provided_tags(&self, shard: ShardIdentifier) -> Option<&HashMap> { - if let Some(tag_pool) = &self.provided_tags.get(&shard) { - return Some(tag_pool) - } - None - } - - /// Returns an iterator of ready operations. - /// - /// Trusted Operations are returned in order: - /// 1. First by the dependencies: - /// - never return operation that requires a tag, which was not provided by one of the previously returned operations - /// 2. Then by priority: - /// - If there are two operations with all requirements satisfied the one with higher priority goes first. - /// 3. Then by the ttl that's left - /// - operations that are valid for a shorter time go first - /// 4. Lastly we sort by the time in the queue - /// - operations that are longer in the queue go first - pub fn get(&self, shard: ShardIdentifier) -> impl Iterator>> { - // check if shard tx pool exists - if let Some(ready_map) = self.ready.get(&shard) { - return BestIterator { - all: ready_map.get_read_only_clone(), - best: self.best.get(&shard).unwrap().clone(), - awaiting: Default::default(), - } - } - let tracked_map: TrackedMap> = Default::default(); - BestIterator { - all: tracked_map.get_read_only_clone(), - best: Default::default(), - awaiting: Default::default(), - } - } - /// Returns an iterator over all shards - pub fn get_shards(&self) -> Box + '_> { - // check if shard tx pool exists - Box::new(self.ready.keys()) - } - - /// Imports operations to the pool of ready operations. - /// - /// The operation needs to have all tags satisfied (be ready) by operations - /// that are in this queue. - /// Returns operations that were replaced by the one imported. - pub fn import( - &mut self, - tx: WaitingTrustedOperations, - shard: ShardIdentifier, - ) -> error::Result>>> { - assert!( - tx.is_ready(), - "Only ready operations can be imported. Missing: {:?}", - tx.missing_tags - ); - if let Some(ready_map) = &self.ready.get(&shard) { - assert!( - !ready_map.read().contains_key(&tx.operation.hash), - "TrustedOperation is already imported." - ); - } - // Get shard pool or create if not yet existing - let current_insertion_id = self.insertion_id.entry(shard).or_insert_with(|| { - let x: u64 = Default::default(); - x - }); - - *current_insertion_id += 1; - let insertion_id = *current_insertion_id; - let hash = tx.operation.hash; - let operation = tx.operation; - - let (replaced, unlocks) = self.replace_previous(&operation, shard)?; - - let mut goes_to_best = true; - let tracked_ready = self.ready.entry(shard).or_insert_with(|| { - let x: TrackedMap> = Default::default(); - x - }); - let mut ready = tracked_ready.write(); - let mut requires_offset = 0; - // Add links to operations that unlock the current one - let tag_map = self.provided_tags.entry(shard).or_insert_with(|| { - let x: HashMap = Default::default(); - x - }); - for tag in &operation.requires { - // Check if the operation that satisfies the tag is still in the queue. - if let Some(other) = tag_map.get(tag) { - let tx = ready.get_mut(other).expect(HASH_READY); - tx.unlocks.push(hash); - // this operation depends on some other, so it doesn't go to best directly. - goes_to_best = false; - } else { - requires_offset += 1; - } - } - - // update provided_tags - // call to replace_previous guarantees that we will be overwriting - // only entries that have been removed. - - for tag in &operation.provides { - tag_map.insert(tag.clone(), hash); - } - - let operation = OperationRef { operation, insertion_id }; - - // insert to best if it doesn't require any other operation to be included before it - let best_set = self.best.entry(shard).or_insert_with(|| { - let x: BTreeSet> = Default::default(); - x - }); - if goes_to_best { - best_set.insert(operation.clone()); - } - - // insert to Ready - ready.insert(hash, ReadyTx { operation, unlocks, requires_offset }); - - Ok(replaced) - } - - /// Fold a list of ready operations to compute a single value. - pub fn fold, &ReadyTx) -> Option>( - &mut self, - f: F, - shard: ShardIdentifier, - ) -> Option { - if let Some(ready_map) = self.ready.get(&shard) { - return ready_map.read().values().fold(None, f) - } - None - } - - /// Returns true if given hash is part of the queue. - pub fn contains(&self, hash: &TxHash, shard: ShardIdentifier) -> bool { - if let Some(ready_map) = self.ready.get(&shard) { - return ready_map.read().contains_key(hash) - } - false - } - - /// Retrive operation by hash - pub fn by_hash( - &self, - hash: &TxHash, - shard: ShardIdentifier, - ) -> Option>> { - self.by_hashes(&[*hash], shard).into_iter().next().unwrap_or(None) - } - - /// Retrieve operations by hash - pub fn by_hashes( - &self, - hashes: &[TxHash], - shard: ShardIdentifier, - ) -> Vec>>> { - if let Some(ready_map) = self.ready.get(&shard) { - let ready = ready_map.read(); - return hashes - .iter() - .map(|hash| ready.get(hash).map(|x| x.operation.operation.clone())) - .collect() - } - vec![] - } - - /// Removes a subtree of operations from the ready pool. - /// - /// NOTE removing a operation will also cause a removal of all operations that depend on that one - /// (i.e. the entire subgraph that this operation is a start of will be removed). - /// All removed operations are returned. - pub fn remove_subtree( - &mut self, - hashes: &[TxHash], - shard: ShardIdentifier, - ) -> Vec>> { - let to_remove = hashes.to_vec(); - self.remove_subtree_with_tag_filter(to_remove, None, shard) - } - - /// Removes a subtrees of operations trees starting from roots given in `to_remove`. - /// - /// We proceed with a particular branch only if there is at least one provided tag - /// that is not part of `provides_tag_filter`. I.e. the filter contains tags - /// that will stay in the pool, so that we can early exit and avoid descending. - fn remove_subtree_with_tag_filter( - &mut self, - mut to_remove: Vec, - provides_tag_filter: Option>, - shard: ShardIdentifier, - ) -> Vec>> { - let mut removed = vec![]; - if let Some(ready_map) = self.ready.get_mut(&shard) { - let mut ready = ready_map.write(); - while let Some(hash) = to_remove.pop() { - if let Some(mut tx) = ready.remove(&hash) { - let invalidated = tx.operation.operation.provides.iter().filter(|tag| { - provides_tag_filter - .as_ref() - .map(|filter| !filter.contains(&**tag)) - .unwrap_or(true) - }); - - let mut removed_some_tags = false; - // remove entries from provided_tags - for tag in invalidated { - removed_some_tags = true; - self.provided_tags.get_mut(&shard).unwrap().remove(tag); - } - - // remove from unlocks - for tag in &tx.operation.operation.requires { - if let Some(hash) = self.provided_tags.get(&shard).unwrap().get(tag) { - if let Some(tx) = ready.get_mut(hash) { - remove_item(&mut tx.unlocks, hash); - } - } - } - - // remove from best - self.best.get_mut(&shard).unwrap().remove(&tx.operation); - - if removed_some_tags { - // remove all operations that the current one unlocks - to_remove.append(&mut tx.unlocks); - } - - // add to removed - trace!(target: "txpool", "[{:?}] Removed as part of the subtree.", hash); - removed.push(tx.operation.operation); - } - } - } - - removed - } - - /// Removes operations that provide given tag. - /// - /// All operations that lead to a operation, which provides this tag - /// are going to be removed from the queue, but no other operations are touched - - /// i.e. all other subgraphs starting from given tag are still considered valid & ready. - pub fn prune_tags( - &mut self, - tag: Tag, - shard: ShardIdentifier, - ) -> Vec>> { - let mut removed = vec![]; - let mut to_remove = vec![tag]; - - if self.provided_tags.contains_key(&shard) { - while let Some(tag) = to_remove.pop() { - let res = self - .provided_tags - .get_mut(&shard) - .unwrap() - .remove(&tag) - .and_then(|hash| self.ready.get_mut(&shard).unwrap().write().remove(&hash)); - - if let Some(tx) = res { - let unlocks = tx.unlocks; - - // Make sure we remove it from best txs - self.best.get_mut(&shard).unwrap().remove(&tx.operation); - - let tx = tx.operation.operation; - - // prune previous operations as well - { - let hash = &tx.hash; - let mut find_previous = |tag| -> Option> { - let prev_hash = self.provided_tags.get(&shard).unwrap().get(tag)?; - let mut ready = self.ready.get_mut(&shard).unwrap().write(); - let tx2 = ready.get_mut(prev_hash)?; - remove_item(&mut tx2.unlocks, hash); - // We eagerly prune previous operations as well. - // But it might not always be good. - // Possible edge case: - // - tx provides two tags - // - the second tag enables some subgraph we don't know of yet - // - we will prune the operation - // - when we learn about the subgraph it will go to future - // - we will have to wait for re-propagation of that operation - // Alternatively the caller may attempt to re-import these operations. - if tx2.unlocks.is_empty() { - Some(tx2.operation.operation.provides.clone()) - } else { - None - } - }; - - // find previous operations - for tag in &tx.requires { - if let Some(mut tags_to_remove) = find_previous(tag) { - to_remove.append(&mut tags_to_remove); - } - } - } - - // add the operations that just got unlocked to `best` - for hash in unlocks { - if let Some(tx) = self.ready.get_mut(&shard).unwrap().write().get_mut(&hash) - { - tx.requires_offset += 1; - // this operation is ready - if tx.requires_offset == tx.operation.operation.requires.len() { - self.best.get_mut(&shard).unwrap().insert(tx.operation.clone()); - } - } - } - - // we also need to remove all other tags that this operation provides, - // but since all the hard work is done, we only clear the provided_tag -> hash - // mapping. - let current_tag = &tag; - for tag in &tx.provides { - let removed = self.provided_tags.get_mut(&shard).unwrap().remove(tag); - assert_eq!( - removed.as_ref(), - if current_tag == tag { None } else { Some(&tx.hash) }, - "The pool contains exactly one operation providing given tag; the removed operation - claims to provide that tag, so it has to be mapped to it's hash; qed" - ); - } - - removed.push(tx); - } - } - } - - removed - } - - /// Checks if the operation is providing the same tags as other operations. - /// - /// In case that's true it determines if the priority of operations that - /// we are about to replace is lower than the priority of the replacement operation. - /// We remove/replace old operations in case they have lower priority. - /// - /// In case replacement is successful returns a list of removed operations - /// and a list of hashes that are still in pool and gets unlocked by the new operation. - fn replace_previous( - &mut self, - tx: &TrustedOperation, - shard: ShardIdentifier, - ) -> TopErrorResult { - if let Some(provided_tag_map) = self.provided_tags.get(&shard) { - let (to_remove, unlocks) = { - // check if we are replacing a operation - let replace_hashes = tx - .provides - .iter() - .filter_map(|tag| provided_tag_map.get(tag)) - .collect::>(); - - // early exit if we are not replacing anything. - if replace_hashes.is_empty() { - return Ok((vec![], vec![])) - } - - // now check if collective priority is lower than the replacement operation. - let old_priority = { - let ready = self.ready.get(&shard).unwrap().read(); - replace_hashes - .iter() - .filter_map(|hash| ready.get(hash)) - .fold(0u64, |total, tx| { - total.saturating_add(tx.operation.operation.priority) - }) - }; - - // bail - the operation has too low priority to replace the old ones - if old_priority >= tx.priority { - return Err(error::Error::TooLowPriority(tx.priority)) - } - - // construct a list of unlocked operations - let unlocks = { - let ready = self.ready.get(&shard).unwrap().read(); - replace_hashes.iter().filter_map(|hash| ready.get(hash)).fold( - vec![], - |mut list, tx| { - list.extend(tx.unlocks.iter().cloned()); - list - }, - ) - }; - - (replace_hashes.into_iter().cloned().collect::>(), unlocks) - }; - - let new_provides = tx.provides.iter().cloned().collect::>(); - let removed = self.remove_subtree_with_tag_filter(to_remove, Some(new_provides), shard); - - return Ok((removed, unlocks)) - } - Ok((vec![], vec![])) - } - - /// Returns number of operations in this queue. - #[allow(clippy::len_without_is_empty)] - pub fn len(&self, shard: ShardIdentifier) -> usize { - self.ready.get(&shard).map_or(0, |ready_map| ready_map.len()) - } - - /// Returns sum of encoding lengths of all operations in this queue. - pub fn bytes(&self, shard: ShardIdentifier) -> usize { - self.ready.get(&shard).map_or(0, |ready_map| ready_map.bytes()) - } -} - -/// Iterator of ready operations ordered by priority. -pub struct BestIterator { - all: ReadOnlyTrackedMap>, - awaiting: HashMap)>, - best: BTreeSet>, -} - -/*impl Default for BestIterator { - let insertion_id = 0; - let operation = Arc::new(with_priority(3, 3)) - let tx_default = OperationRef { - insertion_id, - operation - }; - fn default() -> self.awaiting.insert("NA", (0, tx_default)) -}*/ - -impl BestIterator { - /// Depending on number of satisfied requirements insert given ref - /// either to awaiting set or to best set. - fn best_or_awaiting(&mut self, satisfied: usize, tx_ref: OperationRef) { - if satisfied >= tx_ref.operation.requires.len() { - // If we have satisfied all deps insert to best - self.best.insert(tx_ref); - } else { - // otherwise we're still awaiting for some deps - self.awaiting.insert(tx_ref.operation.hash, (satisfied, tx_ref)); - } - } -} - -impl Iterator for BestIterator { - type Item = Arc>; - - fn next(&mut self) -> Option { - loop { - let best = self.best.iter().next_back()?.clone(); - let best = self.best.take(&best)?; - - let next = self.all.read().get(&best.operation.hash).cloned(); - let ready = match next { - Some(ready) => ready, - // The operation is not in all, maybe it was removed in the meantime? - None => continue, - }; - - // Insert operations that just got unlocked. - for hash in &ready.unlocks { - // first check local awaiting operations - let res = if let Some((mut satisfied, tx_ref)) = self.awaiting.remove(hash) { - satisfied += 1; - Some((satisfied, tx_ref)) - // then get from the pool - } else { - self.all - .read() - .get(hash) - .map(|next| (next.requires_offset + 1, next.operation.clone())) - }; - - if let Some((satisfied, tx_ref)) = res { - self.best_or_awaiting(satisfied, tx_ref) - } - } - - return Some(best.operation) - } - } -} - -// See: https://github.com/rust-lang/rust/issues/40062 -fn remove_item(vec: &mut Vec, item: &T) { - if let Some(idx) = vec.iter().position(|i| i == item) { - vec.swap_remove(idx); - } -} - -#[cfg(test)] -pub mod tests { - use super::*; - use crate::primitives::TrustedOperationSource as Source; - use codec::Encode; - use sp_core::blake2_256; - - fn hash(index: u64) -> TxHash { - blake2_256(index.encode().as_slice()).into() - } - - fn tx(id: u8) -> TrustedOperation> { - TrustedOperation { - data: vec![id], - bytes: 1, - hash: hash(id as u64), - priority: 1, - valid_till: 2, - requires: vec![vec![1], vec![2]], - provides: vec![vec![3], vec![4]], - propagate: true, - source: Source::External, - } - } - - fn import( - ready: &mut ReadyOperations, - tx: TrustedOperation, - shard: ShardIdentifier, - ) -> error::Result>>> { - let x = WaitingTrustedOperations::new(tx, ready.provided_tags(shard), &[]); - ready.import(x, shard) - } - - #[test] - pub fn test_should_replace_transaction_that_provides_the_same_tag() { - // given - let shard = ShardIdentifier::default(); - let mut ready = ReadyOperations::default(); - let mut tx1 = tx(1); - tx1.requires.clear(); - let mut tx2 = tx(2); - tx2.requires.clear(); - tx2.provides = vec![vec![3]]; - let mut tx3 = tx(3); - tx3.requires.clear(); - tx3.provides = vec![vec![4]]; - - // when - import(&mut ready, tx2, shard).unwrap(); - import(&mut ready, tx3, shard).unwrap(); - assert_eq!(ready.get(shard).count(), 2); - - // too low priority - import(&mut ready, tx1.clone(), shard).unwrap_err(); - - tx1.priority = 10; - import(&mut ready, tx1, shard).unwrap(); - - // then - assert_eq!(ready.get(shard).count(), 1); - } - - #[test] - pub fn test_should_replace_multiple_transactions_correctly() { - // given - let shard = ShardIdentifier::default(); - let mut ready = ReadyOperations::default(); - let mut tx0 = tx(0); - tx0.requires = vec![]; - tx0.provides = vec![vec![0]]; - let mut tx1 = tx(1); - tx1.requires = vec![]; - tx1.provides = vec![vec![1]]; - let mut tx2 = tx(2); - tx2.requires = vec![vec![0], vec![1]]; - tx2.provides = vec![vec![2], vec![3]]; - let mut tx3 = tx(3); - tx3.requires = vec![vec![2]]; - tx3.provides = vec![vec![4]]; - let mut tx4 = tx(4); - tx4.requires = vec![vec![3]]; - tx4.provides = vec![vec![5]]; - // replacement - let mut tx2_2 = tx(5); - tx2_2.requires = vec![vec![0], vec![1]]; - tx2_2.provides = vec![vec![2]]; - tx2_2.priority = 10; - - for tx in vec![tx0, tx1, tx2, tx3, tx4] { - import(&mut ready, tx, shard).unwrap(); - } - assert_eq!(ready.get(shard).count(), 5); - - // when - import(&mut ready, tx2_2, shard).unwrap(); - - // then - assert_eq!(ready.get(shard).count(), 3); - } - - #[test] - pub fn test_should_return_best_transactions_in_correct_order() { - // given - let shard = ShardIdentifier::default(); - let mut ready = ReadyOperations::default(); - let mut tx1 = tx(1); - tx1.requires.clear(); - let mut tx2 = tx(2); - tx2.requires = tx1.provides.clone(); - tx2.provides = vec![vec![106]]; - let mut tx3 = tx(3); - tx3.requires = vec![tx1.provides[0].clone(), vec![106]]; - tx3.provides = vec![]; - let mut tx4 = tx(4); - tx4.requires = vec![tx1.provides[0].clone()]; - tx4.provides = vec![]; - let tx5 = TrustedOperation { - data: vec![5], - bytes: 1, - hash: hash(5), - priority: 1, - valid_till: u64::max_value(), // use the max_value() here for testing. - requires: vec![tx1.provides[0].clone()], - provides: vec![], - propagate: true, - source: Source::External, - }; - - // when - for tx in vec![tx1, tx2, tx3, tx4, tx5] { - import(&mut ready, tx, shard).unwrap(); - } - - // then - assert_eq!(ready.best.len(), 1); - - let mut it = ready.get(shard).map(|tx| tx.data[0]); - - assert_eq!(it.next(), Some(1)); - assert_eq!(it.next(), Some(2)); - assert_eq!(it.next(), Some(3)); - assert_eq!(it.next(), Some(4)); - assert_eq!(it.next(), Some(5)); - assert_eq!(it.next(), None); - } - - #[test] - pub fn test_should_order_refs() { - let mut id = 1; - let mut with_priority = |priority, longevity| { - id += 1; - let mut tx = tx(id); - tx.priority = priority; - tx.valid_till = longevity; - tx - }; - // higher priority = better - assert!( - OperationRef { operation: Arc::new(with_priority(3, 3)), insertion_id: 1 } - > OperationRef { operation: Arc::new(with_priority(2, 3)), insertion_id: 2 } - ); - // lower validity = better - assert!( - OperationRef { operation: Arc::new(with_priority(3, 2)), insertion_id: 1 } - > OperationRef { operation: Arc::new(with_priority(3, 3)), insertion_id: 2 } - ); - // lower insertion_id = better - assert!( - OperationRef { operation: Arc::new(with_priority(3, 3)), insertion_id: 1 } - > OperationRef { operation: Arc::new(with_priority(3, 3)), insertion_id: 2 } - ); - } -} diff --git a/tee-worker/bitacross/core-primitives/top-pool/src/rotator.rs b/tee-worker/bitacross/core-primitives/top-pool/src/rotator.rs deleted file mode 100644 index 6cfec05fa7..0000000000 --- a/tee-worker/bitacross/core-primitives/top-pool/src/rotator.rs +++ /dev/null @@ -1,221 +0,0 @@ -// This file is part of Substrate. - -// Copyright (C) 2018-2020 Parity Technologies (UK) Ltd. -// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 - -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with this program. If not, see . - -//! Rotate extrinsic inside the pool. -//! -//! Keeps only recent extrinsic and discard the ones kept for a significant amount of time. -//! Discarded extrinsics are banned so that they don't get re-imported again. - -#[cfg(all(not(feature = "std"), feature = "sgx"))] -use std::sync::SgxRwLock as RwLock; - -#[cfg(feature = "std")] -use std::sync::RwLock; - -use crate::{base_pool::TrustedOperation, primitives::TxHash}; -use std::{ - collections::HashMap, - iter, - time::{Duration, Instant}, -}; - -/// Expected size of the banned extrinsics cache. -const EXPECTED_SIZE: usize = 2048; - -/// Pool rotator is responsible to only keep fresh extrinsics in the pool. -/// -/// Extrinsics that occupy the pool for too long are culled and temporarily banned from entering -/// the pool again. -pub struct PoolRotator { - /// How long the extrinsic is banned for. - ban_time: Duration, - /// Currently banned extrinsics. - banned_until: RwLock>, -} - -impl Default for PoolRotator { - fn default() -> Self { - PoolRotator { ban_time: Duration::from_secs(60 * 30), banned_until: Default::default() } - } -} - -impl PoolRotator { - /// Returns `true` if extrinsic hash is currently banned. - pub fn is_banned(&self, hash: &TxHash) -> bool { - self.banned_until.read().unwrap().contains_key(hash) - } - - /// Bans given set of hashes. - pub fn ban(&self, now: &Instant, hashes: impl IntoIterator) { - let mut banned = self.banned_until.write().unwrap(); - - for hash in hashes { - banned.insert(hash, *now + self.ban_time); - } - - if banned.len() > 2 * EXPECTED_SIZE { - while banned.len() > EXPECTED_SIZE { - if let Some(key) = banned.keys().next().cloned() { - banned.remove(&key); - } - } - } - } - - /// Bans extrinsic if it's stale. - /// - /// Returns `true` if extrinsic is stale and got banned. - pub fn ban_if_stale( - &self, - now: &Instant, - current_block: u64, - xt: &TrustedOperation, - ) -> bool { - if xt.valid_till > current_block { - return false - } - - self.ban(now, iter::once(xt.hash)); - true - } - - /// Removes timed bans. - pub fn clear_timeouts(&self, now: &Instant) { - let mut banned = self.banned_until.write().unwrap(); - - banned.retain(|_, &mut v| v >= *now); - } -} - -#[cfg(test)] -pub mod tests { - use super::*; - use crate::primitives::TrustedOperationSource; - use codec::Encode; - use sp_core::blake2_256; - - type Ex = (); - - fn rotator() -> PoolRotator { - PoolRotator { ban_time: Duration::from_millis(1000), ..Default::default() } - } - - fn hash(index: u64) -> TxHash { - blake2_256(index.encode().as_slice()).into() - } - - fn tx() -> (TxHash, TrustedOperation) { - let hash = hash(5); - let tx = TrustedOperation { - data: (), - bytes: 1, - hash, - priority: 5, - valid_till: 1, - requires: vec![], - provides: vec![], - propagate: true, - source: TrustedOperationSource::External, - }; - - (hash, tx) - } - - #[test] - pub fn test_should_not_ban_if_not_stale() { - // given - let (hash, tx) = tx(); - let rotator = rotator(); - assert!(!rotator.is_banned(&hash)); - let now = Instant::now(); - let past_block = 0; - - // when - assert!(!rotator.ban_if_stale(&now, past_block, &tx)); - - // then - assert!(!rotator.is_banned(&hash)); - } - - #[test] - pub fn test_should_ban_stale_extrinsic() { - // given - let (hash, tx) = tx(); - let rotator = rotator(); - assert!(!rotator.is_banned(&hash)); - - // when - assert!(rotator.ban_if_stale(&Instant::now(), 1, &tx)); - - // then - assert!(rotator.is_banned(&hash)); - } - - #[test] - pub fn test_should_clear_banned() { - // given - let (hash, tx) = tx(); - let rotator = rotator(); - assert!(rotator.ban_if_stale(&Instant::now(), 1, &tx)); - assert!(rotator.is_banned(&hash)); - - // when - let future = Instant::now() + rotator.ban_time + rotator.ban_time; - rotator.clear_timeouts(&future); - - // then - assert!(!rotator.is_banned(&hash)); - } - - #[test] - pub fn test_should_garbage_collect() { - // given - fn tx_with(i: u64, valid_till: u64) -> TrustedOperation { - let hash = hash(i); - TrustedOperation { - data: (), - bytes: 2, - hash, - priority: 5, - valid_till, - requires: vec![], - provides: vec![], - propagate: true, - source: TrustedOperationSource::External, - } - } - - let rotator = rotator(); - - let now = Instant::now(); - let past_block = 0; - - // when - for i in 0..2 * EXPECTED_SIZE { - let tx = tx_with(i as u64, past_block); - assert!(rotator.ban_if_stale(&now, past_block, &tx)); - } - assert_eq!(rotator.banned_until.read().unwrap().len(), 2 * EXPECTED_SIZE); - - // then - let tx = tx_with(2 * EXPECTED_SIZE as u64, past_block); - // trigger a garbage collection - assert!(rotator.ban_if_stale(&now, past_block, &tx)); - assert_eq!(rotator.banned_until.read().unwrap().len(), EXPECTED_SIZE); - } -} diff --git a/tee-worker/bitacross/core-primitives/top-pool/src/tracked_map.rs b/tee-worker/bitacross/core-primitives/top-pool/src/tracked_map.rs deleted file mode 100644 index dacbe841dd..0000000000 --- a/tee-worker/bitacross/core-primitives/top-pool/src/tracked_map.rs +++ /dev/null @@ -1,198 +0,0 @@ -// This file is part of Substrate. - -// Copyright (C) 2018-2020 Parity Technologies (UK) Ltd. -// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 - -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with this program. If not, see . - -pub extern crate alloc; -use alloc::sync::Arc; -use core::{ - clone::Clone, - cmp, hash, - sync::atomic::{AtomicIsize, Ordering as AtomicOrdering}, -}; -use std::collections::{hash_map::Values, HashMap}; - -//use parking_lot::{RwLock, RwLockWriteGuard, RwLockReadGuard}; - -/// Something that can report it's size. -pub trait Size { - fn size(&self) -> usize; -} - -/// Map with size tracking. -/// -/// Size reported might be slightly off and only approximately true. -#[derive(Debug)] -pub struct TrackedMap { - index: Arc>, - bytes: AtomicIsize, - length: AtomicIsize, -} - -impl Default for TrackedMap { - fn default() -> Self { - Self { index: Arc::new(HashMap::new()), bytes: 0.into(), length: 0.into() } - } -} - -impl TrackedMap { - /// Current tracked length of the content. - pub fn len(&self) -> usize { - cmp::max(self.length.load(AtomicOrdering::Relaxed), 0) as usize - } - - /// Returns true if Map is empty - pub fn is_empty(&self) -> bool { - self.length.load(AtomicOrdering::Relaxed) == 0 - } - - /// Current sum of content length. - pub fn bytes(&self) -> usize { - cmp::max(self.bytes.load(AtomicOrdering::Relaxed), 0) as usize - } - - /// Read-only clone of the interior. - pub fn get_read_only_clone(&self) -> ReadOnlyTrackedMap { - ReadOnlyTrackedMap(self.index.clone()) - } - - /// Read Access - no data race safety - pub fn read(&self) -> TrackedMapReadAccess { - TrackedMapReadAccess { inner_guard: self.index.clone() } - } - - /// Write Access - no data race safety - pub fn write(&mut self) -> TrackedMapWriteAccess { - TrackedMapWriteAccess { - //inner_guard: self.index.make_mut(&self), - inner_guard: Arc::make_mut(&mut self.index), - bytes: &self.bytes, - length: &self.length, - } - } -} - -/// Read-only access to map. -/// -/// The only thing can be done is .read(). -pub struct ReadOnlyTrackedMap(Arc>); - -impl ReadOnlyTrackedMap -where - K: Eq + hash::Hash, -{ - /// Lock map for read. - pub fn read(&self) -> TrackedMapReadAccess { - TrackedMapReadAccess { inner_guard: self.0.clone() } - } -} - -pub struct TrackedMapReadAccess { - inner_guard: Arc>, -} - -impl TrackedMapReadAccess -where - K: Eq + hash::Hash, -{ - /// Returns true if map contains key. - pub fn contains_key(&self, key: &K) -> bool { - self.inner_guard.contains_key(key) - } - - /// Returns reference to the contained value by key, if exists. - pub fn get(&self, key: &K) -> Option<&V> { - self.inner_guard.get(key) - } - - /// Returns iterator over all values. - pub fn values(&self) -> Values { - self.inner_guard.values() - } -} - -pub struct TrackedMapWriteAccess<'a, K, V> { - bytes: &'a AtomicIsize, - length: &'a AtomicIsize, - inner_guard: &'a mut HashMap, -} - -impl<'a, K, V> TrackedMapWriteAccess<'a, K, V> -where - K: Eq + hash::Hash, - V: Size, -{ - /// Insert value and return previous (if any). - pub fn insert(&mut self, key: K, val: V) -> Option { - let new_bytes = val.size(); - self.bytes.fetch_add(new_bytes as isize, AtomicOrdering::Relaxed); - self.length.fetch_add(1, AtomicOrdering::Relaxed); - self.inner_guard.insert(key, val).map(|old_val| { - self.bytes.fetch_sub(old_val.size() as isize, AtomicOrdering::Relaxed); - self.length.fetch_sub(1, AtomicOrdering::Relaxed); - old_val - }) - } - - /// Remove value by key. - pub fn remove(&mut self, key: &K) -> Option { - let val = self.inner_guard.remove(key); - if let Some(size) = val.as_ref().map(Size::size) { - self.bytes.fetch_sub(size as isize, AtomicOrdering::Relaxed); - self.length.fetch_sub(1, AtomicOrdering::Relaxed); - } - val - } - - /// Returns mutable reference to the contained value by key, if exists. - pub fn get_mut(&mut self, key: &K) -> Option<&mut V> { - self.inner_guard.get_mut(key) - } -} - -#[cfg(test)] -pub mod tests { - - use super::*; - - impl Size for i32 { - fn size(&self) -> usize { - *self as usize / 10 - } - } - - #[test] - pub fn test_basic() { - let mut map = TrackedMap::default(); - - assert!(map.is_empty()); - - map.write().insert(5, 10); - map.write().insert(6, 20); - - assert_eq!(map.bytes(), 3); - assert_eq!(map.len(), 2); - - map.write().insert(6, 30); - - assert_eq!(map.bytes(), 4); - assert_eq!(map.len(), 2); - - map.write().remove(&6); - assert_eq!(map.bytes(), 1); - assert_eq!(map.len(), 1); - } -} diff --git a/tee-worker/bitacross/core-primitives/top-pool/src/validated_pool.rs b/tee-worker/bitacross/core-primitives/top-pool/src/validated_pool.rs deleted file mode 100644 index 0d66fca8b8..0000000000 --- a/tee-worker/bitacross/core-primitives/top-pool/src/validated_pool.rs +++ /dev/null @@ -1,738 +0,0 @@ -// This file is part of Substrate. - -// Copyright (C) 2018-2020 Parity Technologies (UK) Ltd. -// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 - -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with this program. If not, see . - -#[cfg(all(not(feature = "std"), feature = "sgx"))] -use crate::sgx_reexport_prelude::*; - -#[cfg(all(not(feature = "std"), feature = "sgx"))] -use std::sync::SgxMutex as Mutex; -#[cfg(all(not(feature = "std"), feature = "sgx"))] -use std::sync::SgxRwLock as RwLock; - -#[cfg(feature = "std")] -use std::sync::Mutex; -#[cfg(feature = "std")] -use std::sync::RwLock; - -use crate::{ - base_pool as base, - base_pool::PruneStatus, - error, - listener::Listener, - pool::{ChainApi, EventStream, Options, TransactionFor}, - primitives::{PoolStatus, TrustedOperationSource, TxHash}, - rotator::PoolRotator, -}; -use core::{marker::PhantomData, result::Result}; -use itc_direct_rpc_server::SendRpcResponse; -use itp_stf_primitives::types::ShardIdentifier; -use itp_types::BlockHash as SidechainBlockHash; -use jsonrpc_core::futures::channel::mpsc::{channel, Sender}; -use sp_runtime::{ - generic::BlockId, - traits::SaturatedConversion, - transaction_validity::{TransactionTag as Tag, ValidTransaction}, -}; -use std::{ - collections::{HashMap, HashSet}, - format, - string::String, - sync::Arc, - time::Instant, - vec, - vec::Vec, -}; - -/// Pre-validated operation. Validated pool only accepts operations wrapped in this enum. -#[derive(Debug)] -pub enum ValidatedOperation { - /// TrustedOperation that has been validated successfully. - Valid(base::TrustedOperation), - /// TrustedOperation that is invalid. - Invalid(TxHash, Error), - /// TrustedOperation which validity can't be determined. - /// - /// We're notifying watchers about failure, if 'unknown' operation is submitted. - Unknown(TxHash, Error), -} - -impl ValidatedOperation { - /// Consume validity result, operation data and produce ValidTransaction. - pub fn valid_at( - at: u64, - hash: TxHash, - source: TrustedOperationSource, - data: Ex, - bytes: usize, - validity: ValidTransaction, - ) -> Self { - Self::Valid(base::TrustedOperation { - data, - bytes, - hash, - source, - priority: validity.priority, - requires: validity.requires, - provides: validity.provides, - propagate: validity.propagate, - valid_till: at.saturated_into::().saturating_add(validity.longevity), - }) - } -} - -/// A type of validated operation stored in the pool. -pub type ValidatedOperationFor = ValidatedOperation::Error>; - -/// Pool that deals with validated operations. -pub struct ValidatedPool -where - R: SendRpcResponse, -{ - api: Arc, - options: Options, - listener: RwLock>, - pool: RwLock>, - import_notification_sinks: Mutex>>, - rotator: PoolRotator, - _phantom: PhantomData, -} - -impl ValidatedPool -where - R: SendRpcResponse, - TOP: core::fmt::Debug + Send + Sync + Clone, -{ - /// Create a new operation pool. - pub fn new(options: Options, api: Arc, rpc_response_sender: Arc) -> Self { - let base_pool = base::BasePool::new(options.reject_future_operations); - ValidatedPool { - options, - listener: RwLock::new(Listener::new(rpc_response_sender)), - api, - pool: RwLock::new(base_pool), - import_notification_sinks: Default::default(), - rotator: Default::default(), - _phantom: Default::default(), - } - } - - /// Bans given set of hashes. - pub fn ban(&self, now: &Instant, hashes: impl IntoIterator) { - self.rotator.ban(now, hashes) - } - - /// Returns true if operation with given hash is currently banned from the pool. - pub fn is_banned(&self, hash: &TxHash) -> bool { - self.rotator.is_banned(hash) - } - - /// A fast check before doing any further processing of a operation, like validation. - /// - /// If `ingore_banned` is `true`, it will not check if the operation is banned. - /// - /// It checks if the operation is already imported or banned. If so, it returns an error. - pub fn check_is_known( - &self, - tx_hash: &TxHash, - ignore_banned: bool, - shard: ShardIdentifier, - ) -> Result<(), B::Error> { - if !ignore_banned && self.is_banned(tx_hash) { - Err(error::Error::TemporarilyBanned.into()) - } else if self.pool.read().unwrap().is_imported(tx_hash, shard) { - Err(error::Error::AlreadyImported.into()) - } else { - Ok(()) - } - } - - /// Imports a bunch of pre-validated operations to the pool. - pub fn submit( - &self, - txs: impl IntoIterator>, - shard: ShardIdentifier, - ) -> Vec> { - let results = txs - .into_iter() - .map(|validated_tx| self.submit_one(validated_tx, shard)) - .collect::>(); - - // only enforce limits if there is at least one imported operation - let removed = if results.iter().any(|res| res.is_ok()) { - self.enforce_limits(shard) - } else { - Default::default() - }; - - results - .into_iter() - .map(|res| match res { - Ok(ref hash) if removed.contains(hash) => - Err(error::Error::ImmediatelyDropped.into()), - other => other, - }) - .collect() - } - - /// Submit single pre-validated operation to the pool. - fn submit_one( - &self, - tx: ValidatedOperationFor, - shard: ShardIdentifier, - ) -> Result { - match tx { - ValidatedOperation::Valid(tx) => { - let imported = - self.pool.write().map_err(|_| error::Error::UnlockError)?.import(tx, shard)?; - - if let base::Imported::Ready { ref hash, .. } = imported { - self.import_notification_sinks - .lock() - .map_err(|_| error::Error::UnlockError)? - .retain_mut(|sink| match sink.try_send(*hash) { - Ok(()) => true, - Err(e) => - if e.is_full() { - log::warn!(target: "txpool", "[{:?}] Trying to notify an import but the channel is full", hash); - true - } else { - false - }, - }); - } - - let mut listener = self.listener.write().map_err(|_| error::Error::UnlockError)?; - fire_events(&mut listener, &imported); - Ok(*imported.hash()) - }, - ValidatedOperation::Invalid(hash, err) => { - self.rotator.ban(&Instant::now(), core::iter::once(hash)); - Err(err) - }, - ValidatedOperation::Unknown(hash, err) => { - self.listener.write().unwrap().invalid(&hash); - Err(err) - }, - } - } - - fn enforce_limits(&self, shard: ShardIdentifier) -> HashSet { - let status = self.pool.read().unwrap().status(shard); - let ready_limit = &self.options.ready; - let future_limit = &self.options.future; - - log::debug!(target: "txpool", "Pool Status: {:?}", status); - if ready_limit.is_exceeded(status.ready, status.ready_bytes) - || future_limit.is_exceeded(status.future, status.future_bytes) - { - log::debug!( - target: "txpool", - "Enforcing limits ({}/{}kB ready, {}/{}kB future", - ready_limit.count, ready_limit.total_bytes / 1024, - future_limit.count, future_limit.total_bytes / 1024, - ); - - // clean up the pool - let removed = { - let mut pool = self.pool.write().unwrap(); - let removed = pool - .enforce_limits(ready_limit, future_limit, shard) - .into_iter() - .map(|x| x.hash) - .collect::>(); - // ban all removed operations - self.rotator.ban(&Instant::now(), removed.iter().copied()); - removed - }; - if !removed.is_empty() { - log::debug!(target: "txpool", "Enforcing limits: {} dropped", removed.len()); - } - - // run notifications - let mut listener = self.listener.write().unwrap(); - for h in &removed { - listener.dropped(h, None); - } - - removed - } else { - Default::default() - } - } - - /// Import a single extrinsic and starts to watch their progress in the pool. - pub fn submit_and_watch( - &self, - tx: ValidatedOperationFor, - shard: ShardIdentifier, - ) -> Result { - match tx { - ValidatedOperation::Valid(tx) => { - let hash_result = self - .submit(core::iter::once(ValidatedOperation::Valid(tx)), shard) - .pop() - .expect("One extrinsic passed; one result returned; qed"); - // TODO: How to return / notice if Future or Ready queue? - if let Ok(hash) = hash_result { - self.listener.write().unwrap().create_watcher(hash); - } - hash_result - }, - ValidatedOperation::Invalid(hash, err) => { - self.rotator.ban(&Instant::now(), core::iter::once(hash)); - Err(err) - }, - ValidatedOperation::Unknown(_, err) => Err(err), - } - } - - /// Resubmits revalidated operations back to the pool. - /// - /// Removes and then submits passed operations and all dependent operations. - /// Transactions that are missing from the pool are not submitted. - pub fn resubmit( - &self, - mut updated_transactions: HashMap>, - shard: ShardIdentifier, - ) { - #[derive(Debug, Clone, Copy, PartialEq)] - enum Status { - Future, - Ready, - Failed, - Dropped, - } - - let (mut initial_statuses, final_statuses) = { - let mut pool = self.pool.write().unwrap(); - - // remove all passed operations from the ready/future queues - // (this may remove additional operations as well) - // - // for every operation that has an entry in the `updated_transactions`, - // we store updated validation result in txs_to_resubmit - // for every operation that has no entry in the `updated_transactions`, - // we store last validation result (i.e. the pool entry) in txs_to_resubmit - let mut initial_statuses = HashMap::new(); - let mut txs_to_resubmit = Vec::with_capacity(updated_transactions.len()); - while !updated_transactions.is_empty() { - let hash = updated_transactions - .keys() - .next() - .cloned() - .expect("operations is not empty; qed"); - - // note we are not considering tx with hash invalid here - we just want - // to remove it along with dependent operations and `remove_subtree()` - // does exactly what we need - let removed = pool.remove_subtree(&[hash], shard); - for removed_tx in removed { - let removed_hash = removed_tx.hash; - let updated_transaction = updated_transactions.remove(&removed_hash); - let tx_to_resubmit = if let Some(updated_tx) = updated_transaction { - updated_tx - } else { - // in most cases we'll end up in successful `try_unwrap`, but if not - // we still need to reinsert operation back to the pool => duplicate call - let operation = match Arc::try_unwrap(removed_tx) { - Ok(operation) => operation, - Err(operation) => operation.duplicate(), - }; - ValidatedOperation::Valid(operation) - }; - - initial_statuses.insert(removed_hash, Status::Ready); - txs_to_resubmit.push((removed_hash, tx_to_resubmit)); - } - // make sure to remove the hash even if it's not present in the pool any more. - updated_transactions.remove(&hash); - } - - // if we're rejecting future operations, then insertion order matters here: - // if tx1 depends on tx2, then if tx1 is inserted before tx2, then it goes - // to the future queue and gets rejected immediately - // => let's temporary stop rejection and clear future queue before return - pool.with_futures_enabled(|pool, reject_future_operations| { - // now resubmit all removed operations back to the pool - let mut final_statuses = HashMap::new(); - for (hash, tx_to_resubmit) in txs_to_resubmit { - match tx_to_resubmit { - ValidatedOperation::Valid(tx) => match pool.import(tx, shard) { - Ok(imported) => match imported { - base::Imported::Ready { promoted, failed, removed, .. } => { - final_statuses.insert(hash, Status::Ready); - for hash in promoted { - final_statuses.insert(hash, Status::Ready); - } - for hash in failed { - final_statuses.insert(hash, Status::Failed); - } - for tx in removed { - final_statuses.insert(tx.hash, Status::Dropped); - } - }, - base::Imported::Future { .. } => { - final_statuses.insert(hash, Status::Future); - }, - }, - Err(err) => { - // we do not want to fail if single operation import has failed - // nor we do want to propagate this error, because it could tx unknown to caller - // => let's just notify listeners (and issue debug message) - log::warn!( - target: "txpool", - "[{:?}] Removing invalid operation from update: {:?}", - hash, - err, - ); - final_statuses.insert(hash, Status::Failed); - }, - }, - ValidatedOperation::Invalid(_, _) | ValidatedOperation::Unknown(_, _) => { - final_statuses.insert(hash, Status::Failed); - }, - } - } - - // if the pool is configured to reject future operations, let's clear the future - // queue, updating final statuses as required - if reject_future_operations { - for future_tx in pool.clear_future(shard) { - final_statuses.insert(future_tx.hash, Status::Dropped); - } - } - - (initial_statuses, final_statuses) - }) - }; - - // and now let's notify listeners about status changes - let mut listener = self.listener.write().unwrap(); - for (hash, final_status) in final_statuses { - let initial_status = initial_statuses.remove(&hash); - if initial_status.is_none() || Some(final_status) != initial_status { - match final_status { - Status::Future => listener.future(&hash), - Status::Ready => listener.ready(&hash, None), - Status::Dropped => listener.dropped(&hash, None), - Status::Failed => listener.invalid(&hash), - } - } - } - } - - /// For each extrinsic, returns tags that it provides (if known), or None (if it is unknown). - pub fn extrinsics_tags( - &self, - hashes: &[TxHash], - shard: ShardIdentifier, - ) -> Vec>> { - self.pool - .read() - .unwrap() - .by_hashes(hashes, shard) - .into_iter() - .map(|existing_in_pool| existing_in_pool.map(|operation| operation.provides.to_vec())) - .collect() - } - - /// Get ready operation by hash - pub fn ready_by_hash( - &self, - hash: &TxHash, - shard: ShardIdentifier, - ) -> Option> { - self.pool.read().unwrap().ready_by_hash(hash, shard) - } - - /// Prunes ready operations that provide given list of tags. - pub fn prune_tags( - &self, - tags: impl IntoIterator, - shard: ShardIdentifier, - ) -> Result, B::Error> { - // Perform tag-based pruning in the base pool - let status = self.pool.write().unwrap().prune_tags(tags, shard); - // Notify event listeners of all operations - // that were promoted to `Ready` or were dropped. - { - let mut listener = self.listener.write().unwrap(); - for promoted in &status.promoted { - fire_events(&mut *listener, promoted); - } - for f in &status.failed { - listener.dropped(f, None); - } - } - - Ok(status) - } - - /// Resubmit operations that have been revalidated after prune_tags call. - pub fn resubmit_pruned( - &self, - at: &BlockId, - known_imported_hashes: impl IntoIterator + Clone, - pruned_hashes: Vec, - pruned_xts: Vec>, - shard: ShardIdentifier, - ) -> Result<(), B::Error> - where - ::Error: error::IntoPoolError, - { - debug_assert_eq!(pruned_hashes.len(), pruned_xts.len()); - - // Resubmit pruned operations - let results = self.submit(pruned_xts, shard); - - // Collect the hashes of operations that now became invalid (meaning that they are successfully pruned). - let hashes = results.into_iter().enumerate().filter_map(|(idx, r)| { - match r.map_err(error::IntoPoolError::into_pool_error) { - Err(Ok(error::Error::InvalidTrustedOperation)) => Some(pruned_hashes[idx]), - _ => None, - } - }); - // Fire `pruned` notifications for collected hashes and make sure to include - // `known_imported_hashes` since they were just imported as part of the block. - let hashes = hashes.chain(known_imported_hashes.into_iter()); - self.fire_pruned(at, hashes)?; - - // perform regular cleanup of old operations in the pool - // and update temporary bans. - self.clear_stale(at, shard)?; - Ok(()) - } - - /// Fire notifications for pruned operations. - pub fn fire_pruned( - &self, - at: &BlockId, - hashes: impl Iterator, - ) -> Result<(), B::Error> { - let header_hash = self - .api - .block_id_to_hash(at)? - .ok_or_else(|| error::Error::InvalidBlockId(format!("{:?}", at)))?; - let mut listener = self.listener.write().unwrap(); - let mut set = HashSet::with_capacity(hashes.size_hint().0); - for h in hashes { - // `hashes` has possibly duplicate hashes. - // we'd like to send out the `InBlock` notification only once. - if !set.contains(&h) { - listener.pruned(header_hash, &h); - set.insert(h); - } - } - Ok(()) - } - - /// Removes stale operations from the pool. - /// - /// Stale operations are operation beyond their longevity period. - /// Note this function does not remove operations that are already included in the chain. - /// See `prune_tags` if you want this. - pub fn clear_stale( - &self, - at: &BlockId, - shard: ShardIdentifier, - ) -> Result<(), B::Error> { - let block_number = self - .api - .block_id_to_number(at)? - .ok_or_else(|| error::Error::InvalidBlockId(format!("{:?}", at)))? - .saturated_into::(); - let now = Instant::now(); - let to_remove = { - self.ready(shard) - .filter(|tx| self.rotator.ban_if_stale(&now, block_number, tx)) - .map(|tx| tx.hash) - .collect::>() - }; - let futures_to_remove: Vec = { - let p = self.pool.read().unwrap(); - let mut hashes = Vec::new(); - for tx in p.futures(shard) { - if self.rotator.ban_if_stale(&now, block_number, tx) { - hashes.push(tx.hash); - } - } - hashes - }; - // removing old operations - self.remove_invalid(&to_remove, shard, false); - self.remove_invalid(&futures_to_remove, shard, false); - // clear banned operations timeouts - self.rotator.clear_timeouts(&now); - - Ok(()) - } - - /// Get rotator reference. - /// only used for test - pub fn rotator(&self) -> &PoolRotator { - &self.rotator - } - - /// Get api reference. - pub fn api(&self) -> &B { - &self.api - } - - /// Return an event stream of notifications for when operations are imported to the pool. - /// - /// Consumers of this stream should use the `ready` method to actually get the - /// pending operations in the right order. - pub fn import_notification_stream(&self) -> EventStream { - const CHANNEL_BUFFER_SIZE: usize = 1024; - - let (sink, stream) = channel(CHANNEL_BUFFER_SIZE); - self.import_notification_sinks.lock().unwrap().push(sink); - stream - } - - /// Invoked when extrinsics are broadcasted. - pub fn on_broadcasted(&self, propagated: HashMap>) { - let mut listener = self.listener.write().unwrap(); - for (hash, peers) in propagated.into_iter() { - listener.broadcasted(&hash, peers); - } - } - - /// Remove a subtree of operations from the pool and mark them invalid. - /// - /// The operations passed as an argument will be additionally banned - /// to prevent them from entering the pool right away. - /// Note this is not the case for the dependent operations - those may - /// still be valid so we want to be able to re-import them. - pub fn remove_invalid( - &self, - hashes: &[TxHash], - shard: ShardIdentifier, - inblock: bool, - ) -> Vec> { - // early exit in case there is no invalid operations. - if hashes.is_empty() { - return vec![] - } - - let invalid = self.pool.write().unwrap().remove_subtree(hashes, shard); - - log::debug!(target: "txpool", "Removed invalid operations: {:?}", invalid); - - let mut listener = self.listener.write().unwrap(); - if inblock { - for _tx in &invalid { - //listener.in_block(&tx.hash); - } - } else { - // temporarily ban invalid operations - self.rotator.ban(&Instant::now(), hashes.iter().cloned()); - for tx in &invalid { - listener.invalid(&tx.hash); - } - } - - invalid - } - - /// Get an iterator for ready operations ordered by priority - pub fn ready( - &self, - shard: ShardIdentifier, - ) -> impl Iterator> + Send { - self.pool.read().unwrap().ready(shard) - } - - /// Get an iterator for all shards - pub fn shards(&self) -> Vec { - let mut shards = vec![]; - let base_pool = self.pool.read().unwrap(); - let shard_iterator = base_pool.get_shards(); - for shard in shard_iterator { - shards.push(*shard); - } - shards - } - - /// Returns pool status. - pub fn status(&self, shard: ShardIdentifier) -> PoolStatus { - self.pool.read().unwrap().status(shard) - } - - /// Notify all watchers that operations in the block with hash have been finalized - pub async fn on_block_finalized(&self, block_hash: SidechainBlockHash) -> Result<(), B::Error> - where - <::Block as sp_runtime::traits::Block>::Hash: core::fmt::Display, - { - log::trace!(target: "txpool", "Attempting to notify watchers of finalization for {}", block_hash); - self.listener.write().unwrap().finalized(block_hash); - Ok(()) - } - - /// Notify the listener of retracted blocks - pub fn on_block_retracted(&self, block_hash: SidechainBlockHash) { - self.listener.write().unwrap().retracted(block_hash) - } - - /// Notify the listener of top inclusion in sidechain block - pub fn on_block_imported(&self, hashes: &[TxHash], block_hash: SidechainBlockHash) { - for top_hash in hashes.iter() { - self.listener.write().unwrap().in_block(top_hash, block_hash); - } - } - - #[allow(clippy::type_complexity)] - pub fn update_connection_state(&self, updates: Vec<(TxHash, (Vec, bool))>) { - for (top_hash, (encoded_value, force_wait)) in updates { - self.listener.write().unwrap().update_connection_state( - &top_hash, - encoded_value.clone(), - force_wait, - ); - self.listener - .write() - .unwrap() - .top_executed(&top_hash, &encoded_value, force_wait); - } - } - - pub fn swap_rpc_connection_hash(&self, old_hash: TxHash, new_hash: TxHash) { - self.listener.write().unwrap().swap_rpc_connection_hash(old_hash, new_hash); - } -} - -fn fire_events(listener: &mut Listener, imported: &base::Imported) -where - R: SendRpcResponse, -{ - match *imported { - base::Imported::Ready { ref promoted, ref failed, ref removed, ref hash } => { - listener.ready(hash, None); - for f in failed { - listener.invalid(f); - } - for r in removed { - listener.dropped(&r.hash, Some(hash)); - } - for p in promoted { - listener.ready(p, None); - } - }, - base::Imported::Future { ref hash } => listener.future(hash), - } -} diff --git a/tee-worker/bitacross/core-primitives/top-pool/src/watcher.rs b/tee-worker/bitacross/core-primitives/top-pool/src/watcher.rs deleted file mode 100644 index 018bdf82a8..0000000000 --- a/tee-worker/bitacross/core-primitives/top-pool/src/watcher.rs +++ /dev/null @@ -1,176 +0,0 @@ -// This file is part of Substrate. - -// Copyright (C) 2018-2020 Parity Technologies (UK) Ltd. -// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 - -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with this program. If not, see . - -//! Extrinsics status updates. - -extern crate alloc; -use crate::primitives::TxHash; -use alloc::{string::String, sync::Arc, vec::Vec}; - -use itc_direct_rpc_server::{DirectRpcError, SendRpcResponse}; -use itp_types::{BlockHash as SidechainBlockHash, TrustedOperationStatus}; -use log::*; - -/// Extrinsic watcher. -/// -/// Represents a stream of status updates for particular extrinsic. -#[derive(Debug)] -pub struct Watcher { - //receiver: TracingUnboundedReceiver>, - hash: TxHash, - is_in_block: bool, - rpc_response_sender: Arc, -} - -impl Watcher -where - S: SendRpcResponse, -{ - /// Returns the operation hash. - pub fn hash(&self) -> &TxHash { - &self.hash - } - - pub fn new_watcher(hash: TxHash, rpc_response_sender: Arc) -> Self { - Watcher { hash, is_in_block: false, rpc_response_sender } - } - - /// TrustedOperation became ready. - pub fn ready(&mut self) { - self.send(TrustedOperationStatus::Ready) - } - - /// TrustedOperation was moved to future. - pub fn future(&mut self) { - self.send(TrustedOperationStatus::Future) - } - - /// Some state change (perhaps another extrinsic was included) rendered this extrinsic invalid. - pub fn usurped(&mut self) { - //self.send(TrustedOperationStatus::Usurped(hash)); - self.send(TrustedOperationStatus::Usurped); - self.is_in_block = true; - } - - /// Extrinsic has been included in block with given hash. - pub fn in_block(&mut self, block_hash: SidechainBlockHash) { - self.send(TrustedOperationStatus::InSidechainBlock(block_hash)); - self.is_in_block = true; - } - - /// Extrinsic has been finalized by a finality gadget. - pub fn finalized(&mut self) { - //self.send(TrustedOperationStatus::Finalized(hash)); - self.send(TrustedOperationStatus::Finalized); - self.is_in_block = true; - } - - /// The block this extrinsic was included in has been retracted - pub fn finality_timeout(&mut self) { - //self.send(TrustedOperationStatus::FinalityTimeout(hash)); - self.send(TrustedOperationStatus::FinalityTimeout); - self.is_in_block = true; - } - - /// The block this extrinsic was included in has been retracted - pub fn retracted(&mut self) { - //self.send(TrustedOperationStatus::Retracted(hash)); - self.send(TrustedOperationStatus::Retracted); - } - - /// Extrinsic has been marked as invalid by the block builder. - pub fn invalid(&mut self) { - self.send(TrustedOperationStatus::Invalid); - // we mark as finalized as there are no more notifications - self.is_in_block = true; - } - - /// TrustedOperation has been dropped from the pool because of the limit. - pub fn dropped(&mut self) { - self.send(TrustedOperationStatus::Dropped); - self.is_in_block = true; - } - - /// The extrinsic has been broadcast to the given peers. - pub fn broadcast(&mut self, _peers: Vec) { - //self.send(TrustedOperationStatus::Broadcast(peers)) - self.send(TrustedOperationStatus::Broadcast) - } - - /// The extrinsic has been executed. - pub fn top_executed(&mut self, response: &[u8], force_wait: bool) { - self.send(TrustedOperationStatus::TopExecuted(response.to_vec(), force_wait)) - } - - /// Returns true if the are no more listeners for this extrinsic or it was finalized. - pub fn is_done(&self) -> bool { - self.is_in_block // || self.receivers.is_empty() - } - - fn send(&mut self, status: TrustedOperationStatus) { - if let Err(e) = self.rpc_response_sender.update_status_event(*self.hash(), status) { - match e { - DirectRpcError::InvalidConnectionHash => { - warn!("Client connection interrupted while sending status update"); - }, - _ => error!("Failed to send status update to RPC client: {:?}", e), - } - } - } - - // Litentry: set the new rpc response value and force_wait flag - pub fn update_connection_state(&mut self, encoded_value: Vec, force_wait: bool) { - if let Err(e) = self.rpc_response_sender.update_connection_state( - *self.hash(), - encoded_value, - force_wait, - ) { - warn!("failed to update connection state: {:?}", e); - } - } - - // Litentry: swap the old hash with the new one in rpc connection registry - pub fn swap_rpc_connection_hash(&self, new_hash: TxHash) { - if let Err(e) = self.rpc_response_sender.swap_hash(*self.hash(), new_hash) { - warn!("failed to swap rpc connection hash: {:?}", e); - } - } -} - -/* /// Sender part of the watcher. Exposed only for testing purposes. -#[derive(Debug)] -pub struct Sender { - //receivers: Vec>>, - //receivers: Vec, - is_in_block: bool, -} - */ -/* impl Default for Watcher { - fn default() -> Self { - Watcher { - //receivers: Default::default(), - hash: , - is_in_block: false, - } - } -} */ - -/* impl Sender { - /// Add a new watcher to this sender object. - -} */ diff --git a/tee-worker/bitacross/core/direct-rpc-client/Cargo.toml b/tee-worker/bitacross/core/direct-rpc-client/Cargo.toml deleted file mode 100644 index 0205299ad8..0000000000 --- a/tee-worker/bitacross/core/direct-rpc-client/Cargo.toml +++ /dev/null @@ -1,43 +0,0 @@ -[package] -name = "bc-itc-direct-rpc-client" -version = "0.1.0" -authors = ['Trust Computing GmbH '] -edition = "2021" - -[dependencies] -rustls_sgx = { workspace = true, features = ["dangerous_configuration"], optional = true } -sgx_tstd = { workspace = true, optional = true } -tungstenite_sgx = { workspace = true, optional = true } -webpki_sgx = { workspace = true, optional = true } - -log = { workspace = true } -serde_json = { workspace = true } -url = { workspace = true } - -rustls = { workspace = true, features = ["dangerous_configuration"], optional = true } -tungstenite = { workspace = true, features = ["rustls-tls-webpki-roots"], optional = true } -webpki = { workspace = true, optional = true } - -itp-rpc = { workspace = true } -itp-types = { workspace = true } -itp-utils = { workspace = true } - -[features] -default = ["std"] -sgx = [ - "webpki_sgx", - "tungstenite_sgx", - "rustls_sgx", - "sgx_tstd", - "itp-rpc/sgx", -] -std = [ - "rustls", - "webpki", - "tungstenite", - "url/std", - "itp-rpc/std", - "itp-types/std", - "itp-utils/std", - "log/std", -] diff --git a/tee-worker/bitacross/core/direct-rpc-client/src/lib.rs b/tee-worker/bitacross/core/direct-rpc-client/src/lib.rs deleted file mode 100644 index dbc07484f0..0000000000 --- a/tee-worker/bitacross/core/direct-rpc-client/src/lib.rs +++ /dev/null @@ -1,198 +0,0 @@ -// Copyright 2020-2024 Trust Computing GmbH. -// This file is part of Litentry. -// -// Litentry is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// Litentry is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with Litentry. If not, see . - -#![cfg_attr(not(feature = "std"), no_std)] - -#[cfg(all(feature = "std", feature = "sgx"))] -compile_error!("feature \"std\" and feature \"sgx\" cannot be enabled at the same time"); - -#[cfg(all(not(feature = "std"), feature = "sgx"))] -extern crate sgx_tstd as std; - -// re-export module to properly feature gate sgx and regular std environment -#[cfg(all(not(feature = "std"), feature = "sgx"))] -pub mod sgx_reexport_prelude { - pub use rustls_sgx as rustls; - pub use tungstenite_sgx as tungstenite; - pub use webpki_sgx as webpki; -} - -#[cfg(all(not(feature = "std"), feature = "sgx"))] -use crate::sgx_reexport_prelude::*; - -extern crate alloc; - -use alloc::format; - -use core::str::FromStr; - -use log::{debug, error}; - -use itp_rpc::{Id, RpcRequest, RpcReturnValue}; - -use std::{ - boxed::Box, - error::Error, - net::TcpStream, - string::String, - sync::{ - mpsc::{channel, Sender}, - Arc, - }, - time::Duration, - vec::Vec, -}; -use tungstenite::{client_tls_with_config, stream::MaybeTlsStream, Connector, Message, WebSocket}; -use url::Url; -use webpki::{DNSName, DNSNameRef}; - -pub type Response = (Id, RpcReturnValue); - -pub struct IgnoreCertVerifier {} - -impl rustls::ServerCertVerifier for IgnoreCertVerifier { - fn verify_server_cert( - &self, - _: &rustls::RootCertStore, - _: &[rustls::Certificate], - _: DNSNameRef<'_>, - _: &[u8], - ) -> Result { - log::warn!("Using NoCertVerifier"); - Ok(rustls::ServerCertVerified::assertion()) - } -} - -impl rustls::ClientCertVerifier for IgnoreCertVerifier { - fn client_auth_root_subjects( - &self, - _sni: Option<&DNSName>, - ) -> Option { - None - } - - fn verify_client_cert( - &self, - _presented_certs: &[rustls::Certificate], - _sni: Option<&DNSName>, - ) -> Result { - Ok(rustls::ClientCertVerified::assertion()) - } -} - -pub trait RpcClientFactory { - type Client: RpcClient + Send + Clone; - fn create(&self, url: &str) -> Result>; -} - -pub struct DirectRpcClientFactory {} - -impl RpcClientFactory for DirectRpcClientFactory { - type Client = DirectRpcClient; - - fn create(&self, url: &str) -> Result> { - DirectRpcClient::new(url) - } -} - -pub trait RpcClient { - fn send(&mut self, request: &RpcRequest) -> Result<(), Box>; -} - -#[derive(Clone)] -pub struct DirectRpcClient { - request_sink: Sender<(String, Sender)>, -} - -impl DirectRpcClient { - pub fn new(url: &str) -> Result> { - let server_url = - Url::from_str(url).map_err(|e| format!("Could not connect, reason: {:?}", e))?; - let mut config = rustls::ClientConfig::new(); - // we need to set this cert verifier or client will fail to connect with following error - // HandshakeError::Failure(Io(Custom { kind: InvalidData, error: WebPKIError(UnknownIssuer) })) - config.dangerous().set_certificate_verifier(Arc::new(IgnoreCertVerifier {})); - let connector = Connector::Rustls(Arc::new(config)); - let stream = TcpStream::connect(server_url.authority()) - .map_err(|e| format!("Could not connect to {:?}, reason: {:?}", url, e))?; - - let (mut socket, _response) = - client_tls_with_config(server_url.as_str(), stream, None, Some(connector)) - .map_err(|e| format!("Could not open websocket connection: {:?}", e))?; - - let (request_sender, request_receiver) = channel::<(String, Sender)>(); - - //it fails to perform handshake in non_blocking mode so we are setting it up after the handshake is performed - Self::switch_to_non_blocking(&mut socket); - - std::thread::spawn(move || { - while let Ok((request, result_sender)) = request_receiver.recv() { - let mut result = true; - if let Err(e) = socket.write_message(Message::Text(request)) { - error!("Could not write message to socket, reason: {:?}", e); - result = false; - } - if let Err(e) = result_sender.send(result) { - log::error!("Could not send rpc result back, reason: {:?}", e); - } - } - }); - debug!("Connected to peer: {}", url); - Ok(Self { request_sink: request_sender }) - } - - fn switch_to_non_blocking(socket: &mut WebSocket>) { - match socket.get_ref() { - MaybeTlsStream::Plain(stream) => { - stream.set_nonblocking(true).expect("set_nonblocking call failed"); - stream - .set_read_timeout(Some(Duration::from_millis(5))) - .expect("set_read_timeout call failed"); - }, - MaybeTlsStream::Rustls(stream) => { - stream.get_ref().set_nonblocking(true).expect("set_nonblocking call failed"); - stream - .get_ref() - .set_read_timeout(Some(Duration::from_millis(1))) - .expect("set_read_timeout call failed"); - }, - _ => {}, - } - } -} - -#[derive(Clone)] -pub enum RequestParams { - Rsa(Vec), - Aes(Vec), -} - -impl RpcClient for DirectRpcClient { - fn send(&mut self, request: &RpcRequest) -> Result<(), Box> { - let request = serde_json::to_string(request) - .map_err(|e| format!("Could not parse RpcRequest {:?}", e))?; - let (sender, receiver) = channel(); - self.request_sink - .send((request, sender)) - .map_err(|e| format!("Could not parse RpcRequest {:?}", e))?; - - if receiver.recv()? { - Ok(()) - } else { - Err("Could not send request".into()) - } - } -} diff --git a/tee-worker/bitacross/core/direct-rpc-server/Cargo.toml b/tee-worker/bitacross/core/direct-rpc-server/Cargo.toml deleted file mode 100644 index c913c9e6b6..0000000000 --- a/tee-worker/bitacross/core/direct-rpc-server/Cargo.toml +++ /dev/null @@ -1,49 +0,0 @@ -[package] -name = "bc-itc-direct-rpc-server" -version = "0.1.0" -authors = ['Trust Computing GmbH ', 'Integritee AG '] -edition = "2021" - -[dependencies] -sgx_tstd = { workspace = true, features = ["net", "thread"], optional = true } - -codec = { package = "parity-scale-codec", workspace = true } -log = { workspace = true } -serde_json = { workspace = true } -sp-runtime = { workspace = true } - -itc-tls-websocket-server = { workspace = true } -itp-rpc = { workspace = true } -itp-types = { workspace = true } -itp-utils = { workspace = true } - -jsonrpc-core = { workspace = true, optional = true } -jsonrpc-core_sgx = { workspace = true, optional = true } -thiserror = { workspace = true, optional = true } -thiserror_sgx = { workspace = true, optional = true } - -[features] -default = ["std"] -std = [ - # no-std dependencies - "codec/std", - "log/std", - "serde_json/std", - "sp-runtime/std", - # integritee dependencies - "itp-types/std", - # local - "itc-tls-websocket-server/std", - "itp-rpc/std", - # optional ones - "jsonrpc-core", - "thiserror", -] -sgx = [ - "itc-tls-websocket-server/sgx", - "itp-rpc/sgx", - "jsonrpc-core_sgx", - "sgx_tstd", - "thiserror_sgx", -] -mocks = [] diff --git a/tee-worker/bitacross/core/direct-rpc-server/src/builders/mod.rs b/tee-worker/bitacross/core/direct-rpc-server/src/builders/mod.rs deleted file mode 100644 index ea028434c4..0000000000 --- a/tee-worker/bitacross/core/direct-rpc-server/src/builders/mod.rs +++ /dev/null @@ -1,19 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -pub mod rpc_response_builder; -pub mod rpc_return_value_builder; diff --git a/tee-worker/bitacross/core/direct-rpc-server/src/builders/rpc_response_builder.rs b/tee-worker/bitacross/core/direct-rpc-server/src/builders/rpc_response_builder.rs deleted file mode 100644 index 9cc85cf369..0000000000 --- a/tee-worker/bitacross/core/direct-rpc-server/src/builders/rpc_response_builder.rs +++ /dev/null @@ -1,64 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use crate::builders::rpc_return_value_builder::RpcReturnValueBuilder; -use itp_rpc::{Id, RpcResponse, RpcReturnValue}; -use itp_utils::ToHexPrefixed; - -/// builder pattern for RpcResponse -pub struct RpcResponseBuilder { - maybe_id: Option, - maybe_json_rpc: Option, - maybe_result: Option, -} - -impl RpcResponseBuilder { - #[allow(unused)] - pub fn new() -> Self { - RpcResponseBuilder { maybe_id: None, maybe_json_rpc: None, maybe_result: None } - } - - #[allow(unused)] - pub fn with_id(mut self, id: u32) -> Self { - self.maybe_id = Some(id); - self - } - - #[allow(unused)] - pub fn with_json_rpc(mut self, json_rpc: String) -> Self { - self.maybe_json_rpc = Some(json_rpc); - self - } - - #[allow(unused)] - pub fn with_result(mut self, result: RpcReturnValue) -> Self { - self.maybe_result = Some(result); - self - } - - #[allow(unused)] - pub fn build(self) -> RpcResponse { - let id = Id::Number(self.maybe_id.unwrap_or(1u32)); - let json_rpc = self.maybe_json_rpc.unwrap_or(String::from("json_rpc")); - let result = self - .maybe_result - .unwrap_or_else(|| RpcReturnValueBuilder::new().build()) - .to_hex(); - - RpcResponse { result, jsonrpc: json_rpc, id } - } -} diff --git a/tee-worker/bitacross/core/direct-rpc-server/src/builders/rpc_return_value_builder.rs b/tee-worker/bitacross/core/direct-rpc-server/src/builders/rpc_return_value_builder.rs deleted file mode 100644 index 126d58e985..0000000000 --- a/tee-worker/bitacross/core/direct-rpc-server/src/builders/rpc_return_value_builder.rs +++ /dev/null @@ -1,62 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use codec::Encode; -use itp_rpc::RpcReturnValue; -use itp_types::DirectRequestStatus; -use std::{string::String, vec::Vec}; - -/// Builder pattern for a RpcReturnValue -pub struct RpcReturnValueBuilder { - maybe_do_watch: Option, - maybe_status: Option, - maybe_value: Option>, -} - -impl RpcReturnValueBuilder { - #[allow(unused)] - pub fn new() -> Self { - RpcReturnValueBuilder { maybe_do_watch: None, maybe_status: None, maybe_value: None } - } - - #[allow(unused)] - pub fn with_do_watch(mut self, do_watch: bool) -> Self { - self.maybe_do_watch = Some(do_watch); - self - } - - #[allow(unused)] - pub fn with_status(mut self, status: DirectRequestStatus) -> Self { - self.maybe_status = Some(status); - self - } - - #[allow(unused)] - pub fn with_value(mut self, value: Vec) -> Self { - self.maybe_value = Some(value); - self - } - - #[allow(unused)] - pub fn build(self) -> RpcReturnValue { - let do_watch = self.maybe_do_watch.unwrap_or(false); - let status = self.maybe_status.unwrap_or(DirectRequestStatus::Ok); - let value = self.maybe_value.unwrap_or(String::from("value").encode()); - - RpcReturnValue { value, do_watch, status } - } -} diff --git a/tee-worker/bitacross/core/direct-rpc-server/src/lib.rs b/tee-worker/bitacross/core/direct-rpc-server/src/lib.rs deleted file mode 100644 index 8b779064eb..0000000000 --- a/tee-worker/bitacross/core/direct-rpc-server/src/lib.rs +++ /dev/null @@ -1,165 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ -#![cfg_attr(not(feature = "std"), no_std)] -#![cfg_attr(test, feature(assert_matches))] - -#[cfg(all(feature = "std", feature = "sgx"))] -compile_error!("feature \"std\" and feature \"sgx\" cannot be enabled at the same time"); - -extern crate alloc; - -#[cfg(all(not(feature = "std"), feature = "sgx"))] -extern crate sgx_tstd as std; - -// re-export module to properly feature gate sgx and regular std environment -#[cfg(all(not(feature = "std"), feature = "sgx"))] -pub mod sgx_reexport_prelude { - pub use jsonrpc_core_sgx as jsonrpc_core; - pub use thiserror_sgx as thiserror; -} - -#[cfg(all(not(feature = "std"), feature = "sgx"))] -use crate::sgx_reexport_prelude::*; - -use crate::rpc_watch_extractor::RpcWatchExtractor; -use codec::{Encode, Error as CodecError}; -use itc_tls_websocket_server::error::WebSocketError; -use itp_rpc::RpcResponse; -use itp_types::{DirectRequestStatus, TrustedOperationStatus, H256}; -use serde_json::error::Error as SerdeJsonError; -use sp_runtime::traits; -use std::{boxed::Box, fmt::Debug, vec::Vec}; - -#[cfg(any(test, feature = "mocks"))] -pub mod mocks; - -#[cfg(test)] -mod builders; - -pub mod response_channel; -pub mod rpc_connection_registry; -pub mod rpc_responder; -pub mod rpc_watch_extractor; -pub mod rpc_ws_handler; - -/// General web-socket error type -#[derive(Debug, thiserror::Error)] -pub enum DirectRpcError { - #[error("Invalid connection hash")] - InvalidConnectionHash, - #[error("RPC serialization error: {0}")] - SerializationError(SerdeJsonError), - #[error("Web socket error: {0}")] - WebSocketError(#[from] WebSocketError), - #[error("Encoding error: {0}")] - EncodingError(CodecError), - #[error("Other error: {0}")] - Other(Box), - // Litentry - #[error("Hash conversion error")] - HashConversionError, -} - -pub type DirectRpcResult = Result; - -/// trait helper to mix-in all necessary traits for a hash -pub trait RpcHash: std::hash::Hash + traits::Member + Encode { - fn maybe_h256(&self) -> Option; -} -impl RpcHash for T { - fn maybe_h256(&self) -> Option { - let enc = self.encode(); - if enc.len() == 32 { - let mut inner = [0u8; 32]; - inner.copy_from_slice(&enc); - Some(inner.into()) - } else { - None - } - } -} - -pub type ForceWait = bool; - -/// Registry for RPC connections (i.e. connections that are kept alive to send updates). -pub trait RpcConnectionRegistry: Send + Sync { - type Hash: RpcHash; - type Connection: Copy + Debug; - - fn store( - &self, - hash: Self::Hash, - connection: Self::Connection, - rpc_response: RpcResponse, - force_wait: ForceWait, - ); - - fn withdraw(&self, hash: &Self::Hash) -> Option<(Self::Connection, RpcResponse, ForceWait)>; - - fn is_force_wait(&self, hash: &Self::Hash) -> bool; -} - -/// Sends an RPC response back to the client. -pub trait SendRpcResponse: Send + Sync { - type Hash: RpcHash; - - fn update_status_event( - &self, - hash: Self::Hash, - status_update: TrustedOperationStatus, - ) -> DirectRpcResult<()>; - - fn send_state(&self, hash: Self::Hash, state_encoded: Vec) -> DirectRpcResult<()>; - - fn send_state_with_status( - &self, - hash: Self::Hash, - state_encoded: Vec, - status: DirectRequestStatus, - ) -> DirectRpcResult<()>; - - fn update_force_wait(&self, hash: Self::Hash, force_wait: bool) -> DirectRpcResult<()>; - - // Litentry: update the `value` field in the returning structure and connection force_wait flag - fn update_connection_state( - &self, - hash: Self::Hash, - encoded_value: Vec, - force_wait: bool, - ) -> DirectRpcResult<()>; - - // Litentry: swap the old hash with the new one in rpc connection registry - fn swap_hash(&self, old_hash: Self::Hash, new_hash: Self::Hash) -> DirectRpcResult<()>; - - fn is_force_wait(&self, hash: Self::Hash) -> bool; -} - -/// Determines if a given connection must be watched (i.e. kept alive), -/// based on the information in the RpcResponse. -pub trait DetermineWatch: Send + Sync { - type Hash: RpcHash; - - fn must_be_watched(&self, rpc_response: &RpcResponse) -> DirectRpcResult>; -} - -/// Convenience method to create a do_watch extractor. -pub fn create_determine_watch() -> RpcWatchExtractor -where - Hash: RpcHash, -{ - RpcWatchExtractor::::new() -} diff --git a/tee-worker/bitacross/core/direct-rpc-server/src/mocks/determine_watch_mock.rs b/tee-worker/bitacross/core/direct-rpc-server/src/mocks/determine_watch_mock.rs deleted file mode 100644 index c01730390d..0000000000 --- a/tee-worker/bitacross/core/direct-rpc-server/src/mocks/determine_watch_mock.rs +++ /dev/null @@ -1,52 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use crate::{DetermineWatch, DirectRpcResult, RpcHash}; -use itp_rpc::RpcResponse; - -pub struct DetermineWatchMock -where - Hash: RpcHash, -{ - watch_next: Option, -} - -impl DetermineWatchMock -where - Hash: RpcHash, -{ - #[allow(unused)] - pub fn do_watch(hash: Hash) -> Self { - DetermineWatchMock { watch_next: Some(hash) } - } - - #[allow(unused)] - pub fn no_watch() -> Self { - DetermineWatchMock { watch_next: None } - } -} - -impl DetermineWatch for DetermineWatchMock -where - Hash: RpcHash, -{ - type Hash = Hash; - - fn must_be_watched(&self, _rpc_response: &RpcResponse) -> DirectRpcResult> { - Ok(self.watch_next.clone()) - } -} diff --git a/tee-worker/bitacross/core/direct-rpc-server/src/mocks/mod.rs b/tee-worker/bitacross/core/direct-rpc-server/src/mocks/mod.rs deleted file mode 100644 index 011b4d9905..0000000000 --- a/tee-worker/bitacross/core/direct-rpc-server/src/mocks/mod.rs +++ /dev/null @@ -1,20 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -pub mod determine_watch_mock; -pub mod response_channel_mock; -pub mod send_rpc_response_mock; diff --git a/tee-worker/bitacross/core/direct-rpc-server/src/mocks/response_channel_mock.rs b/tee-worker/bitacross/core/direct-rpc-server/src/mocks/response_channel_mock.rs deleted file mode 100644 index 6a612d6766..0000000000 --- a/tee-worker/bitacross/core/direct-rpc-server/src/mocks/response_channel_mock.rs +++ /dev/null @@ -1,55 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -#[cfg(feature = "sgx")] -use std::sync::SgxRwLock as RwLock; - -#[cfg(feature = "std")] -use std::sync::RwLock; - -use crate::{response_channel::ResponseChannel, DirectRpcError}; -use std::vec::Vec; - -#[derive(Default)] -pub struct ResponseChannelMock -where - Token: Copy + Send + Sync, -{ - sent_messages: RwLock>, -} - -impl ResponseChannelMock -where - Token: Copy + Send + Sync, -{ - pub fn number_of_updates(&self) -> usize { - self.sent_messages.read().unwrap().len() - } -} - -impl ResponseChannel for ResponseChannelMock -where - Token: Copy + Send + Sync, -{ - type Error = DirectRpcError; - - fn respond(&self, token: Token, message: String) -> Result<(), Self::Error> { - let mut messages_lock = self.sent_messages.write().unwrap(); - messages_lock.push((token, message)); - Ok(()) - } -} diff --git a/tee-worker/bitacross/core/direct-rpc-server/src/mocks/send_rpc_response_mock.rs b/tee-worker/bitacross/core/direct-rpc-server/src/mocks/send_rpc_response_mock.rs deleted file mode 100644 index 671ee22f4b..0000000000 --- a/tee-worker/bitacross/core/direct-rpc-server/src/mocks/send_rpc_response_mock.rs +++ /dev/null @@ -1,83 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -#[cfg(feature = "sgx")] -use std::sync::SgxRwLock as RwLock; - -#[cfg(feature = "std")] -use std::sync::RwLock; - -use crate::{DirectRpcResult, RpcHash, SendRpcResponse}; -use itp_types::{DirectRequestStatus, TrustedOperationStatus}; -use std::vec::Vec; - -/// Send RPC response mock. -#[derive(Default)] -pub struct SendRpcResponseMock { - pub sent_states: RwLock)>>, -} - -impl SendRpcResponse for SendRpcResponseMock -where - HashType: RpcHash, -{ - type Hash = HashType; - - fn update_status_event( - &self, - _hash: Self::Hash, - _status_update: TrustedOperationStatus, - ) -> DirectRpcResult<()> { - unimplemented!() - } - - fn send_state(&self, hash: Self::Hash, state_encoded: Vec) -> DirectRpcResult<()> { - let mut states_lock = self.sent_states.write().unwrap(); - states_lock.push((hash, state_encoded)); - Ok(()) - } - - fn send_state_with_status( - &self, - _hash: Self::Hash, - _state_encoded: Vec, - _status: DirectRequestStatus, - ) -> DirectRpcResult<()> { - Ok(()) - } - - fn update_force_wait(&self, _hash: Self::Hash, _force_wait: bool) -> DirectRpcResult<()> { - Ok(()) - } - - fn update_connection_state( - &self, - _hash: Self::Hash, - _encoded_value: Vec, - _force_wait: bool, - ) -> DirectRpcResult<()> { - Ok(()) - } - - fn swap_hash(&self, _old_hash: Self::Hash, _new_hash: Self::Hash) -> DirectRpcResult<()> { - Ok(()) - } - - fn is_force_wait(&self, _hash: Self::Hash) -> bool { - false - } -} diff --git a/tee-worker/bitacross/core/direct-rpc-server/src/response_channel.rs b/tee-worker/bitacross/core/direct-rpc-server/src/response_channel.rs deleted file mode 100644 index b1fe6a3fea..0000000000 --- a/tee-worker/bitacross/core/direct-rpc-server/src/response_channel.rs +++ /dev/null @@ -1,26 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use crate::DirectRpcError; -use std::string::String; - -/// Response / status update channel for an RPC call. -pub trait ResponseChannel: Send + Sync { - type Error: Into; - - fn respond(&self, token: Token, message: String) -> Result<(), Self::Error>; -} diff --git a/tee-worker/bitacross/core/direct-rpc-server/src/rpc_connection_registry.rs b/tee-worker/bitacross/core/direct-rpc-server/src/rpc_connection_registry.rs deleted file mode 100644 index 2c83986fe5..0000000000 --- a/tee-worker/bitacross/core/direct-rpc-server/src/rpc_connection_registry.rs +++ /dev/null @@ -1,140 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -#[cfg(all(not(feature = "std"), feature = "sgx"))] -use std::sync::SgxRwLock as RwLock; - -#[cfg(feature = "std")] -use std::sync::RwLock; - -use crate::{ForceWait, RpcConnectionRegistry, RpcHash}; -use itp_rpc::RpcResponse; -use std::{collections::HashMap, fmt::Debug}; - -type HashMapLock = RwLock>; - -pub struct ConnectionRegistry -where - Hash: RpcHash, - Token: Copy + Send + Sync + Debug, -{ - connection_map: - HashMapLock<::Hash, (Token, RpcResponse, ForceWait)>, -} - -impl ConnectionRegistry -where - Hash: RpcHash, - Token: Copy + Send + Sync + Debug, -{ - pub fn new() -> Self { - Self::default() - } - - #[cfg(test)] - pub fn is_empty(&self) -> bool { - self.connection_map.read().unwrap().is_empty() - } -} - -impl Default for ConnectionRegistry -where - Hash: RpcHash, - Token: Copy + Send + Sync + Debug, -{ - fn default() -> Self { - ConnectionRegistry { connection_map: RwLock::new(HashMap::default()) } - } -} - -impl RpcConnectionRegistry for ConnectionRegistry -where - Hash: RpcHash, - Token: Copy + Send + Sync + Debug, -{ - type Hash = Hash; - type Connection = Token; - - fn store( - &self, - hash: Self::Hash, - connection: Self::Connection, - rpc_response: RpcResponse, - force_wait: ForceWait, - ) { - let mut map = self.connection_map.write().expect("Lock poisoning"); - map.insert(hash, (connection, rpc_response, force_wait)); - } - - fn withdraw(&self, hash: &Self::Hash) -> Option<(Self::Connection, RpcResponse, ForceWait)> { - let mut map = self.connection_map.write().expect("Lock poisoning"); - map.remove(hash) - } - - fn is_force_wait(&self, hash: &Self::Hash) -> bool { - if let Some(v) = self.connection_map.read().unwrap().get(hash) { - v.2 - } else { - false - } - } -} - -#[cfg(test)] -pub mod tests { - use super::*; - use itp_rpc::Id; - - type TestRegistry = ConnectionRegistry; - - #[test] - pub fn adding_element_with_same_hash_overwrite() { - let registry = TestRegistry::new(); - - let hash = "first".to_string(); - - registry.store(hash.clone(), 1, dummy_rpc_response(), false); - registry.store(hash.clone(), 2, dummy_rpc_response(), false); - - let connection_token = registry.withdraw(&hash).unwrap().0; - assert_eq!(2, connection_token); - } - - #[test] - pub fn withdrawing_from_empty_registry_returns_none() { - let registry = TestRegistry::new(); - - assert!(registry.withdraw(&"hash".to_string()).is_none()); - } - - #[test] - pub fn withdrawing_only_element_clears_registry() { - let registry = TestRegistry::new(); - let hash = "first".to_string(); - - registry.store(hash.clone(), 1, dummy_rpc_response(), false); - - let connection = registry.withdraw(&hash); - - assert!(connection.is_some()); - assert!(registry.is_empty()); - } - - fn dummy_rpc_response() -> RpcResponse { - RpcResponse { jsonrpc: String::new(), result: Default::default(), id: Id::Number(1u32) } - } -} diff --git a/tee-worker/bitacross/core/direct-rpc-server/src/rpc_responder.rs b/tee-worker/bitacross/core/direct-rpc-server/src/rpc_responder.rs deleted file mode 100644 index 053fc05c56..0000000000 --- a/tee-worker/bitacross/core/direct-rpc-server/src/rpc_responder.rs +++ /dev/null @@ -1,389 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use crate::{ - response_channel::ResponseChannel, DirectRpcError, DirectRpcResult, RpcConnectionRegistry, - RpcHash, SendRpcResponse, -}; -use alloc::format; -use itp_rpc::{RpcResponse, RpcReturnValue}; -use itp_types::{DirectRequestStatus, TrustedOperationStatus}; -use itp_utils::{FromHexPrefixed, ToHexPrefixed}; -use log::*; -use std::{sync::Arc, vec::Vec}; - -pub struct RpcResponder -where - Registry: RpcConnectionRegistry, - Hash: RpcHash, - ResponseChannelType: ResponseChannel, -{ - connection_registry: Arc, - response_channel: Arc, -} - -impl RpcResponder -where - Registry: RpcConnectionRegistry, - Hash: RpcHash, - ResponseChannelType: ResponseChannel, -{ - pub fn new( - connection_registry: Arc, - web_socket_responder: Arc, - ) -> Self { - RpcResponder { connection_registry, response_channel: web_socket_responder } - } - - fn encode_and_send_response( - &self, - connection: Registry::Connection, - rpc_response: &RpcResponse, - ) -> DirectRpcResult<()> { - let string_response = - serde_json::to_string(&rpc_response).map_err(DirectRpcError::SerializationError)?; - - self.response_channel.respond(connection, string_response).map_err(|e| e.into()) - } -} - -impl SendRpcResponse - for RpcResponder -where - Registry: RpcConnectionRegistry, - Hash: RpcHash, - ResponseChannelType: ResponseChannel, -{ - type Hash = Hash; - - fn update_status_event( - &self, - hash: Hash, - status_update: TrustedOperationStatus, - ) -> DirectRpcResult<()> { - debug!("updating status event, hash: {}, status: {:?}", hash.to_hex(), status_update); - - // withdraw removes it from the registry - let (connection_token, rpc_response, force_wait) = self - .connection_registry - .withdraw(&hash) - .ok_or(DirectRpcError::InvalidConnectionHash)?; - - let mut new_response = rpc_response.clone(); - - let mut result = RpcReturnValue::from_hex(&rpc_response.result) - .map_err(|e| DirectRpcError::Other(format!("{:?}", e).into()))?; - - // Litentry: - // connections are per trusted call, but if we expect trusted call to have a side effect of creating another trusted call (callback) - // we force connection to wait for potential TOP execution - let do_watch = continue_watching(&status_update) || force_wait; - - // update response - result.do_watch = do_watch; - result.status = DirectRequestStatus::TrustedOperationStatus( - status_update, - hash.maybe_h256().ok_or(DirectRpcError::HashConversionError)?, - ); - new_response.result = result.to_hex(); - - self.encode_and_send_response(connection_token, &new_response)?; - - if do_watch { - self.connection_registry.store(hash, connection_token, new_response, force_wait); - } - - debug!("updating status event successful"); - Ok(()) - } - - // TODO(Litentry): it seems that this fn is only used in tests? - fn send_state(&self, hash: Hash, state_encoded: Vec) -> DirectRpcResult<()> { - debug!("sending state"); - - // withdraw removes it from the registry - let (connection_token, mut response, _force_wait) = self - .connection_registry - .withdraw(&hash) - .ok_or(DirectRpcError::InvalidConnectionHash)?; - - // create return value - // TODO: Signature? - let submitted = DirectRequestStatus::TrustedOperationStatus( - TrustedOperationStatus::Submitted, - hash.maybe_h256().ok_or(DirectRpcError::HashConversionError)?, - ); - let result = RpcReturnValue::new(state_encoded, false, submitted); - - // update response - response.result = result.to_hex(); - - self.encode_and_send_response(connection_token, &response)?; - - debug!("sending state successful"); - Ok(()) - } - - fn update_force_wait(&self, hash: Self::Hash, force_wait: bool) -> DirectRpcResult<()> { - let (connection_token, rpc_response, _) = self - .connection_registry - .withdraw(&hash) - .ok_or(DirectRpcError::InvalidConnectionHash)?; - self.connection_registry.store(hash, connection_token, rpc_response, force_wait); - - Ok(()) - } - - fn is_force_wait(&self, hash: Self::Hash) -> bool { - self.connection_registry.is_force_wait(&hash) - } - - fn update_connection_state( - &self, - hash: Self::Hash, - encoded_value: Vec, - force_wait: bool, - ) -> DirectRpcResult<()> { - info!( - "updating connection state for hash {:?}: encoded_value {:?}, force_wait: {:?}", - hash, encoded_value, force_wait - ); - - // withdraw removes it from the registry - let (connection_token, rpc_response, _) = self - .connection_registry - .withdraw(&hash) - .ok_or(DirectRpcError::InvalidConnectionHash)?; - - let mut new_response = rpc_response.clone(); - - let mut result = RpcReturnValue::from_hex(&rpc_response.result) - .map_err(|e| DirectRpcError::Other(format!("{:?}", e).into()))?; - - result.value = encoded_value; - new_response.result = result.to_hex(); - self.connection_registry.store(hash, connection_token, new_response, force_wait); - - debug!("set response value OK"); - Ok(()) - } - - fn swap_hash(&self, old_hash: Self::Hash, new_hash: Self::Hash) -> DirectRpcResult<()> { - debug!("swap hash, old: {:?}, new: {:?}", old_hash, new_hash); - - let (connection_token, rpc_response, force_wait) = self - .connection_registry - .withdraw(&old_hash) - .ok_or(DirectRpcError::InvalidConnectionHash)?; - - // leave `rpc_response` untouched - it should be overwritten later anyway and keep on force waiting - self.connection_registry - .store(new_hash, connection_token, rpc_response, force_wait); - debug!("swap hash OK"); - Ok(()) - } - - fn send_state_with_status( - &self, - hash: Self::Hash, - state_encoded: Vec, - status: DirectRequestStatus, - ) -> DirectRpcResult<()> { - debug!("sending state with status for hash {:?}", hash); - - // withdraw removes it from the registry - let (connection_token, mut response, _force_wait) = self - .connection_registry - .withdraw(&hash) - .ok_or(DirectRpcError::InvalidConnectionHash)?; - - // create return value - let result = RpcReturnValue::new(state_encoded, false, status); - - // update response - response.result = result.to_hex(); - - self.encode_and_send_response(connection_token, &response)?; - - debug!("sending state successful"); - Ok(()) - } -} - -fn continue_watching(status: &TrustedOperationStatus) -> bool { - !matches!( - status, - TrustedOperationStatus::Invalid - | TrustedOperationStatus::InSidechainBlock(_) - | TrustedOperationStatus::Finalized - | TrustedOperationStatus::Usurped - ) -} - -#[cfg(test)] -pub mod tests { - - use super::*; - use crate::{ - builders::rpc_response_builder::RpcResponseBuilder, - mocks::response_channel_mock::ResponseChannelMock, - rpc_connection_registry::ConnectionRegistry, - }; - use codec::Encode; - use itp_types::H256; - use std::assert_matches::assert_matches; - - type TestConnectionToken = u64; - type TestResponseChannel = ResponseChannelMock; - type TestConnectionRegistry = ConnectionRegistry; - - #[test] - fn given_empty_registry_when_updating_status_event_then_return_error() { - let connection_registry = Arc::new(TestConnectionRegistry::new()); - let websocket_responder = Arc::new(TestResponseChannel::default()); - let rpc_responder = RpcResponder::new(connection_registry, websocket_responder); - - assert_matches!( - rpc_responder.update_status_event([1u8; 32].into(), TrustedOperationStatus::Broadcast), - Err(DirectRpcError::InvalidConnectionHash) - ); - } - - #[test] - fn given_empty_registry_when_sending_state_then_return_error() { - let connection_registry = Arc::new(TestConnectionRegistry::new()); - let websocket_responder = Arc::new(TestResponseChannel::default()); - let rpc_responder = RpcResponder::new(connection_registry, websocket_responder); - - assert_matches!( - rpc_responder.send_state([1u8; 32].into(), vec![1u8, 2u8]), - Err(DirectRpcError::InvalidConnectionHash) - ); - } - - #[test] - fn updating_status_event_with_finalized_state_removes_connection() { - let connection_hash = H256::random(); - let connection_registry = create_registry_with_single_connection(connection_hash.clone()); - - let websocket_responder = Arc::new(TestResponseChannel::default()); - let rpc_responder = - RpcResponder::new(connection_registry.clone(), websocket_responder.clone()); - - let result = rpc_responder - .update_status_event(connection_hash.clone(), TrustedOperationStatus::Finalized); - - assert!(result.is_ok()); - - verify_closed_connection(&connection_hash, connection_registry); - assert_eq!(1, websocket_responder.number_of_updates()); - } - - #[test] - fn updating_status_event_with_finalized_state_doesnt_remove_connection_if_force_watch_set() { - let connection_hash = H256::random(); - let connection_registry = create_registry_with_single_connection(connection_hash.clone()); - - let websocket_responder = Arc::new(TestResponseChannel::default()); - let rpc_responder = - RpcResponder::new(connection_registry.clone(), websocket_responder.clone()); - rpc_responder - .update_connection_state(connection_hash.clone(), vec![], true) - .unwrap(); - - let result = rpc_responder - .update_status_event(connection_hash.clone(), TrustedOperationStatus::Finalized); - - assert!(result.is_ok()); - - verify_open_connection(&connection_hash, connection_registry); - assert_eq!(1, websocket_responder.number_of_updates()); - } - - #[test] - fn updating_status_event_with_ready_state_keeps_connection_and_sends_update() { - let connection_hash = H256::random(); - let connection_registry: Arc> = - create_registry_with_single_connection(connection_hash.clone()); - - let websocket_responder = Arc::new(TestResponseChannel::default()); - let rpc_responder = - RpcResponder::new(connection_registry.clone(), websocket_responder.clone()); - - let first_result = rpc_responder - .update_status_event(connection_hash.clone(), TrustedOperationStatus::Ready); - - let second_result = rpc_responder - .update_status_event(connection_hash.clone(), TrustedOperationStatus::Submitted); - - assert!(first_result.is_ok()); - assert!(second_result.is_ok()); - - verify_open_connection(&connection_hash, connection_registry); - assert_eq!(2, websocket_responder.number_of_updates()); - } - - #[test] - fn sending_state_successfully_sends_update_and_removes_connection_token() { - let connection_hash = H256::random(); - let connection_registry = create_registry_with_single_connection(connection_hash.clone()); - - let websocket_responder = Arc::new(TestResponseChannel::default()); - let rpc_responder = - RpcResponder::new(connection_registry.clone(), websocket_responder.clone()); - - let result = rpc_responder.send_state(connection_hash.clone(), "new_state".encode()); - assert!(result.is_ok()); - - verify_closed_connection(&connection_hash, connection_registry); - assert_eq!(1, websocket_responder.number_of_updates()); - } - - #[test] - fn test_continue_watching() { - assert!(!continue_watching(&TrustedOperationStatus::Invalid)); - assert!(!continue_watching(&TrustedOperationStatus::Usurped)); - assert!(continue_watching(&TrustedOperationStatus::Future)); - assert!(continue_watching(&TrustedOperationStatus::Broadcast)); - assert!(continue_watching(&TrustedOperationStatus::Dropped)); - } - - fn verify_open_connection( - connection_hash: &H256, - connection_registry: Arc, - ) { - let maybe_connection = connection_registry.withdraw(&connection_hash); - assert!(maybe_connection.is_some()); - } - - fn verify_closed_connection( - connection_hash: &H256, - connection_registry: Arc, - ) { - assert!(connection_registry.withdraw(&connection_hash).is_none()); - } - - fn create_registry_with_single_connection( - connection_hash: H256, - ) -> Arc { - let connection_registry = TestConnectionRegistry::new(); - let rpc_response = RpcResponseBuilder::new().with_id(2).build(); - - connection_registry.store(connection_hash.clone(), 1, rpc_response, false); - Arc::new(connection_registry) - } -} diff --git a/tee-worker/bitacross/core/direct-rpc-server/src/rpc_watch_extractor.rs b/tee-worker/bitacross/core/direct-rpc-server/src/rpc_watch_extractor.rs deleted file mode 100644 index cbc69bdfd0..0000000000 --- a/tee-worker/bitacross/core/direct-rpc-server/src/rpc_watch_extractor.rs +++ /dev/null @@ -1,133 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use crate::{DetermineWatch, DirectRpcError, DirectRpcResult, RpcHash}; -use alloc::format; -use codec::Decode; -use itp_rpc::{RpcResponse, RpcReturnValue}; -use itp_types::DirectRequestStatus; -use itp_utils::FromHexPrefixed; -use std::marker::PhantomData; - -pub struct RpcWatchExtractor -where - Hash: RpcHash, -{ - phantom_data: PhantomData, -} - -impl RpcWatchExtractor -where - Hash: RpcHash, -{ - pub fn new() -> Self { - Self::default() - } -} - -impl Default for RpcWatchExtractor -where - Hash: RpcHash, -{ - fn default() -> Self { - RpcWatchExtractor { phantom_data: PhantomData } - } -} - -impl DetermineWatch for RpcWatchExtractor -where - Hash: RpcHash + Decode, -{ - type Hash = Hash; - - fn must_be_watched(&self, rpc_response: &RpcResponse) -> DirectRpcResult> { - let rpc_return_value = RpcReturnValue::from_hex(&rpc_response.result) - .map_err(|e| DirectRpcError::Other(format!("{:?}", e).into()))?; - - if !rpc_return_value.do_watch { - return Ok(None) - } - - match rpc_return_value.status { - DirectRequestStatus::TrustedOperationStatus(_, top_hash) => - Self::Hash::decode::<_>(&mut top_hash.as_ref()) - .map(Some) - .map_err(DirectRpcError::EncodingError), - DirectRequestStatus::Processing(hash) => Self::Hash::decode::<_>(&mut hash.as_ref()) - .map(Some) - .map_err(DirectRpcError::EncodingError), - _ => Ok(None), - } - } -} - -#[cfg(test)] -pub mod tests { - use super::*; - use crate::builders::{ - rpc_response_builder::RpcResponseBuilder, rpc_return_value_builder::RpcReturnValueBuilder, - }; - use itp_rpc::Id; - use itp_types::{TrustedOperationStatus, H256}; - - #[test] - fn invalid_rpc_response_returns_error() { - let watch_extractor = RpcWatchExtractor::::new(); - let rpc_response = RpcResponse { - id: Id::Number(1u32), - jsonrpc: String::from("json"), - result: "hello".to_string(), - }; - - assert!(watch_extractor.must_be_watched(&rpc_response).is_err()); - } - - #[test] - fn rpc_response_without_watch_flag_must_not_be_watched() { - let watch_extractor = RpcWatchExtractor::::new(); - let rpc_result = RpcReturnValueBuilder::new() - .with_do_watch(false) - .with_status(DirectRequestStatus::TrustedOperationStatus( - TrustedOperationStatus::Ready, - Default::default(), - )) - .build(); - let rpc_response = RpcResponseBuilder::new().with_result(rpc_result).build(); - - let do_watch = watch_extractor.must_be_watched(&rpc_response).unwrap(); - - assert_eq!(None, do_watch); - } - - #[test] - fn rpc_response_with_watch_flag_must_be_watched() { - let hash = H256::random(); - let watch_extractor = RpcWatchExtractor::::new(); - let rpc_return_value = RpcReturnValueBuilder::new() - .with_do_watch(true) - .with_status(DirectRequestStatus::TrustedOperationStatus( - TrustedOperationStatus::Ready, - hash, - )) - .build(); - let rpc_response = RpcResponseBuilder::new().with_result(rpc_return_value).build(); - - let do_watch = watch_extractor.must_be_watched(&rpc_response).unwrap(); - - assert_eq!(Some(hash), do_watch); - } -} diff --git a/tee-worker/bitacross/core/direct-rpc-server/src/rpc_ws_handler.rs b/tee-worker/bitacross/core/direct-rpc-server/src/rpc_ws_handler.rs deleted file mode 100644 index f585258e84..0000000000 --- a/tee-worker/bitacross/core/direct-rpc-server/src/rpc_ws_handler.rs +++ /dev/null @@ -1,241 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -#[cfg(all(not(feature = "std"), feature = "sgx"))] -use crate::sgx_reexport_prelude::*; - -use crate::{DetermineWatch, RpcConnectionRegistry, RpcHash}; -use itc_tls_websocket_server::{error::WebSocketResult, ConnectionToken, WebSocketMessageHandler}; -use itp_rpc::{RpcResponse, RpcReturnValue}; -use itp_types::DirectRequestStatus; -use itp_utils::FromHexPrefixed; -use jsonrpc_core::IoHandler; -use log::*; -use std::{string::String, sync::Arc}; - -pub struct RpcWsHandler -where - Watcher: DetermineWatch, - Registry: RpcConnectionRegistry, - Hash: RpcHash, -{ - rpc_io_handler: IoHandler, - connection_watcher: Arc, - connection_registry: Arc, -} - -impl RpcWsHandler -where - Watcher: DetermineWatch, - Registry: RpcConnectionRegistry, - Hash: RpcHash, -{ - pub fn new( - rpc_io_handler: IoHandler, - connection_watcher: Arc, - connection_registry: Arc, - ) -> Self { - RpcWsHandler { rpc_io_handler, connection_watcher, connection_registry } - } -} - -impl WebSocketMessageHandler for RpcWsHandler -where - Watcher: DetermineWatch, - Registry: RpcConnectionRegistry, - Registry::Connection: From, - Hash: RpcHash, -{ - fn handle_message( - &self, - connection_token: ConnectionToken, - message: String, - ) -> WebSocketResult> { - let maybe_rpc_response = self.rpc_io_handler.handle_request_sync(message.as_str()); - - debug!("RPC response string: {:?}", maybe_rpc_response); - - if let Ok(rpc_response) = serde_json::from_str::( - maybe_rpc_response.clone().unwrap_or_default().as_str(), - ) { - let ignore_response = - if let Ok(rpc_return_value) = RpcReturnValue::from_hex(&rpc_response.result) { - //in order to silence it - matches!(rpc_return_value.status, DirectRequestStatus::Processing(_)) - } else { - false - }; - - if let Ok(Some(connection_hash)) = - self.connection_watcher.must_be_watched(&rpc_response) - { - self.connection_registry.store( - connection_hash, - connection_token.into(), - rpc_response, - false, - ); - } - - if ignore_response { - return Ok(None) - } - } - - Ok(maybe_rpc_response) - } -} - -#[cfg(test)] -pub mod tests { - - use super::*; - use crate::{ - mocks::determine_watch_mock::DetermineWatchMock, - rpc_connection_registry::ConnectionRegistry, - }; - use codec::Encode; - use itc_tls_websocket_server::ConnectionToken; - use itp_rpc::RpcReturnValue; - use itp_types::DirectRequestStatus; - use itp_utils::ToHexPrefixed; - use jsonrpc_core::Params; - use serde_json::json; - - type TestConnectionRegistry = ConnectionRegistry; - type TestConnectionWatcher = DetermineWatchMock; - type TestWsHandler = RpcWsHandler; - - const RPC_METHOD_NAME: &str = "test_call"; - - #[test] - fn valid_rpc_call_without_watch_runs_successfully() { - let io_handler = create_io_handler_with_method(RPC_METHOD_NAME); - - let (connection_token, message) = create_message_to_handle(RPC_METHOD_NAME); - - let (ws_handler, connection_registry) = create_ws_handler(io_handler, None); - - let handle_result = ws_handler.handle_message(connection_token, message); - - assert!(handle_result.is_ok()); - assert!(connection_registry.is_empty()); - } - - #[test] - fn valid_rpc_call_with_watch_runs_successfully_and_stores_connection() { - let io_handler = create_io_handler_with_method(RPC_METHOD_NAME); - - let connection_hash = String::from("connection_hash"); - let (connection_token, message) = create_message_to_handle(RPC_METHOD_NAME); - - let (ws_handler, connection_registry) = - create_ws_handler(io_handler, Some(connection_hash.clone())); - - let handle_result = ws_handler.handle_message(connection_token, message); - - assert!(handle_result.is_ok()); - assert!(connection_registry.withdraw(&connection_hash).is_some()); - } - - #[test] - fn when_rpc_returns_error_then_return_ok_but_status_is_set_to_error() { - let io_handler = create_io_handler_with_error(RPC_METHOD_NAME); - - let connection_hash = String::from("connection_hash"); - let (connection_token, message) = create_message_to_handle(RPC_METHOD_NAME); - - let (ws_handler, connection_registry) = - create_ws_handler(io_handler, Some(connection_hash.clone())); - - let handle_result = ws_handler.handle_message(connection_token, message); - - assert!(handle_result.is_ok()); - assert!(connection_registry.withdraw(&connection_hash).is_some()); - } - - #[test] - fn when_rpc_method_does_not_match_anything_return_json_error_message() { - let io_handler = create_io_handler_with_error(RPC_METHOD_NAME); - let (connection_token, message) = create_message_to_handle("not_a_valid_method"); - - let (ws_handler, connection_registry) = create_ws_handler(io_handler, None); - - let handle_result = ws_handler.handle_message(connection_token, message).unwrap().unwrap(); - - assert_eq!(handle_result, "{\"jsonrpc\":\"2.0\",\"error\":{\"code\":-32601,\"message\":\"Method not found\"},\"id\":1}"); - assert!(connection_registry.is_empty()); - } - - fn create_message_to_handle(method_name: &str) -> (ConnectionToken, String) { - let json_rpc_pre_method = r#"{"jsonrpc": "2.0", "method": ""#; - let json_rpc_post_method = r#"", "params": {}, "id": 1}"#; - - let json_string = format!("{}{}{}", json_rpc_pre_method, method_name, json_rpc_post_method); - debug!("JSON input: {}", json_string); - - (ConnectionToken(23), json_string) - } - - fn create_ws_handler( - io_handler: IoHandler, - watch_connection: Option, - ) -> (TestWsHandler, Arc) { - let watcher = match watch_connection { - Some(hash) => TestConnectionWatcher::do_watch(hash), - None => TestConnectionWatcher::no_watch(), - }; - - let connection_registry = Arc::new(TestConnectionRegistry::new()); - - ( - TestWsHandler::new(io_handler, Arc::new(watcher), connection_registry.clone()), - connection_registry, - ) - } - - fn create_io_handler_with_method(method_name: &str) -> IoHandler { - create_io_handler( - method_name, - RpcReturnValue { - do_watch: false, - value: String::from("value").encode(), - status: DirectRequestStatus::Ok, - }, - ) - } - - fn create_io_handler_with_error(method_name: &str) -> IoHandler { - create_io_handler( - method_name, - RpcReturnValue { - value: "error!".encode(), - do_watch: false, - status: DirectRequestStatus::Error, - }, - ) - } - - fn create_io_handler(method_name: &str, return_value: ReturnValue) -> IoHandler - where - ReturnValue: Encode + Send + Sync + 'static, - { - let mut io_handler = IoHandler::new(); - io_handler.add_sync_method(method_name, move |_: Params| Ok(json!(return_value.to_hex()))); - io_handler - } -} diff --git a/tee-worker/bitacross/core/offchain-worker-executor/Cargo.toml b/tee-worker/bitacross/core/offchain-worker-executor/Cargo.toml deleted file mode 100644 index db752e7e20..0000000000 --- a/tee-worker/bitacross/core/offchain-worker-executor/Cargo.toml +++ /dev/null @@ -1,61 +0,0 @@ -[package] -name = "bc-itc-offchain-worker-executor" -version = "0.1.0" -authors = ['Trust Computing GmbH ', 'Integritee AG '] -edition = "2021" - -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html - -[dependencies] -codec = { package = "parity-scale-codec", workspace = true } -log = { workspace = true } -sgx_tstd = { workspace = true, optional = true } - -thiserror = { workspace = true, optional = true } -thiserror_sgx = { workspace = true, optional = true } - -itc-parentchain-light-client = { workspace = true } -itp-extrinsics-factory = { workspace = true } -itp-stf-executor = { package = "bc-itp-stf-executor", path = "../../core-primitives/stf-executor", default-features = false } -itp-stf-interface = { workspace = true } -itp-stf-primitives = { workspace = true } -itp-stf-state-handler = { workspace = true } -itp-top-pool-author = { package = "bc-itp-top-pool-author", path = "../../core-primitives/top-pool-author", default-features = false } -itp-types = { workspace = true } - -sp-runtime = { workspace = true } - -[dev-dependencies] -codec = { package = "parity-scale-codec", workspace = true, features = ["std"] } -itc-parentchain-light-client = { workspace = true, features = ["std", "mocks"] } -itp-extrinsics-factory = { workspace = true, features = ["std", "mocks"] } -itp-stf-executor = { package = "bc-itp-stf-executor", path = "../../core-primitives/stf-executor", features = ["std", "mocks"] } -itp-test = { workspace = true, features = ["std"] } -itp-top-pool-author = { package = "bc-itp-top-pool-author", path = "../../core-primitives/top-pool-author", features = ["std", "mocks"] } -itp-stf-interface = { workspace = true, features = ["std", "mocks"] } -itp-sgx-externalities = { workspace = true } -sp-core = { workspace = true, features = ["full_crypto"] } - -[features] -default = ["std"] -std = [ - "itc-parentchain-light-client/std", - "itp-extrinsics-factory/std", - "itp-stf-executor/std", - "itp-stf-interface/std", - "itp-stf-primitives/std", - "itp-stf-state-handler/std", - "itp-top-pool-author/std", - "itp-types/std", - "sp-runtime/std", - "thiserror", -] -sgx = [ - "itc-parentchain-light-client/sgx", - "itp-extrinsics-factory/sgx", - "itp-stf-executor/sgx", - "itp-stf-state-handler/sgx", - "itp-top-pool-author/sgx", - "sgx_tstd", - "thiserror_sgx", -] diff --git a/tee-worker/bitacross/core/offchain-worker-executor/src/error.rs b/tee-worker/bitacross/core/offchain-worker-executor/src/error.rs deleted file mode 100644 index 2c955d3e00..0000000000 --- a/tee-worker/bitacross/core/offchain-worker-executor/src/error.rs +++ /dev/null @@ -1,40 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -#[cfg(all(not(feature = "std"), feature = "sgx"))] -use crate::sgx_reexport_prelude::*; - -use std::boxed::Box; - -pub type Result = core::result::Result; - -/// General offchain-worker error type -#[derive(Debug, thiserror::Error)] -pub enum Error { - #[error("STF state handler error: {0}")] - StfStateHandler(#[from] itp_stf_state_handler::error::Error), - #[error("STF executor error: {0}")] - StfExecutor(#[from] itp_stf_executor::error::Error), - #[error("TOP pool author error: {0}")] - TopPoolAuthor(#[from] itp_top_pool_author::error::Error), - #[error("Light-client error: {0}")] - LightClient(#[from] itc_parentchain_light_client::error::Error), - #[error("Extrinsics factory error: {0}")] - ExtrinsicsFactory(#[from] itp_extrinsics_factory::error::Error), - #[error("{0}")] - Other(Box), -} diff --git a/tee-worker/bitacross/core/offchain-worker-executor/src/executor.rs b/tee-worker/bitacross/core/offchain-worker-executor/src/executor.rs deleted file mode 100644 index 5cf3e778b8..0000000000 --- a/tee-worker/bitacross/core/offchain-worker-executor/src/executor.rs +++ /dev/null @@ -1,373 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use crate::error::Result; -use codec::{Decode, Encode}; -use core::fmt::Debug; -use itc_parentchain_light_client::{ - concurrent_access::ValidatorAccess, BlockNumberOps, ExtrinsicSender, LightClientState, - NumberFor, -}; -use itp_extrinsics_factory::CreateExtrinsics; -use itp_stf_executor::{traits::StateUpdateProposer, ExecutedOperation}; -use itp_stf_interface::system_pallet::SystemPalletEventInterface; -use itp_stf_primitives::{traits::TrustedCallVerification, types::TrustedOperationOrHash}; -use itp_stf_state_handler::{handle_state::HandleState, query_shard_state::QueryShardState}; -use itp_top_pool_author::traits::AuthorApi; -use itp_types::{parentchain::ParentchainCall, OpaqueCall, ShardIdentifier, H256}; -use log::*; -use sp_runtime::traits::Block; -use std::{marker::PhantomData, sync::Arc, time::Duration, vec::Vec}; - -/// Off-chain worker executor implementation. -/// -/// Executes calls found in the top-pool and immediately applies the corresponding state diffs. -/// - Sends confirmations for all executed calls (TODO) -/// - Sends extrinsics for any parentchain effects (such as unshield calls). -/// -/// The trigger to start executing calls is given when the parentchain block imported event is -/// signaled (event listener). -pub struct Executor< - ParentchainBlock, - TopPoolAuthor, - StfExecutor, - StateHandler, - ValidatorAccessor, - ExtrinsicsFactory, - Stf, - TCS, - G, -> { - top_pool_author: Arc, - stf_executor: Arc, - state_handler: Arc, - validator_accessor: Arc, - extrinsics_factory: Arc, - _phantom: PhantomData<(ParentchainBlock, Stf, TCS, G)>, -} - -impl< - ParentchainBlock, - TopPoolAuthor, - StfExecutor, - StateHandler, - ValidatorAccessor, - ExtrinsicsFactory, - Stf, - TCS, - G, - > - Executor< - ParentchainBlock, - TopPoolAuthor, - StfExecutor, - StateHandler, - ValidatorAccessor, - ExtrinsicsFactory, - Stf, - TCS, - G, - > where - ParentchainBlock: Block, - StfExecutor: StateUpdateProposer, - TopPoolAuthor: AuthorApi, - StateHandler: QueryShardState + HandleState, - ValidatorAccessor: ValidatorAccess + Send + Sync + 'static, - ExtrinsicsFactory: CreateExtrinsics, - NumberFor: BlockNumberOps, - Stf: SystemPalletEventInterface, - TCS: PartialEq + Encode + Decode + Debug + Clone + Send + Sync + TrustedCallVerification, - G: PartialEq + Encode + Decode + Debug + Clone + Send + Sync, -{ - pub fn new( - top_pool_author: Arc, - stf_executor: Arc, - state_handler: Arc, - validator_accessor: Arc, - extrinsics_factory: Arc, - ) -> Self { - Self { - top_pool_author, - stf_executor, - state_handler, - validator_accessor, - extrinsics_factory, - _phantom: Default::default(), - } - } - - pub fn execute(&self) -> Result<()> { - let max_duration = Duration::from_secs(5); - let latest_parentchain_header = self.get_latest_parentchain_header()?; - - let mut parentchain_effects: Vec = Vec::new(); - - let shards = self.state_handler.list_shards()?; - trace!("Executing calls on {} shard(s)", shards.len()); - - for shard in shards { - debug!( - "executing pending tops in top pool with status: {:?}", - self.top_pool_author.get_status(shard) - ); - let trusted_calls = self.top_pool_author.get_pending_trusted_calls(shard); - trace!("Executing {} trusted calls on shard {:?}", trusted_calls.len(), shard); - - let batch_execution_result = self.stf_executor.propose_state_update( - &trusted_calls, - &latest_parentchain_header, - &shard, - max_duration, - |mut state| { - Stf::reset_events(&mut state); - state - }, - )?; - - parentchain_effects - .append(&mut batch_execution_result.get_extrinsic_callbacks().clone()); - - let failed_operations = batch_execution_result.get_failed_operations(); - let successful_operations: Vec> = batch_execution_result - .get_executed_operation_hashes() - .into_iter() - .map(|h| { - ExecutedOperation::success( - h, - TrustedOperationOrHash::Hash(h), - Vec::new(), - Vec::new(), - false, - ) - }) - .collect(); - - // Remove all not successfully executed operations from the top pool. - self.remove_calls_from_pool(&shard, failed_operations); - - // Apply the state update - self.apply_state_update(&shard, batch_execution_result.state_after_execution)?; - - // Remove successful operations from pool - self.remove_calls_from_pool(&shard, successful_operations); - - // TODO: notify parentchain about executed operations? -> add to parentchain effects - } - - if !parentchain_effects.is_empty() { - self.send_parentchain_effects(parentchain_effects)?; - } - - Ok(()) - } - - fn get_latest_parentchain_header(&self) -> Result { - let header = self.validator_accessor.execute_on_validator(|v| { - let latest_parentchain_header = v.latest_finalized_header()?; - Ok(latest_parentchain_header) - })?; - Ok(header) - } - - fn apply_state_update( - &self, - shard: &ShardIdentifier, - updated_state: >::Externalities, - ) -> Result<()> { - self.state_handler.reset(updated_state, shard)?; - Ok(()) - } - - fn send_parentchain_effects(&self, parentchain_effects: Vec) -> Result<()> { - let integritee_calls: Vec = parentchain_effects - .iter() - .filter_map(|parentchain_call| parentchain_call.as_litentry()) - .collect(); - let target_a_calls: Vec = parentchain_effects - .iter() - .filter_map(|parentchain_call| parentchain_call.as_target_a()) - .collect(); - let target_b_calls: Vec = parentchain_effects - .iter() - .filter_map(|parentchain_call| parentchain_call.as_target_b()) - .collect(); - debug!( - "stf wants to send calls to parentchains: Integritee: {} TargetA: {} TargetB: {}", - integritee_calls.len(), - target_a_calls.len(), - target_b_calls.len() - ); - if !target_a_calls.is_empty() { - warn!("sending extrinsics to target A unimplemented") - }; - if !target_b_calls.is_empty() { - warn!("sending extrinsics to target B unimplemented") - }; - - let extrinsics = - self.extrinsics_factory.create_extrinsics(integritee_calls.as_slice(), None)?; - self.validator_accessor - .execute_mut_on_validator(|v| v.send_extrinsics(extrinsics))?; - Ok(()) - } - - fn remove_calls_from_pool( - &self, - shard: &ShardIdentifier, - executed_calls: Vec>, - ) -> Vec> { - let executed_calls_tuple: Vec<_> = executed_calls - .iter() - .map(|e| (e.trusted_operation_or_hash.clone(), e.is_success())) - .collect(); - let failed_to_remove_hashes = - self.top_pool_author.remove_calls_from_pool(*shard, executed_calls_tuple); - - let failed_executed_calls: Vec<_> = executed_calls - .into_iter() - .filter(|e| failed_to_remove_hashes.contains(&e.trusted_operation_or_hash)) - .collect(); - - failed_executed_calls - } -} - -#[cfg(test)] -mod tests { - - use super::*; - use codec::{Decode, Encode}; - use itc_parentchain_light_client::mocks::validator_access_mock::ValidatorAccessMock; - use itp_extrinsics_factory::mock::ExtrinsicsFactoryMock; - use itp_sgx_externalities::SgxExternalitiesTrait; - use itp_stf_executor::mocks::StfExecutorMock; - - use itp_test::mock::{ - handle_state_mock::HandleStateMock, - stf_mock::{GetterMock, TrustedCallSignedMock}, - }; - use itp_top_pool_author::mocks::AuthorApiMock; - use itp_types::{Block as ParentchainBlock, RsaRequest}; - - use itp_test::mock::stf_mock::mock_top_indirect_trusted_call_signed; - use std::boxed::Box; - - type TestStateHandler = HandleStateMock; - type TestStfInterface = SystemPalletEventInterfaceMock; - type State = ::StateT; - type TestTopPoolAuthor = AuthorApiMock; - type TestStfExecutor = StfExecutorMock; - type TestValidatorAccess = ValidatorAccessMock; - type TestExtrinsicsFactory = ExtrinsicsFactoryMock; - type TestExecutor = Executor< - ParentchainBlock, - TestTopPoolAuthor, - TestStfExecutor, - TestStateHandler, - TestValidatorAccess, - TestExtrinsicsFactory, - TestStfInterface, - TrustedCallSignedMock, - GetterMock, - >; - - const EVENT_COUNT_KEY: &[u8] = b"event_count"; - - struct SystemPalletEventInterfaceMock; - - impl SystemPalletEventInterface for SystemPalletEventInterfaceMock { - type EventRecord = String; - type EventIndex = u32; - type BlockNumber = u32; - type Hash = String; - - fn get_events(_state: &mut State) -> Vec> { - unimplemented!(); - } - - fn get_event_count(state: &mut State) -> Self::EventIndex { - let encoded_value = state.get(EVENT_COUNT_KEY).unwrap(); - Self::EventIndex::decode(&mut encoded_value.as_slice()).unwrap() - } - - fn get_event_topics( - _state: &mut State, - _topic: &Self::Hash, - ) -> Vec<(Self::BlockNumber, Self::EventIndex)> { - unimplemented!() - } - - fn reset_events(state: &mut State) { - state.insert(EVENT_COUNT_KEY.to_vec(), 0u32.encode()); - } - } - - #[test] - fn executing_tops_from_pool_works_and_empties_pool() { - let stf_executor = Arc::new(TestStfExecutor::new(State::default())); - let top_pool_author = Arc::new(TestTopPoolAuthor::default()); - top_pool_author - .submit_top(RsaRequest::new(shard(), mock_top_indirect_trusted_call_signed().encode())); - - assert_eq!(1, top_pool_author.pending_tops(shard()).unwrap().len()); - - let executor = create_executor(top_pool_author.clone(), stf_executor); - - assert!(executor.execute().is_ok()); - - assert_eq!(0, top_pool_author.pending_tops(shard()).unwrap().len()); - } - - #[test] - fn reset_events_is_called() { - let mut state = State::default(); - let event_count = 5; - state.insert(EVENT_COUNT_KEY.to_vec(), event_count.encode()); - - let stf_executor = Arc::new(TestStfExecutor::new(state)); - assert_eq!(TestStfInterface::get_event_count(&mut stf_executor.get_state()), event_count); - - let top_pool_author = Arc::new(TestTopPoolAuthor::default()); - - let executor = create_executor(top_pool_author, stf_executor.clone()); - - executor.execute().unwrap(); - - assert_eq!(TestStfInterface::get_event_count(&mut stf_executor.get_state()), 0); - } - - fn create_executor( - top_pool_author: Arc, - stf_executor: Arc, - ) -> TestExecutor { - let state_handler = Arc::new(TestStateHandler::from_shard(shard()).unwrap()); - let validator_access = Arc::new(TestValidatorAccess::default()); - let extrinsics_factory = Arc::new(TestExtrinsicsFactory::default()); - - TestExecutor::new( - top_pool_author, - stf_executor, - state_handler, - validator_access, - extrinsics_factory, - ) - } - - fn shard() -> ShardIdentifier { - ShardIdentifier::default() - } -} diff --git a/tee-worker/bitacross/core/offchain-worker-executor/src/lib.rs b/tee-worker/bitacross/core/offchain-worker-executor/src/lib.rs deleted file mode 100644 index d30a11ba0b..0000000000 --- a/tee-worker/bitacross/core/offchain-worker-executor/src/lib.rs +++ /dev/null @@ -1,33 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -#![cfg_attr(not(feature = "std"), no_std)] - -#[cfg(all(feature = "std", feature = "sgx"))] -compile_error!("feature \"std\" and feature \"sgx\" cannot be enabled at the same time"); - -#[cfg(all(not(feature = "std"), feature = "sgx"))] -extern crate sgx_tstd as std; - -// re-export module to properly feature gate sgx and regular std environment -#[cfg(all(not(feature = "std"), feature = "sgx"))] -pub mod sgx_reexport_prelude { - pub use thiserror_sgx as thiserror; -} - -pub mod error; -pub mod executor; diff --git a/tee-worker/bitacross/core/parentchain/block-import-dispatcher/Cargo.toml b/tee-worker/bitacross/core/parentchain/block-import-dispatcher/Cargo.toml deleted file mode 100644 index 28261ceb76..0000000000 --- a/tee-worker/bitacross/core/parentchain/block-import-dispatcher/Cargo.toml +++ /dev/null @@ -1,38 +0,0 @@ -[package] -name = "bc-itc-parentchain-block-import-dispatcher" -version = "0.1.0" -authors = ['Trust Computing GmbH ', 'Integritee AG '] -edition = "2021" - -[dependencies] -sgx_tstd = { workspace = true, optional = true } -sgx_types = { workspace = true } - -itc-parentchain-block-importer = { package = "bc-itc-parentchain-block-importer", path = "../block-importer", default-features = false } -itp-import-queue = { workspace = true } - -thiserror = { workspace = true, optional = true } -thiserror_sgx = { workspace = true, optional = true } - -log = { workspace = true } - -[dev-dependencies] -itc-parentchain-block-importer = { package = "bc-itc-parentchain-block-importer", path = "../block-importer", features = ["mocks"] } - -[features] -default = ["std"] -std = [ - "itc-parentchain-block-importer/std", - "itp-import-queue/std", - "log/std", - "thiserror", -] -sgx = [ - "sgx_tstd", - "itc-parentchain-block-importer/sgx", - "itp-import-queue/sgx", - "thiserror_sgx", -] - -# feature to export mock implementations, only to be used for dev-dependencies! -mocks = [] diff --git a/tee-worker/bitacross/core/parentchain/block-import-dispatcher/src/error.rs b/tee-worker/bitacross/core/parentchain/block-import-dispatcher/src/error.rs deleted file mode 100644 index b5d73ffe54..0000000000 --- a/tee-worker/bitacross/core/parentchain/block-import-dispatcher/src/error.rs +++ /dev/null @@ -1,47 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -#[cfg(all(not(feature = "std"), feature = "sgx"))] -use crate::sgx_reexport_prelude::*; - -use sgx_types::sgx_status_t; -use std::boxed::Box; - -pub type Result = core::result::Result; - -/// Parentchain block importer error. -#[derive(Debug, thiserror::Error)] -pub enum Error { - #[error("SGX error, status: {0}")] - Sgx(sgx_status_t), - #[error("Two Dispatcher types assigned. Please double check the initialization process.")] - CanNotAssignTwoDispatcher, - #[error("Even though there is no dispatcher assigned, the dispatch function is called.")] - NoDispatcherAssigned, - #[error("Block import queue error: {0}")] - ImportQueue(#[from] itp_import_queue::error::Error), - #[error("Block import error: {0}")] - BlockImport(#[from] itc_parentchain_block_importer::error::Error), - #[error(transparent)] - Other(#[from] Box), -} - -impl From for Error { - fn from(sgx_status: sgx_status_t) -> Self { - Self::Sgx(sgx_status) - } -} diff --git a/tee-worker/bitacross/core/parentchain/block-import-dispatcher/src/immediate_dispatcher.rs b/tee-worker/bitacross/core/parentchain/block-import-dispatcher/src/immediate_dispatcher.rs deleted file mode 100644 index 080f158144..0000000000 --- a/tee-worker/bitacross/core/parentchain/block-import-dispatcher/src/immediate_dispatcher.rs +++ /dev/null @@ -1,107 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use crate::{error::Result, DispatchBlockImport}; -use itc_parentchain_block_importer::ImportParentchainBlocks; -use log::*; -use std::{boxed::Box, vec::Vec}; - -/// Block import dispatcher that immediately imports the blocks, without any processing or queueing. -pub struct ImmediateDispatcher { - pub block_importer: BlockImporter, - import_event_observers: Vec>, -} - -impl ImmediateDispatcher { - pub fn new(block_importer: BlockImporter) -> Self { - ImmediateDispatcher { block_importer, import_event_observers: Vec::new() } - } - - pub fn with_observer(self, callback: F) -> Self - where - F: Fn() + Send + Sync + 'static, - { - let mut updated_observers = self.import_event_observers; - updated_observers.push(Box::new(callback)); - - Self { block_importer: self.block_importer, import_event_observers: updated_observers } - } -} - -impl DispatchBlockImport - for ImmediateDispatcher -where - BlockImporter: ImportParentchainBlocks, -{ - fn dispatch_import( - &self, - blocks: Vec, - events: Vec>, - _immediate_import: bool, - ) -> Result<()> { - // _immediate_import does not matter for the immediate dispatcher, behavoiur is the same. Immediate block import. - - debug!("Importing {} parentchain blocks", blocks.len()); - self.block_importer.import_parentchain_blocks(blocks, events)?; - debug!("Notifying {} observers of import", self.import_event_observers.len()); - self.import_event_observers.iter().for_each(|callback| callback()); - Ok(()) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use itc_parentchain_block_importer::block_importer_mock::ParentchainBlockImporterMock; - use std::{ - sync::{Arc, RwLock}, - vec, - }; - - type SignedBlockType = u32; - type TestBlockImporter = ParentchainBlockImporterMock; - type TestDispatcher = ImmediateDispatcher; - - #[derive(Default)] - struct NotificationCounter { - counter: RwLock, - } - - impl NotificationCounter { - fn increment(&self) { - *self.counter.write().unwrap() += 1; - } - - pub fn get_counter(&self) -> usize { - *self.counter.read().unwrap() - } - } - - #[test] - fn listeners_get_notified_upon_import() { - let block_importer = TestBlockImporter::default(); - let notification_counter = Arc::new(NotificationCounter::default()); - let counter_clone = notification_counter.clone(); - let dispatcher = TestDispatcher::new(block_importer).with_observer(move || { - counter_clone.increment(); - }); - - dispatcher.dispatch_import(vec![1u32, 2u32], vec![], false).unwrap(); - - assert_eq!(1, notification_counter.get_counter()); - } -} diff --git a/tee-worker/bitacross/core/parentchain/block-import-dispatcher/src/lib.rs b/tee-worker/bitacross/core/parentchain/block-import-dispatcher/src/lib.rs deleted file mode 100644 index 34e94523d0..0000000000 --- a/tee-worker/bitacross/core/parentchain/block-import-dispatcher/src/lib.rs +++ /dev/null @@ -1,125 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ -//! Dispatching of block imports. - -#![cfg_attr(not(feature = "std"), no_std)] - -#[cfg(all(feature = "std", feature = "sgx"))] -compile_error!("feature \"std\" and feature \"sgx\" cannot be enabled at the same time"); - -#[cfg(all(not(feature = "std"), feature = "sgx"))] -extern crate sgx_tstd as std; - -// re-export module to properly feature gate sgx and regular std environment -#[cfg(all(not(feature = "std"), feature = "sgx"))] -pub mod sgx_reexport_prelude { - pub use thiserror_sgx as thiserror; -} - -pub mod error; -pub mod immediate_dispatcher; -pub mod triggered_dispatcher; - -#[cfg(feature = "mocks")] -pub mod trigger_parentchain_block_import_mock; - -use error::{Error, Result}; -use std::{sync::Arc, vec::Vec}; - -/// Trait to dispatch blocks for import into the local light-client. -pub trait DispatchBlockImport { - /// Dispatch blocks to be imported. - /// - /// The blocks may be imported immediately, get queued, delayed or grouped. - fn dispatch_import( - &self, - blocks: Vec, - events: Vec>, - immediate_import: bool, - ) -> Result<()>; -} - -/// Wrapper for the actual dispatchers. Allows to define one global type for -/// both dispatchers without changing the global variable when switching -/// the dispatcher type. It also allows for empty dispatchers, for use cases that -/// do not need block syncing for a specific parentchain type. -pub enum BlockImportDispatcher { - TriggeredDispatcher(Arc), - ImmediateDispatcher(Arc), - EmptyDispatcher, -} - -impl - BlockImportDispatcher -{ - pub fn new_triggered_dispatcher(triggered_dispatcher: Arc) -> Self { - BlockImportDispatcher::TriggeredDispatcher(triggered_dispatcher) - } - - pub fn new_immediate_dispatcher(immediate_dispatcher: Arc) -> Self { - BlockImportDispatcher::ImmediateDispatcher(immediate_dispatcher) - } - - pub fn new_empty_dispatcher() -> Self { - BlockImportDispatcher::EmptyDispatcher - } - - pub fn triggered_dispatcher(&self) -> Option> { - match self { - BlockImportDispatcher::TriggeredDispatcher(triggered_dispatcher) => - Some(triggered_dispatcher.clone()), - _ => None, - } - } - - pub fn immediate_dispatcher(&self) -> Option> { - match self { - BlockImportDispatcher::ImmediateDispatcher(immediate_dispatcher) => - Some(immediate_dispatcher.clone()), - _ => None, - } - } -} - -impl DispatchBlockImport - for BlockImportDispatcher -where - TriggeredDispatcher: DispatchBlockImport, - ImmediateDispatcher: DispatchBlockImport, -{ - fn dispatch_import( - &self, - blocks: Vec, - events: Vec>, - immediate_import: bool, - ) -> Result<()> { - match self { - BlockImportDispatcher::TriggeredDispatcher(dispatcher) => { - log::trace!("TRIGGERED DISPATCHER MATCH"); - dispatcher.dispatch_import(blocks, events, immediate_import) - }, - BlockImportDispatcher::ImmediateDispatcher(dispatcher) => { - log::trace!("IMMEDIATE DISPATCHER MATCH"); - dispatcher.dispatch_import(blocks, events, immediate_import) - }, - BlockImportDispatcher::EmptyDispatcher => { - log::trace!("EMPTY DISPATCHER DISPATCHER MATCH"); - Err(Error::NoDispatcherAssigned) - }, - } - } -} diff --git a/tee-worker/bitacross/core/parentchain/block-import-dispatcher/src/trigger_parentchain_block_import_mock.rs b/tee-worker/bitacross/core/parentchain/block-import-dispatcher/src/trigger_parentchain_block_import_mock.rs deleted file mode 100644 index a4953a4fbb..0000000000 --- a/tee-worker/bitacross/core/parentchain/block-import-dispatcher/src/trigger_parentchain_block_import_mock.rs +++ /dev/null @@ -1,102 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -#[cfg(feature = "sgx")] -use std::sync::SgxRwLock as RwLock; - -#[cfg(feature = "std")] -use std::sync::RwLock; - -use crate::{error::Result, triggered_dispatcher::TriggerParentchainBlockImport}; - -/// Mock for `TriggerParentchainBlockImport`, to be used in unit tests. -/// -/// Allows setting the latest imported block, which is returned upon calling -/// the import methods. -pub struct TriggerParentchainBlockImportMock { - latest_imported: Option, - import_has_been_called: RwLock, -} - -impl TriggerParentchainBlockImportMock { - pub fn with_latest_imported(mut self, maybe_block: Option) -> Self { - self.latest_imported = maybe_block; - self - } - - pub fn has_import_been_called(&self) -> bool { - let import_flag = self.import_has_been_called.read().unwrap(); - *import_flag - } -} - -impl Default for TriggerParentchainBlockImportMock { - fn default() -> Self { - TriggerParentchainBlockImportMock { - latest_imported: None, - import_has_been_called: RwLock::new(false), - } - } -} - -impl TriggerParentchainBlockImport - for TriggerParentchainBlockImportMock -where - SignedBlockType: Clone, -{ - type SignedBlockType = SignedBlockType; - - fn import_all(&self) -> Result> { - let mut import_flag = self.import_has_been_called.write().unwrap(); - *import_flag = true; - Ok(self.latest_imported.clone()) - } - - fn import_all_but_latest(&self) -> Result<()> { - let mut import_flag = self.import_has_been_called.write().unwrap(); - *import_flag = true; - Ok(()) - } - - fn import_until( - &self, - _predicate: impl Fn(&SignedBlockType) -> bool, - ) -> Result> { - let mut import_flag = self.import_has_been_called.write().unwrap(); - *import_flag = true; - Ok(self.latest_imported.clone()) - } - - fn peek( - &self, - predicate: impl Fn(&SignedBlockType) -> bool, - ) -> Result> { - match &self.latest_imported { - None => Ok(None), - Some(block) => { - if predicate(block) { - return Ok(Some(block.clone())) - } - Ok(None) - }, - } - } - - fn peek_latest(&self) -> Result> { - Ok(self.latest_imported.clone()) - } -} diff --git a/tee-worker/bitacross/core/parentchain/block-import-dispatcher/src/triggered_dispatcher.rs b/tee-worker/bitacross/core/parentchain/block-import-dispatcher/src/triggered_dispatcher.rs deleted file mode 100644 index 712fcc724d..0000000000 --- a/tee-worker/bitacross/core/parentchain/block-import-dispatcher/src/triggered_dispatcher.rs +++ /dev/null @@ -1,374 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -//! A block import dispatcher that retains all blocks in a queue until import is triggered. - -use crate::{ - error::{Error, Result}, - DispatchBlockImport, -}; -use itc_parentchain_block_importer::ImportParentchainBlocks; -use itp_import_queue::{PeekQueue, PopFromQueue, PushToQueue}; -use log::trace; -use std::vec::Vec; - -pub type RawEventsPerBlock = Vec; - -/// Trait to specifically trigger the import of parentchain blocks. -pub trait TriggerParentchainBlockImport { - type SignedBlockType; - /// Trigger the import of all queued block, **including** the latest one. - /// - /// Returns the latest imported block (if any). - fn import_all(&self) -> Result>; - - /// Trigger import of all queued blocks, **except** the latest one. - fn import_all_but_latest(&self) -> Result<()>; - - /// Trigger import of all blocks up to **and including** a specific block. - /// - /// If no block in the queue matches, then no blocks will be imported. - /// Returns the latest imported block (if any). - fn import_until( - &self, - predicate: impl Fn(&Self::SignedBlockType) -> bool, - ) -> Result>; - - /// Search the import queue with a given predicate and return a reference - /// to the first element that matches the predicate. - fn peek( - &self, - predicate: impl Fn(&Self::SignedBlockType) -> bool, - ) -> Result>; - - /// Peek the latest block in the import queue. Returns None if queue is empty. - fn peek_latest(&self) -> Result>; -} - -/// Dispatcher for block imports that retains blocks until the import is triggered, using the -/// `TriggerParentchainBlockImport` trait implementation. -pub struct TriggeredDispatcher { - pub block_importer: BlockImporter, - import_queue: BlockImportQueue, - events_queue: EventsImportQueue, -} - -impl - TriggeredDispatcher -where - BlockImporter: ImportParentchainBlocks, - BlockImportQueue: PushToQueue - + PopFromQueue, - EventsImportQueue: PushToQueue + PopFromQueue, -{ - pub fn new( - block_importer: BlockImporter, - block_import_queue: BlockImportQueue, - events_import_queue: EventsImportQueue, - ) -> Self { - TriggeredDispatcher { - block_importer, - import_queue: block_import_queue, - events_queue: events_import_queue, - } - } -} - -impl - DispatchBlockImport - for TriggeredDispatcher -where - BlockImporter: ImportParentchainBlocks, - BlockImportQueue: PushToQueue + PopFromQueue, - EventsImportQueue: PushToQueue + PopFromQueue, -{ - fn dispatch_import( - &self, - blocks: Vec, - events: Vec, - immediate_import: bool, - ) -> Result<()> { - let parentchain_id = self.block_importer.parentchain_id(); - trace!( - "[{:?}] Triggered dispatcher received block(s) and event(s) ({}) ({})", - parentchain_id, - blocks.len(), - events.len() - ); - if immediate_import { - trace!( - "[{:?}] Triggered is in sync mode, immediately importing blocks and events", - parentchain_id - ); - self.block_importer - .import_parentchain_blocks(blocks, events) - .map_err(Error::BlockImport) - } else { - trace!("[{:?}] pushing blocks and events to import queues", parentchain_id); - self.events_queue.push_multiple(events).map_err(Error::ImportQueue)?; - self.import_queue.push_multiple(blocks).map_err(Error::ImportQueue) - } - } -} - -impl TriggerParentchainBlockImport - for TriggeredDispatcher -where - BlockImporter: ImportParentchainBlocks, - BlockImportQueue: PushToQueue - + PopFromQueue - + PeekQueue, - EventsImportQueue: PushToQueue - + PopFromQueue - + PeekQueue, -{ - type SignedBlockType = BlockImporter::SignedBlockType; - - fn import_all(&self) -> Result> { - let blocks_to_import = self.import_queue.pop_all().map_err(Error::ImportQueue)?; - let events_to_import = self.events_queue.pop_all().map_err(Error::ImportQueue)?; - - let latest_imported_block = blocks_to_import.last().map(|b| (*b).clone()); - let parentchain_id = self.block_importer.parentchain_id(); - trace!( - "[{:?}] Trigger import of all parentchain blocks and events in queue ({}) ({})", - parentchain_id, - blocks_to_import.len(), - events_to_import.len() - ); - - self.block_importer - .import_parentchain_blocks(blocks_to_import, events_to_import) - .map_err(Error::BlockImport)?; - - Ok(latest_imported_block) - } - - fn import_all_but_latest(&self) -> Result<()> { - let blocks_to_import = self.import_queue.pop_all_but_last().map_err(Error::ImportQueue)?; - let events_to_import = self.events_queue.pop_all_but_last().map_err(Error::ImportQueue)?; - let parentchain_id = self.block_importer.parentchain_id(); - trace!( - "[{:?}] Trigger import of all parentchain blocks and events, except the latest, from queue ({}) ({})", - parentchain_id, - blocks_to_import.len(), - events_to_import.len() - ); - - self.block_importer - .import_parentchain_blocks(blocks_to_import, events_to_import) - .map_err(Error::BlockImport) - } - - fn import_until( - &self, - predicate: impl Fn(&BlockImporter::SignedBlockType) -> bool, - ) -> Result> { - trace!("Import of parentchain blocks and events has been triggered"); - let blocks_to_import = - self.import_queue.pop_until(predicate).map_err(Error::ImportQueue)?; - - let events_to_import = self - .events_queue - .pop_from_front_until(blocks_to_import.len()) - .map_err(Error::ImportQueue)?; - - let latest_imported_block = blocks_to_import.last().map(|b| (*b).clone()); - let parentchain_id = self.block_importer.parentchain_id(); - trace!( - "[{:?}] Import of parentchain blocks and events has been triggered, importing {} blocks and {} events from queue", - parentchain_id, - blocks_to_import.len(), - events_to_import.len(), - ); - - self.block_importer - .import_parentchain_blocks(blocks_to_import, events_to_import) - .map_err(Error::BlockImport)?; - - Ok(latest_imported_block) - } - - fn peek( - &self, - predicate: impl Fn(&BlockImporter::SignedBlockType) -> bool, - ) -> Result> { - let parentchain_id = self.block_importer.parentchain_id(); - trace!( - "[{:?}] Peek find parentchain import queue (currently has {} elements)", - parentchain_id, - self.import_queue.peek_queue_size().unwrap_or(0) - ); - self.import_queue.peek_find(predicate).map_err(Error::ImportQueue) - } - - fn peek_latest(&self) -> Result> { - let parentchain_id = self.block_importer.parentchain_id(); - trace!( - "[{:?}] Peek latest parentchain import queue (currently has {} elements)", - parentchain_id, - self.import_queue.peek_queue_size().unwrap_or(0) - ); - self.import_queue.peek_last().map_err(Error::ImportQueue) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use itc_parentchain_block_importer::block_importer_mock::ParentchainBlockImporterMock; - use itp_import_queue::{ImportQueue, PopFromQueue}; - - type SignedBlockType = u32; - type TestBlockImporter = ParentchainBlockImporterMock; - type TestQueue = ImportQueue; - type TestEventsQueue = ImportQueue; - type TestDispatcher = TriggeredDispatcher; - - #[test] - fn dispatching_blocks_imports_none_if_not_triggered() { - let dispatcher = test_fixtures(); - - dispatcher - .dispatch_import( - vec![1, 2, 3, 4, 5], - vec![vec![1], vec![2], vec![3], vec![4], vec![5]], - false, - ) - .unwrap(); - - assert!(dispatcher.block_importer.get_all_imported_blocks().is_empty()); - assert_eq!(dispatcher.import_queue.pop_all().unwrap(), vec![1, 2, 3, 4, 5]); - assert_eq!( - dispatcher.events_queue.pop_all().unwrap(), - vec![vec![1], vec![2], vec![3], vec![4], vec![5]] - ); - } - - #[test] - fn dispatching_blocks_multiple_times_add_all_to_queue() { - let dispatcher = test_fixtures(); - - dispatcher - .dispatch_import( - vec![1, 2, 3, 4, 5], - vec![vec![1], vec![2], vec![3], vec![4], vec![5]], - false, - ) - .unwrap(); - dispatcher - .dispatch_import(vec![6, 7, 8], vec![vec![6], vec![7], vec![8]], false) - .unwrap(); - - assert!(dispatcher.block_importer.get_all_imported_blocks().is_empty()); - assert_eq!(dispatcher.import_queue.pop_all().unwrap(), vec![1, 2, 3, 4, 5, 6, 7, 8]); - assert_eq!( - dispatcher.events_queue.pop_all().unwrap(), - vec![vec![1], vec![2], vec![3], vec![4], vec![5], vec![6], vec![7], vec![8]] - ); - } - - #[test] - fn triggering_import_all_empties_queue() { - let dispatcher = test_fixtures(); - - dispatcher.dispatch_import(vec![1, 2, 3, 4, 5], vec![], false).unwrap(); - let latest_imported = dispatcher.import_all().unwrap().unwrap(); - - assert_eq!(latest_imported, 5); - assert_eq!(dispatcher.block_importer.get_all_imported_blocks(), vec![1, 2, 3, 4, 5]); - assert!(dispatcher.import_queue.is_empty().unwrap()); - } - - #[test] - fn triggering_import_all_on_empty_queue_imports_none() { - let dispatcher = test_fixtures(); - - dispatcher.dispatch_import(vec![], vec![], false).unwrap(); - let maybe_latest_imported = dispatcher.import_all().unwrap(); - - assert!(maybe_latest_imported.is_none()); - assert_eq!( - dispatcher.block_importer.get_all_imported_blocks(), - Vec::::default() - ); - assert!(dispatcher.import_queue.is_empty().unwrap()); - assert!(dispatcher.events_queue.is_empty().unwrap()); - } - - #[test] - fn triggering_import_until_leaves_remaining_in_queue() { - let dispatcher = test_fixtures(); - - dispatcher - .dispatch_import( - vec![1, 2, 3, 4, 5], - vec![vec![1], vec![2], vec![3], vec![4], vec![5]], - false, - ) - .unwrap(); - let latest_imported = - dispatcher.import_until(|i: &SignedBlockType| i == &4).unwrap().unwrap(); - - assert_eq!(latest_imported, 4); - assert_eq!(dispatcher.block_importer.get_all_imported_blocks(), vec![1, 2, 3, 4]); - assert_eq!(dispatcher.import_queue.pop_all().unwrap(), vec![5]); - assert_eq!(dispatcher.events_queue.pop_all().unwrap(), vec![vec![5]]); - } - - #[test] - fn triggering_import_until_with_no_match_imports_nothing() { - let dispatcher = test_fixtures(); - - dispatcher - .dispatch_import( - vec![1, 2, 3, 4, 5], - vec![vec![1], vec![2], vec![3], vec![4], vec![5]], - false, - ) - .unwrap(); - let maybe_latest_imported = dispatcher.import_until(|i: &SignedBlockType| i == &8).unwrap(); - - assert!(maybe_latest_imported.is_none()); - assert!(dispatcher.block_importer.get_all_imported_blocks().is_empty()); - assert_eq!(dispatcher.import_queue.pop_all().unwrap(), vec![1, 2, 3, 4, 5]); - assert_eq!( - dispatcher.events_queue.pop_all().unwrap(), - vec![vec![1], vec![2], vec![3], vec![4], vec![5]] - ); - } - - #[test] - fn trigger_import_all_but_latest_works() { - let dispatcher = test_fixtures(); - - dispatcher.dispatch_import(vec![1, 2, 3, 4, 5], vec![], false).unwrap(); - dispatcher.import_all_but_latest().unwrap(); - - assert_eq!(dispatcher.block_importer.get_all_imported_blocks(), vec![1, 2, 3, 4]); - assert_eq!(dispatcher.import_queue.pop_all().unwrap(), vec![5]); - } - - fn test_fixtures() -> TestDispatcher { - let events_import_queue = ImportQueue::::default(); - let import_queue = ImportQueue::::default(); - let block_importer = ParentchainBlockImporterMock::::default(); - let dispatcher = - TriggeredDispatcher::new(block_importer, import_queue, events_import_queue); - dispatcher - } -} diff --git a/tee-worker/bitacross/core/parentchain/block-importer/Cargo.toml b/tee-worker/bitacross/core/parentchain/block-importer/Cargo.toml deleted file mode 100644 index 9ae50d53f7..0000000000 --- a/tee-worker/bitacross/core/parentchain/block-importer/Cargo.toml +++ /dev/null @@ -1,57 +0,0 @@ -[package] -name = "bc-itc-parentchain-block-importer" -version = "0.1.0" -authors = ['Trust Computing GmbH ', 'Integritee AG '] -edition = "2021" - -[dependencies] -sgx_tstd = { workspace = true, optional = true } -sgx_types = { workspace = true } - -ita-stf = { package = "bc-ita-stf", path = "../../../app-libs/stf", default-features = false } -itc-parentchain-indirect-calls-executor = { package = "bc-itc-parentchain-indirect-calls-executor", path = "../indirect-calls-executor", default-features = false } -itc-parentchain-light-client = { workspace = true } -itp-enclave-metrics = { workspace = true } -itp-extrinsics-factory = { workspace = true } -itp-ocall-api = { workspace = true } -itp-stf-executor = { package = "bc-itp-stf-executor", path = "../../../core-primitives/stf-executor", default-features = false } -itp-stf-interface = { workspace = true } -itp-types = { workspace = true } - -thiserror = { workspace = true, optional = true } -thiserror_sgx = { workspace = true, optional = true } - -codec = { package = "parity-scale-codec", workspace = true } -log = { workspace = true } -sp-runtime = { workspace = true } - -[features] -default = ["std"] -std = [ - "ita-stf/std", - "itc-parentchain-indirect-calls-executor/std", - "itc-parentchain-light-client/std", - "itp-enclave-metrics/std", - "itp-extrinsics-factory/std", - "itp-stf-executor/std", - "itp-stf-interface/std", - "itp-types/std", - "codec/std", - "log/std", - "sp-runtime/std", - "thiserror", - "itp-ocall-api/std", -] -sgx = [ - "sgx_tstd", - "ita-stf/sgx", - "itc-parentchain-indirect-calls-executor/sgx", - "itc-parentchain-light-client/sgx", - "itp-enclave-metrics/sgx", - "itp-extrinsics-factory/sgx", - "itp-stf-executor/sgx", - "thiserror_sgx", -] - -# feature to export mock implementations, only to be used for dev-dependencies! -mocks = [] diff --git a/tee-worker/bitacross/core/parentchain/block-importer/src/block_importer.rs b/tee-worker/bitacross/core/parentchain/block-importer/src/block_importer.rs deleted file mode 100644 index 6ca5c4866a..0000000000 --- a/tee-worker/bitacross/core/parentchain/block-importer/src/block_importer.rs +++ /dev/null @@ -1,221 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -//! Imports parentchain blocks and executes any indirect calls found in the extrinsics. - -use crate::{error::Result, ImportParentchainBlocks}; - -use ita_stf::ParentchainHeader; -use itc_parentchain_indirect_calls_executor::ExecuteIndirectCalls; -use itc_parentchain_light_client::{ - concurrent_access::ValidatorAccess, BlockNumberOps, ExtrinsicSender, Validator, -}; -use itp_enclave_metrics::EnclaveMetric; -use itp_extrinsics_factory::CreateExtrinsics; -use itp_ocall_api::EnclaveMetricsOCallApi; -use itp_stf_executor::traits::StfUpdateState; -use itp_stf_interface::ShardCreationInfo; -use itp_types::{ - parentchain::{IdentifyParentchain, ParentchainId}, - OpaqueCall, H256, -}; -use log::*; -use sp_runtime::{ - generic::SignedBlock as SignedBlockG, - traits::{Block as ParentchainBlockTrait, Header as HeaderT, NumberFor}, -}; -use std::{marker::PhantomData, sync::Arc, vec, vec::Vec}; - -/// Parentchain block import implementation. -pub struct ParentchainBlockImporter< - ParentchainBlock, - ValidatorAccessor, - StfExecutor, - ExtrinsicsFactory, - IndirectCallsExecutor, - OCallApi, -> { - pub validator_accessor: Arc, - stf_executor: Arc, - extrinsics_factory: Arc, - pub indirect_calls_executor: Arc, - ocall_api: Arc, - shard_creation_info: ShardCreationInfo, - pub parentchain_id: ParentchainId, - _phantom: PhantomData, -} - -impl< - ParentchainBlock, - ValidatorAccessor, - StfExecutor, - ExtrinsicsFactory, - IndirectCallsExecutor, - OCallApi, - > - ParentchainBlockImporter< - ParentchainBlock, - ValidatorAccessor, - StfExecutor, - ExtrinsicsFactory, - IndirectCallsExecutor, - OCallApi, - > -{ - pub fn new( - validator_accessor: Arc, - stf_executor: Arc, - extrinsics_factory: Arc, - indirect_calls_executor: Arc, - ocall_api: Arc, - shard_creation_info: ShardCreationInfo, - parentchain_id: ParentchainId, - ) -> Self { - ParentchainBlockImporter { - validator_accessor, - stf_executor, - extrinsics_factory, - indirect_calls_executor, - ocall_api, - shard_creation_info, - parentchain_id, - _phantom: Default::default(), - } - } -} - -impl< - ParentchainBlock, - ValidatorAccessor, - StfExecutor, - ExtrinsicsFactory, - IndirectCallsExecutor, - OcallApi, - > ImportParentchainBlocks - for ParentchainBlockImporter< - ParentchainBlock, - ValidatorAccessor, - StfExecutor, - ExtrinsicsFactory, - IndirectCallsExecutor, - OcallApi, - > where - ParentchainBlock: ParentchainBlockTrait, - NumberFor: BlockNumberOps, - ValidatorAccessor: ValidatorAccess + IdentifyParentchain, - StfExecutor: StfUpdateState, - ExtrinsicsFactory: CreateExtrinsics, - IndirectCallsExecutor: ExecuteIndirectCalls, - OcallApi: EnclaveMetricsOCallApi, -{ - type SignedBlockType = SignedBlockG; - - fn import_parentchain_blocks( - &self, - blocks_to_import: Vec, - events_to_import: Vec>, - ) -> Result<()> { - let mut calls = Vec::::new(); - let id = self.validator_accessor.parentchain_id(); - - debug!( - "[{:?}] Import {} blocks to light-client. event blocks {}", - id, - blocks_to_import.len(), - events_to_import.len() - ); - let events_to_import_aligned: Vec> = if events_to_import.is_empty() { - vec![vec![]; blocks_to_import.len()] - } else { - events_to_import - }; - for (signed_block, raw_events) in - blocks_to_import.into_iter().zip(events_to_import_aligned.into_iter()) - { - let started = std::time::Instant::now(); - if let Err(e) = self - .validator_accessor - .execute_mut_on_validator(|v| v.submit_block(&signed_block)) - { - error!("[{:?}] Header submission to light client failed for block number {} and hash {:?}: {:?}", id, signed_block.block.header().number(), signed_block.block.hash(), e); - - return Err(e.into()) - } - - // check if we can fast-sync - if let Some(creation_block) = self.shard_creation_info.for_parentchain(id) { - if signed_block.block.header().number < creation_block.number { - trace!( - "fast-syncing block import, ignoring any invocations before block {:}", - creation_block.number - ); - continue - } - } - - let block = signed_block.block; - // Perform state updates. - if let Err(e) = self - .stf_executor - .update_states(block.header(), &self.validator_accessor.parentchain_id()) - { - error!("[{:?}] Error performing state updates upon block import", id); - return Err(e.into()) - } - - // Execute indirect calls that were found in the extrinsics of the block, - // incl. shielding and unshielding. - match self - .indirect_calls_executor - .execute_indirect_calls_in_block(&block, &raw_events) - { - Ok(Some(confirm_processed_parentchain_block_call)) => { - calls.push(confirm_processed_parentchain_block_call); - }, - Ok(None) => trace!("omitting confirmation call to non-integritee parentchain"), - Err(e) => error!("[{:?}] Error executing relevant events: {:?}", id, e), - }; - if let Err(e) = self - .ocall_api - .update_metric(EnclaveMetric::ParentchainBlockImportTime(started.elapsed())) - { - warn!("Failed to update metric for parentchain block import: {:?}", e); - }; - - info!( - "[{:?}] Successfully imported parentchain block (number: {}, hash: {})", - id, - block.header().number, - block.header().hash() - ); - } - - // Create extrinsics for all `unshielding` and `block processed` calls we've gathered. - let parentchain_extrinsics = - self.extrinsics_factory.create_extrinsics(calls.as_slice(), None)?; - - // Sending the extrinsic requires mut access because the validator caches the sent extrinsics internally. - self.validator_accessor - .execute_mut_on_validator(|v| v.send_extrinsics(parentchain_extrinsics))?; - - Ok(()) - } - - fn parentchain_id(&self) -> ParentchainId { - self.validator_accessor.parentchain_id() - } -} diff --git a/tee-worker/bitacross/core/parentchain/block-importer/src/block_importer_mock.rs b/tee-worker/bitacross/core/parentchain/block-importer/src/block_importer_mock.rs deleted file mode 100644 index aae92293e7..0000000000 --- a/tee-worker/bitacross/core/parentchain/block-importer/src/block_importer_mock.rs +++ /dev/null @@ -1,65 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -//! Block importer mock. - -use crate::{ - error::{Error, Result}, - ImportParentchainBlocks, -}; -use itp_types::parentchain::ParentchainId; -use std::{sync::RwLock, vec::Vec}; - -/// Mock implementation for the block importer. -/// -/// Just stores all the blocks that were sent to import internally. -#[derive(Default)] -pub struct ParentchainBlockImporterMock { - imported_blocks: RwLock>, -} - -impl ParentchainBlockImporterMock -where - SignedBlockT: Clone, -{ - pub fn get_all_imported_blocks(&self) -> Vec { - let imported_blocks_lock = self.imported_blocks.read().unwrap(); - (*imported_blocks_lock).clone() - } -} - -impl ImportParentchainBlocks for ParentchainBlockImporterMock -where - SignedBlockT: Clone, -{ - type SignedBlockType = SignedBlockT; - - fn import_parentchain_blocks( - &self, - blocks_to_import: Vec, - _events: Vec>, - ) -> Result<()> { - let mut imported_blocks_lock = self.imported_blocks.write().map_err(|e| { - Error::Other(format!("failed to acquire lock for imported blocks vec: {:?}", e).into()) - })?; - imported_blocks_lock.extend(blocks_to_import); - Ok(()) - } - fn parentchain_id(&self) -> ParentchainId { - ParentchainId::Litentry - } -} diff --git a/tee-worker/bitacross/core/parentchain/block-importer/src/error.rs b/tee-worker/bitacross/core/parentchain/block-importer/src/error.rs deleted file mode 100644 index 856aa84ef2..0000000000 --- a/tee-worker/bitacross/core/parentchain/block-importer/src/error.rs +++ /dev/null @@ -1,51 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -#[cfg(all(not(feature = "std"), feature = "sgx"))] -use crate::sgx_reexport_prelude::*; - -use sgx_types::sgx_status_t; -use std::{boxed::Box, format}; - -pub type Result = core::result::Result; - -/// Parentchain block importer error. -#[derive(Debug, thiserror::Error)] -pub enum Error { - #[error("SGX error, status: {0}")] - Sgx(sgx_status_t), - #[error("Extrinsics factory error: {0}")] - ExtrinsicsFactory(#[from] itp_extrinsics_factory::error::Error), - #[error("STF execution error: {0}")] - StfExecution(#[from] itp_stf_executor::error::Error), - #[error("Light-client error: {0}")] - LightClient(#[from] itc_parentchain_light_client::error::Error), - #[error(transparent)] - Other(#[from] Box), -} - -impl From for Error { - fn from(sgx_status: sgx_status_t) -> Self { - Self::Sgx(sgx_status) - } -} - -impl From for Error { - fn from(e: codec::Error) -> Self { - Self::Other(format!("{:?}", e).into()) - } -} diff --git a/tee-worker/bitacross/core/parentchain/block-importer/src/lib.rs b/tee-worker/bitacross/core/parentchain/block-importer/src/lib.rs deleted file mode 100644 index 3f2fd695bc..0000000000 --- a/tee-worker/bitacross/core/parentchain/block-importer/src/lib.rs +++ /dev/null @@ -1,61 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ -//! Parentchain block importing logic. -#![feature(trait_alias)] -#![cfg_attr(not(feature = "std"), no_std)] - -#[cfg(all(feature = "std", feature = "sgx"))] -compile_error!("feature \"std\" and feature \"sgx\" cannot be enabled at the same time"); - -#[cfg(all(not(feature = "std"), feature = "sgx"))] -extern crate sgx_tstd as std; - -// re-export module to properly feature gate sgx and regular std environment -#[cfg(all(not(feature = "std"), feature = "sgx"))] -pub mod sgx_reexport_prelude { - pub use thiserror_sgx as thiserror; -} - -pub mod block_importer; -pub mod error; - -#[cfg(feature = "mocks")] -pub mod block_importer_mock; - -pub use block_importer::*; - -use error::Result; -use itp_types::parentchain::ParentchainId; -use std::vec::Vec; - -/// Block import from the parentchain. -pub trait ImportParentchainBlocks { - type SignedBlockType: Clone; - - /// Import parentchain blocks to the light-client (validator): - /// * Scans the blocks for relevant extrinsics - /// * Validates and execute those extrinsics, mutating state - /// * Includes block headers into the light client - /// * Sends `PROCESSED_PARENTCHAIN_BLOCK` extrinsics that include the merkle root of all processed calls - fn import_parentchain_blocks( - &self, - blocks_to_import: Vec, - events_to_import: Vec>, - ) -> Result<()>; - - fn parentchain_id(&self) -> ParentchainId; -} diff --git a/tee-worker/bitacross/core/parentchain/indirect-calls-executor/Cargo.toml b/tee-worker/bitacross/core/parentchain/indirect-calls-executor/Cargo.toml deleted file mode 100644 index 9ff5496a13..0000000000 --- a/tee-worker/bitacross/core/parentchain/indirect-calls-executor/Cargo.toml +++ /dev/null @@ -1,88 +0,0 @@ -[package] -name = "bc-itc-parentchain-indirect-calls-executor" -version = "0.1.0" -authors = ['Trust Computing GmbH ', 'Integritee AG '] -edition = "2021" - -[dependencies] -sgx_tstd = { workspace = true, optional = true } -sgx_types = { workspace = true } - -itp-api-client-types = { workspace = true } -itp-node-api = { workspace = true } -itp-sgx-crypto = { workspace = true } -itp-sgx-runtime-primitives = { workspace = true } -itp-stf-executor = { package = "bc-itp-stf-executor", path = "../../../core-primitives/stf-executor", default-features = false } -itp-stf-primitives = { workspace = true } -itp-test = { workspace = true } -itp-top-pool-author = { package = "bc-itp-top-pool-author", path = "../../../core-primitives/top-pool-author", default-features = false } -itp-types = { workspace = true } - -futures_sgx = { workspace = true, optional = true } -thiserror_sgx = { workspace = true, optional = true } - -futures = { workspace = true, optional = true } -thiserror = { workspace = true, optional = true } - -bs58 = { version = "0.4.0", default-features = false, features = ["alloc"] } -codec = { package = "parity-scale-codec", workspace = true } -log = { workspace = true } - -binary-merkle-tree = { workspace = true } -sp-runtime = { workspace = true } - -# litentry -bc-enclave-registry = { path = "../../../bitacross/core/bc-enclave-registry", default-features = false } -bc-relayer-registry = { path = "../../../bitacross/core/bc-relayer-registry", default-features = false } -bc-signer-registry = { path = "../../../bitacross/core/bc-signer-registry", default-features = false } -litentry-primitives = { workspace = true } - -[dev-dependencies] -env_logger = { workspace = true } -itp-node-api = { workspace = true, features = ["std", "mocks"] } -itp-sgx-crypto = { workspace = true, features = ["std", "mocks"] } -itp-stf-executor = { package = "bc-itp-stf-executor", path = "../../../core-primitives/stf-executor", features = ["std", "mocks"] } -itp-test = { workspace = true, features = ["std"] } -itp-top-pool-author = { package = "bc-itp-top-pool-author", path = "../../../core-primitives/top-pool-author", features = ["std", "mocks"] } -itc-parentchain-test = { workspace = true, features = ["std"] } - -[features] -default = ["std"] -std = [ - "bs58/std", - "codec/std", - "futures", - "itp-node-api/std", - "itp-sgx-crypto/std", - "itp-stf-executor/std", - "itp-top-pool-author/std", - "itp-api-client-types/std", - "itp-test/std", - "itp-types/std", - "itp-sgx-runtime-primitives/std", - "log/std", - #substrate - "binary-merkle-tree/std", - "sp-runtime/std", - "thiserror", - # litentry - "litentry-primitives/std", - "bc-relayer-registry/std", - "bc-signer-registry/std", - "bc-enclave-registry/std", -] -sgx = [ - "sgx_tstd", - "futures_sgx", - "itp-node-api/sgx", - "itp-sgx-crypto/sgx", - "itp-stf-executor/sgx", - "itp-top-pool-author/sgx", - "itp-test/sgx", - "thiserror_sgx", - # litentry - "litentry-primitives/sgx", - "bc-relayer-registry/sgx", - "bc-signer-registry/sgx", - "bc-enclave-registry/sgx", -] diff --git a/tee-worker/bitacross/core/parentchain/indirect-calls-executor/src/error.rs b/tee-worker/bitacross/core/parentchain/indirect-calls-executor/src/error.rs deleted file mode 100644 index e1c243507c..0000000000 --- a/tee-worker/bitacross/core/parentchain/indirect-calls-executor/src/error.rs +++ /dev/null @@ -1,81 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -#[cfg(all(not(feature = "std"), feature = "sgx"))] -use crate::sgx_reexport_prelude::*; - -use itp_types::parentchain::ParentchainEventProcessingError; -use sgx_types::sgx_status_t; -use sp_runtime::traits::LookupError; -use std::{boxed::Box, format}; - -pub type Result = core::result::Result; - -/// Indirect calls execution error. -#[derive(Debug, thiserror::Error)] -pub enum Error { - #[error("SGX error, status: {0}")] - Sgx(sgx_status_t), - #[error("STF execution error: {0}")] - StfExecution(#[from] itp_stf_executor::error::Error), - #[error("Node Metadata error: {0:?}")] - NodeMetadata(itp_node_api::metadata::Error), - #[error("Node metadata provider error: {0:?}")] - NodeMetadataProvider(#[from] itp_node_api::metadata::provider::Error), - #[error("Crypto error: {0}")] - Crypto(itp_sgx_crypto::Error), - #[error(transparent)] - Other(#[from] Box), - #[error("AccountId lookup error")] - AccountIdLookup, -} - -impl From for Error { - fn from(e: ParentchainEventProcessingError) -> Self { - Self::Other(format!("{:?}", e).into()) - } -} - -impl From for Error { - fn from(sgx_status: sgx_status_t) -> Self { - Self::Sgx(sgx_status) - } -} - -impl From for Error { - fn from(e: itp_sgx_crypto::Error) -> Self { - Self::Crypto(e) - } -} - -impl From for Error { - fn from(e: codec::Error) -> Self { - Self::Other(format!("{:?}", e).into()) - } -} - -impl From for Error { - fn from(e: itp_node_api::metadata::Error) -> Self { - Self::NodeMetadata(e) - } -} - -impl From for Error { - fn from(_: LookupError) -> Self { - Self::AccountIdLookup - } -} diff --git a/tee-worker/bitacross/core/parentchain/indirect-calls-executor/src/event_filter.rs b/tee-worker/bitacross/core/parentchain/indirect-calls-executor/src/event_filter.rs deleted file mode 100644 index ffb9882f58..0000000000 --- a/tee-worker/bitacross/core/parentchain/indirect-calls-executor/src/event_filter.rs +++ /dev/null @@ -1,33 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ -//! Various way to filter Parentchain events - -use crate::error::Error; - -use itp_stf_primitives::error::StfError; - -use std::format; - -impl From for Error { - fn from(a: StfError) -> Self { - Error::Other(format!("Error when shielding for privacy sidechain {:?}", a).into()) - } -} - -pub trait ToEvents { - fn to_events(&self) -> &E; -} diff --git a/tee-worker/bitacross/core/parentchain/indirect-calls-executor/src/executor.rs b/tee-worker/bitacross/core/parentchain/indirect-calls-executor/src/executor.rs deleted file mode 100644 index 216391bda8..0000000000 --- a/tee-worker/bitacross/core/parentchain/indirect-calls-executor/src/executor.rs +++ /dev/null @@ -1,436 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ -//! Execute indirect calls, i.e. extrinsics extracted from parentchain blocks - -#[cfg(all(not(feature = "std"), feature = "sgx"))] -use crate::sgx_reexport_prelude::*; - -use crate::{ - error::{Error, Result}, - filter_metadata::EventsFromMetadata, - traits::ExecuteIndirectCalls, -}; -use bc_enclave_registry::EnclaveRegistryUpdater; -use bc_relayer_registry::RelayerRegistryUpdater; -use bc_signer_registry::SignerRegistryUpdater; -use binary_merkle_tree::merkle_root; -use codec::{Decode, Encode}; -use core::marker::PhantomData; -use itp_node_api::metadata::{ - pallet_teebag::TeebagCallIndexes, provider::AccessNodeMetadata, NodeMetadataTrait, -}; -use itp_sgx_crypto::{key_repository::AccessKey, ShieldingCryptoDecrypt, ShieldingCryptoEncrypt}; -use itp_stf_executor::traits::StfEnclaveSigning; -use itp_stf_primitives::{ - traits::{IndirectExecutor, TrustedCallSigning, TrustedCallVerification}, - types::AccountId, -}; -use itp_top_pool_author::traits::AuthorApi; -use itp_types::{ - parentchain::{HandleParentchainEvents, ParentchainId}, - MrEnclave, OpaqueCall, RsaRequest, ShardIdentifier, H256, -}; -use log::*; -use sp_runtime::traits::{Block as ParentchainBlockTrait, Header, Keccak256}; -use std::{fmt::Debug, sync::Arc, vec::Vec}; - -pub struct IndirectCallsExecutor< - ShieldingKeyRepository, - StfEnclaveSigner, - TopPoolAuthor, - NodeMetadataProvider, - EventCreator, - ParentchainEventHandler, - TCS, - G, - RRU, - SRU, - ERU, -> where - RRU: RelayerRegistryUpdater, - SRU: SignerRegistryUpdater, - ERU: EnclaveRegistryUpdater, -{ - pub(crate) shielding_key_repo: Arc, - pub stf_enclave_signer: Arc, - pub(crate) top_pool_author: Arc, - pub(crate) node_meta_data_provider: Arc, - pub parentchain_id: ParentchainId, - parentchain_event_handler: ParentchainEventHandler, - pub relayer_registry_updater: Arc, - pub signer_registry_updater: Arc, - pub enclave_registry_updater: Arc, - _phantom: PhantomData<(EventCreator, ParentchainEventHandler, TCS, G)>, -} -impl< - ShieldingKeyRepository, - StfEnclaveSigner, - TopPoolAuthor, - NodeMetadataProvider, - EventCreator, - ParentchainEventHandler, - TCS, - G, - RRU, - SRU, - ERU, - > - IndirectCallsExecutor< - ShieldingKeyRepository, - StfEnclaveSigner, - TopPoolAuthor, - NodeMetadataProvider, - EventCreator, - ParentchainEventHandler, - TCS, - G, - RRU, - SRU, - ERU, - > where - RRU: RelayerRegistryUpdater, - SRU: SignerRegistryUpdater, - ERU: EnclaveRegistryUpdater, -{ - #[allow(clippy::too_many_arguments)] - pub fn new( - shielding_key_repo: Arc, - stf_enclave_signer: Arc, - top_pool_author: Arc, - node_meta_data_provider: Arc, - parentchain_id: ParentchainId, - parentchain_event_handler: ParentchainEventHandler, - relayer_registry_updater: Arc, - signer_registry_updater: Arc, - enclave_registry_updater: Arc, - ) -> Self { - IndirectCallsExecutor { - shielding_key_repo, - stf_enclave_signer, - top_pool_author, - node_meta_data_provider, - parentchain_id, - parentchain_event_handler, - relayer_registry_updater, - signer_registry_updater, - enclave_registry_updater, - _phantom: Default::default(), - } - } -} - -impl< - ShieldingKeyRepository, - StfEnclaveSigner, - TopPoolAuthor, - NodeMetadataProvider, - EventCreator, - ParentchainEventHandler, - TCS, - G, - RRU, - SRU, - ERU, - > ExecuteIndirectCalls - for IndirectCallsExecutor< - ShieldingKeyRepository, - StfEnclaveSigner, - TopPoolAuthor, - NodeMetadataProvider, - EventCreator, - ParentchainEventHandler, - TCS, - G, - RRU, - SRU, - ERU, - > where - ShieldingKeyRepository: AccessKey, - ::KeyType: ShieldingCryptoDecrypt - + ShieldingCryptoEncrypt, - StfEnclaveSigner: StfEnclaveSigning, - TopPoolAuthor: AuthorApi + Send + Sync + 'static, - NodeMetadataProvider: AccessNodeMetadata, - NodeMetadataProvider::MetadataType: NodeMetadataTrait + Clone, - EventCreator: EventsFromMetadata, - ParentchainEventHandler: - HandleParentchainEvents>, - TCS: PartialEq + Encode + Decode + Debug + Clone + Send + Sync + TrustedCallVerification, - G: PartialEq + Encode + Decode + Debug + Clone + Send + Sync, - RRU: RelayerRegistryUpdater, - SRU: SignerRegistryUpdater, - ERU: EnclaveRegistryUpdater, -{ - fn execute_indirect_calls_in_block( - &self, - block: &ParentchainBlock, - events: &[u8], - ) -> Result> - where - ParentchainBlock: ParentchainBlockTrait, - { - let block_number = *block.header().number(); - let block_hash = block.hash(); - - trace!("Scanning block {:?} for relevant events", block_number); - - let events = self - .node_meta_data_provider - .get_from_metadata(|metadata| { - EventCreator::create_from_metadata(metadata.clone(), block_hash, events) - })? - .ok_or_else(|| Error::Other("Could not create events from metadata".into()))?; - - let processed_events = self.parentchain_event_handler.handle_events::( - self, - events, - block_number, - )?; - - if self.parentchain_id == ParentchainId::Litentry { - // Include a processed parentchain block confirmation for each block. - Ok(Some(self.create_processed_parentchain_block_call::( - block_hash, - processed_events, - block_number, - )?)) - } else { - // fixme: send other type of confirmation here: https://github.com/integritee-network/worker/issues/1567 - Ok(None) - } - } - - fn create_processed_parentchain_block_call( - &self, - block_hash: H256, - events: Vec, - block_number: <::Header as Header>::Number, - ) -> Result - where - ParentchainBlock: ParentchainBlockTrait, - { - let call = self.node_meta_data_provider.get_from_metadata(|meta_data| { - meta_data.parentchain_block_processed_call_indexes() - })??; - let root: H256 = merkle_root::(events); - trace!("prepared parentchain_block_processed() call for block {:?} with index {:?} and merkle root {}", block_number, call, root); - // Litentry: we don't include `shard` in the extrinsic parameter to be backwards compatible, - // however, we should not forget it in case we need it later - Ok(OpaqueCall::from_tuple(&(call, block_hash, block_number, root))) - } -} - -impl< - ShieldingKeyRepository, - StfEnclaveSigner, - TopPoolAuthor, - NodeMetadataProvider, - EventFilter, - PrivacySidechain, - TCS, - G, - RRU, - SRU, - ERU, - > IndirectExecutor - for IndirectCallsExecutor< - ShieldingKeyRepository, - StfEnclaveSigner, - TopPoolAuthor, - NodeMetadataProvider, - EventFilter, - PrivacySidechain, - TCS, - G, - RRU, - SRU, - ERU, - > where - ShieldingKeyRepository: AccessKey, - ::KeyType: ShieldingCryptoDecrypt - + ShieldingCryptoEncrypt, - StfEnclaveSigner: StfEnclaveSigning, - TopPoolAuthor: AuthorApi + Send + Sync + 'static, - TCS: PartialEq + Encode + Decode + Debug + Clone + Send + Sync + TrustedCallVerification, - G: PartialEq + Encode + Decode + Debug + Clone + Send + Sync, - RRU: RelayerRegistryUpdater, - SRU: SignerRegistryUpdater, - ERU: EnclaveRegistryUpdater, -{ - fn submit_trusted_call(&self, shard: ShardIdentifier, encrypted_trusted_call: Vec) { - if let Err(e) = futures::executor::block_on( - self.top_pool_author.submit_top(RsaRequest::new(shard, encrypted_trusted_call)), - ) { - error!("Error adding indirect trusted call to TOP pool: {:?}", e); - } - } - - fn decrypt(&self, encrypted: &[u8]) -> Result> { - let key = self.shielding_key_repo.retrieve_key()?; - Ok(key.decrypt(encrypted)?) - } - - fn encrypt(&self, value: &[u8]) -> Result> { - let key = self.shielding_key_repo.retrieve_key()?; - Ok(key.encrypt(value)?) - } - - fn get_enclave_account(&self) -> Result { - Ok(self.stf_enclave_signer.get_enclave_account()?) - } - - fn get_mrenclave(&self) -> Result { - Ok(self.stf_enclave_signer.get_mrenclave()?) - } - - fn get_default_shard(&self) -> ShardIdentifier { - self.top_pool_author.list_handled_shards().first().copied().unwrap_or_default() - } - - fn sign_call_with_self>( - &self, - trusted_call: &TC, - shard: &ShardIdentifier, - ) -> Result { - Ok(self.stf_enclave_signer.sign_call_with_self(trusted_call, shard)?) - } - - fn get_relayer_registry_updater(&self) -> &RRU { - self.relayer_registry_updater.as_ref() - } - - fn get_signer_registry_updater(&self) -> &SRU { - self.signer_registry_updater.as_ref() - } - - fn get_enclave_registry_updater(&self) -> &ERU { - self.enclave_registry_updater.as_ref() - } -} - -#[cfg(test)] -mod test { - use super::*; - use crate::mock::*; - use bc_enclave_registry::EnclaveRegistry; - use bc_relayer_registry::RelayerRegistry; - use bc_signer_registry::SignerRegistry; - use codec::Encode; - - use itp_node_api::metadata::{ - metadata_mocks::NodeMetadataMock, provider::NodeMetadataRepository, - }; - use itp_sgx_crypto::mocks::KeyRepositoryMock; - use itp_stf_executor::mocks::StfEnclaveSignerMock; - use itp_test::mock::{ - shielding_crypto_mock::ShieldingCryptoMock, - stf_mock::{GetterMock, TrustedCallSignedMock}, - }; - use itp_top_pool_author::mocks::AuthorApiMock; - use itp_types::Block; - - type TestShieldingKeyRepo = KeyRepositoryMock; - type TestStfEnclaveSigner = StfEnclaveSignerMock; - type TestTopPoolAuthor = AuthorApiMock; - type TestNodeMetadataRepository = NodeMetadataRepository; - type TestIndirectCallExecutor = IndirectCallsExecutor< - TestShieldingKeyRepo, - TestStfEnclaveSigner, - TestTopPoolAuthor, - TestNodeMetadataRepository, - TestEventCreator, - MockParentchainEventHandler, - TrustedCallSignedMock, - GetterMock, - RelayerRegistry, - SignerRegistry, - EnclaveRegistry, - >; - - #[test] - fn ensure_empty_events_vec_triggers_zero_filled_merkle_root() { - // given - let dummy_metadata = NodeMetadataMock::new(); - let (indirect_calls_executor, _, _) = test_fixtures([38u8; 32], dummy_metadata.clone()); - - let block_hash = H256::from([1; 32]); - let events = Vec::new(); - let parentchain_block_processed_call_indexes = - dummy_metadata.parentchain_block_processed_call_indexes().unwrap(); - let expected_call = - (parentchain_block_processed_call_indexes, block_hash, 1u32, H256::default()).encode(); - - // when - let call = indirect_calls_executor - .create_processed_parentchain_block_call::(block_hash, events, 1u32) - .unwrap(); - - // then - assert_eq!(call.0, expected_call); - } - - #[test] - fn ensure_non_empty_events_vec_triggers_non_zero_merkle_root() { - // given - let dummy_metadata = NodeMetadataMock::new(); - let (indirect_calls_executor, _, _) = test_fixtures([39u8; 32], dummy_metadata.clone()); - - let block_hash = H256::from([1; 32]); - let events = vec![H256::from([4; 32]), H256::from([9; 32])]; - let parentchain_block_processed_call_indexes = - dummy_metadata.parentchain_block_processed_call_indexes().unwrap(); - - let zero_root_call = - (parentchain_block_processed_call_indexes, block_hash, 1u32, H256::default()).encode(); - - // when - let call = indirect_calls_executor - .create_processed_parentchain_block_call::(block_hash, events, 1u32) - .unwrap(); - - // then - assert_ne!(call.0, zero_root_call); - } - - fn test_fixtures( - mr_enclave: [u8; 32], - metadata: NodeMetadataMock, - ) -> (TestIndirectCallExecutor, Arc, Arc) { - let shielding_key_repo = Arc::new(TestShieldingKeyRepo::default()); - let stf_enclave_signer = Arc::new(TestStfEnclaveSigner::new(mr_enclave)); - let top_pool_author = Arc::new(TestTopPoolAuthor::default()); - let node_metadata_repo = Arc::new(NodeMetadataRepository::new(metadata)); - let parentchain_event_handler = MockParentchainEventHandler {}; - let relayer_registry = Arc::new(RelayerRegistry::new(Default::default())); - let signer_registry = Arc::new(SignerRegistry::new(Default::default())); - let enclave_registry = Arc::new(EnclaveRegistry::new(Default::default())); - - let executor = IndirectCallsExecutor::new( - shielding_key_repo.clone(), - stf_enclave_signer, - top_pool_author.clone(), - node_metadata_repo, - ParentchainId::Litentry, - parentchain_event_handler, - relayer_registry, - signer_registry, - enclave_registry, - ); - - (executor, top_pool_author, shielding_key_repo) - } -} diff --git a/tee-worker/bitacross/core/parentchain/indirect-calls-executor/src/filter_metadata.rs b/tee-worker/bitacross/core/parentchain/indirect-calls-executor/src/filter_metadata.rs deleted file mode 100644 index 25edc70ed7..0000000000 --- a/tee-worker/bitacross/core/parentchain/indirect-calls-executor/src/filter_metadata.rs +++ /dev/null @@ -1,118 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use crate::{error::Result, IndirectDispatch}; -use codec::{Decode, Encode}; -use core::marker::PhantomData; -use itp_api_client_types::{Events, Metadata}; -use itp_node_api::metadata::NodeMetadata; -use itp_stf_primitives::traits::IndirectExecutor; -use itp_types::{parentchain::FilterEvents, H256}; - -pub trait EventsFromMetadata { - type Output: FilterEvents; - - fn create_from_metadata( - metadata: NodeMetadata, - block_hash: H256, - events: &[u8], - ) -> Option; -} - -pub struct EventCreator { - _phantom: PhantomData, -} - -impl + Clone, FilterableEvents> EventsFromMetadata - for EventCreator -where - FilterableEvents: From> + FilterEvents, -{ - type Output = FilterableEvents; - - fn create_from_metadata( - metadata: NodeMetadata, - block_hash: H256, - events: &[u8], - ) -> Option { - let raw_metadata: Metadata = metadata.try_into().ok()?; - Some(Events::::new(raw_metadata, block_hash, events.to_vec()).into()) - } -} - -/// Trait to filter an indirect call and decode into it, where the decoding -/// is based on the metadata provided. -pub trait FilterIntoDataFrom { - /// Type to decode into. - type Output; - - /// Knows how to parse the parentchain metadata. - type ParseParentchainMetadata; - - /// Filters some bytes and returns `Some(Self::Output)` if the filter matches some criteria. - fn filter_into_from_metadata( - encoded_data: &[u8], - metadata: &NodeMetadata, - ) -> Option; -} - -/// Indirect calls filter denying all indirect calls. -pub struct DenyAll; - -mod seal { - use super::*; - use crate::Error; - use bc_enclave_registry::EnclaveRegistry; - use bc_relayer_registry::RelayerRegistry; - use bc_signer_registry::SignerRegistry; - use core::fmt::Debug; - use itp_stf_primitives::traits::TrustedCallVerification; - - /// Stub struct for the `DenyAll` filter that never executes anything. - #[derive(Debug, Encode)] - pub struct CantExecute; - - impl FilterIntoDataFrom for DenyAll { - type Output = CantExecute; - type ParseParentchainMetadata = (); - - fn filter_into_from_metadata(_: &[u8], _: &NodeMetadata) -> Option { - None - } - } - - impl< - Executor: IndirectExecutor, - TCS, - > IndirectDispatch for CantExecute - where - TCS: PartialEq + Encode + Decode + Debug + Clone + Send + Sync + TrustedCallVerification, - { - type Args = (); - fn dispatch(&self, _: &Executor, _args: Self::Args) -> Result<()> { - // We should never get here because `CantExecute` is in a private module and the trait - // implementation is sealed and always returns `None` instead of a `CantExecute` instance. - // Regardless, we never want the enclave to panic, this is why we take this extra safety - // measure. - log::warn!( - "Executed indirect dispatch for 'CantExecute'\ - this means there is some logic error." - ); - Ok(()) - } - } -} diff --git a/tee-worker/bitacross/core/parentchain/indirect-calls-executor/src/lib.rs b/tee-worker/bitacross/core/parentchain/indirect-calls-executor/src/lib.rs deleted file mode 100644 index 57b0911e87..0000000000 --- a/tee-worker/bitacross/core/parentchain/indirect-calls-executor/src/lib.rs +++ /dev/null @@ -1,52 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ -//! Execute indirect calls, i.e. extrinsics extracted from parentchain blocks. -//! -//! The core struct of this crate is the [IndirectCallsExecutor] executor. It scans parentchain -//! blocks for relevant extrinsics, derives an indirect call for those and dispatches the -//! indirect call. - -#![feature(trait_alias)] -#![cfg_attr(not(feature = "std"), no_std)] -#![cfg_attr(test, feature(assert_matches))] - -#[cfg(all(feature = "std", feature = "sgx"))] -compile_error!("feature \"std\" and feature \"sgx\" cannot be enabled at the same time"); - -extern crate alloc; - -#[cfg(all(not(feature = "std"), feature = "sgx"))] -extern crate sgx_tstd as std; - -// re-export module to properly feature gate sgx and regular std environment -#[cfg(all(not(feature = "std"), feature = "sgx"))] -pub mod sgx_reexport_prelude { - pub use futures_sgx as futures; - pub use thiserror_sgx as thiserror; -} - -mod executor; -pub mod mock; -pub mod traits; - -pub mod error; -pub mod event_filter; -pub mod filter_metadata; - -pub use error::{Error, Result}; -pub use executor::IndirectCallsExecutor; -pub use traits::{ExecuteIndirectCalls, IndirectDispatch}; diff --git a/tee-worker/bitacross/core/parentchain/indirect-calls-executor/src/mock.rs b/tee-worker/bitacross/core/parentchain/indirect-calls-executor/src/mock.rs deleted file mode 100644 index 7b17d920fb..0000000000 --- a/tee-worker/bitacross/core/parentchain/indirect-calls-executor/src/mock.rs +++ /dev/null @@ -1,317 +0,0 @@ -use crate::{ - error::{Error, Result as ICResult}, - filter_metadata::EventsFromMetadata, - IndirectDispatch, -}; -use bc_relayer_registry::RelayerRegistry; -use bc_signer_registry::SignerRegistry; -use codec::{Decode, Encode}; -use core::marker::PhantomData; -use litentry_primitives::DecryptableRequest; - -use bc_enclave_registry::EnclaveRegistry; -use itp_node_api::api_client::{CallIndex, PairSignature, UncheckedExtrinsicV4}; -use itp_sgx_runtime_primitives::types::{AccountId, Balance}; -use itp_stf_primitives::{traits::IndirectExecutor, types::Signature}; -use itp_test::mock::stf_mock::{GetterMock, TrustedCallMock, TrustedCallSignedMock}; -use itp_types::{ - parentchain::{events::*, FilterEvents, HandleParentchainEvents}, - Address, RsaRequest, ShardIdentifier, H256, -}; -use log::*; -use sp_runtime::traits::{Block as ParentchainBlock, Header as ParentchainHeader}; -use std::vec::Vec; - -pub struct ExtrinsicParser { - _phantom: PhantomData, -} -use itp_api_client_types::ParentchainSignedExtra; -use itp_stf_primitives::types::TrustedOperation; - -/// Parses the extrinsics corresponding to the parentchain. -pub type MockParentchainExtrinsicParser = ExtrinsicParser; - -/// Partially interpreted extrinsic containing the `signature` and the `call_index` whereas -/// the `call_args` remain in encoded form. -/// -/// Intended for usage, where the actual `call_args` form is unknown. -pub struct SemiOpaqueExtrinsic<'a> { - /// Signature of the Extrinsic. - pub signature: Signature, - /// Call index of the dispatchable. - pub call_index: CallIndex, - /// Encoded arguments of the dispatchable corresponding to the `call_index`. - pub call_args: &'a [u8], -} - -/// Trait to extract signature and call indexes of an encoded [UncheckedExtrinsicV4]. -pub trait ParseExtrinsic { - /// Signed extra of the extrinsic. - type SignedExtra; - - fn parse(encoded_call: &[u8]) -> Result; -} - -impl ParseExtrinsic for ExtrinsicParser -where - SignedExtra: Decode + Encode, -{ - type SignedExtra = SignedExtra; - - /// Extract a call index of an encoded call. - fn parse(encoded_call: &[u8]) -> Result { - let call_mut = &mut &encoded_call[..]; - - // `()` is a trick to stop decoding after the call index. So the remaining bytes - // of `call` after decoding only contain the parentchain's dispatchable's arguments. - let xt = UncheckedExtrinsicV4::< - Address, - (CallIndex, ()), - PairSignature, - Self::SignedExtra, - >::decode(call_mut)?; - - Ok(SemiOpaqueExtrinsic { - signature: xt.signature.unwrap().1, - call_index: xt.function.0, - call_args: call_mut, - }) - } -} -/// The default indirect call (extrinsic-triggered) of the Integritee-Parachain. -#[derive(Debug, Clone, Encode, Decode, Eq, PartialEq)] -pub enum IndirectCall { - ShieldFunds(ShieldFundsArgs), - Invoke(InvokeArgs), -} - -impl< - Executor: IndirectExecutor< - TrustedCallSignedMock, - Error, - RelayerRegistry, - SignerRegistry, - EnclaveRegistry, - >, - > - IndirectDispatch< - Executor, - TrustedCallSignedMock, - RelayerRegistry, - SignerRegistry, - EnclaveRegistry, - > for IndirectCall -{ - type Args = (); - fn dispatch(&self, executor: &Executor, args: Self::Args) -> ICResult<()> { - trace!("dispatching indirect call {:?}", self); - match self { - IndirectCall::ShieldFunds(shieldfunds_args) => - shieldfunds_args.dispatch(executor, args), - IndirectCall::Invoke(invoke_args) => invoke_args.dispatch(executor, args), - } - } -} - -pub struct TestEventCreator; - -impl EventsFromMetadata for TestEventCreator { - type Output = MockEvents; - - fn create_from_metadata( - _metadata: NodeMetadata, - _block_hash: H256, - _events: &[u8], - ) -> Option { - Some(MockEvents) - } -} - -pub struct MockEvents; - -impl FilterEvents for MockEvents { - type Error = (); - - fn get_link_identity_events(&self) -> Result, Self::Error> { - Ok(Vec::new()) - } - - fn get_vc_requested_events(&self) -> Result, Self::Error> { - Ok(Vec::new()) - } - - fn get_deactivate_identity_events( - &self, - ) -> Result, Self::Error> { - Ok(Vec::new()) - } - - fn get_activate_identity_events(&self) -> Result, Self::Error> { - Ok(Vec::new()) - } - - fn get_enclave_unauthorized_events(&self) -> Result, Self::Error> { - Ok(Vec::new()) - } - - fn get_opaque_task_posted_events(&self) -> Result, Self::Error> { - Ok(Vec::new()) - } - - fn get_assertion_created_events(&self) -> Result, Self::Error> { - Ok(Vec::new()) - } - - fn get_parentchain_block_proccessed_events( - &self, - ) -> Result, Self::Error> { - Ok(Vec::new()) - } - - fn get_relayer_added_events( - &self, - ) -> Result, Self::Error> { - Ok(Vec::new()) - } - - fn get_relayers_removed_events( - &self, - ) -> Result, Self::Error> { - Ok(Vec::new()) - } - - fn get_enclave_added_events( - &self, - ) -> Result, Self::Error> { - Ok(Vec::new()) - } - - fn get_enclave_removed_events( - &self, - ) -> Result, Self::Error> { - Ok(Vec::new()) - } - - fn get_btc_wallet_generated_events( - &self, - ) -> Result, Self::Error> { - Ok(Vec::new()) - } - - fn get_account_store_updated_events(&self) -> Result, Self::Error> { - Ok(Vec::new()) - } -} - -pub struct MockParentchainEventHandler {} - -impl - HandleParentchainEvents< - Executor, - TrustedCallSignedMock, - Error, - RelayerRegistry, - SignerRegistry, - EnclaveRegistry, - > for MockParentchainEventHandler -where - Executor: IndirectExecutor< - TrustedCallSignedMock, - Error, - RelayerRegistry, - SignerRegistry, - EnclaveRegistry, - >, -{ - type Output = Vec; - - fn handle_events( - &self, - _: &Executor, - _: impl itp_types::parentchain::FilterEvents, - _block_number: <::Header as ParentchainHeader>::Number, - ) -> core::result::Result, Error> - where - Block: ParentchainBlock, - { - Ok(Vec::from([H256::default()])) - } -} - -/// Arguments of the Integritee-Parachain's shield fund dispatchable. -#[derive(Debug, Clone, Encode, Decode, Eq, PartialEq)] -pub struct ShieldFundsArgs { - account_encrypted: Vec, - amount: Balance, - shard: ShardIdentifier, -} - -impl< - Executor: IndirectExecutor< - TrustedCallSignedMock, - Error, - RelayerRegistry, - SignerRegistry, - EnclaveRegistry, - >, - > - IndirectDispatch< - Executor, - TrustedCallSignedMock, - RelayerRegistry, - SignerRegistry, - EnclaveRegistry, - > for ShieldFundsArgs -{ - type Args = (); - fn dispatch(&self, executor: &Executor, _args: Self::Args) -> ICResult<()> { - info!("Found ShieldFunds extrinsic in block: \nAccount Encrypted {:?} \nAmount: {} \nShard: {}", - self.account_encrypted, self.amount, bs58::encode(self.shard.encode()).into_string()); - - debug!("decrypt the account id"); - let account_vec = executor.decrypt(&self.account_encrypted)?; - let _account = AccountId::decode(&mut account_vec.as_slice())?; - - let enclave_account_id = executor.get_enclave_account()?; - let trusted_call = TrustedCallMock::noop(enclave_account_id.into()); - let signed_trusted_call = executor.sign_call_with_self(&trusted_call, &self.shard)?; - let trusted_operation = - TrustedOperation::::indirect_call( - signed_trusted_call, - ); - - let encrypted_trusted_call = executor.encrypt(&trusted_operation.encode())?; - executor.submit_trusted_call(self.shard, encrypted_trusted_call); - Ok(()) - } -} - -#[derive(Debug, Clone, Encode, Decode, Eq, PartialEq)] -pub struct InvokeArgs { - request: RsaRequest, -} - -impl< - Executor: IndirectExecutor< - TrustedCallSignedMock, - Error, - RelayerRegistry, - SignerRegistry, - EnclaveRegistry, - >, - > - IndirectDispatch< - Executor, - TrustedCallSignedMock, - RelayerRegistry, - SignerRegistry, - EnclaveRegistry, - > for InvokeArgs -{ - type Args = (); - fn dispatch(&self, executor: &Executor, _args: Self::Args) -> ICResult<()> { - log::debug!("Found trusted call extrinsic, submitting it to the top pool"); - executor.submit_trusted_call(self.request.shard(), self.request.payload().to_vec()); - Ok(()) - } -} diff --git a/tee-worker/bitacross/core/parentchain/indirect-calls-executor/src/traits.rs b/tee-worker/bitacross/core/parentchain/indirect-calls-executor/src/traits.rs deleted file mode 100644 index e2a5c04f17..0000000000 --- a/tee-worker/bitacross/core/parentchain/indirect-calls-executor/src/traits.rs +++ /dev/null @@ -1,65 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use crate::{error::Result, Error}; -use bc_enclave_registry::EnclaveRegistryUpdater; -use bc_relayer_registry::RelayerRegistryUpdater; -use bc_signer_registry::SignerRegistryUpdater; -use codec::{Decode, Encode}; -use core::fmt::Debug; -use itp_stf_primitives::traits::{IndirectExecutor, TrustedCallVerification}; -use itp_types::{OpaqueCall, H256}; -use sp_runtime::traits::{Block as ParentchainBlockTrait, Header}; -use std::vec::Vec; - -/// Trait to execute the indirect calls found in the extrinsics of a block. -pub trait ExecuteIndirectCalls { - /// Scans blocks for extrinsics that ask the enclave to execute some actions. - /// Executes indirect invocation calls, including shielding and unshielding calls. - /// Returns all unshielding call confirmations as opaque calls and the hashes of executed shielding calls. - fn execute_indirect_calls_in_block( - &self, - block: &ParentchainBlock, - events: &[u8], - ) -> Result> - where - ParentchainBlock: ParentchainBlockTrait; - - /// Creates a processed_parentchain_block extrinsic for a given parentchain block hash and the merkle executed extrinsics. - /// - /// Calculates the merkle root of the extrinsics. In case no extrinsics are supplied, the root will be a hash filled with zeros. - fn create_processed_parentchain_block_call( - &self, - block_hash: H256, - extrinsics: Vec, - block_number: <::Header as Header>::Number, - ) -> Result - where - ParentchainBlock: ParentchainBlockTrait; -} - -/// Trait that should be implemented on indirect calls to be executed. -pub trait IndirectDispatch, TCS, RRU, SRU, ERU> -where - TCS: PartialEq + Encode + Decode + Debug + Clone + Send + Sync + TrustedCallVerification, - RRU: RelayerRegistryUpdater, - SRU: SignerRegistryUpdater, - ERU: EnclaveRegistryUpdater, -{ - type Args; - fn dispatch(&self, executor: &E, args: Self::Args) -> Result<()>; -} diff --git a/tee-worker/bitacross/core/parentchain/parentchain-crate/Cargo.toml b/tee-worker/bitacross/core/parentchain/parentchain-crate/Cargo.toml deleted file mode 100644 index 1f2146be92..0000000000 --- a/tee-worker/bitacross/core/parentchain/parentchain-crate/Cargo.toml +++ /dev/null @@ -1,42 +0,0 @@ -[package] -name = "bc-itc-parentchain" -version = "0.1.0" -authors = ['Trust Computing GmbH ', 'Integritee AG '] -edition = "2021" - -[dependencies] -codec = { package = "parity-scale-codec", workspace = true, features = ["chain-error"] } - -sp-runtime = { workspace = true } - -itc-parentchain-block-import-dispatcher = { package = "bc-itc-parentchain-block-import-dispatcher", path = "../block-import-dispatcher", default-features = false } -itc-parentchain-block-importer = { package = "bc-itc-parentchain-block-importer", path = "../block-importer", default-features = false } -itc-parentchain-indirect-calls-executor = { package = "bc-itc-parentchain-indirect-calls-executor", path = "../indirect-calls-executor", default-features = false } -itc-parentchain-light-client = { workspace = true } -itp-types = { workspace = true } - -[features] -default = ["std"] -std = [ - "codec/std", - "sp-runtime/std", - "itc-parentchain-block-import-dispatcher/std", - "itc-parentchain-block-importer/std", - "itc-parentchain-indirect-calls-executor/std", - "itc-parentchain-light-client/std", - "itp-types/std", -] -sgx = [ - "itc-parentchain-block-import-dispatcher/sgx", - "itc-parentchain-block-importer/sgx", - "itc-parentchain-indirect-calls-executor/sgx", - "itc-parentchain-light-client/sgx", -] -mocks = [ - "itc-parentchain-block-import-dispatcher/mocks", - "itc-parentchain-light-client/mocks", -] -test = [ - "mocks", - "itc-parentchain-light-client/test", -] diff --git a/tee-worker/bitacross/core/parentchain/parentchain-crate/src/lib.rs b/tee-worker/bitacross/core/parentchain/parentchain-crate/src/lib.rs deleted file mode 100644 index d9e4e07f55..0000000000 --- a/tee-worker/bitacross/core/parentchain/parentchain-crate/src/lib.rs +++ /dev/null @@ -1,31 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -//! Reexport all the parentchain components in one crate - -#![cfg_attr(not(feature = "std"), no_std)] - -#[cfg(all(feature = "std", feature = "sgx"))] -compile_error!("feature \"std\" and feature \"sgx\" cannot be enabled at the same time"); - -pub use itc_parentchain_block_import_dispatcher as block_import_dispatcher; - -pub use itc_parentchain_block_importer as block_importer; - -pub use itc_parentchain_indirect_calls_executor as indirect_calls_executor; - -pub use itc_parentchain_light_client as light_client; diff --git a/tee-worker/bitacross/docker/README.md b/tee-worker/bitacross/docker/README.md deleted file mode 100644 index 09ee9bb415..0000000000 --- a/tee-worker/bitacross/docker/README.md +++ /dev/null @@ -1,106 +0,0 @@ -# How to run the multi-validateer docker setup - -## Prerequisite - -* Make sure you have installed Docker (version >= `2.0.0`) with [Docker Compose](https://docs.docker.com/compose/install/). On Windows, this can be Docker Desktop with WSL 2 integration. -* In case you also build the worker directly, without docker (e.g. on a dev machine, running `make`), you should run `make clean` before running the docker build. Otherwise, it can occasionally lead to build errors. -* The node image version that is loaded in the `docker-compose.yml`, (e.g. `image: "integritee/integritee-node:1.1.3"`) needs to be compatible with the worker you're trying to build. -* Set export VERSION=dev -* `envsubst` should be installed, it is needed to replace the $VERSION in yaml files as docker compose doesn't support variables on service names. - -## Building the Docker containers - -Run -``` -COMPOSE_DOCKER_CLI_BUILD=1 DOCKER_BUILDKIT=1 docker compose -f <(envsubst < docker-compose.yml) build -``` -in this folder to build the worker image. This will build the worker from source and tag it in an image called `integritee-worker:dev`. - -## Running the docker setup - -``` -docker compose -f <(envsubst < docker-compose.yml) up -``` -Starts all services (node and workers), using the `integritee-worker:dev` images you've built in the previous step. - -## Run the demos - -### Demo indirect invocation (M6) -Build -``` -COMPOSE_DOCKER_CLI_BUILD=1 DOCKER_BUILDKIT=1 docker compose -f <(envsubst < docker-compose.yml) -f <(envsubst < demo-shielding-unshielding-multiworker.yml) build --build-arg WORKER_MODE_ARG=offchain-worker -``` -Run -``` -FLAVOR_ID=offchain-worker docker compose -f <(envsubst < docker-compose.yml) -f <(envsubst < demo-shielding-unshielding-multiworker.yml) up demo-shielding-unshielding-multiworker --exit-code-from demo-shielding-unshielding-multiworker -``` -### Demo direct call (M8) - -Build -``` -COMPOSE_DOCKER_CLI_BUILD=1 DOCKER_BUILDKIT=1 docker compose -f <(envsubst < docker-compose.yml) -f <(envsubst < demo-direct-call.yml) build --build-arg WORKER_MODE_ARG=sidechain -``` -Run -``` -docker compose -f <(envsubst < docker-compose.yml) -f <(envsubst < demo-direct-call.yml) up demo-direct-call --exit-code-from demo-direct-call -``` - -### Demo sidechain -Build -``` -COMPOSE_DOCKER_CLI_BUILD=1 DOCKER_BUILDKIT=1 docker compose -f <(envsubst < docker-compose.yml) -f <(envsubst < demo-sidechain.yml) build --build-arg WORKER_MODE_ARG=sidechain -``` -Run -``` -docker compose -f <(envsubst < docker-compose.yml) -f <(envsubst < demo-sidechain.yml) up demo-sidechain --exit-code-from demo-sidechain -``` - - -## Run the benchmarks -Build with -``` -COMPOSE_DOCKER_CLI_BUILD=1 DOCKER_BUILDKIT=1 docker compose -f <(envsubst < docker-compose.yml) -f <(envsubst < sidechain-benchmark.yml) build -``` -and then run with -``` -docker compose -f <(envsubst < docker-compose.yml) -f <(envsubst < sidechain-benchmark.yml) up sidechain-benchmark --exit-code-from sidechain-benchmark -``` - -## Run the fork simulator -The fork simulation uses `pumba` which in turn uses the Linux traffic control (TC). This is only available on Linux hosts, not on Windows with WSL unfortunately. -Build the docker compose setup with -``` -COMPOSE_DOCKER_CLI_BUILD=1 DOCKER_BUILDKIT=1 docker compose -f <(envsubst < docker-compose.yml) -f <(envsubst < fork-inducer.yml) -f <(envsubst < demo-sidechain.yml) build --build-arg WORKER_MODE_ARG=sidechain -``` - -This requires the docker BuildKit (docker version >= 18.09) and support for it in docker compose (version >= 1.25.0) - -Run the 2-worker setup with a fork inducer (pumba) that delays the traffic on worker 2 -``` -docker compose -f <(envsubst < docker-compose.yml) -f <(envsubst < fork-inducer.yml) -f <(envsubst < integration-test.yml) up --exit-code-from demo-sidechain -``` - -This should show that the integration test fails, because we had an unhandled fork in the sidechain. Clean up the containers after each run with: -``` -docker compose -f <(envsubst < docker-compose.yml) -f <(envsubst < fork-inducer.yml) -f <(envsubst < demo-sidechain.yml) down -``` - -We need these different compose files to separate the services that we're using. E.g. we want the integration test and fork simulator to be optional. The same could be solved using `profiles` - but that requires a more up-to-date version of `docker compose`. - -## FAQ -### What do I have to do to stop everything properly? -With `Ctrl-C` you stop the containers and with `docker compose down` you clean up/remove the containers. Note that `docker compose down` will also remove any logs docker has saved, since it will remove all the container context. - -### What do I have to do if I make changes to the code? -You need to re-build the worker image, using `docker compose build`. - -### How can I change the log level? -You can change the environment variable `RUST_LOG=` in the `docker-compose.yml` for each worker individually. - -### The log from the node are quite a nuisance. Why are they all together. -You can suppress the log output for a container by setting the logging driver. This can be set to either `none` (completely disables all logs), or `local` (docker will record the logs, depending on your docker compose version, it will also log to `stdout`) in the `docker-compose.yml`: -``` -logging: - driver: local -``` -Mind the indent. Explanations for all the logging drivers in `docker compose` can be found [here](https://docs.docker.com/config/containers/logging/local/). diff --git a/tee-worker/bitacross/docker/docker-compose.yml b/tee-worker/bitacross/docker/docker-compose.yml deleted file mode 100644 index 87ed9b1292..0000000000 --- a/tee-worker/bitacross/docker/docker-compose.yml +++ /dev/null @@ -1,42 +0,0 @@ -services: - litentry-node: # just traffic forwarding, the node network should be up already at this point - image: qoomon/docker-host - cap_add: [ 'NET_ADMIN', 'NET_RAW' ] - mem_limit: 8M - restart: on-failure - container_name: litentry-node - networks: - - litentry-test-network - bitacross-worker-1: - image: litentry/bitacross-worker:latest - container_name: bitacross-worker-1 - build: - context: ${PWD}/.. - dockerfile: build.Dockerfile - target: deployed-worker - depends_on: - litentry-node: - condition: service_started - devices: - - "${SGX_PROVISION:-/dev/null}:/dev/sgx/provision" - - "${SGX_ENCLAVE:-/dev/null}:/dev/sgx/enclave" - volumes: - - "${AESMD:-/dev/null}:/var/run/aesmd" - - "${SGX_QCNL:-/dev/null}:/etc/sgx_default_qcnl.conf" - environment: - - RUST_LOG=info,litentry_worker=debug,ws=warn,sp_io=error,substrate_api_client=warn,itc_parentchain_light_client=info,jsonrpsee_ws_client=warn,jsonrpsee_ws_server=warn,enclave_runtime=debug,ita_stf=debug,its_rpc_handler=warn,itc_rpc_client=warn,its_consensus_common=debug,its_state=warn,its_consensus_aura=warn,aura*=warn,its_consensus_slots=warn,itp_attestation_handler=debug,http_req=debug,lc_mock_server=warn,itc_rest_client=debug,lc_credentials=debug,lc_identity_verification=debug,lc_stf_task_receiver=debug,lc_stf_task_sender=debug,lc_data_providers=debug,itp_top_pool=debug,itc_parentchain_indirect_calls_executor=debug, - networks: - - litentry-test-network - healthcheck: - test: curl -s -f http://bitacross-worker-1:4645/is_initialized || exit 1 - interval: 30s - timeout: 10s - retries: 20 - entrypoint: - "/usr/local/bin/bitacross-worker --clean-reset --ws-external -M bitacross-worker-1 -T wss://bitacross-worker-1 - -u ws://litentry-node -U ws://bitacross-worker-1 -P 2011 -w 2101 -p 9944 -h 4645 - run --dev --skip-ra" - restart: "no" -networks: - litentry-test-network: - driver: bridge diff --git a/tee-worker/bitacross/docker/entrypoint.sh b/tee-worker/bitacross/docker/entrypoint.sh deleted file mode 100755 index cfbefaf9c4..0000000000 --- a/tee-worker/bitacross/docker/entrypoint.sh +++ /dev/null @@ -1,19 +0,0 @@ -#!/bin/bash -set -e - -# Check if the first argument is "mrenclave" -if [ "$1" = "mrenclave" ]; then - # If "mrenclave" is provided, execute the corresponding command - $SGX_ENCLAVE_SIGNER dump \ - -enclave /usr/local/bin/enclave.signed.so \ - -dumpfile df.out && \ - /usr/local/bin/extract_identity < df.out && rm df.out | grep -oP ':\s*\K[a-fA-F0-9]+' - -else - # If no specific command is provided, execute the default unnamed command - - # run aesmd in the background - /opt/intel/sgx-aesm-service/aesm/aesm_service - - exec /usr/local/bin/bitacross-worker "${@}" -fi diff --git a/tee-worker/bitacross/docker/fork.Dockerfile b/tee-worker/bitacross/docker/fork.Dockerfile deleted file mode 100644 index e92c8d129a..0000000000 --- a/tee-worker/bitacross/docker/fork.Dockerfile +++ /dev/null @@ -1,26 +0,0 @@ -# Copyright 2021 Integritee AG -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -### Build Pumba image with dockerize -################################################## -FROM scratch AS fork-simulator-deployed -LABEL maintainer="zoltan@integritee.network" - -COPY --from=gaiaadm/pumba /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ca-certificates.crt -COPY --from=gaiaadm/pumba /pumba /usr/local/bin/pumba -COPY --from=powerman/dockerize /usr/local/bin/dockerize /usr/local/bin/dockerize - -ENV PATH="$PATH:/usr/local/bin" - -ENTRYPOINT ["/usr/local/bin/dockerize"] \ No newline at end of file diff --git a/tee-worker/bitacross/docker/lit-parentchain-nonce.yml b/tee-worker/bitacross/docker/lit-parentchain-nonce.yml deleted file mode 100644 index 728728e544..0000000000 --- a/tee-worker/bitacross/docker/lit-parentchain-nonce.yml +++ /dev/null @@ -1,22 +0,0 @@ -services: - lit-parentchain-nonce: - image: litentry/bitacross-cli:latest - container_name: litentry-parentchain-nonce - volumes: - - ../cli:/usr/local/worker-cli - build: - context: .. - dockerfile: build.Dockerfile - target: deployed-client - depends_on: - bitacross-worker-1: - condition: service_healthy - networks: - - litentry-test-network - entrypoint: - "/usr/local/worker-cli/lit_parentchain_nonce.sh -p 9944 -u ws://litentry-node - -V wss://bitacross-worker-1 -A 2011 -C /usr/local/bin/bitacross-cli 2>&1" - restart: "no" -networks: - litentry-test-network: - driver: bridge \ No newline at end of file diff --git a/tee-worker/bitacross/docker/lit-sign-bitcoin.yml b/tee-worker/bitacross/docker/lit-sign-bitcoin.yml deleted file mode 100644 index e1b8621a30..0000000000 --- a/tee-worker/bitacross/docker/lit-sign-bitcoin.yml +++ /dev/null @@ -1,21 +0,0 @@ -services: - lit-sign-bitcoin: - image: litentry/bitacross-cli:latest - container_name: litentry-sign-bitcoin-test - volumes: - - ../ts-tests:/ts-tests - - ../cli:/usr/local/worker-cli - build: - context: .. - dockerfile: build.Dockerfile - target: deployed-client - depends_on: - bitacross-worker-3: - condition: service_healthy - networks: - - litentry-test-network - entrypoint: "bash -c '/usr/local/worker-cli/lit_ts_integration_test.sh sign_bitcoin.test.ts 2>&1' " - restart: "no" -networks: - litentry-test-network: - driver: bridge diff --git a/tee-worker/bitacross/docker/multiworker-docker-compose.yml b/tee-worker/bitacross/docker/multiworker-docker-compose.yml deleted file mode 100644 index e4142a4ee5..0000000000 --- a/tee-worker/bitacross/docker/multiworker-docker-compose.yml +++ /dev/null @@ -1,102 +0,0 @@ -services: - litentry-node: # just traffic forwarding, the node network should be up already at this point - image: qoomon/docker-host - cap_add: [ 'NET_ADMIN', 'NET_RAW' ] - mem_limit: 8M - restart: on-failure - container_name: litentry-node - networks: - - litentry-test-network - bitacross-worker-1: - image: litentry/bitacross-worker:latest - container_name: bitacross-worker-1 - build: - context: ${PWD}/.. - dockerfile: build.Dockerfile - target: deployed-worker - depends_on: - litentry-node: - condition: service_started - devices: - - "${SGX_PROVISION:-/dev/null}:/dev/sgx/provision" - - "${SGX_ENCLAVE:-/dev/null}:/dev/sgx/enclave" - volumes: - - "${AESMD:-/dev/null}:/var/run/aesmd" - - "${SGX_QCNL:-/dev/null}:/etc/sgx_default_qcnl.conf" - environment: - - RUST_LOG=info,litentry_worker=debug,ws=warn,sp_io=error,substrate_api_client=warn,itc_parentchain_light_client=info,jsonrpsee_ws_client=warn,jsonrpsee_ws_server=warn,enclave_runtime=debug,ita_stf=debug,its_rpc_handler=warn,itc_rpc_client=warn,its_consensus_common=debug,its_state=warn,its_consensus_aura=warn,aura*=warn,its_consensus_slots=warn,itp_attestation_handler=debug,http_req=debug,lc_mock_server=warn,itc_rest_client=debug,lc_credentials=debug,lc_identity_verification=debug,lc_stf_task_receiver=debug,lc_stf_task_sender=debug,lc_data_providers=debug,itp_top_pool=debug,itc_parentchain_indirect_calls_executor=debug, - networks: - - litentry-test-network - healthcheck: - test: curl -s -f http://bitacross-worker-1:4645/is_initialized || exit 1 - interval: 30s - timeout: 10s - retries: 20 - entrypoint: - "/usr/local/bin/bitacross-worker --clean-reset --ws-external -M bitacross-worker-1 -T wss://bitacross-worker-1 - -u ws://litentry-node -U ws://bitacross-worker-1 -P 2011 -w 2101 -p 9944 -h 4645 - run --dev --skip-ra" - restart: "no" - bitacross-worker-2: - image: litentry/bitacross-worker:latest - container_name: bitacross-worker-2 - build: - context: ${PWD}/.. - dockerfile: build.Dockerfile - target: deployed-worker - depends_on: - bitacross-worker-1: - condition: service_healthy - devices: - - "${SGX_PROVISION:-/dev/null}:/dev/sgx/provision" - - "${SGX_ENCLAVE:-/dev/null}:/dev/sgx/enclave" - volumes: - - "${AESMD:-/dev/null}:/var/run/aesmd" - - "${SGX_QCNL:-/dev/null}:/etc/sgx_default_qcnl.conf" - environment: - - RUST_LOG=info,litentry_worker=debug,ws=warn,sp_io=error,substrate_api_client=warn,itc_parentchain_light_client=info,jsonrpsee_ws_client=warn,jsonrpsee_ws_server=warn,enclave_runtime=debug,ita_stf=debug,its_rpc_handler=warn,itc_rpc_client=warn,its_consensus_common=debug,its_state=warn,its_consensus_aura=warn,aura*=warn,its_consensus_slots=warn,itp_attestation_handler=debug,http_req=debug,lc_mock_server=warn,itc_rest_client=debug,lc_credentials=debug,lc_identity_verification=debug,lc_stf_task_receiver=debug,lc_stf_task_sender=debug,lc_data_providers=debug,itp_top_pool=debug,itc_parentchain_indirect_calls_executor=debug, - networks: - - litentry-test-network - healthcheck: - test: curl -s -f http://bitacross-worker-2:4645/is_initialized || exit 1 - interval: 30s - timeout: 10s - retries: 20 - entrypoint: - "/usr/local/bin/bitacross-worker --clean-reset --ws-external -M bitacross-worker-2 -T wss://bitacross-worker-2 - -u ws://litentry-node -U ws://bitacross-worker-2 -P 2011 -w 2101 -p 9944 -h 4645 - run --dev --skip-ra --request-state" - restart: "no" - bitacross-worker-3: - image: litentry/bitacross-worker:latest - container_name: bitacross-worker-3 - build: - context: ${PWD}/.. - dockerfile: build.Dockerfile - target: deployed-worker - depends_on: - bitacross-worker-2: - condition: service_healthy - devices: - - "${SGX_PROVISION:-/dev/null}:/dev/sgx/provision" - - "${SGX_ENCLAVE:-/dev/null}:/dev/sgx/enclave" - volumes: - - "${AESMD:-/dev/null}:/var/run/aesmd" - - "${SGX_QCNL:-/dev/null}:/etc/sgx_default_qcnl.conf" - environment: - - RUST_LOG=info,litentry_worker=debug,ws=warn,sp_io=error,substrate_api_client=warn,itc_parentchain_light_client=info,jsonrpsee_ws_client=warn,jsonrpsee_ws_server=warn,enclave_runtime=debug,ita_stf=debug,its_rpc_handler=warn,itc_rpc_client=warn,its_consensus_common=debug,its_state=warn,its_consensus_aura=warn,aura*=warn,its_consensus_slots=warn,itp_attestation_handler=debug,http_req=debug,lc_mock_server=warn,itc_rest_client=debug,lc_credentials=debug,lc_identity_verification=debug,lc_stf_task_receiver=debug,lc_stf_task_sender=debug,lc_data_providers=debug,itp_top_pool=debug,itc_parentchain_indirect_calls_executor=debug, - networks: - - litentry-test-network - healthcheck: - test: curl -s -f http://bitacross-worker-3:4645/is_initialized || exit 1 - interval: 30s - timeout: 10s - retries: 20 - entrypoint: - "/usr/local/bin/bitacross-worker --clean-reset --ws-external -M bitacross-worker-3 -T wss://bitacross-worker-3 - -u ws://litentry-node -U ws://bitacross-worker-3 -P 2011 -w 2101 -p 9944 -h 4645 - run --dev --skip-ra --request-state" - restart: "no" -networks: - litentry-test-network: - driver: bridge diff --git a/tee-worker/bitacross/docker/ping.Dockerfile b/tee-worker/bitacross/docker/ping.Dockerfile deleted file mode 100644 index 50ea4b7723..0000000000 --- a/tee-worker/bitacross/docker/ping.Dockerfile +++ /dev/null @@ -1,19 +0,0 @@ -# Copyright 2021 Integritee AG -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -FROM alpine:latest - -RUN apk add --update iproute2 - -ENTRYPOINT ping \ No newline at end of file diff --git a/tee-worker/bitacross/docker/sidechain-benchmark.yml b/tee-worker/bitacross/docker/sidechain-benchmark.yml deleted file mode 100644 index 5c20f94831..0000000000 --- a/tee-worker/bitacross/docker/sidechain-benchmark.yml +++ /dev/null @@ -1,25 +0,0 @@ -services: - sidechain-benchmark: - image: bitacross-cli:${VERSION:-dev} - devices: - - "${SGX_PROVISION:-/dev/null}:/dev/sgx/provision" - - "${SGX_ENCLAVE:-/dev/null}:/dev/sgx/enclave" - volumes: - - "${AESMD:-/dev/null}:/var/run/aesmd" - - "${SGX_QCNL:-/dev/null}:/etc/sgx_default_qcnl.conf" - build: - context: ${PWD}/.. - dockerfile: build.Dockerfile - target: deployed-client - depends_on: - bitacross-worker-1-${VERSION}: - condition: service_healthy - networks: - - litentry-test-network - entrypoint: - "/usr/local/worker-cli/benchmark.sh -p 9944 -A 2011 -u ws://litentry-node - -V wss://bitacross-worker-1 -C /usr/local/bin/bitacross-cli 2>&1" - restart: "no" -networks: - litentry-test-network: - driver: bridge \ No newline at end of file diff --git a/tee-worker/bitacross/docs/README.md b/tee-worker/bitacross/docs/README.md deleted file mode 100644 index c0e42e94fa..0000000000 --- a/tee-worker/bitacross/docs/README.md +++ /dev/null @@ -1,25 +0,0 @@ -# Knowhow Dump - -This folder contains documents and links that contain some (potentially outdated) information about the worker. -Use with caution, as this is work in progress. Hence, the code is most likely progressing faster than this documentation. - -## Useful links: -### O- / Ecalls -- Ocall Bridge: https://github.com/integritee-network/worker/pull/293 & https://github.com/integritee-network/worker/pull/299 -- Enclave ecalls / ocalls: https://github.com/integritee-network/worker/issues/279 -- Abstract ecalls in enclave: https://github.com/integritee-network/worker/issues/286 -- Abstract ocalls in enclave: https://github.com/integritee-network/worker/issues/279 - -### Sidechain -- Sidechain functionality: https://polkadot.polkassembly.io/post/111 -- Sidechain flow: https://github.com/integritee-network/worker/pull/627 -- Simplified sidechain sequence, of a user call and the STF: https://raw.githubusercontent.com/haerdib/substraTEE_diagramms/main/sidechain-sequence.svg -- Top_pool sequence: https://raw.githubusercontent.com/haerdib/substraTEE_diagramms/main/submit_and_watch_sequence.svg -### Parentchain -- A rough overview of the architecture surrounding the parentchain block import dispatching: https://github.com/integritee-network/worker/pull/530 - -### Runtime -- Enclave runtime: https://github.com/integritee-network/worker/pull/472 - -### Non-worker related graphics -- substrate related graphics: https://github.com/brenzi/substrate-doc diff --git a/tee-worker/bitacross/docs/diagramms/block_import_sequence.svg b/tee-worker/bitacross/docs/diagramms/block_import_sequence.svg deleted file mode 100644 index 369cecb4ab..0000000000 --- a/tee-worker/bitacross/docs/diagramms/block_import_sequence.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - -
For every
sidechain block
For every...
For every
parentchain block
For every...
For every
extrinsic
For every...
For every
shard
For every...
Parentchain BlockImport Queue
pop queue until()
pop queue until()
Light Client
verify block
verify block
import block
import block
! state update
! state update
Node
Validateer / Worker
Validateer / Worker
Substrate Node
Substrate Node
Event: New Finalized Blockget_blocks(last_synced_header)
finalized blocks
finalized blocks
Parentchain BlockImporter
push_to_
import_queue
push_to_...
sync_parentchain(finalized blocks)
last_synced_header
last_synced_header
Sgx Runtime
Sgx Runtime
Sidechain BlockImport Queue
new block
new block
import_block
import_block
Sidechain BlockProducer
create 
sidechain
block
create...
create proposed_sidechain_block
extrinsic
create proposed_sidechain_block...
Top PoolState
calculate state diff
(no state update!)
calculate state diff...
import_parentchain_block(import_until(sidechain block -> parentchain block))Untrusted Listenersubmit_simple_header
Ok()
Ok()
send parentchain extrinsics
send parentchai...
check time
check time
(if_author == self)remove tops (shard, hashes)
Ok()
Ok()
retrieve sidechain blocks
parentchain header
parentchain header
pop until(parentchain header)
blocks
blocks
peek assosciated parentchain header
sidechain blocks
sidechain blocks
latest imported parentchain header
latest imported parentchain header
Sidechain BlockImporter
verify sidechain
block
verify sidechain...
load_state(shard)
load_state(shard)
trigger sidechainblock import
latest parentchain header
latest parentchain header
trusted_calls(shard)
trusted_calls(shard)
get_trusted_calls(shard)Top Pool Execution Loop
intervall trigger
intervall t...
claim_slot
claim_slot
list_shards
shards
shards
exec_aura_on_slot(shards,parentchain header)execute trusted calls(trusted calls)
state_diff, executed hashes
state_diff, executed hashes
sidechain blocks,
extrinsics
sidechain blocks,...
broadcast sidechain block
broadcast sidechai...
Stf::execute(state)
updated state
updated state
Executor
write
(updated state)
write...
execute_indirect_calls_extrinsic(block)
Ok()
Ok()
write(updated_state)
write(updated_state)
For every
parentchain block
For every...
For every
extrinsic
For every...
pop queue until()
pop queue until()
verify block
verify block
import block
import block
! state update
! state update
submit_simple_header
Ok()
Ok()
pop until(parentchain header)
blocks
blocks
latest imported parentchain header
latest imported parentchain header
write
(updated state)
write...
execute_indirect_calls_extrinsic(block)
Ok()
Ok()
import_latest_parentchain_block(parentchain_hedaer)Stf::execute(state)
updated state
updated state
apply_state_update(state, state_diff)+ set_last_block
updated state
updated state
remove invalid tops
Ok()
Ok()
Viewer does not support full SVG 1.1
\ No newline at end of file diff --git a/tee-worker/bitacross/enclave-runtime/Cargo.lock b/tee-worker/bitacross/enclave-runtime/Cargo.lock deleted file mode 100644 index ac1d14954c..0000000000 --- a/tee-worker/bitacross/enclave-runtime/Cargo.lock +++ /dev/null @@ -1,5314 +0,0 @@ -# This file is automatically @generated by Cargo. -# It is not intended for manual editing. -version = 3 - -[[package]] -name = "Inflector" -version = "0.11.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fe438c63458706e03479442743baae6c88256498e6431708f6dfc520a26515d3" -dependencies = [ - "lazy_static", - "regex 1.9.5", -] - -[[package]] -name = "ac-compose-macros" -version = "0.4.2" -source = "git+https://github.com/Kailai-Wang/substrate-api-client?branch=polkadot-v0.9.42-litentry#f867fea44a3de5352d419a605afdd7bf22859e78" -dependencies = [ - "ac-primitives", - "log 0.4.21", - "maybe-async", -] - -[[package]] -name = "ac-node-api" -version = "0.5.1" -source = "git+https://github.com/Kailai-Wang/substrate-api-client?branch=polkadot-v0.9.42-litentry#f867fea44a3de5352d419a605afdd7bf22859e78" -dependencies = [ - "ac-primitives", - "bitvec", - "derive_more", - "either", - "frame-metadata", - "hex", - "log 0.4.21", - "parity-scale-codec", - "scale-bits", - "scale-decode", - "scale-encode", - "scale-info", - "serde 1.0.204", - "serde_json 1.0.133", - "sp-application-crypto", - "sp-core", - "sp-runtime", - "sp-runtime-interface", -] - -[[package]] -name = "ac-primitives" -version = "0.9.0" -source = "git+https://github.com/Kailai-Wang/substrate-api-client?branch=polkadot-v0.9.42-litentry#f867fea44a3de5352d419a605afdd7bf22859e78" -dependencies = [ - "impl-serde", - "parity-scale-codec", - "primitive-types", - "scale-info", - "serde 1.0.204", - "serde_json 1.0.133", - "sp-application-crypto", - "sp-core", - "sp-core-hashing", - "sp-runtime", - "sp-runtime-interface", - "sp-staking", - "sp-version", - "sp-weights", -] - -[[package]] -name = "aes" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "884391ef1066acaa41e766ba8f596341b96e93ce34f9a43e7d24bf0a0eaf0561" -dependencies = [ - "aes-soft", - "aesni", - "cipher", -] - -[[package]] -name = "aes-soft" -version = "0.6.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "be14c7498ea50828a38d0e24a765ed2effe92a705885b57d029cd67d45744072" -dependencies = [ - "cipher", - "opaque-debug 0.3.0", -] - -[[package]] -name = "aesni" -version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea2e11f5e94c2f7d386164cc2aa1f97823fed6f259e486940a71c174dd01b0ce" -dependencies = [ - "cipher", - "opaque-debug 0.3.0", -] - -[[package]] -name = "ahash" -version = "0.7.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fcb51a0695d8f838b1ee009b3fbf66bda078cd64590202a864a8f3e8c4315c47" -dependencies = [ - "getrandom 0.2.12", - "once_cell 1.18.0", - "version_check", -] - -[[package]] -name = "ahash" -version = "0.8.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2c99f64d1e06488f620f932677e24bc6e2897582980441ae90a671415bd7ec2f" -dependencies = [ - "cfg-if 1.0.0", - "once_cell 1.18.0", - "version_check", -] - -[[package]] -name = "aho-corasick" -version = "0.7.10" -source = "git+https://github.com/mesalock-linux/aho-corasick-sgx#7558a97cdf02804f38ec4edd1c0bb0dc2866267f" -dependencies = [ - "memchr 2.2.1", - "sgx_tstd", -] - -[[package]] -name = "aho-corasick" -version = "1.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea5d730647d4fadd988536d06fecce94b7b4f2a7efdae548f1cf4b63205518ab" -dependencies = [ - "memchr 2.6.3", -] - -[[package]] -name = "array-bytes" -version = "4.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f52f63c5c1316a16a4b35eaac8b76a98248961a533f061684cb2a7cb0eafb6c6" - -[[package]] -name = "arrayref" -version = "0.3.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6b4930d2cb77ce62f89ee5d5289b4ac049559b1c45539271f5ed4fdc7db34545" - -[[package]] -name = "arrayvec" -version = "0.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23b62fc65de8e4e7f52534fb52b0f3ed04746ae267519eef2a83941e8085068b" - -[[package]] -name = "arrayvec" -version = "0.7.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "96d30a06541fbafbc7f82ed10c06164cfbd2c401138f6addd8404629c4b16711" - -[[package]] -name = "async-trait" -version = "0.1.73" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bc00ceb34980c03614e35a3a4e218276a0a824e911d07651cd0d858a51e8c0f0" -dependencies = [ - "proc-macro2", - "quote 1.0.36", - "syn 2.0.72", -] - -[[package]] -name = "auto_impl" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fee3da8ef1276b0bee5dd1c7258010d8fffd31801447323115a25560e1327b89" -dependencies = [ - "proc-macro-error", - "proc-macro2", - "quote 1.0.36", - "syn 1.0.109", -] - -[[package]] -name = "autocfg" -version = "0.1.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0dde43e75fd43e8a1bf86103336bc699aa8d17ad1be60c76c0bdfd4828e19b78" -dependencies = [ - "autocfg 1.1.0", -] - -[[package]] -name = "autocfg" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" - -[[package]] -name = "base-x" -version = "0.2.6" -source = "git+https://github.com/whalelephant/base-x-rs?branch=no_std#906c9ac59282ff5a2eec86efd25d50ad9927b147" - -[[package]] -name = "base16ct" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf" - -[[package]] -name = "base58" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6107fe1be6682a68940da878d9e9f5e90ca5745b3dec9fd1bb393c8777d4f581" - -[[package]] -name = "base64" -version = "0.13.0" -source = "git+https://github.com/mesalock-linux/rust-base64-sgx?tag=sgx_1.1.3#dc7389e10817b078f289386b3b6a852ab6c4c021" -dependencies = [ - "sgx_tstd", -] - -[[package]] -name = "base64" -version = "0.13.0" -source = "git+https://github.com/mesalock-linux/rust-base64-sgx?rev=sgx_1.1.3#dc7389e10817b078f289386b3b6a852ab6c4c021" -dependencies = [ - "sgx_tstd", -] - -[[package]] -name = "base64" -version = "0.13.0" -source = "git+https://github.com/mesalock-linux/rust-base64-sgx#dc7389e10817b078f289386b3b6a852ab6c4c021" -dependencies = [ - "sgx_tstd", -] - -[[package]] -name = "base64" -version = "0.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e1b586273c5702936fe7b7d6896644d8be71e6314cfe09d3167c95f712589e8" - -[[package]] -name = "base64ct" -version = "1.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8c3c1a368f70d6cf7302d78f8f7093da241fb8e8807c05cc9e51a125895a6d5b" - -[[package]] -name = "bc-enclave-registry" -version = "0.1.0" -dependencies = [ - "itp-settings", - "itp-sgx-io", - "litentry-primitives", - "log 0.4.21", - "parity-scale-codec", - "sgx_tstd", - "sp-std", - "thiserror", -] - -[[package]] -name = "bc-ita-parentchain-interface" -version = "0.1.0" -dependencies = [ - "bc-enclave-registry", - "bc-ita-sgx-runtime", - "bc-ita-stf", - "bc-itc-parentchain-indirect-calls-executor", - "bc-relayer-registry", - "bc-signer-registry", - "itp-api-client-types", - "itp-node-api", - "itp-stf-primitives", - "itp-types", - "litentry-primitives", - "log 0.4.21", - "parity-scale-codec", - "sgx_tstd", - "sp-core", - "sp-runtime", - "sp-std", -] - -[[package]] -name = "bc-ita-sgx-runtime" -version = "0.1.0" -dependencies = [ - "frame-executive", - "frame-support", - "frame-system", - "itp-sgx-runtime-primitives", - "pallet-balances", - "pallet-parentchain", - "pallet-sudo", - "pallet-timestamp", - "pallet-transaction-payment", - "parity-scale-codec", - "scale-info", - "sp-api", - "sp-core", - "sp-runtime", - "sp-std", - "sp-version", -] - -[[package]] -name = "bc-ita-stf" -version = "0.1.0" -dependencies = [ - "bc-ita-sgx-runtime", - "frame-support", - "frame-system", - "hex", - "hex-literal", - "itp-hashing", - "itp-node-api", - "itp-sgx-externalities", - "itp-stf-interface", - "itp-stf-primitives", - "itp-storage", - "itp-types", - "itp-utils", - "litentry-macros", - "litentry-primitives", - "log 0.4.21", - "pallet-balances", - "pallet-parentchain", - "pallet-sudo", - "parity-scale-codec", - "sgx_tstd", - "sp-core", - "sp-io", - "sp-runtime", - "sp-std", -] - -[[package]] -name = "bc-itc-direct-rpc-client" -version = "0.1.0" -dependencies = [ - "itp-rpc", - "itp-types", - "itp-utils", - "log 0.4.21", - "rustls 0.19.0 (git+https://github.com/mesalock-linux/rustls?tag=sgx_1.1.3)", - "serde_json 1.0.133", - "sgx_tstd", - "tungstenite", - "url 2.5.0", - "webpki", -] - -[[package]] -name = "bc-itc-direct-rpc-server" -version = "0.1.0" -dependencies = [ - "itc-tls-websocket-server", - "itp-rpc", - "itp-types", - "itp-utils", - "jsonrpc-core", - "log 0.4.21", - "parity-scale-codec", - "serde_json 1.0.133", - "sgx_tstd", - "sp-runtime", - "thiserror", -] - -[[package]] -name = "bc-itc-offchain-worker-executor" -version = "0.1.0" -dependencies = [ - "bc-itp-stf-executor", - "bc-itp-top-pool-author", - "itc-parentchain-light-client", - "itp-extrinsics-factory", - "itp-stf-interface", - "itp-stf-primitives", - "itp-stf-state-handler", - "itp-types", - "log 0.4.21", - "parity-scale-codec", - "sgx_tstd", - "sp-runtime", - "thiserror", -] - -[[package]] -name = "bc-itc-parentchain" -version = "0.1.0" -dependencies = [ - "bc-itc-parentchain-block-import-dispatcher", - "bc-itc-parentchain-block-importer", - "bc-itc-parentchain-indirect-calls-executor", - "itc-parentchain-light-client", - "itp-types", - "parity-scale-codec", - "sp-runtime", -] - -[[package]] -name = "bc-itc-parentchain-block-import-dispatcher" -version = "0.1.0" -dependencies = [ - "bc-itc-parentchain-block-importer", - "itp-import-queue", - "log 0.4.21", - "sgx_tstd", - "sgx_types", - "thiserror", -] - -[[package]] -name = "bc-itc-parentchain-block-importer" -version = "0.1.0" -dependencies = [ - "bc-ita-stf", - "bc-itc-parentchain-indirect-calls-executor", - "bc-itp-stf-executor", - "itc-parentchain-light-client", - "itp-enclave-metrics", - "itp-extrinsics-factory", - "itp-ocall-api", - "itp-stf-interface", - "itp-types", - "log 0.4.21", - "parity-scale-codec", - "sgx_tstd", - "sgx_types", - "sp-runtime", - "thiserror", -] - -[[package]] -name = "bc-itc-parentchain-indirect-calls-executor" -version = "0.1.0" -dependencies = [ - "bc-enclave-registry", - "bc-itp-stf-executor", - "bc-itp-top-pool-author", - "bc-relayer-registry", - "bc-signer-registry", - "binary-merkle-tree", - "bs58", - "futures 0.3.8", - "itp-api-client-types", - "itp-node-api", - "itp-sgx-crypto", - "itp-sgx-runtime-primitives", - "itp-stf-primitives", - "itp-test", - "itp-types", - "litentry-primitives", - "log 0.4.21", - "parity-scale-codec", - "sgx_tstd", - "sgx_types", - "sp-runtime", - "thiserror", -] - -[[package]] -name = "bc-itp-stf-executor" -version = "0.1.0" -dependencies = [ - "bc-itp-top-pool-author", - "hex", - "itc-parentchain-test", - "itp-enclave-metrics", - "itp-node-api", - "itp-ocall-api", - "itp-sgx-crypto", - "itp-sgx-externalities", - "itp-stf-interface", - "itp-stf-primitives", - "itp-stf-state-handler", - "itp-stf-state-observer", - "itp-test", - "itp-time-utils", - "itp-types", - "log 0.4.21", - "parity-scale-codec", - "sgx_tstd", - "sgx_types", - "sp-core", - "sp-runtime", - "thiserror", -] - -[[package]] -name = "bc-itp-top-pool" -version = "0.1.0" -dependencies = [ - "bc-itc-direct-rpc-server", - "byteorder 1.4.3", - "derive_more", - "itp-stf-primitives", - "itp-types", - "jsonrpc-core", - "linked-hash-map", - "log 0.4.21", - "parity-scale-codec", - "sgx_tstd", - "sp-core", - "sp-runtime", -] - -[[package]] -name = "bc-itp-top-pool-author" -version = "0.1.0" -dependencies = [ - "bc-itp-top-pool", - "derive_more", - "itp-enclave-metrics", - "itp-ocall-api", - "itp-sgx-crypto", - "itp-stf-primitives", - "itp-stf-state-handler", - "itp-test", - "itp-types", - "itp-utils", - "jsonrpc-core", - "lazy_static", - "litentry-primitives", - "log 0.4.21", - "parity-scale-codec", - "sgx_tstd", - "sp-core", - "sp-runtime", -] - -[[package]] -name = "bc-musig2-ceremony" -version = "0.1.0" -dependencies = [ - "itp-sgx-crypto", - "k256", - "litentry-primitives", - "log 0.4.21", - "musig2", - "parity-scale-codec", - "sgx_rand", - "sgx_tstd", -] - -[[package]] -name = "bc-musig2-event" -version = "0.1.0" -dependencies = [ - "bc-enclave-registry", - "bc-itc-direct-rpc-client", - "bc-itc-direct-rpc-server", - "bc-musig2-ceremony", - "itp-ocall-api", - "itp-rpc", - "itp-sgx-crypto", - "itp-types", - "itp-utils", - "lc-direct-call", - "litentry-primitives", - "log 0.4.21", - "parity-scale-codec", - "sgx_rand", - "sgx_tstd", - "sp-core", - "threadpool", -] - -[[package]] -name = "bc-relayer-registry" -version = "0.1.0" -dependencies = [ - "itp-settings", - "itp-sgx-io", - "litentry-primitives", - "log 0.4.21", - "parity-scale-codec", - "sgx_tstd", - "sp-std", - "thiserror", -] - -[[package]] -name = "bc-signer-registry" -version = "0.1.0" -dependencies = [ - "itp-settings", - "itp-sgx-io", - "litentry-primitives", - "log 0.4.21", - "parity-scale-codec", - "sgx_tstd", - "sp-std", - "thiserror", -] - -[[package]] -name = "bc-task-processor" -version = "0.1.0" -dependencies = [ - "bc-enclave-registry", - "bc-ita-stf", - "bc-itc-direct-rpc-client", - "bc-itc-direct-rpc-server", - "bc-itp-stf-executor", - "bc-musig2-ceremony", - "bc-musig2-event", - "bc-relayer-registry", - "bc-signer-registry", - "bc-task-sender", - "frame-support", - "futures 0.3.8", - "itp-enclave-metrics", - "itp-ocall-api", - "itp-sgx-crypto", - "itp-sgx-externalities", - "itp-stf-state-handler", - "lc-direct-call", - "litentry-primitives", - "log 0.4.21", - "parity-scale-codec", - "sgx_crypto_helper", - "sgx_tstd", - "sp-core", - "thiserror", - "threadpool", -] - -[[package]] -name = "bc-task-sender" -version = "0.1.0" -dependencies = [ - "futures 0.3.8", - "lazy_static", - "litentry-primitives", - "parity-scale-codec", - "sgx_tstd", -] - -[[package]] -name = "bech32" -version = "0.10.0-beta" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "98f7eed2b2781a6f0b5c903471d48e15f56fb4e1165df8a9a2337fd1a59d45ea" - -[[package]] -name = "binary-merkle-tree" -version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" -dependencies = [ - "hash-db 0.16.0", -] - -[[package]] -name = "bit-vec" -version = "0.6.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "349f9b6a179ed607305526ca489b34ad0a41aed5f7980fa90eb03160b69598fb" - -[[package]] -name = "bitcoin" -version = "0.31.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5973a027b341b462105675962214dfe3c938ad9afd395d84b28602608bdcec7b" -dependencies = [ - "bech32", - "bitcoin-internals", - "bitcoin_hashes", - "core2", - "hex-conservative", - "hex_lit", - "secp256k1 0.28.0", -] - -[[package]] -name = "bitcoin-internals" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9425c3bf7089c983facbae04de54513cce73b41c7f9ff8c845b54e7bc64ebbfb" - -[[package]] -name = "bitcoin_hashes" -version = "0.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1930a4dabfebb8d7d9992db18ebe3ae2876f0a305fab206fd168df931ede293b" -dependencies = [ - "bitcoin-internals", - "core2", - "hex-conservative", -] - -[[package]] -name = "bitflags" -version = "1.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" - -[[package]] -name = "bitvec" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1bc2832c24239b0141d5674bb9174f9d68a8b5b3f2753311927c172ca46f7e9c" -dependencies = [ - "funty", - "radium", - "tap", - "wyz", -] - -[[package]] -name = "blake2" -version = "0.10.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe" -dependencies = [ - "digest 0.10.7", -] - -[[package]] -name = "blake2b_simd" -version = "0.5.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "afa748e348ad3be8263be728124b24a24f268266f6f5d58af9d75f6a40b5c587" -dependencies = [ - "arrayref", - "arrayvec 0.5.2", - "constant_time_eq 0.1.5", -] - -[[package]] -name = "blake2b_simd" -version = "1.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23285ad32269793932e830392f2fe2f83e26488fd3ec778883a93c8323735780" -dependencies = [ - "arrayref", - "arrayvec 0.7.4", - "constant_time_eq 0.3.0", -] - -[[package]] -name = "blake2s_simd" -version = "0.5.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e461a7034e85b211a4acb57ee2e6730b32912b06c08cc242243c39fc21ae6a2" -dependencies = [ - "arrayref", - "arrayvec 0.5.2", - "constant_time_eq 0.1.5", -] - -[[package]] -name = "block-buffer" -version = "0.7.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c0940dc441f31689269e10ac70eb1002a3a1d3ad1390e030043662eb7fe4688b" -dependencies = [ - "block-padding 0.1.5", - "byte-tools", - "byteorder 1.4.3", - "generic-array 0.12.4", -] - -[[package]] -name = "block-buffer" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4152116fd6e9dadb291ae18fc1ec3575ed6d84c29642d97890f4b4a3417297e4" -dependencies = [ - "block-padding 0.2.1", - "generic-array 0.14.7", -] - -[[package]] -name = "block-buffer" -version = "0.10.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" -dependencies = [ - "generic-array 0.14.7", -] - -[[package]] -name = "block-padding" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa79dedbb091f449f1f39e53edf88d5dbe95f895dae6135a8d7b881fb5af73f5" -dependencies = [ - "byte-tools", -] - -[[package]] -name = "block-padding" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8d696c370c750c948ada61c69a0ee2cbbb9c50b1019ddb86d9317157a99c2cae" - -[[package]] -name = "bounded-collections" -version = "0.1.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eb5b05133427c07c4776906f673ccf36c21b102c9829c641a5b56bd151d44fd6" -dependencies = [ - "log 0.4.21", - "parity-scale-codec", - "scale-info", -] - -[[package]] -name = "bs58" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "771fe0050b883fcc3ea2359b1a96bcfbc090b7116eae7c3c512c7a083fdf23d3" - -[[package]] -name = "byte-slice-cast" -version = "1.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3ac9f8b63eca6fd385229b3675f6cc0dc5c8a5c8a54a59d4f52ffd670d87b0c" - -[[package]] -name = "byte-tools" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e3b5ca7a04898ad4bcd41c90c5285445ff5b791899bb1b0abdd2a2aa791211d7" - -[[package]] -name = "byteorder" -version = "1.3.4" -source = "git+https://github.com/mesalock-linux/byteorder-sgx?tag=sgx_1.1.3#325f392dcd294109eb05f0a3c45e4141514c7784" -dependencies = [ - "sgx_tstd", -] - -[[package]] -name = "byteorder" -version = "1.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "14c189c53d098945499cdfa7ecc63567cf3886b3332b312a5b4585d8d3a6a610" - -[[package]] -name = "bytes" -version = "1.0.1" -source = "git+https://github.com/integritee-network/bytes-sgx?branch=sgx-experimental#62ed3082be2e23cb9bc8cc7ee9983a523de69292" -dependencies = [ - "sgx_tstd", -] - -[[package]] -name = "bytes" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a2bd12c1caf447e69cd4528f47f94d203fd2582878ecb9e9465484c4148a8223" - -[[package]] -name = "cargo_toml" -version = "0.19.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3dc9f7a067415ab5058020f04c60ec7b557084dbec0e021217bbabc7a8d38d14" -dependencies = [ - "serde 1.0.204", - "toml", -] - -[[package]] -name = "cc" -version = "1.0.83" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1174fb0b6ec23863f8b971027804a42614e347eafb0a95bf0b12cdae21fc4d0" -dependencies = [ - "libc", -] - -[[package]] -name = "cfg-expr" -version = "0.10.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0aacacf4d96c24b2ad6eb8ee6df040e4f27b0d0b39a5710c30091baa830485db" -dependencies = [ - "smallvec 1.11.1", -] - -[[package]] -name = "cfg-if" -version = "0.1.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822" - -[[package]] -name = "cfg-if" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" - -[[package]] -name = "chrono" -version = "0.4.11" -source = "git+https://github.com/mesalock-linux/chrono-sgx#f964ae7f5f65bd2c9cd6f44a067e7980afc08ca0" -dependencies = [ - "num-integer", - "num-traits 0.2.10", - "sgx_tstd", -] - -[[package]] -name = "chrono" -version = "0.4.31" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f2c685bad3eb3d45a01354cedb7d5faa66194d1d58ba6e267a8de788f79db38" -dependencies = [ - "num-traits 0.2.16", - "serde 1.0.204", -] - -[[package]] -name = "cid" -version = "0.5.1" -source = "git+https://github.com/whalelephant/rust-cid?branch=nstd#cca87467c46106c801ca3727500477258b0f13b0" -dependencies = [ - "multibase", - "multihash", - "unsigned-varint", -] - -[[package]] -name = "cipher" -version = "0.2.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "12f8e7987cbd042a63249497f41aed09f8e65add917ea6566effbc56578d6801" -dependencies = [ - "generic-array 0.14.7", -] - -[[package]] -name = "const-oid" -version = "0.9.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "28c122c3980598d243d63d9a704629a2d748d101f278052ff068be5a4423ab6f" - -[[package]] -name = "constant_time_eq" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "245097e9a4535ee1e3e3931fcfcd55a796a44c643e8596ff6566d68f09b87bbc" - -[[package]] -name = "constant_time_eq" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f7144d30dcf0fafbce74250a3963025d8d52177934239851c917d29f1df280c2" - -[[package]] -name = "convert_case" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6245d59a3e82a7fc217c5828a6692dbc6dfb63a0c8c90495621f7b9d79704a0e" - -[[package]] -name = "core-primitives" -version = "0.1.0" -dependencies = [ - "base58", - "base64 0.13.1", - "chrono 0.4.31", - "der 0.6.1", - "frame-support", - "hex", - "hex-literal", - "litentry-hex-utils", - "litentry-macros", - "litentry-proc-macros", - "pallet-evm", - "parity-scale-codec", - "ring 0.16.20", - "rustls-webpki", - "scale-info", - "serde 1.0.204", - "serde_json 1.0.133", - "sp-consensus-aura", - "sp-core", - "sp-io", - "sp-runtime", - "sp-std", - "strum", - "strum_macros", - "x509-cert", -] - -[[package]] -name = "core2" -version = "0.3.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "239fa3ae9b63c2dc74bd3fa852d4792b8b305ae64eeede946265b6af62f1fff3" -dependencies = [ - "memchr 2.6.3", -] - -[[package]] -name = "cpufeatures" -version = "0.2.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a17b76ff3a4162b0b27f354a0c87015ddad39d35f9c0c36607a3bdd175dde1f1" -dependencies = [ - "libc", -] - -[[package]] -name = "crunchy" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a81dae078cea95a014a339291cec439d2f232ebe854a9d672b796c6afafa9b7" - -[[package]] -name = "crypto-bigint" -version = "0.5.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "740fe28e594155f10cfc383984cbefd529d7396050557148f79cb0f621204124" -dependencies = [ - "generic-array 0.14.7", - "rand_core 0.6.4", - "subtle 2.4.1", - "zeroize", -] - -[[package]] -name = "crypto-common" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3" -dependencies = [ - "generic-array 0.14.7", - "typenum", -] - -[[package]] -name = "curve25519-dalek" -version = "2.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4a9b85542f99a2dfa2a1b8e192662741c9859a846b296bef1c92ef9b58b5a216" -dependencies = [ - "byteorder 1.4.3", - "digest 0.8.1", - "rand_core 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)", - "subtle 2.4.1", - "zeroize", -] - -[[package]] -name = "curve25519-dalek" -version = "3.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b9fdf9972b2bd6af2d913799d9ebc165ea4d2e65878e329d9c6b372c4491b61" -dependencies = [ - "byteorder 1.4.3", - "digest 0.9.0", - "rand_core 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)", - "subtle 2.4.1", - "zeroize", -] - -[[package]] -name = "darling" -version = "0.14.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b750cb3417fd1b327431a470f388520309479ab0bf5e323505daf0290cd3850" -dependencies = [ - "darling_core", - "darling_macro", -] - -[[package]] -name = "darling_core" -version = "0.14.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "109c1ca6e6b7f82cc233a97004ea8ed7ca123a9af07a8230878fcfda9b158bf0" -dependencies = [ - "fnv 1.0.7", - "ident_case", - "proc-macro2", - "quote 1.0.36", - "strsim", - "syn 1.0.109", -] - -[[package]] -name = "darling_macro" -version = "0.14.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a4aab4dbc9f7611d8b55048a3a16d2d010c2c8334e46304b40ac1cc14bf3b48e" -dependencies = [ - "darling_core", - "quote 1.0.36", - "syn 1.0.109", -] - -[[package]] -name = "data-encoding" -version = "2.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c2e66c9d817f1720209181c316d28635c050fa304f9c79e47a520882661b7308" - -[[package]] -name = "der" -version = "0.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1a467a65c5e759bce6e65eaf91cc29f466cdc57cb65777bd646872a8a1fd4de" -dependencies = [ - "const-oid", - "der_derive", - "flagset", -] - -[[package]] -name = "der" -version = "0.7.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fffa369a668c8af7dbf8b5e56c9f744fbd399949ed171606040001947de40b1c" -dependencies = [ - "const-oid", - "zeroize", -] - -[[package]] -name = "der_derive" -version = "0.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ef71ddb5b3a1f53dee24817c8f70dfa1cb29e804c18d88c228d4bc9c86ee3b9" -dependencies = [ - "proc-macro-error", - "proc-macro2", - "quote 1.0.36", - "syn 1.0.109", -] - -[[package]] -name = "derive-syn-parse" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e79116f119dd1dba1abf1f3405f03b9b0e79a27a3883864bfebded8a3dc768cd" -dependencies = [ - "proc-macro2", - "quote 1.0.36", - "syn 1.0.109", -] - -[[package]] -name = "derive_more" -version = "0.99.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4fb810d30a7c1953f91334de7244731fc3f3c10d7fe163338a35b9f640960321" -dependencies = [ - "convert_case", - "proc-macro2", - "quote 1.0.36", - "rustc_version", - "syn 1.0.109", -] - -[[package]] -name = "digest" -version = "0.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3d0c8c8752312f9713efd397ff63acb9f85585afbf179282e720e7704954dd5" -dependencies = [ - "generic-array 0.12.4", -] - -[[package]] -name = "digest" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3dd60d1080a57a05ab032377049e0591415d2b31afd7028356dbf3cc6dcb066" -dependencies = [ - "generic-array 0.14.7", -] - -[[package]] -name = "digest" -version = "0.10.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" -dependencies = [ - "block-buffer 0.10.4", - "const-oid", - "crypto-common", - "subtle 2.4.1", -] - -[[package]] -name = "ecdsa" -version = "0.16.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a4b1e0c257a9e9f25f90ff76d7a68360ed497ee519c8e428d1825ef0000799d4" -dependencies = [ - "der 0.7.8", - "digest 0.10.7", - "elliptic-curve", - "rfc6979", - "signature", - "spki 0.7.3", -] - -[[package]] -name = "ed25519-zebra" -version = "3.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7c24f403d068ad0b359e577a77f92392118be3f3c927538f2bb544a5ecd828c6" -dependencies = [ - "curve25519-dalek 3.2.0", - "hashbrown 0.12.3", - "hex", - "rand_core 0.6.4", - "sha2 0.9.9", - "zeroize", -] - -[[package]] -name = "either" -version = "1.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a26ae43d7bcc3b814de94796a5e736d4029efb0ee900c12e2d54c993ad1a1e07" - -[[package]] -name = "elliptic-curve" -version = "0.13.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b5e6043086bf7973472e0c7dff2142ea0b680d30e18d9cc40f267efbf222bd47" -dependencies = [ - "base16ct", - "crypto-bigint", - "digest 0.10.7", - "ff", - "generic-array 0.14.7", - "group", - "pkcs8", - "rand_core 0.6.4", - "sec1", - "subtle 2.4.1", - "zeroize", -] - -[[package]] -name = "enclave-runtime" -version = "0.0.1" -dependencies = [ - "bc-enclave-registry", - "bc-ita-parentchain-interface", - "bc-ita-sgx-runtime", - "bc-ita-stf", - "bc-itc-direct-rpc-server", - "bc-itc-offchain-worker-executor", - "bc-itc-parentchain", - "bc-itp-stf-executor", - "bc-itp-top-pool", - "bc-itp-top-pool-author", - "bc-musig2-ceremony", - "bc-relayer-registry", - "bc-signer-registry", - "bc-task-processor", - "bc-task-sender", - "cid", - "derive_more", - "env_logger", - "frame-support", - "futures 0.3.8", - "hex", - "ipfs-unixfs", - "itc-parentchain-light-client", - "itc-parentchain-test", - "itc-tls-websocket-server", - "itp-attestation-handler", - "itp-component-container", - "itp-extrinsics-factory", - "itp-import-queue", - "itp-node-api", - "itp-node-api-metadata", - "itp-node-api-metadata-provider", - "itp-nonce-cache", - "itp-ocall-api", - "itp-primitives-cache", - "itp-rpc", - "itp-settings", - "itp-sgx-crypto", - "itp-sgx-externalities", - "itp-sgx-temp-dir", - "itp-stf-interface", - "itp-stf-primitives", - "itp-stf-state-handler", - "itp-stf-state-observer", - "itp-storage", - "itp-test", - "itp-types", - "itp-utils", - "jsonrpc-core", - "lazy_static", - "lc-direct-call", - "litentry-hex-utils", - "litentry-macros", - "litentry-primitives", - "litentry-proc-macros", - "log 0.4.17", - "multibase", - "once_cell 1.4.0 (git+https://github.com/mesalock-linux/once_cell-sgx)", - "parity-scale-codec", - "primitive-types", - "rust-base58", - "rustls 0.19.0 (git+https://github.com/mesalock-linux/rustls?rev=sgx_1.1.3)", - "serde_json 1.0.60 (git+https://github.com/mesalock-linux/serde-json-sgx?tag=sgx_1.1.3)", - "sgx_crypto_helper", - "sgx_rand", - "sgx_serialize", - "sgx_serialize_derive", - "sgx_tcrypto", - "sgx_trts", - "sgx_tse", - "sgx_tseal", - "sgx_tstd", - "sgx_tunittest", - "sgx_types", - "sp-core", - "sp-runtime", - "url 2.5.0", - "webpki", -] - -[[package]] -name = "env_logger" -version = "0.9.0" -source = "git+https://github.com/integritee-network/env_logger-sgx#55745829b2ae8a77f0915af3671ec8a9a00cace9" -dependencies = [ - "humantime", - "log 0.4.17", - "regex 1.3.1", - "sgx_tstd", - "termcolor", -] - -[[package]] -name = "environmental" -version = "1.1.3" -dependencies = [ - "sgx_tstd", -] - -[[package]] -name = "environmental" -version = "1.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e48c92028aaa870e83d51c64e5d4e0b6981b360c522198c23959f219a4e1b15b" - -[[package]] -name = "equivalent" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5443807d6dff69373d433ab9ef5378ad8df50ca6298caf15de6e52e24aaf54d5" - -[[package]] -name = "ethbloom" -version = "0.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c22d4b5885b6aa2fe5e8b9329fb8d232bf739e434e6b87347c63bdd00c120f60" -dependencies = [ - "crunchy", - "fixed-hash", - "impl-codec", - "impl-rlp", - "scale-info", - "tiny-keccak", -] - -[[package]] -name = "ethereum" -version = "0.14.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6a89fb87a9e103f71b903b80b670200b54cc67a07578f070681f1fffb7396fb7" -dependencies = [ - "bytes 1.5.0", - "ethereum-types", - "hash-db 0.15.2", - "hash256-std-hasher", - "parity-scale-codec", - "rlp", - "scale-info", - "sha3 0.10.8", - "triehash", -] - -[[package]] -name = "ethereum-types" -version = "0.14.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "02d215cbf040552efcbe99a38372fe80ab9d00268e20012b79fcd0f073edd8ee" -dependencies = [ - "ethbloom", - "fixed-hash", - "impl-codec", - "impl-rlp", - "primitive-types", - "scale-info", - "uint", -] - -[[package]] -name = "evm" -version = "0.39.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a49a4e11987c51220aa89dbe1a5cc877f5079fa6864c0a5b4533331db44e9365" -dependencies = [ - "auto_impl", - "ethereum", - "evm-core", - "evm-gasometer", - "evm-runtime", - "log 0.4.21", - "parity-scale-codec", - "primitive-types", - "rlp", - "scale-info", - "sha3 0.10.8", -] - -[[package]] -name = "evm-core" -version = "0.39.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4f1f13264b044cb66f0602180f0bc781c29accb41ff560669a3ec15858d5b606" -dependencies = [ - "parity-scale-codec", - "primitive-types", - "scale-info", -] - -[[package]] -name = "evm-gasometer" -version = "0.39.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8d43eadc395bd1a52990787ca1495c26b0248165444912be075c28909a853b8c" -dependencies = [ - "evm-core", - "evm-runtime", - "primitive-types", -] - -[[package]] -name = "evm-runtime" -version = "0.39.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2aa5b32f59ec582a5651978004e5c784920291263b7dcb6de418047438e37f4f" -dependencies = [ - "auto_impl", - "evm-core", - "primitive-types", - "sha3 0.10.8", -] - -[[package]] -name = "expander" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f360349150728553f92e4c997a16af8915f418d3a0f21b440d34c5632f16ed84" -dependencies = [ - "blake2", - "fs-err", - "proc-macro2", - "quote 1.0.36", - "syn 1.0.109", -] - -[[package]] -name = "fake-simd" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e88a8acf291dafb59c2d96e8f59828f3838bb1a70398823ade51a84de6a6deed" - -[[package]] -name = "ff" -version = "0.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ded41244b729663b1e574f1b4fb731469f69f79c17667b5d776b16cda0479449" -dependencies = [ - "rand_core 0.6.4", - "subtle 2.4.1", -] - -[[package]] -name = "finality-grandpa" -version = "0.16.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "36530797b9bf31cd4ff126dcfee8170f86b00cfdcea3269d73133cc0415945c3" -dependencies = [ - "either", - "futures 0.3.28", - "num-traits 0.2.16", - "parity-scale-codec", - "scale-info", -] - -[[package]] -name = "fixed-hash" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "835c052cb0c08c1acf6ffd71c022172e18723949c8282f2b9f27efbc51e64534" -dependencies = [ - "byteorder 1.4.3", - "rustc-hex", - "static_assertions", -] - -[[package]] -name = "flagset" -version = "0.4.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b3ea1ec5f8307826a5b71094dd91fc04d4ae75d5709b20ad351c7fb4815c86ec" - -[[package]] -name = "fnv" -version = "1.0.6" -source = "git+https://github.com/mesalock-linux/rust-fnv-sgx#c3bd6153c1403c1fa32fa54be5544d91f5efb017" -dependencies = [ - "hashbrown 0.3.1", -] - -[[package]] -name = "fnv" -version = "1.0.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" - -[[package]] -name = "form_urlencoded" -version = "1.2.1" -source = "git+https://github.com/domenukk/rust-url?rev=316c868#316c8683206f3cb741163779bb30963fa05b3612" -dependencies = [ - "percent-encoding 2.3.1", -] - -[[package]] -name = "fp-account" -version = "1.0.0-dev" -source = "git+https://github.com/polkadot-evm/frontier?branch=bar/polkadot-v0.9.42#a5a5e1e6ec08cd542a6084c310863150fb8841b1" -dependencies = [ - "hex", - "libsecp256k1", - "log 0.4.21", - "parity-scale-codec", - "scale-info", - "sp-core", - "sp-io", - "sp-runtime", - "sp-std", -] - -[[package]] -name = "fp-evm" -version = "3.0.0-dev" -source = "git+https://github.com/polkadot-evm/frontier?branch=bar/polkadot-v0.9.42#a5a5e1e6ec08cd542a6084c310863150fb8841b1" -dependencies = [ - "evm", - "frame-support", - "parity-scale-codec", - "scale-info", - "sp-core", - "sp-runtime", - "sp-std", -] - -[[package]] -name = "frame-executive" -version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" -dependencies = [ - "frame-support", - "frame-system", - "parity-scale-codec", - "scale-info", - "sp-core", - "sp-io", - "sp-runtime", - "sp-std", - "sp-tracing", -] - -[[package]] -name = "frame-metadata" -version = "15.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "878babb0b136e731cc77ec2fd883ff02745ff21e6fb662729953d44923df009c" -dependencies = [ - "cfg-if 1.0.0", - "parity-scale-codec", - "scale-info", - "serde 1.0.204", -] - -[[package]] -name = "frame-support" -version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" -dependencies = [ - "bitflags", - "environmental 1.1.4", - "frame-metadata", - "frame-support-procedural", - "impl-trait-for-tuples", - "k256", - "log 0.4.21", - "parity-scale-codec", - "paste", - "scale-info", - "smallvec 1.11.1", - "sp-api", - "sp-arithmetic", - "sp-core", - "sp-core-hashing-proc-macro", - "sp-inherents", - "sp-io", - "sp-runtime", - "sp-staking", - "sp-std", - "sp-tracing", - "sp-weights", - "tt-call", -] - -[[package]] -name = "frame-support-procedural" -version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" -dependencies = [ - "Inflector", - "cfg-expr", - "derive-syn-parse", - "frame-support-procedural-tools", - "itertools 0.10.5", - "proc-macro-warning", - "proc-macro2", - "quote 1.0.36", - "syn 2.0.72", -] - -[[package]] -name = "frame-support-procedural-tools" -version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" -dependencies = [ - "frame-support-procedural-tools-derive", - "proc-macro-crate", - "proc-macro2", - "quote 1.0.36", - "syn 2.0.72", -] - -[[package]] -name = "frame-support-procedural-tools-derive" -version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" -dependencies = [ - "proc-macro2", - "quote 1.0.36", - "syn 2.0.72", -] - -[[package]] -name = "frame-system" -version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" -dependencies = [ - "frame-support", - "log 0.4.21", - "parity-scale-codec", - "scale-info", - "sp-core", - "sp-io", - "sp-runtime", - "sp-std", - "sp-version", - "sp-weights", -] - -[[package]] -name = "fs-err" -version = "2.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0845fa252299212f0389d64ba26f34fa32cfe41588355f21ed507c59a0f64541" - -[[package]] -name = "funty" -version = "2.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c" - -[[package]] -name = "futures" -version = "0.3.8" -source = "git+https://github.com/mesalock-linux/futures-rs-sgx#d54882f24ddf7d61327a067b2f608d6940a36444" -dependencies = [ - "futures-channel 0.3.8", - "futures-core 0.3.8", - "futures-executor", - "futures-io 0.3.8", - "futures-sink 0.3.8", - "futures-task 0.3.8", - "futures-util 0.3.8", - "sgx_tstd", -] - -[[package]] -name = "futures" -version = "0.3.28" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23342abe12aba583913b2e62f22225ff9c950774065e4bfb61a19cd9770fec40" -dependencies = [ - "futures-channel 0.3.28", - "futures-core 0.3.28", - "futures-io 0.3.28", - "futures-sink 0.3.28", - "futures-task 0.3.28", - "futures-util 0.3.28", -] - -[[package]] -name = "futures-channel" -version = "0.3.8" -source = "git+https://github.com/mesalock-linux/futures-rs-sgx#d54882f24ddf7d61327a067b2f608d6940a36444" -dependencies = [ - "futures-core 0.3.8", - "futures-sink 0.3.8", - "sgx_tstd", -] - -[[package]] -name = "futures-channel" -version = "0.3.28" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "955518d47e09b25bbebc7a18df10b81f0c766eaf4c4f1cccef2fca5f2a4fb5f2" -dependencies = [ - "futures-core 0.3.28", - "futures-sink 0.3.28", -] - -[[package]] -name = "futures-core" -version = "0.3.8" -source = "git+https://github.com/mesalock-linux/futures-rs-sgx#d54882f24ddf7d61327a067b2f608d6940a36444" -dependencies = [ - "sgx_tstd", -] - -[[package]] -name = "futures-core" -version = "0.3.28" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4bca583b7e26f571124fe5b7561d49cb2868d79116cfa0eefce955557c6fee8c" - -[[package]] -name = "futures-executor" -version = "0.3.8" -source = "git+https://github.com/mesalock-linux/futures-rs-sgx#d54882f24ddf7d61327a067b2f608d6940a36444" -dependencies = [ - "futures-core 0.3.8", - "futures-task 0.3.8", - "futures-util 0.3.8", - "sgx_tstd", -] - -[[package]] -name = "futures-io" -version = "0.3.8" -source = "git+https://github.com/mesalock-linux/futures-rs-sgx#d54882f24ddf7d61327a067b2f608d6940a36444" -dependencies = [ - "sgx_tstd", -] - -[[package]] -name = "futures-io" -version = "0.3.28" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4fff74096e71ed47f8e023204cfd0aa1289cd54ae5430a9523be060cdb849964" - -[[package]] -name = "futures-macro" -version = "0.3.8" -source = "git+https://github.com/mesalock-linux/futures-rs-sgx#d54882f24ddf7d61327a067b2f608d6940a36444" -dependencies = [ - "proc-macro-hack", - "proc-macro2", - "quote 1.0.36", - "syn 1.0.109", -] - -[[package]] -name = "futures-sink" -version = "0.3.8" -source = "git+https://github.com/mesalock-linux/futures-rs-sgx#d54882f24ddf7d61327a067b2f608d6940a36444" - -[[package]] -name = "futures-sink" -version = "0.3.28" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f43be4fe21a13b9781a69afa4985b0f6ee0e1afab2c6f454a8cf30e2b2237b6e" - -[[package]] -name = "futures-task" -version = "0.3.8" -source = "git+https://github.com/mesalock-linux/futures-rs-sgx#d54882f24ddf7d61327a067b2f608d6940a36444" -dependencies = [ - "once_cell 1.4.0 (git+https://github.com/mesalock-linux/once_cell-sgx)", - "sgx_tstd", -] - -[[package]] -name = "futures-task" -version = "0.3.28" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "76d3d132be6c0e6aa1534069c705a74a5997a356c0dc2f86a47765e5617c5b65" - -[[package]] -name = "futures-util" -version = "0.3.8" -source = "git+https://github.com/mesalock-linux/futures-rs-sgx#d54882f24ddf7d61327a067b2f608d6940a36444" -dependencies = [ - "futures-channel 0.3.8", - "futures-core 0.3.8", - "futures-io 0.3.8", - "futures-macro", - "futures-sink 0.3.8", - "futures-task 0.3.8", - "memchr 2.2.1", - "pin-project-lite", - "pin-utils", - "proc-macro-hack", - "proc-macro-nested", - "sgx_tstd", - "slab 0.4.2", -] - -[[package]] -name = "futures-util" -version = "0.3.28" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26b01e40b772d54cf6c6d721c1d1abd0647a0106a12ecaa1c186273392a69533" -dependencies = [ - "futures-core 0.3.28", - "futures-sink 0.3.28", - "futures-task 0.3.28", - "pin-project-lite", - "pin-utils", -] - -[[package]] -name = "generic-array" -version = "0.12.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ffdf9f34f1447443d37393cc6c2b8313aebddcd96906caf34e54c68d8e57d7bd" -dependencies = [ - "typenum", -] - -[[package]] -name = "generic-array" -version = "0.14.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" -dependencies = [ - "typenum", - "version_check", - "zeroize", -] - -[[package]] -name = "getrandom" -version = "0.1.14" -source = "git+https://github.com/mesalock-linux/getrandom-sgx#0aa9cc20c7dea713ccaac2c44430d625a395ebae" -dependencies = [ - "cfg-if 0.1.10", - "sgx_libc", - "sgx_trts", - "sgx_tstd", -] - -[[package]] -name = "getrandom" -version = "0.2.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "190092ea657667030ac6a35e305e62fc4dd69fd98ac98631e5d3a2b1575a12b5" -dependencies = [ - "cfg-if 1.0.0", - "libc", - "wasi", -] - -[[package]] -name = "group" -version = "0.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0f9ef7462f7c099f518d754361858f86d8a07af53ba9af0fe635bbccb151a63" -dependencies = [ - "ff", - "rand_core 0.6.4", - "subtle 2.4.1", -] - -[[package]] -name = "hash-db" -version = "0.15.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d23bd4e7b5eda0d0f3a307e8b381fdc8ba9000f26fbe912250c0a4cc3956364a" - -[[package]] -name = "hash-db" -version = "0.16.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e7d7786361d7425ae2fe4f9e407eb0efaa0840f5212d109cc018c40c35c6ab4" - -[[package]] -name = "hash256-std-hasher" -version = "0.15.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92c171d55b98633f4ed3860808f004099b36c1cc29c42cfc53aa8591b21efcf2" -dependencies = [ - "crunchy", -] - -[[package]] -name = "hashbrown" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "29fba9abe4742d586dfd0c06ae4f7e73a1c2d86b856933509b269d82cdf06e18" - -[[package]] -name = "hashbrown" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d7afe4a420e3fe79967a00898cc1f4db7c8a49a9333a29f8a4bd76a253d5cd04" - -[[package]] -name = "hashbrown" -version = "0.12.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" -dependencies = [ - "ahash 0.7.6", -] - -[[package]] -name = "hashbrown" -version = "0.13.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "43a3c133739dddd0d2990f9a4bdf8eb4b21ef50e4851ca85ab661199821d510e" -dependencies = [ - "ahash 0.8.3", -] - -[[package]] -name = "hashbrown" -version = "0.14.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2c6201b9ff9fd90a5a3bac2e56a830d0caa509576f0e503818ee82c181b3437a" - -[[package]] -name = "hashbrown_tstd" -version = "0.12.0" -source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#1b1d03376056321441ef99716aa0888bd5ef19f7" - -[[package]] -name = "heck" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8" - -[[package]] -name = "hex" -version = "0.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" - -[[package]] -name = "hex-conservative" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "30ed443af458ccb6d81c1e7e661545f94d3176752fb1df2f543b902a1e0f51e2" -dependencies = [ - "core2", -] - -[[package]] -name = "hex-literal" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6fe2267d4ed49bc07b63801559be28c718ea06c4738b7a03c94df7386d2cde46" - -[[package]] -name = "hex_lit" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3011d1213f159867b13cfd6ac92d2cd5f1345762c63be3554e84092d85a50bbd" - -[[package]] -name = "hmac" -version = "0.12.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" -dependencies = [ - "digest 0.10.7", -] - -[[package]] -name = "http" -version = "0.2.1" -source = "git+https://github.com/integritee-network/http-sgx.git?branch=sgx-experimental#307b5421fb7a489a114bede0dc05c8d32b804f49" -dependencies = [ - "bytes 1.0.1", - "fnv 1.0.6", - "itoa 0.4.5", - "sgx_tstd", -] - -[[package]] -name = "httparse" -version = "1.4.1" -source = "git+https://github.com/integritee-network/httparse-sgx?branch=sgx-experimental#cc97e4b34d2c44a1e3df5bdebef446b9771f5cc3" -dependencies = [ - "sgx_tstd", -] - -[[package]] -name = "humantime" -version = "1.3.0" -source = "git+https://github.com/mesalock-linux/humantime-sgx#c5243dfa36002c01adbc9aade288ead1b2c411cc" -dependencies = [ - "quick-error", - "sgx_tstd", -] - -[[package]] -name = "ident_case" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" - -[[package]] -name = "idna" -version = "0.2.0" -source = "git+https://github.com/mesalock-linux/rust-url-sgx?tag=sgx_1.1.3#23832f3191456c2d4a0faab10952e1747be58ca8" -dependencies = [ - "matches", - "sgx_tstd", - "unicode-bidi 0.3.4", - "unicode-normalization 0.1.12", -] - -[[package]] -name = "idna" -version = "0.5.0" -source = "git+https://github.com/domenukk/rust-url?rev=316c868#316c8683206f3cb741163779bb30963fa05b3612" -dependencies = [ - "unicode-bidi 0.3.15", - "unicode-normalization 0.1.23", -] - -[[package]] -name = "impl-codec" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba6a270039626615617f3f36d15fc827041df3b78c439da2cadfa47455a77f2f" -dependencies = [ - "parity-scale-codec", -] - -[[package]] -name = "impl-rlp" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f28220f89297a075ddc7245cd538076ee98b01f2a9c23a53a4f1105d5a322808" -dependencies = [ - "rlp", -] - -[[package]] -name = "impl-serde" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ebc88fc67028ae3db0c853baa36269d398d5f45b6982f95549ff5def78c935cd" -dependencies = [ - "serde 1.0.204", -] - -[[package]] -name = "impl-trait-for-tuples" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "11d7a9f6330b71fea57921c9b61c47ee6e84f72d394754eff6163ae67e7395eb" -dependencies = [ - "proc-macro2", - "quote 1.0.36", - "syn 1.0.109", -] - -[[package]] -name = "indexmap" -version = "1.6.1" -source = "git+https://github.com/mesalock-linux/indexmap-sgx#19f52458ba64dd7349a5d3a62227619a17e4db85" -dependencies = [ - "autocfg 1.1.0", - "hashbrown 0.9.1", - "sgx_tstd", -] - -[[package]] -name = "indexmap" -version = "2.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d5477fe2230a79769d8dc68e0eabf5437907c0457a5614a9e8dddb67f65eb65d" -dependencies = [ - "equivalent", - "hashbrown 0.14.0", -] - -[[package]] -name = "integer-sqrt" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "276ec31bcb4a9ee45f58bec6f9ec700ae4cf4f4f8f2fa7e06cb406bd5ffdd770" -dependencies = [ - "num-traits 0.2.16", -] - -[[package]] -name = "iovec" -version = "0.1.4" -source = "git+https://github.com/mesalock-linux/iovec-sgx#5c2f8e81925b4c06c556d856f3237461b00e27c9" -dependencies = [ - "sgx_libc", -] - -[[package]] -name = "ipfs-unixfs" -version = "0.0.1" -source = "git+https://github.com/whalelephant/rust-ipfs?branch=w-nstd#52f84dceea7065bb4ee2c24da53b3bedf162241a" -dependencies = [ - "cid", - "either", - "multihash", - "quick-protobuf", - "sha2 0.9.9", -] - -[[package]] -name = "itc-parentchain-light-client" -version = "0.1.0" -dependencies = [ - "finality-grandpa", - "itc-parentchain-test", - "itp-ocall-api", - "itp-sgx-io", - "itp-sgx-temp-dir", - "itp-storage", - "itp-test", - "itp-types", - "log 0.4.21", - "parity-scale-codec", - "sgx_tstd", - "sgx_types", - "sp-consensus-grandpa", - "sp-runtime", - "thiserror", -] - -[[package]] -name = "itc-parentchain-test" -version = "0.1.0" -dependencies = [ - "itp-types", - "sp-runtime", -] - -[[package]] -name = "itc-tls-websocket-server" -version = "0.1.0" -dependencies = [ - "bit-vec", - "chrono 0.4.31", - "log 0.4.21", - "mio", - "mio-extras", - "rcgen", - "rustls 0.19.0 (git+https://github.com/mesalock-linux/rustls?tag=sgx_1.1.3)", - "sgx_tstd", - "sp-core", - "thiserror", - "tungstenite", - "webpki", - "yasna", -] - -[[package]] -name = "itertools" -version = "0.10.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b0fd2260e829bddf4cb6ea802289de2f86d6a7a690192fbe91b3f46e0f2c8473" -dependencies = [ - "either", -] - -[[package]] -name = "itertools" -version = "0.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b1c173a5686ce8bfa551b3563d0c2170bf24ca44da99c7ca4bfdab5418c3fe57" -dependencies = [ - "either", -] - -[[package]] -name = "itoa" -version = "0.4.5" -source = "git+https://github.com/mesalock-linux/itoa-sgx#295ee451f5ec74f25c299552b481beb445ea3eb7" -dependencies = [ - "sgx_tstd", -] - -[[package]] -name = "itoa" -version = "1.0.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af150ab688ff2122fcef229be89cb50dd66af9e01a4ff320cc137eecc9bacc38" - -[[package]] -name = "itp-api-client-types" -version = "0.1.0" -dependencies = [ - "itp-types", - "parity-scale-codec", - "substrate-api-client", -] - -[[package]] -name = "itp-attestation-handler" -version = "0.8.0" -dependencies = [ - "arrayvec 0.7.4", - "base64 0.13.0 (git+https://github.com/mesalock-linux/rust-base64-sgx?rev=sgx_1.1.3)", - "bit-vec", - "chrono 0.4.11", - "hex", - "httparse", - "itertools 0.10.5", - "itp-ocall-api", - "itp-settings", - "itp-sgx-crypto", - "itp-sgx-io", - "itp-time-utils", - "log 0.4.21", - "num-bigint", - "parity-scale-codec", - "rustls 0.19.0 (git+https://github.com/mesalock-linux/rustls?tag=sgx_1.1.3)", - "serde_json 1.0.60 (git+https://github.com/mesalock-linux/serde-json-sgx?tag=sgx_1.1.3)", - "sgx_rand", - "sgx_tcrypto", - "sgx_tse", - "sgx_tstd", - "sgx_types", - "sp-core", - "thiserror", - "webpki", - "webpki-roots 0.21.0 (git+https://github.com/mesalock-linux/webpki-roots?branch=mesalock_sgx)", - "yasna", -] - -[[package]] -name = "itp-component-container" -version = "0.8.0" -dependencies = [ - "sgx_tstd", - "thiserror", -] - -[[package]] -name = "itp-enclave-metrics" -version = "0.1.0" -dependencies = [ - "litentry-primitives", - "parity-scale-codec", - "sgx_tstd", -] - -[[package]] -name = "itp-extrinsics-factory" -version = "0.1.0" -dependencies = [ - "hex", - "itp-node-api", - "itp-nonce-cache", - "itp-types", - "log 0.4.21", - "parity-scale-codec", - "sgx_tstd", - "sgx_types", - "sp-core", - "sp-runtime", - "substrate-api-client", - "thiserror", -] - -[[package]] -name = "itp-hashing" -version = "0.1.0" -dependencies = [ - "sp-core", -] - -[[package]] -name = "itp-import-queue" -version = "0.8.0" -dependencies = [ - "sgx_tstd", - "sgx_types", - "thiserror", -] - -[[package]] -name = "itp-node-api" -version = "0.1.0" -dependencies = [ - "itp-api-client-types", - "itp-node-api-metadata", - "itp-node-api-metadata-provider", -] - -[[package]] -name = "itp-node-api-metadata" -version = "0.1.0" -dependencies = [ - "derive_more", - "itp-api-client-types", - "itp-stf-primitives", - "parity-scale-codec", - "sp-core", - "sp-version", -] - -[[package]] -name = "itp-node-api-metadata-provider" -version = "0.1.0" -dependencies = [ - "itp-node-api-metadata", - "itp-stf-primitives", - "sgx_tstd", - "thiserror", -] - -[[package]] -name = "itp-nonce-cache" -version = "0.8.0" -dependencies = [ - "sgx_tstd", - "thiserror", -] - -[[package]] -name = "itp-ocall-api" -version = "0.1.0" -dependencies = [ - "derive_more", - "itp-api-client-types", - "itp-storage", - "itp-types", - "parity-scale-codec", - "sgx_types", - "sp-core", - "sp-runtime", - "sp-std", -] - -[[package]] -name = "itp-primitives-cache" -version = "0.1.0" -dependencies = [ - "lazy_static", - "sgx_tstd", - "thiserror", -] - -[[package]] -name = "itp-rpc" -version = "0.1.0" -dependencies = [ - "itp-types", - "parity-scale-codec", - "serde 1.0.204", - "serde_json 1.0.133", - "sgx_tstd", -] - -[[package]] -name = "itp-settings" -version = "0.1.0" -dependencies = [ - "litentry-primitives", -] - -[[package]] -name = "itp-sgx-crypto" -version = "0.1.0" -dependencies = [ - "aes", - "derive_more", - "hex", - "itp-sgx-io", - "itp-sgx-temp-dir", - "k256", - "log 0.4.21", - "ofb", - "parity-scale-codec", - "rand 0.7.3", - "ring 0.16.20", - "secp256k1 0.28.0", - "serde_json 1.0.60 (git+https://github.com/mesalock-linux/serde-json-sgx?tag=sgx_1.1.3)", - "sgx_crypto_helper", - "sgx_rand", - "sgx_tstd", - "sgx_types", - "sp-core", - "sp-std", -] - -[[package]] -name = "itp-sgx-externalities" -version = "0.1.0" -dependencies = [ - "derive_more", - "environmental 1.1.3", - "itp-hashing", - "log 0.4.21", - "parity-scale-codec", - "postcard", - "serde 1.0.204", - "sgx_tstd", - "sp-core", -] - -[[package]] -name = "itp-sgx-io" -version = "0.8.0" -dependencies = [ - "sgx_tstd", -] - -[[package]] -name = "itp-sgx-runtime-primitives" -version = "0.1.0" -dependencies = [ - "frame-system", - "pallet-balances", - "sp-core", - "sp-runtime", -] - -[[package]] -name = "itp-sgx-temp-dir" -version = "0.1.0" -dependencies = [ - "lazy_static", - "sgx_tstd", -] - -[[package]] -name = "itp-stf-interface" -version = "0.8.0" -dependencies = [ - "itp-node-api-metadata", - "itp-node-api-metadata-provider", - "itp-stf-primitives", - "itp-types", - "parity-scale-codec", -] - -[[package]] -name = "itp-stf-primitives" -version = "0.1.0" -dependencies = [ - "derive_more", - "itp-sgx-runtime-primitives", - "litentry-primitives", - "parity-scale-codec", - "sp-core", - "sp-runtime", - "sp-std", -] - -[[package]] -name = "itp-stf-state-handler" -version = "0.1.0" -dependencies = [ - "itp-hashing", - "itp-settings", - "itp-sgx-crypto", - "itp-sgx-externalities", - "itp-sgx-io", - "itp-sgx-temp-dir", - "itp-stf-interface", - "itp-stf-state-observer", - "itp-time-utils", - "itp-types", - "log 0.4.21", - "parity-scale-codec", - "rust-base58", - "sgx_tstd", - "sgx_types", - "sp-core", - "thiserror", -] - -[[package]] -name = "itp-stf-state-observer" -version = "0.1.0" -dependencies = [ - "itp-types", - "log 0.4.21", - "sgx_tstd", - "thiserror", -] - -[[package]] -name = "itp-storage" -version = "0.1.0" -dependencies = [ - "derive_more", - "frame-metadata", - "frame-support", - "hash-db 0.15.2", - "itp-types", - "parity-scale-codec", - "sgx_tstd", - "sp-core", - "sp-runtime", - "sp-std", - "sp-trie", - "thiserror", -] - -[[package]] -name = "itp-test" -version = "0.1.0" -dependencies = [ - "hex", - "itp-node-api", - "itp-node-api-metadata-provider", - "itp-ocall-api", - "itp-sgx-crypto", - "itp-sgx-externalities", - "itp-stf-interface", - "itp-stf-primitives", - "itp-stf-state-handler", - "itp-storage", - "itp-types", - "jsonrpc-core", - "lc-teebag-storage", - "litentry-primitives", - "log 0.4.21", - "parity-scale-codec", - "sgx_crypto_helper", - "sgx_tstd", - "sgx_types", - "sp-core", - "sp-io", - "sp-runtime", - "sp-std", -] - -[[package]] -name = "itp-time-utils" -version = "0.1.0" -dependencies = [ - "chrono 0.4.11", - "sgx_tstd", -] - -[[package]] -name = "itp-types" -version = "0.1.0" -dependencies = [ - "frame-system", - "itp-sgx-crypto", - "itp-sgx-runtime-primitives", - "itp-stf-primitives", - "itp-utils", - "litentry-primitives", - "pallet-balances", - "parity-scale-codec", - "serde 1.0.204", - "sp-consensus-grandpa", - "sp-core", - "sp-runtime", - "sp-std", - "substrate-api-client", -] - -[[package]] -name = "itp-utils" -version = "0.1.0" -dependencies = [ - "hex", - "litentry-hex-utils", - "parity-scale-codec", -] - -[[package]] -name = "jsonrpc-core" -version = "18.0.0" -source = "git+https://github.com/scs/jsonrpc?branch=no_std_v18#0faf53c491c3222b96242a973d902dd06e9b6674" -dependencies = [ - "futures 0.3.8", - "log 0.4.17", - "serde 1.0.118", - "serde_derive 1.0.118", - "serde_json 1.0.60 (git+https://github.com/mesalock-linux/serde-json-sgx)", -] - -[[package]] -name = "k256" -version = "0.13.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "956ff9b67e26e1a6a866cb758f12c6f8746208489e3e4a4b5580802f2f0a587b" -dependencies = [ - "cfg-if 1.0.0", - "ecdsa", - "elliptic-curve", - "sha2 0.10.7", - "signature", -] - -[[package]] -name = "keccak" -version = "0.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f6d5ed8676d904364de097082f4e7d240b571b67989ced0240f08b7f966f940" -dependencies = [ - "cpufeatures", -] - -[[package]] -name = "lazy_static" -version = "1.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" -dependencies = [ - "spin", -] - -[[package]] -name = "lazycell" -version = "1.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "830d08ce1d1d941e6b30645f1a0eb5643013d835ce3779a5fc208261dbe10f55" - -[[package]] -name = "lc-direct-call" -version = "0.1.0" -dependencies = [ - "bc-enclave-registry", - "bc-musig2-ceremony", - "bc-relayer-registry", - "bc-signer-registry", - "itp-sgx-crypto", - "itp-stf-primitives", - "litentry-primitives", - "log 0.4.21", - "parity-scale-codec", - "sgx_tstd", - "sp-core", - "sp-io", -] - -[[package]] -name = "lc-teebag-storage" -version = "0.1.0" -dependencies = [ - "itp-storage", - "itp-types", - "sp-std", -] - -[[package]] -name = "libc" -version = "0.2.152" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "13e3bf6590cbc649f4d1a3eefc9d5d6eb746f5200ffb04e5e142700b8faa56e7" - -[[package]] -name = "libsecp256k1" -version = "0.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "95b09eff1b35ed3b33b877ced3a691fc7a481919c7e29c53c906226fcf55e2a1" -dependencies = [ - "arrayref", - "base64 0.13.1", - "digest 0.9.0", - "libsecp256k1-core", - "libsecp256k1-gen-ecmult", - "libsecp256k1-gen-genmult", - "rand 0.8.5", - "serde 1.0.204", -] - -[[package]] -name = "libsecp256k1-core" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5be9b9bb642d8522a44d533eab56c16c738301965504753b03ad1de3425d5451" -dependencies = [ - "crunchy", - "digest 0.9.0", - "subtle 2.4.1", -] - -[[package]] -name = "libsecp256k1-gen-ecmult" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3038c808c55c87e8a172643a7d87187fc6c4174468159cb3090659d55bcb4809" -dependencies = [ - "libsecp256k1-core", -] - -[[package]] -name = "libsecp256k1-gen-genmult" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3db8d6ba2cec9eacc40e6e8ccc98931840301f1006e95647ceb2dd5c3aa06f7c" -dependencies = [ - "libsecp256k1-core", -] - -[[package]] -name = "linked-hash-map" -version = "0.5.2" -source = "git+https://github.com/mesalock-linux/linked-hash-map-sgx#03e763f7c251c16e0b85e2fb058ba47be52f2a49" -dependencies = [ - "sgx_tstd", -] - -[[package]] -name = "litentry-hex-utils" -version = "0.1.0" -dependencies = [ - "hex", -] - -[[package]] -name = "litentry-macros" -version = "0.1.0" - -[[package]] -name = "litentry-primitives" -version = "0.1.0" -dependencies = [ - "bitcoin", - "core-primitives", - "hex", - "itp-sgx-crypto", - "itp-sgx-runtime-primitives", - "log 0.4.21", - "parity-scale-codec", - "rand 0.7.3", - "ring 0.16.20", - "scale-info", - "secp256k1 0.28.0", - "serde 1.0.204", - "sgx_tstd", - "sp-core", - "sp-io", - "sp-runtime", - "sp-std", -] - -[[package]] -name = "litentry-proc-macros" -version = "0.1.0" -dependencies = [ - "cargo_toml", - "proc-macro2", - "quote 1.0.36", - "syn 2.0.72", -] - -[[package]] -name = "log" -version = "0.4.17" -source = "git+https://github.com/integritee-network/log-sgx#483383a9be3e2e900042eef9b6b2d0837411783f" -dependencies = [ - "cfg-if 1.0.0", - "sgx_tstd", -] - -[[package]] -name = "log" -version = "0.4.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "90ed8c1e510134f979dbc4f070f87d4313098b704861a105fe34231c70a3901c" - -[[package]] -name = "matches" -version = "0.1.8" -source = "git+https://github.com/mesalock-linux/rust-std-candidates-sgx#5747bcf37f3e18687758838da0339ff0f2c83924" - -[[package]] -name = "maybe-async" -version = "0.2.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0f1b8c13cb1f814b634a96b2c725449fe7ed464a7b8781de8688be5ffbd3f305" -dependencies = [ - "proc-macro2", - "quote 1.0.36", - "syn 1.0.109", -] - -[[package]] -name = "memchr" -version = "2.2.1" -source = "git+https://github.com/mesalock-linux/rust-memchr-sgx#fb51ee32766cb9a2be39b7fb2b5de26bb86dcdeb" -dependencies = [ - "sgx_libc", - "sgx_tstd", - "sgx_types", -] - -[[package]] -name = "memchr" -version = "2.6.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f232d6ef707e1956a43342693d2a31e72989554d58299d7a88738cc95b0d35c" - -[[package]] -name = "memoffset" -version = "0.6.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5aa361d4faea93603064a027415f07bd8e1d5c88c9fbf68bf56a285428fd79ce" -dependencies = [ - "autocfg 1.1.0", -] - -[[package]] -name = "memory-db" -version = "0.32.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "808b50db46293432a45e63bc15ea51e0ab4c0a1647b8eb114e31a3e698dd6fbe" -dependencies = [ - "hash-db 0.16.0", -] - -[[package]] -name = "merlin" -version = "2.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4e261cf0f8b3c42ded9f7d2bb59dea03aa52bc8a1cbc7482f9fc3fd1229d3b42" -dependencies = [ - "byteorder 1.4.3", - "keccak", - "rand_core 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)", - "zeroize", -] - -[[package]] -name = "mio" -version = "0.6.21" -source = "git+https://github.com/mesalock-linux/mio-sgx?tag=sgx_1.1.3#5b0e56a3066231c7a8d1876c7be3a19b08ffdfd5" -dependencies = [ - "iovec", - "log 0.4.17", - "net2", - "sgx_libc", - "sgx_trts", - "sgx_tstd", - "slab 0.4.2", -] - -[[package]] -name = "mio-extras" -version = "2.0.6" -source = "git+https://github.com/integritee-network/mio-extras-sgx?rev=963234b#963234bf55e44f9efff921938255126c48deef3a" -dependencies = [ - "lazycell", - "log 0.4.21", - "mio", - "sgx_tstd", - "sgx_types", - "slab 0.4.9", -] - -[[package]] -name = "multibase" -version = "0.8.0" -source = "git+https://github.com/whalelephant/rust-multibase?branch=nstd#df67fb30e86998f7c10d4eea16a1cd480d2448c0" -dependencies = [ - "base-x", - "data-encoding", - "lazy_static", -] - -[[package]] -name = "multihash" -version = "0.11.4" -source = "git+https://github.com/whalelephant/rust-multihash?branch=nstd#2c8aca8fa1fcbcba26951d925de40fa81696020a" -dependencies = [ - "blake2b_simd 0.5.11", - "blake2s_simd", - "digest 0.9.0", - "sha-1", - "sha2 0.9.9", - "sha3 0.9.1", - "unsigned-varint", -] - -[[package]] -name = "musig2" -version = "0.0.8" -source = "git+https://github.com/kailai-wang/musig2?branch=use-sha2-0.8#93857e52abbe8f9898c9ec743eecb1380132abcb" -dependencies = [ - "base16ct", - "hmac", - "k256", - "once_cell 1.4.0 (git+https://github.com/mesalock-linux/once_cell-sgx?branch=master)", - "secp", - "secp256k1 0.28.0", - "sgx_tstd", - "sha2 0.10.7", - "sha2_v08_wrapper", - "subtle 2.5.0", -] - -[[package]] -name = "net2" -version = "0.2.33" -source = "git+https://github.com/mesalock-linux/net2-rs-sgx#554583d15f3c9dff5d862a6ae64e227bb38fa729" -dependencies = [ - "cfg-if 0.1.10", - "sgx_libc", - "sgx_tstd", -] - -[[package]] -name = "no-std-net" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "43794a0ace135be66a25d3ae77d41b91615fb68ae937f904090203e81f755b65" - -[[package]] -name = "num" -version = "0.2.0" -source = "git+https://github.com/mesalock-linux/num-sgx#22645415542cc67551890dfdd34f4d5638b9ec78" -dependencies = [ - "num-bigint", - "num-complex", - "num-integer", - "num-iter", - "num-rational", - "num-traits 0.2.10", -] - -[[package]] -name = "num-bigint" -version = "0.2.5" -source = "git+https://github.com/mesalock-linux/num-bigint-sgx#76a5bed94dc31c32bd1670dbf72877abcf9bbc09" -dependencies = [ - "autocfg 1.1.0", - "num-integer", - "num-traits 0.2.10", - "sgx_tstd", -] - -[[package]] -name = "num-complex" -version = "0.2.3" -source = "git+https://github.com/mesalock-linux/num-complex-sgx#19700ad6de079ebc5560db472c282d1591e0d84f" -dependencies = [ - "autocfg 0.1.8", - "num-traits 0.2.10", - "sgx_tstd", -] - -[[package]] -name = "num-derive" -version = "0.3.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "876a53fff98e03a936a674b29568b0e605f06b29372c2489ff4de23f1949743d" -dependencies = [ - "proc-macro2", - "quote 1.0.36", - "syn 1.0.109", -] - -[[package]] -name = "num-integer" -version = "0.1.41" -source = "git+https://github.com/mesalock-linux/num-integer-sgx#404c50e5378ca635261688b080dee328ff42b6bd" -dependencies = [ - "autocfg 0.1.8", - "num-traits 0.2.10", - "sgx_tstd", -] - -[[package]] -name = "num-iter" -version = "0.1.39" -source = "git+https://github.com/mesalock-linux/num-iter-sgx#f19fc44fcad0b82a040e5a24c511e5049cc04b60" -dependencies = [ - "num-integer", - "num-traits 0.2.10", - "sgx_tstd", -] - -[[package]] -name = "num-rational" -version = "0.2.2" -source = "git+https://github.com/mesalock-linux/num-rational-sgx#be65f9ce439f3c9ec850d8041635ab6c3309b816" -dependencies = [ - "autocfg 0.1.8", - "num-bigint", - "num-integer", - "num-traits 0.2.10", - "sgx_tstd", -] - -[[package]] -name = "num-traits" -version = "0.2.10" -source = "git+https://github.com/mesalock-linux/num-traits-sgx#af046e0b15c594c960007418097dd4ff37ec3f7a" -dependencies = [ - "autocfg 0.1.8", - "sgx_tstd", -] - -[[package]] -name = "num-traits" -version = "0.2.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f30b0abd723be7e2ffca1272140fac1a2f084c77ec3e123c192b66af1ee9e6c2" -dependencies = [ - "autocfg 1.1.0", -] - -[[package]] -name = "ofb" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f5e609fc8b72da3dabd56427be9489d8a9f4bd2e4dc41660dd033c3c8e90b93c" -dependencies = [ - "cipher", -] - -[[package]] -name = "once_cell" -version = "1.4.0" -source = "git+https://github.com/mesalock-linux/once_cell-sgx?branch=master#cefcaa03fed4d85276b3235d875f1b45d399cc3c" -dependencies = [ - "sgx_tstd", -] - -[[package]] -name = "once_cell" -version = "1.4.0" -source = "git+https://github.com/mesalock-linux/once_cell-sgx#cefcaa03fed4d85276b3235d875f1b45d399cc3c" -dependencies = [ - "sgx_tstd", -] - -[[package]] -name = "once_cell" -version = "1.18.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dd8b5dd2ae5ed71462c540258bedcb51965123ad7e7ccf4b9a8cafaa4a63576d" - -[[package]] -name = "opaque-debug" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2839e79665f131bdb5782e51f2c6c9599c133c6098982a54c794358bf432529c" - -[[package]] -name = "opaque-debug" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "624a8340c38c1b80fd549087862da4ba43e08858af025b236e509b6649fc13d5" - -[[package]] -name = "pallet-balances" -version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" -dependencies = [ - "frame-support", - "frame-system", - "log 0.4.21", - "parity-scale-codec", - "scale-info", - "sp-runtime", - "sp-std", -] - -[[package]] -name = "pallet-evm" -version = "6.0.0-dev" -source = "git+https://github.com/polkadot-evm/frontier?branch=bar/polkadot-v0.9.42#a5a5e1e6ec08cd542a6084c310863150fb8841b1" -dependencies = [ - "evm", - "fp-account", - "fp-evm", - "frame-support", - "frame-system", - "hex", - "impl-trait-for-tuples", - "log 0.4.21", - "parity-scale-codec", - "rlp", - "scale-info", - "sp-core", - "sp-io", - "sp-runtime", - "sp-std", -] - -[[package]] -name = "pallet-parentchain" -version = "0.1.0" -dependencies = [ - "frame-support", - "frame-system", - "parity-scale-codec", - "scale-info", - "sp-core", - "sp-io", - "sp-runtime", -] - -[[package]] -name = "pallet-sudo" -version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" -dependencies = [ - "frame-support", - "frame-system", - "parity-scale-codec", - "scale-info", - "sp-io", - "sp-runtime", - "sp-std", -] - -[[package]] -name = "pallet-timestamp" -version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" -dependencies = [ - "frame-support", - "frame-system", - "log 0.4.21", - "parity-scale-codec", - "scale-info", - "sp-inherents", - "sp-runtime", - "sp-std", - "sp-timestamp", -] - -[[package]] -name = "pallet-transaction-payment" -version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" -dependencies = [ - "frame-support", - "frame-system", - "parity-scale-codec", - "scale-info", - "sp-core", - "sp-io", - "sp-runtime", - "sp-std", -] - -[[package]] -name = "parity-scale-codec" -version = "3.6.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dd8e946cc0cc711189c0b0249fb8b599cbeeab9784d83c415719368bb8d4ac64" -dependencies = [ - "arrayvec 0.7.4", - "bitvec", - "byte-slice-cast", - "bytes 1.5.0", - "impl-trait-for-tuples", - "parity-scale-codec-derive", - "serde 1.0.204", -] - -[[package]] -name = "parity-scale-codec-derive" -version = "3.6.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "312270ee71e1cd70289dacf597cab7b207aa107d2f28191c2ae45b2ece18a260" -dependencies = [ - "proc-macro-crate", - "proc-macro2", - "quote 1.0.36", - "syn 1.0.109", -] - -[[package]] -name = "paste" -version = "1.0.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "de3145af08024dea9fa9914f381a17b8fc6034dfb00f3a84013f7ff43f29ed4c" - -[[package]] -name = "pem" -version = "0.8.2" -source = "git+https://github.com/mesalock-linux/pem-rs-sgx#fdfef4f24a9fb3fa72e8a71bb28bd8ff15feff2f" -dependencies = [ - "base64 0.13.0 (git+https://github.com/mesalock-linux/rust-base64-sgx)", - "once_cell 1.4.0 (git+https://github.com/mesalock-linux/once_cell-sgx)", - "regex 1.3.1", - "sgx_tstd", -] - -[[package]] -name = "percent-encoding" -version = "2.1.0" -source = "git+https://github.com/mesalock-linux/rust-url-sgx?tag=sgx_1.1.3#23832f3191456c2d4a0faab10952e1747be58ca8" - -[[package]] -name = "percent-encoding" -version = "2.3.1" -source = "git+https://github.com/domenukk/rust-url?rev=316c868#316c8683206f3cb741163779bb30963fa05b3612" - -[[package]] -name = "pin-project-lite" -version = "0.2.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8afb450f006bf6385ca15ef45d71d2288452bc3683ce2e2cacc0d18e4be60b58" - -[[package]] -name = "pin-utils" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" - -[[package]] -name = "pkcs8" -version = "0.10.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" -dependencies = [ - "der 0.7.8", - "spki 0.7.3", -] - -[[package]] -name = "postcard" -version = "0.7.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a25c0b0ae06fcffe600ad392aabfa535696c8973f2253d9ac83171924c58a858" -dependencies = [ - "postcard-cobs", - "serde 1.0.204", -] - -[[package]] -name = "postcard-cobs" -version = "0.1.5-pre" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7c68cb38ed13fd7bc9dd5db8f165b7c8d9c1a315104083a2b10f11354c2af97f" - -[[package]] -name = "ppv-lite86" -version = "0.2.6" -source = "git+https://github.com/mesalock-linux/cryptocorrosion-sgx#32d7de50b5f03a10fe5a42167410be2dd3c2e389" - -[[package]] -name = "primitive-types" -version = "0.12.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9f3486ccba82358b11a77516035647c34ba167dfa53312630de83b12bd4f3d66" -dependencies = [ - "fixed-hash", - "impl-codec", - "impl-rlp", - "impl-serde", - "scale-info", - "uint", -] - -[[package]] -name = "proc-macro-crate" -version = "1.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f4c021e1093a56626774e81216a4ce732a735e5bad4868a03f3ed65ca0c3919" -dependencies = [ - "once_cell 1.18.0", - "toml_edit 0.19.15", -] - -[[package]] -name = "proc-macro-error" -version = "1.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c" -dependencies = [ - "proc-macro-error-attr", - "proc-macro2", - "quote 1.0.36", - "syn 1.0.109", - "version_check", -] - -[[package]] -name = "proc-macro-error-attr" -version = "1.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869" -dependencies = [ - "proc-macro2", - "quote 1.0.36", - "version_check", -] - -[[package]] -name = "proc-macro-hack" -version = "0.5.20+deprecated" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc375e1527247fe1a97d8b7156678dfe7c1af2fc075c9a4db3690ecd2a148068" - -[[package]] -name = "proc-macro-nested" -version = "0.1.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bc881b2c22681370c6a780e47af9840ef841837bc98118431d4e1868bd0c1086" - -[[package]] -name = "proc-macro-warning" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0e99670bafb56b9a106419397343bdbc8b8742c3cc449fec6345f86173f47cd4" -dependencies = [ - "proc-macro2", - "quote 1.0.36", - "syn 2.0.72", -] - -[[package]] -name = "proc-macro2" -version = "1.0.86" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e719e8df665df0d1c8fbfd238015744736151d4445ec0836b8e628aae103b77" -dependencies = [ - "unicode-ident", -] - -[[package]] -name = "ptr_meta" -version = "0.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0738ccf7ea06b608c10564b31debd4f5bc5e197fc8bfe088f68ae5ce81e7a4f1" -dependencies = [ - "ptr_meta_derive", -] - -[[package]] -name = "ptr_meta_derive" -version = "0.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "16b845dbfca988fa33db069c0e230574d15a3088f147a87b64c7589eb662c9ac" -dependencies = [ - "proc-macro2", - "quote 1.0.36", - "syn 1.0.109", -] - -[[package]] -name = "quick-error" -version = "1.2.2" -source = "git+https://github.com/mesalock-linux/quick-error-sgx#468bf2cce746f34dd3df8c1c5b4a5a6494914d36" - -[[package]] -name = "quick-protobuf" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e489d4a83c17ea69b0291630229b5d4c92a94a3bf0165f7f72f506e94cda8b4b" -dependencies = [ - "byteorder 1.4.3", -] - -[[package]] -name = "quote" -version = "0.3.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a6e920b65c65f10b2ae65c831a81a073a89edd28c7cce89475bff467ab4167a" - -[[package]] -name = "quote" -version = "1.0.36" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0fa76aaf39101c457836aec0ce2316dbdc3ab723cdda1c6bd4e6ad4208acaca7" -dependencies = [ - "proc-macro2", -] - -[[package]] -name = "radium" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc33ff2d4973d518d823d61aa239014831e521c75da58e3df4840d3f47749d09" - -[[package]] -name = "rand" -version = "0.7.3" -source = "git+https://github.com/mesalock-linux/rand-sgx?tag=sgx_1.1.3#83583f073de3b4f75c3c3ef5e174d484ed941f85" -dependencies = [ - "getrandom 0.1.14", - "rand_chacha", - "rand_core 0.5.1 (git+https://github.com/mesalock-linux/rand-sgx?tag=sgx_1.1.3)", - "sgx_tstd", -] - -[[package]] -name = "rand" -version = "0.8.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404" -dependencies = [ - "rand_core 0.6.4", -] - -[[package]] -name = "rand_chacha" -version = "0.2.2" -source = "git+https://github.com/mesalock-linux/rand-sgx?tag=sgx_1.1.3#83583f073de3b4f75c3c3ef5e174d484ed941f85" -dependencies = [ - "ppv-lite86", - "rand_core 0.5.1 (git+https://github.com/mesalock-linux/rand-sgx?tag=sgx_1.1.3)", - "sgx_tstd", -] - -[[package]] -name = "rand_core" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "90bde5296fc891b0cef12a6d03ddccc162ce7b2aff54160af9338f8d40df6d19" - -[[package]] -name = "rand_core" -version = "0.5.1" -source = "git+https://github.com/mesalock-linux/rand-sgx?tag=sgx_1.1.3#83583f073de3b4f75c3c3ef5e174d484ed941f85" -dependencies = [ - "getrandom 0.1.14", - "sgx_tstd", -] - -[[package]] -name = "rand_core" -version = "0.6.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" - -[[package]] -name = "rcgen" -version = "0.9.2" -source = "git+https://github.com/integritee-network/rcgen#1852c8dbeb74de36a422d218254b659497daf717" -dependencies = [ - "chrono 0.4.11", - "pem", - "ring 0.16.19", - "sgx_tstd", - "yasna", -] - -[[package]] -name = "ref-cast" -version = "1.0.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "acde58d073e9c79da00f2b5b84eed919c8326832648a5b109b3fce1bb1175280" -dependencies = [ - "ref-cast-impl", -] - -[[package]] -name = "ref-cast-impl" -version = "1.0.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f7473c2cfcf90008193dd0e3e16599455cb601a9fce322b5bb55de799664925" -dependencies = [ - "proc-macro2", - "quote 1.0.36", - "syn 2.0.72", -] - -[[package]] -name = "regex" -version = "1.3.1" -source = "git+https://github.com/mesalock-linux/regex-sgx#76aef86f9836532d17764523d0fa23bb7d2e31cf" -dependencies = [ - "aho-corasick 0.7.10", - "memchr 2.2.1", - "regex-syntax 0.6.12", - "sgx_tstd", - "thread_local", -] - -[[package]] -name = "regex" -version = "1.9.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "697061221ea1b4a94a624f67d0ae2bfe4e22b8a17b6a192afb11046542cc8c47" -dependencies = [ - "aho-corasick 1.1.1", - "memchr 2.6.3", - "regex-automata", - "regex-syntax 0.7.5", -] - -[[package]] -name = "regex-automata" -version = "0.3.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c2f401f4955220693b56f8ec66ee9c78abffd8d1c4f23dc41a23839eb88f0795" -dependencies = [ - "aho-corasick 1.1.1", - "memchr 2.6.3", - "regex-syntax 0.7.5", -] - -[[package]] -name = "regex-syntax" -version = "0.6.12" -source = "git+https://github.com/mesalock-linux/regex-sgx#76aef86f9836532d17764523d0fa23bb7d2e31cf" -dependencies = [ - "sgx_tstd", -] - -[[package]] -name = "regex-syntax" -version = "0.7.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dbb5fb1acd8a1a18b3dd5be62d25485eb770e05afb408a9627d14d451bae12da" - -[[package]] -name = "rfc6979" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8dd2a808d456c4a54e300a23e9f5a67e122c3024119acbfd73e3bf664491cb2" -dependencies = [ - "hmac", - "subtle 2.4.1", -] - -[[package]] -name = "ring" -version = "0.16.19" -source = "git+https://github.com/mesalock-linux/ring-sgx?tag=v0.16.5#844efe271ed78a399d803b2579f5f2424d543c9f" -dependencies = [ - "cc", - "sgx_tstd", - "spin", - "untrusted 0.7.1", -] - -[[package]] -name = "ring" -version = "0.16.20" -source = "git+https://github.com/betrusted-io/ring-xous?branch=0.16.20-cleanup#4296c2e7904898766cf7d8d589759a129794783b" -dependencies = [ - "cc", - "libc", - "log 0.4.21", - "once_cell 1.18.0", - "rkyv", - "spin", - "untrusted 0.7.1", - "winapi", - "xous", - "xous-api-names", - "xous-ipc", -] - -[[package]] -name = "rkyv" -version = "0.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "70de01b38fe7baba4ecdd33b777096d2b326993d8ea99bc5b6ede691883d3010" -dependencies = [ - "memoffset", - "ptr_meta", - "rkyv_derive", -] - -[[package]] -name = "rkyv_derive" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "95a169f6bc5a81033e86ed39d0f4150e2608160b73d2b93c6e8e6a3efa873f14" -dependencies = [ - "proc-macro2", - "quote 1.0.36", - "syn 1.0.109", -] - -[[package]] -name = "rlp" -version = "0.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb919243f34364b6bd2fc10ef797edbfa75f33c252e7998527479c6d6b47e1ec" -dependencies = [ - "bytes 1.5.0", - "rlp-derive", - "rustc-hex", -] - -[[package]] -name = "rlp-derive" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e33d7b2abe0c340d8797fe2907d3f20d3b5ea5908683618bfe80df7f621f672a" -dependencies = [ - "proc-macro2", - "quote 1.0.36", - "syn 1.0.109", -] - -[[package]] -name = "rust-base58" -version = "0.0.4" -source = "git+https://github.com/mesalock-linux/rust-base58-sgx?rev=sgx_1.1.3#13fb3e0a543690e6e19332f37ba85fd74c56cb2f" -dependencies = [ - "num", - "sgx_tstd", -] - -[[package]] -name = "rustc-hex" -version = "2.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e75f6a532d0fd9f7f13144f392b6ad56a32696bfcd9c78f797f16bbb6f072d6" - -[[package]] -name = "rustc_version" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bfa0f585226d2e68097d4f95d113b15b83a82e819ab25717ec0590d9584ef366" -dependencies = [ - "semver", -] - -[[package]] -name = "rustls" -version = "0.19.0" -source = "git+https://github.com/mesalock-linux/rustls?tag=sgx_1.1.3#95b5e79dc24b02f3ce424437eb9698509d0baf58" -dependencies = [ - "base64 0.13.0 (git+https://github.com/mesalock-linux/rust-base64-sgx)", - "log 0.4.17", - "ring 0.16.19", - "sct", - "sgx_tstd", - "webpki", -] - -[[package]] -name = "rustls" -version = "0.19.0" -source = "git+https://github.com/mesalock-linux/rustls?rev=sgx_1.1.3#95b5e79dc24b02f3ce424437eb9698509d0baf58" -dependencies = [ - "base64 0.13.0 (git+https://github.com/mesalock-linux/rust-base64-sgx)", - "log 0.4.17", - "ring 0.16.19", - "sct", - "sgx_tstd", - "webpki", -] - -[[package]] -name = "rustls-pki-types" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a47003264dea418db67060fa420ad16d0d2f8f0a0360d825c00e177ac52cb5d8" - -[[package]] -name = "rustls-webpki" -version = "0.102.0-alpha.3" -source = "git+https://github.com/rustls/webpki?rev=da923ed#da923edaab56f599971e58773617fb574cd019dc" -dependencies = [ - "ring 0.16.20", - "rustls-pki-types", - "untrusted 0.9.0", -] - -[[package]] -name = "rustversion" -version = "1.0.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ffc183a10b4478d04cbbbfc96d0873219d962dd5accaff2ffbd4ceb7df837f4" - -[[package]] -name = "ryu" -version = "1.0.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ad4cc8da4ef723ed60bced201181d83791ad433213d8c24efffda1eec85d741" - -[[package]] -name = "scale-bits" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "036575c29af9b6e4866ffb7fa055dbf623fe7a9cc159b33786de6013a6969d89" -dependencies = [ - "parity-scale-codec", - "scale-info", - "serde 1.0.204", -] - -[[package]] -name = "scale-decode" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea509715113edab351e1f4d51fba6b186653259049a1155b52e2e994dd2f0e6d" -dependencies = [ - "parity-scale-codec", - "primitive-types", - "scale-bits", - "scale-decode-derive", - "scale-info", - "smallvec 1.11.1", -] - -[[package]] -name = "scale-decode-derive" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "66c9d7a1341497e9d016722144310de3dc6c933909c0376017c88f65092fff37" -dependencies = [ - "darling", - "proc-macro-crate", - "proc-macro2", - "quote 1.0.36", - "syn 1.0.109", -] - -[[package]] -name = "scale-encode" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f6f51bc8cd927dab2f4567b1a8a8e9d7fd5d0866f2dbc7c84fc97cfa9383a26" -dependencies = [ - "parity-scale-codec", - "primitive-types", - "scale-bits", - "scale-encode-derive", - "scale-info", - "smallvec 1.11.1", -] - -[[package]] -name = "scale-encode-derive" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f28be1877787156a2df01be3c029b92bdffa6b6a9748d4996e383fff218c88f3" -dependencies = [ - "darling", - "proc-macro-crate", - "proc-macro2", - "quote 1.0.36", - "syn 1.0.109", -] - -[[package]] -name = "scale-info" -version = "2.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2ef2175c2907e7c8bc0a9c3f86aeb5ec1f3b275300ad58a44d0c3ae379a5e52e" -dependencies = [ - "bitvec", - "cfg-if 1.0.0", - "derive_more", - "parity-scale-codec", - "scale-info-derive", - "serde 1.0.204", -] - -[[package]] -name = "scale-info-derive" -version = "2.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "abf2c68b89cafb3b8d918dd07b42be0da66ff202cf1155c5739a4e0c1ea0dc19" -dependencies = [ - "proc-macro-crate", - "proc-macro2", - "quote 1.0.36", - "syn 1.0.109", -] - -[[package]] -name = "schnorrkel" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "021b403afe70d81eea68f6ea12f6b3c9588e5d536a94c3bf80f15e7faa267862" -dependencies = [ - "arrayref", - "arrayvec 0.5.2", - "curve25519-dalek 2.1.3", - "merlin", - "rand_core 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)", - "sha2 0.8.2", - "subtle 2.4.1", - "zeroize", -] - -[[package]] -name = "sct" -version = "0.6.0" -source = "git+https://github.com/mesalock-linux/sct.rs?branch=mesalock_sgx#c4d859cca232e6c9d88ca12048df3bc26e1ed4ad" -dependencies = [ - "ring 0.16.19", - "sgx_tstd", - "untrusted 0.7.1", -] - -[[package]] -name = "sec1" -version = "0.7.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3e97a565f76233a6003f9f5c54be1d9c5bdfa3eccfb189469f11ec4901c47dc" -dependencies = [ - "base16ct", - "der 0.7.8", - "generic-array 0.14.7", - "pkcs8", - "subtle 2.4.1", - "zeroize", -] - -[[package]] -name = "secp" -version = "0.2.3" -source = "git+https://github.com/kziemianek/secp.git?branch=sgx#0479a3b12fc204015cdb63c138078fefe7e32341" -dependencies = [ - "base16ct", - "k256", - "once_cell 1.4.0 (git+https://github.com/mesalock-linux/once_cell-sgx?branch=master)", - "secp256k1 0.28.0", - "sgx_tstd", - "subtle 2.5.0", -] - -[[package]] -name = "secp256k1" -version = "0.24.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6b1629c9c557ef9b293568b338dddfc8208c98a18c59d722a9d53f859d9c9b62" -dependencies = [ - "secp256k1-sys 0.6.1", -] - -[[package]] -name = "secp256k1" -version = "0.28.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2acea373acb8c21ecb5a23741452acd2593ed44ee3d343e72baaa143bc89d0d5" -dependencies = [ - "bitcoin_hashes", - "secp256k1-sys 0.9.1", -] - -[[package]] -name = "secp256k1-sys" -version = "0.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "83080e2c2fc1006e625be82e5d1eb6a43b7fd9578b617fcc55814daf286bba4b" -dependencies = [ - "cc", -] - -[[package]] -name = "secp256k1-sys" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4dd97a086ec737e30053fd5c46f097465d25bb81dd3608825f65298c4c98be83" -dependencies = [ - "cc", -] - -[[package]] -name = "secrecy" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9bd1c54ea06cfd2f6b63219704de0b9b4f72dcc2b8fdef820be6cd799780e91e" -dependencies = [ - "zeroize", -] - -[[package]] -name = "semver" -version = "1.0.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b0293b4b29daaf487284529cc2f5675b8e57c61f70167ba415a463651fd6a918" - -[[package]] -name = "serde" -version = "1.0.118" -source = "git+https://github.com/mesalock-linux/serde-sgx#db0226f1d5d70fca6b96af2c285851502204e21c" -dependencies = [ - "serde_derive 1.0.118", - "sgx_tstd", -] - -[[package]] -name = "serde" -version = "1.0.204" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bc76f558e0cbb2a839d37354c575f1dc3fdc6546b5be373ba43d95f231bf7c12" -dependencies = [ - "serde_derive 1.0.204", -] - -[[package]] -name = "serde-big-array" -version = "0.3.0" -source = "git+https://github.com/mesalock-linux/serde-big-array-sgx#94122c5167aee38b39b09a620a60db2c28cf7428" -dependencies = [ - "serde 1.0.118", - "serde_derive 1.0.118", -] - -[[package]] -name = "serde_derive" -version = "1.0.118" -source = "git+https://github.com/mesalock-linux/serde-sgx#db0226f1d5d70fca6b96af2c285851502204e21c" -dependencies = [ - "proc-macro2", - "quote 1.0.36", - "syn 1.0.109", -] - -[[package]] -name = "serde_derive" -version = "1.0.204" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e0cd7e117be63d3c3678776753929474f3b04a43a080c744d6b0ae2a8c28e222" -dependencies = [ - "proc-macro2", - "quote 1.0.36", - "syn 2.0.72", -] - -[[package]] -name = "serde_json" -version = "1.0.60" -source = "git+https://github.com/mesalock-linux/serde-json-sgx?tag=sgx_1.1.3#380893814ad2a057758d825bab798aa117f7362a" -dependencies = [ - "indexmap 1.6.1", - "itoa 0.4.5", - "ryu", - "serde 1.0.118", - "sgx_tstd", -] - -[[package]] -name = "serde_json" -version = "1.0.60" -source = "git+https://github.com/mesalock-linux/serde-json-sgx#380893814ad2a057758d825bab798aa117f7362a" -dependencies = [ - "itoa 0.4.5", - "ryu", - "serde 1.0.118", - "sgx_tstd", -] - -[[package]] -name = "serde_json" -version = "1.0.133" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c7fceb2473b9166b2294ef05efcb65a3db80803f0b03ef86a5fc88a2b85ee377" -dependencies = [ - "itoa 1.0.9", - "memchr 2.6.3", - "ryu", - "serde 1.0.204", -] - -[[package]] -name = "serde_spanned" -version = "0.6.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "96426c9936fd7a0124915f9185ea1d20aa9445cc9821142f0a73bc9207a2e186" -dependencies = [ - "serde 1.0.204", -] - -[[package]] -name = "sgx_alloc" -version = "1.1.6" -source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#1b1d03376056321441ef99716aa0888bd5ef19f7" - -[[package]] -name = "sgx_backtrace_sys" -version = "1.1.6" -source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#1b1d03376056321441ef99716aa0888bd5ef19f7" -dependencies = [ - "cc", - "sgx_build_helper", - "sgx_libc", -] - -[[package]] -name = "sgx_build_helper" -version = "1.1.6" -source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#1b1d03376056321441ef99716aa0888bd5ef19f7" - -[[package]] -name = "sgx_crypto_helper" -version = "1.1.6" -source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#3c903bdac4e503dd27b9b1f761c4abfc55f2464c" -dependencies = [ - "itertools 0.11.0", - "serde 1.0.118", - "serde-big-array", - "serde_derive 1.0.118", - "sgx_tcrypto", - "sgx_tstd", - "sgx_types", -] - -[[package]] -name = "sgx_demangle" -version = "1.1.6" -source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#1b1d03376056321441ef99716aa0888bd5ef19f7" - -[[package]] -name = "sgx_libc" -version = "1.1.6" -source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#1b1d03376056321441ef99716aa0888bd5ef19f7" -dependencies = [ - "sgx_types", -] - -[[package]] -name = "sgx_rand" -version = "1.1.6" -source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#3c903bdac4e503dd27b9b1f761c4abfc55f2464c" -dependencies = [ - "sgx_trts", - "sgx_tstd", - "sgx_types", -] - -[[package]] -name = "sgx_serialize" -version = "1.1.6" -source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#3c903bdac4e503dd27b9b1f761c4abfc55f2464c" -dependencies = [ - "sgx_tstd", -] - -[[package]] -name = "sgx_serialize_derive" -version = "1.1.6" -source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#3c903bdac4e503dd27b9b1f761c4abfc55f2464c" -dependencies = [ - "quote 0.3.15", - "sgx_serialize_derive_internals", - "syn 0.11.11", -] - -[[package]] -name = "sgx_serialize_derive_internals" -version = "1.1.6" -source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#3c903bdac4e503dd27b9b1f761c4abfc55f2464c" -dependencies = [ - "syn 0.11.11", -] - -[[package]] -name = "sgx_tcrypto" -version = "1.1.6" -source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#3c903bdac4e503dd27b9b1f761c4abfc55f2464c" -dependencies = [ - "sgx_types", -] - -[[package]] -name = "sgx_tprotected_fs" -version = "1.1.6" -source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#1b1d03376056321441ef99716aa0888bd5ef19f7" -dependencies = [ - "sgx_trts", - "sgx_types", -] - -[[package]] -name = "sgx_trts" -version = "1.1.6" -source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#3c903bdac4e503dd27b9b1f761c4abfc55f2464c" -dependencies = [ - "sgx_libc", - "sgx_types", -] - -[[package]] -name = "sgx_tse" -version = "1.1.6" -source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#3c903bdac4e503dd27b9b1f761c4abfc55f2464c" -dependencies = [ - "sgx_types", -] - -[[package]] -name = "sgx_tseal" -version = "1.1.6" -source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#3c903bdac4e503dd27b9b1f761c4abfc55f2464c" -dependencies = [ - "sgx_tcrypto", - "sgx_trts", - "sgx_tse", - "sgx_types", -] - -[[package]] -name = "sgx_tstd" -version = "1.1.6" -source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#3c903bdac4e503dd27b9b1f761c4abfc55f2464c" -dependencies = [ - "hashbrown_tstd", - "sgx_alloc", - "sgx_backtrace_sys", - "sgx_demangle", - "sgx_libc", - "sgx_tprotected_fs", - "sgx_trts", - "sgx_types", - "sgx_unwind", -] - -[[package]] -name = "sgx_tunittest" -version = "1.1.6" -source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#3c903bdac4e503dd27b9b1f761c4abfc55f2464c" -dependencies = [ - "sgx_tstd", -] - -[[package]] -name = "sgx_types" -version = "1.1.6" -source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#3c903bdac4e503dd27b9b1f761c4abfc55f2464c" - -[[package]] -name = "sgx_unwind" -version = "1.1.6" -source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#1b1d03376056321441ef99716aa0888bd5ef19f7" -dependencies = [ - "sgx_build_helper", -] - -[[package]] -name = "sha-1" -version = "0.9.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "99cd6713db3cf16b6c84e06321e049a9b9f699826e16096d23bbcc44d15d51a6" -dependencies = [ - "block-buffer 0.9.0", - "cfg-if 1.0.0", - "cpufeatures", - "digest 0.9.0", - "opaque-debug 0.3.0", -] - -[[package]] -name = "sha1" -version = "0.6.0" -source = "git+https://github.com/mesalock-linux/rust-sha1-sgx?tag=sgx_1.1.3#482a4d489e860d63a21662aaea988f600f8e20a4" -dependencies = [ - "sgx_tstd", -] - -[[package]] -name = "sha2" -version = "0.8.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a256f46ea78a0c0d9ff00077504903ac881a1dafdc20da66545699e7776b3e69" -dependencies = [ - "block-buffer 0.7.3", - "digest 0.8.1", - "fake-simd", - "opaque-debug 0.2.3", -] - -[[package]] -name = "sha2" -version = "0.9.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4d58a1e1bf39749807d89cf2d98ac2dfa0ff1cb3faa38fbb64dd88ac8013d800" -dependencies = [ - "block-buffer 0.9.0", - "cfg-if 1.0.0", - "cpufeatures", - "digest 0.9.0", - "opaque-debug 0.3.0", -] - -[[package]] -name = "sha2" -version = "0.10.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "479fb9d862239e610720565ca91403019f2f00410f1864c5aa7479b950a76ed8" -dependencies = [ - "cfg-if 1.0.0", - "cpufeatures", - "digest 0.10.7", -] - -[[package]] -name = "sha2_v08_wrapper" -version = "0.1.0" -source = "git+https://github.com/kailai-wang/sha2_v08#c41176becc675e84cd708e8b18ba2cd0c9cf8eb0" -dependencies = [ - "sha2 0.8.2", -] - -[[package]] -name = "sha3" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f81199417d4e5de3f04b1e871023acea7389672c4135918f05aa9cbf2f2fa809" -dependencies = [ - "block-buffer 0.9.0", - "digest 0.9.0", - "keccak", - "opaque-debug 0.3.0", -] - -[[package]] -name = "sha3" -version = "0.10.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "75872d278a8f37ef87fa0ddbda7802605cb18344497949862c0d4dcb291eba60" -dependencies = [ - "digest 0.10.7", - "keccak", -] - -[[package]] -name = "signature" -version = "2.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e1788eed21689f9cf370582dfc467ef36ed9c707f073528ddafa8d83e3b8500" -dependencies = [ - "digest 0.10.7", - "rand_core 0.6.4", -] - -[[package]] -name = "slab" -version = "0.4.2" -source = "git+https://github.com/mesalock-linux/slab-sgx#0b0e6ec2abd588afd2f40fd082bc473d100d0f40" -dependencies = [ - "sgx_tstd", -] - -[[package]] -name = "slab" -version = "0.4.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f92a496fb766b417c996b9c5e57daf2f7ad3b0bebe1ccfca4856390e3d3bb67" -dependencies = [ - "autocfg 1.1.0", -] - -[[package]] -name = "smallvec" -version = "1.6.1" -source = "git+https://github.com/mesalock-linux/rust-smallvec-sgx#b5925f10aa5bc3370a0fb339140ee063f5a888dd" -dependencies = [ - "sgx_tstd", -] - -[[package]] -name = "smallvec" -version = "1.11.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "942b4a808e05215192e39f4ab80813e599068285906cc91aa64f923db842bd5a" - -[[package]] -name = "sp-api" -version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" -dependencies = [ - "log 0.4.21", - "parity-scale-codec", - "scale-info", - "sp-api-proc-macro", - "sp-core", - "sp-metadata-ir", - "sp-runtime", - "sp-std", - "sp-version", -] - -[[package]] -name = "sp-api-proc-macro" -version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" -dependencies = [ - "Inflector", - "blake2", - "expander", - "proc-macro-crate", - "proc-macro2", - "quote 1.0.36", - "syn 2.0.72", -] - -[[package]] -name = "sp-application-crypto" -version = "7.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" -dependencies = [ - "parity-scale-codec", - "scale-info", - "sp-core", - "sp-io", - "sp-std", -] - -[[package]] -name = "sp-arithmetic" -version = "6.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" -dependencies = [ - "integer-sqrt", - "num-traits 0.2.16", - "parity-scale-codec", - "scale-info", - "sp-std", - "static_assertions", -] - -[[package]] -name = "sp-consensus-aura" -version = "0.10.0-dev" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" -dependencies = [ - "parity-scale-codec", - "scale-info", - "sp-api", - "sp-application-crypto", - "sp-consensus-slots", - "sp-inherents", - "sp-runtime", - "sp-std", - "sp-timestamp", -] - -[[package]] -name = "sp-consensus-grandpa" -version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" -dependencies = [ - "finality-grandpa", - "log 0.4.21", - "parity-scale-codec", - "scale-info", - "sp-api", - "sp-application-crypto", - "sp-core", - "sp-runtime", - "sp-std", -] - -[[package]] -name = "sp-consensus-slots" -version = "0.10.0-dev" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" -dependencies = [ - "parity-scale-codec", - "scale-info", - "sp-std", - "sp-timestamp", -] - -[[package]] -name = "sp-core" -version = "7.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" -dependencies = [ - "array-bytes", - "bitflags", - "blake2", - "bounded-collections", - "ed25519-zebra", - "hash-db 0.16.0", - "hash256-std-hasher", - "libsecp256k1", - "log 0.4.21", - "merlin", - "parity-scale-codec", - "paste", - "primitive-types", - "scale-info", - "schnorrkel", - "secp256k1 0.24.3", - "secrecy", - "sp-core-hashing", - "sp-debug-derive", - "sp-runtime-interface", - "sp-std", - "sp-storage", - "ss58-registry", - "zeroize", -] - -[[package]] -name = "sp-core-hashing" -version = "5.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" -dependencies = [ - "blake2b_simd 1.0.2", - "byteorder 1.4.3", - "digest 0.10.7", - "sha2 0.10.7", - "sha3 0.10.8", - "sp-std", - "twox-hash", -] - -[[package]] -name = "sp-core-hashing-proc-macro" -version = "5.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" -dependencies = [ - "proc-macro2", - "quote 1.0.36", - "sp-core-hashing", - "syn 2.0.72", -] - -[[package]] -name = "sp-debug-derive" -version = "5.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" -dependencies = [ - "proc-macro2", - "quote 1.0.36", - "syn 2.0.72", -] - -[[package]] -name = "sp-externalities" -version = "0.13.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" -dependencies = [ - "environmental 1.1.4", - "parity-scale-codec", - "sp-std", - "sp-storage", -] - -[[package]] -name = "sp-inherents" -version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" -dependencies = [ - "impl-trait-for-tuples", - "parity-scale-codec", - "scale-info", - "sp-core", - "sp-std", -] - -[[package]] -name = "sp-io" -version = "7.0.0" -dependencies = [ - "itp-sgx-externalities", - "libsecp256k1", - "log 0.4.21", - "parity-scale-codec", - "sgx_tstd", - "sp-core", -] - -[[package]] -name = "sp-metadata-ir" -version = "0.1.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" -dependencies = [ - "frame-metadata", - "parity-scale-codec", - "scale-info", - "sp-std", -] - -[[package]] -name = "sp-runtime" -version = "7.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" -dependencies = [ - "either", - "hash256-std-hasher", - "impl-trait-for-tuples", - "log 0.4.21", - "parity-scale-codec", - "paste", - "scale-info", - "sp-application-crypto", - "sp-arithmetic", - "sp-core", - "sp-io", - "sp-std", - "sp-weights", -] - -[[package]] -name = "sp-runtime-interface" -version = "7.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" -dependencies = [ - "bytes 1.5.0", - "impl-trait-for-tuples", - "parity-scale-codec", - "primitive-types", - "sp-externalities", - "sp-runtime-interface-proc-macro", - "sp-std", - "sp-storage", - "sp-tracing", - "sp-wasm-interface", - "static_assertions", -] - -[[package]] -name = "sp-runtime-interface-proc-macro" -version = "6.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" -dependencies = [ - "Inflector", - "proc-macro-crate", - "proc-macro2", - "quote 1.0.36", - "syn 2.0.72", -] - -[[package]] -name = "sp-staking" -version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" -dependencies = [ - "parity-scale-codec", - "scale-info", - "sp-core", - "sp-runtime", - "sp-std", -] - -[[package]] -name = "sp-std" -version = "5.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" - -[[package]] -name = "sp-storage" -version = "7.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" -dependencies = [ - "parity-scale-codec", - "ref-cast", - "sp-debug-derive", - "sp-std", -] - -[[package]] -name = "sp-timestamp" -version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" -dependencies = [ - "parity-scale-codec", - "sp-inherents", - "sp-runtime", - "sp-std", -] - -[[package]] -name = "sp-tracing" -version = "6.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" -dependencies = [ - "parity-scale-codec", - "sp-std", - "tracing", - "tracing-core", -] - -[[package]] -name = "sp-trie" -version = "7.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" -dependencies = [ - "hash-db 0.16.0", - "memory-db", - "parity-scale-codec", - "scale-info", - "sp-core", - "sp-std", - "trie-db", - "trie-root", -] - -[[package]] -name = "sp-version" -version = "5.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" -dependencies = [ - "parity-scale-codec", - "scale-info", - "sp-core-hashing-proc-macro", - "sp-runtime", - "sp-std", - "sp-version-proc-macro", -] - -[[package]] -name = "sp-version-proc-macro" -version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" -dependencies = [ - "parity-scale-codec", - "proc-macro2", - "quote 1.0.36", - "syn 2.0.72", -] - -[[package]] -name = "sp-wasm-interface" -version = "7.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" -dependencies = [ - "impl-trait-for-tuples", - "parity-scale-codec", - "sp-std", -] - -[[package]] -name = "sp-weights" -version = "4.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" -dependencies = [ - "parity-scale-codec", - "scale-info", - "smallvec 1.11.1", - "sp-arithmetic", - "sp-core", - "sp-debug-derive", - "sp-std", -] - -[[package]] -name = "spin" -version = "0.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e63cff320ae2c57904679ba7cb63280a3dc4613885beafb148ee7bf9aa9042d" - -[[package]] -name = "spki" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67cf02bbac7a337dc36e4f5a693db6c21e7863f45070f7064577eb4367a3212b" -dependencies = [ - "der 0.6.1", -] - -[[package]] -name = "spki" -version = "0.7.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" -dependencies = [ - "base64ct", - "der 0.7.8", -] - -[[package]] -name = "ss58-registry" -version = "1.43.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e6915280e2d0db8911e5032a5c275571af6bdded2916abd691a659be25d3439" -dependencies = [ - "Inflector", - "proc-macro2", - "quote 1.0.36", - "serde 1.0.204", - "serde_json 1.0.133", - "unicode-xid 0.2.4", -] - -[[package]] -name = "static_assertions" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" - -[[package]] -name = "strsim" -version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623" - -[[package]] -name = "strum" -version = "0.26.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "723b93e8addf9aa965ebe2d11da6d7540fa2283fcea14b3371ff055f7ba13f5f" - -[[package]] -name = "strum_macros" -version = "0.26.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a3417fc93d76740d974a01654a09777cb500428cc874ca9f45edfe0c4d4cd18" -dependencies = [ - "heck", - "proc-macro2", - "quote 1.0.36", - "rustversion", - "syn 2.0.72", -] - -[[package]] -name = "substrate-api-client" -version = "0.14.0" -source = "git+https://github.com/Kailai-Wang/substrate-api-client?branch=polkadot-v0.9.42-litentry#f867fea44a3de5352d419a605afdd7bf22859e78" -dependencies = [ - "ac-compose-macros", - "ac-node-api", - "ac-primitives", - "async-trait", - "derive_more", - "frame-metadata", - "hex", - "log 0.4.21", - "maybe-async", - "parity-scale-codec", - "serde 1.0.204", - "serde_json 1.0.133", - "sp-core", - "sp-runtime", - "sp-runtime-interface", -] - -[[package]] -name = "subtle" -version = "2.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6bdef32e8150c2a081110b42772ffe7d7c9032b606bc226c8260fd97e0976601" - -[[package]] -name = "subtle" -version = "2.5.0" -source = "git+https://github.com/kziemianek/subtle-sgx.git?branch=2.5.0-update#57c424bdb6b98cbf9cfe19879748f20c3525c80e" -dependencies = [ - "sgx_tstd", -] - -[[package]] -name = "syn" -version = "0.11.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3b891b9015c88c576343b9b3e41c2c11a51c219ef067b264bd9c8aa9b441dad" -dependencies = [ - "quote 0.3.15", - "synom", - "unicode-xid 0.0.4", -] - -[[package]] -name = "syn" -version = "1.0.109" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237" -dependencies = [ - "proc-macro2", - "quote 1.0.36", - "unicode-ident", -] - -[[package]] -name = "syn" -version = "2.0.72" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc4b9b9bf2add8093d3f2c0204471e951b2285580335de42f9d2534f3ae7a8af" -dependencies = [ - "proc-macro2", - "quote 1.0.36", - "unicode-ident", -] - -[[package]] -name = "synom" -version = "0.11.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a393066ed9010ebaed60b9eafa373d4b1baac186dd7e008555b0f702b51945b6" -dependencies = [ - "unicode-xid 0.0.4", -] - -[[package]] -name = "tap" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369" - -[[package]] -name = "termcolor" -version = "1.0.5" -source = "git+https://github.com/mesalock-linux/termcolor-sgx#fee5ac79b4a90197d646f3df5e1b45ac56be718b" -dependencies = [ - "sgx_tstd", -] - -[[package]] -name = "thiserror" -version = "1.0.9" -source = "git+https://github.com/mesalock-linux/thiserror-sgx?tag=sgx_1.1.3#c2f806b88616e06aab0af770366a76885d974fdc" -dependencies = [ - "sgx_tstd", - "thiserror-impl", -] - -[[package]] -name = "thiserror-impl" -version = "1.0.9" -source = "git+https://github.com/mesalock-linux/thiserror-sgx?tag=sgx_1.1.3#c2f806b88616e06aab0af770366a76885d974fdc" -dependencies = [ - "proc-macro2", - "quote 1.0.36", - "syn 1.0.109", -] - -[[package]] -name = "thread_local" -version = "1.0.0" -source = "git+https://github.com/mesalock-linux/thread_local-rs-sgx#a8e6e6ce280c53358f7b9e6febe534cba9950547" -dependencies = [ - "lazy_static", - "sgx_tstd", -] - -[[package]] -name = "threadpool" -version = "1.8.0" -source = "git+https://github.com/mesalock-linux/rust-threadpool-sgx?tag=sgx_1.1.3#098d98a85b7e2b02e2bb451a3dec0b027017ff4c" -dependencies = [ - "sgx_tstd", -] - -[[package]] -name = "tiny-keccak" -version = "2.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2c9d3793400a45f954c52e73d068316d76b6f4e36977e3fcebb13a2721e80237" -dependencies = [ - "crunchy", -] - -[[package]] -name = "tinyvec" -version = "1.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "87cc5ceb3875bb20c2890005a4e226a4651264a5c75edb2421b52861a0a0cb50" -dependencies = [ - "tinyvec_macros", -] - -[[package]] -name = "tinyvec_macros" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" - -[[package]] -name = "toml" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c226a7bba6d859b63c92c4b4fe69c5b6b72d0cb897dbc8e6012298e6154cb56e" -dependencies = [ - "serde 1.0.204", - "serde_spanned", - "toml_datetime", - "toml_edit 0.20.0", -] - -[[package]] -name = "toml_datetime" -version = "0.6.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7cda73e2f1397b1262d6dfdcef8aafae14d1de7748d66822d3bfeeb6d03e5e4b" -dependencies = [ - "serde 1.0.204", -] - -[[package]] -name = "toml_edit" -version = "0.19.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b5bb770da30e5cbfde35a2d7b9b8a2c4b8ef89548a7a6aeab5c9a576e3e7421" -dependencies = [ - "indexmap 2.0.0", - "toml_datetime", - "winnow", -] - -[[package]] -name = "toml_edit" -version = "0.20.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ff63e60a958cefbb518ae1fd6566af80d9d4be430a33f3723dfc47d1d411d95" -dependencies = [ - "indexmap 2.0.0", - "serde 1.0.204", - "serde_spanned", - "toml_datetime", - "winnow", -] - -[[package]] -name = "tracing" -version = "0.1.37" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ce8c33a8d48bd45d624a6e523445fd21ec13d3653cd51f681abf67418f54eb8" -dependencies = [ - "cfg-if 1.0.0", - "pin-project-lite", - "tracing-core", -] - -[[package]] -name = "tracing-core" -version = "0.1.31" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0955b8137a1df6f1a2e9a37d8a6656291ff0297c1a97c24e0d8425fe2312f79a" - -[[package]] -name = "trie-db" -version = "0.27.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "767abe6ffed88a1889671a102c2861ae742726f52e0a5a425b92c9fbfa7e9c85" -dependencies = [ - "hash-db 0.16.0", - "hashbrown 0.13.2", - "log 0.4.21", - "smallvec 1.11.1", -] - -[[package]] -name = "trie-root" -version = "0.18.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d4ed310ef5ab98f5fa467900ed906cb9232dd5376597e00fd4cba2a449d06c0b" -dependencies = [ - "hash-db 0.16.0", -] - -[[package]] -name = "triehash" -version = "0.8.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a1631b201eb031b563d2e85ca18ec8092508e262a3196ce9bd10a67ec87b9f5c" -dependencies = [ - "hash-db 0.15.2", - "rlp", -] - -[[package]] -name = "tt-call" -version = "1.0.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f4f195fd851901624eee5a58c4bb2b4f06399148fcd0ed336e6f1cb60a9881df" - -[[package]] -name = "tungstenite" -version = "0.14.0" -source = "git+https://github.com/integritee-network/tungstenite-rs-sgx?branch=sgx-experimental#c87a2c08ea00897bb8b127ca0a5c30c3671492b0" -dependencies = [ - "base64 0.13.0 (git+https://github.com/mesalock-linux/rust-base64-sgx?tag=sgx_1.1.3)", - "byteorder 1.3.4", - "bytes 1.0.1", - "http", - "httparse", - "log 0.4.17", - "rand 0.7.3", - "rustls 0.19.0 (git+https://github.com/mesalock-linux/rustls?tag=sgx_1.1.3)", - "sgx_tstd", - "sha1", - "thiserror", - "url 2.1.1", - "utf-8", - "webpki", - "webpki-roots 0.21.0 (git+https://github.com/mesalock-linux/webpki-roots?tag=sgx_1.1.3)", -] - -[[package]] -name = "twox-hash" -version = "1.6.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "97fee6b57c6a41524a810daee9286c02d7752c4253064d0b05472833a438f675" -dependencies = [ - "cfg-if 1.0.0", - "digest 0.10.7", - "static_assertions", -] - -[[package]] -name = "typenum" -version = "1.17.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "42ff0bf0c66b8238c6f3b578df37d0b7848e55df8577b3f74f92a69acceeb825" - -[[package]] -name = "uint" -version = "0.9.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "76f64bba2c53b04fcab63c01a7d7427eadc821e3bc48c34dc9ba29c501164b52" -dependencies = [ - "byteorder 1.4.3", - "crunchy", - "hex", - "static_assertions", -] - -[[package]] -name = "unicode-bidi" -version = "0.3.4" -source = "git+https://github.com/mesalock-linux/unicode-bidi-sgx#eb10728a635a046e75747849fbc680cbbb7832c7" -dependencies = [ - "matches", - "sgx_tstd", -] - -[[package]] -name = "unicode-bidi" -version = "0.3.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08f95100a766bf4f8f28f90d77e0a5461bbdb219042e7679bebe79004fed8d75" - -[[package]] -name = "unicode-ident" -version = "1.0.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b" - -[[package]] -name = "unicode-normalization" -version = "0.1.12" -source = "git+https://github.com/mesalock-linux/unicode-normalization-sgx#c1b030611969f87d75782c1df77975167cbbd509" -dependencies = [ - "smallvec 1.6.1", -] - -[[package]] -name = "unicode-normalization" -version = "0.1.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a56d1686db2308d901306f92a263857ef59ea39678a5458e7cb17f01415101f5" -dependencies = [ - "tinyvec", -] - -[[package]] -name = "unicode-xid" -version = "0.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8c1f860d7d29cf02cb2f3f359fd35991af3d30bac52c57d265a3c461074cb4dc" - -[[package]] -name = "unicode-xid" -version = "0.2.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f962df74c8c05a667b5ee8bcf162993134c104e96440b663c8daa176dc772d8c" - -[[package]] -name = "unsigned-varint" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f7fdeedbf205afadfe39ae559b75c3240f24e257d0ca27e85f85cb82aa19ac35" - -[[package]] -name = "untrusted" -version = "0.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a156c684c91ea7d62626509bce3cb4e1d9ed5c4d978f7b4352658f96a4c26b4a" - -[[package]] -name = "untrusted" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" - -[[package]] -name = "url" -version = "2.1.1" -source = "git+https://github.com/mesalock-linux/rust-url-sgx?tag=sgx_1.1.3#23832f3191456c2d4a0faab10952e1747be58ca8" -dependencies = [ - "idna 0.2.0", - "matches", - "percent-encoding 2.1.0", - "sgx_tstd", -] - -[[package]] -name = "url" -version = "2.5.0" -source = "git+https://github.com/domenukk/rust-url?rev=316c868#316c8683206f3cb741163779bb30963fa05b3612" -dependencies = [ - "form_urlencoded", - "idna 0.5.0", - "no-std-net", - "percent-encoding 2.3.1", -] - -[[package]] -name = "utf-8" -version = "0.7.4" -source = "git+https://github.com/integritee-network/rust-utf8-sgx?branch=sgx-experimental#b026700da83a2f00f0e9f36f813ef28e447a719e" -dependencies = [ - "sgx_tstd", -] - -[[package]] -name = "version_check" -version = "0.9.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f" - -[[package]] -name = "wasi" -version = "0.11.0+wasi-snapshot-preview1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" - -[[package]] -name = "webpki" -version = "0.21.4" -source = "git+https://github.com/mesalock-linux/webpki?branch=mesalock_sgx#8dbe6fbeefadf05582ae47c7fa818b04db49c61e" -dependencies = [ - "ring 0.16.19", - "sgx_tstd", - "untrusted 0.7.1", -] - -[[package]] -name = "webpki-roots" -version = "0.21.0" -source = "git+https://github.com/mesalock-linux/webpki-roots?tag=sgx_1.1.3#6ff3be547ac13ccd46ae55605ad6506ce30688ef" -dependencies = [ - "sgx_tstd", - "webpki", -] - -[[package]] -name = "webpki-roots" -version = "0.21.0" -source = "git+https://github.com/mesalock-linux/webpki-roots?branch=mesalock_sgx#6ff3be547ac13ccd46ae55605ad6506ce30688ef" -dependencies = [ - "sgx_tstd", - "webpki", -] - -[[package]] -name = "winapi" -version = "0.3.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" -dependencies = [ - "winapi-i686-pc-windows-gnu", - "winapi-x86_64-pc-windows-gnu", -] - -[[package]] -name = "winapi-i686-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" - -[[package]] -name = "winapi-x86_64-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" - -[[package]] -name = "winnow" -version = "0.5.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7c2e3184b9c4e92ad5167ca73039d0c42476302ab603e2fec4487511f38ccefc" -dependencies = [ - "memchr 2.6.3", -] - -[[package]] -name = "wyz" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "05f360fc0b24296329c78fda852a1e9ae82de9cf7b27dae4b7f62f118f77b9ed" -dependencies = [ - "tap", -] - -[[package]] -name = "x509-cert" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "99d224a125dec5adda27d0346b9cae9794830279c4f9c27e4ab0b6c408d54012" -dependencies = [ - "const-oid", - "der 0.6.1", - "flagset", - "spki 0.6.0", -] - -[[package]] -name = "xous" -version = "0.9.58" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb93122c9dab77f8bde501ff0677d3df7777982f9faa23603423aeb5eae4e55d" -dependencies = [ - "lazy_static", -] - -[[package]] -name = "xous-api-log" -version = "0.1.54" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "941f7fd7c114e1e0c401bbbe8222e8adbb4bc8ebeb782f7812d8f1678a578934" -dependencies = [ - "log 0.4.21", - "num-derive", - "num-traits 0.2.16", - "xous", - "xous-ipc", -] - -[[package]] -name = "xous-api-names" -version = "0.9.56" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "471502d9379d198738ec55dec7cd688ce21e1cfe7d93af6dad25e38c1c404d1c" -dependencies = [ - "log 0.4.21", - "num-derive", - "num-traits 0.2.16", - "rkyv", - "xous", - "xous-api-log", - "xous-ipc", -] - -[[package]] -name = "xous-ipc" -version = "0.9.58" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2f5081581314f115e2005403ee2cc0957d86cbfc49edf6e8b05d2fcf6c226c5d" -dependencies = [ - "bitflags", - "rkyv", - "xous", -] - -[[package]] -name = "yasna" -version = "0.3.1" -source = "git+https://github.com/mesalock-linux/yasna.rs-sgx?rev=sgx_1.1.3#a1f50714cd3eb29608ecf7888cacedc173edfdb2" -dependencies = [ - "bit-vec", - "chrono 0.4.11", - "num-bigint", - "sgx_tstd", -] - -[[package]] -name = "zeroize" -version = "1.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "525b4ec142c6b68a2d10f01f7bbf6755599ca3f81ea53b8431b7dd348f5fdb2d" -dependencies = [ - "zeroize_derive", -] - -[[package]] -name = "zeroize_derive" -version = "1.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce36e65b0d2999d2aafac989fb249189a141aee1f53c612c1f37d72631959f69" -dependencies = [ - "proc-macro2", - "quote 1.0.36", - "syn 2.0.72", -] - -[[patch.unused]] -name = "sgx_tcrypto_helper" -version = "1.1.6" -source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#3c903bdac4e503dd27b9b1f761c4abfc55f2464c" diff --git a/tee-worker/bitacross/enclave-runtime/Cargo.toml b/tee-worker/bitacross/enclave-runtime/Cargo.toml deleted file mode 100644 index b74c56ca31..0000000000 --- a/tee-worker/bitacross/enclave-runtime/Cargo.toml +++ /dev/null @@ -1,186 +0,0 @@ -[package] -name = "enclave-runtime" -version = "0.0.1" -authors = ['Trust Computing GmbH ', 'Integritee AG '] -edition = "2021" - -[workspace] -resolver = "2" -members = [] - -[lib] -name = "enclave_runtime" -crate-type = ["staticlib"] - -[features] -default = [] -development = [ - "ita-stf/development", - "itp-settings/development", - "itp-attestation-handler/development", - "litentry-primitives/development", - "litentry-macros/development", - "bc-task-processor/development", -] -offchain-worker = [ - "itp-settings/offchain-worker", - "itp-top-pool-author/offchain-worker", -] -test = [ - "ita-stf/test", - "itc-parentchain/test", - "itp-attestation-handler/test", - "itp-extrinsics-factory/mocks", - "itp-sgx-crypto/test", - "itp-sgx-temp-dir", - "itp-stf-executor/test", - "itp-stf-executor/mocks", - "itp-stf-state-handler/test", - "itp-stf-state-observer/mocks", - "itp-storage/test", - "itp-test/sgx", - "itp-top-pool-author/test", - "itp-top-pool-author/mocks", - "bc-musig2-ceremony/sgx-test", -] -dcap = [] - -[target.'cfg(not(target_env = "sgx"))'.dependencies] -sgx_crypto_helper = { branch = "master", git = "https://github.com/apache/teaclave-sgx-sdk.git", default-features = false, features = ["mesalock_sgx"] } -sgx_rand = { branch = "master", git = "https://github.com/apache/teaclave-sgx-sdk.git" } -sgx_serialize = { branch = "master", git = "https://github.com/apache/teaclave-sgx-sdk.git" } -sgx_serialize_derive = { branch = "master", git = "https://github.com/apache/teaclave-sgx-sdk.git" } -sgx_tcrypto = { branch = "master", git = "https://github.com/apache/teaclave-sgx-sdk.git" } -sgx_trts = { branch = "master", git = "https://github.com/apache/teaclave-sgx-sdk.git" } -sgx_tse = { branch = "master", git = "https://github.com/apache/teaclave-sgx-sdk.git" } -sgx_tseal = { branch = "master", git = "https://github.com/apache/teaclave-sgx-sdk.git" } -sgx_tstd = { branch = "master", git = "https://github.com/apache/teaclave-sgx-sdk.git", features = ["untrusted_fs", "net", "backtrace"] } -sgx_tunittest = { branch = "master", git = "https://github.com/apache/teaclave-sgx-sdk.git" } -sgx_types = { branch = "master", git = "https://github.com/apache/teaclave-sgx-sdk.git" } - -[dependencies] -codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive"] } -derive_more = { version = "0.99.5" } -futures_sgx = { package = "futures", git = "https://github.com/mesalock-linux/futures-rs-sgx" } -hex = { version = "0.4.3", default-features = false, features = ["alloc"] } -ipfs-unixfs = { default-features = false, git = "https://github.com/whalelephant/rust-ipfs", branch = "w-nstd" } -lazy_static = { version = "1.1.0", features = ["spin_no_std"] } -primitive-types = { version = "0.12.1", default-features = false, features = ["codec", "serde_no_std"] } -url = { git = "https://github.com/domenukk/rust-url", rev = "316c868", default-features = false, features = ["alloc", "no_std_net"] } - -# scs / integritee -jsonrpc-core = { default-features = false, git = "https://github.com/scs/jsonrpc", branch = "no_std_v18" } - -# mesalock -env_logger = { git = "https://github.com/integritee-network/env_logger-sgx" } -log = { git = "https://github.com/integritee-network/log-sgx" } -# Todo #1313: use the `once_cell` included in rusts core library once we use rust v1.70.0 -once_cell = { git = "https://github.com/mesalock-linux/once_cell-sgx" } -rustls = { rev = "sgx_1.1.3", features = ["dangerous_configuration"], git = "https://github.com/mesalock-linux/rustls" } -serde_json = { tag = "sgx_1.1.3", git = "https://github.com/mesalock-linux/serde-json-sgx" } -webpki = { git = "https://github.com/mesalock-linux/webpki", branch = "mesalock_sgx" } - -# for attestation -base58 = { rev = "sgx_1.1.3", package = "rust-base58", default-features = false, features = ["mesalock_sgx"], git = "https://github.com/mesalock-linux/rust-base58-sgx" } - -cid = { default-features = false, git = "https://github.com/whalelephant/rust-cid", branch = "nstd" } -multibase = { default-features = false, git = "https://github.com/whalelephant/rust-multibase", branch = "nstd" } - -# local deps -ita-parentchain-interface = { package = "bc-ita-parentchain-interface", path = "../app-libs/parentchain-interface", default-features = false, features = ["sgx"] } -ita-sgx-runtime = { package = "bc-ita-sgx-runtime", path = "../app-libs/sgx-runtime", default-features = false } -ita-stf = { package = "bc-ita-stf", path = "../app-libs/stf", default-features = false, features = ["sgx"] } -itc-direct-rpc-server = { package = "bc-itc-direct-rpc-server", path = "../core/direct-rpc-server", default-features = false, features = ["sgx"] } -itc-offchain-worker-executor = { package = "bc-itc-offchain-worker-executor", path = "../core/offchain-worker-executor", default-features = false, features = ["sgx"] } -itc-parentchain = { package = "bc-itc-parentchain", path = "../core/parentchain/parentchain-crate", default-features = false, features = ["sgx"] } -itc-parentchain-light-client = { path = "../../common/core/parentchain/light-client", default-features = false } -itc-parentchain-test = { path = "../../common/core/parentchain/test", default-features = false } -itc-tls-websocket-server = { path = "../../common/core/tls-websocket-server", default-features = false, features = ["sgx"] } -itp-attestation-handler = { path = "../../common/core-primitives/attestation-handler", default-features = false, features = ["sgx"] } -itp-component-container = { path = "../../common/core-primitives/component-container", default-features = false, features = ["sgx"] } -itp-extrinsics-factory = { path = "../../common/core-primitives/extrinsics-factory", default-features = false, features = ["sgx"] } -itp-import-queue = { path = "../../common/core-primitives/import-queue", default-features = false, features = ["sgx"] } -itp-node-api = { path = "../../common/core-primitives/node-api", default-features = false, features = ["sgx"] } -itp-node-api-metadata = { path = "../../common/core-primitives/node-api/metadata", default-features = false } -itp-node-api-metadata-provider = { path = "../../common/core-primitives/node-api/metadata-provider", default-features = false } -itp-nonce-cache = { path = "../../common/core-primitives/nonce-cache", default-features = false, features = ["sgx"] } -itp-ocall-api = { path = "../../common/core-primitives/ocall-api", default-features = false } -itp-primitives-cache = { path = "../../common/core-primitives/primitives-cache", default-features = false, features = ["sgx"] } -itp-rpc = { path = "../../common/core-primitives/rpc", default-features = false, features = ["sgx"] } -itp-settings = { path = "../../common/core-primitives/settings" } -itp-sgx-crypto = { path = "../../common/core-primitives/sgx/crypto", default-features = false, features = ["sgx"] } -itp-sgx-externalities = { path = "../../common/core-primitives/substrate-sgx/externalities", default-features = false, features = ["sgx"] } -itp-stf-executor = { package = "bc-itp-stf-executor", path = "../core-primitives/stf-executor", default-features = false, features = ["sgx"] } -itp-stf-interface = { path = "../../common/core-primitives/stf-interface", default-features = false } -itp-stf-primitives = { path = "../../common/core-primitives/stf-primitives", default-features = false } -itp-stf-state-handler = { path = "../../common/core-primitives/stf-state-handler", default-features = false, features = ["sgx"] } -itp-stf-state-observer = { path = "../../common/core-primitives/stf-state-observer", default-features = false, features = ["sgx"] } -itp-storage = { path = "../../common/core-primitives/storage", default-features = false, features = ["sgx"] } -itp-test = { path = "../../common/core-primitives/test", default-features = false, optional = true } -itp-top-pool = { package = "bc-itp-top-pool", path = "../core-primitives/top-pool", default-features = false, features = ["sgx"] } -itp-top-pool-author = { package = "bc-itp-top-pool-author", path = "../core-primitives/top-pool-author", default-features = false, features = ["sgx"] } -itp-types = { path = "../../common/core-primitives/types", default-features = false } -itp-utils = { path = "../../common/core-primitives/utils", default-features = false } - -# litentry -bc-enclave-registry = { path = "../bitacross/core/bc-enclave-registry", default-features = false, features = ["sgx"] } -bc-musig2-ceremony = { path = "../bitacross/core/bc-musig2-ceremony", default-features = false, features = ["sgx"] } -bc-relayer-registry = { path = "../bitacross/core/bc-relayer-registry", default-features = false, features = ["sgx"] } -bc-signer-registry = { path = "../bitacross/core/bc-signer-registry", default-features = false, features = ["sgx"] } -bc-task-sender = { path = "../bitacross/core/bc-task-sender", default-features = false, features = ["sgx"] } -lc-direct-call = { path = "../litentry/core/direct-call", default-features = false } -litentry-hex-utils = { path = "../../../common/utils/hex", default-features = false } -litentry-macros = { path = "../../../common/primitives/core/macros", default-features = false } -litentry-primitives = { path = "../../common/litentry/primitives", default-features = false, features = ["sgx"] } -litentry-proc-macros = { path = "../../../common/primitives/core/proc-macros", default-features = false } - -# bitacross -bc-task-processor = { path = "../bitacross/core/bc-task-processor", default-features = false, features = ["sgx"] } - -# substrate deps -frame-support = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.42", default-features = false } -sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.42", default-features = false, features = ["full_crypto"] } -sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.42", default-features = false } - -# test-deps -itp-sgx-temp-dir = { path = "../../common/core-primitives/sgx/temp-dir", default-features = false, optional = true } - -[patch.crates-io] -env_logger = { git = "https://github.com/integritee-network/env_logger-sgx" } -log = { git = "https://github.com/integritee-network/log-sgx" } -ring = { git = "https://github.com/betrusted-io/ring-xous", branch = "0.16.20-cleanup" } - -[patch."https://github.com/mesalock-linux/log-sgx"] -log = { git = "https://github.com/integritee-network/log-sgx" } - -[patch."https://github.com/paritytech/polkadot-sdk"] -frame-support = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.42" } -sp-api = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.42" } -sp-consensus-aura = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.42" } -sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.42" } -sp-io = { path = "../../common/core-primitives/substrate-sgx/sp-io" } -sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.42" } -sp-std = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.42" } - -[patch."https://github.com/paritytech/frontier"] -pallet-evm = { git = "https://github.com/polkadot-evm/frontier", branch = "bar/polkadot-v0.9.42" } - -[patch."https://github.com/paritytech/substrate"] -sp-io = { path = "../../common/core-primitives/substrate-sgx/sp-io" } - -[patch."https://github.com/apache/teaclave-sgx-sdk.git"] -sgx_alloc = { version = "1.1.6", git = "https://github.com/apache/incubator-teaclave-sgx-sdk", branch = "master" } -sgx_crypto_helper = { version = "1.1.6", git = "https://github.com/apache/incubator-teaclave-sgx-sdk", branch = "master" } -sgx_libc = { version = "1.1.6", git = "https://github.com/apache/incubator-teaclave-sgx-sdk", branch = "master" } -sgx_rand = { version = "1.1.6", git = "https://github.com/apache/incubator-teaclave-sgx-sdk", branch = "master" } -sgx_serialize = { version = "1.1.6", git = "https://github.com/apache/incubator-teaclave-sgx-sdk", branch = "master" } -sgx_serialize_derive = { version = "1.1.6", git = "https://github.com/apache/incubator-teaclave-sgx-sdk", branch = "master" } -sgx_serialize_derive_internals = { version = "1.1.6", git = "https://github.com/apache/incubator-teaclave-sgx-sdk", branch = "master" } -sgx_tcrypto = { version = "1.1.6", git = "https://github.com/apache/incubator-teaclave-sgx-sdk", branch = "master" } -sgx_tcrypto_helper = { version = "1.1.6", git = "https://github.com/apache/incubator-teaclave-sgx-sdk", branch = "master" } -sgx_trts = { version = "1.1.6", git = "https://github.com/apache/incubator-teaclave-sgx-sdk", branch = "master" } -sgx_tse = { version = "1.1.6", git = "https://github.com/apache/incubator-teaclave-sgx-sdk", branch = "master" } -sgx_tseal = { version = "1.1.6", git = "https://github.com/apache/incubator-teaclave-sgx-sdk", branch = "master" } -sgx_tstd = { version = "1.1.6", git = "https://github.com/apache/incubator-teaclave-sgx-sdk", branch = "master" } -sgx_tunittest = { version = "1.1.6", git = "https://github.com/apache/incubator-teaclave-sgx-sdk", branch = "master" } -sgx_types = { version = "1.1.6", git = "https://github.com/apache/incubator-teaclave-sgx-sdk", branch = "master" } diff --git a/tee-worker/bitacross/enclave-runtime/Enclave.config.production.xml b/tee-worker/bitacross/enclave-runtime/Enclave.config.production.xml deleted file mode 100644 index 669cbe2087..0000000000 --- a/tee-worker/bitacross/enclave-runtime/Enclave.config.production.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - 0 - 0 - 0x40000 - 0x20000000 - 64 - 0 - 1 - 0 - 0xFFFFFFFF - diff --git a/tee-worker/bitacross/enclave-runtime/Enclave.config.xml b/tee-worker/bitacross/enclave-runtime/Enclave.config.xml deleted file mode 100644 index 747875739c..0000000000 --- a/tee-worker/bitacross/enclave-runtime/Enclave.config.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - 0 - 0 - 0x40000 - 0x20000000 - 64 - 0 - 0 - 0 - 0xFFFFFFFF - diff --git a/tee-worker/bitacross/enclave-runtime/Enclave.edl b/tee-worker/bitacross/enclave-runtime/Enclave.edl deleted file mode 100644 index 11a93e5f49..0000000000 --- a/tee-worker/bitacross/enclave-runtime/Enclave.edl +++ /dev/null @@ -1,253 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ - -enclave { - from "sgx_backtrace.edl" import *; - from "sgx_tstd.edl" import *; - from "sgx_stdio.edl" import *; - from "sgx_backtrace.edl" import *; - from "sgx_tstdc.edl" import *; - from "sgx_tprotected_fs.edl" import *; - from "sgx_fs.edl" import *; - from "sgx_net.edl" import *; - from "sgx_time.edl" import *; - from "sgx_env.edl" import *; - from "sgx_thread.edl" import *; - from "sgx_pipe.edl" import *; - from "sgx_file.edl" import *; - from "sgx_dcap_tvl.edl" import *; - - include "sgx_quote.h" - include "sgx_report.h" - include "sgx_ql_quote.h" - include "sgx_qve_header.h" - - trusted { - /* define ECALLs here. */ - public sgx_status_t init( - [in, size=mu_ra_addr_size] uint8_t* mu_ra_addr, uint32_t mu_ra_addr_size, - [in, size=untrusted_worker_addr_size] uint8_t* untrusted_worker_addr, uint32_t untrusted_worker_addr_size, - [in, size=encoded_base_dir_size] uint8_t* encoded_base_dir_str, uint32_t encoded_base_dir_size, - uint8_t ceremony_commands_thread_count, uint8_t ceremony_events_thread_count - ); - - public sgx_status_t publish_wallets(); - - public sgx_status_t finish_enclave_init(); - - public sgx_status_t init_wallets( - [in, size=encoded_base_dir_size] uint8_t* encoded_base_dir_str, uint32_t encoded_base_dir_size - ); - - public sgx_status_t init_direct_invocation_server( - [in, size=server_addr_size] uint8_t* server_addr, uint32_t server_addr_size - ); - - public sgx_status_t init_parentchain_components( - [in, size=params_size] uint8_t* params, size_t params_size, - [out, size=latest_header_size] uint8_t* latest_header, size_t latest_header_size - ); - - public sgx_status_t init_shard( - [in, size=shard_size] uint8_t* shard, uint32_t shard_size - ); - - public sgx_status_t init_shard_creation_parentchain_header( - [in, size=shard_size] uint8_t* shard, uint32_t shard_size, - [in, size=parentchain_id_size] uint8_t* parentchain_id, uint32_t parentchain_id_size, - [in, size=header_size] uint8_t* header, uint32_t header_size - ); - - public sgx_status_t get_shard_creation_info( - [in, size=shard_size] uint8_t* shard, uint32_t shard_size, - [out, size=creation_size] uint8_t* creation, uint32_t creation_size); - - public sgx_status_t sync_parentchain( - [in, size=blocks_size] uint8_t* blocks, size_t blocks_size, - [in, size=events_size] uint8_t* events, size_t events_size, - [in, size=events_proofs_size] uint8_t* events_proofs, size_t events_proofs_size, - [in, size=parentchain_id_size] uint8_t* parentchain_id, uint32_t parentchain_id_size, - int immediate_import - ); - - public sgx_status_t set_nonce( - [in] uint32_t* nonce, - [in, size=parentchain_id_size] uint8_t* parentchain_id, uint32_t parentchain_id_size - ); - - public sgx_status_t set_node_metadata( - [in, size=node_metadata_size] uint8_t* node_metadata, uint32_t node_metadata_size, - [in, size=parentchain_id_size] uint8_t* parentchain_id, uint32_t parentchain_id_size - ); - - public sgx_status_t get_rsa_encryption_pubkey( - [out, size=pubkey_size] uint8_t* pubkey, uint32_t pubkey_size); - - public sgx_status_t get_ecc_signing_pubkey( - [out, size=pubkey_size] uint8_t* pubkey, uint32_t pubkey_size); - - public sgx_status_t get_bitcoin_wallet_pair( - [out, size=pair_size] uint8_t* pair, uint32_t pair_size); - - public sgx_status_t get_ethereum_wallet_pair( - [out, size=pair_size] uint8_t* pair, uint32_t pair_size); - - public sgx_status_t get_ton_wallet_pair( - [out, size=pair_size] uint8_t* pair, uint32_t pair_size); - - public sgx_status_t get_mrenclave( - [out, size=mrenclave_size] uint8_t* mrenclave, uint32_t mrenclave_size); - - public sgx_status_t generate_ias_ra_extrinsic( - [in, size=w_url_size] uint8_t* w_url, uint32_t w_url_size, - [out, size=unchecked_extrinsic_max_size] uint8_t* unchecked_extrinsic, uint32_t unchecked_extrinsic_max_size, - [out] uint32_t* unchecked_extrinsic_size, - int skip_ra - ); - public sgx_status_t generate_dcap_ra_quote( - int skip_ra, - [in] const sgx_target_info_t* quoting_enclave_target_info, - uint32_t quote_size, - [out, size=dcap_quote_size] uint8_t* dcap_quote_p, uint32_t dcap_quote_size - ); - - public sgx_status_t generate_dcap_ra_extrinsic_from_quote( - [in, size=w_url_size] uint8_t* w_url, uint32_t w_url_size, - [in, size=quote_size] uint8_t* quote, uint32_t quote_size, - [out, size=unchecked_extrinsic_max_size] uint8_t* unchecked_extrinsic, uint32_t unchecked_extrinsic_max_size, - [out] uint32_t* unchecked_extrinsic_size - ); - - public sgx_status_t generate_dcap_ra_extrinsic( - [in, size=w_url_size] uint8_t* w_url, uint32_t w_url_size, - [out, size=unchecked_extrinsic_max_size] uint8_t* unchecked_extrinsic, uint32_t unchecked_extrinsic_max_size, - [out] uint32_t* unchecked_extrinsic_size, - int skip_ra, - [in] const sgx_target_info_t* quoting_enclave_target_info, - [in] uint32_t* quote_size - ); - - public sgx_status_t generate_register_quoting_enclave_extrinsic( - [in] const sgx_ql_qve_collateral_t *p_quote_collateral, - [out, size=unchecked_extrinsic_max_size] uint8_t* unchecked_extrinsic, uint32_t unchecked_extrinsic_max_size, - [out] uint32_t* unchecked_extrinsic_size - ); - - public sgx_status_t generate_register_tcb_info_extrinsic( - [in] const sgx_ql_qve_collateral_t *p_quote_collateral, - [out, size=unchecked_extrinsic_max_size] uint8_t* unchecked_extrinsic, uint32_t unchecked_extrinsic_max_size, - [out] uint32_t* unchecked_extrinsic_size - ); - - public sgx_status_t dump_ias_ra_cert_to_disk(); - - public sgx_status_t dump_dcap_ra_cert_to_disk([in] const sgx_target_info_t* quoting_enclave_target_info, uint32_t quote_size); - - public sgx_status_t dump_dcap_collateral_to_disk([in] const sgx_ql_qve_collateral_t *p_quote_collateral); - - public sgx_status_t run_state_provisioning_server( - int fd, - sgx_quote_sign_type_t quote_type, - [in] sgx_target_info_t* quoting_enclave_target_info, - [in] uint32_t* quote_size, - int skip_ra - ); - public sgx_status_t request_state_provisioning( - int fd, - sgx_quote_sign_type_t quote_type, - [in] sgx_target_info_t* quoting_enclave_target_info, - [in] uint32_t* quote_size, - [in, size=shard_size] uint8_t* shard, uint32_t shard_size, - int skip_ra - ); - - public size_t test_main_entrance(); - - public sgx_status_t migrate_shard( - [in, size=shard_size] uint8_t* new_shard, - uint32_t shard_size - ); - - public sgx_status_t ignore_parentchain_block_import_validation_until( - [in] uint32_t* until - ); - }; - - untrusted { - sgx_status_t ocall_sgx_init_quote( - [out] sgx_target_info_t *ret_ti, - [out] sgx_epid_group_id_t *ret_gid - ); - - sgx_status_t ocall_get_ias_socket([out] int *ret_fd); - - sgx_status_t ocall_get_quote( - [in, size = sigrl_len] uint8_t * p_sigrl, uint32_t sigrl_len, - [in] sgx_report_t *report, sgx_quote_sign_type_t quote_type, - [in] sgx_spid_t *p_spid, [in] sgx_quote_nonce_t *p_nonce, - [out] sgx_report_t *p_qe_report, - [out, size = maxlen] sgx_quote_t *p_quote, uint32_t maxlen, - [out] uint32_t* p_quote_len - ); - - sgx_status_t ocall_get_dcap_quote( - [in] sgx_report_t *report, - [out, size = quote_size] sgx_quote_t *p_quote, uint32_t quote_size - ); - - sgx_status_t ocall_get_qve_report_on_quote( - [in, size = quote_size] const uint8_t * quote, uint32_t quote_size, - time_t current_time, - [in] const sgx_ql_qve_collateral_t *p_quote_collateral, - [out] uint32_t *collateral_expiration_status, - [out] sgx_ql_qv_result_t *quote_verification_result, - [in, out] sgx_ql_qe_report_info_t *qve_report_info, - [out, size=supplemental_data_size] uint8_t *p_supplemental_data, - uint32_t supplemental_data_size - ); - - sgx_status_t ocall_get_update_info( - [in] sgx_platform_info_t * platformBlob, int32_t enclaveTrusted, - [out] sgx_update_info_bit_t * update_info - ); - - sgx_status_t ocall_read_ipfs( - [in, size = cid_size] uint8_t * cid, uint32_t cid_size - ); - - sgx_status_t ocall_write_ipfs( - [in, size = state_size] uint8_t * enc_state, uint32_t state_size, - [out, size = cid_size] uint8_t * cid, uint32_t cid_size - ); - - sgx_status_t ocall_worker_request( - [in, size = req_size] uint8_t * request, uint32_t req_size, - [in, size=parentchain_id_size] uint8_t* parentchain_id, uint32_t parentchain_id_size, - [out, size = resp_size] uint8_t * response, uint32_t resp_size - ); - - sgx_status_t ocall_update_metric( - [in, size = metric_size] uint8_t * metric, uint32_t metric_size - ); - - sgx_status_t ocall_send_to_parentchain( - [in, size = extrinsics_size] uint8_t * extrinsics, uint32_t extrinsics_size, - [in, size=parentchain_id_size] uint8_t* parentchain_id, uint32_t parentchain_id_size, - [in, size=watch_until_size] uint8_t* watch_until, uint32_t watch_until_size, - [out, size = resp_size] uint8_t * response, uint32_t resp_size - ); - }; -}; diff --git a/tee-worker/bitacross/enclave-runtime/Enclave.lds b/tee-worker/bitacross/enclave-runtime/Enclave.lds deleted file mode 100644 index e3d9d0ee0d..0000000000 --- a/tee-worker/bitacross/enclave-runtime/Enclave.lds +++ /dev/null @@ -1,9 +0,0 @@ -enclave.so -{ - global: - g_global_data_sim; - g_global_data; - enclave_entry; - local: - *; -}; diff --git a/tee-worker/bitacross/enclave-runtime/Enclave_private.pem b/tee-worker/bitacross/enclave-runtime/Enclave_private.pem deleted file mode 100644 index 529d07be35..0000000000 --- a/tee-worker/bitacross/enclave-runtime/Enclave_private.pem +++ /dev/null @@ -1,39 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -MIIG4gIBAAKCAYEAroOogvsj/fZDZY8XFdkl6dJmky0lRvnWMmpeH41Bla6U1qLZ -AmZuyIF+mQC/cgojIsrBMzBxb1kKqzATF4+XwPwgKz7fmiddmHyYz2WDJfAjIveJ -ZjdMjM4+EytGlkkJ52T8V8ds0/L2qKexJ+NBLxkeQLfV8n1mIk7zX7jguwbCG1Pr -nEMdJ3Sew20vnje+RsngAzdPChoJpVsWi/K7cettX/tbnre1DL02GXc5qJoQYk7b -3zkmhz31TgFrd9VVtmUGyFXAysuSAb3EN+5VnHGr0xKkeg8utErea2FNtNIgua8H -ONfm9Eiyaav1SVKzPHlyqLtcdxH3I8Wg7yqMsaprZ1n5A1v/levxnL8+It02KseD -5HqV4rf/cImSlCt3lpRg8U5E1pyFQ2IVEC/XTDMiI3c+AR+w2jSRB3Bwn9zJtFlW -KHG3m1xGI4ck+Lci1JvWWLXQagQSPtZTsubxTQNx1gsgZhgv1JHVZMdbVlAbbRMC -1nSuJNl7KPAS/VfzAgEDAoIBgHRXxaynbVP5gkO0ug6Qw/E27wzIw4SmjsxG6Wpe -K7kfDeRskKxESdsA/xCrKkwGwhcx1iIgS5+Qscd1Yg+1D9X9asd/P7waPmWoZd+Z -AhlKwhdPsO7PiF3e1AzHhGQwsUTt/Y/aSI1MpHBvy2/s1h9mFCslOUxTmWw0oj/Q -ldIEgWeNR72CE2+jFIJIyml6ftnb6qzPiga8Bm48ubKh0kvySOqnkmnPzgh+JBD6 -JnBmtZbfPT97bwTT+N6rnPqOOApvfHPf15kWI8yDbprG1l4OCUaIUH1AszxLd826 -5IPM+8gINLRDP1MA6azECPjTyHXhtnSIBZCyWSVkc05vYmNXYUNiXWMajcxW9M02 -wKzFELO8NCEAkaTPxwo4SCyIjUxiK1LbQ9h8PSy4c1+gGP4LAMR8xqP4QKg6zdu9 -osUGG/xRe/uufgTBFkcjqBHtK5L5VI0jeNIUAgW/6iNbYXjBMJ0GfauLs+g1VsOm -WfdgXzsb9DYdMa0OXXHypmV4GwKBwQDUwQj8RKJ6c8cT4vcWCoJvJF00+RFL+P3i -Gx2DLERxRrDa8AVGfqaCjsR+3vLgG8V/py+z+dxZYSqeB80Qeo6PDITcRKoeAYh9 -xlT3LJOS+k1cJcEmlbbO2IjLkTmzSwa80fWexKu8/Xv6vv15gpqYl1ngYoqJM3pd -vzmTIOi7MKSZ0WmEQavrZj8zK4endE3v0eAEeQ55j1GImbypSf7Idh7wOXtjZ7WD -Dg6yWDrri+AP/L3gClMj8wsAxMV4ZR8CgcEA0fzDHkFa6raVOxWnObmRoDhAtE0a -cjUj976NM5yyfdf2MrKy4/RhdTiPZ6b08/lBC/+xRfV3xKVGzacm6QjqjZrUpgHC -0LKiZaMtccCJjLtPwQd0jGQEnKfMFaPsnhOc5y8qVkCzVOSthY5qhz0XNotHHFmJ -gffVgB0iqrMTvSL7IA2yqqpOqNRlhaYhNl8TiFP3gIeMtVa9rZy31JPgT2uJ+kfo -gV7sdTPEjPWZd7OshGxWpT6QfVDj/T9T7L6tAoHBAI3WBf2DFvxNL2KXT2QHAZ9t -k3imC4f7U+wSE6zILaDZyzygA4RUbwG0gv8/TJVn2P/Eynf76DuWHGlaiLWnCbSz -Az2DHBQBBaku409zDQym3j1ugMRjzzSQWzJg0SIyBH3hTmnYcn3+Uqcp/lEBvGW6 -O+rsXFt3pukqJmIV8HzLGGaLm62BHUeZf3dyWm+i3p/hQAL7Xvu04QW70xuGqdr5 -afV7p5eaeQIJXyGQJ0eylV/90+qxjMKiB1XYg6WYvwKBwQCL/ddpgOdHJGN8uRom -e7Zq0Csi3hGheMKlKbN3vcxT5U7MdyHtTZZOJbTvxKNNUNYH/8uD+PqDGNneb29G -BfGzvI3EASyLIcGZF3OhKwZd0jUrWk2y7Vhob91jwp2+t73vdMbkKyI4mHOuXvGv -fg95si9oO7EBT+Oqvhccd2J+F1IVXncccYnF4u5ZGWt5lLewN/pVr7MjjykeaHqN -t+rfnQam2psA6fL4zS2zTmZPzR2tnY8Y1GBTi0Ko1OKd1HMCgcAb5cB/7/AQlhP9 -yQa04PLH9ygQkKKptZp7dy5WcWRx0K/hAHRoi2aw1wZqfm7VBNu2SLcs90kCCCxp -6C5sfJi6b8NpNbIPC+sc9wsFr7pGo9SFzQ78UlcWYK2Gu2FxlMjonhka5hvo4zvg -WxlpXKEkaFt3gLd92m/dMqBrHfafH7VwOJY2zT3WIpjwuk0ZzmRg5p0pG/svVQEH -NZmwRwlopysbR69B/n1nefJ84UO50fLh5s5Zr3gBRwbWNZyzhXk= ------END RSA PRIVATE KEY----- diff --git a/tee-worker/bitacross/enclave-runtime/Makefile b/tee-worker/bitacross/enclave-runtime/Makefile deleted file mode 100644 index 41286a26c3..0000000000 --- a/tee-worker/bitacross/enclave-runtime/Makefile +++ /dev/null @@ -1,68 +0,0 @@ -# Copyright (C) 2017-2018 Baidu, Inc. All Rights Reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions -# are met: -# -# * Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above copyright -# notice, this list of conditions and the following disclaimer in -# the documentation and/or other materials provided with the -# distribution. -# * Neither the name of Baidu, Inc., nor the names of its -# contributors may be used to endorse or promote products derived -# from this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -######## Worker Feature Settings ######## -# Set offchain-worker as default feature mode -WORKER_MODE ?= offchain-worker -WORKER_DEV ?= 0 -RA_METHOD ?= dcap - -Rust_Enclave_Name := libenclave.a -Rust_Enclave_Files := $(wildcard src/*.rs) $(wildcard ../stf/src/*.rs) -RUSTFLAGS :="-C target-feature=+avx2" - -ifeq ($(SGX_DEBUG), 1) - OUTPUT_PATH := debug - CARGO_TARGET := -else - OUTPUT_PATH := release - CARGO_TARGET := --release -endif - -ifeq ($(SGX_PRODUCTION), 1) - ENCLAVE_FEATURES = --features=$(WORKER_MODE),$(ADDITIONAL_FEATURES) -else - ENCLAVE_FEATURES = --features=test,development,$(WORKER_MODE),$(ADDITIONAL_FEATURES) -endif - -ifeq ($(WORKER_DEV), 1) - ADDITIONAL_FEATURES := $(ADDITIONAL_FEATURES),development -endif - -ifeq ($(RA_METHOD), dcap) - ADDITIONAL_FEATURES := $(ADDITIONAL_FEATURES),dcap -endif - -.PHONY: all - -all: $(Rust_Enclave_Name) - -$(Rust_Enclave_Name): $(Rust_Enclave_Files) - RUSTFLAGS=$(RUSTFLAGS) cargo build $(CARGO_TARGET) $(ENCLAVE_FEATURES) - cp ./target/$(OUTPUT_PATH)/libenclave_runtime.a ../lib/libenclave.a - diff --git a/tee-worker/bitacross/enclave-runtime/README.md b/tee-worker/bitacross/enclave-runtime/README.md deleted file mode 100644 index a4b88a52d1..0000000000 --- a/tee-worker/bitacross/enclave-runtime/README.md +++ /dev/null @@ -1,2 +0,0 @@ -# sidechain dependency graph -cargo depgraph --features dcap,sidechain --include enclave-runtime,itp-types,ita-stf | dot -Tsvg > dependency-graph.svg diff --git a/tee-worker/bitacross/enclave-runtime/rust-toolchain.toml b/tee-worker/bitacross/enclave-runtime/rust-toolchain.toml deleted file mode 100644 index 23ed88e6c8..0000000000 --- a/tee-worker/bitacross/enclave-runtime/rust-toolchain.toml +++ /dev/null @@ -1,4 +0,0 @@ -[toolchain] -channel = "nightly-2022-10-22" -targets = ["wasm32-unknown-unknown"] -profile = "default" # include rustfmt, clippy diff --git a/tee-worker/bitacross/enclave-runtime/rustfmt.toml b/tee-worker/bitacross/enclave-runtime/rustfmt.toml deleted file mode 100644 index 104b9aa998..0000000000 --- a/tee-worker/bitacross/enclave-runtime/rustfmt.toml +++ /dev/null @@ -1,18 +0,0 @@ -# Basic -hard_tabs = true -max_width = 100 -use_small_heuristics = "Max" -# Imports -imports_granularity = "Crate" -reorder_imports = true -# Consistency -newline_style = "Unix" -# Misc -chain_width = 80 -spaces_around_ranges = false -match_arm_leading_pipes = "Preserve" -match_arm_blocks = false -match_block_trailing_comma = true -trailing_comma = "Vertical" -trailing_semicolon = false -use_field_init_shorthand = true \ No newline at end of file diff --git a/tee-worker/bitacross/enclave-runtime/src/attestation.rs b/tee-worker/bitacross/enclave-runtime/src/attestation.rs deleted file mode 100644 index 732f6d2851..0000000000 --- a/tee-worker/bitacross/enclave-runtime/src/attestation.rs +++ /dev/null @@ -1,583 +0,0 @@ -// Copyright 2022 Integritee AG and Supercomputing Systems AG -// Copyright (C) 2017-2019 Baidu, Inc. All Rights Reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions -// are met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in -// the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Baidu, Inc., nor the names of its -// contributors may be used to endorse or promote products derived -// from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -use crate::{ - initialization::global_components::{ - GLOBAL_ATTESTATION_HANDLER_COMPONENT, GLOBAL_SHIELDING_KEY_REPOSITORY_COMPONENT, - }, - utils::{ - get_extrinsic_factory_from_integritee_solo_or_parachain, - get_node_metadata_repository_from_integritee_solo_or_parachain, - }, - Error as EnclaveError, Result as EnclaveResult, -}; -use codec::{Decode, Encode}; -use itp_attestation_handler::{AttestationHandler, RemoteAttestationType, SgxQlQveCollateral}; -use itp_component_container::ComponentGetter; -use itp_extrinsics_factory::CreateExtrinsics; -use itp_node_api::metadata::{ - pallet_teebag::TeebagCallIndexes, - provider::{AccessNodeMetadata, Error as MetadataProviderError}, - Error as MetadataError, -}; -use itp_node_api_metadata::NodeMetadata; -use itp_settings::worker::MR_ENCLAVE_SIZE; -use itp_sgx_crypto::{ - ed25519_derivation::DeriveEd25519, key_repository::AccessKey, Error as SgxCryptoError, -}; -use itp_types::{AttestationType, DcapProvider, OpaqueCall, WorkerType}; -use itp_utils::write_slice_and_whitespace_pad; -use litentry_primitives::WorkerMode; -use log::*; -use sgx_types::*; -use sp_core::{ed25519::Public as Ed25519Public, Pair}; -use sp_runtime::OpaqueExtrinsic; -use std::{prelude::v1::*, slice, vec::Vec}; - -#[no_mangle] -pub unsafe extern "C" fn get_mrenclave(mrenclave: *mut u8, mrenclave_size: usize) -> sgx_status_t { - if mrenclave.is_null() || mrenclave_size < MR_ENCLAVE_SIZE { - return sgx_status_t::SGX_ERROR_INVALID_PARAMETER - } - let attestation_handler = match GLOBAL_ATTESTATION_HANDLER_COMPONENT.get() { - Ok(r) => r, - Err(e) => { - error!("Component get failure: {:?}", e); - return sgx_status_t::SGX_ERROR_UNEXPECTED - }, - }; - match attestation_handler.get_mrenclave() { - Ok(mrenclave_value) => { - let mrenclave_slice = slice::from_raw_parts_mut(mrenclave, mrenclave_size); - if let Err(e) = - write_slice_and_whitespace_pad(mrenclave_slice, mrenclave_value.to_vec()) - { - error!("Failed to transfer mrenclave to o-call buffer: {:?}", e); - return sgx_status_t::SGX_ERROR_UNEXPECTED - } - sgx_status_t::SGX_SUCCESS - }, - Err(e) => e.into(), - } -} - -// FIXME: add dcap suppoort for call site -pub fn create_ra_report_and_signature( - skip_ra: bool, - remote_attestation_type: RemoteAttestationType, - sign_type: sgx_quote_sign_type_t, - quoting_enclave_target_info: Option<&sgx_target_info_t>, - quote_size: Option<&u32>, -) -> EnclaveResult<(Vec, Vec)> { - let attestation_handler = match GLOBAL_ATTESTATION_HANDLER_COMPONENT.get() { - Ok(r) => r, - Err(e) => { - error!("Component get failure: {:?}", e); - return Err(e.into()) - }, - }; - - match remote_attestation_type { - RemoteAttestationType::Epid => { - match attestation_handler.create_epid_ra_report_and_signature(sign_type, skip_ra) { - Ok(epid) => Ok(epid), - Err(e) => { - error!("create_epid_ra_report_and_signature failure: {:?}", e); - Err(e.into()) - }, - } - }, - RemoteAttestationType::Dcap => { - match attestation_handler.generate_dcap_ra_cert( - quoting_enclave_target_info, - quote_size, - skip_ra, - ) { - Ok((key_der, cert_der, _qe_quote)) => Ok((key_der, cert_der)), - Err(e) => { - error!("generate_dcap_ra_cert failure: {:?}", e); - Err(e.into()) - }, - } - }, - } -} - -#[no_mangle] -pub unsafe extern "C" fn generate_ias_ra_extrinsic( - w_url: *const u8, - w_url_size: u32, - unchecked_extrinsic: *mut u8, - unchecked_extrinsic_max_size: u32, - unchecked_extrinsic_size: *mut u32, - skip_ra: c_int, -) -> sgx_status_t { - if w_url.is_null() || unchecked_extrinsic.is_null() { - return sgx_status_t::SGX_ERROR_INVALID_PARAMETER - } - let mut url_slice = slice::from_raw_parts(w_url, w_url_size as usize); - let url = match String::decode(&mut url_slice) { - // Litentry: the teebag extrinsic expects an URL with plain utf8 encoded Vec, not string scale-encoded - Ok(url) => url.as_bytes().to_vec(), - Err(_) => - return EnclaveError::Other("Could not decode url slice to a valid String".into()).into(), - }; - let extrinsic_slice = - slice::from_raw_parts_mut(unchecked_extrinsic, unchecked_extrinsic_max_size as usize); - - let extrinsic = match generate_ias_ra_extrinsic_internal(url, skip_ra == 1) { - Ok(xt) => xt, - Err(e) => return e.into(), - }; - - *unchecked_extrinsic_size = - match write_slice_and_whitespace_pad(extrinsic_slice, extrinsic.encode()) { - Ok(l) => l as u32, - Err(e) => return EnclaveError::BufferError(e).into(), - }; - sgx_status_t::SGX_SUCCESS -} - -#[no_mangle] -pub unsafe extern "C" fn generate_dcap_ra_extrinsic( - w_url: *const u8, - w_url_size: u32, - unchecked_extrinsic: *mut u8, - unchecked_extrinsic_max_size: u32, - unchecked_extrinsic_size: *mut u32, - skip_ra: c_int, - quoting_enclave_target_info: Option<&sgx_target_info_t>, - quote_size: Option<&u32>, -) -> sgx_status_t { - if w_url.is_null() || unchecked_extrinsic.is_null() { - return sgx_status_t::SGX_ERROR_INVALID_PARAMETER - } - let mut url_slice = slice::from_raw_parts(w_url, w_url_size as usize); - let url = match String::decode(&mut url_slice) { - // Litentry: the teebag extrinsic expects an URL with plain utf8 encoded Vec, not string scale-encoded - Ok(url) => url.as_bytes().to_vec(), - Err(_) => - return EnclaveError::Other("Could not decode url slice to a valid String".into()).into(), - }; - let extrinsic_slice = - slice::from_raw_parts_mut(unchecked_extrinsic, unchecked_extrinsic_max_size as usize); - - let extrinsic = match generate_dcap_ra_extrinsic_internal( - url, - skip_ra == 1, - quoting_enclave_target_info, - quote_size, - ) { - Ok(xt) => xt, - Err(e) => return e.into(), - }; - - *unchecked_extrinsic_size = - match write_slice_and_whitespace_pad(extrinsic_slice, extrinsic.encode()) { - Ok(l) => l as u32, - Err(e) => return EnclaveError::BufferError(e).into(), - }; - sgx_status_t::SGX_SUCCESS -} - -pub fn generate_dcap_ra_extrinsic_internal( - url: Vec, - skip_ra: bool, - quoting_enclave_target_info: Option<&sgx_target_info_t>, - quote_size: Option<&u32>, -) -> EnclaveResult { - let attestation_handler = GLOBAL_ATTESTATION_HANDLER_COMPONENT.get()?; - - if !skip_ra { - let (_priv_key_der, _cert_der, dcap_quote) = attestation_handler.generate_dcap_ra_cert( - quoting_enclave_target_info, - quote_size, - skip_ra, - )?; - - generate_dcap_ra_extrinsic_from_quote_internal(url, &dcap_quote) - } else { - generate_dcap_skip_ra_extrinsic_from_mr_enclave( - url, - &attestation_handler.get_mrenclave()?.encode(), - ) - } -} - -#[no_mangle] -pub unsafe extern "C" fn generate_dcap_ra_quote( - skip_ra: c_int, - quoting_enclave_target_info: &sgx_target_info_t, - quote_size: u32, - dcap_quote_p: *mut u8, - dcap_quote_size: u32, -) -> sgx_status_t { - if dcap_quote_p.is_null() { - return sgx_status_t::SGX_ERROR_INVALID_PARAMETER - } - let dcap_quote = match generate_dcap_ra_quote_internal( - skip_ra == 1, - quoting_enclave_target_info, - quote_size, - ) { - Ok(dcap_quote) => dcap_quote, - Err(e) => return e.into(), - }; - - let dcap_quote_slice = slice::from_raw_parts_mut(dcap_quote_p, dcap_quote_size as usize); - - if let Err(e) = write_slice_and_whitespace_pad(dcap_quote_slice, dcap_quote) { - return EnclaveError::BufferError(e).into() - }; - - sgx_status_t::SGX_SUCCESS -} - -pub fn generate_dcap_ra_quote_internal( - skip_ra: bool, - quoting_enclave_target_info: &sgx_target_info_t, - quote_size: u32, -) -> EnclaveResult> { - let attestation_handler = GLOBAL_ATTESTATION_HANDLER_COMPONENT.get()?; - - let (_priv_key_der, _cert_der, dcap_quote) = attestation_handler.generate_dcap_ra_cert( - Some(quoting_enclave_target_info), - Some("e_size), - skip_ra, - )?; - - Ok(dcap_quote) -} - -#[no_mangle] -pub unsafe extern "C" fn generate_dcap_ra_extrinsic_from_quote( - w_url: *const u8, - w_url_size: u32, - quote: *const u8, - quote_size: u32, - unchecked_extrinsic: *mut u8, - unchecked_extrinsic_max_size: u32, - unchecked_extrinsic_size: *mut u32, -) -> sgx_status_t { - if w_url.is_null() || unchecked_extrinsic.is_null() { - return sgx_status_t::SGX_ERROR_INVALID_PARAMETER - } - let mut url_slice = slice::from_raw_parts(w_url, w_url_size as usize); - let url = match String::decode(&mut url_slice) { - // Litentry: the teebag extrinsic expects an URL with plain utf8 encoded Vec, not string scale-encoded - Ok(url) => url.as_bytes().to_vec(), - Err(_) => - return EnclaveError::Other("Could not decode url slice to a valid String".into()).into(), - }; - - let extrinsic_slice = - slice::from_raw_parts_mut(unchecked_extrinsic, unchecked_extrinsic_max_size as usize); - - let quote_slice = slice::from_raw_parts(quote, quote_size as usize); - - let extrinsic = match generate_dcap_ra_extrinsic_from_quote_internal(url, quote_slice) { - Ok(xt) => xt, - Err(e) => return e.into(), - }; - - *unchecked_extrinsic_size = - match write_slice_and_whitespace_pad(extrinsic_slice, extrinsic.encode()) { - Ok(l) => l as u32, - Err(e) => return EnclaveError::BufferError(e).into(), - }; - sgx_status_t::SGX_SUCCESS -} - -pub fn generate_dcap_ra_extrinsic_from_quote_internal( - url: Vec, - quote: &[u8], -) -> EnclaveResult { - let node_metadata_repo = get_node_metadata_repository_from_integritee_solo_or_parachain()?; - trace!(" [Enclave] Compose register enclave getting callIDs:"); - - let call_ids = node_metadata_repo - .get_from_metadata(|m| m.register_enclave_call_indexes())? - .map_err(MetadataProviderError::MetadataError)?; - trace!(" [Enclave] Compose register enclave call DCAP IDs: {:?}", call_ids); - - let shielding_pubkey = get_shielding_pubkey()?; - let vc_pubkey = get_vc_pubkey()?; - let attestation_type = AttestationType::Dcap(DcapProvider::Intel); // skip_ra should be false here already - - let call = OpaqueCall::from_tuple(&( - call_ids, - WorkerType::BitAcross, - WorkerMode::OffChainWorker, - quote, - url, - shielding_pubkey, - vc_pubkey, - attestation_type, - )); - trace!(" [Enclave] Compose register enclave got extrinsic, returning"); - create_extrinsics(call) -} - -pub fn generate_dcap_skip_ra_extrinsic_from_mr_enclave( - url: Vec, - quote: &[u8], -) -> EnclaveResult { - let node_metadata_repo = get_node_metadata_repository_from_integritee_solo_or_parachain()?; - trace!(" [Enclave] Compose register enclave (skip-ra) getting callIDs:"); - - let call_ids = node_metadata_repo - .get_from_metadata(|m| m.register_enclave_call_indexes())? - .map_err(MetadataProviderError::MetadataError)?; - trace!(" [Enclave] Compose register enclave (skip-ra) call DCAP IDs: {:?}", call_ids); - - let shielding_pubkey = get_shielding_pubkey()?; - let vc_pubkey = get_vc_pubkey()?; - - let call = OpaqueCall::from_tuple(&( - call_ids, - WorkerType::BitAcross, - WorkerMode::OffChainWorker, - quote, - url, - shielding_pubkey, - vc_pubkey, - AttestationType::Ignore, - )); - info!(" [Enclave] Compose register enclave (skip-ra) got extrinsic, returning"); - create_extrinsics(call) -} - -fn generate_ias_ra_extrinsic_internal( - url: Vec, - skip_ra: bool, -) -> EnclaveResult { - let attestation_handler = GLOBAL_ATTESTATION_HANDLER_COMPONENT.get()?; - let cert_der = attestation_handler.generate_ias_ra_cert(skip_ra)?; - - generate_ias_ra_extrinsic_from_der_cert_internal(url, &cert_der, skip_ra) -} - -pub fn generate_ias_ra_extrinsic_from_der_cert_internal( - url: Vec, - cert_der: &[u8], - skip_ra: bool, -) -> EnclaveResult { - let node_metadata_repo = get_node_metadata_repository_from_integritee_solo_or_parachain()?; - - info!(" [Enclave] Compose register ias enclave (skip-ra) call"); - let call_ids = node_metadata_repo - .get_from_metadata(|m| m.register_enclave_call_indexes())? - .map_err(MetadataProviderError::MetadataError)?; - - let shielding_pubkey = get_shielding_pubkey()?; - let vc_pubkey = get_vc_pubkey()?; - let attestation_type = if skip_ra { AttestationType::Ignore } else { AttestationType::Ias }; - - let call = OpaqueCall::from_tuple(&( - call_ids, - WorkerType::BitAcross, - WorkerMode::OffChainWorker, - cert_der, - url, - shielding_pubkey, - vc_pubkey, - attestation_type, - )); - create_extrinsics(call) -} - -fn create_extrinsics(call: OpaqueCall) -> EnclaveResult { - let extrinsics_factory = get_extrinsic_factory_from_integritee_solo_or_parachain()?; - let extrinsics = extrinsics_factory.create_extrinsics(&[call], None)?; - - match extrinsics.get(0) { - Some(xt) => Ok(xt.clone()), - None => Err(EnclaveError::Other("Could not create extrinsic".into())), - } -} - -#[no_mangle] -pub unsafe extern "C" fn generate_register_quoting_enclave_extrinsic( - collateral: *const sgx_ql_qve_collateral_t, - unchecked_extrinsic: *mut u8, - unchecked_extrinsic_max_size: u32, - unchecked_extrinsic_size: *mut u32, -) -> sgx_status_t { - if unchecked_extrinsic.is_null() || collateral.is_null() { - return sgx_status_t::SGX_ERROR_INVALID_PARAMETER - } - let extrinsic_slice = - slice::from_raw_parts_mut(unchecked_extrinsic, unchecked_extrinsic_max_size as usize); - let collateral = SgxQlQveCollateral::from_c_type(&*collateral); - let collateral_data = match collateral.get_quoting_enclave_split() { - Some(d) => d, - None => return sgx_status_t::SGX_ERROR_INVALID_PARAMETER, - }; - - let call_index_getter = |m: &NodeMetadata| m.register_quoting_enclave_call_indexes(); - *unchecked_extrinsic_size = match generate_generic_register_collateral_extrinsic( - call_index_getter, - extrinsic_slice, - &collateral_data.0, - &collateral_data.1, - &collateral.qe_identity_issuer_chain, - ) { - Ok(l) => l as u32, - Err(e) => return e.into(), - }; - sgx_status_t::SGX_SUCCESS -} - -#[no_mangle] -pub unsafe extern "C" fn generate_register_tcb_info_extrinsic( - collateral: *const sgx_ql_qve_collateral_t, - unchecked_extrinsic: *mut u8, - unchecked_extrinsic_max_size: u32, - unchecked_extrinsic_size: *mut u32, -) -> sgx_status_t { - if unchecked_extrinsic.is_null() || collateral.is_null() { - return sgx_status_t::SGX_ERROR_INVALID_PARAMETER - } - let extrinsic_slice = - slice::from_raw_parts_mut(unchecked_extrinsic, unchecked_extrinsic_max_size as usize); - let collateral = SgxQlQveCollateral::from_c_type(&*collateral); - let collateral_data = match collateral.get_tcb_info_split() { - Some(d) => d, - None => return sgx_status_t::SGX_ERROR_INVALID_PARAMETER, - }; - - let call_index_getter = |m: &NodeMetadata| m.register_tcb_info_call_indexes(); - *unchecked_extrinsic_size = match generate_generic_register_collateral_extrinsic( - call_index_getter, - extrinsic_slice, - &collateral_data.0, - &collateral_data.1, - &collateral.tcb_info_issuer_chain, - ) { - Ok(l) => l as u32, - Err(e) => return e.into(), - }; - sgx_status_t::SGX_SUCCESS -} - -pub fn generate_generic_register_collateral_extrinsic( - getter: F, - extrinsic_slice: &mut [u8], - collateral_data: &str, - data_signature: &[u8], - issuer_chain: &[u8], -) -> EnclaveResult -where - F: Fn(&NodeMetadata) -> Result<[u8; 2], MetadataError>, -{ - let node_metadata_repo = get_node_metadata_repository_from_integritee_solo_or_parachain()?; - let call_ids = node_metadata_repo - .get_from_metadata(getter)? - .map_err(MetadataProviderError::MetadataError)?; - info!(" [Enclave] Compose register collateral call: {:?}", call_ids); - let call = OpaqueCall::from_tuple(&(call_ids, collateral_data, data_signature, issuer_chain)); - - let xt = create_extrinsics(call)?; - write_slice_and_whitespace_pad(extrinsic_slice, xt.encode()) - .map_err(|e| format!("{:?}", e).into()) -} - -#[no_mangle] -pub extern "C" fn dump_ias_ra_cert_to_disk() -> sgx_status_t { - let attestation_handler = match GLOBAL_ATTESTATION_HANDLER_COMPONENT.get() { - Ok(r) => r, - Err(e) => { - error!("Component get failure: {:?}", e); - return sgx_status_t::SGX_ERROR_UNEXPECTED - }, - }; - match attestation_handler.dump_ias_ra_cert_to_disk() { - Ok(_) => sgx_status_t::SGX_SUCCESS, - Err(e) => e.into(), - } -} - -#[no_mangle] -pub unsafe extern "C" fn dump_dcap_ra_cert_to_disk( - quoting_enclave_target_info: &sgx_target_info_t, - quote_size: u32, -) -> sgx_status_t { - let attestation_handler = match GLOBAL_ATTESTATION_HANDLER_COMPONENT.get() { - Ok(r) => r, - Err(e) => { - error!("Component get failure: {:?}", e); - return sgx_status_t::SGX_ERROR_UNEXPECTED - }, - }; - match attestation_handler.dump_dcap_ra_cert_to_disk(quoting_enclave_target_info, quote_size) { - Ok(_) => sgx_status_t::SGX_SUCCESS, - Err(e) => e.into(), - } -} - -#[no_mangle] -pub unsafe extern "C" fn dump_dcap_collateral_to_disk( - collateral: *const sgx_ql_qve_collateral_t, -) -> sgx_status_t { - let collateral = SgxQlQveCollateral::from_c_type(&*collateral); - collateral.dump_to_disk(); - sgx_status_t::SGX_SUCCESS -} - -fn get_shielding_pubkey() -> EnclaveResult>> { - let shielding_pubkey = GLOBAL_SHIELDING_KEY_REPOSITORY_COMPONENT - .get()? - .retrieve_key() - .and_then(|keypair| { - keypair - .export_pubkey() - .and_then(|pubkey| { - serde_json::to_vec(&pubkey).map_err(|e| SgxCryptoError::Serialization(e).into()) - }) - .map_err(|e| SgxCryptoError::Other(Box::new(e))) - }) - .ok(); - - Ok(shielding_pubkey) -} - -fn get_vc_pubkey() -> EnclaveResult> { - let vc_pubkey = GLOBAL_SHIELDING_KEY_REPOSITORY_COMPONENT - .get()? - .retrieve_key() - .and_then(|keypair| { - // vc signing pubkey - keypair.derive_ed25519().map(|keypair| keypair.public()) - }) - .ok(); - - debug!("[Enclave] VC pubkey: {:?}", vc_pubkey); - - Ok(vc_pubkey) -} diff --git a/tee-worker/bitacross/enclave-runtime/src/empty_impls.rs b/tee-worker/bitacross/enclave-runtime/src/empty_impls.rs deleted file mode 100644 index e011e4d19c..0000000000 --- a/tee-worker/bitacross/enclave-runtime/src/empty_impls.rs +++ /dev/null @@ -1,24 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -/// Empty tests entry for production mode. -#[cfg(not(feature = "test"))] -#[no_mangle] -#[allow(clippy::unreachable)] -pub extern "C" fn test_main_entrance() -> sgx_types::size_t { - unreachable!("Tests are not available when compiled in production mode.") -} diff --git a/tee-worker/bitacross/enclave-runtime/src/error.rs b/tee-worker/bitacross/enclave-runtime/src/error.rs deleted file mode 100644 index 48659a5672..0000000000 --- a/tee-worker/bitacross/enclave-runtime/src/error.rs +++ /dev/null @@ -1,87 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use derive_more::From; -use sgx_types::{sgx_quote3_error_t, sgx_status_t}; -use std::{boxed::Box, result::Result as StdResult, string::String}; - -pub type Result = StdResult; - -#[derive(Debug, From)] -pub enum Error { - TopPoolAuthor(itp_top_pool_author::error::Error), - Codec(codec::Error), - ComponentContainer(itp_component_container::error::Error), - Crypto(itp_sgx_crypto::Error), - ChainStorage(itp_ocall_api::Error), - ExtrinsicsFactory(itp_extrinsics_factory::error::Error), - IO(std::io::Error), - LightClient(itc_parentchain::light_client::error::Error), - NodeMetadataProvider(itp_node_api::metadata::provider::Error), - Sgx(sgx_status_t), - SgxQuote(sgx_quote3_error_t), - Stf(String), - StfStateHandler(itp_stf_state_handler::error::Error), - StfExecution(itp_stf_executor::error::Error), - ParentchainBlockImportDispatch(itc_parentchain::block_import_dispatcher::error::Error), - ExpectedTriggeredImportDispatcher, - CouldNotDispatchBlockImport, - NoShardAssigned, - NoLitentryParentchainAssigned, - NoTargetAParentchainAssigned, - NoTargetBParentchainAssigned, - ParentChainValidation(itp_storage::error::Error), - ParentChainSync, - PrimitivesAccess(itp_primitives_cache::error::Error), - MutexAccess, - Attestation(itp_attestation_handler::error::Error), - Metadata(itp_node_api_metadata::error::Error), - BufferError(itp_utils::buffer::BufferError), - Other(Box), -} - -impl From for sgx_status_t { - /// return sgx_status for top level enclave functions - fn from(error: Error) -> sgx_status_t { - match error { - Error::Sgx(status) => status, - _ => { - log::error!("Returning error {:?} as sgx unexpected.", error); - sgx_status_t::SGX_ERROR_UNEXPECTED - }, - } - } -} - -impl From for sgx_quote3_error_t { - /// return sgx_quote error - fn from(error: Error) -> sgx_quote3_error_t { - match error { - Error::SgxQuote(status) => status, - _ => { - log::error!("Returning error {:?} as sgx unexpected.", error); - sgx_quote3_error_t::SGX_QL_ERROR_UNEXPECTED - }, - } - } -} - -impl From for StdResult { - fn from(error: Error) -> StdResult { - Err(error) - } -} diff --git a/tee-worker/bitacross/enclave-runtime/src/initialization/global_components.rs b/tee-worker/bitacross/enclave-runtime/src/initialization/global_components.rs deleted file mode 100644 index 6e60d93af5..0000000000 --- a/tee-worker/bitacross/enclave-runtime/src/initialization/global_components.rs +++ /dev/null @@ -1,459 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -//! Defines all concrete types and global components of the enclave. -//! -//! This allows the crates themselves to stay as generic as possible -//! and ensures that the global instances are initialized once. -use crate::{ - initialization::parentchain::{ - integritee_parachain::IntegriteeParachainHandler, - integritee_solochain::IntegriteeSolochainHandler, - target_a_parachain::TargetAParachainHandler, target_a_solochain::TargetASolochainHandler, - target_b_parachain::TargetBParachainHandler, target_b_solochain::TargetBSolochainHandler, - }, - ocall::OcallApi, - rpc::rpc_response_channel::RpcResponseChannel, - tls_ra::seal_handler::SealHandler, -}; -use bc_enclave_registry::EnclaveRegistry; -use bc_relayer_registry::RelayerRegistry; -use bc_signer_registry::SignerRegistry; -use ita_parentchain_interface::{integritee, target_a, target_b}; -use ita_sgx_runtime::Runtime; -use ita_stf::{Getter, State as StfState, Stf, TrustedCallSigned}; -use itc_direct_rpc_server::{ - rpc_connection_registry::ConnectionRegistry, rpc_responder::RpcResponder, - rpc_watch_extractor::RpcWatchExtractor, rpc_ws_handler::RpcWsHandler, -}; -use itc_parentchain::{ - block_import_dispatcher::{ - immediate_dispatcher::ImmediateDispatcher, triggered_dispatcher::TriggeredDispatcher, - BlockImportDispatcher, - }, - block_importer::ParentchainBlockImporter, - indirect_calls_executor::{filter_metadata::EventCreator, IndirectCallsExecutor}, - light_client::{ - concurrent_access::ValidatorAccessor, io::LightClientStateSealSync, - light_validation::LightValidation, light_validation_state::LightValidationState, - }, -}; -use itc_tls_websocket_server::{ - config_provider::FromFileConfigProvider, ws_server::TungsteniteWsServer, ConnectionToken, -}; -use itp_attestation_handler::IntelAttestationHandler; -use itp_component_container::ComponentContainer; -use itp_extrinsics_factory::ExtrinsicsFactory; -use itp_import_queue::ImportQueue; -use itp_node_api::{ - api_client::PairSignature, - metadata::{provider::NodeMetadataRepository, NodeMetadata}, -}; -use itp_nonce_cache::NonceCache; -use itp_sgx_crypto::{ - ecdsa::{Pair as EcdsaPair, Seal as EcdsaSeal}, - key_repository::KeyRepository, - schnorr::{Pair as SchnorrPair, Seal as SchnorrSeal}, - Aes, AesSeal, Ed25519Seal, Rsa3072Seal, -}; -use itp_stf_executor::{ - enclave_signer::StfEnclaveSigner, executor::StfExecutor, getter_executor::GetterExecutor, - state_getter::StfStateGetter, -}; -use itp_stf_primitives::types::{Hash, TrustedOperation}; -use itp_stf_state_handler::{ - file_io::sgx::SgxStateFileIo, state_initializer::StateInitializer, - state_snapshot_repository::StateSnapshotRepository, StateHandler, -}; -use itp_stf_state_observer::state_observer::StateObserver; -use itp_top_pool::basic_pool::BasicPool; -use itp_top_pool_author::{ - api::SidechainApi, - author::{Author, AuthorTopFilter}, -}; -use itp_types::{Block as ParentchainBlock, SignedBlock as SignedParentchainBlock}; -use lazy_static::lazy_static; -use sgx_crypto_helper::rsa3072::Rsa3072KeyPair; -use sgx_tstd::vec::Vec; -use sp_core::{ed25519, ed25519::Pair}; -use std::sync::Arc; - -pub type EnclaveParentchainSigner = - itp_node_api::api_client::StaticExtrinsicSigner; - -pub type EnclaveGetter = Getter; -pub type EnclaveTrustedCallSigned = TrustedCallSigned; -pub type EnclaveStf = Stf; -pub type EnclaveStateKeyRepository = KeyRepository; -pub type EnclaveShieldingKeyRepository = KeyRepository; -pub type EnclaveSigningKeyRepository = KeyRepository; -pub type EnclaveBitcoinKeyRepository = KeyRepository; -pub type EnclaveEthereumKeyRepository = KeyRepository; -pub type EnclaveTonKeyRepository = KeyRepository; -pub type EnclaveStateFileIo = SgxStateFileIo; -pub type EnclaveStateSnapshotRepository = StateSnapshotRepository; -pub type EnclaveStateObserver = StateObserver; -pub type EnclaveStateInitializer = - StateInitializer; -pub type EnclaveStateHandler = - StateHandler; -pub type EnclaveGetterExecutor = - GetterExecutor, Getter>; -pub type EnclaveOCallApi = OcallApi; -pub type EnclaveNodeMetadataRepository = NodeMetadataRepository; -pub type EnclaveStfExecutor = StfExecutor< - EnclaveOCallApi, - EnclaveStateHandler, - EnclaveNodeMetadataRepository, - EnclaveStf, - EnclaveTrustedCallSigned, - EnclaveGetter, ->; -pub type EnclaveStfEnclaveSigner = StfEnclaveSigner< - EnclaveOCallApi, - EnclaveStateObserver, - EnclaveShieldingKeyRepository, - EnclaveStf, - EnclaveTopPoolAuthor, - EnclaveTrustedCallSigned, - EnclaveGetter, ->; -pub type EnclaveAttestationHandler = - IntelAttestationHandler; - -pub type EnclaveRpcConnectionRegistry = ConnectionRegistry; -pub type EnclaveRpcWsHandler = - RpcWsHandler, EnclaveRpcConnectionRegistry, Hash>; -pub type EnclaveWebSocketServer = TungsteniteWsServer; -pub type EnclaveRpcResponder = RpcResponder; -pub type EnclaveSidechainApi = SidechainApi; - -// Parentchain types relevant for all parentchains -pub type EnclaveLightClientSeal = - LightClientStateSealSync>; -pub type EnclaveExtrinsicsFactory = - ExtrinsicsFactory; - -pub type EnclaveValidatorAccessor = ValidatorAccessor< - LightValidation, - ParentchainBlock, - EnclaveLightClientSeal, ->; - -pub type IntegriteeParentchainBlockImportQueue = ImportQueue; -pub type TargetAParentchainBlockImportQueue = ImportQueue; -pub type TargetBParentchainBlockImportQueue = ImportQueue; - -/// Import queue for the events -/// -/// Note: `Vec` is correct. It should not be `Vec` -pub type IntegriteeParentchainEventImportQueue = ImportQueue>; -pub type TargetAParentchainEventImportQueue = ImportQueue>; -pub type TargetBParentchainEventImportQueue = ImportQueue>; - -// Stuff for the integritee parentchain - -pub type IntegriteeParentchainIndirectCallsExecutor = IndirectCallsExecutor< - EnclaveShieldingKeyRepository, - EnclaveStfEnclaveSigner, - EnclaveTopPoolAuthor, - EnclaveNodeMetadataRepository, - EventCreator, - integritee::ParentchainEventHandler, - EnclaveTrustedCallSigned, - EnclaveGetter, - RelayerRegistry, - SignerRegistry, - EnclaveRegistry, ->; - -pub type IntegriteeParentchainBlockImporter = ParentchainBlockImporter< - ParentchainBlock, - EnclaveValidatorAccessor, - EnclaveStfExecutor, - EnclaveExtrinsicsFactory, - IntegriteeParentchainIndirectCallsExecutor, - EnclaveOCallApi, ->; - -pub type IntegriteeParentchainTriggeredBlockImportDispatcher = TriggeredDispatcher< - IntegriteeParentchainBlockImporter, - IntegriteeParentchainBlockImportQueue, - IntegriteeParentchainEventImportQueue, ->; - -pub type IntegriteeParentchainImmediateBlockImportDispatcher = - ImmediateDispatcher; - -pub type IntegriteeParentchainBlockImportDispatcher = BlockImportDispatcher< - IntegriteeParentchainTriggeredBlockImportDispatcher, - IntegriteeParentchainImmediateBlockImportDispatcher, ->; - -// Stuff for the Target A parentchain - -/// IndirectCalls executor instance of the Target A parentchain. -/// -/// **Note**: The filter here is purely used for demo purposes. -/// -/// Also note that the extrinsic parser must be changed if the signed extra contains the -/// `AssetTxPayment`. -pub type TargetAParentchainIndirectCallsExecutor = IndirectCallsExecutor< - EnclaveShieldingKeyRepository, - EnclaveStfEnclaveSigner, - EnclaveTopPoolAuthor, - EnclaveNodeMetadataRepository, - EventCreator, - target_a::ParentchainEventHandler, - EnclaveTrustedCallSigned, - EnclaveGetter, - RelayerRegistry, - SignerRegistry, - EnclaveRegistry, ->; - -pub type TargetAParentchainBlockImporter = ParentchainBlockImporter< - ParentchainBlock, - EnclaveValidatorAccessor, - EnclaveStfExecutor, - EnclaveExtrinsicsFactory, - TargetAParentchainIndirectCallsExecutor, - EnclaveOCallApi, ->; - -pub type TargetAParentchainTriggeredBlockImportDispatcher = TriggeredDispatcher< - TargetAParentchainBlockImporter, - TargetAParentchainBlockImportQueue, - TargetAParentchainEventImportQueue, ->; - -pub type TargetAParentchainImmediateBlockImportDispatcher = - ImmediateDispatcher; - -pub type TargetAParentchainBlockImportDispatcher = BlockImportDispatcher< - TargetAParentchainTriggeredBlockImportDispatcher, - TargetAParentchainImmediateBlockImportDispatcher, ->; - -// Stuff for the Target B parentchain - -/// IndirectCalls executor instance of the Target B parentchain. -/// -/// **Note**: The filter here is purely used for demo purposes. -/// -/// Also note that the extrinsic parser must be changed if the signed extra contains the -/// `AssetTxPayment`. -pub type TargetBParentchainIndirectCallsExecutor = IndirectCallsExecutor< - EnclaveShieldingKeyRepository, - EnclaveStfEnclaveSigner, - EnclaveTopPoolAuthor, - EnclaveNodeMetadataRepository, - EventCreator, - target_b::ParentchainEventHandler, - EnclaveTrustedCallSigned, - EnclaveGetter, - RelayerRegistry, - SignerRegistry, - EnclaveRegistry, ->; - -pub type TargetBParentchainBlockImporter = ParentchainBlockImporter< - ParentchainBlock, - EnclaveValidatorAccessor, - EnclaveStfExecutor, - EnclaveExtrinsicsFactory, - TargetBParentchainIndirectCallsExecutor, - EnclaveOCallApi, ->; - -pub type TargetBParentchainTriggeredBlockImportDispatcher = TriggeredDispatcher< - TargetBParentchainBlockImporter, - TargetBParentchainBlockImportQueue, - TargetBParentchainEventImportQueue, ->; - -pub type TargetBParentchainImmediateBlockImportDispatcher = - ImmediateDispatcher; - -pub type TargetBParentchainBlockImportDispatcher = BlockImportDispatcher< - TargetBParentchainTriggeredBlockImportDispatcher, - TargetBParentchainImmediateBlockImportDispatcher, ->; - -/// Sidechain types -pub type EnclaveTopPool = BasicPool< - EnclaveSidechainApi, - ParentchainBlock, - EnclaveRpcResponder, - TrustedOperation, ->; - -pub type EnclaveTopPoolAuthor = Author< - EnclaveTopPool, - AuthorTopFilter, - EnclaveStateHandler, - EnclaveShieldingKeyRepository, - EnclaveTrustedCallSigned, - EnclaveGetter, ->; -pub type EnclaveSealHandler = SealHandler< - EnclaveShieldingKeyRepository, - EnclaveStateKeyRepository, - EnclaveStateHandler, - EnclaveLightClientSeal, - SignerRegistry, - EnclaveRegistry, ->; -pub type EnclaveOffchainWorkerExecutor = itc_offchain_worker_executor::executor::Executor< - ParentchainBlock, - EnclaveTopPoolAuthor, - EnclaveStfExecutor, - EnclaveStateHandler, - EnclaveValidatorAccessor, - EnclaveExtrinsicsFactory, - EnclaveStf, - EnclaveTrustedCallSigned, - EnclaveGetter, ->; - -// Base component instances -//------------------------------------------------------------------------------------------------- - -/// State key repository -pub static GLOBAL_STATE_KEY_REPOSITORY_COMPONENT: ComponentContainer = - ComponentContainer::new("State key repository"); - -/// Shielding key repository -pub static GLOBAL_SHIELDING_KEY_REPOSITORY_COMPONENT: ComponentContainer< - EnclaveShieldingKeyRepository, -> = ComponentContainer::new("Shielding key repository"); - -/// Signing key repository -pub static GLOBAL_SIGNING_KEY_REPOSITORY_COMPONENT: ComponentContainer< - EnclaveSigningKeyRepository, -> = ComponentContainer::new("Signing key repository"); - -/// Bitcoin key repository -pub static GLOBAL_BITCOIN_KEY_REPOSITORY_COMPONENT: ComponentContainer< - EnclaveBitcoinKeyRepository, -> = ComponentContainer::new("Bitcoin key repository"); - -/// Ethereum key repository -pub static GLOBAL_ETHEREUM_KEY_REPOSITORY_COMPONENT: ComponentContainer< - EnclaveEthereumKeyRepository, -> = ComponentContainer::new("Ethereum key repository"); - -/// Ton key repository -pub static GLOBAL_TON_KEY_REPOSITORY_COMPONENT: ComponentContainer = - ComponentContainer::new("Ton key repository"); - -/// Light client db seal for the Integritee parentchain -pub static GLOBAL_INTEGRITEE_PARENTCHAIN_LIGHT_CLIENT_SEAL: ComponentContainer< - EnclaveLightClientSeal, -> = ComponentContainer::new("Integritee Parentchain EnclaveLightClientSealSync"); - -/// Light client db seal for the Target A parentchain. -pub static GLOBAL_TARGET_A_PARENTCHAIN_LIGHT_CLIENT_SEAL: ComponentContainer< - EnclaveLightClientSeal, -> = ComponentContainer::new("Target A EnclaveLightClientSealSync"); - -/// Light client db seal for the Target A parentchain. -pub static GLOBAL_TARGET_B_PARENTCHAIN_LIGHT_CLIENT_SEAL: ComponentContainer< - EnclaveLightClientSeal, -> = ComponentContainer::new("Target B EnclaveLightClientSealSync"); - -/// O-Call API -pub static GLOBAL_OCALL_API_COMPONENT: ComponentContainer = - ComponentContainer::new("O-call API"); - -/// Trusted Web-socket server -pub static GLOBAL_WEB_SOCKET_SERVER_COMPONENT: ComponentContainer = - ComponentContainer::new("Web-socket server"); - -/// State handler. -pub static GLOBAL_STATE_HANDLER_COMPONENT: ComponentContainer = - ComponentContainer::new("state handler"); - -/// State observer. -pub static GLOBAL_STATE_OBSERVER_COMPONENT: ComponentContainer = - ComponentContainer::new("state observer"); - -/// TOP pool author. -pub static GLOBAL_TOP_POOL_AUTHOR_COMPONENT: ComponentContainer = - ComponentContainer::new("top_pool_author"); - -/// attestation handler -pub static GLOBAL_ATTESTATION_HANDLER_COMPONENT: ComponentContainer = - ComponentContainer::new("Attestation handler"); - -// Parentchain component instances -//------------------------------------------------------------------------------------------------- - -lazy_static! { - /// Global nonce cache for the Integritee Parentchain. - pub static ref GLOBAL_INTEGRITEE_PARENTCHAIN_NONCE_CACHE: Arc = Default::default(); - - /// Global nonce cache for the Target A parentchain.. - pub static ref GLOBAL_TARGET_A_PARENTCHAIN_NONCE_CACHE: Arc = Default::default(); - - /// Global nonce cache for the Target B parentchain.. - pub static ref GLOBAL_TARGET_B_PARENTCHAIN_NONCE_CACHE: Arc = Default::default(); -} - -/// Solochain Handler. -pub static GLOBAL_INTEGRITEE_SOLOCHAIN_HANDLER_COMPONENT: ComponentContainer< - IntegriteeSolochainHandler, -> = ComponentContainer::new("integritee solochain handler"); - -pub static GLOBAL_INTEGRITEE_PARACHAIN_HANDLER_COMPONENT: ComponentContainer< - IntegriteeParachainHandler, -> = ComponentContainer::new("integritee parachain handler"); - -pub static GLOBAL_TARGET_A_SOLOCHAIN_HANDLER_COMPONENT: ComponentContainer< - TargetASolochainHandler, -> = ComponentContainer::new("target A solochain handler"); - -pub static GLOBAL_TARGET_A_PARACHAIN_HANDLER_COMPONENT: ComponentContainer< - TargetAParachainHandler, -> = ComponentContainer::new("target A parachain handler"); - -pub static GLOBAL_TARGET_B_SOLOCHAIN_HANDLER_COMPONENT: ComponentContainer< - TargetBSolochainHandler, -> = ComponentContainer::new("target B solochain handler"); - -pub static GLOBAL_TARGET_B_PARACHAIN_HANDLER_COMPONENT: ComponentContainer< - TargetBParachainHandler, -> = ComponentContainer::new("target B parachain handler"); - -// Sidechain component instances -//------------------------------------------------------------------------------------------------- - -/// Enclave RPC WS handler. -pub static GLOBAL_RPC_WS_HANDLER_COMPONENT: ComponentContainer = - ComponentContainer::new("rpc_ws_handler"); - -/// Relayer registry -pub static GLOBAL_RELAYER_REGISTRY: ComponentContainer = - ComponentContainer::new("relayer_registry"); - -/// Signer registry -pub static GLOBAL_SIGNER_REGISTRY: ComponentContainer = - ComponentContainer::new("signer_registry"); - -/// Enclave registry -pub static GLOBAL_ENCLAVE_REGISTRY: ComponentContainer = - ComponentContainer::new("enclave_registry"); diff --git a/tee-worker/bitacross/enclave-runtime/src/initialization/mod.rs b/tee-worker/bitacross/enclave-runtime/src/initialization/mod.rs deleted file mode 100644 index dacb97c261..0000000000 --- a/tee-worker/bitacross/enclave-runtime/src/initialization/mod.rs +++ /dev/null @@ -1,517 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -#![allow(clippy::unwrap_used)] - -pub mod global_components; -pub mod parentchain; -use crate::{ - error::{Error, Result as EnclaveResult}, - get_node_metadata_repository_from_integritee_solo_or_parachain, - get_validator_accessor_from_integritee_solo_or_parachain, - initialization::global_components::{ - EnclaveGetterExecutor, EnclaveLightClientSeal, EnclaveRpcResponder, - EnclaveShieldingKeyRepository, EnclaveSidechainApi, EnclaveStateFileIo, - EnclaveStateHandler, EnclaveStateInitializer, EnclaveStateObserver, - EnclaveStateSnapshotRepository, EnclaveStfEnclaveSigner, EnclaveTopPool, - EnclaveTopPoolAuthor, GLOBAL_ATTESTATION_HANDLER_COMPONENT, - GLOBAL_BITCOIN_KEY_REPOSITORY_COMPONENT, GLOBAL_ETHEREUM_KEY_REPOSITORY_COMPONENT, - GLOBAL_INTEGRITEE_PARENTCHAIN_LIGHT_CLIENT_SEAL, GLOBAL_OCALL_API_COMPONENT, - GLOBAL_RPC_WS_HANDLER_COMPONENT, GLOBAL_SHIELDING_KEY_REPOSITORY_COMPONENT, - GLOBAL_SIGNING_KEY_REPOSITORY_COMPONENT, GLOBAL_STATE_HANDLER_COMPONENT, - GLOBAL_STATE_KEY_REPOSITORY_COMPONENT, GLOBAL_STATE_OBSERVER_COMPONENT, - GLOBAL_TARGET_A_PARENTCHAIN_LIGHT_CLIENT_SEAL, - GLOBAL_TARGET_B_PARENTCHAIN_LIGHT_CLIENT_SEAL, GLOBAL_TON_KEY_REPOSITORY_COMPONENT, - GLOBAL_TOP_POOL_AUTHOR_COMPONENT, GLOBAL_WEB_SOCKET_SERVER_COMPONENT, - }, - ocall::OcallApi, - rpc::{rpc_response_channel::RpcResponseChannel, worker_api_direct::public_api_rpc_handler}, - utils::get_extrinsic_factory_from_integritee_solo_or_parachain, - Hash, -}; -use base58::ToBase58; -use bc_enclave_registry::EnclaveRegistryUpdater; -use bc_musig2_ceremony::{CeremonyCommandTmp, CeremonyId, CeremonyRegistry, MuSig2Ceremony}; -use bc_relayer_registry::{RelayerRegistry, RelayerRegistryUpdater}; -use bc_signer_registry::SignerRegistryUpdater; -use bc_task_processor::{run_bit_across_handler_runner, BitAcrossTaskContext}; -use codec::Encode; -use ita_stf::{Getter, TrustedCallSigned}; -use itc_direct_rpc_server::{ - create_determine_watch, rpc_connection_registry::ConnectionRegistry, - rpc_responder::RpcResponder, rpc_ws_handler::RpcWsHandler, -}; - -use itc_parentchain_light_client::{concurrent_access::ValidatorAccess, ExtrinsicSender}; -use itc_tls_websocket_server::{ - certificate_generation::ed25519_self_signed_certificate, - config_provider::FromFileConfigProvider, ws_server::TungsteniteWsServer, ConnectionToken, - WebSocketServer, -}; -use itp_attestation_handler::IntelAttestationHandler; -use itp_component_container::{ComponentGetter, ComponentInitializer}; -use itp_extrinsics_factory::CreateExtrinsics; -use itp_node_api_metadata::pallet_bitacross::BitAcrossCallIndexes; -use itp_node_api_metadata_provider::AccessNodeMetadata; -use itp_primitives_cache::GLOBAL_PRIMITIVES_CACHE; -use itp_settings::files::{ - LITENTRY_PARENTCHAIN_LIGHT_CLIENT_DB_PATH, STATE_SNAPSHOTS_CACHE_SIZE, - TARGET_A_PARENTCHAIN_LIGHT_CLIENT_DB_PATH, TARGET_B_PARENTCHAIN_LIGHT_CLIENT_DB_PATH, -}; -use itp_sgx_crypto::{ - ecdsa::create_ecdsa_repository, - get_aes_repository, get_ed25519_repository, get_rsa3072_repository, - key_repository::{AccessKey, KeyRepository}, - schnorr::{create_schnorr_repository, Pair as SchnorrPair, Seal}, -}; - -use crate::initialization::global_components::{ - GLOBAL_ENCLAVE_REGISTRY, GLOBAL_RELAYER_REGISTRY, GLOBAL_SIGNER_REGISTRY, -}; -use bc_enclave_registry::EnclaveRegistry; -use bc_signer_registry::SignerRegistry; -use itp_stf_state_handler::{ - file_io::StateDir, handle_state::HandleState, query_shard_state::QueryShardState, - state_snapshot_repository::VersionedStateAccess, - state_snapshot_repository_loader::StateSnapshotRepositoryLoader, StateHandler, -}; -use itp_top_pool::pool::Options as PoolOptions; -use itp_top_pool_author::author::AuthorTopFilter; -use itp_types::{parentchain::ParentchainId, OpaqueCall, ShardIdentifier}; -use litentry_macros::if_development_or; -use log::*; -use sp_core::{crypto::Pair, H256}; -use std::{ - collections::HashMap, - path::PathBuf, - string::{String, ToString}, - sync::Arc, -}; - -use std::sync::SgxRwLock as RwLock; - -pub(crate) fn init_enclave( - mu_ra_url: String, - untrusted_worker_url: String, - base_dir: PathBuf, - ceremony_commands_thread_count: u8, - ceremony_events_thread_count: u8, -) -> EnclaveResult<()> { - info!("Ceremony commands thread count: {}", ceremony_commands_thread_count); - info!("Ceremony events thread count: {}", ceremony_events_thread_count); - - let signing_key_repository = Arc::new(get_ed25519_repository(base_dir.clone(), None, None)?); - - GLOBAL_SIGNING_KEY_REPOSITORY_COMPONENT.initialize(signing_key_repository.clone()); - let signer = signing_key_repository.retrieve_key()?; - info!("[Enclave initialized] Ed25519 prim raw : {:?}", signer.public().0); - - let bitcoin_key_repository = - Arc::new(create_schnorr_repository(base_dir.clone(), "bitcoin", None)?); - GLOBAL_BITCOIN_KEY_REPOSITORY_COMPONENT.initialize(bitcoin_key_repository.clone()); - let bitcoin_key = bitcoin_key_repository.retrieve_key()?; - info!("[Enclave initialized] Bitcoin public key raw : {:?}", bitcoin_key.public_bytes()); - - let ethereum_key_repository = - Arc::new(create_ecdsa_repository(base_dir.clone(), "ethereum", None)?); - GLOBAL_ETHEREUM_KEY_REPOSITORY_COMPONENT.initialize(ethereum_key_repository.clone()); - let ethereum_key = ethereum_key_repository.retrieve_key()?; - info!("[Enclave initialized] Ethereum public key raw : {:?}", ethereum_key.public_bytes()); - - let ton_key_repository = - Arc::new(get_ed25519_repository(base_dir.clone(), Some("ton".to_string()), None)?); - GLOBAL_TON_KEY_REPOSITORY_COMPONENT.initialize(ton_key_repository.clone()); - let ton_key = ton_key_repository.retrieve_key()?; - info!("[Enclave initialized] Ton public key raw : {:?}", ton_key.public().0); - - let shielding_key_repository = Arc::new(get_rsa3072_repository(base_dir.clone())?); - GLOBAL_SHIELDING_KEY_REPOSITORY_COMPONENT.initialize(shielding_key_repository.clone()); - - // Create the aes key that is used for state encryption such that a key is always present in tests. - // It will be overwritten anyway if mutual remote attestation is performed with the primary worker. - let state_key_repository = Arc::new(get_aes_repository(base_dir.clone())?); - GLOBAL_STATE_KEY_REPOSITORY_COMPONENT.initialize(state_key_repository.clone()); - - let integritee_light_client_seal = Arc::new(EnclaveLightClientSeal::new( - base_dir.join(LITENTRY_PARENTCHAIN_LIGHT_CLIENT_DB_PATH), - ParentchainId::Litentry, - )?); - GLOBAL_INTEGRITEE_PARENTCHAIN_LIGHT_CLIENT_SEAL.initialize(integritee_light_client_seal); - - let target_a_light_client_seal = Arc::new(EnclaveLightClientSeal::new( - base_dir.join(TARGET_A_PARENTCHAIN_LIGHT_CLIENT_DB_PATH), - ParentchainId::TargetA, - )?); - GLOBAL_TARGET_A_PARENTCHAIN_LIGHT_CLIENT_SEAL.initialize(target_a_light_client_seal); - - let target_b_light_client_seal = Arc::new(EnclaveLightClientSeal::new( - base_dir.join(TARGET_B_PARENTCHAIN_LIGHT_CLIENT_DB_PATH), - ParentchainId::TargetB, - )?); - GLOBAL_TARGET_B_PARENTCHAIN_LIGHT_CLIENT_SEAL.initialize(target_b_light_client_seal); - - let state_file_io = - Arc::new(EnclaveStateFileIo::new(state_key_repository, StateDir::new(base_dir.clone()))); - let state_initializer = - Arc::new(EnclaveStateInitializer::new(shielding_key_repository.clone())); - let state_snapshot_repository_loader = StateSnapshotRepositoryLoader::< - EnclaveStateFileIo, - EnclaveStateInitializer, - >::new(state_file_io, state_initializer.clone()); - - let state_snapshot_repository = - state_snapshot_repository_loader.load_snapshot_repository(STATE_SNAPSHOTS_CACHE_SIZE)?; - let state_observer = initialize_state_observer(&state_snapshot_repository)?; - GLOBAL_STATE_OBSERVER_COMPONENT.initialize(state_observer.clone()); - - let state_handler = Arc::new(StateHandler::load_from_repository( - state_snapshot_repository, - state_observer.clone(), - state_initializer, - )?); - - GLOBAL_STATE_HANDLER_COMPONENT.initialize(state_handler.clone()); - - let ocall_api = Arc::new(OcallApi); - GLOBAL_OCALL_API_COMPONENT.initialize(ocall_api.clone()); - - // For debug purposes, list shards. no problem to panic if fails. - #[allow(clippy::unwrap_used)] - let shards = state_handler.list_shards().unwrap(); - debug!("found the following {} shards on disk:", shards.len()); - for s in shards { - debug!("{}", s.encode().to_base58()) - } - - itp_primitives_cache::set_primitives( - GLOBAL_PRIMITIVES_CACHE.as_ref(), - mu_ra_url, - untrusted_worker_url, - ) - .map_err(Error::PrimitivesAccess)?; - - let watch_extractor = Arc::new(create_determine_watch::()); - - let connection_registry = Arc::new(ConnectionRegistry::::new()); - - // We initialize components for the public RPC / direct invocation server here, so we can start the server - // before registering on the parentchain. If we started the RPC AFTER registering on the parentchain and - // initializing the light-client, there is a period of time where a peer might want to reach us, - // but the RPC server is not yet up and running, resulting in error messages or even in that - // validateer completely breaking (IO PipeError). - // Corresponding GH issues are #545 and #600. - - let response_channel = Arc::new(RpcResponseChannel::default()); - let rpc_responder = - Arc::new(EnclaveRpcResponder::new(connection_registry.clone(), response_channel)); - - let top_pool_author = create_top_pool_author( - rpc_responder.clone(), - state_handler, - shielding_key_repository.clone(), - ); - GLOBAL_TOP_POOL_AUTHOR_COMPONENT.initialize(top_pool_author.clone()); - - let getter_executor = Arc::new(EnclaveGetterExecutor::new(state_observer)); - - let ceremony_registry = Arc::new(RwLock::new(HashMap::< - CeremonyId, - (Arc>>>, u64), - >::new())); - - let ceremony_command_tmp = Arc::new(RwLock::new(CeremonyCommandTmp::new())); - - let attestation_handler = - Arc::new(IntelAttestationHandler::new(ocall_api.clone(), signing_key_repository.clone())); - GLOBAL_ATTESTATION_HANDLER_COMPONENT.initialize(attestation_handler); - - let relayer_registry = RelayerRegistry::new(base_dir.clone()); - relayer_registry.init().map_err(|e| Error::Other(e.into()))?; - GLOBAL_RELAYER_REGISTRY.initialize(relayer_registry.into()); - - let signer_registry = Arc::new(SignerRegistry::new(base_dir.clone())); - signer_registry.init().map_err(|e| Error::Other(e.into()))?; - GLOBAL_SIGNER_REGISTRY.initialize(signer_registry.clone()); - - let enclave_registry = Arc::new(EnclaveRegistry::new(base_dir)); - enclave_registry.init().map_err(|e| Error::Other(e.into()))?; - GLOBAL_ENCLAVE_REGISTRY.initialize(enclave_registry); - - let io_handler = public_api_rpc_handler( - top_pool_author, - getter_executor, - shielding_key_repository, - ocall_api, - signing_key_repository, - bitcoin_key_repository, - ethereum_key_repository, - ton_key_repository, - signer_registry, - ); - let rpc_handler = Arc::new(RpcWsHandler::new(io_handler, watch_extractor, connection_registry)); - GLOBAL_RPC_WS_HANDLER_COMPONENT.initialize(rpc_handler); - - std::thread::spawn(move || { - run_bit_across_handler( - ceremony_registry, - ceremony_command_tmp, - signer.public().0, - rpc_responder, - ceremony_commands_thread_count, - ceremony_events_thread_count, - ) - .unwrap() - }); - - Ok(()) -} - -pub(crate) fn finish_enclave_init() -> EnclaveResult<()> { - // TODO: it's not required after ScheduledEnclave is removed - // however, it's not bad to leave a placeholder as post-init hook - Ok(()) -} - -#[allow(unused_variables)] -pub(crate) fn init_wallets(base_dir: PathBuf) -> EnclaveResult<()> { - if_development_or!( - { - println!("Initializing wallets from BTC_KEY, ETH_KEY and TON_KEY env variables"); - let btc_key: Option<[u8; 32]> = read_key_from_env("BTC_KEY")?; - if btc_key.is_some() { - create_schnorr_repository(base_dir.clone(), "bitcoin", btc_key)?; - } - - let eth_key: Option<[u8; 32]> = read_key_from_env("ETH_KEY")?; - if eth_key.is_some() { - create_ecdsa_repository(base_dir.clone(), "ethereum", eth_key)?; - } - - let ton_key: Option<[u8; 32]> = read_key_from_env("TON_KEY")?; - if ton_key.is_some() { - get_ed25519_repository(base_dir, Some("ton".to_string()), ton_key)?; - } - }, - { - println!("Init wallets available in dev mode only!"); - } - ); - - Ok(()) -} - -#[cfg(feature = "development")] -fn read_key_from_env(env_variable: &str) -> EnclaveResult> { - use std::env; - if let Ok(value) = env::var(env_variable) { - let decoded = - hex::decode(value).map_err(|_| Error::Other("Could not decode key value".into()))?; - Ok(Some( - decoded - .try_into() - .map_err(|_| Error::Other("Provided key is not 32 bytes long".into()))?, - )) - } else { - Ok(None) - } -} - -pub(crate) fn publish_wallets() -> EnclaveResult<()> { - let metadata_repository = get_node_metadata_repository_from_integritee_solo_or_parachain()?; - let extrinsics_factory = get_extrinsic_factory_from_integritee_solo_or_parachain()?; - let validator_accessor = get_validator_accessor_from_integritee_solo_or_parachain()?; - - let bitcoin_key_repository = GLOBAL_BITCOIN_KEY_REPOSITORY_COMPONENT.get()?; - let bitcoin_key = bitcoin_key_repository.retrieve_key()?; - - let bitcoin_call = metadata_repository - .get_from_metadata(|m| m.btc_wallet_generated_indexes()) - .map_err(|e| Error::Other(e.into()))? - .map_err(|e| Error::Other(format!("{:?}", e).into()))?; - - let bitcoin_opaque_call = OpaqueCall::from_tuple(&(bitcoin_call, bitcoin_key.public_bytes())); - - let ethereum_key_repository = GLOBAL_ETHEREUM_KEY_REPOSITORY_COMPONENT.get()?; - let ethereum_key = ethereum_key_repository.retrieve_key()?; - - let ethereum_call = metadata_repository - .get_from_metadata(|m| m.eth_wallet_generated_indexes()) - .map_err(|e| Error::Other(e.into()))? - .map_err(|e| Error::Other(format!("{:?}", e).into()))?; - - let ethereum_opaque_call = - OpaqueCall::from_tuple(&(ethereum_call, ethereum_key.public_bytes())); - - let ton_key_repository = GLOBAL_TON_KEY_REPOSITORY_COMPONENT.get()?; - let ton_key = ton_key_repository.retrieve_key()?; - - let ton_call = metadata_repository - .get_from_metadata(|m| m.ton_wallet_generated_indexes()) - .map_err(|e| Error::Other(e.into()))? - .map_err(|e| Error::Other(format!("{:?}", e).into()))?; - - let ton_opaque_call = OpaqueCall::from_tuple(&(ton_call, ton_key.public().0)); - - let xts = extrinsics_factory - .create_extrinsics(&[bitcoin_opaque_call, ethereum_opaque_call, ton_opaque_call], None) - .map_err(|e| Error::Other(e.into()))?; - validator_accessor - .execute_mut_on_validator(|v| v.send_extrinsics(xts)) - .map_err(|e| Error::Other(e.into()))?; - - Ok(()) -} - -fn initialize_state_observer( - snapshot_repository: &EnclaveStateSnapshotRepository, -) -> EnclaveResult> { - let shards = snapshot_repository.list_shards()?; - let mut states_map = HashMap::< - ShardIdentifier, - ::StateType, - >::new(); - for shard in shards.into_iter() { - let state = snapshot_repository.load_latest(&shard)?; - states_map.insert(shard, state); - } - Ok(Arc::new(EnclaveStateObserver::from_map(states_map))) -} - -fn run_bit_across_handler( - ceremony_registry: Arc>>>, - musig2_ceremony_pending_commands: Arc>, - signing_key_pub: [u8; 32], - responder: Arc< - RpcResponder, H256, RpcResponseChannel>, - >, - ceremony_commands_thread_count: u8, - ceremony_events_thread_count: u8, -) -> Result<(), Error> { - let author_api = GLOBAL_TOP_POOL_AUTHOR_COMPONENT.get()?; - let signing_key = GLOBAL_SIGNING_KEY_REPOSITORY_COMPONENT.get()?; - let state_handler = GLOBAL_STATE_HANDLER_COMPONENT.get()?; - let state_observer = GLOBAL_STATE_OBSERVER_COMPONENT.get()?; - let relayer_registry_lookup = GLOBAL_RELAYER_REGISTRY.get()?; - let enclave_registry_lookup = GLOBAL_ENCLAVE_REGISTRY.get()?; - let signer_registry_lookup = GLOBAL_SIGNER_REGISTRY.get()?; - - let shielding_key_repository = GLOBAL_SHIELDING_KEY_REPOSITORY_COMPONENT.get()?; - let ethereum_key_repository = GLOBAL_ETHEREUM_KEY_REPOSITORY_COMPONENT.get()?; - let bitcoin_key_repository = GLOBAL_BITCOIN_KEY_REPOSITORY_COMPONENT.get()?; - let ton_key_repository = GLOBAL_TON_KEY_REPOSITORY_COMPONENT.get()?; - - #[allow(clippy::unwrap_used)] - let ocall_api = GLOBAL_OCALL_API_COMPONENT.get()?; - let stf_enclave_signer = Arc::new(EnclaveStfEnclaveSigner::new( - state_observer, - ocall_api.clone(), - shielding_key_repository.clone(), - author_api, - )); - - let task_context = BitAcrossTaskContext::new( - shielding_key_repository, - signing_key, - ethereum_key_repository, - bitcoin_key_repository, - ton_key_repository, - stf_enclave_signer, - state_handler, - ocall_api, - relayer_registry_lookup, - enclave_registry_lookup, - signer_registry_lookup, - signing_key_pub, - ceremony_registry, - musig2_ceremony_pending_commands, - responder, - ); - run_bit_across_handler_runner( - Arc::new(task_context), - ceremony_commands_thread_count, - ceremony_events_thread_count, - ); - Ok(()) -} - -pub(crate) fn init_direct_invocation_server(server_addr: String) -> EnclaveResult<()> { - info!("Initialize direct invocation server on {}", &server_addr); - let rpc_handler = GLOBAL_RPC_WS_HANDLER_COMPONENT.get()?; - let signer = GLOBAL_SIGNING_KEY_REPOSITORY_COMPONENT.get()?.retrieve_key()?; - - let url = url::Url::parse(&server_addr).map_err(|e| Error::Other(format!("{}", e).into()))?; - let maybe_config_provider = if url.scheme() == "wss" { - let cert = ed25519_self_signed_certificate(signer, "Enclave") - .map_err(|e| Error::Other(e.into()))?; - - // Serialize certificate(s) and private key to PEM. - // PEM format is needed as a certificate chain can only be serialized into PEM. - let pem_serialized = cert.serialize_pem().map_err(|e| Error::Other(e.into()))?; - let private_key = cert.serialize_private_key_pem(); - - Some(Arc::new(FromFileConfigProvider::new(private_key, pem_serialized))) - } else { - return Err(Error::Other("Only accept wss scheme".into())) - }; - - let web_socket_server = Arc::new(TungsteniteWsServer::new( - url.authority().into(), - maybe_config_provider, - rpc_handler, - )); - - GLOBAL_WEB_SOCKET_SERVER_COMPONENT.initialize(web_socket_server.clone()); - - match web_socket_server.run() { - Ok(()) => {}, - Err(e) => { - error!("Web socket server encountered an unexpected error: {:?}", e) - }, - } - - Ok(()) -} - -pub(crate) fn init_shard(shard: ShardIdentifier) -> EnclaveResult<()> { - let state_handler = GLOBAL_STATE_HANDLER_COMPONENT.get()?; - let _ = state_handler.initialize_shard(shard)?; - Ok(()) -} - -pub(crate) fn migrate_shard(new_shard: ShardIdentifier) -> EnclaveResult<()> { - let state_handler = GLOBAL_STATE_HANDLER_COMPONENT.get()?; - let _ = state_handler.migrate_shard(new_shard)?; - Ok(()) -} - -/// Initialize the TOP pool author component. -pub fn create_top_pool_author( - rpc_responder: Arc, - state_handler: Arc, - shielding_key_repository: Arc, -) -> Arc { - let side_chain_api = Arc::new(EnclaveSidechainApi::new()); - let top_pool = - Arc::new(EnclaveTopPool::create(PoolOptions::default(), side_chain_api, rpc_responder)); - - Arc::new(EnclaveTopPoolAuthor::new( - top_pool, - AuthorTopFilter::::new(), - state_handler, - shielding_key_repository, - )) -} diff --git a/tee-worker/bitacross/enclave-runtime/src/initialization/parentchain/common.rs b/tee-worker/bitacross/enclave-runtime/src/initialization/parentchain/common.rs deleted file mode 100644 index 1d45f55dc7..0000000000 --- a/tee-worker/bitacross/enclave-runtime/src/initialization/parentchain/common.rs +++ /dev/null @@ -1,291 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use crate::{ - error::Result, - initialization::{ - global_components::{ - EnclaveExtrinsicsFactory, EnclaveNodeMetadataRepository, EnclaveOffchainWorkerExecutor, - EnclaveParentchainSigner, EnclaveStfExecutor, EnclaveValidatorAccessor, - IntegriteeParentchainBlockImportDispatcher, IntegriteeParentchainBlockImporter, - IntegriteeParentchainImmediateBlockImportDispatcher, - IntegriteeParentchainIndirectCallsExecutor, TargetAParentchainBlockImportDispatcher, - TargetAParentchainBlockImporter, TargetAParentchainImmediateBlockImportDispatcher, - TargetAParentchainIndirectCallsExecutor, TargetBParentchainBlockImportDispatcher, - TargetBParentchainBlockImporter, TargetBParentchainImmediateBlockImportDispatcher, - TargetBParentchainIndirectCallsExecutor, GLOBAL_OCALL_API_COMPONENT, - GLOBAL_SHIELDING_KEY_REPOSITORY_COMPONENT, GLOBAL_SIGNING_KEY_REPOSITORY_COMPONENT, - GLOBAL_STATE_HANDLER_COMPONENT, GLOBAL_STATE_OBSERVER_COMPONENT, - GLOBAL_TOP_POOL_AUTHOR_COMPONENT, - }, - EnclaveStfEnclaveSigner, GLOBAL_ENCLAVE_REGISTRY, GLOBAL_RELAYER_REGISTRY, - GLOBAL_SIGNER_REGISTRY, - }, -}; -use ita_parentchain_interface::{ - integritee::ParentchainEventHandler as LitentryParentchainEventHandler, - target_a::ParentchainEventHandler as TargetAParentchainEventHandler, - target_b::ParentchainEventHandler as TargetBParentchainEventHandler, -}; -use itp_component_container::ComponentGetter; -use itp_nonce_cache::NonceCache; -use itp_sgx_crypto::key_repository::AccessKey; -use itp_stf_interface::ShardCreationInfo; -use itp_types::parentchain::ParentchainId; -use log::*; -use sp_core::H256; -use std::sync::Arc; - -pub(crate) fn create_integritee_parentchain_block_importer( - validator_access: Arc, - stf_executor: Arc, - extrinsics_factory: Arc, - node_metadata_repository: Arc, - shard_creation_info: ShardCreationInfo, -) -> Result { - let state_observer = GLOBAL_STATE_OBSERVER_COMPONENT.get()?; - let top_pool_author = GLOBAL_TOP_POOL_AUTHOR_COMPONENT.get()?; - let shielding_key_repository = GLOBAL_SHIELDING_KEY_REPOSITORY_COMPONENT.get()?; - let ocall_api = GLOBAL_OCALL_API_COMPONENT.get()?; - let relayer_registry = GLOBAL_RELAYER_REGISTRY.get()?; - let signer_registry = GLOBAL_SIGNER_REGISTRY.get()?; - let enclave_registry = GLOBAL_ENCLAVE_REGISTRY.get()?; - - let parentchain_event_handler = LitentryParentchainEventHandler {}; - - let stf_enclave_signer = Arc::new(EnclaveStfEnclaveSigner::new( - state_observer, - ocall_api.clone(), - shielding_key_repository.clone(), - top_pool_author.clone(), - )); - let indirect_calls_executor = Arc::new(IntegriteeParentchainIndirectCallsExecutor::new( - shielding_key_repository, - stf_enclave_signer, - top_pool_author, - node_metadata_repository, - ParentchainId::Litentry, - parentchain_event_handler, - relayer_registry, - signer_registry, - enclave_registry, - )); - Ok(IntegriteeParentchainBlockImporter::new( - validator_access, - stf_executor, - extrinsics_factory, - indirect_calls_executor, - ocall_api, - shard_creation_info, - ParentchainId::TargetB, - )) -} - -pub(crate) fn create_target_a_parentchain_block_importer( - validator_access: Arc, - stf_executor: Arc, - extrinsics_factory: Arc, - node_metadata_repository: Arc, - shard_creation_info: ShardCreationInfo, -) -> Result { - let state_observer = GLOBAL_STATE_OBSERVER_COMPONENT.get()?; - let top_pool_author = GLOBAL_TOP_POOL_AUTHOR_COMPONENT.get()?; - let shielding_key_repository = GLOBAL_SHIELDING_KEY_REPOSITORY_COMPONENT.get()?; - let ocall_api = GLOBAL_OCALL_API_COMPONENT.get()?; - let relayer_registry = GLOBAL_RELAYER_REGISTRY.get()?; - let signer_registry = GLOBAL_SIGNER_REGISTRY.get()?; - let enclave_registry = GLOBAL_ENCLAVE_REGISTRY.get()?; - - let parentchain_event_handler = TargetAParentchainEventHandler {}; - - let stf_enclave_signer = Arc::new(EnclaveStfEnclaveSigner::new( - state_observer, - ocall_api.clone(), - shielding_key_repository.clone(), - top_pool_author.clone(), - )); - let indirect_calls_executor = Arc::new(TargetAParentchainIndirectCallsExecutor::new( - shielding_key_repository, - stf_enclave_signer, - top_pool_author, - node_metadata_repository, - ParentchainId::TargetA, - parentchain_event_handler, - relayer_registry, - signer_registry, - enclave_registry, - )); - Ok(TargetAParentchainBlockImporter::new( - validator_access, - stf_executor, - extrinsics_factory, - indirect_calls_executor, - ocall_api, - shard_creation_info, - ParentchainId::Litentry, - )) -} - -pub(crate) fn create_target_b_parentchain_block_importer( - validator_access: Arc, - stf_executor: Arc, - extrinsics_factory: Arc, - node_metadata_repository: Arc, - shard_creation_info: ShardCreationInfo, -) -> Result { - let state_observer = GLOBAL_STATE_OBSERVER_COMPONENT.get()?; - let top_pool_author = GLOBAL_TOP_POOL_AUTHOR_COMPONENT.get()?; - let shielding_key_repository = GLOBAL_SHIELDING_KEY_REPOSITORY_COMPONENT.get()?; - let ocall_api = GLOBAL_OCALL_API_COMPONENT.get()?; - let relayer_registry = GLOBAL_RELAYER_REGISTRY.get()?; - let signer_registry = GLOBAL_SIGNER_REGISTRY.get()?; - let enclave_registry = GLOBAL_ENCLAVE_REGISTRY.get()?; - - let parentchain_event_handler = TargetBParentchainEventHandler {}; - - let stf_enclave_signer = Arc::new(EnclaveStfEnclaveSigner::new( - state_observer, - ocall_api.clone(), - shielding_key_repository.clone(), - top_pool_author.clone(), - )); - let indirect_calls_executor = Arc::new(TargetBParentchainIndirectCallsExecutor::new( - shielding_key_repository, - stf_enclave_signer, - top_pool_author, - node_metadata_repository, - ParentchainId::TargetB, - parentchain_event_handler, - relayer_registry, - signer_registry, - enclave_registry, - )); - Ok(TargetBParentchainBlockImporter::new( - validator_access, - stf_executor, - extrinsics_factory, - indirect_calls_executor, - ocall_api, - shard_creation_info, - ParentchainId::TargetA, - )) -} - -pub(crate) fn create_extrinsics_factory( - genesis_hash: H256, - nonce_cache: Arc, - node_metadata_repository: Arc, -) -> Result> { - let signer = GLOBAL_SIGNING_KEY_REPOSITORY_COMPONENT.get()?.retrieve_key()?; - - Ok(Arc::new(EnclaveExtrinsicsFactory::new( - genesis_hash, - EnclaveParentchainSigner::new(signer), - nonce_cache, - node_metadata_repository, - ))) -} - -pub(crate) fn create_integritee_offchain_immediate_import_dispatcher( - stf_executor: Arc, - block_importer: IntegriteeParentchainBlockImporter, - validator_access: Arc, - extrinsics_factory: Arc, -) -> Result> { - let state_handler = GLOBAL_STATE_HANDLER_COMPONENT.get()?; - let top_pool_author = GLOBAL_TOP_POOL_AUTHOR_COMPONENT.get()?; - - let offchain_worker_executor = Arc::new(EnclaveOffchainWorkerExecutor::new( - top_pool_author, - stf_executor, - state_handler, - validator_access, - extrinsics_factory, - )); - let immediate_dispatcher = IntegriteeParentchainImmediateBlockImportDispatcher::new( - block_importer, - ) - .with_observer(move || { - if let Err(e) = offchain_worker_executor.execute() { - error!("Failed to execute trusted calls: {:?}", e); - } - }); - - Ok(Arc::new(IntegriteeParentchainBlockImportDispatcher::new_immediate_dispatcher(Arc::new( - immediate_dispatcher, - )))) -} - -pub(crate) fn create_target_a_offchain_immediate_import_dispatcher( - stf_executor: Arc, - block_importer: TargetAParentchainBlockImporter, - validator_access: Arc, - extrinsics_factory: Arc, -) -> Result> { - let state_handler = GLOBAL_STATE_HANDLER_COMPONENT.get()?; - let top_pool_author = GLOBAL_TOP_POOL_AUTHOR_COMPONENT.get()?; - - let offchain_worker_executor = Arc::new(EnclaveOffchainWorkerExecutor::new( - top_pool_author, - stf_executor, - state_handler, - validator_access, - extrinsics_factory, - )); - let immediate_dispatcher = TargetAParentchainImmediateBlockImportDispatcher::new( - block_importer, - ) - .with_observer(move || { - if let Err(e) = offchain_worker_executor.execute() { - error!("Failed to execute trusted calls: {:?}", e); - } - }); - - Ok(Arc::new(TargetAParentchainBlockImportDispatcher::new_immediate_dispatcher(Arc::new( - immediate_dispatcher, - )))) -} - -pub(crate) fn create_target_b_offchain_immediate_import_dispatcher( - stf_executor: Arc, - block_importer: TargetBParentchainBlockImporter, - validator_access: Arc, - extrinsics_factory: Arc, -) -> Result> { - let state_handler = GLOBAL_STATE_HANDLER_COMPONENT.get()?; - let top_pool_author = GLOBAL_TOP_POOL_AUTHOR_COMPONENT.get()?; - - let offchain_worker_executor = Arc::new(EnclaveOffchainWorkerExecutor::new( - top_pool_author, - stf_executor, - state_handler, - validator_access, - extrinsics_factory, - )); - let immediate_dispatcher = TargetBParentchainImmediateBlockImportDispatcher::new( - block_importer, - ) - .with_observer(move || { - if let Err(e) = offchain_worker_executor.execute() { - error!("Failed to execute trusted calls: {:?}", e); - } - }); - - Ok(Arc::new(TargetBParentchainBlockImportDispatcher::new_immediate_dispatcher(Arc::new( - immediate_dispatcher, - )))) -} diff --git a/tee-worker/bitacross/enclave-runtime/src/initialization/parentchain/integritee_parachain.rs b/tee-worker/bitacross/enclave-runtime/src/initialization/parentchain/integritee_parachain.rs deleted file mode 100644 index f0cc06a94b..0000000000 --- a/tee-worker/bitacross/enclave-runtime/src/initialization/parentchain/integritee_parachain.rs +++ /dev/null @@ -1,113 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use crate::{ - error::Result, - initialization::{ - global_components::{ - EnclaveExtrinsicsFactory, EnclaveNodeMetadataRepository, EnclaveOCallApi, - EnclaveStfExecutor, EnclaveValidatorAccessor, - IntegriteeParentchainBlockImportDispatcher, - GLOBAL_INTEGRITEE_PARENTCHAIN_LIGHT_CLIENT_SEAL, - GLOBAL_INTEGRITEE_PARENTCHAIN_NONCE_CACHE, GLOBAL_OCALL_API_COMPONENT, - GLOBAL_STATE_HANDLER_COMPONENT, - }, - parentchain::common::{ - create_extrinsics_factory, create_integritee_offchain_immediate_import_dispatcher, - create_integritee_parentchain_block_importer, - }, - }, -}; -use itc_parentchain::light_client::{concurrent_access::ValidatorAccess, LightClientState}; -use itp_component_container::ComponentGetter; -use itp_stf_interface::ShardCreationInfo; -use itp_types::parentchain::ParentchainId; -pub use itp_types::parentchain::{ParachainBlock, ParachainHeader, ParachainParams}; -use std::{path::PathBuf, sync::Arc}; - -#[derive(Clone)] -pub struct IntegriteeParachainHandler { - pub genesis_header: ParachainHeader, - pub node_metadata_repository: Arc, - pub stf_executor: Arc, - pub validator_accessor: Arc, - pub extrinsics_factory: Arc, - pub import_dispatcher: Arc, -} - -impl IntegriteeParachainHandler { - pub fn init( - _base_path: PathBuf, - params: ParachainParams, - shard_creation_info: ShardCreationInfo, - ) -> Result { - let ocall_api = GLOBAL_OCALL_API_COMPONENT.get()?; - let state_handler = GLOBAL_STATE_HANDLER_COMPONENT.get()?; - let node_metadata_repository = Arc::new(EnclaveNodeMetadataRepository::default()); - - let genesis_header = params.genesis_header.clone(); - - let light_client_seal = GLOBAL_INTEGRITEE_PARENTCHAIN_LIGHT_CLIENT_SEAL.get()?; - let validator = itc_parentchain::light_client::io::read_or_init_parachain_validator::< - ParachainBlock, - EnclaveOCallApi, - _, - >(params, ocall_api.clone(), &*light_client_seal, ParentchainId::Litentry)?; - let validator_accessor = - Arc::new(EnclaveValidatorAccessor::new(validator, light_client_seal)); - - let genesis_hash = validator_accessor.execute_on_validator(|v| v.genesis_hash())?; - - let extrinsics_factory = create_extrinsics_factory( - genesis_hash, - GLOBAL_INTEGRITEE_PARENTCHAIN_NONCE_CACHE.clone(), - node_metadata_repository.clone(), - )?; - - let stf_executor = Arc::new(EnclaveStfExecutor::new( - ocall_api, - state_handler, - node_metadata_repository.clone(), - )); - - let block_importer = create_integritee_parentchain_block_importer( - validator_accessor.clone(), - stf_executor.clone(), - extrinsics_factory.clone(), - node_metadata_repository.clone(), - shard_creation_info, - )?; - - let import_dispatcher = create_integritee_offchain_immediate_import_dispatcher( - stf_executor.clone(), - block_importer, - validator_accessor.clone(), - extrinsics_factory.clone(), - )?; - - let parachain_handler = Self { - genesis_header, - node_metadata_repository, - stf_executor, - validator_accessor, - extrinsics_factory, - import_dispatcher, - }; - - Ok(parachain_handler) - } -} diff --git a/tee-worker/bitacross/enclave-runtime/src/initialization/parentchain/integritee_solochain.rs b/tee-worker/bitacross/enclave-runtime/src/initialization/parentchain/integritee_solochain.rs deleted file mode 100644 index ee5697967f..0000000000 --- a/tee-worker/bitacross/enclave-runtime/src/initialization/parentchain/integritee_solochain.rs +++ /dev/null @@ -1,112 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use crate::{ - error::Result, - initialization::{ - global_components::{ - EnclaveExtrinsicsFactory, EnclaveNodeMetadataRepository, EnclaveOCallApi, - EnclaveStfExecutor, EnclaveValidatorAccessor, - IntegriteeParentchainBlockImportDispatcher, - GLOBAL_INTEGRITEE_PARENTCHAIN_LIGHT_CLIENT_SEAL, - GLOBAL_INTEGRITEE_PARENTCHAIN_NONCE_CACHE, GLOBAL_OCALL_API_COMPONENT, - GLOBAL_STATE_HANDLER_COMPONENT, - }, - parentchain::common::{ - create_extrinsics_factory, create_integritee_offchain_immediate_import_dispatcher, - create_integritee_parentchain_block_importer, - }, - }, -}; -use itc_parentchain::light_client::{concurrent_access::ValidatorAccess, LightClientState}; -use itp_component_container::ComponentGetter; -use itp_stf_interface::ShardCreationInfo; -use itp_types::parentchain::ParentchainId; -pub use itp_types::parentchain::{SolochainBlock, SolochainHeader, SolochainParams}; -use std::{path::PathBuf, sync::Arc}; - -pub struct IntegriteeSolochainHandler { - pub genesis_header: SolochainHeader, - pub node_metadata_repository: Arc, - pub stf_executor: Arc, - pub validator_accessor: Arc, - pub extrinsics_factory: Arc, - pub import_dispatcher: Arc, -} - -impl IntegriteeSolochainHandler { - pub fn init( - _base_path: PathBuf, - params: SolochainParams, - shard_creation_info: ShardCreationInfo, - ) -> Result { - let ocall_api = GLOBAL_OCALL_API_COMPONENT.get()?; - let state_handler = GLOBAL_STATE_HANDLER_COMPONENT.get()?; - let light_client_seal = GLOBAL_INTEGRITEE_PARENTCHAIN_LIGHT_CLIENT_SEAL.get()?; - let node_metadata_repository = Arc::new(EnclaveNodeMetadataRepository::default()); - - let genesis_header = params.genesis_header.clone(); - - let validator = itc_parentchain::light_client::io::read_or_init_grandpa_validator::< - SolochainBlock, - EnclaveOCallApi, - _, - >(params, ocall_api.clone(), &*light_client_seal, ParentchainId::Litentry)?; - let validator_accessor = - Arc::new(EnclaveValidatorAccessor::new(validator, light_client_seal)); - - let genesis_hash = validator_accessor.execute_on_validator(|v| v.genesis_hash())?; - - let extrinsics_factory = create_extrinsics_factory( - genesis_hash, - GLOBAL_INTEGRITEE_PARENTCHAIN_NONCE_CACHE.clone(), - node_metadata_repository.clone(), - )?; - - let stf_executor = Arc::new(EnclaveStfExecutor::new( - ocall_api, - state_handler, - node_metadata_repository.clone(), - )); - - let block_importer = create_integritee_parentchain_block_importer( - validator_accessor.clone(), - stf_executor.clone(), - extrinsics_factory.clone(), - node_metadata_repository.clone(), - shard_creation_info, - )?; - - let import_dispatcher = create_integritee_offchain_immediate_import_dispatcher( - stf_executor.clone(), - block_importer, - validator_accessor.clone(), - extrinsics_factory.clone(), - )?; - - let solochain_handler = Self { - genesis_header, - node_metadata_repository, - stf_executor, - validator_accessor, - extrinsics_factory, - import_dispatcher, - }; - - Ok(solochain_handler) - } -} diff --git a/tee-worker/bitacross/enclave-runtime/src/initialization/parentchain/mod.rs b/tee-worker/bitacross/enclave-runtime/src/initialization/parentchain/mod.rs deleted file mode 100644 index d658ec6c36..0000000000 --- a/tee-worker/bitacross/enclave-runtime/src/initialization/parentchain/mod.rs +++ /dev/null @@ -1,136 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use crate::{ - error::Result, - initialization::{ - global_components::{ - GLOBAL_INTEGRITEE_PARACHAIN_HANDLER_COMPONENT, - GLOBAL_INTEGRITEE_SOLOCHAIN_HANDLER_COMPONENT, - GLOBAL_TARGET_A_PARACHAIN_HANDLER_COMPONENT, - GLOBAL_TARGET_A_SOLOCHAIN_HANDLER_COMPONENT, - GLOBAL_TARGET_B_PARACHAIN_HANDLER_COMPONENT, - GLOBAL_TARGET_B_SOLOCHAIN_HANDLER_COMPONENT, - }, - parentchain::{ - target_a_parachain::TargetAParachainHandler, - target_a_solochain::TargetASolochainHandler, - target_b_parachain::TargetBParachainHandler, - target_b_solochain::TargetBSolochainHandler, - }, - }, - shard_creation_info::get_shard_creation_info_internal, -}; -use codec::{Decode, Encode}; -use integritee_parachain::IntegriteeParachainHandler; -use integritee_solochain::IntegriteeSolochainHandler; -use itc_parentchain::light_client::{concurrent_access::ValidatorAccess, LightClientState}; -use itp_component_container::ComponentInitializer; -use itp_types::parentchain::{ParentchainId, ParentchainInitParams}; -use log::*; -use std::{path::PathBuf, vec::Vec}; - -mod common; -pub mod integritee_parachain; -pub mod integritee_solochain; -pub mod target_a_parachain; -pub mod target_a_solochain; -pub mod target_b_parachain; -pub mod target_b_solochain; - -pub(crate) fn init_parentchain_components( - base_path: PathBuf, - encoded_params: Vec, -) -> Result> { - match ParentchainInitParams::decode(&mut encoded_params.as_slice())? { - ParentchainInitParams::Parachain { id, shard, params } => { - info!( - "[{:?}] initializing parachain parentchain components for shard: {:?}", - id, shard - ); - let shard_creation_info = get_shard_creation_info_internal(shard)?; - - // todo: query timestamp of creation header to give a creation reference to target_a/b as well in order to fast-sync - match id { - ParentchainId::Litentry => { - let handler = - IntegriteeParachainHandler::init(base_path, params, shard_creation_info)?; - let header = handler - .validator_accessor - .execute_on_validator(|v| v.latest_finalized_header())?; - GLOBAL_INTEGRITEE_PARACHAIN_HANDLER_COMPONENT.initialize(handler.into()); - Ok(header.encode()) - }, - ParentchainId::TargetA => { - let handler = - TargetAParachainHandler::init(base_path, params, shard_creation_info)?; - let header = handler - .validator_accessor - .execute_on_validator(|v| v.latest_finalized_header())?; - GLOBAL_TARGET_A_PARACHAIN_HANDLER_COMPONENT.initialize(handler.into()); - Ok(header.encode()) - }, - ParentchainId::TargetB => { - let handler = - TargetBParachainHandler::init(base_path, params, shard_creation_info)?; - let header = handler - .validator_accessor - .execute_on_validator(|v| v.latest_finalized_header())?; - GLOBAL_TARGET_B_PARACHAIN_HANDLER_COMPONENT.initialize(handler.into()); - Ok(header.encode()) - }, - } - }, - ParentchainInitParams::Solochain { id, shard, params } => { - info!( - "[{:?}] initializing solochain parentchain components for shard: {:?}", - id, shard - ); - let shard_creation_info = get_shard_creation_info_internal(shard)?; - // todo: query timestamp of creation header to give a creation reference to target_a/b as well in order to fast-sync - match id { - ParentchainId::Litentry => { - let handler = - IntegriteeSolochainHandler::init(base_path, params, shard_creation_info)?; - let header = handler - .validator_accessor - .execute_on_validator(|v| v.latest_finalized_header())?; - GLOBAL_INTEGRITEE_SOLOCHAIN_HANDLER_COMPONENT.initialize(handler.into()); - Ok(header.encode()) - }, - ParentchainId::TargetA => { - let handler = - TargetASolochainHandler::init(base_path, params, shard_creation_info)?; - let header = handler - .validator_accessor - .execute_on_validator(|v| v.latest_finalized_header())?; - GLOBAL_TARGET_A_SOLOCHAIN_HANDLER_COMPONENT.initialize(handler.into()); - Ok(header.encode()) - }, - ParentchainId::TargetB => { - let handler = - TargetBSolochainHandler::init(base_path, params, shard_creation_info)?; - let header = handler - .validator_accessor - .execute_on_validator(|v| v.latest_finalized_header())?; - GLOBAL_TARGET_B_SOLOCHAIN_HANDLER_COMPONENT.initialize(handler.into()); - Ok(header.encode()) - }, - } - }, - } -} diff --git a/tee-worker/bitacross/enclave-runtime/src/initialization/parentchain/target_a_parachain.rs b/tee-worker/bitacross/enclave-runtime/src/initialization/parentchain/target_a_parachain.rs deleted file mode 100644 index 32de87cfba..0000000000 --- a/tee-worker/bitacross/enclave-runtime/src/initialization/parentchain/target_a_parachain.rs +++ /dev/null @@ -1,117 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -//! Naive implementation of adding a second parachain handler to the setup. -//! -//! Ideally, most of the redundant code can be abstracted away, but it turns out -//! that this is quite tedious, so for now this is a copy-past of the [IntegriteeParachainHandler]: -//! * https://github.com/integritee-network/worker/issues/1417 - -use crate::{ - error::Result, - initialization::{ - global_components::{ - EnclaveExtrinsicsFactory, EnclaveNodeMetadataRepository, EnclaveOCallApi, - EnclaveStfExecutor, EnclaveValidatorAccessor, TargetAParentchainBlockImportDispatcher, - GLOBAL_OCALL_API_COMPONENT, GLOBAL_STATE_HANDLER_COMPONENT, - GLOBAL_TARGET_A_PARENTCHAIN_LIGHT_CLIENT_SEAL, GLOBAL_TARGET_A_PARENTCHAIN_NONCE_CACHE, - }, - parentchain::common::{ - create_extrinsics_factory, create_target_a_offchain_immediate_import_dispatcher, - create_target_a_parentchain_block_importer, - }, - }, -}; -use itc_parentchain::light_client::{concurrent_access::ValidatorAccess, LightClientState}; -use itp_component_container::ComponentGetter; -use itp_stf_interface::ShardCreationInfo; -use itp_types::parentchain::ParentchainId; -pub use itp_types::parentchain::{ParachainBlock, ParachainHeader, ParachainParams}; -use std::{path::PathBuf, sync::Arc}; - -#[derive(Clone)] -pub struct TargetAParachainHandler { - pub genesis_header: ParachainHeader, - pub node_metadata_repository: Arc, - pub stf_executor: Arc, - pub validator_accessor: Arc, - pub extrinsics_factory: Arc, - pub import_dispatcher: Arc, -} - -impl TargetAParachainHandler { - pub fn init( - _base_path: PathBuf, - params: ParachainParams, - shard_creation_info: ShardCreationInfo, - ) -> Result { - let ocall_api = GLOBAL_OCALL_API_COMPONENT.get()?; - let state_handler = GLOBAL_STATE_HANDLER_COMPONENT.get()?; - let node_metadata_repository = Arc::new(EnclaveNodeMetadataRepository::default()); - - let genesis_header = params.genesis_header.clone(); - - let light_client_seal = GLOBAL_TARGET_A_PARENTCHAIN_LIGHT_CLIENT_SEAL.get()?; - let validator = itc_parentchain::light_client::io::read_or_init_parachain_validator::< - ParachainBlock, - EnclaveOCallApi, - _, - >(params, ocall_api.clone(), &*light_client_seal, ParentchainId::TargetA)?; - let validator_accessor = - Arc::new(EnclaveValidatorAccessor::new(validator, light_client_seal)); - - let genesis_hash = validator_accessor.execute_on_validator(|v| v.genesis_hash())?; - - let extrinsics_factory = create_extrinsics_factory( - genesis_hash, - GLOBAL_TARGET_A_PARENTCHAIN_NONCE_CACHE.clone(), - node_metadata_repository.clone(), - )?; - - let stf_executor = Arc::new(EnclaveStfExecutor::new( - ocall_api, - state_handler, - node_metadata_repository.clone(), - )); - - let block_importer = create_target_a_parentchain_block_importer( - validator_accessor.clone(), - stf_executor.clone(), - extrinsics_factory.clone(), - node_metadata_repository.clone(), - shard_creation_info, - )?; - - let import_dispatcher = create_target_a_offchain_immediate_import_dispatcher( - stf_executor.clone(), - block_importer, - validator_accessor.clone(), - extrinsics_factory.clone(), - )?; - - let parachain_handler = Self { - genesis_header, - node_metadata_repository, - stf_executor, - validator_accessor, - extrinsics_factory, - import_dispatcher, - }; - - Ok(parachain_handler) - } -} diff --git a/tee-worker/bitacross/enclave-runtime/src/initialization/parentchain/target_a_solochain.rs b/tee-worker/bitacross/enclave-runtime/src/initialization/parentchain/target_a_solochain.rs deleted file mode 100644 index bd76a450f6..0000000000 --- a/tee-worker/bitacross/enclave-runtime/src/initialization/parentchain/target_a_solochain.rs +++ /dev/null @@ -1,110 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use crate::{ - error::Result, - initialization::{ - global_components::{ - EnclaveExtrinsicsFactory, EnclaveNodeMetadataRepository, EnclaveOCallApi, - EnclaveStfExecutor, EnclaveValidatorAccessor, TargetAParentchainBlockImportDispatcher, - GLOBAL_OCALL_API_COMPONENT, GLOBAL_STATE_HANDLER_COMPONENT, - GLOBAL_TARGET_A_PARENTCHAIN_LIGHT_CLIENT_SEAL, GLOBAL_TARGET_A_PARENTCHAIN_NONCE_CACHE, - }, - parentchain::common::{ - create_extrinsics_factory, create_target_a_offchain_immediate_import_dispatcher, - create_target_a_parentchain_block_importer, - }, - }, -}; -use itc_parentchain::light_client::{concurrent_access::ValidatorAccess, LightClientState}; -use itp_component_container::ComponentGetter; -use itp_stf_interface::ShardCreationInfo; -use itp_types::parentchain::ParentchainId; -pub use itp_types::parentchain::{SolochainBlock, SolochainHeader, SolochainParams}; -use std::{path::PathBuf, sync::Arc}; - -pub struct TargetASolochainHandler { - pub genesis_header: SolochainHeader, - pub node_metadata_repository: Arc, - pub stf_executor: Arc, - pub validator_accessor: Arc, - pub extrinsics_factory: Arc, - pub import_dispatcher: Arc, -} - -impl TargetASolochainHandler { - pub fn init( - _base_path: PathBuf, - params: SolochainParams, - shard_creation_info: ShardCreationInfo, - ) -> Result { - let ocall_api = GLOBAL_OCALL_API_COMPONENT.get()?; - let state_handler = GLOBAL_STATE_HANDLER_COMPONENT.get()?; - let light_client_seal = GLOBAL_TARGET_A_PARENTCHAIN_LIGHT_CLIENT_SEAL.get()?; - let node_metadata_repository = Arc::new(EnclaveNodeMetadataRepository::default()); - - let genesis_header = params.genesis_header.clone(); - - let validator = itc_parentchain::light_client::io::read_or_init_grandpa_validator::< - SolochainBlock, - EnclaveOCallApi, - _, - >(params, ocall_api.clone(), &*light_client_seal, ParentchainId::TargetA)?; - let validator_accessor = - Arc::new(EnclaveValidatorAccessor::new(validator, light_client_seal)); - - let genesis_hash = validator_accessor.execute_on_validator(|v| v.genesis_hash())?; - - let extrinsics_factory = create_extrinsics_factory( - genesis_hash, - GLOBAL_TARGET_A_PARENTCHAIN_NONCE_CACHE.clone(), - node_metadata_repository.clone(), - )?; - - let stf_executor = Arc::new(EnclaveStfExecutor::new( - ocall_api, - state_handler, - node_metadata_repository.clone(), - )); - - let block_importer = create_target_a_parentchain_block_importer( - validator_accessor.clone(), - stf_executor.clone(), - extrinsics_factory.clone(), - node_metadata_repository.clone(), - shard_creation_info, - )?; - - let import_dispatcher = create_target_a_offchain_immediate_import_dispatcher( - stf_executor.clone(), - block_importer, - validator_accessor.clone(), - extrinsics_factory.clone(), - )?; - - let solochain_handler = Self { - genesis_header, - node_metadata_repository, - stf_executor, - validator_accessor, - extrinsics_factory, - import_dispatcher, - }; - - Ok(solochain_handler) - } -} diff --git a/tee-worker/bitacross/enclave-runtime/src/initialization/parentchain/target_b_parachain.rs b/tee-worker/bitacross/enclave-runtime/src/initialization/parentchain/target_b_parachain.rs deleted file mode 100644 index 221a37b0c0..0000000000 --- a/tee-worker/bitacross/enclave-runtime/src/initialization/parentchain/target_b_parachain.rs +++ /dev/null @@ -1,117 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -//! Naive implementation of adding a second parachain handler to the setup. -//! -//! Ideally, most of the redundant code can be abstracted away, but it turns out -//! that this is quite tedious, so for now this is a copy-past of the [IntegriteeParachainHandler]: -//! * https://github.com/integritee-network/worker/issues/1417 - -use crate::{ - error::Result, - initialization::{ - global_components::{ - EnclaveExtrinsicsFactory, EnclaveNodeMetadataRepository, EnclaveOCallApi, - EnclaveStfExecutor, EnclaveValidatorAccessor, TargetBParentchainBlockImportDispatcher, - GLOBAL_OCALL_API_COMPONENT, GLOBAL_STATE_HANDLER_COMPONENT, - GLOBAL_TARGET_B_PARENTCHAIN_LIGHT_CLIENT_SEAL, GLOBAL_TARGET_B_PARENTCHAIN_NONCE_CACHE, - }, - parentchain::common::{ - create_extrinsics_factory, create_target_b_offchain_immediate_import_dispatcher, - create_target_b_parentchain_block_importer, - }, - }, -}; -use itc_parentchain::light_client::{concurrent_access::ValidatorAccess, LightClientState}; -use itp_component_container::ComponentGetter; -use itp_stf_interface::ShardCreationInfo; -use itp_types::parentchain::ParentchainId; -pub use itp_types::parentchain::{ParachainBlock, ParachainHeader, ParachainParams}; -use std::{path::PathBuf, sync::Arc}; - -#[derive(Clone)] -pub struct TargetBParachainHandler { - pub genesis_header: ParachainHeader, - pub node_metadata_repository: Arc, - pub stf_executor: Arc, - pub validator_accessor: Arc, - pub extrinsics_factory: Arc, - pub import_dispatcher: Arc, -} - -impl TargetBParachainHandler { - pub fn init( - _base_path: PathBuf, - params: ParachainParams, - shard_creation_info: ShardCreationInfo, - ) -> Result { - let ocall_api = GLOBAL_OCALL_API_COMPONENT.get()?; - let state_handler = GLOBAL_STATE_HANDLER_COMPONENT.get()?; - let node_metadata_repository = Arc::new(EnclaveNodeMetadataRepository::default()); - - let genesis_header = params.genesis_header.clone(); - - let light_client_seal = GLOBAL_TARGET_B_PARENTCHAIN_LIGHT_CLIENT_SEAL.get()?; - let validator = itc_parentchain::light_client::io::read_or_init_parachain_validator::< - ParachainBlock, - EnclaveOCallApi, - _, - >(params, ocall_api.clone(), &*light_client_seal, ParentchainId::TargetB)?; - let validator_accessor = - Arc::new(EnclaveValidatorAccessor::new(validator, light_client_seal)); - - let genesis_hash = validator_accessor.execute_on_validator(|v| v.genesis_hash())?; - - let extrinsics_factory = create_extrinsics_factory( - genesis_hash, - GLOBAL_TARGET_B_PARENTCHAIN_NONCE_CACHE.clone(), - node_metadata_repository.clone(), - )?; - - let stf_executor = Arc::new(EnclaveStfExecutor::new( - ocall_api, - state_handler, - node_metadata_repository.clone(), - )); - - let block_importer = create_target_b_parentchain_block_importer( - validator_accessor.clone(), - stf_executor.clone(), - extrinsics_factory.clone(), - node_metadata_repository.clone(), - shard_creation_info, - )?; - - let import_dispatcher = create_target_b_offchain_immediate_import_dispatcher( - stf_executor.clone(), - block_importer, - validator_accessor.clone(), - extrinsics_factory.clone(), - )?; - - let parachain_handler = Self { - genesis_header, - node_metadata_repository, - stf_executor, - validator_accessor, - extrinsics_factory, - import_dispatcher, - }; - - Ok(parachain_handler) - } -} diff --git a/tee-worker/bitacross/enclave-runtime/src/initialization/parentchain/target_b_solochain.rs b/tee-worker/bitacross/enclave-runtime/src/initialization/parentchain/target_b_solochain.rs deleted file mode 100644 index 0953d15779..0000000000 --- a/tee-worker/bitacross/enclave-runtime/src/initialization/parentchain/target_b_solochain.rs +++ /dev/null @@ -1,110 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use crate::{ - error::Result, - initialization::{ - global_components::{ - EnclaveExtrinsicsFactory, EnclaveNodeMetadataRepository, EnclaveOCallApi, - EnclaveStfExecutor, EnclaveValidatorAccessor, TargetBParentchainBlockImportDispatcher, - GLOBAL_OCALL_API_COMPONENT, GLOBAL_STATE_HANDLER_COMPONENT, - GLOBAL_TARGET_B_PARENTCHAIN_LIGHT_CLIENT_SEAL, GLOBAL_TARGET_B_PARENTCHAIN_NONCE_CACHE, - }, - parentchain::common::{ - create_extrinsics_factory, create_target_b_offchain_immediate_import_dispatcher, - create_target_b_parentchain_block_importer, - }, - }, -}; -use itc_parentchain::light_client::{concurrent_access::ValidatorAccess, LightClientState}; -use itp_component_container::ComponentGetter; -use itp_stf_interface::ShardCreationInfo; -use itp_types::parentchain::ParentchainId; -pub use itp_types::parentchain::{SolochainBlock, SolochainHeader, SolochainParams}; -use std::{path::PathBuf, sync::Arc}; - -pub struct TargetBSolochainHandler { - pub genesis_header: SolochainHeader, - pub node_metadata_repository: Arc, - pub stf_executor: Arc, - pub validator_accessor: Arc, - pub extrinsics_factory: Arc, - pub import_dispatcher: Arc, -} - -impl TargetBSolochainHandler { - pub fn init( - _base_path: PathBuf, - params: SolochainParams, - shard_creation_info: ShardCreationInfo, - ) -> Result { - let ocall_api = GLOBAL_OCALL_API_COMPONENT.get()?; - let state_handler = GLOBAL_STATE_HANDLER_COMPONENT.get()?; - let light_client_seal = GLOBAL_TARGET_B_PARENTCHAIN_LIGHT_CLIENT_SEAL.get()?; - let node_metadata_repository = Arc::new(EnclaveNodeMetadataRepository::default()); - - let genesis_header = params.genesis_header.clone(); - - let validator = itc_parentchain::light_client::io::read_or_init_grandpa_validator::< - SolochainBlock, - EnclaveOCallApi, - _, - >(params, ocall_api.clone(), &*light_client_seal, ParentchainId::TargetB)?; - let validator_accessor = - Arc::new(EnclaveValidatorAccessor::new(validator, light_client_seal)); - - let genesis_hash = validator_accessor.execute_on_validator(|v| v.genesis_hash())?; - - let extrinsics_factory = create_extrinsics_factory( - genesis_hash, - GLOBAL_TARGET_B_PARENTCHAIN_NONCE_CACHE.clone(), - node_metadata_repository.clone(), - )?; - - let stf_executor = Arc::new(EnclaveStfExecutor::new( - ocall_api, - state_handler, - node_metadata_repository.clone(), - )); - - let block_importer = create_target_b_parentchain_block_importer( - validator_accessor.clone(), - stf_executor.clone(), - extrinsics_factory.clone(), - node_metadata_repository.clone(), - shard_creation_info, - )?; - - let import_dispatcher = create_target_b_offchain_immediate_import_dispatcher( - stf_executor.clone(), - block_importer, - validator_accessor.clone(), - extrinsics_factory.clone(), - )?; - - let solochain_handler = Self { - genesis_header, - node_metadata_repository, - stf_executor, - validator_accessor, - extrinsics_factory, - import_dispatcher, - }; - - Ok(solochain_handler) - } -} diff --git a/tee-worker/bitacross/enclave-runtime/src/ipfs.rs b/tee-worker/bitacross/enclave-runtime/src/ipfs.rs deleted file mode 100644 index c376456455..0000000000 --- a/tee-worker/bitacross/enclave-runtime/src/ipfs.rs +++ /dev/null @@ -1,105 +0,0 @@ -use cid::{Cid, Result as CidResult}; -use ipfs_unixfs::file::adder::FileAdder; -use log::*; -use multibase::Base; -use std::{convert::TryFrom, vec::Vec}; - -pub struct IpfsContent { - pub cid: CidResult, - pub file_content: Vec, - pub stats: Stats, -} -#[derive(Debug, PartialEq)] -pub enum IpfsError { - InputCidInvalid, - FinalCidMissing, - Verification, -} - -impl IpfsContent { - pub fn new(_cid: &str, _content: Vec) -> IpfsContent { - IpfsContent { cid: Cid::try_from(_cid), file_content: _content, stats: Stats::default() } - } - - pub fn verify(&mut self) -> Result<(), IpfsError> { - let mut adder: FileAdder = FileAdder::default(); - let mut total: usize = 0; - while total < self.file_content.len() { - #[allow(clippy::string_slice)] - let bytes = &self.file_content.get(total..).ok_or(IpfsError::Verification)?; - let (blocks, consumed) = adder.push(bytes); - total = total.saturating_add(consumed); - self.stats.process(blocks); - } - let blocks = adder.finish(); - self.stats.process(blocks); - - if let Some(last_cid) = self.stats.last.as_ref() { - let cid_str = Base::Base58Btc.encode(last_cid.hash().as_bytes()); - info!( - "new cid: {} generated from {} blocks, total of {} bytes", - cid_str, self.stats.blocks, self.stats.block_bytes - ); - match self.cid.as_ref() { - Ok(initial_cid) => - if last_cid.hash().eq(&initial_cid.hash()) { - Ok(()) - } else { - Err(IpfsError::Verification) - }, - Err(_) => Err(IpfsError::InputCidInvalid), - } - } else { - Err(IpfsError::FinalCidMissing) - } - } -} -#[derive(Default)] -pub struct Stats { - pub blocks: usize, - pub block_bytes: u64, - pub last: Option, -} - -impl Stats { - fn process)>>(&mut self, new_blocks: I) { - for (cid, block) in new_blocks { - self.last = Some(cid); - self.blocks = self.blocks.saturating_add(1); - self.block_bytes = self.block_bytes.saturating_add(block.len() as u64); - } - } -} - -#[allow(unused)] -pub fn test_creates_ipfs_content_struct_works() { - let cid = "QmSaFjwJ2QtS3rZDKzC98XEzv2bqT4TfpWLCpphPPwyQTr"; - let content: Vec = vec![20; 512 * 1024]; - let ipfs_content = IpfsContent::new(cid, content.clone()); - - #[allow(clippy::unwrap_used)] - let cid_str = Base::Base58Btc.encode(ipfs_content.cid.as_ref().unwrap().hash().as_bytes()); - assert_eq!(cid_str, cid); - assert_eq!(ipfs_content.file_content, content); -} - -#[allow(unused)] -pub fn test_verification_ok_for_correct_content() { - let cid = "QmSaFjwJ2QtS3rZDKzC98XEzv2bqT4TfpWLCpphPPwyQTr"; - let content: Vec = vec![20; 512 * 1024]; - let mut ipfs_content = IpfsContent::new(cid, content); - let verification = ipfs_content.verify(); - assert!(verification.is_ok()); -} - -#[allow(unused)] -pub fn test_verification_fails_for_incorrect_content() { - let cid = "QmSaFjwJ2QtS3rZDKzC98XEzv2bqT4TfpWLCpphPPwyQTr"; - let content: Vec = vec![10; 512 * 1024]; - let mut ipfs_content = IpfsContent::new(cid, content); - let verification = ipfs_content.verify(); - #[allow(clippy::unwrap_used)] - { - assert_eq!(verification.unwrap_err(), IpfsError::Verification); - } -} diff --git a/tee-worker/bitacross/enclave-runtime/src/lib.rs b/tee-worker/bitacross/enclave-runtime/src/lib.rs deleted file mode 100644 index e5593baaa9..0000000000 --- a/tee-worker/bitacross/enclave-runtime/src/lib.rs +++ /dev/null @@ -1,772 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ -#![feature(structural_match)] -#![feature(rustc_attrs)] -#![feature(core_intrinsics)] -#![feature(derive_eq)] -#![feature(trait_alias)] -#![crate_name = "enclave_runtime"] -#![crate_type = "staticlib"] -#![cfg_attr(not(target_env = "sgx"), no_std)] -#![cfg_attr(target_env = "sgx", feature(rustc_private))] -#![allow(clippy::missing_safety_doc)] -#![allow(clippy::unreachable)] -#![warn( - clippy::unwrap_used, - /* comment out for the moment. There are some upstream code `unimplemented` */ - // clippy::unimplemented, - // clippy::panic_in_result_fn, - clippy::string_slice, - clippy::panic, - clippy::indexing_slicing, - clippy::expect_used, - clippy::arithmetic_side_effects -)] - -#[cfg(not(target_env = "sgx"))] -#[macro_use] -extern crate sgx_tstd as std; - -use crate::{ - error::{Error, Result}, - initialization::global_components::{ - GLOBAL_INTEGRITEE_PARACHAIN_HANDLER_COMPONENT, GLOBAL_INTEGRITEE_PARENTCHAIN_NONCE_CACHE, - GLOBAL_INTEGRITEE_SOLOCHAIN_HANDLER_COMPONENT, GLOBAL_SHIELDING_KEY_REPOSITORY_COMPONENT, - GLOBAL_SIGNING_KEY_REPOSITORY_COMPONENT, GLOBAL_STATE_HANDLER_COMPONENT, - GLOBAL_TARGET_A_PARACHAIN_HANDLER_COMPONENT, GLOBAL_TARGET_A_PARENTCHAIN_NONCE_CACHE, - GLOBAL_TARGET_A_SOLOCHAIN_HANDLER_COMPONENT, GLOBAL_TARGET_B_PARACHAIN_HANDLER_COMPONENT, - GLOBAL_TARGET_B_PARENTCHAIN_NONCE_CACHE, GLOBAL_TARGET_B_SOLOCHAIN_HANDLER_COMPONENT, - }, - utils::{ - get_node_metadata_repository_from_integritee_solo_or_parachain, - get_node_metadata_repository_from_target_a_solo_or_parachain, - get_node_metadata_repository_from_target_b_solo_or_parachain, - get_validator_accessor_from_integritee_solo_or_parachain, DecodeRaw, - }, -}; -use codec::Decode; -use core::ffi::c_int; -#[cfg(feature = "development")] -use initialization::global_components::{ - GLOBAL_BITCOIN_KEY_REPOSITORY_COMPONENT, GLOBAL_ETHEREUM_KEY_REPOSITORY_COMPONENT, - GLOBAL_TON_KEY_REPOSITORY_COMPONENT, -}; -use itc_parentchain::{ - block_import_dispatcher::DispatchBlockImport, - light_client::{concurrent_access::ValidatorAccess, Validator}, -}; -use itp_component_container::ComponentGetter; -use itp_node_api::metadata::NodeMetadata; -use itp_nonce_cache::{MutateNonce, Nonce}; -#[cfg(feature = "development")] -use itp_sgx_crypto::key_repository::AccessKey; -use itp_sgx_crypto::key_repository::AccessPubkey; -use itp_storage::{StorageProof, StorageProofChecker}; -use itp_types::{parentchain::ParentchainId, ShardIdentifier, SignedBlock}; -use itp_utils::write_slice_and_whitespace_pad; -use litentry_macros::if_development_or; -use log::*; -use once_cell::sync::OnceCell; -use sgx_types::sgx_status_t; -use sp_runtime::traits::BlakeTwo256; -use std::{ - path::PathBuf, - slice, - string::{String, ToString}, - vec::Vec, -}; - -mod attestation; -mod empty_impls; -mod initialization; -mod ipfs; -mod ocall; -mod shard_config; -mod shard_creation_info; -mod stf_task_handler; -mod utils; - -pub mod error; -pub mod rpc; -mod sync; -#[cfg(feature = "test")] -pub mod test; -mod tls_ra; - -pub type Hash = sp_core::H256; -pub type AuthorityPair = sp_core::ed25519::Pair; - -static BASE_PATH: OnceCell = OnceCell::new(); - -fn get_base_path() -> Result { - let base_path = BASE_PATH.get().ok_or_else(|| { - Error::Other("BASE_PATH not initialized. Broken enclave init flow!".to_string().into()) - })?; - - Ok(base_path.clone()) -} - -/// Initialize the enclave. -#[no_mangle] -pub unsafe extern "C" fn init( - mu_ra_addr: *const u8, - mu_ra_addr_size: u32, - untrusted_worker_addr: *const u8, - untrusted_worker_addr_size: u32, - encoded_base_dir_str: *const u8, - encoded_base_dir_size: u32, - ceremony_commands_thread_count: u8, - ceremony_events_thread_count: u8, -) -> sgx_status_t { - // Initialize the logging environment in the enclave. - if_development_or!( - env_logger::builder() - .format_timestamp(Some(env_logger::TimestampPrecision::Micros)) - .init(), - { - let module_names = litentry_proc_macros::local_modules!(); - println!( - "Initializing logger to filter only following local modules: {:?}", - module_names - ); - let mut builder = env_logger::Builder::new(); - builder.format_timestamp(Some(env_logger::TimestampPrecision::Micros)); - builder.filter(None, LevelFilter::Off); - module_names.into_iter().for_each(|module| { - builder.filter(Some(module), LevelFilter::Info); - }); - builder.init(); - } - ); - - #[cfg(feature = "dcap")] - info!(" DCAP is enabled within enclave"); - #[cfg(not(feature = "dcap"))] - info!(" DCAP is disabled within enclave"); - - let mu_ra_url = - match String::decode(&mut slice::from_raw_parts(mu_ra_addr, mu_ra_addr_size as usize)) - .map_err(Error::Codec) - { - Ok(addr) => addr, - Err(e) => return e.into(), - }; - - let untrusted_worker_url = match String::decode(&mut slice::from_raw_parts( - untrusted_worker_addr, - untrusted_worker_addr_size as usize, - )) - .map_err(Error::Codec) - { - Ok(addr) => addr, - Err(e) => return e.into(), - }; - - let base_dir = match String::decode(&mut slice::from_raw_parts( - encoded_base_dir_str, - encoded_base_dir_size as usize, - )) - .map_err(Error::Codec) - { - Ok(b) => b, - Err(e) => return e.into(), - }; - - info!("Setting base_dir to {}", base_dir); - let path = PathBuf::from(base_dir); - // Litentry: the default value here is only for clippy checking - BASE_PATH.set(path.clone()).unwrap_or(()); - - match initialization::init_enclave( - mu_ra_url, - untrusted_worker_url, - path, - ceremony_commands_thread_count, - ceremony_events_thread_count, - ) { - Err(e) => e.into(), - Ok(()) => sgx_status_t::SGX_SUCCESS, - } -} - -#[no_mangle] -pub unsafe extern "C" fn get_rsa_encryption_pubkey( - pubkey: *mut u8, - pubkey_size: u32, -) -> sgx_status_t { - let shielding_key_repository = match GLOBAL_SHIELDING_KEY_REPOSITORY_COMPONENT.get() { - Ok(s) => s, - Err(e) => { - error!("{:?}", e); - return sgx_status_t::SGX_ERROR_UNEXPECTED - }, - }; - - let rsa_pubkey = match shielding_key_repository.retrieve_pubkey() { - Ok(key) => key, - Err(e) => return e.into(), - }; - - let rsa_pubkey_json = match serde_json::to_string(&rsa_pubkey) { - Ok(k) => k, - Err(x) => { - println!("[Enclave] can't serialize rsa_pubkey {:?} {}", rsa_pubkey, x); - return sgx_status_t::SGX_ERROR_UNEXPECTED - }, - }; - - let pubkey_slice = slice::from_raw_parts_mut(pubkey, pubkey_size as usize); - - if let Err(e) = - write_slice_and_whitespace_pad(pubkey_slice, rsa_pubkey_json.as_bytes().to_vec()) - { - return Error::BufferError(e).into() - }; - - sgx_status_t::SGX_SUCCESS -} - -#[no_mangle] -pub unsafe extern "C" fn get_ecc_signing_pubkey(pubkey: *mut u8, pubkey_size: u32) -> sgx_status_t { - let signing_key_repository = match GLOBAL_SIGNING_KEY_REPOSITORY_COMPONENT.get() { - Ok(s) => s, - Err(e) => { - error!("{:?}", e); - return sgx_status_t::SGX_ERROR_UNEXPECTED - }, - }; - - let signer_public = match signing_key_repository.retrieve_pubkey() { - Ok(s) => s, - Err(e) => return e.into(), - }; - - debug!("Restored ECC pubkey: {:?}", signer_public); - - let pubkey_slice = slice::from_raw_parts_mut(pubkey, pubkey_size as usize); - pubkey_slice.clone_from_slice(&signer_public); - - sgx_status_t::SGX_SUCCESS -} - -#[no_mangle] -#[cfg_attr(not(feature = "development"), allow(unused_variables))] -pub unsafe extern "C" fn get_bitcoin_wallet_pair(pair: *mut u8, pair_size: u32) -> sgx_status_t { - if_development_or!( - { - let bitcoin_key_repository = match GLOBAL_BITCOIN_KEY_REPOSITORY_COMPONENT.get() { - Ok(s) => s, - Err(e) => { - error!("{:?}", e); - return sgx_status_t::SGX_ERROR_UNEXPECTED - }, - }; - - let keypair = match bitcoin_key_repository.retrieve_key() { - Ok(p) => p, - Err(e) => return e.into(), - }; - - let privkey_slice = slice::from_raw_parts_mut(pair, pair_size as usize); - privkey_slice.clone_from_slice(&keypair.private_bytes()); - - sgx_status_t::SGX_SUCCESS - }, - { - error!("Bitcoin wallet can only be retrieved in non-prod"); - sgx_status_t::SGX_ERROR_UNEXPECTED - } - ) -} - -#[no_mangle] -#[cfg_attr(not(feature = "development"), allow(unused_variables))] -pub unsafe extern "C" fn get_ethereum_wallet_pair(pair: *mut u8, pair_size: u32) -> sgx_status_t { - if_development_or!( - { - let ethereum_key_repository = match GLOBAL_ETHEREUM_KEY_REPOSITORY_COMPONENT.get() { - Ok(s) => s, - Err(e) => { - error!("{:?}", e); - return sgx_status_t::SGX_ERROR_UNEXPECTED - }, - }; - - let keypair = match ethereum_key_repository.retrieve_key() { - Ok(p) => p, - Err(e) => return e.into(), - }; - - let privkey_slice = slice::from_raw_parts_mut(pair, pair_size as usize); - privkey_slice.clone_from_slice(&keypair.private_bytes()); - - sgx_status_t::SGX_SUCCESS - }, - { - error!("Ethereum wallet can only be retrieved in non-prod"); - sgx_status_t::SGX_ERROR_UNEXPECTED - } - ) -} - -#[no_mangle] -#[cfg_attr(not(feature = "development"), allow(unused_variables))] -pub unsafe extern "C" fn get_ton_wallet_pair(pair: *mut u8, pair_size: u32) -> sgx_status_t { - if_development_or!( - { - let ton_key_repository = match GLOBAL_TON_KEY_REPOSITORY_COMPONENT.get() { - Ok(s) => s, - Err(e) => { - error!("{:?}", e); - return sgx_status_t::SGX_ERROR_UNEXPECTED - }, - }; - - let keypair = match ton_key_repository.retrieve_key() { - Ok(p) => p, - Err(e) => return e.into(), - }; - - let privkey_slice = slice::from_raw_parts_mut(pair, pair_size as usize); - privkey_slice.clone_from_slice(&keypair.seed()); - - sgx_status_t::SGX_SUCCESS - }, - { - error!("Ton wallet can only be retrieved in non-prod"); - sgx_status_t::SGX_ERROR_UNEXPECTED - } - ) -} - -#[no_mangle] -pub unsafe extern "C" fn set_nonce( - nonce: *const u32, - parentchain_id: *const u8, - parentchain_id_size: u32, -) -> sgx_status_t { - let id = match ParentchainId::decode_raw(parentchain_id, parentchain_id_size as usize) { - Err(e) => { - error!("Failed to decode parentchain_id: {:?}", e); - return sgx_status_t::SGX_ERROR_UNEXPECTED - }, - Ok(m) => m, - }; - - info!("Setting the nonce of the enclave to: {} for parentchain: {:?}", *nonce, id); - - let nonce_lock = match id { - ParentchainId::Litentry => GLOBAL_INTEGRITEE_PARENTCHAIN_NONCE_CACHE.load_for_mutation(), - ParentchainId::TargetA => GLOBAL_TARGET_A_PARENTCHAIN_NONCE_CACHE.load_for_mutation(), - ParentchainId::TargetB => GLOBAL_TARGET_B_PARENTCHAIN_NONCE_CACHE.load_for_mutation(), - }; - - match nonce_lock { - Ok(mut nonce_guard) => *nonce_guard = Nonce(*nonce), - Err(e) => { - error!("Failed to set {:?} parentchain nonce in enclave: {:?}", id, e); - return sgx_status_t::SGX_ERROR_UNEXPECTED - }, - }; - - sgx_status_t::SGX_SUCCESS -} - -#[no_mangle] -pub unsafe extern "C" fn set_node_metadata( - node_metadata: *const u8, - node_metadata_size: u32, - parentchain_id: *const u8, - parentchain_id_size: u32, -) -> sgx_status_t { - let id = match ParentchainId::decode_raw(parentchain_id, parentchain_id_size as usize) { - Err(e) => { - error!("Failed to decode parentchain_id: {:?}", e); - return sgx_status_t::SGX_ERROR_UNEXPECTED - }, - Ok(m) => m, - }; - - let metadata = match NodeMetadata::decode_raw(node_metadata, node_metadata_size as usize) { - Err(e) => { - error!("Failed to decode node metadata: {:?}", e); - return sgx_status_t::SGX_ERROR_UNEXPECTED - }, - Ok(m) => m, - }; - - info!("Setting node meta data for parentchain: {:?}", id); - - let node_metadata_repository = match id { - ParentchainId::Litentry => get_node_metadata_repository_from_integritee_solo_or_parachain(), - ParentchainId::TargetA => get_node_metadata_repository_from_target_a_solo_or_parachain(), - ParentchainId::TargetB => get_node_metadata_repository_from_target_b_solo_or_parachain(), - }; - - match node_metadata_repository { - Ok(repo) => repo.set_metadata(metadata), - Err(e) => { - error!("Could not get {:?} parentchain component: {:?}", id, e); - return sgx_status_t::SGX_ERROR_UNEXPECTED - }, - }; - - trace!("Successfully set the node meta data"); - - sgx_status_t::SGX_SUCCESS -} - -#[no_mangle] -pub unsafe extern "C" fn publish_wallets() -> sgx_status_t { - if let Err(e) = initialization::publish_wallets() { - error!("Failed to publish generated wallets: {:?}", e); - return sgx_status_t::SGX_ERROR_UNEXPECTED - } - - sgx_status_t::SGX_SUCCESS -} - -#[no_mangle] -pub unsafe extern "C" fn finish_enclave_init() -> sgx_status_t { - if let Err(e) = initialization::finish_enclave_init() { - error!("Failed to finish enclave init: {:?}", e); - return sgx_status_t::SGX_ERROR_UNEXPECTED - } - - sgx_status_t::SGX_SUCCESS -} - -#[no_mangle] -pub unsafe extern "C" fn init_wallets( - encoded_base_dir_str: *const u8, - encoded_base_dir_size: u32, -) -> sgx_status_t { - let base_dir = match String::decode(&mut slice::from_raw_parts( - encoded_base_dir_str, - encoded_base_dir_size as usize, - )) - .map_err(Error::Codec) - { - Ok(b) => b, - Err(e) => return e.into(), - }; - - info!("Setting base_dir to {}", base_dir); - - let path = PathBuf::from(base_dir); - // Litentry: the default value here is only for clippy checking - BASE_PATH.set(path.clone()).unwrap_or(()); - - if let Err(e) = initialization::init_wallets(path) { - error!("Failed to init wallets: {:?}", e); - return sgx_status_t::SGX_ERROR_UNEXPECTED - } - - sgx_status_t::SGX_SUCCESS -} - -/// Call this once at worker startup to initialize the TOP pool and direct invocation RPC server. -/// -/// This function will run the RPC server on the same thread as it is called and will loop there. -/// That means that this function will not return as long as the RPC server is running. The calling -/// code should therefore spawn a new thread when calling this function. -#[no_mangle] -pub unsafe extern "C" fn init_direct_invocation_server( - server_addr: *const u8, - server_addr_size: usize, -) -> sgx_status_t { - let mut server_addr_encoded = slice::from_raw_parts(server_addr, server_addr_size); - - let server_addr = match String::decode(&mut server_addr_encoded) { - Ok(s) => s, - Err(e) => { - error!("Decoding RPC server address failed. Error: {:?}", e); - return sgx_status_t::SGX_ERROR_UNEXPECTED - }, - }; - - if let Err(e) = initialization::init_direct_invocation_server(server_addr) { - error!("Failed to initialize direct invocation server: {:?}", e); - return sgx_status_t::SGX_ERROR_UNEXPECTED - } - - sgx_status_t::SGX_SUCCESS -} - -#[no_mangle] -pub unsafe extern "C" fn init_parentchain_components( - params: *const u8, - params_size: usize, - latest_header: *mut u8, - latest_header_size: usize, -) -> sgx_status_t { - let encoded_params = slice::from_raw_parts(params, params_size); - let latest_header_slice = slice::from_raw_parts_mut(latest_header, latest_header_size); - - match init_parentchain_params_internal(encoded_params.to_vec(), latest_header_slice) { - Ok(()) => sgx_status_t::SGX_SUCCESS, - Err(e) => e.into(), - } -} - -/// Initializes the parentchain components and writes the latest header into the `latest_header` slice. -fn init_parentchain_params_internal(params: Vec, latest_header: &mut [u8]) -> Result<()> { - use initialization::parentchain::init_parentchain_components; - - let encoded_latest_header = init_parentchain_components(get_base_path()?, params)?; - - write_slice_and_whitespace_pad(latest_header, encoded_latest_header)?; - - Ok(()) -} - -#[no_mangle] -pub unsafe extern "C" fn init_shard(shard: *const u8, shard_size: u32) -> sgx_status_t { - let shard_identifier = - ShardIdentifier::from_slice(slice::from_raw_parts(shard, shard_size as usize)); - - if let Err(e) = initialization::init_shard(shard_identifier) { - error!("Failed to initialize shard ({:?}): {:?}", shard_identifier, e); - return sgx_status_t::SGX_ERROR_UNEXPECTED - } - - sgx_status_t::SGX_SUCCESS -} - -#[no_mangle] -pub unsafe extern "C" fn migrate_shard(new_shard: *const u8, shard_size: u32) -> sgx_status_t { - let shard_identifier = - ShardIdentifier::from_slice(slice::from_raw_parts(new_shard, shard_size as usize)); - - if let Err(e) = initialization::migrate_shard(shard_identifier) { - error!("Failed to migrate shard ({:?}): {:?}", shard_identifier, e); - return sgx_status_t::SGX_ERROR_UNEXPECTED - } - - sgx_status_t::SGX_SUCCESS -} - -#[no_mangle] -pub unsafe extern "C" fn sync_parentchain( - blocks_to_sync: *const u8, - blocks_to_sync_size: usize, - events_to_sync: *const u8, - events_to_sync_size: usize, - events_proofs_to_sync: *const u8, - events_proofs_to_sync_size: usize, - parentchain_id: *const u8, - parentchain_id_size: u32, - immediate_import: c_int, -) -> sgx_status_t { - if let Err(e) = sync_parentchain_internal( - blocks_to_sync, - blocks_to_sync_size, - events_to_sync, - events_to_sync_size, - events_proofs_to_sync, - events_proofs_to_sync_size, - parentchain_id, - parentchain_id_size, - immediate_import == 1, - ) { - error!("Error synching parentchain: {:?}", e); - return sgx_status_t::SGX_ERROR_UNEXPECTED - } - - sgx_status_t::SGX_SUCCESS -} - -#[allow(clippy::too_many_arguments)] -unsafe fn sync_parentchain_internal( - blocks_to_sync: *const u8, - blocks_to_sync_size: usize, - events_to_sync: *const u8, - events_to_sync_size: usize, - events_proofs_to_sync: *const u8, - events_proofs_to_sync_size: usize, - parentchain_id: *const u8, - parentchain_id_size: u32, - immediate_import: bool, -) -> Result<()> { - let blocks_to_sync = Vec::::decode_raw(blocks_to_sync, blocks_to_sync_size)?; - let events_to_sync = Vec::>::decode_raw(events_to_sync, events_to_sync_size)?; - let events_proofs_to_sync = - Vec::::decode_raw(events_proofs_to_sync, events_proofs_to_sync_size)?; - let parentchain_id = ParentchainId::decode_raw(parentchain_id, parentchain_id_size as usize)?; - - if !events_proofs_to_sync.is_empty() { - let blocks_to_sync_merkle_roots: Vec = - blocks_to_sync.iter().map(|block| block.block.header.state_root).collect(); - // fixme: vulnerability! https://github.com/integritee-network/worker/issues/1518 - // until fixed properly, we deactivate the panic upon error altogether in the scope of #1547 - if let Err(e) = validate_events(&events_proofs_to_sync, &blocks_to_sync_merkle_roots) { - warn!("ignoring event validation error {:?}", e); - // return e.into() - } - } - dispatch_parentchain_blocks_for_import( - blocks_to_sync, - events_to_sync, - &parentchain_id, - immediate_import, - ) -} - -#[no_mangle] -pub unsafe extern "C" fn ignore_parentchain_block_import_validation_until( - until: *const u32, -) -> sgx_status_t { - let va = match get_validator_accessor_from_integritee_solo_or_parachain() { - Ok(r) => r, - Err(e) => { - error!("Can't get validator accessor: {:?}", e); - return sgx_status_t::SGX_ERROR_UNEXPECTED - }, - }; - - let _ = va.execute_mut_on_validator(|v| v.set_ignore_validation_until(*until)); - - sgx_status_t::SGX_SUCCESS -} - -/// Dispatch the parentchain blocks for import. -/// Depending on the worker mode, a different dispatcher is used: -/// -/// * An immediate dispatcher will immediately import any parentchain blocks and execute -/// the corresponding extrinsics (offchain-worker executor). -/// * The sidechain uses a triggered dispatcher, where the import of a parentchain block is -/// synchronized and triggered by the sidechain block production cycle. -/// -fn dispatch_parentchain_blocks_for_import( - blocks_to_sync: Vec, - events_to_sync: Vec>, - id: &ParentchainId, - immediate_import: bool, -) -> Result<()> { - trace!( - "[{:?}] Dispatching Import of {} blocks and {} events", - id, - blocks_to_sync.len(), - events_to_sync.len() - ); - match id { - ParentchainId::Litentry => { - if let Ok(handler) = GLOBAL_INTEGRITEE_SOLOCHAIN_HANDLER_COMPONENT.get() { - handler.import_dispatcher.dispatch_import( - blocks_to_sync, - events_to_sync, - immediate_import, - )?; - } else if let Ok(handler) = GLOBAL_INTEGRITEE_PARACHAIN_HANDLER_COMPONENT.get() { - handler.import_dispatcher.dispatch_import( - blocks_to_sync, - events_to_sync, - immediate_import, - )?; - } else { - return Err(Error::NoLitentryParentchainAssigned) - }; - }, - ParentchainId::TargetA => { - if let Ok(handler) = GLOBAL_TARGET_A_SOLOCHAIN_HANDLER_COMPONENT.get() { - handler.import_dispatcher.dispatch_import( - blocks_to_sync, - events_to_sync, - immediate_import, - )?; - } else if let Ok(handler) = GLOBAL_TARGET_A_PARACHAIN_HANDLER_COMPONENT.get() { - handler.import_dispatcher.dispatch_import( - blocks_to_sync, - events_to_sync, - immediate_import, - )?; - } else { - return Err(Error::NoTargetAParentchainAssigned) - }; - }, - ParentchainId::TargetB => { - if let Ok(handler) = GLOBAL_TARGET_B_SOLOCHAIN_HANDLER_COMPONENT.get() { - handler.import_dispatcher.dispatch_import( - blocks_to_sync, - events_to_sync, - immediate_import, - )?; - } else if let Ok(handler) = GLOBAL_TARGET_B_PARACHAIN_HANDLER_COMPONENT.get() { - handler.import_dispatcher.dispatch_import( - blocks_to_sync, - events_to_sync, - immediate_import, - )?; - } else { - return Err(Error::NoTargetBParentchainAssigned) - }; - }, - } - - Ok(()) -} - -/// Validates the events coming from the parentchain -fn validate_events( - events_proofs: &Vec, - blocks_merkle_roots: &Vec, -) -> Result<()> { - debug!( - "Validating events, events_proofs_length: {:?}, blocks_merkle_roots_lengths: {:?}", - events_proofs.len(), - blocks_merkle_roots.len() - ); - - if events_proofs.len() != blocks_merkle_roots.len() { - return Err(Error::ParentChainSync) - } - - let events_key = itp_storage::storage_value_key("System", "Events"); - - let validated_events: Result>> = events_proofs - .iter() - .zip(blocks_merkle_roots.iter()) - .map(|(proof, root)| { - StorageProofChecker::::check_proof( - *root, - events_key.as_slice(), - proof.clone(), - ) - .ok() - .flatten() - .ok_or_else(|| Error::ParentChainValidation(itp_storage::Error::WrongValue)) - }) - .collect(); - - let _ = validated_events?; - - Ok(()) -} - -// This is required, because `ring` / `ring-xous` would not compile without it non-release (debug) mode. -// See #1200 for more details. -#[cfg(debug_assertions)] -#[no_mangle] -pub extern "C" fn __assert_fail( - __assertion: *const u8, - __file: *const u8, - __line: u32, - __function: *const u8, -) -> ! { - use core::intrinsics::abort; - abort() -} diff --git a/tee-worker/bitacross/enclave-runtime/src/ocall/attestation_ocall.rs b/tee-worker/bitacross/enclave-runtime/src/ocall/attestation_ocall.rs deleted file mode 100644 index 3a3abbae9e..0000000000 --- a/tee-worker/bitacross/enclave-runtime/src/ocall/attestation_ocall.rs +++ /dev/null @@ -1,275 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use crate::ocall::{ffi, OcallApi}; -use frame_support::ensure; -use itp_ocall_api::EnclaveAttestationOCallApi; -use lazy_static::lazy_static; -use log::*; -use sgx_tse::rsgx_create_report; -use sgx_types::*; -use std::{ptr, sync::Arc, vec::Vec}; - -use std::sync::SgxRwLock as RwLock; - -const RET_QUOTE_BUF_LEN: usize = 2048; - -lazy_static! { - /// Global cache of MRENCLAVE - /// will never change at runtime but must be initialized at runtime - static ref MY_MRENCLAVE: RwLock> = RwLock::new(Default::default()); -} - -#[derive(Default, Copy, Clone, Debug)] -pub struct MrEnclave { - pub maybe_mrenclave: Option, -} - -impl MrEnclave { - pub fn current() -> SgxResult> { - Ok(MY_MRENCLAVE - .read() - .map_err(|e| { - error!("fetching current value of MR_ENCLAVE lazy static failed: {:?}", e); - sgx_status_t::SGX_ERROR_UNEXPECTED - })? - .clone()) - } - pub fn make_current(self) -> SgxResult<()> { - *MY_MRENCLAVE.write().map_err(|e| { - error!("writing current value of MR_ENCLAVE lazy static failed: {:?}", e); - sgx_status_t::SGX_ERROR_UNEXPECTED - })? = Arc::new(self); - Ok(()) - } -} - -impl EnclaveAttestationOCallApi for OcallApi { - fn sgx_init_quote(&self) -> SgxResult<(sgx_target_info_t, sgx_epid_group_id_t)> { - let mut ti: sgx_target_info_t = sgx_target_info_t::default(); - let mut eg: sgx_epid_group_id_t = sgx_epid_group_id_t::default(); - let mut rt: sgx_status_t = sgx_status_t::SGX_ERROR_UNEXPECTED; - - let res = unsafe { - ffi::ocall_sgx_init_quote( - &mut rt as *mut sgx_status_t, - &mut ti as *mut sgx_target_info_t, - &mut eg as *mut sgx_epid_group_id_t, - ) - }; - - ensure!(res == sgx_status_t::SGX_SUCCESS, res); - ensure!(rt == sgx_status_t::SGX_SUCCESS, rt); - - Ok((ti, eg)) - } - - fn get_ias_socket(&self) -> SgxResult { - let mut rt: sgx_status_t = sgx_status_t::SGX_ERROR_UNEXPECTED; - let mut ias_sock: i32 = 0; - - let res = unsafe { - ffi::ocall_get_ias_socket(&mut rt as *mut sgx_status_t, &mut ias_sock as *mut i32) - }; - - ensure!(res == sgx_status_t::SGX_SUCCESS, res); - ensure!(rt == sgx_status_t::SGX_SUCCESS, rt); - - Ok(ias_sock) - } - - fn get_quote( - &self, - sig_rl: Vec, - report: sgx_report_t, - sign_type: sgx_quote_sign_type_t, - spid: sgx_spid_t, - quote_nonce: sgx_quote_nonce_t, - ) -> SgxResult<(sgx_report_t, Vec)> { - let mut qe_report = sgx_report_t::default(); - let mut return_quote_buf = [0u8; RET_QUOTE_BUF_LEN]; - let mut quote_len: u32 = 0; - - let (p_sigrl, sigrl_len) = if sig_rl.is_empty() { - (ptr::null(), 0) - } else { - (sig_rl.as_ptr(), sig_rl.len() as u32) - }; - let p_report = &report as *const sgx_report_t; - let quote_type = sign_type; - - let mut rt: sgx_status_t = sgx_status_t::SGX_ERROR_UNEXPECTED; - let p_spid = &spid as *const sgx_spid_t; - let p_nonce = "e_nonce as *const sgx_quote_nonce_t; - let p_qe_report = &mut qe_report as *mut sgx_report_t; - let p_quote = return_quote_buf.as_mut_ptr(); - let maxlen = RET_QUOTE_BUF_LEN as u32; - let p_quote_len = &mut quote_len as *mut u32; - - let result = unsafe { - ffi::ocall_get_quote( - &mut rt as *mut sgx_status_t, - p_sigrl, - sigrl_len, - p_report, - quote_type, - p_spid, - p_nonce, - p_qe_report, - p_quote, - maxlen, - p_quote_len, - ) - }; - - ensure!(result == sgx_status_t::SGX_SUCCESS, result); - ensure!(rt == sgx_status_t::SGX_SUCCESS, rt); - - #[allow(clippy::indexing_slicing)] - let quote_vec: Vec = Vec::from(&return_quote_buf[..quote_len as usize]); - - Ok((qe_report, quote_vec)) - } - - fn get_dcap_quote(&self, report: sgx_report_t, quote_size: u32) -> SgxResult> { - let mut return_quote_buf = vec![0u8; quote_size as usize]; - let p_quote = return_quote_buf.as_mut_ptr(); - let p_report = &report as *const sgx_report_t; - let mut rt: sgx_status_t = sgx_status_t::SGX_ERROR_UNEXPECTED; - - let result = unsafe { - ffi::ocall_get_dcap_quote(&mut rt as *mut sgx_status_t, p_report, p_quote, quote_size) - }; - ensure!(result == sgx_status_t::SGX_SUCCESS, result); - ensure!(rt == sgx_status_t::SGX_SUCCESS, rt); - #[allow(clippy::indexing_slicing)] - let quote_vec: Vec = Vec::from(&return_quote_buf[..quote_size as usize]); - Ok(quote_vec) - } - - fn get_qve_report_on_quote( - &self, - quote: Vec, - current_time: i64, - quote_collateral: sgx_ql_qve_collateral_t, - qve_report_info: sgx_ql_qe_report_info_t, - supplemental_data_size: u32, - ) -> SgxResult<(u32, sgx_ql_qv_result_t, sgx_ql_qe_report_info_t, Vec)> { - let mut supplemental_data = vec![0u8; supplemental_data_size as usize]; - let mut qve_report_info_return_value: sgx_ql_qe_report_info_t = qve_report_info; - let mut quote_verification_result = sgx_ql_qv_result_t::SGX_QL_QV_RESULT_UNSPECIFIED; - let mut collateral_expiration_status = 1u32; - let mut rt: sgx_status_t = sgx_status_t::SGX_ERROR_UNEXPECTED; - - let result = unsafe { - ffi::ocall_get_qve_report_on_quote( - &mut rt as *mut sgx_status_t, - quote.as_ptr(), - quote.len() as u32, - current_time, - "e_collateral as *const sgx_ql_qve_collateral_t, - &mut collateral_expiration_status as *mut u32, - &mut quote_verification_result as *mut sgx_ql_qv_result_t, - &mut qve_report_info_return_value as *mut sgx_ql_qe_report_info_t, - supplemental_data.as_mut_ptr(), - supplemental_data_size, - ) - }; - ensure!(result == sgx_status_t::SGX_SUCCESS, result); - ensure!(rt == sgx_status_t::SGX_SUCCESS, rt); - - Ok(( - collateral_expiration_status, - quote_verification_result, - qve_report_info_return_value, - supplemental_data.to_vec(), - )) - } - - fn get_update_info( - &self, - platform_info: sgx_platform_info_t, - enclave_trusted: i32, - ) -> SgxResult { - let mut rt: sgx_status_t = sgx_status_t::SGX_ERROR_UNEXPECTED; - let mut update_info = sgx_update_info_bit_t::default(); - - let result = unsafe { - ffi::ocall_get_update_info( - &mut rt as *mut sgx_status_t, - &platform_info as *const sgx_platform_info_t, - enclave_trusted, - &mut update_info as *mut sgx_update_info_bit_t, - ) - }; - - // debug logging - if rt != sgx_status_t::SGX_SUCCESS { - warn!("ocall_get_update_info unsuccessful. rt={:?}", rt); - // Curly braces to copy `unaligned_references` of packed fields into properly aligned temporary: - // https://github.com/rust-lang/rust/issues/82523 - debug!("update_info.pswUpdate: {}", { update_info.pswUpdate }); - debug!("update_info.csmeFwUpdate: {}", { update_info.csmeFwUpdate }); - debug!("update_info.ucodeUpdate: {}", { update_info.ucodeUpdate }); - } - - ensure!(result == sgx_status_t::SGX_SUCCESS, result); - ensure!(rt == sgx_status_t::SGX_SUCCESS, rt); - - Ok(update_info) - } - - fn get_mrenclave_of_self(&self) -> SgxResult { - if let Some(mrenclave) = MrEnclave::current()?.maybe_mrenclave { - trace!("found cached MRENCLAVE"); - return Ok(mrenclave) - }; - debug!("initializing MY_MRENCLAVE cache"); - let mrenclave_value = self.get_report_of_self()?.mr_enclave; - MrEnclave { maybe_mrenclave: Some(mrenclave_value) }.make_current()?; - Ok(mrenclave_value) - } -} - -trait GetSgxReport { - fn get_report_of_self(&self) -> SgxResult; -} - -impl GetSgxReport for T { - fn get_report_of_self(&self) -> SgxResult { - // (1) get ti + eg - let init_quote_result = self.sgx_init_quote()?; - - let target_info = init_quote_result.0; - let report_data: sgx_report_data_t = sgx_report_data_t::default(); - - let rep = match rsgx_create_report(&target_info, &report_data) { - Ok(r) => { - debug!( - " [Enclave] Report creation successful. mr_signer.m = {:?}", - r.body.mr_signer.m - ); - r - }, - Err(e) => { - error!(" [Enclave] Report creation failed. {:?}", e); - return Err(e) - }, - }; - Ok(rep.body) - } -} diff --git a/tee-worker/bitacross/enclave-runtime/src/ocall/ffi.rs b/tee-worker/bitacross/enclave-runtime/src/ocall/ffi.rs deleted file mode 100644 index b2b163f827..0000000000 --- a/tee-worker/bitacross/enclave-runtime/src/ocall/ffi.rs +++ /dev/null @@ -1,111 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use sgx_types::*; - -extern "C" { - pub fn ocall_sgx_init_quote( - ret_val: *mut sgx_status_t, - ret_ti: *mut sgx_target_info_t, - ret_gid: *mut sgx_epid_group_id_t, - ) -> sgx_status_t; - - pub fn ocall_get_ias_socket(ret_val: *mut sgx_status_t, ret_fd: *mut i32) -> sgx_status_t; - - pub fn ocall_get_quote( - ret_val: *mut sgx_status_t, - p_sigrl: *const u8, - sigrl_len: u32, - p_report: *const sgx_report_t, - quote_type: sgx_quote_sign_type_t, - p_spid: *const sgx_spid_t, - p_nonce: *const sgx_quote_nonce_t, - p_qe_report: *mut sgx_report_t, - p_quote: *mut u8, - maxlen: u32, - p_quote_len: *mut u32, - ) -> sgx_status_t; - - pub fn ocall_get_dcap_quote( - ret_val: *mut sgx_status_t, - p_report: *const sgx_report_t, - p_quote: *mut u8, - quote_size: u32, - ) -> sgx_status_t; - - pub fn ocall_get_qve_report_on_quote( - ret_val: *mut sgx_status_t, - p_quote: *const u8, - quote_len: u32, - current_time: i64, - p_quote_collateral: *const sgx_ql_qve_collateral_t, - p_collateral_expiration_status: *mut u32, - p_quote_verification_result: *mut sgx_ql_qv_result_t, - p_qve_report_info: *mut sgx_ql_qe_report_info_t, - p_supplemental_data: *mut u8, - supplemental_data_size: u32, - ) -> sgx_status_t; - - pub fn ocall_get_update_info( - ret_val: *mut sgx_status_t, - platform_blob: *const sgx_platform_info_t, - enclave_trusted: i32, - update_info: *mut sgx_update_info_bit_t, - ) -> sgx_status_t; - - pub fn ocall_worker_request( - ret_val: *mut sgx_status_t, - request: *const u8, - req_size: u32, - parentchain_id: *const u8, - parentchain_id_size: u32, - response: *mut u8, - resp_size: u32, - ) -> sgx_status_t; - - pub fn ocall_update_metric( - ret_val: *mut sgx_status_t, - metric_ptr: *const u8, - metric_size: u32, - ) -> sgx_status_t; - - pub fn ocall_send_to_parentchain( - ret_val: *mut sgx_status_t, - extrinsics: *const u8, - extrinsics_size: u32, - parentchain_id: *const u8, - parentchain_id_size: u32, - watch_until: *const u8, - watch_until_size: u32, - response: *mut u8, - response_size: u32, - ) -> sgx_status_t; - - pub fn ocall_read_ipfs( - ret_val: *mut sgx_status_t, - cid: *const u8, - cid_size: u32, - ) -> sgx_status_t; - - pub fn ocall_write_ipfs( - ret_val: *mut sgx_status_t, - enc_state: *const u8, - enc_state_size: u32, - cid: *mut u8, - cid_size: u32, - ) -> sgx_status_t; -} diff --git a/tee-worker/bitacross/enclave-runtime/src/ocall/ipfs_ocall.rs b/tee-worker/bitacross/enclave-runtime/src/ocall/ipfs_ocall.rs deleted file mode 100644 index d1a5530856..0000000000 --- a/tee-worker/bitacross/enclave-runtime/src/ocall/ipfs_ocall.rs +++ /dev/null @@ -1,57 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - Copyright (C) 2017-2019 Baidu, Inc. All Rights Reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use crate::ocall::{ffi, OcallApi}; -use frame_support::ensure; -use itp_ocall_api::{EnclaveIpfsOCallApi, IpfsCid}; -use sgx_types::{sgx_status_t, SgxResult}; - -impl EnclaveIpfsOCallApi for OcallApi { - fn write_ipfs(&self, encoded_state: &[u8]) -> SgxResult { - let mut rt: sgx_status_t = sgx_status_t::SGX_ERROR_UNEXPECTED; - let mut cid_buf = IpfsCid([0u8; 46]); - - let res = unsafe { - ffi::ocall_write_ipfs( - &mut rt as *mut sgx_status_t, - encoded_state.as_ptr(), - encoded_state.len() as u32, - cid_buf.0.as_mut_ptr(), - cid_buf.0.len() as u32, - ) - }; - - ensure!(rt == sgx_status_t::SGX_SUCCESS, rt); - ensure!(res == sgx_status_t::SGX_SUCCESS, res); - - Ok(cid_buf) - } - - fn read_ipfs(&self, cid: &IpfsCid) -> SgxResult<()> { - let mut rt: sgx_status_t = sgx_status_t::SGX_ERROR_UNEXPECTED; - - let res = unsafe { - ffi::ocall_read_ipfs(&mut rt as *mut sgx_status_t, cid.0.as_ptr(), cid.0.len() as u32) - }; - - ensure!(rt == sgx_status_t::SGX_SUCCESS, rt); - ensure!(res == sgx_status_t::SGX_SUCCESS, res); - - Ok(()) - } -} diff --git a/tee-worker/bitacross/enclave-runtime/src/ocall/metrics_ocall.rs b/tee-worker/bitacross/enclave-runtime/src/ocall/metrics_ocall.rs deleted file mode 100644 index 0d12dfd7d6..0000000000 --- a/tee-worker/bitacross/enclave-runtime/src/ocall/metrics_ocall.rs +++ /dev/null @@ -1,42 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use crate::ocall::{ffi, OcallApi}; -use codec::Encode; -use frame_support::ensure; -use itp_ocall_api::EnclaveMetricsOCallApi; -use sgx_types::{sgx_status_t, SgxResult}; - -impl EnclaveMetricsOCallApi for OcallApi { - fn update_metric(&self, metric: Metric) -> SgxResult<()> { - let mut rt: sgx_status_t = sgx_status_t::SGX_ERROR_UNEXPECTED; - let metric_encoded = metric.encode(); - - let res = unsafe { - ffi::ocall_update_metric( - &mut rt as *mut sgx_status_t, - metric_encoded.as_ptr(), - metric_encoded.len() as u32, - ) - }; - - ensure!(rt == sgx_status_t::SGX_SUCCESS, rt); - ensure!(res == sgx_status_t::SGX_SUCCESS, res); - - Ok(()) - } -} diff --git a/tee-worker/bitacross/enclave-runtime/src/ocall/mod.rs b/tee-worker/bitacross/enclave-runtime/src/ocall/mod.rs deleted file mode 100644 index f85d82d8b3..0000000000 --- a/tee-worker/bitacross/enclave-runtime/src/ocall/mod.rs +++ /dev/null @@ -1,25 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -mod attestation_ocall; -mod ffi; -mod ipfs_ocall; -mod metrics_ocall; -mod on_chain_ocall; - -#[derive(Clone, Debug, Default)] -pub struct OcallApi; diff --git a/tee-worker/bitacross/enclave-runtime/src/ocall/on_chain_ocall.rs b/tee-worker/bitacross/enclave-runtime/src/ocall/on_chain_ocall.rs deleted file mode 100644 index 60ee217585..0000000000 --- a/tee-worker/bitacross/enclave-runtime/src/ocall/on_chain_ocall.rs +++ /dev/null @@ -1,226 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - Copyright (C) 2017-2019 Baidu, Inc. All Rights Reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use crate::ocall::{ffi, OcallApi}; -use codec::{Decode, Encode, MaxEncodedLen}; -use frame_support::ensure; -use itp_node_api::api_client::{ExtrinsicReport, XtStatus}; -use itp_ocall_api::{EnclaveOnChainOCallApi, Error, Result}; -use itp_storage::{verify_storage_entries, Error as StorageError}; -use itp_types::{ - parentchain::{AccountId, Index as ParentchainIndex, ParentchainId}, - storage::StorageEntryVerified, - WorkerRequest, WorkerResponse, H256, -}; -use log::*; -use sgx_types::*; -use sp_runtime::{traits::Header, OpaqueExtrinsic}; -use std::{mem::size_of, vec::Vec}; - -impl EnclaveOnChainOCallApi for OcallApi { - fn send_to_parentchain( - &self, - extrinsics: Vec, - parentchain_id: &ParentchainId, - watch_until: Option, - ) -> SgxResult>> { - let mut rt: sgx_status_t = sgx_status_t::SGX_ERROR_UNEXPECTED; - let extrinsics_encoded = extrinsics.encode(); - let parentchain_id_encoded = parentchain_id.encode(); - let watch_until_encoded = watch_until.encode(); - let response_size = match watch_until { - Some(_) => extrinsics - .len() - .checked_mul(ExtrinsicReport::::max_encoded_len()) - .ok_or(sgx_status_t::SGX_ERROR_UNEXPECTED)? - .checked_add(size_of::>()) - .ok_or(sgx_status_t::SGX_ERROR_UNEXPECTED)?, - None => size_of::>(), - }; - let mut response: Vec = vec![0; response_size]; - - let res = unsafe { - ffi::ocall_send_to_parentchain( - &mut rt as *mut sgx_status_t, - extrinsics_encoded.as_ptr(), - extrinsics_encoded.len() as u32, - parentchain_id_encoded.as_ptr(), - parentchain_id_encoded.len() as u32, - watch_until_encoded.as_ptr(), - watch_until_encoded.len() as u32, - response.as_mut_ptr(), - response_size as u32, - ) - }; - - ensure!(rt == sgx_status_t::SGX_SUCCESS, rt); - ensure!(res == sgx_status_t::SGX_SUCCESS, res); - - let decoded_response: Vec> = Decode::decode(&mut response.as_slice()) - .map_err(|e| { - error!("Failed to decode ExtrinsicReport: {}", e); - sgx_status_t::SGX_ERROR_UNEXPECTED - })?; - - Ok(decoded_response) - } - - fn worker_request( - &self, - req: Vec, - parentchain_id: &ParentchainId, - ) -> SgxResult>> { - let mut rt: sgx_status_t = sgx_status_t::SGX_ERROR_UNEXPECTED; - // Litentry: since #1221 we need 28139 bytes - let mut resp: Vec = vec![0; 4196 * 16]; - let request_encoded = req.encode(); - let parentchain_id_encoded = parentchain_id.encode(); - - let res = unsafe { - ffi::ocall_worker_request( - &mut rt as *mut sgx_status_t, - request_encoded.as_ptr(), - request_encoded.len() as u32, - parentchain_id_encoded.as_ptr(), - parentchain_id_encoded.len() as u32, - resp.as_mut_ptr(), - resp.len() as u32, - ) - }; - - ensure!(rt == sgx_status_t::SGX_SUCCESS, rt); - ensure!(res == sgx_status_t::SGX_SUCCESS, res); - - let decoded_response: Vec> = Decode::decode(&mut resp.as_slice()) - .map_err(|e| { - error!("Failed to decode WorkerResponse: {}", e); - sgx_status_t::SGX_ERROR_UNEXPECTED - })?; - - Ok(decoded_response) - } - - fn get_storage_verified, V: Decode>( - &self, - storage_hash: Vec, - header: &H, - parentchain_id: &ParentchainId, - ) -> Result> { - // the code below seems like an overkill, but it is surprisingly difficult to - // get an owned value from a `Vec` without cloning. - Ok(self - .get_multiple_storages_verified(vec![storage_hash], header, parentchain_id)? - .into_iter() - .next() - .ok_or(StorageError::StorageValueUnavailable)?) - } - - fn get_multiple_storages_verified, V: Decode>( - &self, - storage_hashes: Vec>, - header: &H, - parentchain_id: &ParentchainId, - ) -> Result>> { - let requests = storage_hashes - .into_iter() - .map(|key| WorkerRequest::ChainStorage(key, Some(header.hash()))) - .collect(); - - let storage_entries = self - .worker_request::>(requests, parentchain_id) - .map(|storages| verify_storage_entries(storages, header))??; - - Ok(storage_entries) - } - - fn get_storage_keys>( - &self, - key_prefix: Vec, - header: Option<&H>, - ) -> Result>> { - let header_hash = header.map(|h| h.hash()); - let requests = vec![WorkerRequest::ChainStorageKeys(key_prefix, header_hash)]; - - let responses: Vec>> = self - .worker_request::>(requests, &ParentchainId::Litentry)? - .iter() - .filter_map(|r| match r { - WorkerResponse::ChainStorageKeys(k) => Some(k.clone()), - _ => None, - }) - .collect(); - - // we should only have one response as we only sent one request - let first_response = responses.get(0).ok_or(StorageError::WrongValue)?; - Ok(first_response.clone()) - } - - fn get_storage_keys_paged>( - &self, - key_prefix: Vec, - count: u32, - start_key: Option>, - header: Option<&H>, - ) -> Result>> { - let header_hash = header.map(|h| h.hash()); - let requests = - vec![WorkerRequest::ChainStorageKeysPaged(key_prefix, count, start_key, header_hash)]; - - let responses: Vec>> = self - .worker_request::>(requests, &ParentchainId::Litentry)? - .iter() - .filter_map(|r| match r { - WorkerResponse::ChainStorageKeys(k) => Some(k.clone()), - _ => None, - }) - .collect(); - - // we should only have one response as we only sent one request - let first_response = responses.get(0).ok_or(StorageError::WrongValue)?; - Ok(first_response.clone()) - } - - fn get_header>(&self) -> Result { - let request = vec![WorkerRequest::ChainHeader(None)]; - let responses: Vec = self - .worker_request::>(request, &ParentchainId::Litentry)? - .iter() - .filter_map(|r| match r { - WorkerResponse::ChainHeader(Some(h)) => - Some(Decode::decode(&mut h.as_slice()).ok()?), - _ => None, - }) - .collect(); - - responses.first().cloned().ok_or(Error::ChainCallFailed) - } - - fn get_account_nonce(&self, account_id: AccountId) -> Result { - let request = vec![WorkerRequest::ChainAccountNonce(account_id.encode())]; - let responses: Vec = self - .worker_request::>(request, &ParentchainId::Litentry)? - .iter() - .filter_map(|r| match r { - WorkerResponse::ChainAccountNonce(Some(index)) => Some(*index), - _ => None, - }) - .collect(); - - responses.first().cloned().ok_or(Error::ChainCallFailed) - } -} diff --git a/tee-worker/bitacross/enclave-runtime/src/rpc/mod.rs b/tee-worker/bitacross/enclave-runtime/src/rpc/mod.rs deleted file mode 100644 index 5b359ab270..0000000000 --- a/tee-worker/bitacross/enclave-runtime/src/rpc/mod.rs +++ /dev/null @@ -1,19 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -pub mod rpc_response_channel; -pub mod worker_api_direct; diff --git a/tee-worker/bitacross/enclave-runtime/src/rpc/rpc_response_channel.rs b/tee-worker/bitacross/enclave-runtime/src/rpc/rpc_response_channel.rs deleted file mode 100644 index 7a84fde928..0000000000 --- a/tee-worker/bitacross/enclave-runtime/src/rpc/rpc_response_channel.rs +++ /dev/null @@ -1,40 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use crate::initialization::global_components::GLOBAL_WEB_SOCKET_SERVER_COMPONENT; -use itc_direct_rpc_server::{response_channel::ResponseChannel, DirectRpcError}; -use itc_tls_websocket_server::{ConnectionToken, WebSocketResponder}; -use itp_component_container::ComponentGetter; -use std::string::String; - -/// RPC response channel. -/// -/// Uses the web-socket server to send an RPC response/update. -/// In case no server is available or running, the response will be discarded. -#[derive(Default)] -pub struct RpcResponseChannel; - -impl ResponseChannel for RpcResponseChannel { - type Error = DirectRpcError; - - fn respond(&self, token: ConnectionToken, message: String) -> Result<(), Self::Error> { - let web_socket_server = GLOBAL_WEB_SOCKET_SERVER_COMPONENT - .get() - .map_err(|e| DirectRpcError::Other(e.into()))?; - web_socket_server.send_message(token, message).map_err(|e| e.into()) - } -} diff --git a/tee-worker/bitacross/enclave-runtime/src/rpc/worker_api_direct.rs b/tee-worker/bitacross/enclave-runtime/src/rpc/worker_api_direct.rs deleted file mode 100644 index e89f840a32..0000000000 --- a/tee-worker/bitacross/enclave-runtime/src/rpc/worker_api_direct.rs +++ /dev/null @@ -1,603 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use crate::{ - attestation::{ - generate_dcap_ra_extrinsic_from_quote_internal, - generate_ias_ra_extrinsic_from_der_cert_internal, - }, - initialization::global_components::{ - EnclaveBitcoinKeyRepository, EnclaveEthereumKeyRepository, EnclaveSigningKeyRepository, - EnclaveTonKeyRepository, - }, - std::string::ToString, - utils::get_validator_accessor_from_integritee_solo_or_parachain, -}; -use bc_musig2_ceremony::{generate_aggregated_public_key, PublicKey}; -use bc_signer_registry::SignerRegistryLookup; -use bc_task_sender::{BitAcrossProcessingResult, BitAcrossRequest, BitAcrossRequestSender}; -use codec::Encode; -use core::result::Result; -use futures_sgx::channel::oneshot; -use ita_sgx_runtime::Runtime; -use ita_stf::{Getter, TrustedCallSigned}; -use itc_parentchain::light_client::{concurrent_access::ValidatorAccess, ExtrinsicSender}; -use itp_ocall_api::EnclaveAttestationOCallApi; -use itp_primitives_cache::{GetPrimitives, GLOBAL_PRIMITIVES_CACHE}; -use itp_rpc::RpcReturnValue; -use itp_sgx_crypto::{ - ed25519_derivation::DeriveEd25519, - key_repository::{AccessKey, AccessPubkey}, - ShieldingCryptoDecrypt, ShieldingCryptoEncrypt, -}; -use itp_stf_executor::getter_executor::ExecuteGetter; -use itp_stf_primitives::types::KeyPair; -use itp_top_pool_author::traits::AuthorApi; -use itp_types::{DirectRequestStatus, RsaRequest, ShardIdentifier, H256}; -use itp_utils::{FromHexPrefixed, ToHexPrefixed}; -use jsonrpc_core::{serde_json::json, IoHandler, Params, Value}; -use lc_direct_call::DirectCall; -use litentry_primitives::{Identity, PlainRequest}; -use log::{debug, error}; -use sgx_crypto_helper::rsa3072::Rsa3072PubKey; -use sp_core::crypto::Pair; -use sp_runtime::OpaqueExtrinsic; -use std::{borrow::ToOwned, boxed::Box, format, str, string::String, sync::Arc, vec::Vec}; - -fn compute_hex_encoded_return_error(error_msg: &str) -> String { - RpcReturnValue::from_error_message(error_msg).to_hex() -} - -fn get_all_rpc_methods_string(io_handler: &IoHandler) -> String { - let method_string = io_handler - .iter() - .map(|rp_tuple| rp_tuple.0.to_owned()) - .collect::>() - .join(", "); - - format!("methods: [{}]", method_string) -} - -#[allow(clippy::too_many_arguments)] -pub fn public_api_rpc_handler( - top_pool_author: Arc, - getter_executor: Arc, - shielding_key: Arc, - ocall_api: Arc, - signing_key_repository: Arc, - bitcoin_key_repository: Arc, - ethereum_key_repository: Arc, - ton_key_repository: Arc, - signer_lookup: Arc, -) -> IoHandler -where - Author: AuthorApi + Send + Sync + 'static, - GetterExecutor: ExecuteGetter + Send + Sync + 'static, - AccessShieldingKey: AccessPubkey + AccessKey + Send + Sync + 'static, - ::KeyType: - ShieldingCryptoDecrypt + ShieldingCryptoEncrypt + DeriveEd25519 + Send + Sync + 'static, - OcallApi: EnclaveAttestationOCallApi + Send + Sync + 'static, - SR: SignerRegistryLookup + Send + Sync + 'static, -{ - let mut io = IoHandler::new(); - - let signer_lookup_cloned = signer_lookup.clone(); - let shielding_key_cloned = shielding_key.clone(); - let signing_key_repository_cloned = signing_key_repository.clone(); - let ocall_api_cloned = ocall_api.clone(); - io.add_sync_method("author_getShieldingKey", move |_: Params| { - debug!("worker_api_direct rpc was called: author_getShieldingKey"); - let rsa_pubkey = match shielding_key_cloned.retrieve_pubkey() { - Ok(key) => key, - Err(status) => { - let error_msg: String = format!("Could not get rsa pubkey due to: {}", status); - return Ok(json!(compute_hex_encoded_return_error(error_msg.as_str()))) - }, - }; - - let rsa_pubkey_json = match serde_json::to_string(&rsa_pubkey) { - Ok(k) => k, - Err(x) => { - let error_msg: String = - format!("[Enclave] can't serialize rsa_pubkey {:?} {}", rsa_pubkey, x); - return Ok(json!(compute_hex_encoded_return_error(error_msg.as_str()))) - }, - }; - let json_value = - RpcReturnValue::new(rsa_pubkey_json.encode(), false, DirectRequestStatus::Ok); - Ok(json!(json_value.to_hex())) - }); - - // author_getEnclaveSignerAccount - let rsa_pubkey_name: &str = "author_getEnclaveSignerAccount"; - io.add_sync_method(rsa_pubkey_name, move |_: Params| { - let enclave_signer_public_key = match shielding_key - .retrieve_key() - .and_then(|keypair| keypair.derive_ed25519().map(|keypair| keypair.public().to_hex())) - { - Err(e) => { - let error_msg: String = format!("{:?}", e); - return Ok(json!(compute_hex_encoded_return_error(error_msg.as_str()))) - }, - Ok(public_key) => public_key, - }; - debug!("[Enclave] enclave_signer_public_key: {:?}", enclave_signer_public_key); - - let json_value = RpcReturnValue { - do_watch: false, - value: enclave_signer_public_key.encode(), - status: DirectRequestStatus::Ok, - }; - - Ok(json!(json_value.to_hex())) - }); - - // Submit BitAcross Request - io.add_method("bitacross_submitRequest", move |params: Params| { - debug!("worker_api_direct rpc was called: bitacross_submitRequest"); - async move { - let json_value = match bitacross_task_create_inner(params).await { - Ok(value) => value.to_hex(), - Err(error) => RpcReturnValue { - value: error, - do_watch: false, - status: DirectRequestStatus::Error, - } - .to_hex(), - }; - Ok(json!(json_value)) - } - }); - - // btc sign task data share - io.add_sync_method("bitacross_btcDataShare", move |params: Params| { - debug!("worker_api_direct rpc was called: bitacross_btcDataShare"); - let json_value = match bitacross_data_share_inner(params) { - Ok(value) => value.to_hex(), - Err(error) => - RpcReturnValue { value: error, do_watch: false, status: DirectRequestStatus::Error } - .to_hex(), - }; - Ok(json!(json_value)) - }); - - io.add_method("bitacross_checkSignBitcoin", move |_params: Params| { - debug!("worker_api_direct rpc was called: bitacross_checkSignBitcoin"); - let request = prepare_check_sign_bitcoin_request( - signing_key_repository_cloned.as_ref(), - ocall_api_cloned.as_ref(), - ); - async move { - if let Ok(request) = request { - let params = Params::Array(vec![jsonrpc_core::Value::String(request.to_hex())]); - let json_value = match bitacross_task_create_inner(params).await { - Ok(value) => value.to_hex(), - Err(error) => RpcReturnValue { - value: error, - do_watch: false, - status: DirectRequestStatus::Error, - } - .to_hex(), - }; - Ok(json!(json_value)) - } else { - Ok(json!(RpcReturnValue { - value: vec![], - do_watch: false, - status: DirectRequestStatus::Error, - } - .to_hex())) - } - } - }); - - io.add_sync_method("bitacross_aggregatedPublicKey", move |_: Params| { - debug!("worker_api_direct rpc was called: bitacross_aggregatedPublicKey"); - if let Ok(keys) = signer_lookup - .get_all() - .iter() - .map(|(_, pub_key)| PublicKey::from_sec1_bytes(pub_key)) - .collect() - { - let key_bytes = generate_aggregated_public_key(keys).to_sec1_bytes().to_vec(); - let json_value = RpcReturnValue::new(key_bytes, false, DirectRequestStatus::Ok); - Ok(json!(json_value.to_hex())) - } else { - Ok(json!(compute_hex_encoded_return_error("Could not produce aggregate key"))) - } - }); - - io.add_sync_method("bitacross_getPublicKeys", move |_: Params| { - debug!("worker_api_direct rpc was called: bitacross_getPublicKeys"); - - let signer = match signing_key_repository.retrieve_key() { - Ok(pair) => pair.public().0.to_hex(), - Err(_e) => compute_hex_encoded_return_error("Can not obtain signer key"), - }; - - let bitcoin_key = match bitcoin_key_repository.retrieve_key() { - Ok(pair) => pair.public_bytes().to_hex(), - Err(_e) => compute_hex_encoded_return_error("Can not obtain bitcoin key"), - }; - - let ethereum_key = match ethereum_key_repository.retrieve_key() { - Ok(pair) => pair.public_bytes().to_hex(), - Err(_e) => compute_hex_encoded_return_error("Can not obtain ethereum key"), - }; - - let ton_key = match ton_key_repository.retrieve_key() { - Ok(pair) => pair.public().0.to_hex(), - Err(_e) => compute_hex_encoded_return_error("Can not obtain ton key"), - }; - - Ok(json!({ - "signer": signer, - "bitcoin_key": bitcoin_key, - "ethereum_key": ethereum_key, - "ton_key": ton_key - })) - }); - - io.add_sync_method("bitacross_getSealedSigners", move |_: Params| { - debug!("worker_api_direct rpc was called: bitacross_getSealedSigners"); - - let keys: Vec = signer_lookup_cloned - .get_all() - .iter() - .map(|(signer, pub_key)| { - json!({ - "signer": signer.as_ref().to_vec(), - "key": pub_key.to_vec() - }) - }) - .collect(); - Ok(json!(keys)) - }); - - io.add_sync_method("author_getShard", move |_: Params| { - debug!("worker_api_direct rpc was called: author_getShard"); - let shard = top_pool_author.list_handled_shards().first().copied().unwrap_or_default(); - let json_value = RpcReturnValue::new(shard.encode(), false, DirectRequestStatus::Ok); - Ok(json!(json_value.to_hex())) - }); - - io.add_sync_method("author_getMuRaUrl", move |_: Params| { - debug!("worker_api_direct rpc was called: author_getMuRaUrl"); - let url = match GLOBAL_PRIMITIVES_CACHE.get_mu_ra_url() { - Ok(url) => url, - Err(status) => { - let error_msg: String = format!("Could not get mu ra url due to: {}", status); - return Ok(json!(compute_hex_encoded_return_error(error_msg.as_str()))) - }, - }; - - let json_value = RpcReturnValue::new(url.encode(), false, DirectRequestStatus::Ok); - Ok(json!(json_value.to_hex())) - }); - - io.add_sync_method("author_getUntrustedUrl", move |_: Params| { - debug!("worker_api_direct rpc was called: author_getUntrustedUrl"); - let url = match GLOBAL_PRIMITIVES_CACHE.get_untrusted_worker_url() { - Ok(url) => url, - Err(status) => { - let error_msg: String = format!("Could not get untrusted url due to: {}", status); - return Ok(json!(compute_hex_encoded_return_error(error_msg.as_str()))) - }, - }; - - let json_value = RpcReturnValue::new(url.encode(), false, DirectRequestStatus::Ok); - Ok(json!(json_value.to_hex())) - }); - - io.add_sync_method("chain_subscribeAllHeads", |_: Params| { - debug!("worker_api_direct rpc was called: chain_subscribeAllHeads"); - let parsed = "world"; - Ok(Value::String(format!("hello, {}", parsed))) - }); - - io.add_sync_method("state_getMetadata", |_: Params| { - debug!("worker_api_direct rpc was called: tate_getMetadata"); - let metadata = Runtime::metadata(); - let json_value = RpcReturnValue::new(metadata.into(), false, DirectRequestStatus::Ok); - Ok(json!(json_value.to_hex())) - }); - - io.add_sync_method("state_getRuntimeVersion", |_: Params| { - debug!("worker_api_direct rpc was called: state_getRuntimeVersion"); - let parsed = "world"; - Ok(Value::String(format!("hello, {}", parsed))) - }); - - io.add_sync_method("state_executeGetter", move |params: Params| { - debug!("worker_api_direct rpc was called: state_executeGetter"); - let json_value = match execute_getter_inner(getter_executor.as_ref(), params) { - Ok(state_getter_value) => RpcReturnValue { - do_watch: false, - value: state_getter_value.encode(), - status: DirectRequestStatus::Ok, - } - .to_hex(), - Err(error) => compute_hex_encoded_return_error(error.as_str()), - }; - Ok(json!(json_value)) - }); - - io.add_sync_method("attesteer_forwardDcapQuote", move |params: Params| { - debug!("worker_api_direct rpc was called: attesteer_forwardDcapQuote"); - let json_value = match forward_dcap_quote_inner(params) { - Ok(val) => RpcReturnValue { - do_watch: false, - value: val.encode(), - status: DirectRequestStatus::Ok, - } - .to_hex(), - Err(error) => compute_hex_encoded_return_error(error.as_str()), - }; - - Ok(json!(json_value)) - }); - - io.add_sync_method("attesteer_forwardIasAttestationReport", move |params: Params| { - debug!("worker_api_direct rpc was called: attesteer_forwardIasAttestationReport"); - let json_value = match attesteer_forward_ias_attestation_report_inner(params) { - Ok(val) => RpcReturnValue { - do_watch: false, - value: val.encode(), - status: DirectRequestStatus::Ok, - } - .to_hex(), - Err(error) => compute_hex_encoded_return_error(error.as_str()), - }; - Ok(json!(json_value)) - }); - - // state_getMrenclave - io.add_sync_method("state_getMrenclave", move |_: Params| { - let json_value = match ocall_api.get_mrenclave_of_self() { - Ok(m) => RpcReturnValue { - do_watch: false, - value: m.m.encode(), - status: DirectRequestStatus::Ok, - } - .to_hex(), - Err(e) => { - let error_msg: String = format!("Could not get current mrenclave due to: {}", e); - compute_hex_encoded_return_error(error_msg.as_str()) - }, - }; - Ok(json!(json_value)) - }); - - // system_health - io.add_sync_method("system_health", |_: Params| { - debug!("worker_api_direct rpc was called: system_health"); - let parsed = "world"; - Ok(Value::String(format!("hello, {}", parsed))) - }); - - io.add_sync_method("system_name", |_: Params| { - debug!("worker_api_direct rpc was called: system_name"); - let parsed = "world"; - Ok(Value::String(format!("hello, {}", parsed))) - }); - - io.add_sync_method("system_version", |_: Params| { - debug!("worker_api_direct rpc was called: system_version"); - let parsed = "world"; - Ok(Value::String(format!("hello, {}", parsed))) - }); - - let rpc_methods_string = get_all_rpc_methods_string(&io); - io.add_sync_method("rpc_methods", move |_: Params| { - debug!("worker_api_direct rpc was called: rpc_methods"); - Ok(Value::String(rpc_methods_string.to_owned())) - }); - - io -} - -fn prepare_check_sign_bitcoin_request( - signing_key_repository: &EnclaveSigningKeyRepository, - ocall_api: &OcallApi, -) -> Result -where - OcallApi: EnclaveAttestationOCallApi + Send + Sync + 'static, -{ - let signer = signing_key_repository.retrieve_key().map_err(|_| ())?; - let identity = Identity::Substrate(signer.public().into()); - let mrenclave = ocall_api.get_mrenclave_of_self().map_err(|_| ())?.m; - let call = DirectCall::CheckSignBitcoin(identity).sign( - &KeyPair::Ed25519(Box::new(signer)), - &mrenclave, - &mrenclave.into(), - ); - Ok(PlainRequest { shard: mrenclave.into(), payload: call.encode() }) -} - -// Litentry: TODO - we still use `RsaRequest` for trusted getter, as the result -// in unencrypted, see P-183 -fn execute_getter_inner( - getter_executor: &GE, - params: Params, -) -> Result>, String> { - let hex_encoded_params = params.parse::>().map_err(|e| format!("{:?}", e))?; - - let param = &hex_encoded_params.get(0).ok_or("Could not get first param")?; - let request = RsaRequest::from_hex(param).map_err(|e| format!("{:?}", e))?; - - let shard: ShardIdentifier = request.shard; - let encoded_trusted_getter: Vec = request.payload.to_vec(); - - let getter_result = getter_executor - .execute_getter(&shard, encoded_trusted_getter) - .map_err(|e| format!("{:?}", e))?; - - Ok(getter_result) -} - -fn forward_dcap_quote_inner(params: Params) -> Result { - let hex_encoded_params = params.parse::>().map_err(|e| format!("{:?}", e))?; - - if hex_encoded_params.len() != 1 { - return Err(format!( - "Wrong number of arguments for IAS attestation report forwarding: {}, expected: {}", - hex_encoded_params.len(), - 1 - )) - } - - let param = &hex_encoded_params.get(0).ok_or("Could not get first param")?; - let encoded_quote_to_forward: Vec = - litentry_hex_utils::decode_hex(param).map_err(|e| format!("{:?}", e))?; - - let url = String::new(); - let ext = generate_dcap_ra_extrinsic_from_quote_internal( - url.as_bytes().to_vec(), - &encoded_quote_to_forward, - ) - .map_err(|e| format!("{:?}", e))?; - - let validator_access = get_validator_accessor_from_integritee_solo_or_parachain() - .map_err(|e| format!("{:?}", e))?; - validator_access - .execute_mut_on_validator(|v| v.send_extrinsics(vec![ext.clone()])) - .map_err(|e| format!("{:?}", e))?; - - Ok(ext) -} - -fn attesteer_forward_ias_attestation_report_inner( - params: Params, -) -> Result { - let hex_encoded_params = params.parse::>().map_err(|e| format!("{:?}", e))?; - - if hex_encoded_params.len() != 1 { - return Err(format!( - "Wrong number of arguments for IAS attestation report forwarding: {}, expected: {}", - hex_encoded_params.len(), - 1 - )) - } - - let param = &hex_encoded_params.get(0).ok_or("Could not get first param")?; - let ias_attestation_report = - litentry_hex_utils::decode_hex(param).map_err(|e| format!("{:?}", e))?; - - let url = String::new(); - let ext = generate_ias_ra_extrinsic_from_der_cert_internal( - url.as_bytes().to_vec(), - &ias_attestation_report, - false, - ) - .map_err(|e| format!("{:?}", e))?; - - let validator_access = get_validator_accessor_from_integritee_solo_or_parachain() - .map_err(|e| format!("{:?}", e))?; - validator_access - .execute_mut_on_validator(|v| v.send_extrinsics(vec![ext.clone()])) - .map_err(|e| format!("{:?}", e))?; - - Ok(ext) -} - -pub enum BitacrossRequestError { - DirectCallError(Vec), - Other(Vec), -} - -async fn bitacross_task_create_inner(params: Params) -> Result> { - let request = get_request_from_params(params)?; - - let bit_across_request_sender = BitAcrossRequestSender::new(); - let (sender, receiver) = oneshot::channel::>>(); - - bit_across_request_sender.send(BitAcrossRequest::Request(request, sender))?; - - // we only expect one response, hence no loop - match receiver.await { - Ok(Ok(response)) => match response { - BitAcrossProcessingResult::Ok(response_payload) => { - println!("BitAcrossProcessingResult::Ok"); - - Ok(RpcReturnValue { - do_watch: false, - value: response_payload, - status: DirectRequestStatus::Ok, - }) - }, - BitAcrossProcessingResult::Submitted(hash) => { - println!("BitAcrossProcessingResult::Submitted"); - Ok(RpcReturnValue { - do_watch: true, - value: vec![], - status: DirectRequestStatus::Processing(hash.into()), - }) - }, - }, - Ok(Err(e)) => { - error!("Error while processing request: {:?}", e); - - Err(e) - }, - Err(_) => { - println!("Got Err"); - // This case will only happen if the sender has been dropped - Err(vec![]) - }, - } -} - -fn bitacross_data_share_inner(params: Params) -> Result> { - let request = get_request_from_params(params)?; - let bit_across_request_sender = BitAcrossRequestSender::new(); - bit_across_request_sender.send(BitAcrossRequest::ShareCeremonyData(request))?; - Ok(RpcReturnValue { do_watch: false, value: vec![], status: DirectRequestStatus::Ok }) -} - -// we expect our `params` to be "by-position array" -// see https://www.jsonrpc.org/specification#parameter_structures -fn get_request_from_params(params: Params) -> Result { - let s_vec = params.parse::>().map_err(|e| format!("{}", e))?; - - let s = s_vec.get(0).ok_or_else(|| "Empty params".to_string())?; - debug!("Request payload: {}", s); - - let request = PlainRequest::from_hex(s) - .map_err(|e| format!("PlainRequest construction error: {:?}", e))?; - Ok(request) -} - -#[cfg(feature = "test")] -pub mod tests { - use super::*; - use std::string::ToString; - - pub fn test_given_io_handler_methods_then_retrieve_all_names_as_string() { - let mut io = IoHandler::new(); - let method_names: [&str; 4] = ["method1", "another_method", "fancy_thing", "solve_all"]; - - for method_name in method_names.iter() { - io.add_sync_method(method_name, |_: Params| Ok(Value::String("".to_string()))); - } - - let method_string = get_all_rpc_methods_string(&io); - - for method_name in method_names.iter() { - assert!(method_string.contains(method_name)); - } - } -} diff --git a/tee-worker/bitacross/enclave-runtime/src/shard_config.rs b/tee-worker/bitacross/enclave-runtime/src/shard_config.rs deleted file mode 100644 index 126e5c2503..0000000000 --- a/tee-worker/bitacross/enclave-runtime/src/shard_config.rs +++ /dev/null @@ -1,24 +0,0 @@ -/* - Copyright 2021 Integritee AG - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ - -use crate::error::Result as EnclaveResult; -use itp_types::ShardIdentifier; -use log::*; - -pub(crate) fn init_shard_config(_shard: ShardIdentifier) -> EnclaveResult<()> { - warn!("TODO(Litentry P-627): init_shard_config"); - Ok(()) -} diff --git a/tee-worker/bitacross/enclave-runtime/src/shard_creation_info.rs b/tee-worker/bitacross/enclave-runtime/src/shard_creation_info.rs deleted file mode 100644 index 4eef7be830..0000000000 --- a/tee-worker/bitacross/enclave-runtime/src/shard_creation_info.rs +++ /dev/null @@ -1,144 +0,0 @@ -/* - Copyright 2021 Integritee AG - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ -use crate::{ - error::{Error, Result as EnclaveResult}, - initialization::global_components::{EnclaveStf, GLOBAL_STATE_HANDLER_COMPONENT}, - shard_config, - std::string::ToString, - utils::DecodeRaw, -}; -use codec::{Decode, Encode}; -use itp_component_container::ComponentGetter; - -use itp_stf_interface::{ - parentchain_pallet::ParentchainPalletInstancesInterface, ShardCreationInfo, ShardCreationQuery, -}; -use itp_stf_state_handler::{handle_state::HandleState, query_shard_state::QueryShardState}; -use itp_types::{ - parentchain::{Header, ParentchainId}, - ShardIdentifier, -}; -use itp_utils::write_slice_and_whitespace_pad; -use log::*; -use sgx_types::sgx_status_t; -use std::slice; - -#[no_mangle] -pub unsafe extern "C" fn init_shard_creation_parentchain_header( - shard: *const u8, - shard_size: u32, - parentchain_id: *const u8, - parentchain_id_size: u32, - header: *const u8, - header_size: u32, -) -> sgx_status_t { - let shard_identifier = - ShardIdentifier::from_slice(slice::from_raw_parts(shard, shard_size as usize)); - let header = match Header::decode(&mut slice::from_raw_parts(header, header_size as usize)) { - Ok(hdr) => hdr, - Err(e) => { - error!("Could not decode header: {:?}", e); - return sgx_status_t::SGX_ERROR_UNEXPECTED - }, - }; - let parentchain_id = - match ParentchainId::decode_raw(parentchain_id, parentchain_id_size as usize) { - Ok(id) => id, - Err(e) => { - error!("Could not decode parentchain id: {:?}", e); - return sgx_status_t::SGX_ERROR_UNEXPECTED - }, - }; - - if let Err(e) = - init_shard_creation_parentchain_header_internal(shard_identifier, parentchain_id, header) - { - error!( - "Failed to initialize first relevant parentchain header [{:?}]: {:?}", - parentchain_id, e - ); - return sgx_status_t::SGX_ERROR_UNEXPECTED - } - sgx_status_t::SGX_SUCCESS -} - -fn init_shard_creation_parentchain_header_internal( - shard: ShardIdentifier, - parentchain_id: ParentchainId, - header: Header, -) -> EnclaveResult<()> { - if let Some(creation_block) = - get_shard_creation_info_internal(shard)?.for_parentchain(parentchain_id) - { - error!("first relevant parentchain header has been previously initialized to {:?}. cannot change: {:?}", creation_block.number, parentchain_id); - return Err(Error::Other( - "first relevant parentchain header has been previously initialized. cannot change" - .into(), - )) - } - debug!("initializing shard creation header: {:?}", parentchain_id); - - let state_handler = GLOBAL_STATE_HANDLER_COMPONENT.get()?; - if !state_handler - .shard_exists(&shard) - .map_err(|_| Error::Other("get shard_exists failed".into()))? - { - return Err(Error::Other("shard not initialized".into())) - }; - - let (state_lock, mut state) = state_handler.load_for_mutation(&shard)?; - EnclaveStf::set_creation_block(&mut state, header, parentchain_id) - .map_err(|e| Error::Stf(e.to_string()))?; - state_handler.write_after_mutation(state, state_lock, &shard)?; - - shard_config::init_shard_config(shard)?; - Ok(()) -} - -/// reads the shard vault account id form state if it has been initialized previously -pub(crate) fn get_shard_creation_info_internal( - shard: ShardIdentifier, -) -> EnclaveResult { - let state_handler = GLOBAL_STATE_HANDLER_COMPONENT.get()?; - let (_state_lock, mut state) = state_handler.load_for_mutation(&shard)?; - Ok(EnclaveStf::get_shard_creation_info(&mut state)) -} - -/// reads the shard vault account id form state if it has been initialized previously -#[no_mangle] -pub unsafe extern "C" fn get_shard_creation_info( - shard: *const u8, - shard_size: u32, - creation: *mut u8, - creation_size: u32, -) -> sgx_status_t { - let shard = ShardIdentifier::from_slice(slice::from_raw_parts(shard, shard_size as usize)); - - let shard_creation_info = match get_shard_creation_info_internal(shard) { - Ok(creation) => creation, - Err(e) => { - warn!("Failed to fetch creation header: {:?}", e); - return sgx_status_t::SGX_ERROR_UNEXPECTED - }, - }; - trace!("fetched shard creation header from state: {:?}", shard_creation_info); - - let creation_slice = slice::from_raw_parts_mut(creation, creation_size as usize); - if let Err(e) = write_slice_and_whitespace_pad(creation_slice, shard_creation_info.encode()) { - return Error::BufferError(e).into() - }; - sgx_status_t::SGX_SUCCESS -} diff --git a/tee-worker/bitacross/enclave-runtime/src/stf_task_handler.rs b/tee-worker/bitacross/enclave-runtime/src/stf_task_handler.rs deleted file mode 100644 index 8b13789179..0000000000 --- a/tee-worker/bitacross/enclave-runtime/src/stf_task_handler.rs +++ /dev/null @@ -1 +0,0 @@ - diff --git a/tee-worker/bitacross/enclave-runtime/src/sync.rs b/tee-worker/bitacross/enclave-runtime/src/sync.rs deleted file mode 100644 index a348134d6f..0000000000 --- a/tee-worker/bitacross/enclave-runtime/src/sync.rs +++ /dev/null @@ -1,104 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ - -//! Primitives to handle multithreaded state access in the enclave. -//! -//! Note: In general the design should try to minimize usage of these, as potential deadlocks can -//! occur. Documentation of the `SgxRwLock` says that panics __might__ occur when trying to acquire -//! a lock multiple times in the same thread. However, tests have shown that it also might result in -//! a deadlock. -//! -//! @clangenb: Does currently not see any way to entirely get rid of these synchronization -//! primitives because we can only start new threads from the untrusted side. `parking_lot` would be -//! an alternative to consider for the primitives. It has several performance and ergonomic benefits -//! over the `std` lib's. One of the benefits would be compile-time deadlock detection (experimental). -//! Unfortunately, it would need to be ported to SGX. -//! -//! `https://amanieu.github.io/parking_lot/parking_lot/index.html` - -use crate::error::{Error, Result as EnclaveResult}; -use lazy_static::lazy_static; -use std::sync::{SgxRwLock, SgxRwLockReadGuard, SgxRwLockWriteGuard}; - -lazy_static! { - pub static ref SIDECHAIN_DB_LOCK: SgxRwLock<()> = Default::default(); -} - -pub struct EnclaveLock; - -impl SidechainRwLock for EnclaveLock { - fn read_sidechain_db() -> EnclaveResult> { - SIDECHAIN_DB_LOCK.read().map_err(|e| Error::Other(e.into())) - } - - fn write_sidechain_db() -> EnclaveResult> { - SIDECHAIN_DB_LOCK.write().map_err(|e| Error::Other(e.into())) - } -} - -pub trait SidechainRwLock { - fn read_sidechain_db() -> EnclaveResult>; - fn write_sidechain_db() -> EnclaveResult>; -} - -// simple type defs to prevent too long names -type AggregatedReadGuards<'a> = SgxRwLockReadGuard<'a, ()>; -type AggregatedWriteGuards<'a> = SgxRwLockWriteGuard<'a, ()>; - -/// Useful, if all state must be accessed. Reduces the number of lines. -pub trait EnclaveStateRWLock: SidechainRwLock { - /// return read locks of all enclave states - fn read_all() -> EnclaveResult>; - - /// return write locks of all enclave states - fn write_all() -> EnclaveResult>; -} - -impl EnclaveStateRWLock for T { - fn read_all() -> EnclaveResult> { - Self::read_sidechain_db() - } - - fn write_all() -> EnclaveResult> { - Self::write_sidechain_db() - } -} - -#[cfg(feature = "test")] -pub mod tests { - use super::*; - pub fn sidechain_rw_lock_works() { - drop(EnclaveLock::read_sidechain_db().unwrap()); - drop(EnclaveLock::write_sidechain_db().unwrap()); - - let x1 = EnclaveLock::read_sidechain_db().unwrap(); - let x2 = EnclaveLock::read_sidechain_db().unwrap(); - - drop((x1, x2)); - drop(EnclaveLock::write_sidechain_db().unwrap()) - } - - pub fn enclave_rw_lock_works() { - drop(EnclaveLock::read_all().unwrap()); - drop(EnclaveLock::write_all().unwrap()); - - let x1 = EnclaveLock::read_all().unwrap(); - let x2 = EnclaveLock::read_all().unwrap(); - - drop((x1, x2)); - drop(EnclaveLock::write_all().unwrap()) - } -} diff --git a/tee-worker/bitacross/enclave-runtime/src/test/Counter.sol b/tee-worker/bitacross/enclave-runtime/src/test/Counter.sol deleted file mode 100644 index ce3cce3259..0000000000 --- a/tee-worker/bitacross/enclave-runtime/src/test/Counter.sol +++ /dev/null @@ -1,31 +0,0 @@ -pragma solidity >=0.8.0; - -contract Counter { - uint256 private value; - address private last_caller; - - constructor() { - value = 1; - last_caller = msg.sender; - } - - fallback() external payable { value = 5; } - - function inc() public { - value += 1; - last_caller = msg.sender; - } - - function add(uint delta) public { - value += delta; - last_caller = msg.sender; - } - - function get_value() view public returns (uint) { - return value; - } - - function get_last_caller() view public returns (address) { - return last_caller; - } -} \ No newline at end of file diff --git a/tee-worker/bitacross/enclave-runtime/src/test/cert_tests.rs b/tee-worker/bitacross/enclave-runtime/src/test/cert_tests.rs deleted file mode 100644 index ad3b78df76..0000000000 --- a/tee-worker/bitacross/enclave-runtime/src/test/cert_tests.rs +++ /dev/null @@ -1,72 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - Copyright (C) 2017-2019 Baidu, Inc. All Rights Reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ -use crate::test::mocks::attestation_ocall_mock::AttestationOCallMock; -use hex::FromHexError; -use itp_attestation_handler::cert::{verify_attn_report, verify_mra_cert}; -use sgx_types::{sgx_measurement_t, sgx_status_t, SGX_HASH_SIZE}; -use std::vec::Vec; - -// Test data and tests are mostly copied from: -// https://github.com/integritee-network/pallet-teerex/blob/master/ias-verify/ - -const TEST4_CERT: &[u8] = include_bytes!("fixtures/ra_dump_cert_TEST4.der"); - -const TEST4_MRENCLAVE: &str = "7a3454ec8f42e265cb5be7dfd111e1d95ac6076ed82a0948b2e2a45cf17b62a0"; - -#[allow(clippy::octal_escapes)] -const CERT_WRONG_PLATFORM_BLOB: &[u8] = b"0\x82\x0c\x8c0\x82\x0c2\xa0\x03\x02\x01\x02\x02\x01\x010\n\x06\x08*\x86H\xce=\x04\x03\x020\x121\x100\x0e\x06\x03U\x04\x03\x0c\x07MesaTEE0\x1e\x17\r190617124609Z\x17\r190915124609Z0\x121\x100\x0e\x06\x03U\x04\x03\x0c\x07MesaTEE0Y0\x13\x06\x07*\x86H\xce=\x02\x01\x06\x08*\x86H\xce=\x03\x01\x07\x03B\0\x04RT\x16\x16 \xef_\xd8\xe7\xc3\xb7\x03\x1d\xd6:\x1fF\xe3\xf2b!\xa9/\x8b\xd4\x82\x8f\xd1\xff[\x9c\x97\xbc\xf27\xb8,L\x8a\x01\xb0r;;\xa9\x83\xdc\x86\x9f\x1d%y\xf4;I\xe4Y\xc80'$K[\xd6\xa3\x82\x0bw0\x82\x0bs0\x82\x0bo\x06\t`\x86H\x01\x86\xf8B\x01\r\x04\x82\x0b`{\"id\":\"117077750682263877593646412006783680848\",\"timestamp\":\"2019-06-17T12:46:04.002066\",\"version\":3,\"isvEnclaveQuoteStatus\":\"GROUP_OUT_OF_DATE\",\"platformInfoBlob\":\"1602006504000900000909020401800000000000000000000008000009000000020000000000000B401A355B313FC939B4F48A54349C914A32A3AE2C4871BFABF22E960C55635869FC66293A3D9B2D58ED96CA620B65D669A444C80291314EF691E896F664317CF80C\",\"isvEnclaveQuoteBody\":\"AgAAAEALAAAIAAcAAAAAAOE6wgoHKsZsnVWSrsWX9kky0kWt9K4xcan0fQ996Ct+CAj//wGAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABwAAAAAAAAAHAAAAAAAAAFJJYIbPVot9NzRCjW2z9+k+9K8BsHQKzVMEHOR14hNbAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACD1xnnferKFHD2uvYqTXdDA8iZ22kCD5xw7h38CMfOngAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABSVBYWIO9f2OfDtwMd1jofRuPyYiGpL4vUgo/R/1ucl7zyN7gsTIoBsHI7O6mD3IafHSV59DtJ5FnIMCckS1vW\"}|EbPFH/ThUaS/dMZoDKC5EgmdUXUORFtQzF49Umi1P55oeESreJaUvmA0sg/ATSTn5t2e+e6ZoBQIUbLHjcWLMLzK4pJJUeHhok7EfVgoQ378i+eGR9v7ICNDGX7a1rroOe0s1OKxwo/0hid2KWvtAUBvf1BDkqlHy025IOiXWhXFLkb/qQwUZDWzrV4dooMfX5hfqJPi1q9s18SsdLPmhrGBheh9keazeCR9hiLhRO9TbnVgR9zJk43SPXW+pHkbNigW+2STpVAi5ugWaSwBOdK11ZjaEU1paVIpxQnlW1D6dj1Zc3LibMH+ly9ZGrbYtuJks4eRnjPhroPXxlJWpQ==|MIIEoTCCAwmgAwIBAgIJANEHdl0yo7CWMA0GCSqGSIb3DQEBCwUAMH4xCzAJBgNVBAYTAlVTMQswCQYDVQQIDAJDQTEUMBIGA1UEBwwLU2FudGEgQ2xhcmExGjAYBgNVBAoMEUludGVsIENvcnBvcmF0aW9uMTAwLgYDVQQDDCdJbnRlbCBTR1ggQXR0ZXN0YXRpb24gUmVwb3J0IFNpZ25pbmcgQ0EwHhcNMTYxMTIyMDkzNjU4WhcNMjYxMTIwMDkzNjU4WjB7MQswCQYDVQQGEwJVUzELMAkGA1UECAwCQ0ExFDASBgNVBAcMC1NhbnRhIENsYXJhMRowGAYDVQQKDBFJbnRlbCBDb3Jwb3JhdGlvbjEtMCsGA1UEAwwkSW50ZWwgU0dYIEF0dGVzdGF0aW9uIFJlcG9ydCBTaWduaW5nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqXot4OZuphR8nudFrAFiaGxxkgma/Es/BA+tbeCTUR106AL1ENcWA4FX3K+E9BBL0/7X5rj5nIgX/R/1ubhkKWw9gfqPG3KeAtIdcv/uTO1yXv50vqaPvE1CRChvzdS/ZEBqQ5oVvLTPZ3VEicQjlytKgN9cLnxbwtuvLUK7eyRPfJW/ksddOzP8VBBniolYnRCD2jrMRZ8nBM2ZWYwnXnwYeOAHV+W9tOhAImwRwKF/95yAsVwd21ryHMJBcGH70qLagZ7Ttyt++qO/6+KAXJuKwZqjRlEtSEz8gZQeFfVYgcwSfo96oSMAzVr7V0L6HSDLRnpb6xxmbPdqNol4tQIDAQABo4GkMIGhMB8GA1UdIwQYMBaAFHhDe3amfrzQr35CN+s1fDuHAVE8MA4GA1UdDwEB/wQEAwIGwDAMBgNVHRMBAf8EAjAAMGAGA1UdHwRZMFcwVaBToFGGT2h0dHA6Ly90cnVzdGVkc2VydmljZXMuaW50ZWwuY29tL2NvbnRlbnQvQ1JML1NHWC9BdHRlc3RhdGlvblJlcG9ydFNpZ25pbmdDQS5jcmwwDQYJKoZIhvcNAQELBQADggGBAGcIthtcK9IVRz4rRq+ZKE+7k50/OxUsmW8aavOzKb0iCx07YQ9rzi5nU73tME2yGRLzhSViFs/LpFa9lpQL6JL1aQwmDR74TxYGBAIi5f4I5TJoCCEqRHz91kpG6Uvyn2tLmnIdJbPE4vYvWLrtXXfFBSSPD4Afn7+3/XUggAlc7oCTizOfbbtOFlYA4g5KcYgS1J2ZAeMQqbUdZseZCcaZZZn65tdqee8UXZlDvx0+NdO0LR+5pFy+juM0wWbu59MvzcmTXbjsi7HY6zd53Yq5K244fwFHRQ8eOB0IWB+4PfM7FeAApZvlfqlKOlLcZL2uyVmzRkyR5yW72uo9mehX44CiPJ2fse9Y6eQtcfEhMPkmHXI01sN+KwPbpA39+xOsStjhP9N1Y1a2tQAVo+yVgLgV2Hws73Fc0o3wC78qPEA+v2aRs/Be3ZFDgDyghc/1fgU+7C+P6kbqd4poyb6IW8KCJbxfMJvkordNOgOUUxndPHEi/tb/U7uLjLOgPA==0\n\x06\x08*\x86H\xce=\x04\x03\x02\x03H\00E\x02!\0\xae6\x06\t@Sy\x8f\x8ec\x9d\xdci^Ex*\x92}\xdcG\x15A\x97\xd7\xd7\xd1\xccx\xe0\x1e\x08\x02 \x15Q\xa0BT\xde'~\xec\xbd\x027\xd3\xd8\x83\xf7\xe6Z\xc5H\xb4D\xf7\xe2\r\xa7\xe4^f\x10\x85p"; - -pub fn test_verify_mra_cert_should_work() { - let mr_enclave = get_mr_enclave_from_hex_string(TEST4_MRENCLAVE).unwrap(); - let attestation_ocall = - AttestationOCallMock::create_with_mr_enclave(sgx_measurement_t { m: mr_enclave }); - let result = verify_mra_cert(TEST4_CERT, false, false, &attestation_ocall); - - assert!(result.is_ok()); -} - -pub fn test_verify_wrong_cert_is_err() { - let mr_enclave = get_mr_enclave_from_hex_string(TEST4_MRENCLAVE).unwrap(); - let attestation_ocall = - AttestationOCallMock::create_with_mr_enclave(sgx_measurement_t { m: mr_enclave }); - let result = verify_mra_cert(CERT_WRONG_PLATFORM_BLOB, false, false, &attestation_ocall); - - assert!(result.is_err()); - assert_eq!(result.unwrap_err(), sgx_status_t::SGX_ERROR_UNEXPECTED); -} - -pub fn test_given_wrong_platform_info_when_verifying_attestation_report_then_return_error() { - let attestation_ocall = AttestationOCallMock::new(); - let result = verify_attn_report(CERT_WRONG_PLATFORM_BLOB, Vec::new(), &attestation_ocall); - - assert!(result.is_err()); - assert_eq!(result.unwrap_err(), sgx_status_t::SGX_ERROR_UNEXPECTED); -} - -fn get_mr_enclave_from_hex_string(input_str: &str) -> Result<[u8; SGX_HASH_SIZE], FromHexError> { - let decoded_str = hex::decode(input_str)?; - - if decoded_str.len() != SGX_HASH_SIZE { - return Err(FromHexError::InvalidStringLength) - } - - let mut mr_enclave = [0u8; SGX_HASH_SIZE]; - mr_enclave.clone_from_slice(decoded_str.as_slice()); - - Ok(mr_enclave) -} diff --git a/tee-worker/bitacross/enclave-runtime/src/test/direct_rpc_tests.rs b/tee-worker/bitacross/enclave-runtime/src/test/direct_rpc_tests.rs deleted file mode 100644 index 122da0484b..0000000000 --- a/tee-worker/bitacross/enclave-runtime/src/test/direct_rpc_tests.rs +++ /dev/null @@ -1,176 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - Copyright (C) 2017-2019 Baidu, Inc. All Rights Reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use crate::{ - initialization::global_components::{ - GLOBAL_BITCOIN_KEY_REPOSITORY_COMPONENT, GLOBAL_ETHEREUM_KEY_REPOSITORY_COMPONENT, - GLOBAL_SIGNING_KEY_REPOSITORY_COMPONENT, GLOBAL_TON_KEY_REPOSITORY_COMPONENT, - }, - rpc::worker_api_direct::public_api_rpc_handler, - test::{ - fixtures::components::create_ocall_api, - mocks::types::{TestOCallApi, TestSigner}, - }, - Hash, -}; -use bc_signer_registry::{PubKey, SignerRegistryLookup}; -use codec::{Decode, Encode}; -use ita_stf::{Getter, PublicGetter}; -use itc_direct_rpc_server::{ - create_determine_watch, rpc_connection_registry::ConnectionRegistry, - rpc_ws_handler::RpcWsHandler, -}; -use itc_parentchain_test::ParentchainHeaderBuilder; -use itc_tls_websocket_server::{ConnectionToken, WebSocketMessageHandler}; -use itp_component_container::ComponentGetter; -use itp_rpc::{Id, RpcRequest, RpcReturnValue}; -use itp_sgx_crypto::get_rsa3072_repository; -use itp_sgx_temp_dir::TempDir; -use itp_stf_executor::{getter_executor::GetterExecutor, mocks::GetStateMock}; -use itp_stf_state_observer::mock::ObserveStateMock; -use itp_top_pool_author::mocks::AuthorApiMock; -use itp_types::{DirectRequestStatus, RsaRequest, ShardIdentifier}; -use itp_utils::{FromHexPrefixed, ToHexPrefixed}; -use litentry_primitives::{Address32, Identity}; -use sp_core::Pair; -use std::{string::ToString, sync::Arc, vec::Vec}; - -struct SignerRegistryMock {} - -impl SignerRegistryLookup for SignerRegistryMock { - fn contains_key(&self, _account: &Address32) -> bool { - true - } - fn get_all(&self) -> Vec<(Address32, PubKey)> { - vec![] - } -} - -pub fn state_get_mrenclave_works() { - type TestState = u64; - - let temp_dir = TempDir::with_prefix("get_state_request_works").unwrap(); - - let connection_registry = Arc::new(ConnectionRegistry::::new()); - let watch_extractor = Arc::new(create_determine_watch::()); - let rsa_repository = get_rsa3072_repository(temp_dir.path().to_path_buf()).unwrap(); - - let mr_enclave = [1; 32]; - - let ocall_api = TestOCallApi::default().with_mr_enclave(mr_enclave.clone()); - - let state: TestState = 78234u64; - let state_observer = Arc::new(ObserveStateMock::::new(state)); - let getter_executor = - Arc::new(GetterExecutor::<_, GetStateMock, Getter>::new(state_observer)); - let top_pool_author = Arc::new(AuthorApiMock::default()); - let signer_lookup = Arc::new(SignerRegistryMock {}); - - let io_handler = public_api_rpc_handler( - top_pool_author, - getter_executor, - Arc::new(rsa_repository), - ocall_api.into(), - GLOBAL_SIGNING_KEY_REPOSITORY_COMPONENT.get().unwrap(), - GLOBAL_BITCOIN_KEY_REPOSITORY_COMPONENT.get().unwrap(), - GLOBAL_ETHEREUM_KEY_REPOSITORY_COMPONENT.get().unwrap(), - GLOBAL_TON_KEY_REPOSITORY_COMPONENT.get().unwrap(), - signer_lookup, - ); - let rpc_handler = Arc::new(RpcWsHandler::new(io_handler, watch_extractor, connection_registry)); - - let request_string = RpcRequest::compose_jsonrpc_call( - Id::Text("1".to_string()), - "state_getMrenclave".to_string(), - vec![], - ) - .unwrap(); - - let response_string = - rpc_handler.handle_message(ConnectionToken(1), request_string).unwrap().unwrap(); - - assert!(!response_string.is_empty()); - - const EXPECTED_HEX_RETURN_VALUE: &str = - "0x8001010101010101010101010101010101010101010101010101010101010101010000"; - assert!(response_string.contains(EXPECTED_HEX_RETURN_VALUE)); - let rpc_return_value = RpcReturnValue::from_hex(EXPECTED_HEX_RETURN_VALUE).unwrap(); - assert_eq!(rpc_return_value.status, DirectRequestStatus::Ok); - let decoded_value: [u8; 32] = Decode::decode(&mut rpc_return_value.value.as_slice()).unwrap(); - assert_eq!(decoded_value, mr_enclave); -} - -pub fn get_state_request_works() { - type TestState = u64; - - let temp_dir = TempDir::with_prefix("get_state_request_works").unwrap(); - - let connection_registry = Arc::new(ConnectionRegistry::::new()); - let watch_extractor = Arc::new(create_determine_watch::()); - let rsa_repository = get_rsa3072_repository(temp_dir.path().to_path_buf()).unwrap(); - - let signer = TestSigner::from_seed(b"42315678901234567890123456789012"); - let header = ParentchainHeaderBuilder::default().build(); - - let ocall_api = create_ocall_api(&header, &signer); - - let state: TestState = 78234u64; - let state_observer = Arc::new(ObserveStateMock::::new(state)); - let getter_executor = - Arc::new(GetterExecutor::<_, GetStateMock, Getter>::new(state_observer)); - let top_pool_author = Arc::new(AuthorApiMock::default()); - let signer_lookup = Arc::new(SignerRegistryMock {}); - - let io_handler = public_api_rpc_handler( - top_pool_author, - getter_executor, - Arc::new(rsa_repository), - ocall_api, - GLOBAL_SIGNING_KEY_REPOSITORY_COMPONENT.get().unwrap(), - GLOBAL_BITCOIN_KEY_REPOSITORY_COMPONENT.get().unwrap(), - GLOBAL_ETHEREUM_KEY_REPOSITORY_COMPONENT.get().unwrap(), - GLOBAL_TON_KEY_REPOSITORY_COMPONENT.get().unwrap(), - signer_lookup, - ); - let rpc_handler = Arc::new(RpcWsHandler::new(io_handler, watch_extractor, connection_registry)); - - let getter = - Getter::public(PublicGetter::nonce(Identity::Substrate(Address32::from([0u8; 32])))); - - let request = RsaRequest::new(ShardIdentifier::default(), getter.encode()); - - let request_string = RpcRequest::compose_jsonrpc_call( - Id::Text("1".to_string()), - "state_executeGetter".to_string(), - vec![request.to_hex()], - ) - .unwrap(); - - let response_string = - rpc_handler.handle_message(ConnectionToken(1), request_string).unwrap().unwrap(); - - assert!(!response_string.is_empty()); - - const EXPECTED_HEX_RETURN_VALUE: &str = "0x2801209a310100000000000000"; - assert!(response_string.contains(EXPECTED_HEX_RETURN_VALUE)); - let rpc_return_value = RpcReturnValue::from_hex(EXPECTED_HEX_RETURN_VALUE).unwrap(); - assert_eq!(rpc_return_value.status, DirectRequestStatus::Ok); - let decoded_value: Option> = - Option::decode(&mut rpc_return_value.value.as_slice()).unwrap(); - assert_eq!(decoded_value, Some(state.encode())); -} diff --git a/tee-worker/bitacross/enclave-runtime/src/test/enclave_signer_tests.rs b/tee-worker/bitacross/enclave-runtime/src/test/enclave_signer_tests.rs deleted file mode 100644 index b76af97d4a..0000000000 --- a/tee-worker/bitacross/enclave-runtime/src/test/enclave_signer_tests.rs +++ /dev/null @@ -1,172 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ -use codec::Encode; -use ita_sgx_runtime::Runtime; -use ita_stf::{Getter, Stf, TrustedCall, TrustedCallSigned}; -use itp_node_api::metadata::{metadata_mocks::NodeMetadataMock, provider::NodeMetadataRepository}; -use itp_ocall_api::EnclaveAttestationOCallApi; -use itp_sgx_crypto::{ - ed25519_derivation::DeriveEd25519, key_repository::AccessKey, mocks::KeyRepositoryMock, -}; -use itp_sgx_externalities::SgxExternalities; -use itp_stf_executor::{enclave_signer::StfEnclaveSigner, traits::StfEnclaveSigning}; -use itp_stf_interface::{ - mocks::GetterExecutorMock, system_pallet::SystemPalletAccountInterface, InitState, - StateCallInterface, -}; -use itp_stf_primitives::{ - traits::TrustedCallVerification, - types::{AccountId, ShardIdentifier, TrustedOperation}, -}; -use itp_stf_state_observer::mock::ObserveStateMock; -use itp_test::mock::onchain_mock::OnchainMock; -use itp_top_pool_author::{mocks::AuthorApiMock, traits::AuthorApi}; -use itp_types::{parentchain::ParentchainId, RsaRequest}; -use litentry_primitives::Identity; -use sgx_crypto_helper::{rsa3072::Rsa3072KeyPair, RsaKeyPair}; -use sp_core::Pair; -use std::{sync::Arc, vec::Vec}; - -type ShieldingKeyRepositoryMock = KeyRepositoryMock; -type TestStf = Stf; - -pub fn derive_key_is_deterministic() { - let rsa_key = Rsa3072KeyPair::new().unwrap(); - - let first_ed_key = rsa_key.derive_ed25519().unwrap(); - let second_ed_key = rsa_key.derive_ed25519().unwrap(); - assert_eq!(first_ed_key.public(), second_ed_key.public()); -} - -pub fn enclave_signer_signatures_are_valid() { - let top_pool_author = Arc::new(AuthorApiMock::default()); - let ocall_api = Arc::new(OnchainMock::default()); - let shielding_key_repo = Arc::new(ShieldingKeyRepositoryMock::default()); - let enclave_account: AccountId = shielding_key_repo - .retrieve_key() - .unwrap() - .derive_ed25519() - .unwrap() - .public() - .into(); - - let state_observer: Arc> = - Arc::new(ObserveStateMock::new(TestStf::init_state(enclave_account.clone()))); - let shard = ShardIdentifier::default(); - let mr_enclave = ocall_api.get_mrenclave_of_self().unwrap(); - let enclave_signer = StfEnclaveSigner::<_, _, _, TestStf, _, TrustedCallSigned, Getter>::new( - state_observer, - ocall_api, - shielding_key_repo, - top_pool_author, - ); - let trusted_call = TrustedCall::balance_shield( - Identity::Substrate(enclave_account.into()), - AccountId::new([3u8; 32]), - 200u128, - ParentchainId::Litentry, - ); - - let trusted_call_signed = enclave_signer.sign_call_with_self(&trusted_call, &shard).unwrap(); - assert!(trusted_call_signed.verify_signature(&mr_enclave.m, &shard)); -} - -pub fn nonce_is_computed_correctly() { - let top_pool_author = Arc::new(AuthorApiMock::default()); - let ocall_api = Arc::new(OnchainMock::default()); - let shielding_key_repo = Arc::new(ShieldingKeyRepositoryMock::default()); - let enclave_account: AccountId = shielding_key_repo - .retrieve_key() - .unwrap() - .derive_ed25519() - .unwrap() - .public() - .into(); - let mut state = TestStf::init_state(enclave_account.clone()); - // only used to create the enclave signer, the state is **not** synchronised - let state_observer: Arc> = - Arc::new(ObserveStateMock::new(state.clone())); - let shard = ShardIdentifier::default(); - let enclave_signer = StfEnclaveSigner::<_, _, _, TestStf, _, TrustedCallSigned, Getter>::new( - state_observer, - ocall_api, - shielding_key_repo, - top_pool_author.clone(), - ); - assert_eq!(enclave_account, enclave_signer.get_enclave_account().unwrap()); - - // create the first trusted_call and submit it - let trusted_call_1 = TrustedCall::balance_shield( - Identity::Substrate(enclave_account.clone().into()), - AccountId::new([1u8; 32]), - 100u128, - ParentchainId::Litentry, - ); - let trusted_call_1_signed = - enclave_signer.sign_call_with_self(&trusted_call_1, &shard).unwrap(); - top_pool_author.submit_top(RsaRequest::new( - shard, - TrustedOperation::::indirect_call(trusted_call_1_signed.clone()) - .encode(), - )); - assert_eq!(1, top_pool_author.get_pending_trusted_calls_for(shard, &enclave_account).len()); - // create the second trusted_call and submit it - let trusted_call_2 = TrustedCall::balance_shield( - Identity::Substrate(enclave_account.clone().into()), - AccountId::new([2u8; 32]), - 200u128, - ParentchainId::Litentry, - ); - let trusted_call_2_signed = - enclave_signer.sign_call_with_self(&trusted_call_2, &shard).unwrap(); - top_pool_author.submit_top(RsaRequest::new( - shard, - TrustedOperation::::indirect_call(trusted_call_2_signed.clone()) - .encode(), - )); - assert_eq!(2, top_pool_author.get_pending_trusted_calls_for(shard, &enclave_account).len()); - // there should be no pending trusted calls for non-enclave-account - assert_eq!( - 0, - top_pool_author - .get_pending_trusted_calls_for(shard, &AccountId::new([1u8; 32])) - .len() - ); - - assert_eq!(0, TestStf::get_account_nonce(&mut state, &enclave_account)); - let repo = Arc::new(NodeMetadataRepository::new(NodeMetadataMock::new())); - assert!(TestStf::execute_call( - &mut state, - &shard, - trusted_call_1_signed, - Default::default(), - &mut Vec::new(), - repo.clone(), - ) - .is_ok()); - - assert!(TestStf::execute_call( - &mut state, - &shard, - trusted_call_2_signed, - Default::default(), - &mut Vec::new(), - repo, - ) - .is_ok()); - assert_eq!(2, TestStf::get_account_nonce(&mut state, &enclave_account)); -} diff --git a/tee-worker/bitacross/enclave-runtime/src/test/fixtures/components.rs b/tee-worker/bitacross/enclave-runtime/src/test/fixtures/components.rs deleted file mode 100644 index 34f3606010..0000000000 --- a/tee-worker/bitacross/enclave-runtime/src/test/fixtures/components.rs +++ /dev/null @@ -1,63 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - Copyright (C) 2017-2019 Baidu, Inc. All Rights Reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use crate::test::mocks::types::{TestOCallApi, TestRpcResponder, TestSigner, TestTopPool}; -use codec::Encode; -use ita_stf::{Getter, TrustedCall, TrustedCallSigned}; -use itp_ocall_api::EnclaveAttestationOCallApi; -use itp_sgx_crypto::ShieldingCryptoEncrypt; -use itp_stf_primitives::{ - traits::TrustedCallSigning, - types::{KeyPair, TrustedOperation}, -}; -use itp_top_pool::pool::Options as PoolOptions; -use itp_top_pool_author::api::SidechainApi; -use itp_types::{Block as ParentchainBlock, ShardIdentifier}; -use sp_core::{ed25519, Pair, H256}; -use sp_runtime::traits::Header as HeaderTrait; -use std::{boxed::Box, sync::Arc, vec::Vec}; -pub(crate) fn create_top_pool() -> Arc { - let rpc_responder = Arc::new(TestRpcResponder::new()); - let sidechain_api = Arc::new(SidechainApi::::new()); - Arc::new(TestTopPool::create(PoolOptions::default(), sidechain_api, rpc_responder)) -} - -pub(crate) fn create_ocall_api>( - header: &Header, - signer: &TestSigner, -) -> Arc { - Arc::new(TestOCallApi::default().add_validateer_set(header, Some(vec![signer.public().into()]))) -} - -pub(crate) fn encrypt_trusted_operation( - shielding_key: &ShieldingKey, - trusted_operation: &TrustedOperation, -) -> Vec { - let encoded_operation = trusted_operation.encode(); - shielding_key.encrypt(encoded_operation.as_slice()).unwrap() -} - -pub(crate) fn sign_trusted_call( - trusted_call: &TrustedCall, - attestation_api: &AttestationApi, - shard_id: &ShardIdentifier, - from: ed25519::Pair, -) -> TrustedCallSigned { - let mr_enclave = attestation_api.get_mrenclave_of_self().unwrap(); - trusted_call.sign(&KeyPair::Ed25519(Box::new(from)), 0, &mr_enclave.m, shard_id) -} diff --git a/tee-worker/bitacross/enclave-runtime/src/test/fixtures/initialize_test_state.rs b/tee-worker/bitacross/enclave-runtime/src/test/fixtures/initialize_test_state.rs deleted file mode 100644 index 41cba705b5..0000000000 --- a/tee-worker/bitacross/enclave-runtime/src/test/fixtures/initialize_test_state.rs +++ /dev/null @@ -1,43 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - Copyright (C) 2017-2019 Baidu, Inc. All Rights Reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use super::test_setup::TestStf; -use ita_stf::State; -use itp_sgx_externalities::{SgxExternalities, SgxExternalitiesTrait}; -use itp_stf_interface::InitState; -use itp_stf_primitives::types::AccountId; -use itp_stf_state_handler::handle_state::HandleState; -use itp_types::ShardIdentifier; - -/// Returns an empty `State` with the corresponding `ShardIdentifier`. -pub fn init_state>( - state_handler: &S, - enclave_account: AccountId, -) -> (State, ShardIdentifier) { - let shard = ShardIdentifier::default(); - - let _hash = state_handler.initialize_shard(shard).unwrap(); - let (lock, _) = state_handler.load_for_mutation(&shard).unwrap(); - let mut state = TestStf::init_state(enclave_account); - - state.prune_state_diff(); - - state_handler.write_after_mutation(state.clone(), lock, &shard).unwrap(); - - (state, shard) -} diff --git a/tee-worker/bitacross/enclave-runtime/src/test/fixtures/mod.rs b/tee-worker/bitacross/enclave-runtime/src/test/fixtures/mod.rs deleted file mode 100644 index bc01106db1..0000000000 --- a/tee-worker/bitacross/enclave-runtime/src/test/fixtures/mod.rs +++ /dev/null @@ -1,21 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - Copyright (C) 2017-2019 Baidu, Inc. All Rights Reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -pub mod components; -pub mod initialize_test_state; -pub mod test_setup; diff --git a/tee-worker/bitacross/enclave-runtime/src/test/fixtures/ra_dump_cert_TEST4.der b/tee-worker/bitacross/enclave-runtime/src/test/fixtures/ra_dump_cert_TEST4.der deleted file mode 100644 index 2e775236d6..0000000000 Binary files a/tee-worker/bitacross/enclave-runtime/src/test/fixtures/ra_dump_cert_TEST4.der and /dev/null differ diff --git a/tee-worker/bitacross/enclave-runtime/src/test/fixtures/test_ra_signer_attn_MRSIGNER1_MRENCLAVE1.bin b/tee-worker/bitacross/enclave-runtime/src/test/fixtures/test_ra_signer_attn_MRSIGNER1_MRENCLAVE1.bin deleted file mode 100644 index d7149d37d5..0000000000 Binary files a/tee-worker/bitacross/enclave-runtime/src/test/fixtures/test_ra_signer_attn_MRSIGNER1_MRENCLAVE1.bin and /dev/null differ diff --git a/tee-worker/bitacross/enclave-runtime/src/test/fixtures/test_setup.rs b/tee-worker/bitacross/enclave-runtime/src/test/fixtures/test_setup.rs deleted file mode 100644 index b9a357eab5..0000000000 --- a/tee-worker/bitacross/enclave-runtime/src/test/fixtures/test_setup.rs +++ /dev/null @@ -1,116 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ - -use crate::{ - ocall::OcallApi, - test::{ - fixtures::initialize_test_state::init_state, mocks::rpc_responder_mock::RpcResponderMock, - }, -}; -use ita_sgx_runtime::Runtime; -use ita_stf::{Getter, State, Stf, TrustedCallSigned}; -use itp_node_api::metadata::{metadata_mocks::NodeMetadataMock, provider::NodeMetadataRepository}; -use itp_ocall_api::EnclaveAttestationOCallApi; -use itp_sgx_crypto::{ed25519_derivation::DeriveEd25519, mocks::KeyRepositoryMock}; -use itp_sgx_externalities::SgxExternalities; -use itp_stf_executor::executor::StfExecutor; -use itp_stf_primitives::types::{ShardIdentifier, TrustedOperation}; -use itp_test::mock::{ - handle_state_mock::HandleStateMock, shielding_crypto_mock::ShieldingCryptoMock, -}; -use itp_top_pool::{basic_pool::BasicPool, pool::ExtrinsicHash}; -use itp_top_pool_author::{api::SidechainApi, author::Author, top_filter::AllowAllTopsFilter}; -use itp_types::{Block, MrEnclave}; -use sp_core::{crypto::Pair, ed25519 as spEd25519}; -use std::sync::Arc; -pub type TestRpcResponder = RpcResponderMock>>; -pub type TestTopPool = BasicPool< - SidechainApi, - Block, - TestRpcResponder, - TrustedOperation, ->; -pub type TestShieldingKeyRepo = KeyRepositoryMock; -pub type TestTopPoolAuthor = Author< - TestTopPool, - AllowAllTopsFilter, - HandleStateMock, - TestShieldingKeyRepo, - TrustedCallSigned, - Getter, ->; -pub type TestStf = Stf; - -pub type TestStfExecutor = StfExecutor< - OcallApi, - HandleStateMock, - NodeMetadataRepository, - TestStf, - TrustedCallSigned, - Getter, ->; - -/// Returns all the things that are commonly used in tests and runs -/// `ensure_no_empty_shard_directory_exists` -pub fn test_setup() -> ( - Arc, - State, - ShardIdentifier, - MrEnclave, - ShieldingCryptoMock, - Arc, - Arc, -) { - let shielding_key = ShieldingCryptoMock::default(); - let shielding_key_repo = Arc::new(KeyRepositoryMock::new(shielding_key.clone())); - - let state_handler = Arc::new(HandleStateMock::default()); - let (state, shard) = - init_state(state_handler.as_ref(), enclave_call_signer(&shielding_key).public().into()); - let top_pool = test_top_pool(); - let mrenclave = OcallApi.get_mrenclave_of_self().unwrap().m; - - let node_metadata_repo = Arc::new(NodeMetadataRepository::new(NodeMetadataMock::new())); - let stf_executor = Arc::new(TestStfExecutor::new( - Arc::new(OcallApi), - state_handler.clone(), - node_metadata_repo, - )); - - ( - Arc::new(TestTopPoolAuthor::new( - Arc::new(top_pool), - AllowAllTopsFilter::::new(), - state_handler.clone(), - shielding_key_repo, - )), - state, - shard, - mrenclave, - shielding_key, - state_handler, - stf_executor, - ) -} - -pub fn test_top_pool() -> TestTopPool { - let chain_api = Arc::new(SidechainApi::::new()); - BasicPool::create(Default::default(), chain_api, Arc::new(TestRpcResponder::new())) -} - -pub fn enclave_call_signer(key_source: &Source) -> spEd25519::Pair { - key_source.derive_ed25519().unwrap() -} diff --git a/tee-worker/bitacross/enclave-runtime/src/test/ipfs_tests.rs b/tee-worker/bitacross/enclave-runtime/src/test/ipfs_tests.rs deleted file mode 100644 index f1f94d3696..0000000000 --- a/tee-worker/bitacross/enclave-runtime/src/test/ipfs_tests.rs +++ /dev/null @@ -1,42 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - Copyright (C) 2017-2019 Baidu, Inc. All Rights Reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use crate::{ipfs::IpfsContent, ocall::OcallApi}; -use itp_ocall_api::EnclaveIpfsOCallApi; -use log::*; -use std::{fs::File, io::Read, vec::Vec}; - -#[allow(unused)] -fn test_ocall_read_write_ipfs() { - info!("testing IPFS read/write. Hopefully ipfs daemon is running..."); - let enc_state: Vec = vec![20; 4 * 512 * 1024]; - - let cid = OcallApi.write_ipfs(enc_state.as_slice()).unwrap(); - - OcallApi.read_ipfs(&cid).unwrap(); - - let cid_str = std::str::from_utf8(&cid.0).unwrap(); - let mut f = File::open(cid_str).unwrap(); - let mut content_buf = Vec::new(); - f.read_to_end(&mut content_buf).unwrap(); - info!("reading file {:?} of size {} bytes", f, &content_buf.len()); - - let mut ipfs_content = IpfsContent::new(cid_str, content_buf); - let verification = ipfs_content.verify(); - assert!(verification.is_ok()); -} diff --git a/tee-worker/bitacross/enclave-runtime/src/test/mocks/attestation_ocall_mock.rs b/tee-worker/bitacross/enclave-runtime/src/test/mocks/attestation_ocall_mock.rs deleted file mode 100644 index a480890761..0000000000 --- a/tee-worker/bitacross/enclave-runtime/src/test/mocks/attestation_ocall_mock.rs +++ /dev/null @@ -1,101 +0,0 @@ -/* - CCopyright 2021 Integritee AG and Supercomputing Systems AG - Copyright (C) 2017-2019 Baidu, Inc. All Rights Reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use itp_ocall_api::EnclaveAttestationOCallApi; -use sgx_types::*; -use std::{ - fmt::{Debug, Formatter, Result as FormatResult}, - vec::Vec, -}; - -#[derive(Clone)] -pub struct AttestationOCallMock { - mr_enclave: sgx_measurement_t, -} - -impl AttestationOCallMock { - pub fn new() -> Self { - Default::default() - } - - pub fn create_with_mr_enclave(mr_enclave: sgx_measurement_t) -> Self { - AttestationOCallMock { mr_enclave } - } -} - -impl EnclaveAttestationOCallApi for AttestationOCallMock { - fn sgx_init_quote(&self) -> SgxResult<(sgx_target_info_t, sgx_epid_group_id_t)> { - unreachable!() - } - - fn get_ias_socket(&self) -> SgxResult { - unreachable!() - } - - fn get_quote( - &self, - _sig_rl: Vec, - _report: sgx_report_t, - _sign_type: sgx_quote_sign_type_t, - _spid: sgx_spid_t, - _quote_nonce: sgx_quote_nonce_t, - ) -> SgxResult<(sgx_report_t, Vec)> { - unreachable!() - } - - fn get_dcap_quote(&self, _report: sgx_report_t, _quote_size: u32) -> SgxResult> { - unreachable!() - } - - fn get_qve_report_on_quote( - &self, - _quote: Vec, - _current_time: i64, - _quote_collateral: sgx_ql_qve_collateral_t, - _qve_report_info: sgx_ql_qe_report_info_t, - _supplemental_data_size: u32, - ) -> SgxResult<(u32, sgx_ql_qv_result_t, sgx_ql_qe_report_info_t, Vec)> { - unreachable!() - } - - fn get_update_info( - &self, - _platform_info: sgx_platform_info_t, - _enclave_trusted: i32, - ) -> SgxResult { - Ok(sgx_update_info_bit_t { csmeFwUpdate: 0, pswUpdate: 0, ucodeUpdate: 0 }) - } - - fn get_mrenclave_of_self(&self) -> SgxResult { - Ok(self.mr_enclave) - } -} - -impl Default for AttestationOCallMock { - fn default() -> Self { - AttestationOCallMock { mr_enclave: sgx_measurement_t { m: [1; SGX_HASH_SIZE] } } - } -} - -impl Debug for AttestationOCallMock { - fn fmt(&self, f: &mut Formatter<'_>) -> FormatResult { - f.debug_struct("AttestationOCallMock") - .field("mr_enclave", &self.mr_enclave.m) - .finish() - } -} diff --git a/tee-worker/bitacross/enclave-runtime/src/test/mocks/mod.rs b/tee-worker/bitacross/enclave-runtime/src/test/mocks/mod.rs deleted file mode 100644 index a6079c29eb..0000000000 --- a/tee-worker/bitacross/enclave-runtime/src/test/mocks/mod.rs +++ /dev/null @@ -1,21 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - Copyright (C) 2017-2019 Baidu, Inc. All Rights Reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -pub mod attestation_ocall_mock; -pub mod rpc_responder_mock; -pub mod types; diff --git a/tee-worker/bitacross/enclave-runtime/src/test/mocks/rpc_responder_mock.rs b/tee-worker/bitacross/enclave-runtime/src/test/mocks/rpc_responder_mock.rs deleted file mode 100644 index 4fd85d68fd..0000000000 --- a/tee-worker/bitacross/enclave-runtime/src/test/mocks/rpc_responder_mock.rs +++ /dev/null @@ -1,84 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use itc_direct_rpc_server::{DirectRpcResult, RpcHash, SendRpcResponse}; -use itp_types::{DirectRequestStatus, TrustedOperationStatus}; -use std::{marker::PhantomData, vec::Vec}; - -pub struct RpcResponderMock { - _hash: PhantomData, -} - -impl RpcResponderMock { - pub fn new() -> Self { - RpcResponderMock { _hash: PhantomData } - } -} -impl Default for RpcResponderMock { - fn default() -> Self { - Self::new() - } -} - -impl SendRpcResponse for RpcResponderMock -where - Hash: RpcHash, -{ - type Hash = Hash; - - fn update_status_event( - &self, - _hash: Self::Hash, - _status_update: TrustedOperationStatus, - ) -> DirectRpcResult<()> { - Ok(()) - } - - fn send_state(&self, _hash: Self::Hash, _state_encoded: Vec) -> DirectRpcResult<()> { - Ok(()) - } - - fn send_state_with_status( - &self, - _hash: Self::Hash, - _state_encoded: Vec, - _status: DirectRequestStatus, - ) -> DirectRpcResult<()> { - Ok(()) - } - - fn update_force_wait(&self, _hash: Self::Hash, _force_wait: bool) -> DirectRpcResult<()> { - Ok(()) - } - - fn update_connection_state( - &self, - _hash: Self::Hash, - _encoded_value: Vec, - _force_wait: bool, - ) -> DirectRpcResult<()> { - Ok(()) - } - - fn swap_hash(&self, _old_hash: Self::Hash, _new_hash: Self::Hash) -> DirectRpcResult<()> { - Ok(()) - } - - fn is_force_wait(&self, _hash: Self::Hash) -> bool { - false - } -} diff --git a/tee-worker/bitacross/enclave-runtime/src/test/mocks/types.rs b/tee-worker/bitacross/enclave-runtime/src/test/mocks/types.rs deleted file mode 100644 index 1ffe90a2fd..0000000000 --- a/tee-worker/bitacross/enclave-runtime/src/test/mocks/types.rs +++ /dev/null @@ -1,84 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - Copyright (C) 2017-2019 Baidu, Inc. All Rights Reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -//! Type definitions for testing. Includes various mocks. - -use crate::test::mocks::rpc_responder_mock::RpcResponderMock; -use ita_sgx_runtime::Runtime; -use ita_stf::{Getter, Stf, TrustedCallSigned}; -use itc_parentchain::block_import_dispatcher::trigger_parentchain_block_import_mock::TriggerParentchainBlockImportMock; -use itp_node_api::metadata::{metadata_mocks::NodeMetadataMock, provider::NodeMetadataRepository}; -use itp_sgx_crypto::{mocks::KeyRepositoryMock, Aes}; -use itp_sgx_externalities::SgxExternalities; -use itp_stf_executor::executor::StfExecutor; -use itp_stf_primitives::types::TrustedOperation; -use itp_test::mock::{handle_state_mock::HandleStateMock, onchain_mock::OnchainMock}; -use itp_top_pool::basic_pool::BasicPool; -use itp_top_pool_author::{api::SidechainApi, author::Author, top_filter::AllowAllTopsFilter}; -use itp_types::{Block as ParentchainBlock, SignedBlock as SignedParentchainBlock}; -use primitive_types::H256; -use sgx_crypto_helper::rsa3072::Rsa3072KeyPair; -use sp_core::ed25519 as spEd25519; - -pub type TestSigner = spEd25519::Pair; -pub type TestShieldingKey = Rsa3072KeyPair; -pub type TestStateKey = Aes; - -pub type TestGetter = Getter; -pub type TestCall = TrustedCallSigned; -pub type TestStf = Stf; - -pub type TestShieldingKeyRepo = KeyRepositoryMock; - -pub type TestStateKeyRepo = KeyRepositoryMock; - -pub type TestStateHandler = HandleStateMock; - -pub type TestOCallApi = OnchainMock; - -pub type TestParentchainBlockImportTrigger = - TriggerParentchainBlockImportMock; - -pub type TestNodeMetadataRepository = NodeMetadataRepository; - -pub type TestStfExecutor = StfExecutor< - TestOCallApi, - TestStateHandler, - TestNodeMetadataRepository, - TestStf, - TrustedCallSigned, - Getter, ->; - -pub type TestRpcResponder = RpcResponderMock; - -pub type TestTopPool = BasicPool< - SidechainApi, - ParentchainBlock, - TestRpcResponder, - TrustedOperation, ->; - -pub type TestTopPoolAuthor = Author< - TestTopPool, - AllowAllTopsFilter, - TestStateHandler, - TestShieldingKeyRepo, - TrustedCallSigned, - Getter, ->; diff --git a/tee-worker/bitacross/enclave-runtime/src/test/mod.rs b/tee-worker/bitacross/enclave-runtime/src/test/mod.rs deleted file mode 100644 index 8bdbe375c9..0000000000 --- a/tee-worker/bitacross/enclave-runtime/src/test/mod.rs +++ /dev/null @@ -1,27 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - Copyright (C) 2017-2019 Baidu, Inc. All Rights Reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -pub mod cert_tests; -pub mod direct_rpc_tests; -pub mod enclave_signer_tests; -pub mod fixtures; -pub mod ipfs_tests; -pub mod mocks; -mod state_getter_tests; -pub mod tests_main; -pub mod top_pool_tests; diff --git a/tee-worker/bitacross/enclave-runtime/src/test/state_getter_tests.rs b/tee-worker/bitacross/enclave-runtime/src/test/state_getter_tests.rs deleted file mode 100644 index f902061e9e..0000000000 --- a/tee-worker/bitacross/enclave-runtime/src/test/state_getter_tests.rs +++ /dev/null @@ -1,53 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - Copyright (C) 2017-2019 Baidu, Inc. All Rights Reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use codec::Decode; -use ita_sgx_runtime::Runtime; -use ita_stf::{ - test_genesis::{endowed_account, test_genesis_setup, ENDOWED_ACC_FUNDS}, - Balance, Getter, Stf, TrustedCallSigned, TrustedGetter, -}; -use itp_sgx_externalities::SgxExternalities; -use itp_stf_executor::state_getter::{GetState, StfStateGetter}; -use litentry_primitives::Identity; -use sp_core::Pair; - -type TestState = SgxExternalities; -type TestStf = Stf; -type TestStfStateGetter = StfStateGetter; - -pub fn state_getter_works() { - let sender = endowed_account(); - let signed_getter = TrustedGetter::free_balance(Identity::Substrate(sender.public().into())) - .sign(&sender.into()); - let mut state = test_state(); - - let encoded_balance = TestStfStateGetter::get_state(signed_getter.into(), &mut state) - .unwrap() - .unwrap(); - - let balance = Balance::decode(&mut encoded_balance.as_slice()).unwrap(); - - assert_eq!(balance, ENDOWED_ACC_FUNDS); -} - -fn test_state() -> TestState { - let mut state = TestState::default(); - test_genesis_setup(&mut state); - state -} diff --git a/tee-worker/bitacross/enclave-runtime/src/test/tests_main.rs b/tee-worker/bitacross/enclave-runtime/src/test/tests_main.rs deleted file mode 100644 index 0e44a1937b..0000000000 --- a/tee-worker/bitacross/enclave-runtime/src/test/tests_main.rs +++ /dev/null @@ -1,625 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ - -use crate::{ - rpc, - sync::tests::{enclave_rw_lock_works, sidechain_rw_lock_works}, - test::{ - cert_tests::*, - direct_rpc_tests, enclave_signer_tests, - fixtures::test_setup::{ - enclave_call_signer, test_setup, TestStf, TestStfExecutor, TestTopPoolAuthor, - }, - state_getter_tests, top_pool_tests, - }, - tls_ra, -}; -use codec::Decode; -use ita_sgx_runtime::ParentchainLitentry; -use ita_stf::{ - helpers::set_block_number, - stf_sgx_tests, - test_genesis::{endowed_account as funded_pair, unendowed_account}, - Getter, State, TrustedCall, TrustedCallSigned, TrustedGetter, -}; -use itp_node_api::metadata::{metadata_mocks::NodeMetadataMock, provider::NodeMetadataRepository}; -use itp_sgx_crypto::{Aes, StateCrypto}; -use itp_sgx_externalities::{SgxExternalitiesDiffType, SgxExternalitiesTrait}; -use itp_stf_executor::{ - executor_tests as stf_executor_tests, traits::StateUpdateProposer, BatchExecutionResult, -}; -use itp_stf_interface::{ - parentchain_pallet::ParentchainPalletInstancesInterface, - system_pallet::{SystemPalletAccountInterface, SystemPalletEventInterface}, - StateCallInterface, -}; -use itp_stf_primitives::{ - traits::TrustedCallSigning, - types::{ShardIdentifier, StatePayload, TrustedOperation}, -}; -use itp_stf_state_handler::handle_state::HandleState; -use itp_test::mock::handle_state_mock; -use itp_top_pool_author::{test_utils::submit_operation_to_top_pool, traits::AuthorApi}; -use itp_types::{parentchain::ParentchainId, AccountId, Header}; -use litentry_primitives::Identity; -use sgx_tunittest::*; -use sgx_types::size_t; -use sp_core::{crypto::Pair, ed25519 as spEd25519, H256}; -use sp_runtime::traits::Header as HeaderT; -use std::{string::String, sync::Arc, time::Duration, vec::Vec}; -#[no_mangle] -pub extern "C" fn test_main_entrance() -> size_t { - rsgx_unit_tests!( - itp_attestation_handler::attestation_handler::tests::decode_spid_works, - stf_sgx_tests::enclave_account_initialization_works, - stf_sgx_tests::shield_funds_increments_signer_account_nonce, - stf_sgx_tests::test_root_account_exists_after_initialization, - itp_stf_state_handler::test::sgx_tests::test_write_and_load_state_works, - itp_stf_state_handler::test::sgx_tests::test_sgx_state_decode_encode_works, - itp_stf_state_handler::test::sgx_tests::test_encrypt_decrypt_state_type_works, - itp_stf_state_handler::test::sgx_tests::test_write_access_locks_read_until_finished, - itp_stf_state_handler::test::sgx_tests::test_ensure_subsequent_state_loads_have_same_hash, - itp_stf_state_handler::test::sgx_tests::test_state_handler_file_backend_is_initialized, - itp_stf_state_handler::test::sgx_tests::test_multiple_state_updates_create_snapshots_up_to_cache_size, - itp_stf_state_handler::test::sgx_tests::test_state_files_from_handler_can_be_loaded_again, - itp_stf_state_handler::test::sgx_tests::test_file_io_get_state_hash_works, - itp_stf_state_handler::test::sgx_tests::test_list_state_ids_ignores_files_not_matching_the_pattern, - itp_stf_state_handler::test::sgx_tests::test_in_memory_state_initializes_from_shard_directory, - itp_sgx_crypto::tests::aes_sealing_works, - itp_sgx_crypto::tests::using_get_aes_repository_twice_initializes_key_only_once, - itp_sgx_crypto::tests::ed25529_sealing_works, - itp_sgx_crypto::tests::using_get_ed25519_repository_twice_initializes_key_only_once, - itp_sgx_crypto::tests::rsa3072_sealing_works, - itp_sgx_crypto::tests::using_get_rsa3072_repository_twice_initializes_key_only_once, - itp_sgx_crypto::tests::ecdsa_creating_repository_with_same_path_and_prefix_results_in_same_key, - itp_sgx_crypto::tests::ecdsa_creating_repository_with_same_path_and_prefix_but_new_key_results_in_new_key, - itp_sgx_crypto::tests::ecdsa_seal_init_should_create_new_key_if_not_present, - itp_sgx_crypto::tests::ecdsa_seal_init_should_seal_provided_key, - itp_sgx_crypto::tests::ecdsa_seal_init_should_not_change_key_if_exists_and_not_provided, - itp_sgx_crypto::tests::ecdsa_seal_init_with_key_should_change_current_key, - itp_sgx_crypto::tests::ecdsa_sign_should_produce_valid_signature, - itp_sgx_crypto::tests::schnorr_creating_repository_with_same_path_and_prefix_results_in_same_key, - itp_sgx_crypto::tests::schnorr_creating_repository_with_same_path_and_prefix_but_new_key_results_in_new_key, - itp_sgx_crypto::tests::schnorr_seal_init_should_create_new_key_if_not_present, - itp_sgx_crypto::tests::schnorr_seal_init_should_seal_provided_key, - itp_sgx_crypto::tests::schnorr_seal_init_should_not_change_key_if_exists_and_not_provided, - itp_sgx_crypto::tests::schnorr_seal_init_with_key_should_change_key_current_key, - test_submit_trusted_call_to_top_pool, - test_submit_trusted_getter_to_top_pool, - test_differentiate_getter_and_call_works, - test_executing_call_updates_account_nonce, - test_call_set_update_parentchain_block, - test_invalid_nonce_call_is_not_executed, - test_signature_must_match_public_sender_in_call, - test_non_root_shielding_call_is_not_executed, - test_shielding_call_with_enclave_self_is_executed, - test_retrieve_events, - test_retrieve_event_count, - test_reset_events, - rpc::worker_api_direct::tests::test_given_io_handler_methods_then_retrieve_all_names_as_string, - handle_state_mock::tests::initialized_shards_list_is_empty, - handle_state_mock::tests::shard_exists_after_inserting, - handle_state_mock::tests::from_shard_works, - handle_state_mock::tests::initialize_creates_default_state, - handle_state_mock::tests::load_mutate_and_write_works, - handle_state_mock::tests::ensure_subsequent_state_loads_have_same_hash, - handle_state_mock::tests::ensure_encode_and_encrypt_does_not_affect_state_hash, - handle_state_mock::tests::migrate_shard_works, - // mra cert tests - test_verify_mra_cert_should_work, - test_verify_wrong_cert_is_err, - test_given_wrong_platform_info_when_verifying_attestation_report_then_return_error, - // sync tests - sidechain_rw_lock_works, - enclave_rw_lock_works, - // unit tests of stf_executor - stf_executor_tests::propose_state_update_always_executes_preprocessing_step, - stf_executor_tests::propose_state_update_executes_no_trusted_calls_given_no_time, - stf_executor_tests::propose_state_update_executes_only_one_trusted_call_given_not_enough_time, - stf_executor_tests::propose_state_update_executes_all_calls_given_enough_time, - enclave_signer_tests::enclave_signer_signatures_are_valid, - enclave_signer_tests::derive_key_is_deterministic, - enclave_signer_tests::nonce_is_computed_correctly, - state_getter_tests::state_getter_works, - // sidechain integration tests - top_pool_tests::process_indirect_call_in_top_pool, - // TODO: Litentry disables it for now (P-494) - // top_pool_tests::submit_shielding_call_to_top_pool, - // tls_ra unit tests - tls_ra::seal_handler::test::seal_shielding_key_works, - tls_ra::seal_handler::test::seal_shielding_key_fails_for_invalid_key, - tls_ra::seal_handler::test::unseal_seal_shielding_key_works, - tls_ra::seal_handler::test::seal_state_key_works, - tls_ra::seal_handler::test::seal_state_key_fails_for_invalid_key, - tls_ra::seal_handler::test::unseal_seal_state_key_works, - tls_ra::seal_handler::test::seal_state_works, - tls_ra::seal_handler::test::seal_state_fails_for_invalid_state, - tls_ra::seal_handler::test::unseal_seal_state_works, - tls_ra::tests::test_state_and_key_provisioning, - tls_ra::tests::test_tls_ra_server_client_networking, - // RPC tests - direct_rpc_tests::get_state_request_works, - direct_rpc_tests::state_get_mrenclave_works, - - // light-client-test - itc_parentchain::light_client::io::sgx_tests::init_parachain_light_client_works, - itc_parentchain::light_client::io::sgx_tests::sealing_creates_backup, - - // test musig ceremony - bc_musig2_ceremony::sgx_tests::test_full_flow_with_3_ceremonies, - - // these unit test (?) need an ipfs node running.. - // ipfs::test_creates_ipfs_content_struct_works, - // ipfs::test_verification_ok_for_correct_content, - // ipfs::test_verification_fails_for_incorrect_content, - // test_ocall_read_write_ipfs, - ) -} - -fn test_submit_trusted_call_to_top_pool() { - // given - let (top_pool_author, _, shard, mrenclave, shielding_key, ..) = test_setup(); - - let sender = funded_pair(); - - let signed_call = TrustedCall::balance_set_balance( - Identity::Substrate(sender.public().into()), - sender.public().into(), - 42, - 42, - ) - .sign(&sender.into(), 0, &mrenclave, &shard); - let trusted_operation = direct_top(signed_call); - - // when - submit_operation_to_top_pool( - top_pool_author.as_ref(), - &trusted_operation, - &shielding_key, - shard, - ) - .unwrap(); - - let calls = top_pool_author.get_pending_trusted_calls(shard); - - // then - assert_eq!(calls[0], trusted_operation); -} - -// The TOP pool can hold any TrustedOperation, which at the moment also includes Getters. -// However, in reality we don't submit getters to the TOP pool anymore, they are executed immediately. -// The filter set in the TOP pool author prevents getters from being submitted. -// In this test however, we set the filter to `AllowAllTops`, so getters can be submitted. -// We want to keep this back door open, in case we would want to submit getter into the TOP pool again in the future. -fn test_submit_trusted_getter_to_top_pool() { - // given - let (top_pool_author, _, shard, _, shielding_key, ..) = test_setup(); - - let sender = funded_pair(); - - let signed_getter = TrustedGetter::free_balance(Identity::Substrate(sender.public().into())) - .sign(&sender.into()); - - // when - submit_operation_to_top_pool( - top_pool_author.as_ref(), - &TrustedOperation::::get(Getter::trusted(signed_getter.clone())), - &shielding_key, - shard, - ) - .unwrap(); - - let getters = top_pool_author.get_pending_getters(shard); - - // then - assert_eq!( - getters[0], - TrustedOperation::::get(Getter::trusted(signed_getter)) - ); -} - -fn test_differentiate_getter_and_call_works() { - // given - let (top_pool_author, _, shard, mrenclave, shielding_key, ..) = test_setup(); - - // create accounts - let sender = funded_pair(); - - let signed_getter = TrustedGetter::free_balance(Identity::Substrate(sender.public().into())) - .sign(&sender.into()); - - let signed_call = TrustedCall::balance_set_balance( - Identity::Substrate(sender.public().into()), - sender.public().into(), - 42, - 42, - ) - .sign(&sender.into(), 0, &mrenclave, &shard); - let trusted_operation = direct_top(signed_call); - - // when - submit_operation_to_top_pool( - top_pool_author.as_ref(), - &TrustedOperation::::get(Getter::trusted(signed_getter.clone())), - &shielding_key, - shard, - ) - .unwrap(); - submit_operation_to_top_pool( - top_pool_author.as_ref(), - &trusted_operation, - &shielding_key, - shard, - ) - .unwrap(); - - let calls = top_pool_author.get_pending_trusted_calls(shard); - let getters = top_pool_author.get_pending_getters(shard); - - // then - assert_eq!(calls[0], trusted_operation); - assert_eq!( - getters[0], - TrustedOperation::::get(Getter::trusted(signed_getter)) - ); -} - -fn test_executing_call_updates_account_nonce() { - // given - let (top_pool_author, _, shard, mrenclave, shielding_key, _, stf_executor) = test_setup(); - - let sender = funded_pair(); - let receiver = unfunded_public(); - - let trusted_operation = TrustedCall::balance_transfer( - Identity::Substrate(sender.public().into()), - receiver.into(), - 1000, - ) - .sign(&sender.into(), 0, &mrenclave, &shard) - .into_trusted_operation(false); - - submit_operation_to_top_pool( - top_pool_author.as_ref(), - &trusted_operation, - &shielding_key, - shard, - ) - .unwrap(); - - // when - let mut execution_result = - execute_trusted_calls(&shard, stf_executor.as_ref(), &top_pool_author); - - let nonce = TestStf::get_account_nonce( - &mut execution_result.state_after_execution, - &sender.public().into(), - ); - assert_eq!(nonce, 1); -} - -fn test_call_set_update_parentchain_block() { - let (_, _, shard, _, _, state_handler, _) = test_setup(); - let (mut state, _) = state_handler.load_cloned(&shard).unwrap(); - - let block_number = 3; - let parent_hash = H256::from([1; 32]); - - let header: Header = HeaderT::new( - block_number, - Default::default(), - Default::default(), - parent_hash, - Default::default(), - ); - - TestStf::update_parentchain_litentry_block(&mut state, header.clone()).unwrap(); - - assert_eq!(header.hash(), state.execute_with(ParentchainLitentry::block_hash)); - assert_eq!(parent_hash, state.execute_with(ParentchainLitentry::parent_hash)); - assert_eq!(block_number, state.execute_with(ParentchainLitentry::block_number)); -} - -fn test_signature_must_match_public_sender_in_call() { - // given - let (top_pool_author, _, shard, mrenclave, shielding_key, _, stf_executor) = test_setup(); - - // create accounts - let sender = funded_pair(); - let receiver = unfunded_public(); - - let trusted_operation = TrustedCall::balance_transfer( - Identity::Substrate(receiver.into()), - sender.public().into(), - 1000, - ) - .sign(&sender.into(), 10, &mrenclave, &shard) - .into_trusted_operation(true); - - submit_operation_to_top_pool( - top_pool_author.as_ref(), - &trusted_operation, - &shielding_key, - shard, - ) - .unwrap(); - - let executed_batch = execute_trusted_calls(&shard, stf_executor.as_ref(), &top_pool_author); - - // the top pool doesn't verify signatures, the call will only fail upon execution - assert!(!executed_batch.executed_operations[0].is_success()); -} - -fn test_invalid_nonce_call_is_not_executed() { - // given - let (top_pool_author, _, shard, mrenclave, shielding_key, _, stf_executor) = test_setup(); - - // create accounts - let sender = funded_pair(); - let receiver = unfunded_public(); - - let trusted_operation = TrustedCall::balance_transfer( - Identity::Substrate(sender.public().into()), - receiver.into(), - 1000, - ) - .sign(&sender.into(), 10, &mrenclave, &shard) - .into_trusted_operation(true); - - submit_operation_to_top_pool( - top_pool_author.as_ref(), - &trusted_operation, - &shielding_key, - shard, - ) - .unwrap(); - - let executed_batch = execute_trusted_calls(&shard, stf_executor.as_ref(), &top_pool_author); - - // due to #1488, even invalid nonces will enter the pool ready state, so we can only verify that the call will fail - assert!(!executed_batch.executed_operations[0].is_success()); -} - -fn test_non_root_shielding_call_is_not_executed() { - // given - let (top_pool_author, _state, shard, mrenclave, shielding_key, _, stf_executor) = test_setup(); - - let sender = funded_pair(); - let sender_acc: AccountId = sender.public().into(); - - let signed_call = TrustedCall::balance_shield( - Identity::Substrate(sender_acc.clone().into()), - sender_acc, - 1000, - ParentchainId::Litentry, - ) - .sign(&sender.into(), 0, &mrenclave, &shard); - - submit_operation_to_top_pool( - top_pool_author.as_ref(), - &direct_top(signed_call), - &shielding_key, - shard, - ) - .unwrap(); - - // when - let executed_batch = execute_trusted_calls(&shard, stf_executor.as_ref(), &top_pool_author); - - // then - assert!(!executed_batch.executed_operations[0].is_success()); -} - -fn test_shielding_call_with_enclave_self_is_executed() { - let (top_pool_author, _state, shard, mrenclave, shielding_key, _, stf_executor) = test_setup(); - - let sender = funded_pair(); - let sender_account: AccountId = sender.public().into(); - let enclave_call_signer = enclave_call_signer(&shielding_key); - - let signed_call = TrustedCall::balance_shield( - Identity::Substrate(enclave_call_signer.public().into()), - sender_account, - 1000, - ParentchainId::Litentry, - ) - .sign(&enclave_call_signer.into(), 0, &mrenclave, &shard); - let trusted_operation = - TrustedOperation::::indirect_call(signed_call); - - submit_operation_to_top_pool( - top_pool_author.as_ref(), - &trusted_operation, - &shielding_key, - shard, - ) - .unwrap(); - - // when - let executed_batch = - execute_trusted_calls(&shard, stf_executor.as_ref(), top_pool_author.as_ref()); - - // then - assert_eq!(1, executed_batch.executed_operations.len()); - assert!(executed_batch.executed_operations[0].is_success()); -} - -pub fn test_retrieve_events() { - // given - let (_, mut state, shard, mrenclave, ..) = test_setup(); - let mut opaque_vec = Vec::new(); - let sender = funded_pair(); - let receiver = unendowed_account(); - let transfer_value: u128 = 1_000; - // Events will only get executed after genesis. - state.execute_with(|| set_block_number(100)); - - // Execute a transfer extrinsic to generate events via the Balance pallet. - let trusted_call = TrustedCall::balance_transfer( - Identity::Substrate(sender.public().into()), - receiver.public().into(), - transfer_value, - ) - .sign(&sender.into(), 0, &mrenclave, &shard); - let repo = Arc::new(NodeMetadataRepository::::default()); - let shard = ShardIdentifier::default(); - TestStf::execute_call( - &mut state, - &shard, - trusted_call, - Default::default(), - &mut opaque_vec, - repo, - ) - .unwrap(); - - assert_eq!(TestStf::get_events(&mut state).len(), 4); -} - -pub fn test_retrieve_event_count() { - let (_, mut state, shard, mrenclave, ..) = test_setup(); - let mut opaque_vec = Vec::new(); - let sender = funded_pair(); - let receiver = unendowed_account(); - let transfer_value: u128 = 1_000; - // Events will only get executed after genesis. - state.execute_with(|| set_block_number(100)); - - // Execute a transfer extrinsic to generate events via the Balance pallet. - let trusted_call = TrustedCall::balance_transfer( - Identity::Substrate(sender.public().into()), - receiver.public().into(), - transfer_value, - ) - .sign(&sender.into(), 0, &mrenclave, &shard); - - // when - let repo = Arc::new(NodeMetadataRepository::::default()); - let shard = ShardIdentifier::default(); - TestStf::execute_call( - &mut state, - &shard, - trusted_call, - Default::default(), - &mut opaque_vec, - repo, - ) - .unwrap(); - - let event_count = TestStf::get_event_count(&mut state); - assert_eq!(event_count, 4); -} - -pub fn test_reset_events() { - let (_, mut state, shard, mrenclave, ..) = test_setup(); - let mut opaque_vec = Vec::new(); - let sender = funded_pair(); - let receiver = unendowed_account(); - let transfer_value: u128 = 1_000; - // Events will only get executed after genesis. - state.execute_with(|| set_block_number(100)); - // Execute a transfer extrinsic to generate events via the Balance pallet. - let trusted_call = TrustedCall::balance_transfer( - Identity::Substrate(sender.public().into()), - receiver.public().into(), - transfer_value, - ) - .sign(&sender.into(), 0, &mrenclave, &shard); - let repo = Arc::new(NodeMetadataRepository::::default()); - let shard = ShardIdentifier::default(); - TestStf::execute_call( - &mut state, - &shard, - trusted_call, - Default::default(), - &mut opaque_vec, - repo, - ) - .unwrap(); - let receiver_acc_info = TestStf::get_account_data(&mut state, &receiver.public().into()); - assert_eq!(receiver_acc_info.free, transfer_value); - // Ensure that there really have been events generated. - assert_eq!(TestStf::get_events(&mut state).len(), 4); - - // Remove the events. - TestStf::reset_events(&mut state); - - // Ensure that the events storage has been cleared. - assert_eq!(TestStf::get_events(&mut state).len(), 0); -} - -fn execute_trusted_calls( - shard: &ShardIdentifier, - stf_executor: &TestStfExecutor, - top_pool_author: &TestTopPoolAuthor, -) -> BatchExecutionResult { - let top_pool_calls = top_pool_author.get_pending_trusted_calls(*shard); - stf_executor - .propose_state_update( - &top_pool_calls, - &latest_parentchain_header(), - shard, - Duration::from_millis(600), - |s| s, - ) - .unwrap() -} - -// helper functions -/// Decrypt `encrypted` and decode it into `StatePayload` -pub fn encrypted_state_diff_from_encrypted( - encrypted: &[u8], -) -> StatePayload { - let mut encrypted_payload: Vec = encrypted.to_vec(); - let state_key = state_key(); - state_key.decrypt(&mut encrypted_payload).unwrap(); - StatePayload::decode(&mut encrypted_payload.as_slice()).unwrap() -} - -pub fn state_key() -> Aes { - Aes::default() -} - -/// Some random account that has no funds in the `Stf`'s `test_genesis` config. -pub fn unfunded_public() -> spEd25519::Public { - spEd25519::Public::from_raw(*b"asdfasdfadsfasdfasfasdadfadfasdf") -} - -pub fn test_account() -> spEd25519::Pair { - spEd25519::Pair::from_seed(b"42315678901234567890123456789012") -} - -/// transforms `call` into `TrustedOperation::direct(call)` -pub fn direct_top(call: TrustedCallSigned) -> TrustedOperation { - call.into_trusted_operation(true) -} - -/// Just some random onchain header -pub fn latest_parentchain_header() -> Header { - Header::new(1, Default::default(), Default::default(), [69; 32].into(), Default::default()) -} - -/// Reads the value at `key_hash` from `state_diff` and decodes it into `D` -pub fn get_from_state_diff(state_diff: &SgxExternalitiesDiffType, key_hash: &[u8]) -> D { - // fixme: what's up here with the wrapping?? - state_diff - .get(key_hash) - .unwrap() - .as_ref() - .map(|d| Decode::decode(&mut d.as_slice())) - .unwrap() - .unwrap() -} diff --git a/tee-worker/bitacross/enclave-runtime/src/test/top_pool_tests.rs b/tee-worker/bitacross/enclave-runtime/src/test/top_pool_tests.rs deleted file mode 100644 index c34e3209ac..0000000000 --- a/tee-worker/bitacross/enclave-runtime/src/test/top_pool_tests.rs +++ /dev/null @@ -1,210 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - Copyright (C) 2017-2019 Baidu, Inc. All Rights Reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use crate::test::{ - fixtures::{ - components::{ - create_ocall_api, create_top_pool, encrypt_trusted_operation, sign_trusted_call, - }, - initialize_test_state::init_state, - }, - mocks::types::{ - TestShieldingKey, TestShieldingKeyRepo, TestSigner, TestStateHandler, TestTopPoolAuthor, - }, -}; -use ita_stf::{ - test_genesis::{endowed_account, unendowed_account}, - Getter, TrustedCall, TrustedCallSigned, -}; -use itc_parentchain_test::ParentchainHeaderBuilder; -use itp_ocall_api::EnclaveAttestationOCallApi; -use itp_sgx_crypto::ShieldingCryptoEncrypt; -use itp_stf_primitives::types::TrustedOperation; -use itp_top_pool_author::{top_filter::AllowAllTopsFilter, traits::AuthorApi}; -use itp_types::{RsaRequest, ShardIdentifier}; -use jsonrpc_core::futures::executor; -use litentry_primitives::Identity; -use log::*; -use sgx_crypto_helper::RsaKeyPair; -use sp_core::Pair; -use std::{sync::Arc, vec::Vec}; - -pub fn process_indirect_call_in_top_pool() { - let _ = env_logger::builder().is_test(true).try_init(); - info!("Setting up test."); - - let signer = TestSigner::from_seed(b"42315678901234567890123456789012"); - let shielding_key = TestShieldingKey::new().unwrap(); - let shielding_key_repo = Arc::new(TestShieldingKeyRepo::new(shielding_key)); - let header = ParentchainHeaderBuilder::default().build(); - - let ocall_api = create_ocall_api(&header, &signer); - - let state_handler = Arc::new(TestStateHandler::default()); - let (_, shard_id) = init_state(state_handler.as_ref(), signer.public().into()); - - let top_pool = create_top_pool(); - - let top_pool_author = Arc::new(TestTopPoolAuthor::new( - top_pool, - AllowAllTopsFilter::::new(), - state_handler, - shielding_key_repo, - )); - - let encrypted_indirect_call = - encrypted_indirect_call(ocall_api.as_ref(), &shard_id, &shielding_key); - - executor::block_on( - top_pool_author.submit_top(RsaRequest::new(shard_id, encrypted_indirect_call)), - ) - .unwrap(); - - assert_eq!(1, top_pool_author.get_pending_trusted_calls(shard_id).len()); -} - -/* -// TODO: use our trusted call for testing - see P-494 - -pub fn submit_shielding_call_to_top_pool() { - let _ = env_logger::builder().is_test(true).try_init(); - - let signer = TestSigner::from_seed(b"42315678901234567890123456789012"); - let shielding_key = TestShieldingKey::new().unwrap(); - let shielding_key_repo = Arc::new(TestShieldingKeyRepo::new(shielding_key)); - let header = ParentchainHeaderBuilder::default().build(); - - let ocall_api = create_ocall_api(&header, &signer); - let mr_enclave = ocall_api.get_mrenclave_of_self().unwrap(); - - let state_handler = Arc::new(TestStateHandler::default()); - let (state, shard_id) = init_state(state_handler.as_ref(), signer.public().into()); - let state_observer = Arc::new(ObserveStateMock::new(state)); - - let top_pool = create_top_pool(); - let (sender, _receiver) = std::sync::mpsc::sync_channel(1000); - - let top_pool_author = Arc::new(TestTopPoolAuthor::new( - top_pool, - AllowAllTopsFilter::::new(), - DirectCallsOnlyFilter::::new(), - state_handler, - shielding_key_repo.clone(), - Arc::new(sender), - )); - - let enclave_signer = - Arc::new(StfEnclaveSigner::<_, _, _, TestStf, _, TrustedCallSigned, Getter>::new( - state_observer, - ocall_api, - shielding_key_repo.clone(), - top_pool_author.clone(), - )); - let node_meta_data_repository = Arc::new(NodeMetadataRepository::default()); - node_meta_data_repository.set_metadata(NodeMetadataMock::new()); - let indirect_calls_executor = IndirectCallsExecutor::< - _, - _, - _, - _, - integritee::ExtrinsicFilter, - TestEventCreator, - integritee::ParentchainEventHandler, - TrustedCallSigned, - Getter, - >::new( - shielding_key_repo, - enclave_signer, - top_pool_author.clone(), - node_meta_data_repository, - ParentchainId::Litentry, - ); - - let block_with_shielding_call = create_shielding_call_extrinsic(shard_id, &shielding_key); - - let _ = indirect_calls_executor - .execute_indirect_calls_in_extrinsics(&block_with_shielding_call, &Vec::new()) - .unwrap(); - - assert_eq!(1, top_pool_author.get_pending_trusted_calls(shard_id).len()); - let trusted_operation = - top_pool_author.get_pending_trusted_calls(shard_id).first().cloned().unwrap(); - let trusted_call = trusted_operation.to_call().unwrap(); - assert!(trusted_call.verify_signature(&mr_enclave.m, &shard_id)); -} - -*/ - -fn encrypted_indirect_call< - AttestationApi: EnclaveAttestationOCallApi, - ShieldingKey: ShieldingCryptoEncrypt, ->( - attestation_api: &AttestationApi, - shard_id: &ShardIdentifier, - shielding_key: &ShieldingKey, -) -> Vec { - let sender = endowed_account(); - let receiver = unendowed_account(); - - let call = TrustedCall::balance_transfer( - Identity::Substrate(sender.public().into()), - receiver.public().into(), - 10000u128, - ); - let call_signed = sign_trusted_call(&call, attestation_api, shard_id, sender); - let trusted_operation = - TrustedOperation::::indirect_call(call_signed); - encrypt_trusted_operation(shielding_key, &trusted_operation) -} - -/* -fn create_opaque_call_extrinsic( - _shard: ShardIdentifier, - _shielding_key: &ShieldingKey, -) -> Block { - let test_signer = ed25519::Pair::from_seed(b"33345678901234567890123456789012"); - let signature = test_signer.sign(&[0u8]); - - let default_extra_for_test = ParentchainExtrinsicParams::new( - 0, - 0, - 0, - H256::default(), - ParentchainAdditionalParams::default(), - ); - - let dummy_node_metadata = NodeMetadataMock::new(); - - let call_index = dummy_node_metadata.post_opaque_task_call_indexes().unwrap(); - let opaque_extrinsic = OpaqueExtrinsic::from_bytes( - ParentchainUncheckedExtrinsic::::new_signed( - (call_index, RsaRequest::default()), - Address::Address32([1u8; 32]), - MultiSignature::Ed25519(signature), - default_extra_for_test.signed_extra(), - ) - .encode() - .as_slice(), - ) - .unwrap(); - - ParentchainBlockBuilder::default() - .with_extrinsics(vec![opaque_extrinsic]) - .build() -} -*/ diff --git a/tee-worker/bitacross/enclave-runtime/src/tls_ra/README.md b/tee-worker/bitacross/enclave-runtime/src/tls_ra/README.md deleted file mode 100644 index 3f4effa148..0000000000 --- a/tee-worker/bitacross/enclave-runtime/src/tls_ra/README.md +++ /dev/null @@ -1,33 +0,0 @@ -# provisioning - -each worker runs a provisioning server for other workers of the same MRENCLAVE and shard to get recent stf state and secrets from. - -Light client storage can also be provisioned to avoid re-synching the entire parentchains with each worker - -enclave instances are short-lived on both sides, just for a single request. - -```mermaid -sequenceDiagram -participant untrusted_server -participant enclave_server -participant enclave_client -participant untrusted_client -enclave_server ->> enclave_server: generate shielding & state encryption key -enclave_server ->> enclave_server: init_shard & sync parentchains -untrusted_client ->> untrusted_server: connect TCP -untrusted_client ->> enclave_client: request_state_provisioning -activate enclave_client -untrusted_server ->> enclave_server: run_state_provisioning_server -activate enclave_server -enclave_server ->> enclave_server: load state and secrets -enclave_client ->> enclave_server: open TLS session (including MU RA) -enclave_client ->> enclave_server: request_state_provisioning(shard, account) -enclave_server ->> enclave_client: write_provisioning_payloads -enclave_server ->> enclave_server: add client as vault proxy for shard -enclave_client ->> enclave_client: seal state and secrets to disk -enclave_client -->> untrusted_client: _ -deactivate enclave_client -enclave_server -->> untrusted_server: _ -deactivate enclave_server -untrusted_client --> untrusted_server: disconnect TCP -``` diff --git a/tee-worker/bitacross/enclave-runtime/src/tls_ra/authentication.rs b/tee-worker/bitacross/enclave-runtime/src/tls_ra/authentication.rs deleted file mode 100644 index a3c14528de..0000000000 --- a/tee-worker/bitacross/enclave-runtime/src/tls_ra/authentication.rs +++ /dev/null @@ -1,158 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -//! Remote attestation certificate authentication of server and client -use itp_attestation_handler::cert; -use itp_ocall_api::EnclaveAttestationOCallApi; -use log::*; -use sgx_types::*; -use webpki::DNSName; - -pub struct ClientAuth
{ - outdated_ok: bool, - skip_ra: bool, - attestation_ocall: A, -} - -impl ClientAuth { - pub fn new(outdated_ok: bool, skip_ra: bool, attestation_ocall: A) -> Self { - ClientAuth { outdated_ok, skip_ra, attestation_ocall } - } -} - -impl rustls::ClientCertVerifier for ClientAuth -where - A: EnclaveAttestationOCallApi, -{ - fn client_auth_root_subjects( - &self, - _sni: Option<&DNSName>, - ) -> Option { - Some(rustls::DistinguishedNames::new()) - } - - fn verify_client_cert( - &self, - certs: &[rustls::Certificate], - _sni: Option<&DNSName>, - ) -> Result { - debug!("client cert: {:?}", certs); - let issuer = - certs.get(0).ok_or(rustls::TLSError::NoCertificatesPresented).and_then(|cert| { - cert::parse_cert_issuer(&cert.0) - .map_err(|_| rustls::TLSError::NoCertificatesPresented) - })?; - info!("client signer (issuer) is: 0x{}", hex::encode(issuer)); - - // This call will automatically verify cert is properly signed - if self.skip_ra { - warn!("Skip verifying ra-report"); - return Ok(rustls::ClientCertVerified::assertion()) - } - - if certs.is_empty() { - return Err(rustls::TLSError::NoCertificatesPresented) - } - - #[cfg(feature = "dcap")] - let is_dcap = true; - #[cfg(not(feature = "dcap"))] - let is_dcap = false; - match certs.first() { - Some(cert) => { - match cert::verify_mra_cert(&cert.0, true, is_dcap, &self.attestation_ocall) { - Ok(()) => Ok(rustls::ClientCertVerified::assertion()), - Err(sgx_status_t::SGX_ERROR_UPDATE_NEEDED) => - if self.outdated_ok { - warn!("outdated_ok is set, overriding outdated error"); - Ok(rustls::ClientCertVerified::assertion()) - } else { - Err(rustls::TLSError::WebPKIError(webpki::Error::ExtensionValueInvalid)) - }, - Err(_) => - Err(rustls::TLSError::WebPKIError(webpki::Error::ExtensionValueInvalid)), - } - }, - None => Err(rustls::TLSError::WebPKIError(webpki::Error::ExtensionValueInvalid)), - } - } -} - -pub struct ServerAuth { - outdated_ok: bool, - skip_ra: bool, - attestation_ocall: A, -} - -impl ServerAuth { - pub fn new(outdated_ok: bool, skip_ra: bool, attestation_ocall: A) -> Self { - ServerAuth { outdated_ok, skip_ra, attestation_ocall } - } -} - -impl rustls::ServerCertVerifier for ServerAuth -where - A: EnclaveAttestationOCallApi, -{ - fn verify_server_cert( - &self, - _roots: &rustls::RootCertStore, - certs: &[rustls::Certificate], - _hostname: webpki::DNSNameRef, - _ocsp: &[u8], - ) -> Result { - debug!("server cert: {:?}", certs); - let issuer = - certs.get(0).ok_or(rustls::TLSError::NoCertificatesPresented).and_then(|cert| { - cert::parse_cert_issuer(&cert.0) - .map_err(|_| rustls::TLSError::NoCertificatesPresented) - })?; - info!("server signer (issuer) is: 0x{}", hex::encode(issuer)); - - if self.skip_ra { - warn!("Skip verifying ra-report"); - return Ok(rustls::ServerCertVerified::assertion()) - } - - if certs.is_empty() { - return Err(rustls::TLSError::NoCertificatesPresented) - } - - #[cfg(feature = "dcap")] - let is_dcap = true; - #[cfg(not(feature = "dcap"))] - let is_dcap = false; - // This call will automatically verify cert is properly signed - match certs.first() { - Some(cert) => { - match cert::verify_mra_cert(&cert.0, true, is_dcap, &self.attestation_ocall) { - Ok(()) => Ok(rustls::ServerCertVerified::assertion()), - Err(sgx_status_t::SGX_ERROR_UPDATE_NEEDED) => - if self.outdated_ok { - warn!("outdated_ok is set, overriding outdated error"); - Ok(rustls::ServerCertVerified::assertion()) - } else { - Err(rustls::TLSError::WebPKIError(webpki::Error::ExtensionValueInvalid)) - }, - Err(_) => - Err(rustls::TLSError::WebPKIError(webpki::Error::ExtensionValueInvalid)), - } - }, - None => Err(rustls::TLSError::WebPKIError(webpki::Error::ExtensionValueInvalid)), - } - } -} diff --git a/tee-worker/bitacross/enclave-runtime/src/tls_ra/mocks.rs b/tee-worker/bitacross/enclave-runtime/src/tls_ra/mocks.rs deleted file mode 100644 index 0d5dea4b4c..0000000000 --- a/tee-worker/bitacross/enclave-runtime/src/tls_ra/mocks.rs +++ /dev/null @@ -1,103 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use super::seal_handler::{SealStateAndKeys, UnsealStateAndKeys}; -use crate::error::Result as EnclaveResult; -use itp_types::ShardIdentifier; -use std::{ - sync::{Arc, SgxRwLock as RwLock}, - vec::Vec, -}; - -#[derive(Clone)] -pub struct SealHandlerMock { - pub shielding_key: Arc>>, - pub state_key: Arc>>, - pub state: Arc>>, - pub light_client_state: Arc>>, -} - -impl SealHandlerMock { - pub fn new( - shielding_key: Arc>>, - state_key: Arc>>, - state: Arc>>, - light_client_state: Arc>>, - ) -> Self { - Self { shielding_key, state_key, state, light_client_state } - } -} - -impl SealStateAndKeys for SealHandlerMock { - fn seal_shielding_key(&self, bytes: &[u8]) -> EnclaveResult<()> { - *self.shielding_key.write().unwrap() = bytes.to_vec(); - Ok(()) - } - - fn seal_state_key(&self, bytes: &[u8]) -> EnclaveResult<()> { - *self.state_key.write().unwrap() = bytes.to_vec(); - Ok(()) - } - - fn seal_state(&self, bytes: &[u8], _shard: &ShardIdentifier) -> EnclaveResult<()> { - *self.state.write().unwrap() = bytes.to_vec(); - Ok(()) - } - - fn seal_new_empty_state(&self, _shard: &ShardIdentifier) -> EnclaveResult<()> { - Ok(()) - } - - fn seal_light_client_state(&self, bytes: &[u8]) -> EnclaveResult<()> { - *self.light_client_state.write().unwrap() = bytes.to_vec(); - Ok(()) - } - - fn seal_signers(&self, _bytes: &[u8]) -> EnclaveResult<()> { - Ok(()) - } - - fn seal_enclaves(&self, _bytes: &[u8]) -> EnclaveResult<()> { - Ok(()) - } -} - -impl UnsealStateAndKeys for SealHandlerMock { - fn unseal_shielding_key(&self) -> EnclaveResult> { - Ok(self.shielding_key.read().unwrap().clone()) - } - - fn unseal_state_key(&self) -> EnclaveResult> { - Ok(self.state_key.read().unwrap().clone()) - } - - fn unseal_state(&self, _shard: &ShardIdentifier) -> EnclaveResult> { - Ok(self.state.read().unwrap().clone()) - } - - fn unseal_light_client_state(&self) -> EnclaveResult> { - Ok(self.light_client_state.read().unwrap().clone()) - } - - fn unseal_signers(&self) -> EnclaveResult> { - Ok(vec![]) - } - - fn unseal_enclaves(&self) -> EnclaveResult> { - Ok(vec![]) - } -} diff --git a/tee-worker/bitacross/enclave-runtime/src/tls_ra/mod.rs b/tee-worker/bitacross/enclave-runtime/src/tls_ra/mod.rs deleted file mode 100644 index 3e07960dbe..0000000000 --- a/tee-worker/bitacross/enclave-runtime/src/tls_ra/mod.rs +++ /dev/null @@ -1,85 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -//! Contains all logic of the state provisioning mechanism -//! including the remote attestation and tls / tcp connection part. - -use codec::{Decode, Encode, MaxEncodedLen}; -use itp_types::{AccountId, ShardIdentifier}; - -mod authentication; -pub mod seal_handler; -mod tls_ra_client; -mod tls_ra_server; - -#[cfg(feature = "test")] -pub mod tests; - -#[cfg(feature = "test")] -pub mod mocks; - -/// Header of an accompanied payload. Indicates the -/// length an the type (opcode) of the following payload. -#[derive(Clone, Debug, Decode, Encode, MaxEncodedLen)] -pub struct TcpHeader { - pub opcode: Opcode, - pub payload_length: u64, -} - -impl TcpHeader { - fn new(opcode: Opcode, payload_length: u64) -> Self { - Self { opcode, payload_length } - } -} - -/// Indicates the payload content type. -#[derive(Copy, Clone, Debug, Eq, PartialEq, Decode, Encode, MaxEncodedLen)] -pub enum Opcode { - ShieldingKey, - StateKey, - State, - LightClient, - Signers, - Enclaves, -} - -impl From for Opcode { - fn from(item: u8) -> Self { - match item { - 0 => Opcode::ShieldingKey, - 1 => Opcode::StateKey, - 2 => Opcode::State, - 3 => Opcode::LightClient, - 4 => Opcode::Signers, - 5 => Opcode::Enclaves, - _ => unimplemented!("Unsupported/unknown Opcode for MU-RA exchange"), - } - } -} - -impl Opcode { - pub fn to_bytes(self) -> [u8; 1] { - (self as u8).to_be_bytes() - } -} - -/// The data structure to be sent by the client to request provisioning -#[derive(Clone, Debug, Eq, PartialEq, Decode, Encode, MaxEncodedLen)] -pub struct ClientProvisioningRequest { - pub shard: ShardIdentifier, - pub account: AccountId, -} diff --git a/tee-worker/bitacross/enclave-runtime/src/tls_ra/seal_handler.rs b/tee-worker/bitacross/enclave-runtime/src/tls_ra/seal_handler.rs deleted file mode 100644 index fe0e9947b8..0000000000 --- a/tee-worker/bitacross/enclave-runtime/src/tls_ra/seal_handler.rs +++ /dev/null @@ -1,382 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -//! Abstraction of the reading (unseal) and storing (seal) part of the -//! shielding key, state key and state. - -use crate::error::{Error as EnclaveError, Result as EnclaveResult}; -use bc_enclave_registry::{EnclaveRegistryMap, EnclaveRegistrySealer}; -use bc_signer_registry::{SignerRegistryMap, SignerRegistrySealer}; -use codec::{Decode, Encode}; -use ita_stf::{State as StfState, StateType as StfStateType}; -use itc_parentchain::light_client::LightClientSealing; -use itp_sgx_crypto::{ - key_repository::{AccessKey, MutateKey}, - Aes, -}; -use itp_sgx_externalities::SgxExternalitiesTrait; -use itp_stf_state_handler::handle_state::HandleState; -use itp_types::ShardIdentifier; -use log::*; -use sgx_crypto_helper::rsa3072::Rsa3072KeyPair; -use std::{sync::Arc, vec::Vec}; - -/// Handles the sealing and unsealing of the shielding key, state key and the state. -#[derive(Default)] -pub struct SealHandler< - ShieldingKeyRepository, - StateKeyRepository, - StateHandler, - LightClientSeal, - SignersSeal, - EnclavesSeal, -> { - state_handler: Arc, - state_key_repository: Arc, - shielding_key_repository: Arc, - light_client_seal: Arc, - signers_seal: Arc, - enclaves_seal: Arc, -} - -impl< - ShieldingKeyRepository, - StateKeyRepository, - StateHandler, - LightClientSeal, - SignersSeal, - EnclavesSeal, - > - SealHandler< - ShieldingKeyRepository, - StateKeyRepository, - StateHandler, - LightClientSeal, - SignersSeal, - EnclavesSeal, - > -{ - pub fn new( - state_handler: Arc, - state_key_repository: Arc, - shielding_key_repository: Arc, - light_client_seal: Arc, - signers_seal: Arc, - enclaves_seal: Arc, - ) -> Self { - Self { - state_handler, - state_key_repository, - shielding_key_repository, - light_client_seal, - signers_seal, - enclaves_seal, - } - } -} - -pub trait SealStateAndKeys { - fn seal_shielding_key(&self, bytes: &[u8]) -> EnclaveResult<()>; - fn seal_state_key(&self, bytes: &[u8]) -> EnclaveResult<()>; - fn seal_state(&self, bytes: &[u8], shard: &ShardIdentifier) -> EnclaveResult<()>; - fn seal_new_empty_state(&self, shard: &ShardIdentifier) -> EnclaveResult<()>; - fn seal_light_client_state(&self, bytes: &[u8]) -> EnclaveResult<()>; - fn seal_signers(&self, bytes: &[u8]) -> EnclaveResult<()>; - fn seal_enclaves(&self, bytes: &[u8]) -> EnclaveResult<()>; -} - -pub trait UnsealStateAndKeys { - fn unseal_shielding_key(&self) -> EnclaveResult>; - fn unseal_state_key(&self) -> EnclaveResult>; - fn unseal_state(&self, shard: &ShardIdentifier) -> EnclaveResult>; - fn unseal_light_client_state(&self) -> EnclaveResult>; - fn unseal_signers(&self) -> EnclaveResult>; - fn unseal_enclaves(&self) -> EnclaveResult>; -} - -impl< - ShieldingKeyRepository, - StateKeyRepository, - StateHandler, - LightClientSeal, - SignersSeal, - EnclavesSeal, - > SealStateAndKeys - for SealHandler< - ShieldingKeyRepository, - StateKeyRepository, - StateHandler, - LightClientSeal, - SignersSeal, - EnclavesSeal, - > where - ShieldingKeyRepository: AccessKey + MutateKey, - StateKeyRepository: AccessKey + MutateKey, - StateHandler: HandleState, - LightClientSeal: LightClientSealing, - LightClientSeal::LightClientState: Decode, - SignersSeal: SignerRegistrySealer, - EnclavesSeal: EnclaveRegistrySealer, -{ - fn seal_shielding_key(&self, bytes: &[u8]) -> EnclaveResult<()> { - let key: Rsa3072KeyPair = serde_json::from_slice(bytes).map_err(|e| { - error!(" [Enclave] Received Invalid RSA key"); - EnclaveError::Other(e.into()) - })?; - self.shielding_key_repository.update_key(key)?; - info!("Successfully stored a new shielding key"); - Ok(()) - } - - fn seal_state_key(&self, mut bytes: &[u8]) -> EnclaveResult<()> { - let aes = Aes::decode(&mut bytes)?; - self.state_key_repository.update_key(aes)?; - info!("Successfully stored a new state key"); - Ok(()) - } - - fn seal_state(&self, mut bytes: &[u8], shard: &ShardIdentifier) -> EnclaveResult<()> { - let state = StfStateType::decode(&mut bytes)?; - let state_with_empty_diff = StfState::new(state); - - self.state_handler.reset(state_with_empty_diff, shard)?; - info!("Successfully updated shard {:?} with provisioned state", shard); - Ok(()) - } - - fn seal_light_client_state(&self, mut bytes: &[u8]) -> EnclaveResult<()> { - let state = ::LightClientState::decode(&mut bytes)?; - self.light_client_seal.seal(&state)?; - info!("Successfully sealed light client state"); - Ok(()) - } - - fn seal_signers(&self, mut bytes: &[u8]) -> EnclaveResult<()> { - let state = SignerRegistryMap::decode(&mut bytes)?; - self.signers_seal.seal(state).map_err(|e| { - error!(" [Enclave] Could not seal signers"); - EnclaveError::Other(e.into()) - })?; - info!("Successfully sealed signers state"); - Ok(()) - } - - fn seal_enclaves(&self, mut bytes: &[u8]) -> EnclaveResult<()> { - let state = EnclaveRegistryMap::decode(&mut bytes)?; - self.enclaves_seal.seal(state).map_err(|e| { - error!(" [Enclave] Could not seal enclaves"); - EnclaveError::Other(e.into()) - })?; - info!("Successfully sealed enclaves state"); - Ok(()) - } - - /// Seal an empty, newly initialized state. - /// - /// Requires the shielding key to be sealed and updated before calling this. - /// - /// Call this function in case we don't provision the state itself, only the shielding key. - /// Since the enclave signing account is derived from the shielding key, we need to - /// newly initialize the state with the updated shielding key. - fn seal_new_empty_state(&self, shard: &ShardIdentifier) -> EnclaveResult<()> { - self.state_handler.initialize_shard(*shard)?; - info!("Successfully reset state with new enclave account, for shard {:?}", shard); - Ok(()) - } -} - -impl< - ShieldingKeyRepository, - StateKeyRepository, - StateHandler, - LightClientSeal, - SignerSeal, - EnclavesSeal, - > UnsealStateAndKeys - for SealHandler< - ShieldingKeyRepository, - StateKeyRepository, - StateHandler, - LightClientSeal, - SignerSeal, - EnclavesSeal, - > where - ShieldingKeyRepository: AccessKey + MutateKey, - StateKeyRepository: AccessKey + MutateKey, - StateHandler: HandleState, - LightClientSeal: LightClientSealing, - LightClientSeal::LightClientState: Encode, - SignerSeal: SignerRegistrySealer, - EnclavesSeal: EnclaveRegistrySealer, -{ - fn unseal_shielding_key(&self) -> EnclaveResult> { - let shielding_key = self - .shielding_key_repository - .retrieve_key() - .map_err(|e| EnclaveError::Other(format!("{:?}", e).into()))?; - serde_json::to_vec(&shielding_key).map_err(|e| EnclaveError::Other(e.into())) - } - - fn unseal_state_key(&self) -> EnclaveResult> { - self.state_key_repository - .retrieve_key() - .map(|k| k.encode()) - .map_err(|e| EnclaveError::Other(format!("{:?}", e).into())) - } - - fn unseal_state(&self, shard: &ShardIdentifier) -> EnclaveResult> { - Ok(self.state_handler.execute_on_current(shard, |state, _| state.state.encode())?) - } - - fn unseal_light_client_state(&self) -> EnclaveResult> { - Ok(self.light_client_seal.unseal()?.encode()) - } - - fn unseal_signers(&self) -> EnclaveResult> { - Ok(self - .signers_seal - .unseal() - .map_err(|e| { - error!(" [Enclave] Could not unseal signers"); - EnclaveError::Other(e.into()) - })? - .encode()) - } - - fn unseal_enclaves(&self) -> EnclaveResult> { - Ok(self - .enclaves_seal - .unseal() - .map_err(|e| { - error!(" [Enclave] Could not unseal enclaves"); - EnclaveError::Other(e.into()) - })? - .encode()) - } -} - -#[cfg(feature = "test")] -pub mod test { - use super::*; - use bc_enclave_registry::EnclaveRegistry; - use bc_signer_registry::SignerRegistry; - use itc_parentchain::light_client::mocks::validator_mock_seal::LightValidationStateSealMock; - use itp_sgx_crypto::mocks::KeyRepositoryMock; - use itp_test::mock::handle_state_mock::HandleStateMock; - - type StateKeyRepositoryMock = KeyRepositoryMock; - type ShieldingKeyRepositoryMock = KeyRepositoryMock; - - type SealHandlerMock = SealHandler< - ShieldingKeyRepositoryMock, - StateKeyRepositoryMock, - HandleStateMock, - LightValidationStateSealMock, - SignerRegistry, - EnclaveRegistry, - >; - - pub fn seal_shielding_key_works() { - let seal_handler = SealHandlerMock::default(); - let key_pair_in_bytes = serde_json::to_vec(&Rsa3072KeyPair::default()).unwrap(); - - let result = seal_handler.seal_shielding_key(&key_pair_in_bytes); - - assert!(result.is_ok()); - } - - pub fn seal_shielding_key_fails_for_invalid_key() { - let seal_handler = SealHandlerMock::default(); - - let result = seal_handler.seal_shielding_key(&[1, 2, 3]); - - assert!(result.is_err()); - } - - pub fn unseal_seal_shielding_key_works() { - let seal_handler = SealHandlerMock::default(); - - let key_pair_in_bytes = seal_handler.unseal_shielding_key().unwrap(); - - let result = seal_handler.seal_shielding_key(&key_pair_in_bytes); - - assert!(result.is_ok()); - } - - pub fn seal_state_key_works() { - let seal_handler = SealHandlerMock::default(); - let key_pair_in_bytes = Aes::default().encode(); - - let result = seal_handler.seal_state_key(&key_pair_in_bytes); - - assert!(result.is_ok()); - } - - pub fn seal_state_key_fails_for_invalid_key() { - let seal_handler = SealHandlerMock::default(); - - let result = seal_handler.seal_state_key(&[1, 2, 3]); - - assert!(result.is_err()); - } - - pub fn unseal_seal_state_key_works() { - let seal_handler = SealHandlerMock::default(); - let key_pair_in_bytes = seal_handler.unseal_state_key().unwrap(); - - let result = seal_handler.seal_state_key(&key_pair_in_bytes); - - assert!(result.is_ok()); - } - - pub fn seal_state_works() { - let seal_handler = SealHandlerMock::default(); - let state = ::StateT::default(); - let shard = ShardIdentifier::default(); - let _init_hash = seal_handler.state_handler.initialize_shard(shard).unwrap(); - - let result = seal_handler.seal_state(&state.encode(), &shard); - - assert!(result.is_ok()); - } - - pub fn seal_state_fails_for_invalid_state() { - let seal_handler = SealHandlerMock::default(); - let shard = ShardIdentifier::default(); - - let result = seal_handler.seal_state(&[1, 0, 3], &shard); - - assert!(result.is_err()); - } - - pub fn unseal_seal_state_works() { - let seal_handler = SealHandlerMock::default(); - let shard = ShardIdentifier::default(); - seal_handler.state_handler.initialize_shard(shard).unwrap(); - // Fill our mock state: - let (lock, mut state) = seal_handler.state_handler.load_for_mutation(&shard).unwrap(); - let (key, value) = ("my_key", "my_value"); - state.insert(key.encode(), value.encode()); - seal_handler.state_handler.write_after_mutation(state, lock, &shard).unwrap(); - - let state_in_bytes = seal_handler.unseal_state(&shard).unwrap(); - - let result = seal_handler.seal_state(&state_in_bytes, &shard); - - assert!(result.is_ok()); - } -} diff --git a/tee-worker/bitacross/enclave-runtime/src/tls_ra/tests.rs b/tee-worker/bitacross/enclave-runtime/src/tls_ra/tests.rs deleted file mode 100644 index a96ec8cb11..0000000000 --- a/tee-worker/bitacross/enclave-runtime/src/tls_ra/tests.rs +++ /dev/null @@ -1,201 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -//! Tests of tls-ra client / server communication. - -use super::{ - mocks::SealHandlerMock, tls_ra_client::request_state_provisioning_internal, - tls_ra_server::run_state_provisioning_server_internal, -}; -use crate::{ - initialization::global_components::EnclaveStf, - tls_ra::seal_handler::{SealHandler, SealStateAndKeys, UnsealStateAndKeys}, -}; -use bc_enclave_registry::EnclaveRegistry; -use bc_signer_registry::SignerRegistry; -use ita_stf::State; -use itc_parentchain::light_client::mocks::validator_mock_seal::LightValidationStateSealMock; -use itp_sgx_crypto::{mocks::KeyRepositoryMock, Aes}; -use itp_stf_interface::InitState; -use itp_stf_primitives::types::AccountId; -use itp_stf_state_handler::handle_state::HandleState; -use itp_test::mock::handle_state_mock::HandleStateMock; -use itp_types::ShardIdentifier; -use sgx_crypto_helper::{rsa3072::Rsa3072KeyPair, RsaKeyPair}; -use sgx_types::{sgx_quote_sign_type_t, sgx_target_info_t}; -use std::{ - net::{TcpListener, TcpStream}, - os::unix::io::AsRawFd, - string::String, - sync::{Arc, SgxRwLock as RwLock}, - thread, - time::Duration, - vec::Vec, -}; - -static SIGN_TYPE: sgx_quote_sign_type_t = sgx_quote_sign_type_t::SGX_UNLINKABLE_SIGNATURE; -static SKIP_RA: i32 = 1; -static QUOTE_SIZE: u32 = 0; - -fn run_state_provisioning_server(seal_handler: impl UnsealStateAndKeys, port: u16) { - let listener = TcpListener::bind(server_addr(port)).unwrap(); - - let (socket, _addr) = listener.accept().unwrap(); - let sgx_target_info: sgx_target_info_t = sgx_target_info_t::default(); - run_state_provisioning_server_internal::<_>( - socket.as_raw_fd(), - SIGN_TYPE, - Some(&sgx_target_info), - Some("E_SIZE), - SKIP_RA, - seal_handler, - ) - .unwrap(); -} - -fn server_addr(port: u16) -> String { - format!("127.0.0.1:{}", port) -} - -pub fn test_tls_ra_server_client_networking() { - let shard = ShardIdentifier::default(); - let client_account = AccountId::from([42; 32]); - let shielding_key_encoded = vec![1, 2, 3]; - let state_key_encoded = vec![5, 2, 3, 7]; - let state_encoded = Vec::from([1u8; 26000]); // Have a decently sized state, so read() must be called multiple times. - let light_client_state_encoded = Vec::from([1u8; 10000]); // Have a decently sized state, so read() must be called multiple times. - - let server_seal_handler = SealHandlerMock::new( - Arc::new(RwLock::new(shielding_key_encoded.clone())), - Arc::new(RwLock::new(state_key_encoded.clone())), - Arc::new(RwLock::new(state_encoded.clone())), - Arc::new(RwLock::new(light_client_state_encoded.clone())), - ); - let initial_client_state = vec![0, 0, 1]; - let initial_client_state_key = vec![0, 0, 2]; - let initial_client_light_client_state = vec![0, 0, 3]; - let client_shielding_key = Arc::new(RwLock::new(Vec::new())); - let client_state_key = Arc::new(RwLock::new(initial_client_state_key.clone())); - let client_state = Arc::new(RwLock::new(initial_client_state.clone())); - let client_light_client_state = Arc::new(RwLock::new(initial_client_light_client_state)); - - let client_seal_handler = SealHandlerMock::new( - client_shielding_key.clone(), - client_state_key.clone(), - client_state.clone(), - client_light_client_state.clone(), - ); - - let port: u16 = 3149; - - // Start server. - let server_thread_handle = thread::spawn(move || { - run_state_provisioning_server(server_seal_handler, port); - }); - thread::sleep(Duration::from_secs(1)); - - // Start client. - let socket = TcpStream::connect(server_addr(port)).unwrap(); - let sgx_target_info: sgx_target_info_t = sgx_target_info_t::default(); - let result = request_state_provisioning_internal( - socket.as_raw_fd(), - SIGN_TYPE, - Some(&sgx_target_info), - Some("E_SIZE), - shard, - SKIP_RA, - client_seal_handler, - client_account, - ); - - // Ensure server thread has finished. - server_thread_handle.join().unwrap(); - - assert!(result.is_ok()); - assert_eq!(*client_shielding_key.read().unwrap(), shielding_key_encoded); - assert_eq!(*client_light_client_state.read().unwrap(), light_client_state_encoded); - - // Sidechain or OffchainWorker - assert_eq!(*client_state.read().unwrap(), state_encoded); - assert_eq!(*client_state_key.read().unwrap(), state_key_encoded); -} - -// Test state and key provisioning with 'real' data structures. -pub fn test_state_and_key_provisioning() { - let client_account = AccountId::from([42; 32]); - let state_key = Aes::new([3u8; 16], [0u8; 16]); - let shielding_key = Rsa3072KeyPair::new().unwrap(); - let initialized_state = EnclaveStf::init_state(AccountId::new([1u8; 32])); - let shard = ShardIdentifier::from([1u8; 32]); - - let server_seal_handler = - create_seal_handler(state_key, shielding_key, initialized_state, &shard); - let client_seal_handler = - create_seal_handler(Aes::default(), Rsa3072KeyPair::default(), State::default(), &shard); - - let port: u16 = 3150; - - // Start server. - let server_thread_handle = thread::spawn(move || { - run_state_provisioning_server(server_seal_handler, port); - }); - thread::sleep(Duration::from_secs(1)); - - // Start client. - let socket = TcpStream::connect(server_addr(port)).unwrap(); - let sgx_target_info: sgx_target_info_t = sgx_target_info_t::default(); - let result = request_state_provisioning_internal( - socket.as_raw_fd(), - SIGN_TYPE, - Some(&sgx_target_info), - Some("E_SIZE), - shard, - SKIP_RA, - client_seal_handler, - client_account, - ); - - // Ensure server thread has finished. - server_thread_handle.join().unwrap(); - - assert!(result.is_ok()); -} - -fn create_seal_handler( - state_key: Aes, - shielding_key: Rsa3072KeyPair, - state: State, - shard: &ShardIdentifier, -) -> impl UnsealStateAndKeys + SealStateAndKeys { - let state_key_repository = Arc::new(KeyRepositoryMock::::new(state_key)); - let shielding_key_repository = - Arc::new(KeyRepositoryMock::::new(shielding_key)); - let state_handler = Arc::new(HandleStateMock::default()); - state_handler.reset(state, shard).unwrap(); - let seal = Arc::new(LightValidationStateSealMock::new()); - let signer_sealer: Arc = Default::default(); - let enclave_sealer: Arc = Default::default(); - - SealHandler::new( - state_handler, - state_key_repository, - shielding_key_repository, - seal, - signer_sealer, - enclave_sealer, - ) -} diff --git a/tee-worker/bitacross/enclave-runtime/src/tls_ra/tls_ra_client.rs b/tee-worker/bitacross/enclave-runtime/src/tls_ra/tls_ra_client.rs deleted file mode 100644 index 0d6aac53c9..0000000000 --- a/tee-worker/bitacross/enclave-runtime/src/tls_ra/tls_ra_client.rs +++ /dev/null @@ -1,357 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -//! Implementation of the client part of the state provisioning. - -use super::{authentication::ServerAuth, Opcode, TcpHeader}; -use crate::{ - attestation::create_ra_report_and_signature, - error::{Error as EnclaveError, Result as EnclaveResult}, - initialization::global_components::{ - EnclaveSealHandler, GLOBAL_INTEGRITEE_PARENTCHAIN_LIGHT_CLIENT_SEAL, - GLOBAL_SHIELDING_KEY_REPOSITORY_COMPONENT, GLOBAL_SIGNER_REGISTRY, - GLOBAL_STATE_KEY_REPOSITORY_COMPONENT, - }, - ocall::OcallApi, - shard_config::init_shard_config, - tls_ra::{seal_handler::SealStateAndKeys, ClientProvisioningRequest}, - GLOBAL_SIGNING_KEY_REPOSITORY_COMPONENT, GLOBAL_STATE_HANDLER_COMPONENT, -}; -use codec::Encode; - -use itp_attestation_handler::{RemoteAttestationType, DEV_HOSTNAME}; -use itp_component_container::ComponentGetter; - -use itp_ocall_api::EnclaveAttestationOCallApi; -use itp_sgx_crypto::key_repository::AccessPubkey; -use itp_types::{AccountId, ShardIdentifier}; - -use crate::initialization::global_components::GLOBAL_ENCLAVE_REGISTRY; -use log::*; -use rustls::{ClientConfig, ClientSession, Stream}; -use sgx_types::*; -use std::{ - backtrace::{self, PrintFormat}, - convert::TryInto, - io::{Read, Write}, - net::TcpStream, - slice, - sync::Arc, - vec::Vec, -}; -/// Client part of the TCP-level connection and the underlying TLS-level session. -/// -/// Includes a seal handler, which handles the storage part of the received data. -struct TlsClient<'a, StateAndKeySealer> -where - StateAndKeySealer: SealStateAndKeys, -{ - tls_stream: Stream<'a, ClientSession, TcpStream>, - seal_handler: StateAndKeySealer, - shard: ShardIdentifier, -} - -impl<'a, StateAndKeySealer> TlsClient<'a, StateAndKeySealer> -where - StateAndKeySealer: SealStateAndKeys, -{ - fn new( - tls_stream: Stream<'a, ClientSession, TcpStream>, - seal_handler: StateAndKeySealer, - shard: ShardIdentifier, - ) -> TlsClient { - TlsClient { tls_stream, seal_handler, shard } - } - - /// Read all data sent by the server of the specific shard. - /// - /// We trust here that the server sends us the correct data, as - /// we do not have any way to test it. - fn obtain_provisioning_for_shard(&mut self, account: AccountId) -> EnclaveResult<()> { - debug!( - "obtain_provisioning_for_shard called, about to call self.send_provisioning_request()." - ); - self.send_provisioning_request(account)?; - debug!("self.send_provisioning_request() succeeded."); - self.read_and_seal_all() - } - - /// Send the shard of the state we want to receive to the provisioning server. - fn send_provisioning_request(&mut self, account: AccountId) -> EnclaveResult<()> { - debug!("self.send_provisioning_request() called."); - self.tls_stream - .write_all(&ClientProvisioningRequest { shard: self.shard, account }.encode())?; - debug!("write_all succeeded."); - Ok(()) - } - - /// Read and seal all relevant data sent by the server. - fn read_and_seal_all(&mut self) -> EnclaveResult<()> { - let mut received_payloads: Vec = Vec::new(); - - loop { - let maybe_opcode = self.read_and_seal()?; - match maybe_opcode { - None => break, - Some(o) => { - received_payloads.push(o); - }, - } - } - info!("Successfully read and sealed all data sent by the state provisioning server."); - - // In case we receive a shielding key, but no state, we need to reset our state - // to update the enclave account. - if received_payloads.contains(&Opcode::ShieldingKey) - && !received_payloads.contains(&Opcode::State) - { - self.seal_handler.seal_new_empty_state(&self.shard)?; - } - - Ok(()) - } - - /// Read a server header / payload pair and directly seal the received data. - fn read_and_seal(&mut self) -> EnclaveResult> { - let mut start_byte = [0u8; 1]; - let read_size = self.tls_stream.read(&mut start_byte)?; - // If we're reading but there's no data: EOF. - if read_size == 0 { - return Ok(None) - } - let header = self.read_header(start_byte[0])?; - let bytes = self.read_until(header.payload_length as usize)?; - match header.opcode { - Opcode::ShieldingKey => self.seal_handler.seal_shielding_key(&bytes)?, - Opcode::StateKey => self.seal_handler.seal_state_key(&bytes)?, - Opcode::State => self.seal_handler.seal_state(&bytes, &self.shard)?, - Opcode::LightClient => self.seal_handler.seal_light_client_state(&bytes)?, - Opcode::Signers => self.seal_handler.seal_signers(&bytes)?, - Opcode::Enclaves => self.seal_handler.seal_enclaves(&bytes)?, - }; - Ok(Some(header.opcode)) - } - - /// Reads the payload header, indicating the sent payload length and type. - fn read_header(&mut self, start_byte: u8) -> EnclaveResult { - debug!("Read first byte: {:?}", start_byte); - // The first sent byte indicates the payload type. - let opcode: Opcode = start_byte - .try_into() - .map_err(|_| EnclaveError::Other("Could not convert opcode".into()))?; - debug!("Read header opcode: {:?}", opcode); - // The following bytes contain the payload length, which is a u64. - let mut payload_length_buffer = [0u8; std::mem::size_of::()]; - self.tls_stream.read_exact(&mut payload_length_buffer)?; - let payload_length = u64::from_be_bytes(payload_length_buffer); - debug!("Payload length of {:?}: {}", opcode, payload_length); - - Ok(TcpHeader::new(opcode, payload_length)) - } - - /// Read all bytes into a buffer of given length. - fn read_until(&mut self, length: usize) -> EnclaveResult> { - let mut bytes = vec![0u8; length]; - self.tls_stream.read_exact(&mut bytes)?; - Ok(bytes) - } -} - -#[no_mangle] -pub unsafe extern "C" fn request_state_provisioning( - socket_fd: c_int, - sign_type: sgx_quote_sign_type_t, - quoting_enclave_target_info: Option<&sgx_target_info_t>, - quote_size: Option<&u32>, - shard: *const u8, - shard_size: u32, - skip_ra: c_int, -) -> sgx_status_t { - let _ = backtrace::enable_backtrace("enclave.signed.so", PrintFormat::Short); - let shard = ShardIdentifier::from_slice(slice::from_raw_parts(shard, shard_size as usize)); - - let state_handler = match GLOBAL_STATE_HANDLER_COMPONENT.get() { - Ok(s) => s, - Err(e) => { - error!("{:?}", e); - return sgx_status_t::SGX_ERROR_UNEXPECTED - }, - }; - - let state_key_repository = match GLOBAL_STATE_KEY_REPOSITORY_COMPONENT.get() { - Ok(s) => s, - Err(e) => { - error!("{:?}", e); - return sgx_status_t::SGX_ERROR_UNEXPECTED - }, - }; - - let shielding_key_repository = match GLOBAL_SHIELDING_KEY_REPOSITORY_COMPONENT.get() { - Ok(s) => s, - Err(e) => { - error!("{:?}", e); - return sgx_status_t::SGX_ERROR_UNEXPECTED - }, - }; - - let light_client_seal = match GLOBAL_INTEGRITEE_PARENTCHAIN_LIGHT_CLIENT_SEAL.get() { - Ok(s) => s, - Err(e) => { - error!("{:?}", e); - return sgx_status_t::SGX_ERROR_UNEXPECTED - }, - }; - - let signer_registry = match GLOBAL_SIGNER_REGISTRY.get() { - Ok(s) => s, - Err(e) => { - error!("{:?}", e); - return sgx_status_t::SGX_ERROR_UNEXPECTED - }, - }; - let enclave_registry = match GLOBAL_ENCLAVE_REGISTRY.get() { - Ok(s) => s, - Err(e) => { - error!("{:?}", e); - return sgx_status_t::SGX_ERROR_UNEXPECTED - }, - }; - - let seal_handler = EnclaveSealHandler::new( - state_handler, - state_key_repository, - shielding_key_repository, - light_client_seal, - signer_registry, - enclave_registry, - ); - - let signing_key_repository = match GLOBAL_SIGNING_KEY_REPOSITORY_COMPONENT.get() { - Ok(s) => s, - Err(e) => { - error!("{:?}", e); - return sgx_status_t::SGX_ERROR_UNEXPECTED - }, - }; - - let client_account = match signing_key_repository.retrieve_pubkey() { - Ok(s) => AccountId::from(s), - Err(e) => return e.into(), - }; - - if let Err(e) = request_state_provisioning_internal( - socket_fd, - sign_type, - quoting_enclave_target_info, - quote_size, - shard, - skip_ra, - seal_handler, - client_account, - ) { - error!("Failed to sync state due to: {:?}", e); - return e.into() - }; - - // fixme: this needs only be called in sidechain mode. no harm though - if let Err(e) = init_shard_config(shard) { - error!("touch shard error: {:?}", e); - return sgx_status_t::SGX_ERROR_UNEXPECTED - } - sgx_status_t::SGX_SUCCESS -} - -/// Internal [`request_state_provisioning`] function to be able to use the handy `?` operator. -// allowing clippy rant because this fn will be refactored with MU RA deprecation -#[allow(clippy::too_many_arguments)] -pub(crate) fn request_state_provisioning_internal( - socket_fd: c_int, - sign_type: sgx_quote_sign_type_t, - quoting_enclave_target_info: Option<&sgx_target_info_t>, - quote_size: Option<&u32>, - shard: ShardIdentifier, - skip_ra: c_int, - seal_handler: StateAndKeySealer, - client_account: AccountId, -) -> EnclaveResult<()> { - debug!("Client config generate..."); - let client_config = tls_client_config( - sign_type, - quoting_enclave_target_info, - quote_size, - OcallApi, - skip_ra == 1, - )?; - debug!("Client config retrieved"); - let (mut client_session, mut tcp_stream) = tls_client_session_stream(socket_fd, client_config)?; - debug!("Client sesssion established."); - - let mut client = TlsClient::new( - rustls::Stream::new(&mut client_session, &mut tcp_stream), - seal_handler, - shard, - ); - - info!("Requesting keys and state from mu-ra server of fellow validateer"); - client.obtain_provisioning_for_shard(client_account) -} - -fn tls_client_config( - sign_type: sgx_quote_sign_type_t, - quoting_enclave_target_info: Option<&sgx_target_info_t>, - quote_size: Option<&u32>, - ocall_api: A, - skip_ra: bool, -) -> EnclaveResult { - #[cfg(not(feature = "dcap"))] - let attestation_type = RemoteAttestationType::Epid; - #[cfg(feature = "dcap")] - let attestation_type = RemoteAttestationType::Dcap; - - // report will be signed with client enclave ed25519 signing key - let (key_der, cert_der) = create_ra_report_and_signature( - skip_ra, - attestation_type, - sign_type, - quoting_enclave_target_info, - quote_size, - )?; - debug!("got key_der and cert_der"); - - let mut cfg = rustls::ClientConfig::new(); - let certs = vec![rustls::Certificate(cert_der)]; - let privkey = rustls::PrivateKey(key_der); - #[allow(clippy::unwrap_used)] - cfg.set_single_client_cert(certs, privkey).unwrap(); - // ServerAuth will perform MU RA as part of authentication process - cfg.dangerous() - .set_certificate_verifier(Arc::new(ServerAuth::new(true, skip_ra, ocall_api))); - cfg.versions.clear(); - cfg.versions.push(rustls::ProtocolVersion::TLSv1_2); - Ok(cfg) -} - -fn tls_client_session_stream( - socket_fd: i32, - client_config: ClientConfig, -) -> EnclaveResult<(ClientSession, TcpStream)> { - let dns_name = webpki::DNSNameRef::try_from_ascii_str(DEV_HOSTNAME) - .map_err(|e| EnclaveError::Other(e.into()))?; - let sess = rustls::ClientSession::new(&Arc::new(client_config), dns_name); - let conn = TcpStream::new(socket_fd)?; - Ok((sess, conn)) -} diff --git a/tee-worker/bitacross/enclave-runtime/src/tls_ra/tls_ra_server.rs b/tee-worker/bitacross/enclave-runtime/src/tls_ra/tls_ra_server.rs deleted file mode 100644 index a047b821f1..0000000000 --- a/tee-worker/bitacross/enclave-runtime/src/tls_ra/tls_ra_server.rs +++ /dev/null @@ -1,340 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -//! Implementation of the server part of the state provisioning. - -use super::{authentication::ClientAuth, ClientProvisioningRequest, Opcode, TcpHeader}; -use crate::{ - attestation::create_ra_report_and_signature, - error::{Error as EnclaveError, Result as EnclaveResult}, - initialization::global_components::{ - EnclaveSealHandler, GLOBAL_INTEGRITEE_PARENTCHAIN_LIGHT_CLIENT_SEAL, - GLOBAL_SHIELDING_KEY_REPOSITORY_COMPONENT, GLOBAL_SIGNER_REGISTRY, - GLOBAL_STATE_KEY_REPOSITORY_COMPONENT, - }, - ocall::OcallApi, - tls_ra::seal_handler::UnsealStateAndKeys, - GLOBAL_STATE_HANDLER_COMPONENT, -}; - -use crate::initialization::global_components::GLOBAL_ENCLAVE_REGISTRY; -use codec::Decode; -use itp_attestation_handler::RemoteAttestationType; -use itp_component_container::ComponentGetter; -use itp_ocall_api::EnclaveAttestationOCallApi; -use itp_types::ShardIdentifier; -use litentry_primitives::WorkerMode; -use log::*; -use rustls::{ServerConfig, ServerSession, StreamOwned}; -use sgx_types::*; -use std::{ - backtrace::{self, PrintFormat}, - io::{Read, Write}, - net::TcpStream, - sync::Arc, -}; - -#[allow(dead_code)] -#[derive(Clone, Eq, PartialEq, Debug)] -enum ProvisioningPayload { - Everything, - ShieldingKeyAndLightClient, -} - -impl From for ProvisioningPayload { - fn from(m: WorkerMode) -> Self { - match m { - WorkerMode::OffChainWorker => ProvisioningPayload::Everything, - WorkerMode::Sidechain => ProvisioningPayload::Everything, - } - } -} - -/// Server part of the TCP-level connection and the underlying TLS-level session. -/// -/// Includes a seal handler, which handles the reading part of the data to be sent. -struct TlsServer { - tls_stream: StreamOwned, - seal_handler: StateAndKeyUnsealer, - provisioning_payload: ProvisioningPayload, -} - -impl TlsServer -where - StateAndKeyUnsealer: UnsealStateAndKeys, -{ - fn new( - tls_stream: StreamOwned, - seal_handler: StateAndKeyUnsealer, - provisioning_payload: ProvisioningPayload, - ) -> Self { - Self { tls_stream, seal_handler, provisioning_payload } - } - - /// Sends all relevant data of the specific shard to the client. - fn handle_shard_request_from_client(&mut self) -> EnclaveResult<()> { - println!( - " [Enclave] (MU-RA-Server) handle_shard_request_from_client, calling read_shard()" - ); - let request = self.await_shard_request_from_client()?; - println!(" [Enclave] (MU-RA-Server) handle_shard_request_from_client, await_shard_request_from_client() OK"); - println!(" [Enclave] (MU-RA-Server) handle_shard_request_from_client, write_all()"); - self.write_provisioning_payloads(&request.shard) - } - - /// Read the shard of the state the client wants to receive. - fn await_shard_request_from_client(&mut self) -> EnclaveResult { - let mut request = [0u8; std::mem::size_of::()]; - println!( - " [Enclave] (MU-RA-Server) await_shard_request_from_client, calling read_exact()" - ); - self.tls_stream.read_exact(&mut request)?; - ClientProvisioningRequest::decode(&mut request.as_slice()) - .map_err(|_| EnclaveError::Other("matching byte size can't fail to decode".into())) - } - - /// Sends all relevant data to the client. - fn write_provisioning_payloads(&mut self, shard: &ShardIdentifier) -> EnclaveResult<()> { - debug!("Provisioning is set to: {:?}", self.provisioning_payload); - match self.provisioning_payload { - ProvisioningPayload::Everything => { - self.write_shielding_key()?; - self.write_signers()?; - self.write_enclaves()?; - self.write_state_key()?; - self.write_state(shard)?; - self.write_light_client_state()?; - }, - ProvisioningPayload::ShieldingKeyAndLightClient => { - self.write_shielding_key()?; - self.write_light_client_state()?; - }, - } - - debug!("Successfully provisioned all payloads to peer"); - Ok(()) - } - - fn write_shielding_key(&mut self) -> EnclaveResult<()> { - let shielding_key = self.seal_handler.unseal_shielding_key()?; - self.write(Opcode::ShieldingKey, &shielding_key)?; - Ok(()) - } - - fn write_signers(&mut self) -> EnclaveResult<()> { - let signers = self.seal_handler.unseal_signers()?; - self.write(Opcode::Signers, &signers)?; - Ok(()) - } - - fn write_enclaves(&mut self) -> EnclaveResult<()> { - let enclaves = self.seal_handler.unseal_enclaves()?; - self.write(Opcode::Enclaves, &enclaves)?; - Ok(()) - } - - fn write_state_key(&mut self) -> EnclaveResult<()> { - let state_key = self.seal_handler.unseal_state_key()?; - self.write(Opcode::StateKey, &state_key)?; - Ok(()) - } - - fn write_state(&mut self, shard: &ShardIdentifier) -> EnclaveResult<()> { - let state = self.seal_handler.unseal_state(shard)?; - self.write(Opcode::State, &state)?; - Ok(()) - } - - fn write_light_client_state(&mut self) -> EnclaveResult<()> { - let state = self.seal_handler.unseal_light_client_state()?; - self.write(Opcode::LightClient, &state)?; - Ok(()) - } - - /// Sends the header followed by the payload. - fn write(&mut self, opcode: Opcode, bytes: &[u8]) -> EnclaveResult<()> { - let payload_length = bytes.len() as u64; - self.write_header(TcpHeader::new(opcode, payload_length))?; - debug!("Write payload - opcode: {:?}, payload_length: {}", opcode, payload_length); - self.tls_stream.write_all(bytes)?; - Ok(()) - } - - /// Sends the header which includes the payload length and the Opcode indicating the payload type. - fn write_header(&mut self, tcp_header: TcpHeader) -> EnclaveResult<()> { - self.tls_stream.write_all(&tcp_header.opcode.to_bytes())?; - self.tls_stream.write_all(&tcp_header.payload_length.to_be_bytes())?; - debug!( - "Write header - opcode: {:?}, payload length: {}", - tcp_header.opcode, tcp_header.payload_length - ); - Ok(()) - } -} - -#[no_mangle] -pub unsafe extern "C" fn run_state_provisioning_server( - socket_fd: c_int, - sign_type: sgx_quote_sign_type_t, - quoting_enclave_target_info: Option<&sgx_target_info_t>, - quote_size: Option<&u32>, - skip_ra: c_int, -) -> sgx_status_t { - let _ = backtrace::enable_backtrace("enclave.signed.so", PrintFormat::Short); - - let state_handler = match GLOBAL_STATE_HANDLER_COMPONENT.get() { - Ok(s) => s, - Err(e) => { - error!("{:?}", e); - return sgx_status_t::SGX_ERROR_UNEXPECTED - }, - }; - - let state_key_repository = match GLOBAL_STATE_KEY_REPOSITORY_COMPONENT.get() { - Ok(s) => s, - Err(e) => { - error!("{:?}", e); - return sgx_status_t::SGX_ERROR_UNEXPECTED - }, - }; - - let shielding_key_repository = match GLOBAL_SHIELDING_KEY_REPOSITORY_COMPONENT.get() { - Ok(s) => s, - Err(e) => { - error!("{:?}", e); - return sgx_status_t::SGX_ERROR_UNEXPECTED - }, - }; - - let light_client_seal = match GLOBAL_INTEGRITEE_PARENTCHAIN_LIGHT_CLIENT_SEAL.get() { - Ok(s) => s, - Err(e) => { - error!("{:?}", e); - return sgx_status_t::SGX_ERROR_UNEXPECTED - }, - }; - - let signer_registry = match GLOBAL_SIGNER_REGISTRY.get() { - Ok(s) => s, - Err(e) => { - error!("{:?}", e); - return sgx_status_t::SGX_ERROR_UNEXPECTED - }, - }; - let enclave_registry = match GLOBAL_ENCLAVE_REGISTRY.get() { - Ok(s) => s, - Err(e) => { - error!("{:?}", e); - return sgx_status_t::SGX_ERROR_UNEXPECTED - }, - }; - - let seal_handler = EnclaveSealHandler::new( - state_handler, - state_key_repository, - shielding_key_repository, - light_client_seal, - signer_registry, - enclave_registry, - ); - - if let Err(e) = run_state_provisioning_server_internal::<_>( - socket_fd, - sign_type, - quoting_enclave_target_info, - quote_size, - skip_ra, - seal_handler, - ) { - error!("Failed to provision state due to: {:?}", e); - return e.into() - }; - - sgx_status_t::SGX_SUCCESS -} - -/// Internal [`run_state_provisioning_server`] function to be able to use the handy `?` operator. -pub(crate) fn run_state_provisioning_server_internal( - socket_fd: c_int, - sign_type: sgx_quote_sign_type_t, - quoting_enclave_target_info: Option<&sgx_target_info_t>, - quote_size: Option<&u32>, - skip_ra: c_int, - seal_handler: StateAndKeyUnsealer, -) -> EnclaveResult<()> { - let server_config = tls_server_config( - sign_type, - quoting_enclave_target_info, - quote_size, - OcallApi, - skip_ra == 1, - )?; - let (server_session, tcp_stream) = tls_server_session_stream(socket_fd, server_config)?; - - let provisioning = ProvisioningPayload::Everything; - - let mut server = - TlsServer::new(StreamOwned::new(server_session, tcp_stream), seal_handler, provisioning); - - // todo: verify client signer belongs to a registered enclave on integritee network with a - // matching or whitelisted MRENCLAVE as replacement for MU RA #1385 - - println!(" [Enclave] (MU-RA-Server) MU-RA successful sending keys"); - println!( - " [Enclave] (MU-RA-Server) MU-RA successful, calling handle_shard_request_from_client()" - ); - server.handle_shard_request_from_client() -} - -fn tls_server_session_stream( - socket_fd: i32, - server_config: ServerConfig, -) -> EnclaveResult<(ServerSession, TcpStream)> { - let sess = ServerSession::new(&Arc::new(server_config)); - let conn = TcpStream::new(socket_fd).map_err(|e| EnclaveError::Other(e.into()))?; - Ok((sess, conn)) -} - -fn tls_server_config( - sign_type: sgx_quote_sign_type_t, - quoting_enclave_target_info: Option<&sgx_target_info_t>, - quote_size: Option<&u32>, - ocall_api: A, - skip_ra: bool, -) -> EnclaveResult { - #[cfg(not(feature = "dcap"))] - let attestation_type = RemoteAttestationType::Epid; - #[cfg(feature = "dcap")] - let attestation_type = RemoteAttestationType::Dcap; - - // report will be signed with server enclave ed25519 signing key - let (key_der, cert_der) = create_ra_report_and_signature( - skip_ra, - attestation_type, - sign_type, - quoting_enclave_target_info, - quote_size, - )?; - - // ClientAuth will perform MU RA as part of authentication process - let mut cfg = rustls::ServerConfig::new(Arc::new(ClientAuth::new(true, skip_ra, ocall_api))); - let certs = vec![rustls::Certificate(cert_der)]; - let privkey = rustls::PrivateKey(key_der); - cfg.set_single_cert_with_ocsp_and_sct(certs, privkey, vec![], vec![]) - .map_err(|e| EnclaveError::Other(e.into()))?; - Ok(cfg) -} diff --git a/tee-worker/bitacross/enclave-runtime/src/utils.rs b/tee-worker/bitacross/enclave-runtime/src/utils.rs deleted file mode 100644 index 03fb776de0..0000000000 --- a/tee-worker/bitacross/enclave-runtime/src/utils.rs +++ /dev/null @@ -1,126 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ -use crate::{ - error::{Error, Result}, - initialization::global_components::{ - EnclaveExtrinsicsFactory, EnclaveNodeMetadataRepository, EnclaveValidatorAccessor, - GLOBAL_INTEGRITEE_PARACHAIN_HANDLER_COMPONENT, - GLOBAL_INTEGRITEE_SOLOCHAIN_HANDLER_COMPONENT, GLOBAL_TARGET_A_PARACHAIN_HANDLER_COMPONENT, - GLOBAL_TARGET_A_SOLOCHAIN_HANDLER_COMPONENT, GLOBAL_TARGET_B_PARACHAIN_HANDLER_COMPONENT, - GLOBAL_TARGET_B_SOLOCHAIN_HANDLER_COMPONENT, - }, -}; -use codec::{Decode, Input}; -use itp_component_container::ComponentGetter; -use std::{result::Result as StdResult, slice, sync::Arc}; - -/// Helper trait to transform the sgx-ffi pointers to any type that implements -/// `parity-scale-codec::Decode` -pub unsafe trait DecodeRaw { - /// the type to decode into - type Decoded: Decode; - - unsafe fn decode_raw<'a, T>( - data: *const T, - len: usize, - ) -> StdResult - where - T: 'a, - &'a [T]: Input; -} - -unsafe impl DecodeRaw for D { - type Decoded = D; - - unsafe fn decode_raw<'a, T>( - data: *const T, - len: usize, - ) -> StdResult - where - T: 'a, - &'a [T]: Input, - { - let mut s = slice::from_raw_parts(data, len); - - Decode::decode(&mut s) - } -} - -pub(crate) fn get_validator_accessor_from_integritee_solo_or_parachain( -) -> Result> { - let validator_accessor = - if let Ok(solochain_handler) = GLOBAL_INTEGRITEE_SOLOCHAIN_HANDLER_COMPONENT.get() { - solochain_handler.validator_accessor.clone() - } else if let Ok(parachain_handler) = GLOBAL_INTEGRITEE_PARACHAIN_HANDLER_COMPONENT.get() { - parachain_handler.validator_accessor.clone() - } else { - return Err(Error::NoLitentryParentchainAssigned) - }; - Ok(validator_accessor) -} - -pub(crate) fn get_node_metadata_repository_from_integritee_solo_or_parachain( -) -> Result> { - let metadata_repository = - if let Ok(solochain_handler) = GLOBAL_INTEGRITEE_SOLOCHAIN_HANDLER_COMPONENT.get() { - solochain_handler.node_metadata_repository.clone() - } else if let Ok(parachain_handler) = GLOBAL_INTEGRITEE_PARACHAIN_HANDLER_COMPONENT.get() { - parachain_handler.node_metadata_repository.clone() - } else { - return Err(Error::NoLitentryParentchainAssigned) - }; - Ok(metadata_repository) -} - -pub(crate) fn get_node_metadata_repository_from_target_a_solo_or_parachain( -) -> Result> { - let metadata_repository = - if let Ok(solochain_handler) = GLOBAL_TARGET_A_SOLOCHAIN_HANDLER_COMPONENT.get() { - solochain_handler.node_metadata_repository.clone() - } else if let Ok(parachain_handler) = GLOBAL_TARGET_A_PARACHAIN_HANDLER_COMPONENT.get() { - parachain_handler.node_metadata_repository.clone() - } else { - return Err(Error::NoTargetAParentchainAssigned) - }; - Ok(metadata_repository) -} - -pub(crate) fn get_node_metadata_repository_from_target_b_solo_or_parachain( -) -> Result> { - let metadata_repository = - if let Ok(solochain_handler) = GLOBAL_TARGET_B_SOLOCHAIN_HANDLER_COMPONENT.get() { - solochain_handler.node_metadata_repository.clone() - } else if let Ok(parachain_handler) = GLOBAL_TARGET_B_PARACHAIN_HANDLER_COMPONENT.get() { - parachain_handler.node_metadata_repository.clone() - } else { - return Err(Error::NoTargetBParentchainAssigned) - }; - Ok(metadata_repository) -} - -pub(crate) fn get_extrinsic_factory_from_integritee_solo_or_parachain( -) -> Result> { - let extrinsics_factory = - if let Ok(solochain_handler) = GLOBAL_INTEGRITEE_SOLOCHAIN_HANDLER_COMPONENT.get() { - solochain_handler.extrinsics_factory.clone() - } else if let Ok(parachain_handler) = GLOBAL_INTEGRITEE_PARACHAIN_HANDLER_COMPONENT.get() { - parachain_handler.extrinsics_factory.clone() - } else { - return Err(Error::NoLitentryParentchainAssigned) - }; - Ok(extrinsics_factory) -} diff --git a/tee-worker/bitacross/enclave-runtime/src/vc_issuance_task.rs b/tee-worker/bitacross/enclave-runtime/src/vc_issuance_task.rs deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/tee-worker/bitacross/enclave-runtime/x86_64-unknown-linux-sgx.json b/tee-worker/bitacross/enclave-runtime/x86_64-unknown-linux-sgx.json deleted file mode 100644 index 10d37a7490..0000000000 --- a/tee-worker/bitacross/enclave-runtime/x86_64-unknown-linux-sgx.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "arch": "x86_64", - "cpu": "x86-64", - "data-layout": "e-m:e-i64:64-f80:128-n8:16:32:64-S128", - "dynamic-linking": true, - "env": "sgx", - "exe-allocation-crate": "alloc_system", - "executables": true, - "has-elf-tls": true, - "has-rpath": true, - "linker-flavor": "gcc", - "linker-is-gnu": true, - "llvm-target": "x86_64-unknown-linux-gnu", - "max-atomic-width": 64, - "os": "linux", - "position-independent-executables": true, - "pre-link-args": { - "gcc": [ - "-Wl,--as-needed", - "-Wl,-z,noexecstack", - "-m64" - ] - }, - "relro-level": "full", - "stack-probes": true, - "target-c-int-width": "32", - "target-endian": "little", - "target-family": "unix", - "target-pointer-width": "64", - "vendor": "mesalock" -} diff --git a/tee-worker/bitacross/entrypoint.sh b/tee-worker/bitacross/entrypoint.sh deleted file mode 100755 index ac71403ba5..0000000000 --- a/tee-worker/bitacross/entrypoint.sh +++ /dev/null @@ -1,37 +0,0 @@ -#!/bin/bash - -log_file='./worker.log' - -touch ${log_file} - -check_env(){ - if [ -z $DATA_DIR ];then - echo "ENV DATA_DIR not set!" - exit 1 - fi -} - -copy_files(){ - for file in key.txt key_production.txt mrenclave.txt spid.txt spid_production.txt; do - wkdir_file="${DATA_DIR}/${file}" - if [ -s ${wkdir_file} ];then - echo "Working file ${wkdir_file} exist, not copy" - else - echo "Copy working file ${file} to ${DATA_DIR}" - cp /origin/${file} ${DATA_DIR}/ - fi - done - # Must copy,Ensure the consistency of binary files. - cp /origin/enclave.signed.so ${DATA_DIR}/ - -} - -runtime(){ - /usr/local/bin/bitacross-worker --version - echo "Worker subcommand is: $@" - /usr/local/bin/bitacross-worker $@ -} - -check_env -copy_files -runtime $@ >> ${log_file} 2>&1 \ No newline at end of file diff --git a/tee-worker/bitacross/example/README.md b/tee-worker/bitacross/example/README.md deleted file mode 100644 index 573f48d9e2..0000000000 --- a/tee-worker/bitacross/example/README.md +++ /dev/null @@ -1,9 +0,0 @@ -Example golang code for connecting to bitacross worker and requesting ethereum signature through trusted direct rpc. - -It connects to worker's trusted direct rpc endpoint exposed at `wss://localhost:2000` and requests `SignEthereum` direct call using JSON-RPC 2.0 protocol. -Direct call is signed by ethereum keypair. - -### Running -Specify worker's trusted rpc port as first argument - -`go run example --port 2000` \ No newline at end of file diff --git a/tee-worker/bitacross/example/client/definitions.json b/tee-worker/bitacross/example/client/definitions.json deleted file mode 100644 index 4824d890fa..0000000000 --- a/tee-worker/bitacross/example/client/definitions.json +++ /dev/null @@ -1,256 +0,0 @@ -{ - "RpcReturnValue": { - "type": "struct", - "type_mapping": [ - [ - "value", - "Vec" - ], - [ - "do_watch", - "bool" - ], - [ - "status", - "DirectRequestStatus" - ] - ] - }, - "DirectRequestStatus": { - "type": "enum", - "type_mapping": [ - [ - "Ok", - "()" - ], - [ - "TrustedOperationStatus", - "(TrustedOperationStatus, H256)" - ], - [ - "Error", - "()" - ], - [ - "Processing", - "H256" - ] - ] - }, - "TrustedOperationStatus": { - "type": "enum", - "type_mapping": [ - [ - "Submitted", - "()" - ], - [ - "Future", - "()" - ], - [ - "Ready", - "()" - ], - [ - "Broadcast", - "()" - ], - [ - "InSidechainBlock", - "H256" - ], - [ - "Retracted", - "()" - ], - [ - "FinalityTimeout", - "()" - ], - [ - "Finalized", - "()" - ], - [ - "Usurped", - "()" - ], - [ - "Dropped", - "()" - ], - [ - "Invalid", - "()" - ], - [ - "TopExecuted", - "(Vec, bool)" - ], - [ - "SuccessorExecuted", - "()" - ] - ] - }, - "DirectCallSigned": { - "type": "struct", - "type_mapping": [ - [ - "call", - "DirectCall" - ], - [ - "signature", - "LitentryMultiSignature" - ] - ] - }, - "SignEthereumPayload": "(bool, bool, bool)", - "SignBitcoinPayload": { - "type": "enum", - "type_mapping": [ - [ - "Derived", - "Vec" - ], - [ - "TaprootUnspendable", - "Vec" - ], - [ - "TaprootSpendable", - "(Vec, [u8; 32])" - ], - [ - "WithTweaks", - "(Vec, Vec<([u8; 32], bool)>)" - ] - ] - }, - "DirectCall": { - "type": "enum", - "type_mapping": [ - [ - "SignBitcoin", - "(LitentryIdentity, SignBitcoinPayload)" - ], - [ - "SignEthereum", - "(LitentryIdentity, PrehashedEthereumMessage)" - ], - [ - "SignTon", - "(LitentryIdentity, Vec)" - ] - ] - }, - "SignBitcoinError": { - "type": "enum", - "type_mapping": [ - ["InvalidSigner", "()"], - ["CeremonyError", "()"] - ] - }, - "SignEthereumError": { - "type": "enum", - "type_mapping": [ - ["InvalidSigner", "()"], - ["SigningError", "()"] - ] - }, - "SignTonError": { - "type": "enum", - "type_mapping": [ - ["InvalidSigner", "()"], - ["SigningError", "()"] - ] - }, - "PrehashedEthereumMessage": "[u8; 32]", - "PlainRequest": { - "type": "struct", - "type_mapping": [ - [ - "shard", - "ShardIdentifier" - ], - [ - "payload", - "Vec" - ] - ] - }, - "ShardIdentifier": "[u8; 32]", - "Address32": "[u8;32]", - "Address20": "[u8;20]", - "Address33": "[u8;33]", - "IdentityString": "Vec", - "LitentryIdentity": { - "type": "enum", - "type_mapping": [ - [ - "Twitter", - "IdentityString" - ], - [ - "Discord", - "IdentityString" - ], - [ - "Github", - "IdentityString" - ], - [ - "Substrate", - "[u8; 32]" - ], - [ - "Evm", - "[u8; 20]" - ], - [ - "Bitcoin", - "[u8; 33]" - ] - ] - }, - "LitentryMultiSignature": { - "type": "enum", - "type_mapping": [ - [ - "Ed25519", - "Ed25519Signature" - ], - [ - "Sr25519", - "Sr25519Signature" - ], - [ - "Ecdsa", - "EcdsaSignature" - ], - [ - "Ethereum", - "EthereumSignature" - ], - [ - "EthereumPrettified", - "EthereumSignature" - ], - [ - "Bitcoin", - "BitcoinSignature" - ], - [ - "BitcoinPrettified", - "BitcoinSignature" - ] - ] - }, - "Ed25519Signature": "([u8; 64])", - "Sr25519Signature": "([u8; 64])", - "EcdsaSignature": "([u8; 65])", - "EthereumSignature": "([u8; 65])", - "BitcoinSignature": "([u8; 65])" -} \ No newline at end of file diff --git a/tee-worker/bitacross/example/client/example.go b/tee-worker/bitacross/example/client/example.go deleted file mode 100644 index 1b11f01f54..0000000000 --- a/tee-worker/bitacross/example/client/example.go +++ /dev/null @@ -1,405 +0,0 @@ -package main - -import ( - "encoding/json" - "flag" - "fmt" - "github.com/ethereum/go-ethereum/common/hexutil" - "github.com/ethereum/go-ethereum/common/math" - "github.com/ethereum/go-ethereum/crypto" - "github.com/ethereum/go-ethereum/crypto/blake2b" - "github.com/ethereum/go-ethereum/crypto/secp256k1" - "github.com/itering/scale.go/source" - "github.com/itering/scale.go/types/scaleBytes" - "io/ioutil" -) -import "github.com/gorilla/websocket" -import "crypto/tls" -import "github.com/itering/scale.go/types" -import "github.com/itering/scale.go/utiles" - -type response struct { - Jsonrpc string `json:"jsonrpc"` - Result string `json:"result"` - Id int `json:"id"` -} - -type request struct { - Jsonrpc string `json:"jsonrpc"` - Method string `json:"method"` - Params []string `json:"params"` - Id int `json:"id"` -} - -type rpcResult struct { - Value string `json:"value"` - Do_watch bool `json:"do_watch"` - Status map[string]interface{} `json:"status"` -} - -type Rsa3072PubKey struct { - N [384]byte `json:"n"` - E [4]byte `json:"e"` -} - -func main() { - portPtr := flag.String("port", "2000", "worker's port number") - flag.Parse() - - fmt.Println("port:", *portPtr) - - registerCustomTypes() - c := create_conn(*portPtr) - - //** request shielding key - requestAuthorGetShieldingKey(*c) - res := read_response(*c) - - //** request aggregated public key - requestAggregatedPublicKey(*c) - res = read_response(*c) - - aggregatedPubKeyResult, _ := decodeRpcReturnValue(res.Result) - fmt.Println("Aggregated public key:") - fmt.Println(utiles.HexToBytes(aggregatedPubKeyResult)) - - //** request mrenclave - requestStateGetMrenclave(*c) - res = read_response(*c) - // shard is also mrenclave - getStateMrEnclaveResult, _ := decodeRpcReturnValue(res.Result) - //at this point we got all stuff from worker - shielding key, mrenclave and shard (shard == mrenclave) - - //** WARNING: use this key only for environment without real value - //public 0xffefbfc831e25a4dc6ece5c3600db669132a06ff8db152e3d7a1bbc0a3d425e596e708015b72266e0c6b7975662c794db43846c312ab58a678d9440a42cceba9 - //address 0x144Fa896B5FAbcA9D352483f0741776d1F836094 - key, _ := crypto.HexToECDSA("453134b1fda19819772d2fe7de3c2a8670f930e3187f2a81a509a52500e3a281") - ethAddress := crypto.PubkeyToAddress(key.PublicKey).Bytes() - - fmt.Println("Eth address") - fmt.Println(crypto.PubkeyToAddress(key.PublicKey)) - - //** prepare identity (signer) - identity := map[string]interface{}{ - "Evm": hexutil.Encode(ethAddress), - } - - //** prepare SignEthereum direct call - prehashedEthereumMessage := []byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32, 64} - - //** prepare signed direct call - directCall := prepareSignEthereumDirectCall(identity, prehashedEthereumMessage) - encodedDirectCall := types.Encode("DirectCall", directCall) - - fmt.Println(encodedDirectCall) - - encodedMrEnclave := types.Encode("[u8; 32]", getStateMrEnclaveResult) - - //prepare payload to sign - payloadToSign := blake2b.Sum256(prepareDirectCallSignaturePayload(encodedDirectCall, encodedMrEnclave)) - - payloadHash := crypto.Keccak256(payloadToSign[:]) - sig, _ := secp256k1.Sign(payloadHash, math.PaddedBigBytes(key.D, key.Params().BitSize/8)) - - directCallSigned := prepareSignedDirectCall(directCall, sig) - fmt.Println("Direct call signed: ") - fmt.Println(directCallSigned) - encodedDirectCallSigned := types.Encode("DirectCallSigned", directCallSigned) - fmt.Println("Encoded Direct call signed: ") - fmt.Println(encodedDirectCallSigned) - - //** create PlainRequest - plainRequest := map[string]interface{}{ - "shard": getStateMrEnclaveResult, - "payload": hexutil.Encode(utiles.HexToBytes(encodedDirectCallSigned)), - } - - fmt.Println(plainRequest) - - encodedPlainRequest := types.Encode("PlainRequest", plainRequest) - fmt.Println("Encoded plain request:") - fmt.Println(encodedPlainRequest) - - // ** create rpc request with hex encoded scale encoded request - signRequest := request{ - Jsonrpc: "2.0", - Method: "bitacross_submitRequest", - Params: []string{encodedPlainRequest}, - Id: 1, - } - serializedRequest, srErr := json.Marshal(signRequest) - - if srErr != nil { - fmt.Println("Problem while serializing the request") - fmt.Println(srErr) - } - - sendRequest(*c, serializedRequest) - - // ** decode response and parse shielding key, status 0 means success - signResp := read_response(*c) - signResult, signStatus := decodeRpcReturnValue(signResp.Result) - - fmt.Println("Result") - fmt.Println(signResult) - - if _, ok := signStatus["Error"]; ok { - fmt.Println(signResult) - } else { - signature := signResult - fmt.Println("Got signature:") - fmt.Println(signature) - } -} - -func prepareDirectCallSignaturePayload(directCallScaleEncoded string, mrEnclaveScaleEncoded string) []byte { - enclaveAppended := append(utiles.HexToBytes(directCallScaleEncoded), utiles.HexToBytes(mrEnclaveScaleEncoded)...) - shardAppended := append(enclaveAppended, utiles.HexToBytes(mrEnclaveScaleEncoded)...) - return shardAppended -} - -func prepareSignedDirectCall(directCall map[string]interface{}, signature []byte) map[string]interface{} { - return map[string]interface{}{ - "call": directCall, - "signature": map[string]interface{}{ - "Ethereum": map[string]interface{}{ - "col1": hexutil.Encode(signature), - }, - }, - } -} - -func prepareSignEthereumDirectCall(identity map[string]interface{}, prehashedEthereumMessage []byte) map[string]interface{} { - signEthereumDirectCall := map[string]interface{}{ - "col1": identity, - "col2": utiles.BytesToHex(prehashedEthereumMessage), - } - - return map[string]interface{}{ - "SignEthereum": signEthereumDirectCall, - } - -} - -func prepareSignTonDirectCall(identity map[string]interface{}, payload []byte) map[string]interface{} { - signTonDirectCall := map[string]interface{}{ - "col1": identity, - "col2": utiles.BytesToHex(payload), - } - - return map[string]interface{}{ - "SignTon": signTonDirectCall, - } - -} - -func prepareSignBitcoinTaprootSpendableDirectCall(identity map[string]interface{}, bitcoinPayload []byte, merkleRootHash [32]byte) map[string]interface{} { - payload := map[string]interface{}{ - "TaprootSpendable": map[string]interface{}{ - "col1": string(bitcoinPayload), - "col2": utiles.BytesToHex(merkleRootHash[:]), - }, - } - - signBitcoinDirectCall := map[string]interface{}{ - "col1": identity, - "col2": payload, - } - - return map[string]interface{}{ - "SignBitcoin": signBitcoinDirectCall, - } -} - -func prepareSignBitcoinWithTweakDirectCall(identity map[string]interface{}, bitcoinPayload []byte, tweakBytes [32]byte, tweakIsXOnly bool) map[string]interface{} { - tweaks := []map[string]interface{}{ - map[string]interface{}{ - "col1": utiles.BytesToHex(tweakBytes[:]), - "col2": tweakIsXOnly, - }, - } - - payload := map[string]interface{}{ - "WithTweaks": map[string]interface{}{ - "col1": string(bitcoinPayload), - "col2": tweaks, - }, - } - - directCall := map[string]interface{}{ - "col1": identity, - "col2": payload, - } - - return map[string]interface{}{ - "SignBitcoin": directCall, - } -} - -func prepareSignBitcoinTaprootUnspendableDirectCall(identity map[string]interface{}, bitcoinPayload []byte) map[string]interface{} { - payload := map[string]interface{}{ - "TaprootUnspendable": string(bitcoinPayload), - } - - signBitcoinDirectCall := map[string]interface{}{ - "col1": identity, - "col2": payload, - } - - return map[string]interface{}{ - "SignBitcoin": signBitcoinDirectCall, - } - -} - -func prepareSignBitcoinDerivedDirectCall(identity map[string]interface{}, bitcoinPayload []byte) map[string]interface{} { - payload := map[string]interface{}{ - "Derived": string(bitcoinPayload), - } - - signBitcoinDirectCall := map[string]interface{}{ - "col1": identity, - "col2": payload, - } - - return map[string]interface{}{ - "SignBitcoin": signBitcoinDirectCall, - } - -} - -func parseShieldingKey(hexEncodedShieldingKey string) Rsa3072PubKey { - var pubKey Rsa3072PubKey - keyBytes := utiles.HexToBytes(hexEncodedShieldingKey) - //we need to strip first two bytes - I don't know why - err := json.Unmarshal(keyBytes[2:len(keyBytes)], &pubKey) - if err != nil { - fmt.Println("error unmarshaling") - fmt.Println(err) - } - return pubKey -} - -func requestAuthorGetShieldingKey(c websocket.Conn) { - err := c.WriteMessage(websocket.TextMessage, []byte("{\"id\":1,\"jsonrpc\":\"2.0\",\"method\":\"author_getShieldingKey\",\"params\":[]}")) - if err != nil { - fmt.Println("Error sending message") - fmt.Println(err) - } -} - -func requestAggregatedPublicKey(c websocket.Conn) { - err := c.WriteMessage(websocket.TextMessage, []byte("{\"id\":1,\"jsonrpc\":\"2.0\",\"method\":\"bitacross_aggregatedPublicKey\",\"params\":[]}")) - if err != nil { - fmt.Println("Error sending message") - fmt.Println(err) - } -} - -func sendRequest(c websocket.Conn, request []byte) { - err := c.WriteMessage(websocket.TextMessage, request) - if err != nil { - fmt.Println("Error sending message") - fmt.Println(err) - } -} - -func requestStateGetMrenclave(c websocket.Conn) { - err := c.WriteMessage(websocket.TextMessage, []byte("{\"id\":1,\"jsonrpc\":\"2.0\",\"method\":\"state_getMrenclave\",\"params\":[]}")) - if err != nil { - fmt.Println("Error sending message") - fmt.Println(err) - } -} - -func decodeRpcReturnValue(hexEncoded string) (string, map[string]interface{}) { - bytes := scaleBytes.ScaleBytes{Data: utiles.HexToBytes(hexEncoded)} - m := types.ScaleDecoder{} - m.Init(bytes, nil) - var rpcResult rpcResult - err := utiles.UnmarshalAny(m.ProcessAndUpdateData("RpcReturnValue").(interface{}), &rpcResult) - - if err != nil { - fmt.Println("Unmarshall error!") - fmt.Println(err) - } - return rpcResult.Value, rpcResult.Status -} - -func decodeSignBitcoinError(encoded []byte) map[string]interface{} { - bytes := scaleBytes.ScaleBytes{Data: encoded} - m := types.ScaleDecoder{} - m.Init(bytes, &types.ScaleDecoderOption{ - SubType: "string,string", - }) - var output map[string]interface{} - err := utiles.UnmarshalAny(m.ProcessAndUpdateData("SignBitcoinError").(interface{}), &output) - - if err != nil { - fmt.Println("Unmarshall error!") - fmt.Println(err) - } - return output -} - -func decodeSignEthereumError(encoded []byte) map[string]interface{} { - bytes := scaleBytes.ScaleBytes{Data: encoded} - m := types.ScaleDecoder{} - m.Init(bytes, &types.ScaleDecoderOption{ - SubType: "string,string", - }) - var output map[string]interface{} - err := utiles.UnmarshalAny(m.ProcessAndUpdateData("SignEthereumError").(interface{}), &output) - - if err != nil { - fmt.Println("Unmarshall error!") - fmt.Println(err) - } - return output -} - -func read_response(c websocket.Conn) response { - _, message, r_err := c.ReadMessage() - if r_err != nil { - fmt.Println("Error reading message") - fmt.Println(r_err) - } - - res := response{} - if err := json.Unmarshal(message, &res); err != nil { - panic(err) - } - return res -} - -func create_conn(port string) *websocket.Conn { - - dialer := *websocket.DefaultDialer - url := "wss://localhost:" + port - fmt.Println("Connecting to worker:") - fmt.Println(url) - - // this is not secure, use with caution - dialer.TLSClientConfig = &tls.Config{InsecureSkipVerify: true} - c, _, err := dialer.Dial(url, nil) - if err != nil { - fmt.Println("Could not connect to worker") - fmt.Println(err) - } - fmt.Println("connected to worker") - return c -} - -func registerCustomTypes() { - def, read_err := ioutil.ReadFile("definitions.json") - if read_err != nil { - fmt.Println("Error while reading definitions file") - fmt.Println(read_err) - } - types.RegCustomTypes(source.LoadTypeRegistry(def)) - types.TypeRegistry["[u8; 4]"] = &types.FixedU8{FixedLength: 4} - types.TypeRegistry["[u8; 12]"] = &types.FixedU8{FixedLength: 12} - types.TypeRegistry["[u8; 32]"] = &types.FixedU8{FixedLength: 32} - types.TypeRegistry["[u8; 20]"] = &types.FixedU8{FixedLength: 20} - types.TypeRegistry["[u8; 65]"] = &types.FixedU8{FixedLength: 65} -} diff --git a/tee-worker/bitacross/example/client/go.mod b/tee-worker/bitacross/example/client/go.mod deleted file mode 100644 index adfe3d768a..0000000000 --- a/tee-worker/bitacross/example/client/go.mod +++ /dev/null @@ -1,20 +0,0 @@ -module example - -go 1.21 - -require ( - github.com/ethereum/go-ethereum v1.13.15 - github.com/gorilla/websocket v1.5.1 - github.com/itering/scale.go v1.8.2 -) - -require ( - github.com/btcsuite/btcd/btcec/v2 v2.2.0 // indirect - github.com/decred/dcrd/dcrec/secp256k1/v4 v4.0.1 // indirect - github.com/holiman/uint256 v1.2.4 // indirect - github.com/huandu/xstrings v1.4.0 // indirect - github.com/shopspring/decimal v1.3.1 // indirect - golang.org/x/crypto v0.21.0 // indirect - golang.org/x/net v0.23.0 // indirect - golang.org/x/sys v0.18.0 // indirect -) diff --git a/tee-worker/bitacross/example/client/go.sum b/tee-worker/bitacross/example/client/go.sum deleted file mode 100644 index 80b37129c8..0000000000 --- a/tee-worker/bitacross/example/client/go.sum +++ /dev/null @@ -1,70 +0,0 @@ -github.com/btcsuite/btcd/btcec/v2 v2.2.0 h1:fzn1qaOt32TuLjFlkzYSsBC35Q3KUjT1SwPxiMSCF5k= -github.com/btcsuite/btcd/btcec/v2 v2.2.0/go.mod h1:U7MHm051Al6XmscBQ0BoNydpOTsFAn707034b5nY8zU= -github.com/btcsuite/btcd/chaincfg/chainhash v1.0.1 h1:q0rUy8C/TYNBQS1+CGKw68tLOFYSNEs0TFnxxnS9+4U= -github.com/btcsuite/btcd/chaincfg/chainhash v1.0.1/go.mod h1:7SFka0XMvUgj3hfZtydOrQY2mwhPclbT2snogU7SQQc= -github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= -github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/decred/dcrd/crypto/blake256 v1.0.0 h1:/8DMNYp9SGi5f0w7uCm6d6M4OU2rGFK09Y2A4Xv7EE0= -github.com/decred/dcrd/crypto/blake256 v1.0.0/go.mod h1:sQl2p6Y26YV+ZOcSTP6thNdn47hh8kt6rqSlvmrXFAc= -github.com/decred/dcrd/dcrec/secp256k1/v4 v4.0.1 h1:YLtO71vCjJRCBcrPMtQ9nqBsqpA1m5sE92cU+pd5Mcc= -github.com/decred/dcrd/dcrec/secp256k1/v4 v4.0.1/go.mod h1:hyedUtir6IdtD/7lIxGeCxkaw7y45JueMRL4DIyJDKs= -github.com/ethereum/go-ethereum v1.13.15 h1:U7sSGYGo4SPjP6iNIifNoyIAiNjrmQkz6EwQG+/EZWo= -github.com/ethereum/go-ethereum v1.13.15/go.mod h1:TN8ZiHrdJwSe8Cb6x+p0hs5CxhJZPbqB7hHkaUXcmIU= -github.com/gorilla/websocket v1.5.1 h1:gmztn0JnHVt9JZquRuzLw3g4wouNVzKL15iLr/zn/QY= -github.com/gorilla/websocket v1.5.1/go.mod h1:x3kM2JMyaluk02fnUJpQuwD2dCS5NDG2ZHL0uE0tcaY= -github.com/holiman/uint256 v1.2.4 h1:jUc4Nk8fm9jZabQuqr2JzednajVmBpC+oiTiXZJEApU= -github.com/holiman/uint256 v1.2.4/go.mod h1:EOMSn4q6Nyt9P6efbI3bueV4e1b3dGlUCXeiRV4ng7E= -github.com/huandu/xstrings v1.3.1/go.mod h1:y5/lhBue+AyNmUVz9RLU9xbLR0o4KIIExikq4ovT0aE= -github.com/huandu/xstrings v1.4.0 h1:D17IlohoQq4UcpqD7fDk80P7l+lwAmlFaBHgOipl2FU= -github.com/huandu/xstrings v1.4.0/go.mod h1:y5/lhBue+AyNmUVz9RLU9xbLR0o4KIIExikq4ovT0aE= -github.com/itering/scale.go v1.8.2 h1:g+1XCSIdZlrzQDhg0S7gs2HtF6LlH9kmHPzLwqnwlRg= -github.com/itering/scale.go v1.8.2/go.mod h1:mEyWsfihftdLjhpeAo13wnGEM7XE42ZPvFVpC5Lsgqo= -github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= -github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/shopspring/decimal v1.2.0/go.mod h1:DKyhrW/HYNuLGql+MJL6WCR6knT2jwCFRcu2hWCYk4o= -github.com/shopspring/decimal v1.3.1 h1:2Usl1nmF/WZucqkFZhnfFYxxxu8LG21F6nPQBE5gKV8= -github.com/shopspring/decimal v1.3.1/go.mod h1:DKyhrW/HYNuLGql+MJL6WCR6knT2jwCFRcu2hWCYk4o= -github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= -github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= -github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= -golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= -golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= -golang.org/x/crypto v0.6.0/go.mod h1:OFC/31mSvZgRz0V1QTNCzfAI1aIRzbiufJtkMIlEp58= -golang.org/x/crypto v0.21.0 h1:X31++rzVUdKhX5sWmSOFZxx8UW/ldWx55cbf08iNAMA= -golang.org/x/crypto v0.21.0/go.mod h1:0BP7YvVV9gBbVKyeTG0Gyn+gZm94bibOW5BjDEYAOMs= -golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= -golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= -golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= -golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= -golang.org/x/net v0.23.0 h1:7EYJ93RZ9vYSZAIb2x3lnuvqO5zneoD6IvWjuhfxjTs= -golang.org/x/net v0.23.0/go.mod h1:JKghWKKOSdJwpW2GEx0Ja7fmaKnMsbu+MWVZTokSYmg= -golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.18.0 h1:DBdB3niSjOA/O0blCZBqDefyWNYveAYMNF1Wum0DYQ4= -golang.org/x/sys v0.18.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= -golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= -golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= -golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= -golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= -golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= -golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= -golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -gopkg.in/yaml.v3 v3.0.0/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= -gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/tee-worker/bitacross/extract_identity b/tee-worker/bitacross/extract_identity deleted file mode 100755 index 2c79268c15..0000000000 --- a/tee-worker/bitacross/extract_identity +++ /dev/null @@ -1,28 +0,0 @@ -#!/usr/bin/python3 - -import argparse - -if __name__ == "__main__": - parser = argparse.ArgumentParser() - parser.add_argument('--mrsigner', action="store_true") - args = parser.parse_args() - - line = "" - - searched_header = "enclave_hash.m" - output_header = "MRENCLAVE" - if args.mrsigner: - searched_header = "mrsigner->value" - output_header = "MRSIGNER" - while searched_header not in line: - line = input() - value = list() - line = input() - while line.startswith("0x"): - value += line.strip().split() - try: - line = input() - except: - break - value = "".join(map(lambda x: x.replace("0x",""), value)) -print("{}: {}".format(output_header, value)) diff --git a/tee-worker/bitacross/lib/readme.txt b/tee-worker/bitacross/lib/readme.txt deleted file mode 100644 index 7951405f85..0000000000 --- a/tee-worker/bitacross/lib/readme.txt +++ /dev/null @@ -1 +0,0 @@ -lib \ No newline at end of file diff --git a/tee-worker/bitacross/license_header_scs.txt b/tee-worker/bitacross/license_header_scs.txt deleted file mode 100644 index 6ded8ce2fd..0000000000 --- a/tee-worker/bitacross/license_header_scs.txt +++ /dev/null @@ -1,16 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ \ No newline at end of file diff --git a/tee-worker/bitacross/litentry/core/direct-call/Cargo.toml b/tee-worker/bitacross/litentry/core/direct-call/Cargo.toml deleted file mode 100644 index 749225754d..0000000000 --- a/tee-worker/bitacross/litentry/core/direct-call/Cargo.toml +++ /dev/null @@ -1,59 +0,0 @@ -[package] -authors = ["Trust Computing GmbH "] -edition = "2021" -name = "lc-direct-call" -version = "0.1.0" - -[dependencies] -codec = { package = "parity-scale-codec", workspace = true } -log = { workspace = true } -sp-core = { workspace = true } -sp-io = { workspace = true } - -# internal dependencies -bc-enclave-registry = { path = "../../../bitacross/core/bc-enclave-registry", default-features = false } -bc-musig2-ceremony = { path = "../../../bitacross/core/bc-musig2-ceremony", default-features = false } -bc-relayer-registry = { path = "../../../bitacross/core/bc-relayer-registry", default-features = false } -bc-signer-registry = { path = "../../../bitacross/core/bc-signer-registry", default-features = false } - -itp-sgx-crypto = { workspace = true } -itp-stf-primitives = { workspace = true } -litentry-primitives = { workspace = true } - -sgx_tstd = { workspace = true, optional = true } - -[dev-dependencies] -k256 = { workspace = true, features = ["ecdsa-core", "schnorr"] } -rand = { workspace = true } -hex = { workspace = true } -itp-sgx-crypto = { workspace = true, features = ["std", "mocks"] } - -[features] -default = ["std"] -development = [ - "litentry-primitives/development", -] -sgx = [ - "sgx_tstd", - "bc-musig2-ceremony/sgx", - "bc-enclave-registry/sgx", - "bc-relayer-registry/sgx", - "bc-signer-registry/sgx", - "litentry-primitives/sgx", - "itp-sgx-crypto/sgx", -] -std = [ - "bc-musig2-ceremony/std", - "bc-enclave-registry/std", - "bc-relayer-registry/std", - "bc-signer-registry/std", - "itp-stf-primitives/std", - "itp-sgx-crypto/std", - "litentry-primitives/std", - "sp-core/std", - "sp-io/std", - "codec/std", -] -test = [ - "itp-sgx-crypto/mocks", -] diff --git a/tee-worker/bitacross/litentry/core/direct-call/src/handler/kill_ceremony.rs b/tee-worker/bitacross/litentry/core/direct-call/src/handler/kill_ceremony.rs deleted file mode 100644 index ed7b01502d..0000000000 --- a/tee-worker/bitacross/litentry/core/direct-call/src/handler/kill_ceremony.rs +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright 2020-2024 Trust Computing GmbH. -// This file is part of Litentry. -// -// Litentry is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// Litentry is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with Litentry. If not, see . - -use bc_enclave_registry::EnclaveRegistryLookup; -use bc_musig2_ceremony::CeremonyCommand; -use codec::Encode; -use litentry_primitives::Identity; - -#[derive(Encode, Debug)] -pub enum KillCeremonyError { - InvalidSigner, -} - -pub fn handle( - signer: Identity, - enclave_registry: &ER, -) -> Result { - let is_valid_signer = match signer { - Identity::Substrate(address) => enclave_registry.contains_key(&address), - _ => false, - }; - if !is_valid_signer { - return Err(KillCeremonyError::InvalidSigner) - } - - match signer { - Identity::Substrate(_) => Ok(CeremonyCommand::KillCeremony), - _ => Err(KillCeremonyError::InvalidSigner), - } -} diff --git a/tee-worker/bitacross/litentry/core/direct-call/src/handler/mod.rs b/tee-worker/bitacross/litentry/core/direct-call/src/handler/mod.rs deleted file mode 100644 index 4c7a8d3c03..0000000000 --- a/tee-worker/bitacross/litentry/core/direct-call/src/handler/mod.rs +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright 2020-2024 Trust Computing GmbH. -// This file is part of Litentry. -// -// Litentry is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// Litentry is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with Litentry. If not, see . - -pub mod kill_ceremony; -pub mod nonce_share; -pub mod partial_signature_share; -pub mod sign_bitcoin; -pub mod sign_ethereum; -pub mod sign_ton; diff --git a/tee-worker/bitacross/litentry/core/direct-call/src/handler/nonce_share.rs b/tee-worker/bitacross/litentry/core/direct-call/src/handler/nonce_share.rs deleted file mode 100644 index ba039aea9c..0000000000 --- a/tee-worker/bitacross/litentry/core/direct-call/src/handler/nonce_share.rs +++ /dev/null @@ -1,126 +0,0 @@ -// Copyright 2020-2024 Trust Computing GmbH. -// This file is part of Litentry. -// -// Litentry is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// Litentry is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with Litentry. If not, see . - -use crate::handler::nonce_share::NonceShareError::InvalidSigner; -use bc_enclave_registry::EnclaveRegistryLookup; -use bc_musig2_ceremony::{CeremonyCommand, CeremonyId, PubNonce}; -use codec::Encode; -use litentry_primitives::Identity; -use log::debug; -use std::sync::Arc; - -#[derive(Encode, Debug)] -pub enum NonceShareError { - InvalidSigner, - InvalidNonce, -} - -pub fn handle( - signer: Identity, - ceremony_id: &CeremonyId, - payload: [u8; 66], - enclave_registry: Arc, -) -> Result { - debug!("Received nonce share from: {:?} for ceremony {:?}", signer, ceremony_id); - let is_valid_signer = match signer { - Identity::Substrate(address) => enclave_registry.contains_key(&address), - _ => false, - }; - if !is_valid_signer { - return Err(InvalidSigner) - } - - let nonce = - PubNonce::from_bytes(payload.as_slice()).map_err(|_| NonceShareError::InvalidNonce)?; - - match signer { - Identity::Substrate(address) => Ok(CeremonyCommand::SaveNonce(*address.as_ref(), nonce)), - _ => Err(InvalidSigner), - } -} - -#[cfg(test)] -pub mod test { - use crate::handler::nonce_share::{handle, NonceShareError}; - use alloc::sync::Arc; - use bc_enclave_registry::{EnclaveRegistry, EnclaveRegistryUpdater}; - use bc_musig2_ceremony::SignBitcoinPayload; - use itp_sgx_crypto::{key_repository::AccessKey, schnorr::Pair as SchnorrPair, Error}; - use litentry_primitives::Identity; - use sp_core::{sr25519, Pair}; - - struct SignerAccess {} - - impl AccessKey for SignerAccess { - type KeyType = SchnorrPair; - - fn retrieve_key(&self) -> itp_sgx_crypto::Result { - Err(Error::LockPoisoning) - } - } - - #[test] - pub fn it_should_return_ok_for_enclave_signer() { - // given - let alice_key_pair = sr25519::Pair::from_string("//Alice", None).unwrap(); - let signer_account = Identity::Substrate(alice_key_pair.public().into()); - let ceremony_id = SignBitcoinPayload::Derived(vec![]); - let enclave_registry = Arc::new(EnclaveRegistry::default()); - let _ = - enclave_registry.update(alice_key_pair.public().into(), "localhost:2000".to_string()); - - // when - let result = handle( - signer_account, - &ceremony_id, - [ - 2, 121, 190, 102, 126, 249, 220, 187, 172, 85, 160, 98, 149, 206, 135, 11, 7, 2, - 155, 252, 219, 45, 206, 40, 217, 89, 242, 129, 91, 22, 248, 23, 152, 3, 45, 226, - 102, 38, 40, 201, 11, 3, 245, 231, 32, 40, 78, 181, 47, 247, 215, 31, 66, 132, 246, - 39, 182, 138, 133, 61, 120, 199, 142, 31, 254, 147, - ], - enclave_registry, - ); - - // then - assert!(result.is_ok()) - } - - #[test] - pub fn it_should_return_err_for_non_enclave_signer() { - // given - let alice_key_pair = sr25519::Pair::from_string("//Alice", None).unwrap(); - let signer_account = Identity::Substrate(alice_key_pair.public().into()); - let ceremony_id = SignBitcoinPayload::Derived(vec![]); - let enclave_registry = Arc::new(EnclaveRegistry::default()); - - // when - let result = handle( - signer_account, - &ceremony_id, - [ - 2, 121, 190, 102, 126, 249, 220, 187, 172, 85, 160, 98, 149, 206, 135, 11, 7, 2, - 155, 252, 219, 45, 206, 40, 217, 89, 242, 129, 91, 22, 248, 23, 152, 3, 45, 226, - 102, 38, 40, 201, 11, 3, 245, 231, 32, 40, 78, 181, 47, 247, 215, 31, 66, 132, 246, - 39, 182, 138, 133, 61, 120, 199, 142, 31, 254, 147, - ], - enclave_registry, - ); - - // then - assert!(matches!(result, Err(NonceShareError::InvalidSigner))) - } -} diff --git a/tee-worker/bitacross/litentry/core/direct-call/src/handler/partial_signature_share.rs b/tee-worker/bitacross/litentry/core/direct-call/src/handler/partial_signature_share.rs deleted file mode 100644 index 38ec1d5b12..0000000000 --- a/tee-worker/bitacross/litentry/core/direct-call/src/handler/partial_signature_share.rs +++ /dev/null @@ -1,123 +0,0 @@ -// Copyright 2020-2024 Trust Computing GmbH. -// This file is part of Litentry. -// -// Litentry is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// Litentry is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with Litentry. If not, see . - -use crate::handler::partial_signature_share::PartialSignatureShareError::InvalidSignature; -use bc_enclave_registry::EnclaveRegistryLookup; -use bc_musig2_ceremony::{CeremonyCommand, CeremonyId, PartialSignature}; -use codec::Encode; -use litentry_primitives::Identity; -use log::debug; -use std::sync::Arc; - -#[derive(Encode, Debug)] -pub enum PartialSignatureShareError { - InvalidSigner, - SignatureSaveError, - InvalidSignature, -} - -pub fn handle( - signer: Identity, - ceremony_id: &CeremonyId, - signature: [u8; 32], - enclave_registry: Arc, -) -> Result { - debug!("Received partial signature share from: {:?} for ceremony {:?}", signer, ceremony_id); - let is_valid_signer = match signer { - Identity::Substrate(address) => enclave_registry.contains_key(&address), - _ => false, - }; - if !is_valid_signer { - return Err(PartialSignatureShareError::InvalidSigner) - } - - match signer { - Identity::Substrate(address) => Ok(CeremonyCommand::SavePartialSignature( - *address.as_ref(), - PartialSignature::from_slice(&signature).map_err(|_| InvalidSignature)?, - )), - _ => Err(PartialSignatureShareError::InvalidSigner), - } -} - -#[cfg(test)] -pub mod test { - use crate::handler::partial_signature_share::{handle, PartialSignatureShareError}; - use alloc::sync::Arc; - use bc_enclave_registry::{EnclaveRegistry, EnclaveRegistryUpdater}; - use bc_musig2_ceremony::SignBitcoinPayload; - use itp_sgx_crypto::{key_repository::AccessKey, schnorr::Pair as SchnorrPair, Error}; - use litentry_primitives::Identity; - use sp_core::{sr25519, Pair}; - - struct SignerAccess {} - - impl AccessKey for SignerAccess { - type KeyType = SchnorrPair; - - fn retrieve_key(&self) -> itp_sgx_crypto::Result { - Err(Error::LockPoisoning) - } - } - - #[test] - pub fn it_should_return_ok_for_enclave_signer() { - // given - let alice_key_pair = sr25519::Pair::from_string("//Alice", None).unwrap(); - let signer_account = Identity::Substrate(alice_key_pair.public().into()); - let ceremony_id = SignBitcoinPayload::Derived(vec![]); - let enclave_registry = Arc::new(EnclaveRegistry::default()); - let _ = - enclave_registry.update(alice_key_pair.public().into(), "localhost:2000".to_string()); - - // when - let result = handle( - signer_account, - &ceremony_id, - [ - 137, 19, 147, 124, 98, 243, 46, 98, 24, 93, 239, 14, 218, 117, 49, 69, 110, 245, - 176, 150, 209, 28, 241, 70, 195, 172, 198, 5, 12, 146, 251, 228, - ], - enclave_registry, - ); - - // then - assert!(result.is_ok()) - } - - #[test] - pub fn it_should_return_err_for_non_enclave_signer() { - // given - let alice_key_pair = sr25519::Pair::from_string("//Alice", None).unwrap(); - let signer_account = Identity::Substrate(alice_key_pair.public().into()); - let ceremony_id = SignBitcoinPayload::Derived(vec![]); - let enclave_registry = Arc::new(EnclaveRegistry::default()); - - // when - let result = handle( - signer_account, - &ceremony_id, - [ - 137, 19, 147, 124, 98, 243, 46, 98, 24, 93, 239, 14, 218, 117, 49, 69, 110, 245, - 176, 150, 209, 28, 241, 70, 195, 172, 198, 5, 12, 146, 251, 228, - ], - enclave_registry, - ); - - // then - assert!(matches!(result, Err(PartialSignatureShareError::InvalidSigner))) - } -} diff --git a/tee-worker/bitacross/litentry/core/direct-call/src/handler/sign_bitcoin.rs b/tee-worker/bitacross/litentry/core/direct-call/src/handler/sign_bitcoin.rs deleted file mode 100644 index 5dfaafa362..0000000000 --- a/tee-worker/bitacross/litentry/core/direct-call/src/handler/sign_bitcoin.rs +++ /dev/null @@ -1,188 +0,0 @@ -// Copyright 2020-2024 Trust Computing GmbH. -// This file is part of Litentry. -// -// Litentry is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// Litentry is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with Litentry. If not, see . - -use bc_enclave_registry::EnclaveRegistryLookup; -use bc_musig2_ceremony::{CeremonyCommand, PublicKey, SignBitcoinPayload, SignersWithKeys}; -use bc_relayer_registry::RelayerRegistryLookup; -use bc_signer_registry::SignerRegistryLookup; -use codec::Encode; -use litentry_primitives::Identity; -use std::sync::Arc; - -#[derive(Encode, Debug)] -pub enum SignBitcoinError { - InvalidSigner, - CeremonyError, -} - -#[allow(clippy::too_many_arguments)] -pub fn handle( - signer: Identity, - payload: SignBitcoinPayload, - relayer_registry: &RRL, - signer_registry: Arc, - enclave_registry: &ER, - check_run: bool, -) -> Result { - if relayer_registry.contains_key(&signer) - || match &signer { - Identity::Substrate(address) => enclave_registry.contains_key(address), - _ => false, - } { - let signers: Result = signer_registry - .get_all() - .iter() - .map(|(address, pub_key)| { - let public_key = PublicKey::from_sec1_bytes(pub_key) - .map_err(|_| SignBitcoinError::CeremonyError)?; - Ok((*address.as_ref(), public_key)) - }) - .collect(); - - Ok(CeremonyCommand::InitCeremony(signers?, payload, check_run)) - } else { - Err(SignBitcoinError::InvalidSigner) - } -} - -#[cfg(test)] -pub mod test { - use crate::handler::sign_bitcoin::{handle, SignBitcoinError}; - use alloc::sync::Arc; - use bc_enclave_registry::{EnclaveRegistry, EnclaveRegistryUpdater}; - use bc_musig2_ceremony::SignBitcoinPayload; - use bc_relayer_registry::{RelayerRegistry, RelayerRegistryUpdater}; - use bc_signer_registry::{PubKey, SignerRegistryLookup}; - use itp_sgx_crypto::{key_repository::AccessKey, schnorr::Pair as SchnorrPair, Error}; - use litentry_primitives::{Address32, Identity}; - use sp_core::{sr25519, Pair}; - - struct SignersRegistryMock {} - - impl SignerRegistryLookup for SignersRegistryMock { - fn contains_key(&self, _account: &Address32) -> bool { - true - } - - fn get_all(&self) -> Vec<(Address32, PubKey)> { - vec![ - ( - Address32::from([0u8; 32]), - [ - 2, 58, 165, 169, 140, 84, 151, 130, 21, 185, 32, 243, 101, 89, 29, 51, 56, - 38, 233, 110, 219, 75, 23, 37, 81, 20, 189, 129, 185, 104, 46, 113, 33, - ], - ), - ( - Address32::from([1u8; 32]), - [ - 2, 33, 158, 56, 188, 136, 36, 56, 255, 109, 228, 17, 179, 63, 196, 98, 40, - 57, 207, 209, 184, 120, 220, 9, 54, 115, 189, 207, 56, 230, 136, 48, 51, - ], - ), - ( - Address32::from([2u8; 32]), - [ - 2, 167, 108, 241, 140, 166, 89, 112, 114, 58, 251, 60, 114, 93, 85, 16, - 221, 20, 31, 40, 78, 234, 124, 2, 156, 166, 18, 246, 230, 29, 49, 229, 58, - ], - ), - ] - } - } - - struct SignerAccess {} - - impl AccessKey for SignerAccess { - type KeyType = SchnorrPair; - - fn retrieve_key(&self) -> itp_sgx_crypto::Result { - Err(Error::LockPoisoning) - } - } - - #[test] - pub fn it_should_return_ok_for_relayer_signer() { - // given - let relayer_registry = RelayerRegistry::default(); - let enclave_registry = EnclaveRegistry::default(); - let alice_key_pair = sr25519::Pair::from_string("//Alice", None).unwrap(); - let relayer_account = Identity::Substrate(alice_key_pair.public().into()); - relayer_registry.update(relayer_account.clone()).unwrap(); - let signers_registry = Arc::new(SignersRegistryMock {}); - - // when - let result = handle( - relayer_account, - SignBitcoinPayload::Derived(vec![]), - &relayer_registry, - signers_registry, - &enclave_registry, - false, - ); - - // then - assert!(result.is_ok()) - } - - #[test] - pub fn it_should_return_ok_for_enclave_signer() { - // given - let relayer_registry = RelayerRegistry::default(); - let enclave_registry = EnclaveRegistry::default(); - let alice_key_pair = sr25519::Pair::from_string("//Alice", None).unwrap(); - let enclave_account = Identity::Substrate(alice_key_pair.public().into()); - enclave_registry.update(alice_key_pair.public().into(), "".to_string()).unwrap(); - let signers_registry = Arc::new(SignersRegistryMock {}); - - // when - let result = handle( - enclave_account, - SignBitcoinPayload::Derived(vec![]), - &relayer_registry, - signers_registry, - &enclave_registry, - false, - ); - - // then - assert!(result.is_ok()) - } - - #[test] - pub fn it_should_return_err_for_non_relayer_and_non_enclave_signer() { - //given - let relayer_registry = RelayerRegistry::default(); - let enclave_registry = EnclaveRegistry::default(); - - let alice_key_pair = sr25519::Pair::from_string("//Alice", None).unwrap(); - let non_relayer_account = Identity::Substrate(alice_key_pair.public().into()); - let signers_registry = Arc::new(SignersRegistryMock {}); - - //when - let result = handle( - non_relayer_account, - SignBitcoinPayload::Derived(vec![]), - &relayer_registry, - signers_registry, - &enclave_registry, - false, - ); - - //then - assert!(matches!(result, Err(SignBitcoinError::InvalidSigner))) - } -} diff --git a/tee-worker/bitacross/litentry/core/direct-call/src/handler/sign_ethereum.rs b/tee-worker/bitacross/litentry/core/direct-call/src/handler/sign_ethereum.rs deleted file mode 100644 index eb07926a7d..0000000000 --- a/tee-worker/bitacross/litentry/core/direct-call/src/handler/sign_ethereum.rs +++ /dev/null @@ -1,116 +0,0 @@ -// Copyright 2020-2024 Trust Computing GmbH. -// This file is part of Litentry. -// -// Litentry is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// Litentry is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with Litentry. If not, see . - -use crate::PrehashedEthereumMessage; -use bc_relayer_registry::RelayerRegistryLookup; -use codec::Encode; -use itp_sgx_crypto::{ecdsa::Pair, key_repository::AccessKey}; -use litentry_primitives::Identity; -use log::error; - -#[derive(Encode, Debug)] -pub enum SignEthereumError { - InvalidSigner, - SigningError, -} - -pub fn handle>( - signer: Identity, - msg: PrehashedEthereumMessage, - relayer_registry: &RRL, - key_repository: &EKR, -) -> Result<[u8; 65], SignEthereumError> { - if relayer_registry.contains_key(&signer) { - let key = key_repository.retrieve_key().map_err(|e| { - error!("Could not retrieve ethereum signing key: {}", e); - SignEthereumError::SigningError - })?; - let sig = key.sign_prehash_recoverable(&msg).map_err(|e| { - error!("Could not sign: {}", e); - SignEthereumError::SigningError - })?; - Ok(sig) - } else { - Err(SignEthereumError::InvalidSigner) - } -} - -#[cfg(test)] -pub mod test { - use crate::handler::sign_ethereum::handle; - use bc_relayer_registry::{RelayerRegistry, RelayerRegistryUpdater}; - use itp_sgx_crypto::{ecdsa::Pair as EcdsaPair, mocks::KeyRepositoryMock}; - use k256::{ecdsa::SigningKey, elliptic_curve::rand_core}; - use litentry_primitives::Identity; - use sp_core::{sr25519, Pair}; - - #[test] - pub fn it_should_return_ok_for_relayer_signer() { - //given - let relayer_registry = RelayerRegistry::default(); - let alice_key_pair = sr25519::Pair::from_string("//Alice", None).unwrap(); - let relayer_account = Identity::Substrate(alice_key_pair.public().into()); - relayer_registry.update(relayer_account.clone()).unwrap(); - - let private = SigningKey::random(&mut rand_core::OsRng); - let signing_key = EcdsaPair::new(private); - - let key_repository = KeyRepositoryMock::new(signing_key); - - //when - let result = - handle(relayer_account, Default::default(), &relayer_registry, &key_repository); - - //then - assert!(result.is_ok()) - } - - #[test] - pub fn it_should_return_err_for_non_relayer_signer() { - //given - let relayer_registry = RelayerRegistry::default(); - let alice_key_pair = sr25519::Pair::from_string("//Alice", None).unwrap(); - let non_relayer_account = Identity::Substrate(alice_key_pair.public().into()); - - let private = SigningKey::random(&mut rand_core::OsRng); - let signing_key = EcdsaPair::new(private); - - let key_repository = KeyRepositoryMock::new(signing_key); - - //when - let result = - handle(non_relayer_account, Default::default(), &relayer_registry, &key_repository); - - //then - assert!(result.is_err()) - } - - #[test] - pub fn sign_ethereum_works() { - // test vector from bc team, verified with sp_core::ecdsa::Pair::sign_prehashed - let private_key = - hex::decode("038a5c907573ea7f61a7dcce5ebb2e233a6e9376e5a6f077729bd732d6cab620") - .unwrap(); - let key_pair = EcdsaPair::from_bytes(&private_key).unwrap(); - let payload = - hex::decode("3b08e117290fdd2617ea0e457a8eeebe373c456ecd3f6dc6dc4089380f486516") - .unwrap(); - let result = key_pair.sign_prehash_recoverable(&payload).unwrap(); - let expected_result = hex::decode("e733e8e3cd4f90d8fc10c2f8eeb7183623451b8e1d55b5ab6c4724c5428264955289fac3da7ce2095e12f19b4eb157c55be5c58a09ac8ae3358af0b7ec266a7201").unwrap(); - - assert_eq!(&result, expected_result.as_slice()) - } -} diff --git a/tee-worker/bitacross/litentry/core/direct-call/src/handler/sign_ton.rs b/tee-worker/bitacross/litentry/core/direct-call/src/handler/sign_ton.rs deleted file mode 100644 index 8ab4cee10e..0000000000 --- a/tee-worker/bitacross/litentry/core/direct-call/src/handler/sign_ton.rs +++ /dev/null @@ -1,103 +0,0 @@ -// Copyright 2020-2024 Trust Computing GmbH. -// This file is part of Litentry. -// -// Litentry is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// Litentry is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with Litentry. If not, see . - -use bc_relayer_registry::RelayerRegistryLookup; -use codec::Encode; -use itp_sgx_crypto::key_repository::AccessKey; -use litentry_primitives::Identity; -use log::error; -use sp_core::{ed25519::Pair as Ed25519Pair, Pair}; -use std::vec::Vec; - -#[derive(Encode, Debug)] -pub enum SignTonError { - InvalidSigner, - SigningError, -} - -pub fn handle>( - signer: Identity, - msg: Vec, - relayer_registry: &RRL, - key_repository: &EKR, -) -> Result<[u8; 64], SignTonError> { - if relayer_registry.contains_key(&signer) { - let key = key_repository.retrieve_key().map_err(|e| { - error!("Could not retrieve ton signing key: {}", e); - SignTonError::SigningError - })?; - let sig = key.sign(&msg); - Ok(sig.into()) - } else { - Err(SignTonError::InvalidSigner) - } -} - -#[cfg(test)] -pub mod test { - use crate::handler::sign_ton::handle; - use bc_relayer_registry::{RelayerRegistry, RelayerRegistryUpdater}; - use itp_sgx_crypto::{ecdsa::Pair as EcdsaPair, mocks::KeyRepositoryMock}; - use k256::{ecdsa::SigningKey, elliptic_curve::rand_core}; - use litentry_primitives::Identity; - use sp_core::{sr25519, Pair}; - - #[test] - pub fn it_should_return_ok_for_relayer_signer() { - //given - let relayer_registry = RelayerRegistry::default(); - let alice_key_pair = sr25519::Pair::from_string("//Alice", None).unwrap(); - let relayer_account = Identity::Substrate(alice_key_pair.public().into()); - relayer_registry.update(relayer_account.clone()).unwrap(); - - let signing_key = Pair::from_seed(&[ - 135, 174, 141, 248, 62, 107, 189, 100, 181, 60, 54, 229, 76, 255, 248, 189, 240, 238, - 171, 149, 56, 144, 67, 122, 222, 52, 26, 118, 79, 121, 33, 37, - ]); - - let key_repository = KeyRepositoryMock::new(signing_key); - - //when - let result = - handle(relayer_account, Default::default(), &relayer_registry, &key_repository); - - //then - assert!(result.is_ok()) - } - - #[test] - pub fn it_should_return_err_for_non_relayer_signer() { - //given - let relayer_registry = RelayerRegistry::default(); - let alice_key_pair = sr25519::Pair::from_string("//Alice", None).unwrap(); - let non_relayer_account = Identity::Substrate(alice_key_pair.public().into()); - - let private = SigningKey::random(&mut rand_core::OsRng); - let signing_key = Pair::from_seed(&[ - 135, 174, 141, 248, 62, 107, 189, 100, 181, 60, 54, 229, 76, 255, 248, 189, 240, 238, - 171, 149, 56, 144, 67, 122, 222, 52, 26, 118, 79, 121, 33, 37, - ]); - - let key_repository = KeyRepositoryMock::new(signing_key); - - //when - let result = - handle(non_relayer_account, Default::default(), &relayer_registry, &key_repository); - - //then - assert!(result.is_err()) - } -} diff --git a/tee-worker/bitacross/litentry/core/direct-call/src/lib.rs b/tee-worker/bitacross/litentry/core/direct-call/src/lib.rs deleted file mode 100644 index d2043ec53c..0000000000 --- a/tee-worker/bitacross/litentry/core/direct-call/src/lib.rs +++ /dev/null @@ -1,132 +0,0 @@ -// Copyright 2020-2024 Trust Computing GmbH. -// This file is part of Litentry. -// -// Litentry is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// Litentry is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with Litentry. If not, see . - -#![cfg_attr(not(feature = "std"), no_std)] - -extern crate alloc; -#[cfg(all(not(feature = "std"), feature = "sgx"))] -extern crate sgx_tstd as std; - -use bc_musig2_ceremony::SignBitcoinPayload; -use codec::{Decode, Encode}; -use itp_stf_primitives::types::KeyPair; -use litentry_primitives::{Identity, LitentryMultiSignature, ShardIdentifier}; -use sp_io::hashing::blake2_256; -use std::vec::Vec; - -pub mod handler; - -pub type PrehashedEthereumMessage = [u8; 32]; - -#[derive(Encode, Decode, Clone, Debug, PartialEq, Eq)] -pub struct DirectCallSigned { - pub call: DirectCall, - pub signature: LitentryMultiSignature, -} - -impl DirectCallSigned { - pub fn verify_signature(&self, mrenclave: &[u8; 32], shard: &ShardIdentifier) -> bool { - let mut payload = self.call.encode(); - payload.append(&mut mrenclave.encode()); - payload.append(&mut shard.encode()); - - self.signature.verify(blake2_256(&payload).as_slice(), self.call.signer()) - } -} - -#[derive(Encode, Decode, Clone, Debug, PartialEq, Eq)] -pub enum DirectCall { - SignBitcoin(Identity, SignBitcoinPayload), - SignEthereum(Identity, PrehashedEthereumMessage), - SignTon(Identity, Vec), - CheckSignBitcoin(Identity), -} - -impl DirectCall { - pub fn signer(&self) -> &Identity { - match self { - Self::SignBitcoin(signer, ..) => signer, - Self::SignEthereum(signer, ..) => signer, - Self::SignTon(signer, ..) => signer, - Self::CheckSignBitcoin(signer) => signer, - } - } - - pub fn sign( - &self, - pair: &KeyPair, - mrenclave: &[u8; 32], - shard: &ShardIdentifier, - ) -> DirectCallSigned { - let mut payload = self.encode(); - payload.append(&mut mrenclave.encode()); - payload.append(&mut shard.encode()); - - DirectCallSigned { - call: self.clone(), - signature: pair.sign(blake2_256(&payload).as_slice()), - } - } -} - -#[derive(Encode, Decode, Clone, Debug, PartialEq, Eq)] -pub struct CeremonyRoundCallSigned { - pub call: CeremonyRoundCall, - pub signature: LitentryMultiSignature, -} - -impl CeremonyRoundCallSigned { - pub fn verify_signature(&self, mrenclave: &[u8; 32], shard: &ShardIdentifier) -> bool { - let mut payload = self.call.encode(); - payload.append(&mut mrenclave.encode()); - payload.append(&mut shard.encode()); - - self.signature.verify(blake2_256(&payload).as_slice(), self.call.signer()) - } -} - -#[derive(Encode, Decode, Clone, Debug, PartialEq, Eq)] -pub enum CeremonyRoundCall { - NonceShare(Identity, SignBitcoinPayload, [u8; 66]), - PartialSignatureShare(Identity, SignBitcoinPayload, [u8; 32]), - KillCeremony(Identity, SignBitcoinPayload), -} - -impl CeremonyRoundCall { - pub fn signer(&self) -> &Identity { - match self { - Self::NonceShare(signer, ..) => signer, - Self::PartialSignatureShare(signer, ..) => signer, - Self::KillCeremony(signer, ..) => signer, - } - } - - pub fn sign( - &self, - pair: &KeyPair, - mrenclave: &[u8; 32], - shard: &ShardIdentifier, - ) -> CeremonyRoundCallSigned { - let mut payload = self.encode(); - payload.append(&mut mrenclave.encode()); - payload.append(&mut shard.encode()); - - CeremonyRoundCallSigned { - call: self.clone(), - signature: pair.sign(blake2_256(&payload).as_slice()), - } - } -} diff --git a/tee-worker/bitacross/rust-sgx-sdk/Readme.md b/tee-worker/bitacross/rust-sgx-sdk/Readme.md deleted file mode 100644 index 4c71699c10..0000000000 --- a/tee-worker/bitacross/rust-sgx-sdk/Readme.md +++ /dev/null @@ -1,5 +0,0 @@ -# RUST-SGX-SDK - -This folder contains only the neccessary parts from the [RUST-SGX-SDK](https://github.com/baidu/rust-sgx-sdk). - -All the crates are directly fetched from github. \ No newline at end of file diff --git a/tee-worker/bitacross/rust-sgx-sdk/buildenv.mk b/tee-worker/bitacross/rust-sgx-sdk/buildenv.mk deleted file mode 100644 index ce28be4e55..0000000000 --- a/tee-worker/bitacross/rust-sgx-sdk/buildenv.mk +++ /dev/null @@ -1,179 +0,0 @@ -# -# Copyright (C) 2017-2018 Baidu, Inc. All Rights Reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions -# are met: -# -# * Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above copyright -# notice, this list of conditions and the following disclaimer in -# the documentation and/or other materials provided with the -# distribution. -# * Neither the name of Baidu, Inc., nor the names of its -# contributors may be used to endorse or promote products derived -# from this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -# -# - -CP := /bin/cp -f -MKDIR := mkdir -p -STRIP := strip -OBJCOPY := objcopy - -# clean the content of 'INCLUDE' - this variable will be set by vcvars32.bat -# thus it will cause build error when this variable is used by our Makefile, -# when compiling the code under Cygwin tainted by MSVC environment settings. -INCLUDE := - -# turn on stack protector for SDK -COMMON_FLAGS += -fstack-protector - -ifdef DEBUG - COMMON_FLAGS += -O0 -g -DDEBUG -UNDEBUG -else - COMMON_FLAGS += -O2 -D_FORTIFY_SOURCE=2 -UDEBUG -DNDEBUG -endif - -# turn on compiler warnings as much as possible -COMMON_FLAGS += -Wall -Wextra -Winit-self -Wpointer-arith -Wreturn-type \ - -Waddress -Wsequence-point -Wformat-security \ - -Wmissing-include-dirs -Wfloat-equal -Wundef -Wshadow \ - -Wcast-align -Wconversion -Wredundant-decls - -# additional warnings flags for C -CFLAGS += -Wjump-misses-init -Wstrict-prototypes -Wunsuffixed-float-constants - -# additional warnings flags for C++ -CXXFLAGS += -Wnon-virtual-dtor - -# for static_assert() -CXXFLAGS += -std=c++0x - -.DEFAULT_GOAL := all -# this turns off the RCS / SCCS implicit rules of GNU Make -% : RCS/%,v -% : RCS/% -% : %,v -% : s.% -% : SCCS/s.% - -# If a rule fails, delete $@. -.DELETE_ON_ERROR: - -HOST_FILE_PROGRAM := file - -UNAME := $(shell uname -m) -ifneq (,$(findstring 86,$(UNAME))) - HOST_ARCH := x86 - ifneq (,$(shell $(HOST_FILE_PROGRAM) -L $(SHELL) | grep 'x86[_-]64')) - HOST_ARCH := x86_64 - endif -else - $(info Unknown host CPU architecture $(UNAME)) - $(error Aborting) -endif - - -ifeq "$(findstring __INTEL_COMPILER, $(shell $(CC) -E -dM -xc /dev/null))" "__INTEL_COMPILER" - ifeq ($(shell test -f /usr/bin/dpkg; echo $$?), 0) - ADDED_INC := -I /usr/include/$(shell dpkg-architecture -qDEB_BUILD_MULTIARCH) - endif -endif - -ARCH := $(HOST_ARCH) -ifeq "$(findstring -m32, $(CXXFLAGS))" "-m32" - ARCH := x86 -endif - -ifeq ($(ARCH), x86) -COMMON_FLAGS += -DITT_ARCH_IA32 -else -COMMON_FLAGS += -DITT_ARCH_IA64 -endif - -CFLAGS += $(COMMON_FLAGS) -CXXFLAGS += $(COMMON_FLAGS) - -# Enable the security flags -COMMON_LDFLAGS := -Wl,-z,relro,-z,now,-z,noexecstack - -# mitigation options -MITIGATION_INDIRECT ?= 0 -MITIGATION_RET ?= 0 -MITIGATION_C ?= 0 -MITIGATION_ASM ?= 0 -MITIGATION_AFTERLOAD ?= 0 -MITIGATION_LIB_PATH := - -ifeq ($(MITIGATION-CVE-2020-0551), LOAD) - MITIGATION_C := 1 - MITIGATION_ASM := 1 - MITIGATION_INDIRECT := 1 - MITIGATION_RET := 1 - MITIGATION_AFTERLOAD := 1 - MITIGATION_LIB_PATH := cve_2020_0551_load -else ifeq ($(MITIGATION-CVE-2020-0551), CF) - MITIGATION_C := 1 - MITIGATION_ASM := 1 - MITIGATION_INDIRECT := 1 - MITIGATION_RET := 1 - MITIGATION_AFTERLOAD := 0 - MITIGATION_LIB_PATH := cve_2020_0551_cf -endif - -MITIGATION_CFLAGS := -MITIGATION_ASFLAGS := -ifeq ($(MITIGATION_C), 1) -ifeq ($(MITIGATION_INDIRECT), 1) - MITIGATION_CFLAGS += -mindirect-branch-register -endif -ifeq ($(MITIGATION_RET), 1) - MITIGATION_CFLAGS += -mfunction-return=thunk-extern -endif -endif - -ifeq ($(MITIGATION_ASM), 1) - MITIGATION_ASFLAGS += -fno-plt -ifeq ($(MITIGATION_AFTERLOAD), 1) - MITIGATION_ASFLAGS += -Wa,-mlfence-after-load=yes -else - MITIGATION_ASFLAGS += -Wa,-mlfence-before-indirect-branch=register -endif -ifeq ($(MITIGATION_RET), 1) - MITIGATION_ASFLAGS += -Wa,-mlfence-before-ret=not -endif -endif - -MITIGATION_CFLAGS += $(MITIGATION_ASFLAGS) - -# Compiler and linker options for an Enclave -# -# We are using '--export-dynamic' so that `g_global_data_sim' etc. -# will be exported to dynamic symbol table. -# -# When `pie' is enabled, the linker (both BFD and Gold) under Ubuntu 14.04 -# will hide all symbols from dynamic symbol table even if they are marked -# as `global' in the LD version script. -ENCLAVE_CFLAGS = -ffreestanding -nostdinc -fvisibility=hidden -fpie -fno-strict-overflow -fno-delete-null-pointer-checks -ENCLAVE_CXXFLAGS = $(ENCLAVE_CFLAGS) -nostdinc++ -ENCLAVE_LDFLAGS = $(COMMON_LDFLAGS) -Wl,-Bstatic -Wl,-Bsymbolic -Wl,--no-undefined \ - -Wl,-pie,-eenclave_entry -Wl,--export-dynamic \ - -Wl,--gc-sections \ - -Wl,--defsym,__ImageBase=0 - -ENCLAVE_CFLAGS += $(MITIGATION_CFLAGS) -ENCLAVE_ASFLAGS = $(MITIGATION_ASFLAGS) \ No newline at end of file diff --git a/tee-worker/bitacross/rust-sgx-sdk/common/inc/assert.h b/tee-worker/bitacross/rust-sgx-sdk/common/inc/assert.h deleted file mode 100644 index a153995416..0000000000 --- a/tee-worker/bitacross/rust-sgx-sdk/common/inc/assert.h +++ /dev/null @@ -1,63 +0,0 @@ -/* $OpenBSD: assert.h,v 1.12 2006/01/31 10:53:51 hshoexer Exp $ */ -/* $NetBSD: assert.h,v 1.6 1994/10/26 00:55:44 cgd Exp $ */ - -/*- - * Copyright (c) 1992, 1993 - * The Regents of the University of California. All rights reserved. - * (c) UNIX System Laboratories, Inc. - * All or some portions of this file are derived from material licensed - * to the University of California by American Telephone and Telegraph - * Co. or Unix System Laboratories, Inc. and are reproduced herein with - * the permission of UNIX System Laboratories, Inc. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS - * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY - * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - * - * @(#)assert.h 8.2 (Berkeley) 1/21/94 - */ - -/* - * Unlike other ANSI header files, may usefully be included - * multiple times, with and without NDEBUG defined. - */ - -#include - -#undef assert - -#ifdef NDEBUG -# define assert(e) ((void)0) -#else -# define assert(e) ((e) ? (void)0 : __assert(__FILE__, __LINE__, __func__, #e)) -#endif - -#ifndef _ASSERT_H_DECLS -#define _ASSERT_H_DECLS -__BEGIN_DECLS - -void _TLIBC_CDECL_ __assert(const char *, int, const char *, const char *); - -__END_DECLS -#endif /* Not _ASSERT_H_DECLS */ - diff --git a/tee-worker/bitacross/rust-sgx-sdk/common/inc/complex.h b/tee-worker/bitacross/rust-sgx-sdk/common/inc/complex.h deleted file mode 100644 index 904cb31fbf..0000000000 --- a/tee-worker/bitacross/rust-sgx-sdk/common/inc/complex.h +++ /dev/null @@ -1,134 +0,0 @@ -/* $OpenBSD: complex.h,v 1.3 2010/07/24 22:17:03 guenther Exp $ */ -/* - * Copyright (c) 2008 Martynas Venckus - * - * Permission to use, copy, modify, and distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -#ifndef _COMPLEX_H_ -#define _COMPLEX_H_ - -#include - -/* - * C99 - */ -#ifdef __GNUC__ -#if __STDC_VERSION__ < 199901 -#define _Complex __complex__ -#endif -#define _Complex_I 1.0fi -#elif defined(lint) -#define _Complex_I 1.0fi -#endif - -#define complex _Complex - -/* XXX switch to _Imaginary_I */ -#undef I -#define I _Complex_I - -__BEGIN_DECLS -/* - * Double versions of C99 functions - */ -double complex cacos(double complex); -double complex casin(double complex); -double complex catan(double complex); -double complex ccos(double complex); -double complex csin(double complex); -double complex ctan(double complex); -double complex cacosh(double complex); -double complex casinh(double complex); -double complex catanh(double complex); -double complex ccosh(double complex); -double complex csinh(double complex); -double complex ctanh(double complex); -double complex cexp(double complex); -double complex clog(double complex); -double cabs(double complex); -double complex cpow(double complex, double complex); -double complex csqrt(double complex); -double carg(double complex); -double cimag(double complex); -double complex conj(double complex); -double complex cproj(double complex); -double creal(double complex); -/* - * C99 reserved - */ -double complex clog10(double complex); - -/* - * Float versions of C99 functions - */ -float complex cacosf(float complex); -float complex casinf(float complex); -float complex catanf(float complex); -float complex ccosf(float complex); -float complex csinf(float complex); -float complex ctanf(float complex); -float complex cacoshf(float complex); -float complex casinhf(float complex); -float complex catanhf(float complex); -float complex ccoshf(float complex); -float complex csinhf(float complex); -float complex ctanhf(float complex); -float complex cexpf(float complex); -float complex clogf(float complex); -float cabsf(float complex); -float complex cpowf(float complex, float complex); -float complex csqrtf(float complex); -float cargf(float complex); -float cimagf(float complex); -float complex conjf(float complex); -float complex cprojf(float complex); -float crealf(float complex); -/* - * C99 reserved - */ -float complex clog10f(float complex); - -/* - * Long double versions of C99 functions - */ -long double complex cacosl(long double complex); -long double complex casinl(long double complex); -long double complex catanl(long double complex); -long double complex ccosl(long double complex); -long double complex csinl(long double complex); -long double complex ctanl(long double complex); -long double complex cacoshl(long double complex); -long double complex casinhl(long double complex); -long double complex catanhl(long double complex); -long double complex ccoshl(long double complex); -long double complex csinhl(long double complex); -long double complex ctanhl(long double complex); -long double complex cexpl(long double complex); -long double complex clogl(long double complex); -long double cabsl(long double complex); -long double complex cpowl(long double complex, long double complex); -long double complex csqrtl(long double complex); -long double cargl(long double complex); -long double cimagl(long double complex); -long double complex conjl(long double complex); -long double complex cprojl(long double complex); -long double creall(long double complex); -/* - * C99 reserved - */ -long double complex clog10l(long double complex); - -__END_DECLS - -#endif /* !_COMPLEX_H_ */ diff --git a/tee-worker/bitacross/rust-sgx-sdk/common/inc/ctype.h b/tee-worker/bitacross/rust-sgx-sdk/common/inc/ctype.h deleted file mode 100644 index 57ac70ff11..0000000000 --- a/tee-worker/bitacross/rust-sgx-sdk/common/inc/ctype.h +++ /dev/null @@ -1,65 +0,0 @@ -/* $OpenBSD: ctype.h,v 1.22 2010/10/01 20:10:24 guenther Exp $ */ -/* $NetBSD: ctype.h,v 1.14 1994/10/26 00:55:47 cgd Exp $ */ - -/* - * Copyright (c) 1989 The Regents of the University of California. - * All rights reserved. - * (c) UNIX System Laboratories, Inc. - * All or some portions of this file are derived from material licensed - * to the University of California by American Telephone and Telegraph - * Co. or Unix System Laboratories, Inc. and are reproduced herein with - * the permission of UNIX System Laboratories, Inc. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS - * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY - * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - * - * @(#)ctype.h 5.3 (Berkeley) 4/3/91 - */ - -#ifndef _CTYPE_H_ -#define _CTYPE_H_ - -#include - -__BEGIN_DECLS - -int _TLIBC_CDECL_ isalnum(int); -int _TLIBC_CDECL_ isalpha(int); -int _TLIBC_CDECL_ iscntrl(int); -int _TLIBC_CDECL_ isdigit(int); -int _TLIBC_CDECL_ isgraph(int); -int _TLIBC_CDECL_ islower(int); -int _TLIBC_CDECL_ isprint(int); -int _TLIBC_CDECL_ ispunct(int); -int _TLIBC_CDECL_ isspace(int); -int _TLIBC_CDECL_ isupper(int); -int _TLIBC_CDECL_ isxdigit(int); -int _TLIBC_CDECL_ tolower(int); -int _TLIBC_CDECL_ toupper(int); -int _TLIBC_CDECL_ isblank(int); -int _TLIBC_CDECL_ isascii(int); - -__END_DECLS - -#endif /* _CTYPE_H_ */ diff --git a/tee-worker/bitacross/rust-sgx-sdk/common/inc/dirent.h b/tee-worker/bitacross/rust-sgx-sdk/common/inc/dirent.h deleted file mode 100644 index a0ede0375c..0000000000 --- a/tee-worker/bitacross/rust-sgx-sdk/common/inc/dirent.h +++ /dev/null @@ -1,48 +0,0 @@ -// -// Copyright © 2005-2020 Rich Felker, et al. -// Licensed under the MIT license.s -// - -/* Copyright © 2005-2020 Rich Felker, et al. - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ - -#ifndef _DIRENT_H_ -#define _DIRENT_H_ - -struct dirent { - __ino_t d_ino; - __off_t d_off; - unsigned short d_reclen; - unsigned char d_type; - char d_name[256]; -}; - -struct dirent64 { - __ino64_t d_ino; - __off64_t d_off; - unsigned short d_reclen; - unsigned char d_type; - char d_name[256]; -}; - -#define d_fileno d_ino - -#endif /* _DIRENT_H_ */ diff --git a/tee-worker/bitacross/rust-sgx-sdk/common/inc/endian.h b/tee-worker/bitacross/rust-sgx-sdk/common/inc/endian.h deleted file mode 100644 index 2620c5898f..0000000000 --- a/tee-worker/bitacross/rust-sgx-sdk/common/inc/endian.h +++ /dev/null @@ -1,33 +0,0 @@ -/* $OpenBSD: endian.h,v 1.18 2006/03/27 07:09:24 otto Exp $ */ - -/*- - * Copyright (c) 1997 Niklas Hallqvist. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef _ENDIAN_H_ -#define _ENDIAN_H_ - -#include - -#endif /* _ENDIAN_H_ */ - diff --git a/tee-worker/bitacross/rust-sgx-sdk/common/inc/errno.h b/tee-worker/bitacross/rust-sgx-sdk/common/inc/errno.h deleted file mode 100644 index dbe293cb9e..0000000000 --- a/tee-worker/bitacross/rust-sgx-sdk/common/inc/errno.h +++ /dev/null @@ -1,187 +0,0 @@ -/* $OpenBSD: errno.h,v 1.1 2005/12/28 16:33:56 millert Exp $ */ - -/* - * Copyright (c) 1982, 1986, 1989, 1993 - * The Regents of the University of California. All rights reserved. - * (c) UNIX System Laboratories, Inc. - * All or some portions of this file are derived from material licensed - * to the University of California by American Telephone and Telegraph - * Co. or Unix System Laboratories, Inc. and are reproduced herein with - * the permission of UNIX System Laboratories, Inc. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS - * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY - * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - * - * @(#)errno.h 8.5 (Berkeley) 1/21/94 - */ - -#ifndef _ERRNO_H_ -#define _ERRNO_H_ - -#include - -#define EPERM 1 -#define ENOENT 2 -#define ESRCH 3 -#define EINTR 4 -#define EIO 5 -#define ENXIO 6 -#define E2BIG 7 -#define ENOEXEC 8 -#define EBADF 9 -#define ECHILD 10 -#define EAGAIN 11 -#define ENOMEM 12 -#define EACCES 13 -#define EFAULT 14 -#define ENOTBLK 15 -#define EBUSY 16 -#define EEXIST 17 -#define EXDEV 18 -#define ENODEV 19 -#define ENOTDIR 20 -#define EISDIR 21 -#define EINVAL 22 -#define ENFILE 23 -#define EMFILE 24 -#define ENOTTY 25 -#define ETXTBSY 26 -#define EFBIG 27 -#define ENOSPC 28 -#define ESPIPE 29 -#define EROFS 30 -#define EMLINK 31 -#define EPIPE 32 -#define EDOM 33 -#define ERANGE 34 -#define EDEADLK 35 -#define ENAMETOOLONG 36 -#define ENOLCK 37 -#define ENOSYS 38 -#define ENOTEMPTY 39 -#define ELOOP 40 -#define EWOULDBLOCK EAGAIN -#define ENOMSG 42 -#define EIDRM 43 -#define ECHRNG 44 -#define EL2NSYNC 45 -#define EL3HLT 46 -#define EL3RST 47 -#define ELNRNG 48 -#define EUNATCH 49 -#define ENOCSI 50 -#define EL2HLT 51 -#define EBADE 52 -#define EBADR 53 -#define EXFULL 54 -#define ENOANO 55 -#define EBADRQC 56 -#define EBADSLT 57 -#define EDEADLOCK EDEADLK -#define EBFONT 59 -#define ENOSTR 60 -#define ENODATA 61 -#define ETIME 62 -#define ENOSR 63 -#define ENONET 64 -#define ENOPKG 65 -#define EREMOTE 66 -#define ENOLINK 67 -#define EADV 68 -#define ESRMNT 69 -#define ECOMM 70 -#define EPROTO 71 -#define EMULTIHOP 72 -#define EDOTDOT 73 -#define EBADMSG 74 -#define EOVERFLOW 75 -#define ENOTUNIQ 76 -#define EBADFD 77 -#define EREMCHG 78 -#define ELIBACC 79 -#define ELIBBAD 80 -#define ELIBSCN 81 -#define ELIBMAX 82 -#define ELIBEXEC 83 -#define EILSEQ 84 -#define ERESTART 85 -#define ESTRPIPE 86 -#define EUSERS 87 -#define ENOTSOCK 88 -#define EDESTADDRREQ 89 -#define EMSGSIZE 90 -#define EPROTOTYPE 91 -#define ENOPROTOOPT 92 -#define EPROTONOSUPPORT 93 -#define ESOCKTNOSUPPORT 94 -#define EOPNOTSUPP 95 -#define EPFNOSUPPORT 96 -#define EAFNOSUPPORT 97 -#define EADDRINUSE 98 -#define EADDRNOTAVAIL 99 -#define ENETDOWN 100 -#define ENETUNREACH 101 -#define ENETRESET 102 -#define ECONNABORTED 103 -#define ECONNRESET 104 -#define ENOBUFS 105 -#define EISCONN 106 -#define ENOTCONN 107 -#define ESHUTDOWN 108 -#define ETOOMANYREFS 109 -#define ETIMEDOUT 110 -#define ECONNREFUSED 111 -#define EHOSTDOWN 112 -#define EHOSTUNREACH 113 -#define EALREADY 114 -#define EINPROGRESS 115 -#define ESTALE 116 -#define EUCLEAN 117 -#define ENOTNAM 118 -#define ENAVAIL 119 -#define EISNAM 120 -#define EREMOTEIO 121 -#define EDQUOT 122 -#define ENOMEDIUM 123 -#define EMEDIUMTYPE 124 -#define ECANCELED 125 -#define ENOKEY 126 -#define EKEYEXPIRED 127 -#define EKEYREVOKED 128 -#define EKEYREJECTED 129 -#define EOWNERDEAD 130 -#define ENOTRECOVERABLE 131 -#define ERFKILL 132 -#define EHWPOISON 133 -#define ENOTSUP EOPNOTSUPP - -__BEGIN_DECLS - -#ifndef errno -int * _TLIBC_CDECL_ __errno(void); -#define errno (*__errno()) -#endif /* errno */ -__END_DECLS - -#endif /* _ERRNO_H_ */ diff --git a/tee-worker/bitacross/rust-sgx-sdk/common/inc/fenv.h b/tee-worker/bitacross/rust-sgx-sdk/common/inc/fenv.h deleted file mode 100644 index a233172a41..0000000000 --- a/tee-worker/bitacross/rust-sgx-sdk/common/inc/fenv.h +++ /dev/null @@ -1,139 +0,0 @@ -/* $OpenBSD: fenv.h,v 1.2 2011/05/25 21:46:49 martynas Exp $ */ -/* $NetBSD: fenv.h,v 1.2.4.1 2011/02/08 16:18:55 bouyer Exp $ */ - -/* - * Copyright (c) 2010 The NetBSD Foundation, Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS - * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED - * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef _FENV_H_ -#define _FENV_H_ - -#include - -/* - * Each symbol representing a floating point exception expands to an integer - * constant expression with values, such that bitwise-inclusive ORs of _all - * combinations_ of the constants result in distinct values. - * - * We use such values that allow direct bitwise operations on FPU/SSE registers. - */ -#define FE_INVALID 0x01 -#define FE_DENORMAL 0x02 -#define FE_DIVBYZERO 0x04 -#define FE_OVERFLOW 0x08 -#define FE_UNDERFLOW 0x10 -#define FE_INEXACT 0x20 - -/* - * The following symbol is simply the bitwise-inclusive OR of all floating-point - * exception constants defined above. - */ -#define FE_ALL_EXCEPT (FE_INVALID | FE_DENORMAL | FE_DIVBYZERO | \ - FE_OVERFLOW | FE_UNDERFLOW | FE_INEXACT) -#define _SSE_MASK_SHIFT 7 - -/* - * Each symbol representing the rounding direction, expands to an integer - * constant expression whose value is distinct non-negative value. - * - * We use such values that allow direct bitwise operations on FPU/SSE registers. - */ -#define FE_TONEAREST 0x000 -#define FE_DOWNWARD 0x400 -#define FE_UPWARD 0x800 -#define FE_TOWARDZERO 0xc00 - -/* - * The following symbol is simply the bitwise-inclusive OR of all floating-point - * rounding direction constants defined above. - */ -#define _X87_ROUND_MASK (FE_TONEAREST | FE_DOWNWARD | FE_UPWARD | \ - FE_TOWARDZERO) -#define _SSE_ROUND_SHIFT 3 - -/* - * fenv_t represents the entire floating-point environment. - */ -typedef struct { - struct { - unsigned int __control; /* Control word register */ - unsigned int __status; /* Status word register */ - unsigned int __tag; /* Tag word register */ - unsigned int __others[4]; /* EIP, Pointer Selector, etc */ - } __x87; - unsigned int __mxcsr; /* Control, status register */ -} fenv_t; - -/* - * The following constant represents the default floating-point environment - * (that is, the one installed at program startup) and has type pointer to - * const-qualified fenv_t. - * - * It can be used as an argument to the functions within the header - * that manage the floating-point environment, namely fesetenv() and - * feupdateenv(). - */ -__BEGIN_DECLS -extern fenv_t __fe_dfl_env; -__END_DECLS -#define FE_DFL_ENV ((const fenv_t *)&__fe_dfl_env) - -/* - * fexcept_t represents the floating-point status flags collectively, including - * any status the implementation associates with the flags. - * - * A floating-point status flag is a system variable whose value is set (but - * never cleared) when a floating-point exception is raised, which occurs as a - * side effect of exceptional floating-point arithmetic to provide auxiliary - * information. - * - * A floating-point control mode is a system variable whose value may be set by - * the user to affect the subsequent behavior of floating-point arithmetic. - */ -typedef unsigned int fexcept_t; - -__BEGIN_DECLS - -int feclearexcept(int); -int fegetexceptflag(fexcept_t *, int); -int feraiseexcept(int); -int fesetexceptflag(const fexcept_t *, int); -int fetestexcept(int); - -int fegetround(void); -int fesetround(int); - -int fegetenv(fenv_t *); -int feholdexcept(fenv_t *); -int fesetenv(const fenv_t *); -int feupdateenv(const fenv_t *); - -int feenableexcept(int); -int fedisableexcept(int); -int fegetexcept(void); - -__END_DECLS - -#endif /* ! _FENV_H_ */ diff --git a/tee-worker/bitacross/rust-sgx-sdk/common/inc/float.h b/tee-worker/bitacross/rust-sgx-sdk/common/inc/float.h deleted file mode 100644 index e38a7c6a9f..0000000000 --- a/tee-worker/bitacross/rust-sgx-sdk/common/inc/float.h +++ /dev/null @@ -1,84 +0,0 @@ -/* $OpenBSD: float.h,v 1.3 2008/07/21 20:50:54 martynas Exp $ */ -/* $NetBSD: float.h,v 1.8 1995/06/20 20:45:37 jtc Exp $ */ - -/* - * Copyright (c) 1989 Regents of the University of California. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS - * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY - * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - * - * @(#)float.h 7.1 (Berkeley) 5/8/90 - */ - -#ifndef _FLOAT_H_ -#define _FLOAT_H_ - -#include - -#define FLT_RADIX 2 /* b */ - -// The rounding direction can be specified by fesetround() in -#define FLT_ROUNDS 1 /* addition rounding: near */ -#define DECIMAL_DIG 21 /* max precision in decimal digits */ - -// NOTE: FLT_EVAL_METHOD is -1 under FREEBSD x86. -#ifdef __i386__ -#define FLT_EVAL_METHOD 2 /* long double */ -#else -#define FLT_EVAL_METHOD 0 /* no promotions */ -#endif - -#define DBL_MANT_DIG 53 -#define DBL_EPSILON 2.2204460492503131E-16 -#define DBL_DIG 15 -#define DBL_MIN_EXP (-1021) -#define DBL_MIN 2.2250738585072014E-308 -#define DBL_MIN_10_EXP (-307) -#define DBL_MAX_EXP 1024 -#define DBL_MAX_10_EXP 308 - -#define FLT_MANT_DIG 24 /* p */ -#define FLT_DIG 6 /* floor((p-1)*log10(b))+(b == 10) */ -#define FLT_MIN_EXP (-125) /* emin */ -#define FLT_MIN_10_EXP (-37) /* ceil(log10(b**(emin-1))) */ -#define FLT_MAX_EXP 128 /* emax */ -#define FLT_MAX_10_EXP 38 /* floor(log10((1-b**(-p))*b**emax)) */ - -#define DBL_MAX 1.7976931348623157E+308 -#define FLT_EPSILON 1.19209290E-07F /* b**(1-p) */ -#define FLT_MIN 1.17549435E-38F /* b**(emin-1) */ -#define FLT_MAX 3.40282347E+38F /* (1-b**(-p))*b**emax */ - -#define LDBL_MANT_DIG 64 -#define LDBL_EPSILON 1.08420217248550443401e-19L -#define LDBL_DIG 18 -#define LDBL_MIN_EXP (-16381) -#define LDBL_MIN 3.36210314311209350626e-4932L -#define LDBL_MIN_10_EXP (-4931) -#define LDBL_MAX_EXP 16384 -#define LDBL_MAX 1.18973149535723176502e+4932L -#define LDBL_MAX_10_EXP 4932 - -#endif /* _FLOAT_H_ */ diff --git a/tee-worker/bitacross/rust-sgx-sdk/common/inc/inttypes.h b/tee-worker/bitacross/rust-sgx-sdk/common/inc/inttypes.h deleted file mode 100644 index fbc009c975..0000000000 --- a/tee-worker/bitacross/rust-sgx-sdk/common/inc/inttypes.h +++ /dev/null @@ -1,330 +0,0 @@ -/* $OpenBSD: inttypes.h,v 1.10 2009/01/13 18:13:51 kettenis Exp $ */ - -/* - * Copyright (c) 1997, 2005 Todd C. Miller - * - * Permission to use, copy, modify, and distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -#ifndef _INTTYPES_H_ -#define _INTTYPES_H_ - -#include - -/* - * 7.8.1 Macros for format specifiers - * - * Each of the following object-like macros expands to a string - * literal containing a conversion specifier, possibly modified by - * a prefix such as hh, h, l, or ll, suitable for use within the - * format argument of a formatted input/output function when - * converting the corresponding integer type. These macro names - * have the general form of PRI (character string literals for the - * fprintf family) or SCN (character string literals for the fscanf - * family), followed by the conversion specifier, followed by a - * name corresponding to a similar typedef name. For example, - * PRIdFAST32 can be used in a format string to print the value of - * an integer of type int_fast32_t. - */ - -/* fprintf macros for signed integers */ -#define PRId8 "d" /* int8_t */ -#define PRId16 "d" /* int16_t */ -#define PRId32 "d" /* int32_t */ -#ifdef __x86_64__ -#define PRId64 "ld" /* int64_t */ -#else -#define PRId64 "lld" /* int64_t */ -#endif - -#define PRIdLEAST8 "d" /* int_least8_t */ -#define PRIdLEAST16 "d" /* int_least16_t */ -#define PRIdLEAST32 "d" /* int_least32_t */ -#ifdef __x86_64__ -#define PRIdLEAST64 "ld" /* int_least64_t */ -#else -#define PRIdLEAST64 "lld" /* int_least64_t */ -#endif - -#define PRIdFAST8 "d" /* int_fast8_t */ -#ifdef __x86_64__ -#define PRIdFAST16 "ld" /* int_fast16_t */ -#define PRIdFAST32 "ld" /* int_fast32_t */ -#define PRIdFAST64 "ld" /* int_fast64_t */ -#else -#define PRIdFAST16 "d" /* int_fast16_t */ -#define PRIdFAST32 "d" /* int_fast32_t */ -#define PRIdFAST64 "lld" /* int_fast64_t */ -#endif - -#ifdef __x86_64__ -#define PRIdMAX "ld" /* intmax_t */ -#else -#if defined(__i386__) -#define PRIdMAX "lld" /* intmax_t */ -#else -#define PRIdMAX "jd" /* intmax_t */ -#endif -#endif - -#ifdef __i386__ -#define PRIdPTR "d" /* intptr_t */ -#else -#define PRIdPTR "ld" /* intptr_t */ -#endif - -#define PRIi8 "i" /* int8_t */ -#define PRIi16 "i" /* int16_t */ -#define PRIi32 "i" /* int32_t */ -#ifdef __x86_64__ -#define PRIi64 "li" /* int64_t */ -#else -#define PRIi64 "lli" /* int64_t */ -#endif - -#define PRIiLEAST8 "i" /* int_least8_t */ -#define PRIiLEAST16 "i" /* int_least16_t */ -#define PRIiLEAST32 "i" /* int_least32_t */ -#ifdef __x86_64__ -#define PRIiLEAST64 "li" /* int_least64_t */ -#else -#define PRIiLEAST64 "lli" /* int_least64_t */ -#endif - -#define PRIiFAST8 "i" /* int_fast8_t */ -#ifdef __x86_64__ -#define PRIiFAST16 "li" /* int_fast16_t */ -#define PRIiFAST32 "li" /* int_fast32_t */ -#define PRIiFAST64 "li" /* int_fast64_t */ -#else -#define PRIiFAST16 "i" /* int_fast16_t */ -#define PRIiFAST32 "i" /* int_fast32_t */ -#define PRIiFAST64 "lli" /* int_fast64_t */ -#endif - -#ifdef __x86_64__ -#define PRIiMAX "li" /* intmax_t */ -#else -#if defined(__i386__) -#define PRIiMAX "lli" /* intmax_t */ -#else -#define PRIiMAX "ji" /* intmax_t */ -#endif -#endif - -#ifdef __i386__ -#define PRIiPTR "i" /* intptr_t */ -#else -#define PRIiPTR "li" /* intptr_t */ -#endif - -/* fprintf macros for unsigned integers */ -#define PRIo8 "o" /* int8_t */ -#define PRIo16 "o" /* int16_t */ -#define PRIo32 "o" /* int32_t */ -#ifdef __x86_64__ -#define PRIo64 "lo" /* int64_t */ -#else -#define PRIo64 "llo" /* int64_t */ -#endif - -#define PRIoLEAST8 "o" /* int_least8_t */ -#define PRIoLEAST16 "o" /* int_least16_t */ -#define PRIoLEAST32 "o" /* int_least32_t */ -#ifdef __x86_64__ -#define PRIoLEAST64 "lo" /* int_least64_t */ -#else -#define PRIoLEAST64 "llo" /* int_least64_t */ -#endif - -#define PRIoFAST8 "o" /* int_fast8_t */ -#ifdef __x86_64__ -#define PRIoFAST16 "lo" /* int_fast16_t */ -#define PRIoFAST32 "lo" /* int_fast32_t */ -#define PRIoFAST64 "lo" /* int_fast64_t */ -#else -#define PRIoFAST16 "o" /* int_fast16_t */ -#define PRIoFAST32 "o" /* int_fast32_t */ -#define PRIoFAST64 "llo" /* int_fast64_t */ -#endif - -#ifdef __x86_64__ -#define PRIoMAX "lo" /* intmax_t */ -#else -#if defined(__i386__) -#define PRIoMAX "llo" /* intmax_t */ -#else -#define PRIoMAX "jo" /* intmax_t */ -#endif -#endif - -#ifdef __i386__ -#define PRIoPTR "o" /* intptr_t */ -#else -#define PRIoPTR "lo" /* intptr_t */ -#endif - -#define PRIu8 "u" /* uint8_t */ -#define PRIu16 "u" /* uint16_t */ -#define PRIu32 "u" /* uint32_t */ - -#ifdef __x86_64__ -#define PRIu64 "lu" /* uint64_t */ -#else -#define PRIu64 "llu" /* uint64_t */ -#endif - -#define PRIuLEAST8 "u" /* uint_least8_t */ -#define PRIuLEAST16 "u" /* uint_least16_t */ -#define PRIuLEAST32 "u" /* uint_least32_t */ - -#ifdef __x86_64__ -#define PRIuLEAST64 "lu" /* uint_least64_t */ -#else -#define PRIuLEAST64 "llu" /* uint_least64_t */ -#endif - -#define PRIuFAST8 "u" /* uint_fast8_t */ - -#ifdef __x86_64__ -#define PRIuFAST16 "lu" /* uint_fast16_t */ -#define PRIuFAST32 "lu" /* uint_fast32_t */ -#define PRIuFAST64 "lu" /* uint_fast64_t */ -#else -#define PRIuFAST16 "u" /* uint_fast16_t */ -#define PRIuFAST32 "u" /* uint_fast32_t */ -#define PRIuFAST64 "llu" /* uint_fast64_t */ -#endif - -#ifdef __x86_64__ -#define PRIuMAX "lu" /* uintmax_t */ -#else -#if defined(__i386__) -#define PRIuMAX "llu" /* uintmax_t */ -#else -#define PRIuMAX "ju" /* uintmax_t */ -#endif -#endif - -#ifdef __i386__ -#define PRIuPTR "u" /* uintptr_t */ -#else -#define PRIuPTR "lu" /* uintptr_t */ -#endif - -#define PRIx8 "x" /* uint8_t */ -#define PRIx16 "x" /* uint16_t */ -#define PRIx32 "x" /* uint32_t */ -#ifdef __x86_64__ -#define PRIx64 "lx" /* uint64_t */ -#else -#define PRIx64 "llx" /* uint64_t */ -#endif - -#define PRIxLEAST8 "x" /* uint_least8_t */ -#define PRIxLEAST16 "x" /* uint_least16_t */ -#define PRIxLEAST32 "x" /* uint_least32_t */ -#ifdef __x86_64__ -#define PRIxLEAST64 "lx" /* uint_least64_t */ -#else -#define PRIxLEAST64 "llx" /* uint_least64_t */ -#endif - -#define PRIxFAST8 "x" /* uint_fast8_t */ -#ifdef __x86_64__ -#define PRIxFAST16 "lx" /* uint_fast16_t */ -#define PRIxFAST32 "lx" /* uint_fast32_t */ -#define PRIxFAST64 "lx" /* uint_fast64_t */ -#else -#define PRIxFAST16 "x" /* uint_fast16_t */ -#define PRIxFAST32 "x" /* uint_fast32_t */ -#define PRIxFAST64 "llx" /* uint_fast64_t */ -#endif - -#ifdef __x86_64__ -#define PRIxMAX "lx" /* uintmax_t */ -#else -#if defined(__i386__) -#define PRIxMAX "llx" /* uintmax_t */ -#else -#define PRIxMAX "jx" /* uintmax_t */ -#endif -#endif - -#ifdef __i386__ -#define PRIxPTR "x" /* uintptr_t */ -#else -#define PRIxPTR "lx" /* uintptr_t */ -#endif - -#define PRIX8 "X" /* uint8_t */ -#define PRIX16 "X" /* uint16_t */ -#define PRIX32 "X" /* uint32_t */ - -#ifdef __x86_64__ -#define PRIX64 "lX" /* uint64_t */ -#else -#define PRIX64 "llX" /* uint64_t */ -#endif - -#define PRIXLEAST8 "X" /* uint_least8_t */ -#define PRIXLEAST16 "X" /* uint_least16_t */ -#define PRIXLEAST32 "X" /* uint_least32_t */ -#ifdef __x86_64__ -#define PRIXLEAST64 "lX" /* uint_least64_t */ -#else -#define PRIXLEAST64 "llX" /* uint_least64_t */ -#endif - -#define PRIXFAST8 "X" /* uint_fast8_t */ -#ifdef __x86_64__ -#define PRIXFAST16 "lX" /* uint_fast16_t */ -#define PRIXFAST32 "lX" /* uint_fast32_t */ -#define PRIXFAST64 "lX" /* uint_fast64_t */ -#else -#define PRIXFAST16 "X" /* uint_fast16_t */ -#define PRIXFAST32 "X" /* uint_fast32_t */ -#define PRIXFAST64 "llX" /* uint_fast64_t */ -#endif - -#ifdef __x86_64__ -#define PRIXMAX "lX" /* uintmax_t */ -#else -#if defined(__i386__) -#define PRIXMAX "llX" /* uintmax_t */ -#else -#define PRIXMAX "jX" /* uintmax_t */ -#endif -#endif - -#ifdef __i386__ -#define PRIXPTR "X" /* uintptr_t */ -#else -#define PRIXPTR "lX" /* uintptr_t */ -#endif - -typedef struct { - intmax_t quot; /* quotient */ - intmax_t rem; /* remainder */ -} imaxdiv_t; - -__BEGIN_DECLS - -intmax_t _TLIBC_CDECL_ imaxabs(intmax_t); -imaxdiv_t _TLIBC_CDECL_ imaxdiv(intmax_t, intmax_t); -intmax_t _TLIBC_CDECL_ strtoimax(const char *, char **, int); -uintmax_t _TLIBC_CDECL_ strtoumax(const char *, char **, int); - -__END_DECLS - -#endif /* _INTTYPES_H_ */ diff --git a/tee-worker/bitacross/rust-sgx-sdk/common/inc/iso646.h b/tee-worker/bitacross/rust-sgx-sdk/common/inc/iso646.h deleted file mode 100644 index a0c341b658..0000000000 --- a/tee-worker/bitacross/rust-sgx-sdk/common/inc/iso646.h +++ /dev/null @@ -1,26 +0,0 @@ -/* $OpenBSD: iso646.h,v 1.3 2001/10/11 00:05:21 espie Exp $ */ -/* $NetBSD: iso646.h,v 1.1 1995/02/17 09:08:10 jtc Exp $ */ - -/* - * Written by J.T. Conklin 02/16/95. - * Public domain. - */ - -#ifndef _ISO646_H_ -#define _ISO646_H_ - -#ifndef __cplusplus -#define and && -#define and_eq &= -#define bitand & -#define bitor | -#define compl ~ -#define not ! -#define not_eq != -#define or || -#define or_eq |= -#define xor ^ -#define xor_eq ^= -#endif - -#endif /* !_ISO646_H_ */ diff --git a/tee-worker/bitacross/rust-sgx-sdk/common/inc/limits.h b/tee-worker/bitacross/rust-sgx-sdk/common/inc/limits.h deleted file mode 100644 index 9d42cb545c..0000000000 --- a/tee-worker/bitacross/rust-sgx-sdk/common/inc/limits.h +++ /dev/null @@ -1,41 +0,0 @@ -/* $OpenBSD: limits.h,v 1.15 2008/02/10 09:59:54 kettenis Exp $ */ -/* $NetBSD: limits.h,v 1.7 1994/10/26 00:56:00 cgd Exp $ */ - -/* - * Copyright (c) 1988 The Regents of the University of California. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS - * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY - * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - * - * @(#)limits.h 5.9 (Berkeley) 4/3/91 - */ - - -#ifndef _LIMITS_H_ -#define _LIMITS_H_ - -#include - -#endif /* !_LIMITS_H_ */ diff --git a/tee-worker/bitacross/rust-sgx-sdk/common/inc/math.h b/tee-worker/bitacross/rust-sgx-sdk/common/inc/math.h deleted file mode 100644 index 6ea425b840..0000000000 --- a/tee-worker/bitacross/rust-sgx-sdk/common/inc/math.h +++ /dev/null @@ -1,430 +0,0 @@ -/* $OpenBSD: math.h,v 1.27 2010/12/14 11:16:15 martynas Exp $ */ -/* - * ==================================================== - * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. - * - * Developed at SunPro, a Sun Microsystems, Inc. business. - * Permission to use, copy, modify, and distribute this - * software is freely granted, provided that this notice - * is preserved. - * ==================================================== - */ - -/* - * from: @(#)fdlibm.h 5.1 93/09/24 - */ - -#ifndef _MATH_H_ -#define _MATH_H_ - -#include -#include -#include - -#include - -typedef __float_t float_t; -typedef __double_t double_t; - -#define FP_NAN 0x00 -#define FP_INFINITE 0x01 -#define FP_ZERO 0x02 -#define FP_SUBNORMAL 0x03 -#define FP_NORMAL 0x04 - -#define FP_ILOGB0 (-INT_MAX - 1) -#define FP_ILOGBNAN (-INT_MAX - 1) - -#define fpclassify(x) \ - ((sizeof (x) == sizeof (float)) ? \ - __fpclassifyf(x) \ - : (sizeof (x) == sizeof (double)) ? \ - __fpclassify(x) \ - : __fpclassifyl(x)) -#define isfinite(x) \ - ((sizeof (x) == sizeof (float)) ? \ - __isfinitef(x) \ - : (sizeof (x) == sizeof (double)) ? \ - __isfinite(x) \ - : __isfinitel(x)) -#define isnormal(x) \ - ((sizeof (x) == sizeof (float)) ? \ - __isnormalf(x) \ - : (sizeof (x) == sizeof (double)) ? \ - __isnormal(x) \ - : __isnormall(x)) -#define signbit(x) \ - ((sizeof (x) == sizeof (float)) ? \ - __signbitf(x) \ - : (sizeof (x) == sizeof (double)) ? \ - __signbit(x) \ - : __signbitl(x)) -#define isinf(x) \ - ((sizeof (x) == sizeof (float)) ? \ - __isinff(x) \ - : (sizeof (x) == sizeof (double)) ? \ - __isinf(x) \ - : __isinfl(x)) -#define isnan(x) \ - ((sizeof (x) == sizeof (float)) ? \ - __isnanf(x) \ - : (sizeof (x) == sizeof (double)) ? \ - __isnan(x) \ - : __isnanl(x)) - -#define isgreater(x, y) (!isunordered((x), (y)) && (x) > (y)) -#define isgreaterequal(x, y) (!isunordered((x), (y)) && (x) >= (y)) -#define isless(x, y) (!isunordered((x), (y)) && (x) < (y)) -#define islessequal(x, y) (!isunordered((x), (y)) && (x) <= (y)) -#define islessgreater(x, y) (!isunordered((x), (y)) && ((x) > (y) || (y) > (x))) -#define isunordered(x, y) (isnan(x) || isnan(y)) - -__BEGIN_DECLS - -extern char __infinity[]; -#define HUGE_VAL (*(double *)(void *)__infinity) -#define HUGE_VALF ((float)HUGE_VAL) -#define HUGE_VALL ((long double)HUGE_VAL) -#define INFINITY HUGE_VALF -extern char __nan[]; -#define NAN (*(float *)(void *)__nan) - -/* - * ANSI/POSIX - */ -double _TLIBC_CDECL_ acos(double); -double _TLIBC_CDECL_ asin(double); -double _TLIBC_CDECL_ atan(double); -double _TLIBC_CDECL_ atan2(double, double); -double _TLIBC_CDECL_ cos(double); -double _TLIBC_CDECL_ sin(double); -double _TLIBC_CDECL_ tan(double); - -double _TLIBC_CDECL_ cosh(double); -double _TLIBC_CDECL_ sinh(double); -double _TLIBC_CDECL_ tanh(double); - -double _TLIBC_CDECL_ exp(double); -double _TLIBC_CDECL_ frexp(double, int *); -double _TLIBC_CDECL_ ldexp(double, int); -double _TLIBC_CDECL_ log(double); -double _TLIBC_CDECL_ log10(double); -double _TLIBC_CDECL_ modf(double, double *); - -double _TLIBC_CDECL_ pow(double, double); -double _TLIBC_CDECL_ sqrt(double); - -double _TLIBC_CDECL_ ceil(double); -double _TLIBC_CDECL_ fabs(double); -double _TLIBC_CDECL_ floor(double); -double _TLIBC_CDECL_ fmod(double, double); - -/* - * C99 - */ -double _TLIBC_CDECL_ acosh(double); -double _TLIBC_CDECL_ asinh(double); -double _TLIBC_CDECL_ atanh(double); - -double _TLIBC_CDECL_ exp2(double); -double _TLIBC_CDECL_ expm1(double); -int _TLIBC_CDECL_ ilogb(double); -double _TLIBC_CDECL_ log1p(double); -double _TLIBC_CDECL_ log2(double); -double _TLIBC_CDECL_ logb(double); -double _TLIBC_CDECL_ scalbn(double, int); -double _TLIBC_CDECL_ scalbln(double, long int); - -double _TLIBC_CDECL_ cbrt(double); -double _TLIBC_CDECL_ hypot(double, double); - -double _TLIBC_CDECL_ erf(double); -double _TLIBC_CDECL_ erfc(double); -double _TLIBC_CDECL_ lgamma(double); -double _TLIBC_CDECL_ tgamma(double); - -double _TLIBC_CDECL_ nearbyint(double); -double _TLIBC_CDECL_ rint(double); -long int _TLIBC_CDECL_ lrint(double); -long long int _TLIBC_CDECL_ llrint(double); -double _TLIBC_CDECL_ round(double); -long int _TLIBC_CDECL_ lround(double); -long long int _TLIBC_CDECL_ llround(double); -double _TLIBC_CDECL_ trunc(double); - -double _TLIBC_CDECL_ remainder(double, double); -double _TLIBC_CDECL_ remquo(double, double, int *); - -double _TLIBC_CDECL_ copysign(double, double); -double _TLIBC_CDECL_ nan(const char *); -double _TLIBC_CDECL_ nextafter(double, double); - -double _TLIBC_CDECL_ fdim(double, double); -double _TLIBC_CDECL_ fmax(double, double); -double _TLIBC_CDECL_ fmin(double, double); - -double _TLIBC_CDECL_ fma(double, double, double); - -/* - * Float versions of C99 functions - */ - -float _TLIBC_CDECL_ acosf(float); -float _TLIBC_CDECL_ asinf(float); -float _TLIBC_CDECL_ atanf(float); -float _TLIBC_CDECL_ atan2f(float, float); -float _TLIBC_CDECL_ cosf(float); -float _TLIBC_CDECL_ sinf(float); -float _TLIBC_CDECL_ tanf(float); - -float _TLIBC_CDECL_ acoshf(float); -float _TLIBC_CDECL_ asinhf(float); -float _TLIBC_CDECL_ atanhf(float); -float _TLIBC_CDECL_ coshf(float); -float _TLIBC_CDECL_ sinhf(float); -float _TLIBC_CDECL_ tanhf(float); - -float _TLIBC_CDECL_ expf(float); -float _TLIBC_CDECL_ exp2f(float); -float _TLIBC_CDECL_ expm1f(float); -float _TLIBC_CDECL_ frexpf(float, int *); -int _TLIBC_CDECL_ ilogbf(float); -float _TLIBC_CDECL_ ldexpf(float, int); -float _TLIBC_CDECL_ logf(float); -float _TLIBC_CDECL_ log10f(float); -float _TLIBC_CDECL_ log1pf(float); -float _TLIBC_CDECL_ log2f(float); -float _TLIBC_CDECL_ logbf(float); -float _TLIBC_CDECL_ modff(float, float *); -float _TLIBC_CDECL_ scalbnf(float, int); -float _TLIBC_CDECL_ scalblnf(float, long int); - -float _TLIBC_CDECL_ cbrtf(float); -float _TLIBC_CDECL_ fabsf(float); -float _TLIBC_CDECL_ hypotf(float, float); -float _TLIBC_CDECL_ powf(float, float); -float _TLIBC_CDECL_ sqrtf(float); - -float _TLIBC_CDECL_ erff(float); -float _TLIBC_CDECL_ erfcf(float); -float _TLIBC_CDECL_ lgammaf(float); -float _TLIBC_CDECL_ tgammaf(float); - -float _TLIBC_CDECL_ ceilf(float); -float _TLIBC_CDECL_ floorf(float); -float _TLIBC_CDECL_ nearbyintf(float); - -float _TLIBC_CDECL_ rintf(float); -long int _TLIBC_CDECL_ lrintf(float); -long long int _TLIBC_CDECL_ llrintf(float); -float _TLIBC_CDECL_ roundf(float); -long int _TLIBC_CDECL_ lroundf(float); -long long int _TLIBC_CDECL_ llroundf(float); -float _TLIBC_CDECL_ truncf(float); - -float _TLIBC_CDECL_ fmodf(float, float); -float _TLIBC_CDECL_ remainderf(float, float); -float _TLIBC_CDECL_ remquof(float, float, int *); - -float _TLIBC_CDECL_ copysignf(float, float); -float _TLIBC_CDECL_ nanf(const char *); -float _TLIBC_CDECL_ nextafterf(float, float); - -float _TLIBC_CDECL_ fdimf(float, float); -float _TLIBC_CDECL_ fmaxf(float, float); -float _TLIBC_CDECL_ fminf(float, float); - -float _TLIBC_CDECL_ fmaf(float, float, float); - -/* - * Long double versions of C99 functions - */ - -/* Macros defining long double functions to be their double counterparts - * (long double is synonymous with double in this implementation). - */ - -long double _TLIBC_CDECL_ acosl(long double); -long double _TLIBC_CDECL_ asinl(long double); -long double _TLIBC_CDECL_ atanl(long double); -long double _TLIBC_CDECL_ atan2l(long double, long double); -long double _TLIBC_CDECL_ cosl(long double); -long double _TLIBC_CDECL_ sinl(long double); -long double _TLIBC_CDECL_ tanl(long double); - -long double _TLIBC_CDECL_ acoshl(long double); -long double _TLIBC_CDECL_ asinhl(long double); -long double _TLIBC_CDECL_ atanhl(long double); -long double _TLIBC_CDECL_ coshl(long double); -long double _TLIBC_CDECL_ sinhl(long double); -long double _TLIBC_CDECL_ tanhl(long double); - -long double _TLIBC_CDECL_ expl(long double); -long double _TLIBC_CDECL_ exp2l(long double); -long double _TLIBC_CDECL_ expm1l(long double); -long double _TLIBC_CDECL_ frexpl(long double, int *); -int _TLIBC_CDECL_ ilogbl(long double); -long double _TLIBC_CDECL_ ldexpl(long double, int); -long double _TLIBC_CDECL_ logl(long double); -long double _TLIBC_CDECL_ log10l(long double); -long double _TLIBC_CDECL_ log1pl(long double); -long double _TLIBC_CDECL_ log2l(long double); -long double _TLIBC_CDECL_ logbl(long double); -long double _TLIBC_CDECL_ modfl(long double, long double *); -long double _TLIBC_CDECL_ scalbnl(long double, int); -long double _TLIBC_CDECL_ scalblnl(long double, long int); - -long double _TLIBC_CDECL_ cbrtl(long double); -long double _TLIBC_CDECL_ fabsl(long double); -long double _TLIBC_CDECL_ hypotl(long double, long double); -long double _TLIBC_CDECL_ powl(long double, long double); -long double _TLIBC_CDECL_ sqrtl(long double); - -long double _TLIBC_CDECL_ erfl(long double); -long double _TLIBC_CDECL_ erfcl(long double); -long double _TLIBC_CDECL_ lgammal(long double); -long double _TLIBC_CDECL_ tgammal(long double); - -long double _TLIBC_CDECL_ ceill(long double); -long double _TLIBC_CDECL_ floorl(long double); -long double _TLIBC_CDECL_ nearbyintl(long double); -long double _TLIBC_CDECL_ rintl(long double); -long int _TLIBC_CDECL_ lrintl(long double); -long long int _TLIBC_CDECL_ llrintl(long double); -long double _TLIBC_CDECL_ roundl(long double); -long int _TLIBC_CDECL_ lroundl(long double); -long long int _TLIBC_CDECL_ llroundl(long double); -long double _TLIBC_CDECL_ truncl(long double); - -long double _TLIBC_CDECL_ fmodl(long double, long double); -long double _TLIBC_CDECL_ remainderl(long double, long double); -long double _TLIBC_CDECL_ remquol(long double, long double, int *); - -long double _TLIBC_CDECL_ copysignl(long double, long double); -long double _TLIBC_CDECL_ nanl(const char *); -long double _TLIBC_CDECL_ nextafterl(long double, long double); - -long double _TLIBC_CDECL_ fdiml(long double, long double); -long double _TLIBC_CDECL_ fmaxl(long double, long double); -long double _TLIBC_CDECL_ fminl(long double, long double); -long double _TLIBC_CDECL_ fmal(long double, long double, long double); - -/* nexttoward(): -* The implementation in Intel math library is incompatible with MSVC. -* Because sizeof(long double) is 8bytes with MSVC, -* but the expected long double size is 10bytes. -* And by default, MSVC doesn't provide nexttoward(). -* So we only provide Linux version here. -*/ -double _TLIBC_CDECL_ nexttoward(double, long double); -float _TLIBC_CDECL_ nexttowardf(float, long double); - -long double _TLIBC_CDECL_ nexttowardl(long double, long double); - -/* - * Library implementation - */ -int _TLIBC_CDECL_ __fpclassify(double); -int _TLIBC_CDECL_ __fpclassifyf(float); -int _TLIBC_CDECL_ __isfinite(double); -int _TLIBC_CDECL_ __isfinitef(float); -int _TLIBC_CDECL_ __isinf(double); -int _TLIBC_CDECL_ __isinff(float); -int _TLIBC_CDECL_ __isnan(double); -int _TLIBC_CDECL_ __isnanf(float); -int _TLIBC_CDECL_ __isnormal(double); -int _TLIBC_CDECL_ __isnormalf(float); -int _TLIBC_CDECL_ __signbit(double); -int _TLIBC_CDECL_ __signbitf(float); - -int _TLIBC_CDECL_ __fpclassifyl(long double); -int _TLIBC_CDECL_ __isfinitel(long double); -int _TLIBC_CDECL_ __isinfl(long double); -int _TLIBC_CDECL_ __isnanl(long double); -int _TLIBC_CDECL_ __isnormall(long double); -int _TLIBC_CDECL_ __signbitl(long double); - -/* - * Non-C99 functions. - */ -double _TLIBC_CDECL_ drem(double, double); -double _TLIBC_CDECL_ exp10(double); -double _TLIBC_CDECL_ gamma(double); -double _TLIBC_CDECL_ gamma_r(double, int *); -double _TLIBC_CDECL_ j0(double); -double _TLIBC_CDECL_ j1(double); -double _TLIBC_CDECL_ jn(int, double); -double _TLIBC_CDECL_ lgamma_r(double, int *); -double _TLIBC_CDECL_ pow10(double); -double _TLIBC_CDECL_ scalb(double, double); -/* C99 Macro signbit.*/ -double _TLIBC_CDECL_ significand(double); -void _TLIBC_CDECL_ sincos(double, double *, double *); -double _TLIBC_CDECL_ y0(double); -double _TLIBC_CDECL_ y1(double); -double _TLIBC_CDECL_ yn(int, double); -/* C99 Macro isinf.*/ -/* C99 Macro isnan.*/ -int _TLIBC_CDECL_ finite(double); - -float _TLIBC_CDECL_ dremf(float, float); -float _TLIBC_CDECL_ exp10f(float); -float _TLIBC_CDECL_ gammaf(float); -float _TLIBC_CDECL_ gammaf_r(float, int *); -float _TLIBC_CDECL_ j0f(float); -float _TLIBC_CDECL_ j1f(float); -float _TLIBC_CDECL_ jnf(int, float); -float _TLIBC_CDECL_ lgammaf_r(float, int *); -float _TLIBC_CDECL_ pow10f(float); -float _TLIBC_CDECL_ scalbf(float, float); -int _TLIBC_CDECL_ signbitf(float); -float _TLIBC_CDECL_ significandf(float); -void _TLIBC_CDECL_ sincosf(float, float *, float *); -float _TLIBC_CDECL_ y0f(float); -float _TLIBC_CDECL_ y1f(float); -float _TLIBC_CDECL_ ynf(int, float); -int _TLIBC_CDECL_ finitef(float); -int _TLIBC_CDECL_ isinff(float); -int _TLIBC_CDECL_ isnanf(float); - -long double _TLIBC_CDECL_ dreml(long double, long double); -long double _TLIBC_CDECL_ exp10l(long double); -long double _TLIBC_CDECL_ gammal(long double); -long double _TLIBC_CDECL_ gammal_r(long double, int *); -long double _TLIBC_CDECL_ j0l(long double); -long double _TLIBC_CDECL_ j1l(long double); -long double _TLIBC_CDECL_ jnl(int, long double); -long double _TLIBC_CDECL_ lgammal_r(long double, int *); -long double _TLIBC_CDECL_ pow10l(long double); -long double _TLIBC_CDECL_ scalbl(long double, long double); -int _TLIBC_CDECL_ signbitl(long double); -long double _TLIBC_CDECL_ significandl(long double); -void _TLIBC_CDECL_ sincosl(long double, long double *, long double *); -long double _TLIBC_CDECL_ y1l(long double); -long double _TLIBC_CDECL_ y0l(long double); -long double _TLIBC_CDECL_ ynl(int, long double); -int _TLIBC_CDECL_ finitel(long double); -int _TLIBC_CDECL_ isinfl(long double); -int _TLIBC_CDECL_ isnanl(long double); - -/* - * TODO: From Intel Decimal Floating-Point Math Library - * signbitd32/signbitd64/signbitd128, finited32/finited64/finited128 - * isinfd32/isinfd64/isinfd128, isnand32/isnand64/isnand128 - */ -#if defined(__cplusplus) -/* Clang does not support decimal floating point types. - * - * c.f.: - * http://clang.llvm.org/docs/UsersManual.html#gcc-extensions-not-implemented-yet - */ -#if !defined(__clang__) -typedef float _Decimal32 __attribute__((mode(SD))); -typedef float _Decimal64 __attribute__((mode(DD))); -typedef float _Decimal128 __attribute__((mode(TD))); -#endif -#endif - -__END_DECLS - -#endif /* !_MATH_H_ */ diff --git a/tee-worker/bitacross/rust-sgx-sdk/common/inc/mbusafecrt.h b/tee-worker/bitacross/rust-sgx-sdk/common/inc/mbusafecrt.h deleted file mode 100644 index 91d888b3f8..0000000000 --- a/tee-worker/bitacross/rust-sgx-sdk/common/inc/mbusafecrt.h +++ /dev/null @@ -1,85 +0,0 @@ -// -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. -// - -/*** -* mbusafecrt.h - public declarations for SafeCRT lib -* - -* -* Purpose: -* This file contains the public declarations SafeCRT -* functions ported to MacOS. These are the safe versions of -* functions standard functions banned by SWI -* - -****/ - -/* shields! */ - -#ifndef MBUSAFECRT_H -#define MBUSAFECRT_H -#include -#include -#include -typedef wchar_t WCHAR; - -#ifdef __cplusplus - extern "C" { -#endif - -extern errno_t strcat_s( char* ioDest, size_t inDestBufferSize, const char* inSrc ); -extern errno_t wcscat_s( WCHAR* ioDest, size_t inDestBufferSize, const WCHAR* inSrc ); - -extern errno_t strncat_s( char* ioDest, size_t inDestBufferSize, const char* inSrc, size_t inCount ); -extern errno_t wcsncat_s( WCHAR* ioDest, size_t inDestBufferSize, const WCHAR* inSrc, size_t inCount ); - -extern errno_t strcpy_s( char* outDest, size_t inDestBufferSize, const char* inSrc ); -extern errno_t wcscpy_s( WCHAR* outDest, size_t inDestBufferSize, const WCHAR* inSrc ); - -extern errno_t strncpy_s( char* outDest, size_t inDestBufferSize, const char* inSrc, size_t inCount ); -extern errno_t wcsncpy_s( WCHAR* outDest, size_t inDestBufferSize, const WCHAR* inSrc, size_t inCount ); - -extern char* strtok_s( char* inString, const char* inControl, char** ioContext ); -extern WCHAR* wcstok_s( WCHAR* inString, const WCHAR* inControl, WCHAR** ioContext ); - -extern size_t wcsnlen( const WCHAR* inString, size_t inMaxSize ); - -extern errno_t _itoa_s( int inValue, char* outBuffer, size_t inDestBufferSize, int inRadix ); -extern errno_t _itow_s( int inValue, WCHAR* outBuffer, size_t inDestBufferSize, int inRadix ); - -extern errno_t _ltoa_s( long inValue, char* outBuffer, size_t inDestBufferSize, int inRadix ); -extern errno_t _ltow_s( long inValue, WCHAR* outBuffer, size_t inDestBufferSize, int inRadix ); - -extern errno_t _ultoa_s( unsigned long inValue, char* outBuffer, size_t inDestBufferSize, int inRadix ); -extern errno_t _ultow_s( unsigned long inValue, WCHAR* outBuffer, size_t inDestBufferSize, int inRadix ); - -extern errno_t _i64toa_s( long long inValue, char* outBuffer, size_t inDestBufferSize, int inRadix ); -extern errno_t _i64tow_s( long long inValue, WCHAR* outBuffer, size_t inDestBufferSize, int inRadix ); - -extern errno_t _ui64toa_s( unsigned long long inValue, char* outBuffer, size_t inDestBufferSize, int inRadix ); -extern errno_t _ui64tow_s( unsigned long long inValue, WCHAR* outBuffer, size_t inDestBufferSize, int inRadix ); - -extern int sprintf_s( char *string, size_t sizeInBytes, const char *format, ... ); -extern int swprintf_s( WCHAR *string, size_t sizeInWords, const WCHAR *format, ... ); - -extern int _snprintf_s( char *string, size_t sizeInBytes, size_t count, const char *format, ... ); -extern int _snwprintf_s( WCHAR *string, size_t sizeInWords, size_t count, const WCHAR *format, ... ); - -extern int _vsprintf_s( char* string, size_t sizeInBytes, const char* format, va_list arglist ); -extern int _vsnprintf_s( char* string, size_t sizeInBytes, size_t count, const char* format, va_list arglist ); - -extern int _vswprintf_s( WCHAR* string, size_t sizeInWords, const WCHAR* format, va_list arglist ); -extern int _vsnwprintf_s( WCHAR* string, size_t sizeInWords, size_t count, const WCHAR* format, va_list arglist ); - -extern errno_t memcpy_s( void * dst, size_t sizeInBytes, const void * src, size_t count ); -extern errno_t memcpy_verw_s( void * dst, size_t sizeInBytes, const void * src, size_t count ); -extern errno_t memmove_s( void * dst, size_t sizeInBytes, const void * src, size_t count ); -extern errno_t memmove_verw_s( void * dst, size_t sizeInBytes, const void * src, size_t count ); - -#ifdef __cplusplus - } -#endif - -#endif /* MBUSAFECRT_H */ diff --git a/tee-worker/bitacross/rust-sgx-sdk/common/inc/netdb.h b/tee-worker/bitacross/rust-sgx-sdk/common/inc/netdb.h deleted file mode 100644 index 264f90ff39..0000000000 --- a/tee-worker/bitacross/rust-sgx-sdk/common/inc/netdb.h +++ /dev/null @@ -1,41 +0,0 @@ -// -// Copyright © 2005-2020 Rich Felker, et al. -// Licensed under the MIT license.s -// - -/* Copyright © 2005-2020 Rich Felker, et al. - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ - -#ifndef _NETDB_H -#define _NETDB_H - -struct addrinfo { - int ai_flags; - int ai_family; - int ai_socktype; - int ai_protocol; - socklen_t ai_addrlen; - struct sockaddr *ai_addr; - char *ai_canonname; - struct addrinfo *ai_next; -}; - -#endif diff --git a/tee-worker/bitacross/rust-sgx-sdk/common/inc/poll.h b/tee-worker/bitacross/rust-sgx-sdk/common/inc/poll.h deleted file mode 100644 index fc786fc279..0000000000 --- a/tee-worker/bitacross/rust-sgx-sdk/common/inc/poll.h +++ /dev/null @@ -1,38 +0,0 @@ -// -// Copyright © 2005-2020 Rich Felker, et al. -// Licensed under the MIT license. -// - -/* Copyright © 2005-2020 Rich Felker, et al. - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ - -#ifndef _POLL_H_ -#define _POLL_H_ - -typedef unsigned long nfds_t; - -struct pollfd { - int fd; - short int events; - short int revents; -}; - -#endif diff --git a/tee-worker/bitacross/rust-sgx-sdk/common/inc/pthread.h b/tee-worker/bitacross/rust-sgx-sdk/common/inc/pthread.h deleted file mode 100644 index e79668ffd6..0000000000 --- a/tee-worker/bitacross/rust-sgx-sdk/common/inc/pthread.h +++ /dev/null @@ -1,34 +0,0 @@ -#ifndef _SYS_THREAD_H_ -#define _SYS_THREAD_H_ - -/* Thread identifiers. The structure of the attribute type is not - exposed on purpose. */ -typedef unsigned long int pthread_t; - -#if defined __x86_64__ && !defined __ILP32__ -# define __WORDSIZE 64 -#else -# define __WORDSIZE 32 -#define __WORDSIZE32_SIZE_ULONG 0 -#define __WORDSIZE32_PTRDIFF_LONG 0 -#endif - -#ifdef __x86_64__ -# if __WORDSIZE == 64 -# define __SIZEOF_PTHREAD_ATTR_T 56 -# else -# define __SIZEOF_PTHREAD_ATTR_T 32 -#endif - -union pthread_attr_t -{ - char __size[__SIZEOF_PTHREAD_ATTR_T]; - long int __align; -}; -#ifndef __have_pthread_attr_t -typedef union pthread_attr_t pthread_attr_t; -# define __have_pthread_attr_t 1 -#endif - -#endif -#endif diff --git a/tee-worker/bitacross/rust-sgx-sdk/common/inc/pwd.h b/tee-worker/bitacross/rust-sgx-sdk/common/inc/pwd.h deleted file mode 100644 index a45b145a94..0000000000 --- a/tee-worker/bitacross/rust-sgx-sdk/common/inc/pwd.h +++ /dev/null @@ -1,40 +0,0 @@ -// -// Copyright © 2005-2020 Rich Felker, et al. -// Licensed under the MIT license. -// - -/* Copyright © 2005-2020 Rich Felker, et al. - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ - -#ifndef _PWD_H -#define _PWD_H - -struct passwd { - char *pw_name; - char *pw_passwd; - __uid_t pw_uid; - __gid_t pw_gid; - char *pw_gecos; - char *pw_dir; - char *pw_shell; -}; - -#endif diff --git a/tee-worker/bitacross/rust-sgx-sdk/common/inc/sched.h b/tee-worker/bitacross/rust-sgx-sdk/common/inc/sched.h deleted file mode 100644 index 4d237c4044..0000000000 --- a/tee-worker/bitacross/rust-sgx-sdk/common/inc/sched.h +++ /dev/null @@ -1,62 +0,0 @@ -// -// Copyright © 2005-2020 Rich Felker, et al. -// Licensed under the MIT license.s -// - -/* Copyright © 2005-2020 Rich Felker, et al. - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ - -#ifndef _SCHED_H -#define _SCHED_H -#include - -typedef struct { - unsigned long __bits[128/sizeof(long)]; -} cpu_set_t; - -#define __CPU_op_S(i, size, set, op) ( (i)/8U >= (size) ? 0 : \ - (((unsigned long *)(set))[(i)/8/sizeof(long)] op (1UL<<((i)%(8*sizeof(long))))) ) - -#define CPU_SET_S(i, size, set) __CPU_op_S(i, size, set, |=) -#define CPU_CLR_S(i, size, set) __CPU_op_S(i, size, set, &=~) -#define CPU_ISSET_S(i, size, set) __CPU_op_S(i, size, set, &) - -#define __CPU_op_func_S(func, op) \ -static __inline void __CPU_##func##_S(size_t __size, cpu_set_t *__dest, \ - const cpu_set_t *__src1, const cpu_set_t *__src2) \ -{ \ - size_t __i; \ - for (__i=0; __i<__size/sizeof(long); __i++) \ - ((unsigned long *)__dest)[__i] = ((unsigned long *)__src1)[__i] \ - op ((unsigned long *)__src2)[__i] ; \ -} - -__CPU_op_func_S(AND, &) -__CPU_op_func_S(OR, |) -__CPU_op_func_S(XOR, ^) - -#define CPU_AND_S(a,b,c,d) __CPU_AND_S(a,b,c,d) -#define CPU_OR_S(a,b,c,d) __CPU_OR_S(a,b,c,d) -#define CPU_XOR_S(a,b,c,d) __CPU_XOR_S(a,b,c,d) - -typedef __pid_t pid_t; - -#endif diff --git a/tee-worker/bitacross/rust-sgx-sdk/common/inc/setjmp.h b/tee-worker/bitacross/rust-sgx-sdk/common/inc/setjmp.h deleted file mode 100644 index 752f0cf763..0000000000 --- a/tee-worker/bitacross/rust-sgx-sdk/common/inc/setjmp.h +++ /dev/null @@ -1,65 +0,0 @@ -/* $NetBSD: setjmp.h,v 1.26 2011/11/05 09:27:06 joerg Exp $ */ - -/*- - * Copyright (c) 1990, 1993 - * The Regents of the University of California. All rights reserved. - * (c) UNIX System Laboratories, Inc. - * All or some portions of this file are derived from material licensed - * to the University of California by American Telephone and Telegraph - * Co. or Unix System Laboratories, Inc. and are reproduced herein with - * the permission of UNIX System Laboratories, Inc. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS - * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY - * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - * - * @(#)setjmp.h 8.2 (Berkeley) 1/21/94 - */ - -#ifndef _SETJMP_H_ -#define _SETJMP_H_ - -#ifndef _JB_ATTRIBUTES -#define _JB_ATTRIBUTES /**/ -#else -#endif -#ifndef _BSD_JBSLOT_T_ -#define _BSD_JBSLOT_T_ long -#endif - -#define _JBLEN 8 - -typedef _BSD_JBSLOT_T_ jmp_buf[_JBLEN] _JB_ATTRIBUTES; - -#include -#define __returns_twice __attribute__((__returns_twice__)) -#define __dead - - -__BEGIN_DECLS -int setjmp(jmp_buf) __returns_twice; -void longjmp(jmp_buf, int) __dead; -__END_DECLS - -#endif /* !_SETJMP_H_ */ - diff --git a/tee-worker/bitacross/rust-sgx-sdk/common/inc/signal.h b/tee-worker/bitacross/rust-sgx-sdk/common/inc/signal.h deleted file mode 100644 index c0da74f456..0000000000 --- a/tee-worker/bitacross/rust-sgx-sdk/common/inc/signal.h +++ /dev/null @@ -1,104 +0,0 @@ -// -// Copyright © 2005-2020 Rich Felker, et al. -// Licensed under the MIT license.s -// - -/* Copyright © 2005-2020 Rich Felker, et al. - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ - -#ifndef _SIGNAL_H -#define _SIGNAL_H - -#include - -typedef struct { - unsigned long _bits[128/sizeof(long)]; -} __sigset_t; - -typedef __sigset_t sigset_t; - -union sigval { - int sival_int; - void *sival_ptr; -}; - -typedef struct { - int si_signo; - int si_errno; - int si_code; - union { - char __pad[128 - 2*sizeof(int) - sizeof(long)]; - struct { - union { - struct { - __pid_t si_pid; - __uid_t si_uid; - } __piduid; - struct { - int si_timerid; - int si_overrun; - } __timer; - } __first; - union { - union sigval si_value; - struct { - int si_status; - __clock_t si_utime, si_stime; - } __sigchld; - } __second; - } __si_common; - struct { - void *si_addr; - short si_addr_lsb; - union { - struct { - void *si_lower; - void *si_upper; - } __addr_bnd; - unsigned si_pkey; - } __first; - } __sigfault; - struct { - long si_band; - int si_fd; - } __sigpoll; - struct { - void *si_call_addr; - int si_syscall; - unsigned si_arch; - } __sigsys; - } __si_fields; -} siginfo_t; - -struct sigaction { - union { - void (*sa_handler) (int); - void (*sa_sigaction) (int, siginfo_t *, void *); - } __sa_handler; - __sigset_t sa_mask; - int sa_flags; - void (*sa_restorer) (void); -}; - -#define sa_handler __sa_handler.sa_handler -#define sa_sigaction __sa_handler.sa_sigaction - -#endif diff --git a/tee-worker/bitacross/rust-sgx-sdk/common/inc/stdalign.h b/tee-worker/bitacross/rust-sgx-sdk/common/inc/stdalign.h deleted file mode 100644 index 93b8f6016e..0000000000 --- a/tee-worker/bitacross/rust-sgx-sdk/common/inc/stdalign.h +++ /dev/null @@ -1,15 +0,0 @@ -#ifndef _STDALIGN_H -#define _STDALIGN_H -#ifndef __cplusplus -/* this whole header only works in C11 or with compiler extensions */ -#if __STDC_VERSION__ < 201112L && defined( __GNUC__) -#define _Alignas(t) __attribute__((__aligned__(t))) -#define _Alignof(t) __alignof__(t) -#endif -#define alignas _Alignas -#define alignof _Alignof -#endif -#define __alignas_is_defined 1 -#define __alignof_is_defined 1 -#endif - diff --git a/tee-worker/bitacross/rust-sgx-sdk/common/inc/stdarg.h b/tee-worker/bitacross/rust-sgx-sdk/common/inc/stdarg.h deleted file mode 100644 index b2a5d36e82..0000000000 --- a/tee-worker/bitacross/rust-sgx-sdk/common/inc/stdarg.h +++ /dev/null @@ -1,48 +0,0 @@ -/* $OpenBSD: stdarg.h,v 1.14 2010/12/30 05:01:36 tedu Exp $ */ -/* $NetBSD: stdarg.h,v 1.12 1995/12/25 23:15:31 mycroft Exp $ */ - -/*- - * Copyright (c) 1991, 1993 - * The Regents of the University of California. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS - * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY - * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - * - * @(#)stdarg.h 8.1 (Berkeley) 6/10/93 - */ - -#ifndef _STDARG_H_ -#define _STDARG_H_ - -#include -#include - -typedef __va_list va_list; - -#define va_start(ap, last) __builtin_va_start((ap), last) -#define va_end __builtin_va_end -#define va_arg __builtin_va_arg -#define va_copy(dst, src) __builtin_va_copy((dst),(src)) - -#endif /* !_STDARG_H_ */ diff --git a/tee-worker/bitacross/rust-sgx-sdk/common/inc/stdbool.h b/tee-worker/bitacross/rust-sgx-sdk/common/inc/stdbool.h deleted file mode 100644 index 86b866d5d7..0000000000 --- a/tee-worker/bitacross/rust-sgx-sdk/common/inc/stdbool.h +++ /dev/null @@ -1,44 +0,0 @@ -/* $OpenBSD: stdbool.h,v 1.5 2010/07/24 22:17:03 guenther Exp $ */ - -/* - * Written by Marc Espie, September 25, 1999 - * Public domain. - */ - -#ifndef _STDBOOL_H_ -#define _STDBOOL_H_ - -#ifndef __cplusplus - -#ifndef __GNUC__ -/* Support for _C99: type _Bool is already built-in. */ -/* `_Bool' type must promote to `int' or `unsigned int'. */ -typedef enum { - false = 0, - true = 1 -} _Bool; - -/* And those constants must also be available as macros. */ -# define false false -# define true true -#else /* __GNUC__ */ -# define false 0 -# define true 1 -#endif - -/* User visible type `bool' is provided as a macro which may be redefined */ -#define bool _Bool - -#else /* __cplusplus */ - -# define _Bool bool -# define bool bool -# define false false -# define true true - -#endif - -/* Inform that everything is fine */ -#define __bool_true_false_are_defined 1 - -#endif /* _STDBOOL_H_ */ diff --git a/tee-worker/bitacross/rust-sgx-sdk/common/inc/stddef.h b/tee-worker/bitacross/rust-sgx-sdk/common/inc/stddef.h deleted file mode 100644 index 62d653029d..0000000000 --- a/tee-worker/bitacross/rust-sgx-sdk/common/inc/stddef.h +++ /dev/null @@ -1,70 +0,0 @@ -/* $OpenBSD: stddef.h,v 1.10 2009/09/22 21:40:02 jsg Exp $ */ -/* $NetBSD: stddef.h,v 1.4 1994/10/26 00:56:26 cgd Exp $ */ - -/*- - * Copyright (c) 1990 The Regents of the University of California. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS - * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY - * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - * - * @(#)stddef.h 5.5 (Berkeley) 4/3/91 - */ - -#ifndef _STDDEF_H_ -#define _STDDEF_H_ - -#include -#include - -#ifndef _PTRDIFF_T_DEFINED_ -#define _PTRDIFF_T_DEFINED_ -typedef __ptrdiff_t ptrdiff_t; -#endif - -#ifndef _SIZE_T_DEFINED_ -#define _SIZE_T_DEFINED_ -typedef __size_t size_t; -#endif - -#if !defined(_WCHAR_T_DEFINED_) && !defined(__cplusplus) -#define _WCHAR_T_DEFINED_ -#ifndef __WCHAR_TYPE__ -#define __WCHAR_TYPE__ int -#endif -typedef __WCHAR_TYPE__ wchar_t; -#endif - -#ifndef NULL -#ifdef __cplusplus -#define NULL 0 -#else -#define NULL ((void *)0) -#endif -#endif - -#define offsetof(type, member) __builtin_offsetof (type, member) - -#endif /* _STDDEF_H_ */ - diff --git a/tee-worker/bitacross/rust-sgx-sdk/common/inc/stdint.h b/tee-worker/bitacross/rust-sgx-sdk/common/inc/stdint.h deleted file mode 100644 index e574484062..0000000000 --- a/tee-worker/bitacross/rust-sgx-sdk/common/inc/stdint.h +++ /dev/null @@ -1,24 +0,0 @@ -/* $OpenBSD: stdint.h,v 1.4 2006/12/10 22:17:55 deraadt Exp $ */ - -/* - * Copyright (c) 1997, 2005 Todd C. Miller - * - * Permission to use, copy, modify, and distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -#ifndef _STDINT_H_ -#define _STDINT_H_ - -#include - -#endif /* _STDINT_H_ */ diff --git a/tee-worker/bitacross/rust-sgx-sdk/common/inc/stdio.h b/tee-worker/bitacross/rust-sgx-sdk/common/inc/stdio.h deleted file mode 100644 index 92d01a0d9e..0000000000 --- a/tee-worker/bitacross/rust-sgx-sdk/common/inc/stdio.h +++ /dev/null @@ -1,95 +0,0 @@ -/* $OpenBSD: stdio.h,v 1.38 2009/11/09 00:18:27 kurt Exp $ */ -/* $NetBSD: stdio.h,v 1.18 1996/04/25 18:29:21 jtc Exp $ */ - -/*- - * Copyright (c) 1990 The Regents of the University of California. - * All rights reserved. - * - * This code is derived from software contributed to Berkeley by - * Chris Torek. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS - * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY - * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - * - * @(#)stdio.h 5.17 (Berkeley) 6/3/91 - */ - -#ifndef _STDIO_H_ -#define _STDIO_H_ - -#include -#include - -#include - -#ifndef _SIZE_T_DEFINED_ -typedef __size_t size_t; -#define _SIZE_T_DEFINED_ -#endif - -#ifndef NULL -# ifdef __cplusplus -# define NULL 0 -# else -# define NULL ((void *)0) -# endif -#endif - -# define BUFSIZ 8192 - -#define EOF (-1) - -__BEGIN_DECLS - -int _TLIBC_CDECL_ snprintf(char *, size_t, const char *, ...) _GCC_PRINTF_FORMAT_(3, 4); -int _TLIBC_CDECL_ vsnprintf(char *, size_t, const char *, __va_list) _GCC_PRINTF_FORMAT_(3, 0); - -/* - * Deprecated definitions. - */ -#if 0 /* No FILE */ -_TLIBC_DEPRECATED_FUNCTION_(int _TLIBC_CDECL_, fprintf, FILE *, const char *, ...); -_TLIBC_DEPRECATED_FUNCTION_(int _TLIBC_CDECL_, putc, int, FILE *); -_TLIBC_DEPRECATED_FUNCTION_(int _TLIBC_CDECL_, fputc, int, FILE *); -_TLIBC_DEPRECATED_FUNCTION_(int _TLIBC_CDECL_, fputs, const char *, FILE *); -_TLIBC_DEPRECATED_FUNCTION_(int _TLIBC_CDECL_, fscanf, FILE *, const char *, ...); -_TLIBC_DEPRECATED_FUNCTION_(size_t _TLIBC_CDECL_, fwrite, const void *, size_t, size_t, FILE *); -_TLIBC_DEPRECATED_FUNCTION_(int _TLIBC_CDECL_, printf, const char *, ...); -_TLIBC_DEPRECATED_FUNCTION_(int _TLIBC_CDECL_, putchar, int); -_TLIBC_DEPRECATED_FUNCTION_(int _TLIBC_CDECL_, puts, const char *); -_TLIBC_DEPRECATED_FUNCTION_(int _TLIBC_CDECL_, scanf, const char *, ...); -_TLIBC_DEPRECATED_FUNCTION_(int _TLIBC_CDECL_, sprintf, char *, const char *, ...); -_TLIBC_DEPRECATED_FUNCTION_(int _TLIBC_CDECL_, sscanf, const char *, const char *, ...); -_TLIBC_DEPRECATED_FUNCTION_(int _TLIBC_CDECL_, vfprintf, FILE *, const char *, __va_list); -_TLIBC_DEPRECATED_FUNCTION_(int _TLIBC_CDECL_, vfscanf, FILE *, const char *, __va_list); -_TLIBC_DEPRECATED_FUNCTION_(int _TLIBC_CDECL_, vprintf, const char *, __va_list); -_TLIBC_DEPRECATED_FUNCTION_(int _TLIBC_CDECL_, vscanf, const char *, __va_list); -_TLIBC_DEPRECATED_FUNCTION_(int _TLIBC_CDECL_, vsprintf, char *, const char *, __va_list); -_TLIBC_DEPRECATED_FUNCTION_(int _TLIBC_CDECL_, vsscanf, const char *, const char *, __va_list); -#endif - -__END_DECLS - - -#endif /* !_STDIO_H_ */ diff --git a/tee-worker/bitacross/rust-sgx-sdk/common/inc/stdlib.h b/tee-worker/bitacross/rust-sgx-sdk/common/inc/stdlib.h deleted file mode 100644 index 8128e0d56d..0000000000 --- a/tee-worker/bitacross/rust-sgx-sdk/common/inc/stdlib.h +++ /dev/null @@ -1,159 +0,0 @@ -/* $OpenBSD: stdlib.h,v 1.47 2010/05/18 22:24:55 tedu Exp $ */ -/* $NetBSD: stdlib.h,v 1.25 1995/12/27 21:19:08 jtc Exp $ */ - -/*- -* Copyright (c) 1990 The Regents of the University of California. -* All rights reserved. -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions -* are met: -* 1. Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* 2. Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* 3. Neither the name of the University nor the names of its contributors -* may be used to endorse or promote products derived from this software -* without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND -* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE -* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS -* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) -* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY -* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF -* SUCH DAMAGE. -* -* @(#)stdlib.h 5.13 (Berkeley) 6/4/91 -*/ - -#ifndef _STDLIB_H_ -#define _STDLIB_H_ - -#include -#include - -#ifndef _SIZE_T_DEFINED_ -#define _SIZE_T_DEFINED_ -typedef __size_t size_t; -#endif - -#if !defined(_WCHAR_T_DEFINED_) && !defined(__cplusplus) -#define _WCHAR_T_DEFINED_ -#ifndef __WCHAR_TYPE__ -#define __WCHAR_TYPE__ int -#endif -typedef __WCHAR_TYPE__ wchar_t; -#endif - -#ifndef _DIV_T_DEFINED -typedef struct { - int quot; /* quotient */ - int rem; /* remainder */ -} div_t; - -typedef struct { - long quot; /* quotient */ - long rem; /* remainder */ -} ldiv_t; - -typedef struct { - long long quot; /* quotient */ - long long rem; /* remainder */ -} lldiv_t; -#define _DIV_T_DEFINED -#endif - -#ifndef NULL -#ifdef __cplusplus -#define NULL 0 -#else -#define NULL ((void *)0) -#endif -#endif - -#define EXIT_FAILURE 1 -#define EXIT_SUCCESS 0 - -#define RAND_MAX 0x7fffffff -#define MB_CUR_MAX 1 - -__BEGIN_DECLS - -_TLIBC_NORETURN_ void _TLIBC_CDECL_ abort(void); -int _TLIBC_CDECL_ atexit(void (*)(void)); -int _TLIBC_CDECL_ abs(int); -double _TLIBC_CDECL_ atof(const char *); -int _TLIBC_CDECL_ atoi(const char *); -long _TLIBC_CDECL_ atol(const char *); -void * _TLIBC_CDECL_ bsearch(const void *, const void *, size_t, size_t, int (*)(const void *, const void *)); -void * _TLIBC_CDECL_ calloc(size_t, size_t); -div_t _TLIBC_CDECL_ div(int, int); -void _TLIBC_CDECL_ free(void *); -long _TLIBC_CDECL_ labs(long); -ldiv_t _TLIBC_CDECL_ ldiv(long, long); -void * _TLIBC_CDECL_ malloc(size_t); -void * _TLIBC_CDECL_ memalign(size_t, size_t); -#ifndef __cplusplus -int _TLIBC_CDECL_ posix_memalign(void **, size_t, size_t); -#else -int _TLIBC_CDECL_ posix_memalign(void **, size_t, size_t) throw (); -#endif -void * _TLIBC_CDECL_ aligned_alloc(size_t, size_t); -void _TLIBC_CDECL_ qsort(void *, size_t, size_t, int (*)(const void *, const void *)); -void * _TLIBC_CDECL_ realloc(void *, size_t); -double _TLIBC_CDECL_ strtod(const char *, char **); -long _TLIBC_CDECL_ strtol(const char *, char **, int); -float _TLIBC_CDECL_ strtof(const char *, char **); - -long long - _TLIBC_CDECL_ atoll(const char *); -long long - _TLIBC_CDECL_ llabs(long long); -lldiv_t - _TLIBC_CDECL_ lldiv(long long, long long); -long long - _TLIBC_CDECL_ strtoll(const char *, char **, int); -unsigned long - _TLIBC_CDECL_ strtoul(const char *, char **, int); -long double - _TLIBC_CDECL_ strtold(const char *, char **); -unsigned long long - _TLIBC_CDECL_ strtoull(const char *, char **, int); - -int _TLIBC_CDECL_ mblen(const char *, size_t); -size_t _TLIBC_CDECL_ mbstowcs(wchar_t *, const char *, size_t); -int _TLIBC_CDECL_ wctomb(char *, wchar_t); -int _TLIBC_CDECL_ mbtowc(wchar_t *, const char *, size_t); -size_t _TLIBC_CDECL_ wcstombs(char *, const wchar_t *, size_t); - - -/* - * Deprecated C99. - */ -_TLIBC_DEPRECATED_FUNCTION_(int _TLIBC_CDECL_, atexit, void (_TLIBC_CDECL_ *)(void)); -_TLIBC_DEPRECATED_FUNCTION_(int _TLIBC_CDECL_, rand, void); -_TLIBC_DEPRECATED_FUNCTION_(void _TLIBC_CDECL_, srand, unsigned); -_TLIBC_DEPRECATED_FUNCTION_(void _TLIBC_CDECL_, exit, int); -_TLIBC_DEPRECATED_FUNCTION_(void _TLIBC_CDECL_, _Exit, int); -_TLIBC_DEPRECATED_FUNCTION_(char * _TLIBC_CDECL_, getenv, const char *); -_TLIBC_DEPRECATED_FUNCTION_(int _TLIBC_CDECL_, system, const char *); - -/* - * Non-C99 Functions. - */ -void * _TLIBC_CDECL_ alloca(size_t); - -/* - * Deprecated Non-C99. - */ -//_TLIBC_DEPRECATED_FUNCTION_(void _TLIBC_CDECL_, _exit, int); - -__END_DECLS - -#endif /* !_STDLIB_H_ */ diff --git a/tee-worker/bitacross/rust-sgx-sdk/common/inc/string.h b/tee-worker/bitacross/rust-sgx-sdk/common/inc/string.h deleted file mode 100644 index 00a89fde77..0000000000 --- a/tee-worker/bitacross/rust-sgx-sdk/common/inc/string.h +++ /dev/null @@ -1,130 +0,0 @@ -/* $OpenBSD: string.h,v 1.20 2010/09/24 13:33:00 matthew Exp $ */ -/* $NetBSD: string.h,v 1.6 1994/10/26 00:56:30 cgd Exp $ */ - -/*- - * Copyright (c) 1990 The Regents of the University of California. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS - * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY - * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - * - * @(#)string.h 5.10 (Berkeley) 3/9/91 - */ - -#ifndef _STRING_H_ -#define _STRING_H_ - -#include -#include - -#ifndef _SIZE_T_DEFINED_ -typedef __size_t size_t; -#define _SIZE_T_DEFINED_ -#endif - -#ifndef _ERRNO_T_DEFINED -#define _ERRNO_T_DEFINED -typedef int errno_t; -#endif - -#ifndef NULL -#ifdef __cplusplus -#define NULL 0 -#else -#define NULL ((void *)0) -#endif -#endif - -__BEGIN_DECLS - -void * _TLIBC_CDECL_ memchr(const void *, int, size_t); -int _TLIBC_CDECL_ memcmp(const void *, const void *, size_t); -void * _TLIBC_CDECL_ memcpy_nochecks(void *, const void *, size_t); -void * _TLIBC_CDECL_ memcpy(void *, const void *, size_t); -void * _TLIBC_CDECL_ memcpy_verw(void *, const void *, size_t); -void * _TLIBC_CDECL_ memmove(void *, const void *, size_t); -void * _TLIBC_CDECL_ memmove_verw(void *, const void *, size_t); -void * _TLIBC_CDECL_ memset(void *, int, size_t); -void * _TLIBC_CDECL_ memset_verw(void *, int, size_t); -char * _TLIBC_CDECL_ strchr(const char *, int); -int _TLIBC_CDECL_ strcmp(const char *, const char *); -int _TLIBC_CDECL_ strcoll(const char *, const char *); -size_t _TLIBC_CDECL_ strcspn(const char *, const char *); -char * _TLIBC_CDECL_ strerror(int); -size_t _TLIBC_CDECL_ strlen(const char *); -char * _TLIBC_CDECL_ strncat(char *, const char *, size_t); -int _TLIBC_CDECL_ strncmp(const char *, const char *, size_t); -char * _TLIBC_CDECL_ strncpy(char *, const char *, size_t); -char * _TLIBC_CDECL_ strpbrk(const char *, const char *); -char * _TLIBC_CDECL_ strrchr(const char *, int); -size_t _TLIBC_CDECL_ strspn(const char *, const char *); -char * _TLIBC_CDECL_ strstr(const char *, const char *); -char * _TLIBC_CDECL_ strtok(char *, const char *); -size_t _TLIBC_CDECL_ strxfrm(char *, const char *, size_t); -size_t _TLIBC_CDECL_ strlcpy(char *, const char *, size_t); -errno_t _TLIBC_CDECL_ memset_s(void *s, size_t smax, int c, size_t n); -errno_t _TLIBC_CDECL_ memset_verw_s(void *s, size_t smax, int c, size_t n); - -/* - * Deprecated C99. - */ -_TLIBC_DEPRECATED_FUNCTION_(char * _TLIBC_CDECL_, strcat, char *, const char *); -_TLIBC_DEPRECATED_FUNCTION_(char * _TLIBC_CDECL_, strcpy, char *, const char *); - -/* - * Common used non-C99 functions. - */ -char * _TLIBC_CDECL_ strndup(const char *, size_t); -size_t _TLIBC_CDECL_ strnlen(const char *, size_t); -int _TLIBC_CDECL_ consttime_memequal(const void *b1, const void *b2, size_t len); - -/* - * Non-C99 - */ -int _TLIBC_CDECL_ bcmp(const void *, const void *, size_t); -void _TLIBC_CDECL_ bcopy(const void *, void *, size_t); -void _TLIBC_CDECL_ bzero(void *, size_t); -char * _TLIBC_CDECL_ index(const char *, int); -void * _TLIBC_CDECL_ mempcpy(void *, const void *, size_t); -char * _TLIBC_CDECL_ rindex(const char *, int); -char * _TLIBC_CDECL_ stpncpy(char *dest, const char *src, size_t n); -int _TLIBC_CDECL_ strcasecmp(const char *, const char *); -int _TLIBC_CDECL_ strncasecmp(const char *, const char *, size_t); - -int _TLIBC_CDECL_ ffs(int); -int _TLIBC_CDECL_ ffsl(long int); -int _TLIBC_CDECL_ ffsll(long long int); - -char * _TLIBC_CDECL_ strtok_r(char *, const char *, char **); -int _TLIBC_CDECL_ strerror_r(int, char *, size_t); - -/* - * Deprecated Non-C99. - */ -_TLIBC_DEPRECATED_FUNCTION_(char * _TLIBC_CDECL_, strdup, const char *); -_TLIBC_DEPRECATED_FUNCTION_(char * _TLIBC_CDECL_, stpcpy, char *dest, const char *src); - -__END_DECLS - -#endif /* _STRING_H_ */ diff --git a/tee-worker/bitacross/rust-sgx-sdk/common/inc/sys/_types.h b/tee-worker/bitacross/rust-sgx-sdk/common/inc/sys/_types.h deleted file mode 100644 index 5dc6d5bbfb..0000000000 --- a/tee-worker/bitacross/rust-sgx-sdk/common/inc/sys/_types.h +++ /dev/null @@ -1,168 +0,0 @@ -/* $OpenBSD: _types.h,v 1.2 2008/03/16 19:42:57 otto Exp $ */ - -/*- - * Copyright (c) 1990, 1993 - * The Regents of the University of California. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS - * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY - * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - * - * @(#)types.h 8.3 (Berkeley) 1/5/94 - */ - -#ifndef _SYS__TYPES_H_ -#define _SYS__TYPES_H_ - -#include -/* 7.18.1.1 Exact-width integer types */ -typedef signed char __int8_t; -typedef unsigned char __uint8_t; -typedef short __int16_t; -typedef unsigned short __uint16_t; -typedef int __int32_t; -typedef unsigned int __uint32_t; -#ifdef __x86_64__ -typedef long __int64_t; -typedef unsigned long __uint64_t; -#else -typedef long long __int64_t; -typedef unsigned long long __uint64_t; -#endif - -/* 7.18.1.2 Minimum-width integer types */ -typedef __int8_t __int_least8_t; -typedef __uint8_t __uint_least8_t; -typedef __int16_t __int_least16_t; -typedef __uint16_t __uint_least16_t; -typedef __int32_t __int_least32_t; -typedef __uint32_t __uint_least32_t; -typedef __int64_t __int_least64_t; -typedef __uint64_t __uint_least64_t; - -/* 7.18.1.3 Fastest minimum-width integer types */ -typedef __int8_t __int_fast8_t; -typedef __uint8_t __uint_fast8_t; -#ifdef __x86_64__ -/* Linux x86_64, from stdint.h */ -typedef long int __int_fast16_t; -typedef unsigned long int __uint_fast16_t; -typedef long int __int_fast32_t; -typedef unsigned long int __uint_fast32_t; -typedef long int __int_fast64_t; -typedef unsigned long int __uint_fast64_t; -#else -/* Android x86, and Linux x86 */ -typedef __int32_t __int_fast16_t; -typedef __uint32_t __uint_fast16_t; -typedef __int32_t __int_fast32_t; -typedef __uint32_t __uint_fast32_t; -typedef __int64_t __int_fast64_t; -typedef __uint64_t __uint_fast64_t; -#endif - -typedef long __off_t; -#ifdef __x86_64__ -typedef long int __off64_t; -#else -typedef long long int __off64_t; -#endif - -/* 7.18.1.4 Integer types capable of holding object pointers */ -#ifdef __i386__ -typedef __int32_t __intptr_t; -typedef __uint32_t __uintptr_t; -typedef __int32_t __ptrdiff_t; -/* Standard system types */ -typedef __uint32_t __size_t; -typedef __int32_t __ssize_t; -typedef long double __double_t; -typedef long double __float_t; -#else -typedef __int64_t __intptr_t; -typedef __uint64_t __uintptr_t; -typedef __int64_t __ptrdiff_t; - -/* Standard system types */ -typedef unsigned long __size_t; -typedef long __ssize_t; -typedef double __double_t; -typedef float __float_t; - -#endif /* !__i386__ */ - -typedef long __clock_t; - -typedef long __time_t; -typedef __builtin_va_list __va_list; -typedef unsigned int __wint_t; -/* wctype_t and wctrans_t are defined in wchar.h */ -typedef unsigned long int __wctype_t; -typedef int * __wctrans_t; - -/* - * mbstate_t is an opaque object to keep conversion state, during multibyte - * stream conversions. The content must not be referenced by user programs. - */ -/* For Linux, __mbstate_t is defined in wchar.h */ -typedef struct { - int __c; - union { - __wint_t __wc; - char __wcb[4]; - } __v; -} __mbstate_t; - -/* 7.18.1.5 Greatest-width integer types */ -typedef __int64_t __intmax_t; -typedef __uint64_t __uintmax_t; - - -typedef unsigned long int __ino_t; -typedef unsigned int __mode_t; -typedef unsigned int __uid_t; -typedef unsigned int __gid_t; -typedef long int __blksize_t; -typedef long int __blkcnt_t; - -#ifdef __x86_64__ -typedef unsigned long int __dev_t; -typedef long int __off64_t; -typedef unsigned long int __nlink_t; -typedef long int __blkcnt64_t; -typedef unsigned long int __ino64_t; -#else -typedef unsigned long long int __dev_t; -typedef long long int __off64_t; -typedef unsigned int __nlink_t; -typedef long long int __blkcnt64_t; -typedef unsigned long long int __ino64_t; -#endif - -typedef unsigned int __socklen_t; -typedef int __pid_t; -typedef long __cpu_mask; -#endif /* !_SYS__TYPES_H_ */ - - - diff --git a/tee-worker/bitacross/rust-sgx-sdk/common/inc/sys/cdefs.h b/tee-worker/bitacross/rust-sgx-sdk/common/inc/sys/cdefs.h deleted file mode 100644 index 71c3c1ce22..0000000000 --- a/tee-worker/bitacross/rust-sgx-sdk/common/inc/sys/cdefs.h +++ /dev/null @@ -1,132 +0,0 @@ -/* $OpenBSD: cdefs.h,v 1.34 2012/08/14 20:11:37 matthew Exp $ */ -/* $NetBSD: cdefs.h,v 1.16 1996/04/03 20:46:39 christos Exp $ */ - -/* - * Copyright (c) 1991, 1993 - * The Regents of the University of California. All rights reserved. - * - * This code is derived from software contributed to Berkeley by - * Berkeley Software Design, Inc. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS - * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY - * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - * - * @(#)cdefs.h 8.7 (Berkeley) 1/21/94 - */ - -#ifndef _SYS_CDEFS_H_ -#define _SYS_CDEFS_H_ - -/* Declaration field in C/C++ headers */ -#if defined(__cplusplus) -# define __BEGIN_DECLS extern "C" { -# define __END_DECLS } -#else -# define __BEGIN_DECLS -# define __END_DECLS -#endif - -#if defined(__STDC__) || defined(__cplusplus) -# define __CONCAT(x,y) x ## y -# define __STRING(x) #x -#else -# define __CONCAT(x,y) x/**/y -# define __STRING(x) "x" -#endif -/* - * Macro to test if we're using a specific version of gcc or later. - */ -#if defined __GNUC__ && defined __GNUC_MINOR_ -# define __GNUC_PREREQ__(ma, mi) \ - ((__GNUC__ > (ma)) || (__GNUC__ == (ma) && __GNUC_MINOR__ >= (mi))) -#else -# define __GNUC_PREREQ__(ma, mi) 0 -#endif - -/* Calling Convention: cdecl */ -#define _TLIBC_CDECL_ - -/* Thread Directive */ -#define _TLIBC_THREAD_ /* __thread */ - -/* Deprecated Warnings */ -#define _TLIBC_DEPRECATED_MSG(x) __STRING(x)" is deprecated in tlibc." -#define _TLIBC_DEPRECATED_(x) __attribute__((deprecated(_TLIBC_DEPRECATED_MSG(x)))) - -#ifndef _TLIBC_WARN_DEPRECATED_FUNCTIONS_ -# define _TLIBC_DEPRECATED_FUNCTION_(__ret, __func, ...) -#else -# define _TLIBC_DEPRECATED_FUNCTION_(__ret, __func, ...) \ - _TLIBC_DEPRECATED_(__func) \ - __ret __func(__VA_ARGS__) -#endif - -/* Static analysis for printf format strings. - * _MSC_PRINTF_FORMAT_: MSVC SAL annotation for specifying format strings. - * _GCC_PRINTF_FORMAT_(x, y): GCC declaring attribute for checking format strings. - * x - index of the format string. In C++ non-static method, index 1 is reseved for 'this'. - * y - index of first variadic agrument in '...'. - */ -#define _GCC_PRINTF_FORMAT_(x, y) __attribute__((__format__ (printf, x, y))) - -/* Attribute - noreturn */ -#define _TLIBC_NORETURN_ __attribute__ ((__noreturn__)) - -/* - * GNU C version 2.96 adds explicit branch prediction so that - * the CPU back-end can hint the processor and also so that - * code blocks can be reordered such that the predicted path - * sees a more linear flow, thus improving cache behavior, etc. - * - * The following two macros provide us with a way to utilize this - * compiler feature. Use __predict_true() if you expect the expression - * to evaluate to true, and __predict_false() if you expect the - * expression to evaluate to false. - * - * A few notes about usage: - * - * * Generally, __predict_false() error condition checks (unless - * you have some _strong_ reason to do otherwise, in which case - * document it), and/or __predict_true() `no-error' condition - * checks, assuming you want to optimize for the no-error case. - * - * * Other than that, if you don't know the likelihood of a test - * succeeding from empirical or other `hard' evidence, don't - * make predictions. - * - * * These are meant to be used in places that are run `a lot'. - * It is wasteful to make predictions in code that is run - * seldomly (e.g. at subsystem initialization time) as the - * basic block reordering that this affects can often generate - * larger code. - */ -#if defined(__GNUC__) && __GNUC_PREREQ__(2, 96) -#define __predict_true(exp) __builtin_expect(((exp) != 0), 1) -#define __predict_false(exp) __builtin_expect(((exp) != 0), 0) -#else -#define __predict_true(exp) ((exp) != 0) -#define __predict_false(exp) ((exp) != 0) -#endif - -#endif /* !_SYS_CDEFS_H_ */ diff --git a/tee-worker/bitacross/rust-sgx-sdk/common/inc/sys/endian.h b/tee-worker/bitacross/rust-sgx-sdk/common/inc/sys/endian.h deleted file mode 100644 index 1cd7b810c3..0000000000 --- a/tee-worker/bitacross/rust-sgx-sdk/common/inc/sys/endian.h +++ /dev/null @@ -1,54 +0,0 @@ -/* $OpenBSD: endian.h,v 1.18 2006/03/27 07:09:24 otto Exp $ */ - -/*- - * Copyright (c) 1997 Niklas Hallqvist. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -/* - * Generic definitions for little- and big-endian systems. Other endianesses - * has to be dealt with in the specific machine/endian.h file for that port. - * - * This file is meant to be included from a little- or big-endian port's - * machine/endian.h after setting _BYTE_ORDER to either 1234 for little endian - * or 4321 for big.. - */ - -#ifndef _SYS_ENDIAN_H_ -#define _SYS_ENDIAN_H_ - -#define _LITTLE_ENDIAN 1234 -#define _BIG_ENDIAN 4321 -#define _PDP_ENDIAN 3412 -#define _BYTE_ORDER _LITTLE_ENDIAN - -#define LITTLE_ENDIAN _LITTLE_ENDIAN -#define BIG_ENDIAN _BIG_ENDIAN -#define PDP_ENDIAN _PDP_ENDIAN -#define BYTE_ORDER _BYTE_ORDER - -#define __BYTE_ORDER _BYTE_ORDER -#define __BIG_ENDIAN _BIG_ENDIAN -#define __LITTLE_ENDIAN _LITTLE_ENDIAN - -#endif /* _SYS_ENDIAN_H_ */ - diff --git a/tee-worker/bitacross/rust-sgx-sdk/common/inc/sys/epoll.h b/tee-worker/bitacross/rust-sgx-sdk/common/inc/sys/epoll.h deleted file mode 100644 index 958a4c4fb0..0000000000 --- a/tee-worker/bitacross/rust-sgx-sdk/common/inc/sys/epoll.h +++ /dev/null @@ -1,42 +0,0 @@ -// -// Copyright © 2005-2020 Rich Felker, et al. -// Licensed under the MIT license. -// - -/* Copyright © 2005-2020 Rich Felker, et al. - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ - -#ifndef _SYS_EPOLL_H -#define _SYS_EPOLL_H - -typedef union epoll_data { - void *ptr; - int fd; - uint32_t u32; - uint64_t u64; -} epoll_data_t; - -struct epoll_event { - uint32_t events; - epoll_data_t data; -} __attribute__ ((__packed__)); - -#endif diff --git a/tee-worker/bitacross/rust-sgx-sdk/common/inc/sys/fpu.h b/tee-worker/bitacross/rust-sgx-sdk/common/inc/sys/fpu.h deleted file mode 100644 index 4c218a91b6..0000000000 --- a/tee-worker/bitacross/rust-sgx-sdk/common/inc/sys/fpu.h +++ /dev/null @@ -1,99 +0,0 @@ -/* $OpenBSD: fpu.h,v 1.16 2018/10/07 22:43:06 guenther Exp $ */ -/* $NetBSD: fpu.h,v 1.1 2003/04/26 18:39:40 fvdl Exp $ */ - -#ifndef _MACHINE_FPU_H_ -#define _MACHINE_FPU_H_ - -#include - -/* - * If the CPU supports xsave/xrstor then we use them so that we can provide - * AVX support. Otherwise we require fxsave/fxrstor, as the SSE registers - * are part of the ABI for passing floating point values. - * While fxsave/fxrstor only required 16-byte alignment for the save area, - * xsave/xrstor requires the save area to have 64-byte alignment. - */ - -struct fxsave64 { - u_int16_t fx_fcw; - u_int16_t fx_fsw; - u_int8_t fx_ftw; - u_int8_t fx_unused1; - u_int16_t fx_fop; - u_int64_t fx_rip; - u_int64_t fx_rdp; - u_int32_t fx_mxcsr; - u_int32_t fx_mxcsr_mask; - u_int64_t fx_st[8][2]; /* 8 normal FP regs */ - u_int64_t fx_xmm[16][2]; /* 16 SSE2 registers */ - u_int8_t fx_unused3[96]; -} __packed; - -struct xstate_hdr { - uint64_t xstate_bv; - uint64_t xstate_xcomp_bv; - uint8_t xstate_rsrv0[0]; - uint8_t xstate_rsrv[40]; -} ___packed; - -struct savefpu { - struct fxsave64 fp_fxsave; /* see above */ - struct xstate_hdr fp_xstate; - u_int64_t fp_ymm[16][2]; - u_int16_t fp_ex_sw; /* saved status from last exception */ - u_int16_t fp_ex_tw; /* saved tag from last exception */ -}; - -/* - * The i387 defaults to Intel extended precision mode and round to nearest, - * with all exceptions masked. - */ -#define __INITIAL_NPXCW__ 0x037f -#define __INITIAL_MXCSR__ 0x1f80 -#define __INITIAL_MXCSR_MASK__ 0xffbf - -#ifdef _KERNEL -/* - * XXX - */ -struct trapframe; -struct cpu_info; - -extern size_t fpu_save_len; -extern uint32_t fpu_mxcsr_mask; -extern uint64_t xsave_mask; - -void fpuinit(struct cpu_info *); -int fputrap(int _type); -void fpusave(struct savefpu *); -void fpusavereset(struct savefpu *); -void fpu_kernel_enter(void); -void fpu_kernel_exit(void); - -int xrstor_user(struct savefpu *_addr, uint64_t _mask); -#define fpureset() \ - xrstor_user(&proc0.p_addr->u_pcb.pcb_savefpu, xsave_mask) -int xsetbv_user(uint32_t _reg, uint64_t _mask); - -#define fninit() __asm("fninit") -#define fwait() __asm("fwait") -/* should be fxsave64, but where we use this it doesn't matter */ -#define fxsave(addr) __asm("fxsave %0" : "=m" (*addr)) -#define ldmxcsr(addr) __asm("ldmxcsr %0" : : "m" (*addr)) -#define fldcw(addr) __asm("fldcw %0" : : "m" (*addr)) - -static inline void -xsave(struct savefpu *addr, uint64_t mask) -{ - uint32_t lo, hi; - - lo = mask; - hi = mask >> 32; - /* should be xsave64, but where we use this it doesn't matter */ - __asm volatile("xsave %0" : "=m" (*addr) : "a" (lo), "d" (hi) : - "memory"); -} - -#endif - -#endif /* _MACHINE_FPU_H_ */ diff --git a/tee-worker/bitacross/rust-sgx-sdk/common/inc/sys/ieee.h b/tee-worker/bitacross/rust-sgx-sdk/common/inc/sys/ieee.h deleted file mode 100644 index 47379b28ed..0000000000 --- a/tee-worker/bitacross/rust-sgx-sdk/common/inc/sys/ieee.h +++ /dev/null @@ -1,170 +0,0 @@ -/* $OpenBSD: ieee.h,v 1.2 2008/09/07 20:36:06 martynas Exp $ */ -/* $NetBSD: ieee.h,v 1.1 1996/09/30 16:34:25 ws Exp $ */ - -/* - * Copyright (c) 1992, 1993 - * The Regents of the University of California. All rights reserved. - * - * This software was developed by the Computer Systems Engineering group - * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and - * contributed to Berkeley. - * - * All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * This product includes software developed by the University of - * California, Lawrence Berkeley Laboratory. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS - * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY - * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - * - * @(#)ieee.h 8.1 (Berkeley) 6/11/93 - */ - -/* - * ieee.h defines the machine-dependent layout of the machine's IEEE - * floating point. It does *not* define (yet?) any of the rounding - * mode bits, exceptions, and so forth. - */ - -/* - * Define the number of bits in each fraction and exponent. - * - * k k+1 - * Note that 1.0 x 2 == 0.1 x 2 and that denorms are represented - * - * (-exp_bias+1) - * as fractions that look like 0.fffff x 2 . This means that - * - * -126 - * the number 0.10000 x 2 , for instance, is the same as the normalized - * - * -127 -128 - * float 1.0 x 2 . Thus, to represent 2 , we need one leading zero - * - * -129 - * in the fraction; to represent 2 , we need two, and so on. This - * - * (-exp_bias-fracbits+1) - * implies that the smallest denormalized number is 2 - * - * for whichever format we are talking about: for single precision, for - * - * -126 -149 - * instance, we get .00000000000000000000001 x 2 , or 1.0 x 2 , and - * - * -149 == -127 - 23 + 1. - */ - -#include -#include - -#define SNG_EXPBITS 8 -#define SNG_FRACBITS 23 - -#define DBL_EXPBITS 11 -#define DBL_FRACHBITS 20 -#define DBL_FRACLBITS 32 -#define DBL_FRACBITS 52 - -#define EXT_EXPBITS 15 -#define EXT_FRACHBITS 32 -#define EXT_FRACLBITS 32 -#define EXT_FRACBITS 64 - -#define EXT_TO_ARRAY32(p, a) do { \ - (a)[0] = (uint32_t)(p)->ext_fracl; \ - (a)[1] = (uint32_t)(p)->ext_frach; \ -} while(0) - -struct ieee_single { - u_int sng_frac:23; - u_int sng_exp:8; - u_int sng_sign:1; -}; - -struct ieee_double { - u_int dbl_fracl; - u_int dbl_frach:20; - u_int dbl_exp:11; - u_int dbl_sign:1; -}; - -struct ieee_ext { - u_int ext_fracl; - u_int ext_frach; - u_int ext_exp:15; - u_int ext_sign:1; - u_int ext_padl:16; - u_int ext_padh; -}; - -/* - * Floats whose exponent is in [1..INFNAN) (of whatever type) are - * `normal'. Floats whose exponent is INFNAN are either Inf or NaN. - * Floats whose exponent is zero are either zero (iff all fraction - * bits are zero) or subnormal values. - * - * A NaN is a `signalling NaN' if its QUIETNAN bit is clear in its - * high fraction; if the bit is set, it is a `quiet NaN'. - */ -#define SNG_EXP_INFNAN 255 -#define DBL_EXP_INFNAN 2047 -#define EXT_EXP_INFNAN 32767 - -#if 0 -#define SNG_QUIETNAN (1 << 22) -#define DBL_QUIETNAN (1 << 19) -#define EXT_QUIETNAN (1 << 15) -#endif - -/* - * Exponent biases. - */ -#define SNG_EXP_BIAS 127 -#define DBL_EXP_BIAS 1023 -#define EXT_EXP_BIAS 16383 - -typedef int fp_except; -#define FP_X_INV 0x01 /* invalid operation exception */ -#define FP_X_DNML 0x02 /* denormalization exception */ -#define FP_X_DZ 0x04 /* divide-by-zero exception */ -#define FP_X_OFL 0x08 /* overflow exception */ -#define FP_X_UFL 0x10 /* underflow exception */ -#define FP_X_IMP 0x20 /* imprecise (loss of precision) */ - -typedef enum { - FP_RN=0, /* round to nearest representable number */ - FP_RM=1, /* round toward negative infinity */ - FP_RP=2, /* round toward positive infinity */ - FP_RZ=3 /* round to zero (truncate) */ -} fp_rnd; - -__BEGIN_DECLS -extern fp_rnd fpgetround(void); -extern fp_rnd fpsetround(fp_rnd); -extern fp_except fpgetmask(void); -extern fp_except fpsetmask(fp_except); -extern fp_except fpgetsticky(void); -extern fp_except fpsetsticky(fp_except); -__END_DECLS diff --git a/tee-worker/bitacross/rust-sgx-sdk/common/inc/sys/limits.h b/tee-worker/bitacross/rust-sgx-sdk/common/inc/sys/limits.h deleted file mode 100644 index 3d1f9673ad..0000000000 --- a/tee-worker/bitacross/rust-sgx-sdk/common/inc/sys/limits.h +++ /dev/null @@ -1,77 +0,0 @@ -/* $OpenBSD: limits.h,v 1.8 2009/11/27 19:54:35 guenther Exp $ */ -/* - * Copyright (c) 2002 Marc Espie. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE OPENBSD PROJECT AND CONTRIBUTORS - * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OPENBSD - * PROJECT OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -#ifndef _SYS_LIMITS_H_ -#define _SYS_LIMITS_H_ - -#include - -/* Common definitions for limits.h. */ - -#define CHAR_BIT 8 /* number of bits in a char */ - -#define SCHAR_MAX 0x7f /* max value for a signed char */ -#define SCHAR_MIN (-0x7f - 1) /* min value for a signed char */ - -#define UCHAR_MAX 0xff /* max value for an unsigned char */ -#ifdef __CHAR_UNSIGNED__ -# define CHAR_MIN 0 /* min value for a char */ -# define CHAR_MAX 0xff /* max value for a char */ -#else -# define CHAR_MAX 0x7f -# define CHAR_MIN (-0x7f-1) -#endif - -#define MB_LEN_MAX 1 /* Allow UTF-8 (RFC 3629) */ - -#define USHRT_MAX 0xffff /* max value for an unsigned short */ -#define SHRT_MAX 0x7fff /* max value for a short */ -#define SHRT_MIN (-0x7fff-1) /* min value for a short */ - -#define UINT_MAX 0xffffffffU /* max value for an unsigned int */ -#define INT_MAX 0x7fffffff /* max value for an int */ -#define INT_MIN (-0x7fffffff-1) /* min value for an int */ - -#ifdef __x86_64__ -# define ULONG_MAX 0xffffffffffffffffUL /* max value for unsigned long */ -# define LONG_MAX 0x7fffffffffffffffL /* max value for a signed long */ -# define LONG_MIN (-0x7fffffffffffffffL-1) /* min value for a signed long */ -#else -# define ULONG_MAX 0xffffffffUL /* max value for an unsigned long */ -# define LONG_MAX 0x7fffffffL /* max value for a long */ -# define LONG_MIN (-0x7fffffffL-1) /* min value for a long */ -#endif - -#define ULLONG_MAX 0xffffffffffffffffULL /* max value for unsigned long long */ -#define LLONG_MAX 0x7fffffffffffffffLL /* max value for a signed long long */ -#define LLONG_MIN (-0x7fffffffffffffffLL-1) /* min value for a signed long long */ - -#ifdef __x86_64__ -# define LONG_BIT 64 -#else -# define LONG_BIT 32 -#endif - -#endif /* !_SYS_LIMITS_H_ */ diff --git a/tee-worker/bitacross/rust-sgx-sdk/common/inc/sys/sockaddr.h b/tee-worker/bitacross/rust-sgx-sdk/common/inc/sys/sockaddr.h deleted file mode 100644 index ba6811cbf7..0000000000 --- a/tee-worker/bitacross/rust-sgx-sdk/common/inc/sys/sockaddr.h +++ /dev/null @@ -1,32 +0,0 @@ -// -// Copyright © 2005-2020 Rich Felker, et al. -// Licensed under the MIT license. -// - -/* Copyright © 2005-2020 Rich Felker, et al. - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ - -#ifndef _SYS_SOCKADDR_H_ -#define _SYS_SOCKADDR_H_ - -typedef unsigned short int sa_family_t; - -#endif diff --git a/tee-worker/bitacross/rust-sgx-sdk/common/inc/sys/socket.h b/tee-worker/bitacross/rust-sgx-sdk/common/inc/sys/socket.h deleted file mode 100644 index 0b16699cc6..0000000000 --- a/tee-worker/bitacross/rust-sgx-sdk/common/inc/sys/socket.h +++ /dev/null @@ -1,54 +0,0 @@ -// -// Copyright © 2005-2020 Rich Felker, et al. -// Licensed under the MIT license. -// - -/* Copyright © 2005-2020 Rich Felker, et al. - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ - -#ifndef _SYS_SOCKET_H_ -#define _SYS_SOCKET_H_ - -#include -#include -#include - -typedef __socklen_t socklen_t; - -struct sockaddr { - sa_family_t sa_family; - char sa_data[14]; -}; - -struct msghdr { - void *msg_name; - socklen_t msg_namelen; - - struct iovec *msg_iov; - size_t msg_iovlen; - - void *msg_control; - size_t msg_controllen; - - int msg_flags; -}; - -#endif diff --git a/tee-worker/bitacross/rust-sgx-sdk/common/inc/sys/stat.h b/tee-worker/bitacross/rust-sgx-sdk/common/inc/sys/stat.h deleted file mode 100644 index 1cf090a7a1..0000000000 --- a/tee-worker/bitacross/rust-sgx-sdk/common/inc/sys/stat.h +++ /dev/null @@ -1,127 +0,0 @@ -// -// Copyright © 2005-2020 Rich Felker, et al. -// Licensed under the MIT license. -// - -/* Copyright © 2005-2020 Rich Felker, et al. - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ - - -#ifndef _SYS_STAT_H_ -#define _SYS_STAT_H_ - -#include -#include -#include - -typedef __dev_t dev_t; -typedef __ino_t ino_t; -typedef __ino64_t ino64_t; -typedef __mode_t mode_t; -typedef __nlink_t nlink_t; -typedef __uid_t uid_t; -typedef __gid_t gid_t; -typedef __blksize_t blksize_t; -typedef __blkcnt_t blkcnt_t; -typedef __blkcnt64_t blkcnt64_t; - -struct stat { - dev_t st_dev; - ino_t st_ino; - nlink_t st_nlink; - - mode_t st_mode; - uid_t st_uid; - gid_t st_gid; - unsigned int __pad0; - dev_t st_rdev; - off_t st_size; - blksize_t st_blksize; - blkcnt_t st_blocks; - - struct timespec st_atim; - struct timespec st_mtim; - struct timespec st_ctim; - long __unused[3]; -}; - -struct stat64 { - dev_t st_dev; - ino64_t st_ino; - nlink_t st_nlink; - - mode_t st_mode; - uid_t st_uid; - gid_t st_gid; - unsigned int __pad0; - dev_t st_rdev; - off_t st_size; - blksize_t st_blksize; - blkcnt64_t st_blocks; - - struct timespec st_atim; - struct timespec st_mtim; - struct timespec st_ctim; - long __unused[3]; -}; - -#define S_IFMT 0170000 - -#define S_IFDIR 0040000 -#define S_IFCHR 0020000 -#define S_IFBLK 0060000 -#define S_IFREG 0100000 -#define S_IFIFO 0010000 -#define S_IFLNK 0120000 -#define S_IFSOCK 0140000 - -#define S_TYPEISMQ(buf) 0 -#define S_TYPEISSEM(buf) 0 -#define S_TYPEISSHM(buf) 0 -#define S_TYPEISTMO(buf) 0 - -#define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR) -#define S_ISCHR(mode) (((mode) & S_IFMT) == S_IFCHR) -#define S_ISBLK(mode) (((mode) & S_IFMT) == S_IFBLK) -#define S_ISREG(mode) (((mode) & S_IFMT) == S_IFREG) -#define S_ISFIFO(mode) (((mode) & S_IFMT) == S_IFIFO) -#define S_ISLNK(mode) (((mode) & S_IFMT) == S_IFLNK) -#define S_ISSOCK(mode) (((mode) & S_IFMT) == S_IFSOCK) - -#ifndef S_IRUSR -#define S_ISUID 04000 -#define S_ISGID 02000 -#define S_ISVTX 01000 -#define S_IRUSR 0400 -#define S_IWUSR 0200 -#define S_IXUSR 0100 -#define S_IRWXU 0700 -#define S_IRGRP 0040 -#define S_IWGRP 0020 -#define S_IXGRP 0010 -#define S_IRWXG 0070 -#define S_IROTH 0004 -#define S_IWOTH 0002 -#define S_IXOTH 0001 -#define S_IRWXO 0007 -#endif - -#endif /* _SYS_STAT_H_ */ diff --git a/tee-worker/bitacross/rust-sgx-sdk/common/inc/sys/stdint.h b/tee-worker/bitacross/rust-sgx-sdk/common/inc/sys/stdint.h deleted file mode 100644 index 51599456d5..0000000000 --- a/tee-worker/bitacross/rust-sgx-sdk/common/inc/sys/stdint.h +++ /dev/null @@ -1,260 +0,0 @@ -/* $OpenBSD: stdint.h,v 1.4 2006/12/10 22:17:55 deraadt Exp $ */ - -/* - * Copyright (c) 1997, 2005 Todd C. Miller - * - * Permission to use, copy, modify, and distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -#ifndef _SYS_STDINT_H_ -#define _SYS_STDINT_H_ - -#include -#include - -/* 7.18.1.1 Exact-width integer types (also in sys/types.h) */ -#ifndef _INT8_T_DEFINED_ -#define _INT8_T_DEFINED_ -typedef __int8_t int8_t; -#endif - -#ifndef _UINT8_T_DEFINED_ -#define _UINT8_T_DEFINED_ -typedef __uint8_t uint8_t; -#endif - -#ifndef _INT16_T_DEFINED_ -#define _INT16_T_DEFINED_ -typedef __int16_t int16_t; -#endif - -#ifndef _UINT16_T_DEFINED_ -#define _UINT16_T_DEFINED_ -typedef __uint16_t uint16_t; -#endif - -#ifndef _INT32_T_DEFINED_ -#define _INT32_T_DEFINED_ -typedef __int32_t int32_t; -#endif - -#ifndef _UINT32_T_DEFINED_ -#define _UINT32_T_DEFINED_ -typedef __uint32_t uint32_t; -#endif - -#ifndef _INT64_T_DEFINED_ -#define _INT64_T_DEFINED_ -typedef __int64_t int64_t; -#endif - -#ifndef _UINT64_T_DEFINED_ -#define _UINT64_T_DEFINED_ -typedef __uint64_t uint64_t; -#endif - -/* 7.18.1.2 Minimum-width integer types */ -typedef __int_least8_t int_least8_t; -typedef __uint_least8_t uint_least8_t; -typedef __int_least16_t int_least16_t; -typedef __uint_least16_t uint_least16_t; -typedef __int_least32_t int_least32_t; -typedef __uint_least32_t uint_least32_t; -typedef __int_least64_t int_least64_t; -typedef __uint_least64_t uint_least64_t; - -/* 7.18.1.3 Fastest minimum-width integer types */ -typedef __int_fast8_t int_fast8_t; -typedef __uint_fast8_t uint_fast8_t; -typedef __int_fast16_t int_fast16_t; -typedef __uint_fast16_t uint_fast16_t; -typedef __int_fast32_t int_fast32_t; -typedef __uint_fast32_t uint_fast32_t; -typedef __int_fast64_t int_fast64_t; -typedef __uint_fast64_t uint_fast64_t; - -/* 7.18.1.4 Integer types capable of holding object pointers */ -#ifndef _INTPTR_T_DEFINED_ -#define _INTPTR_T_DEFINED_ -typedef __intptr_t intptr_t; -#endif - -#ifndef _UINTPTR_T_DEFINED_ -#define _UINTPTR_T_DEFINED_ -typedef __uintptr_t uintptr_t; -#endif - -/* 7.18.1.5 Greatest-width integer types */ -typedef __intmax_t intmax_t; -typedef __uintmax_t uintmax_t; - -//#if !defined(__cplusplus) || defined(__STDC_LIMIT_MACROS) -/* - * 7.18.2 Limits of specified-width integer types. - * - * The following object-like macros specify the minimum and maximum limits - * of integer types corresponding to the typedef names defined above. - */ - -/* 7.18.2.1 Limits of exact-width integer types */ -#define INT8_MIN (-0x7f - 1) -#define INT16_MIN (-0x7fff - 1) -#define INT32_MIN (-0x7fffffff - 1) -#ifdef __x86_64__ -#define INT64_MIN (-0x7fffffffffffffffL - 1) -#else -#define INT64_MIN (-0x7fffffffffffffffLL - 1) -#endif - -#define INT8_MAX 0x7f -#define INT16_MAX 0x7fff -#define INT32_MAX 0x7fffffff -#ifdef __x86_64__ -#define INT64_MAX 0x7fffffffffffffffL -#else -#define INT64_MAX 0x7fffffffffffffffLL -#endif - -#define UINT8_MAX 0xff -#define UINT16_MAX 0xffff -#define UINT32_MAX 0xffffffffU -#ifdef __x86_64__ -#define UINT64_MAX 0xffffffffffffffffUL -#else -#define UINT64_MAX 0xffffffffffffffffULL -#endif - -/* 7.18.2.2 Limits of minimum-width integer types */ -#define INT_LEAST8_MIN INT8_MIN -#define INT_LEAST16_MIN INT16_MIN -#define INT_LEAST32_MIN INT32_MIN -#define INT_LEAST64_MIN INT64_MIN - -#define INT_LEAST8_MAX INT8_MAX -#define INT_LEAST16_MAX INT16_MAX -#define INT_LEAST32_MAX INT32_MAX -#define INT_LEAST64_MAX INT64_MAX - -#define UINT_LEAST8_MAX UINT8_MAX -#define UINT_LEAST16_MAX UINT16_MAX -#define UINT_LEAST32_MAX UINT32_MAX -#define UINT_LEAST64_MAX UINT64_MAX - -/* 7.18.2.3 Limits of fastest minimum-width integer types */ -#define INT_FAST8_MIN INT8_MIN -#define INT_FAST16_MIN INT16_MIN -#define INT_FAST32_MIN INT32_MIN -#define INT_FAST64_MIN INT64_MIN - -#define INT_FAST8_MAX INT8_MAX -#ifdef __x86_64__ -#define INT_FAST16_MAX INT64_MAX -#define INT_FAST32_MAX INT64_MAX -#else -#define INT_FAST16_MAX INT32_MAX -#define INT_FAST32_MAX INT32_MAX -#endif -#define INT_FAST64_MAX INT64_MAX - -#define UINT_FAST8_MAX UINT8_MAX -#ifdef __x86_64__ -#define UINT_FAST16_MAX UINT64_MAX -#define UINT_FAST32_MAX UINT64_MAX -#else -#define UINT_FAST16_MAX UINT32_MAX -#define UINT_FAST32_MAX UINT32_MAX -#endif -#define UINT_FAST64_MAX UINT64_MAX - -/* 7.18.2.4 Limits of integer types capable of holding object pointers */ -#ifdef __x86_64__ -#define INTPTR_MIN INT64_MIN -#define INTPTR_MAX INT64_MAX -#define UINTPTR_MAX UINT64_MAX -#else -#define INTPTR_MIN INT32_MIN -#define INTPTR_MAX INT32_MAX -#define UINTPTR_MAX UINT32_MAX -#endif - -/* 7.18.2.5 Limits of greatest-width integer types */ -#define INTMAX_MIN INT64_MIN -#define INTMAX_MAX INT64_MAX -#define UINTMAX_MAX UINT64_MAX - -/* - * 7.18.3 Limits of other integer types. - * - * The following object-like macros specify the minimum and maximum limits - * of integer types corresponding to types specified in other standard - * header files. - */ - -/* Limits of ptrdiff_t */ -#define PTRDIFF_MIN INTPTR_MIN -#define PTRDIFF_MAX INTPTR_MAX - -/* Limits of size_t (also in limits.h) */ -#ifndef SIZE_MAX -#define SIZE_MAX UINTPTR_MAX -#endif - -/* Limits of wchar_t */ -# ifdef __WCHAR_MAX__ -# define WCHAR_MAX __WCHAR_MAX__ -# else -# define WCHAR_MAX (2147483647) -# endif -# ifdef __WCHAR_MIN__ -# define WCHAR_MIN __WCHAR_MIN__ -# elif L'\0' - 1 > 0 -# define WCHAR_MIN L'\0' -# else -# define WCHAR_MIN (-WCHAR_MAX - 1) -# endif - -/* Limits of wint_t */ -# define WINT_MIN (0u) -# define WINT_MAX (4294967295u) - -//#endif /* __cplusplus || __STDC_LIMIT_MACROS */ - -//#if !defined(__cplusplus) || defined(__STDC_CONSTANT_MACROS) -/* - * 7.18.4 Macros for integer constants. - * - * The following function-like macros expand to integer constants - * suitable for initializing objects that have integer types corresponding - * to types defined in . The argument in any instance of - * these macros shall be a decimal, octal, or hexadecimal constant with - * a value that does not exceed the limits for the corresponding type. - */ - -/* 7.18.4.1 Macros for minimum-width integer constants. */ -#define INT8_C(_c) (_c) -#define INT16_C(_c) (_c) -#define INT32_C(_c) (_c) -#define INT64_C(_c) __CONCAT(_c, LL) - -#define UINT8_C(_c) (_c) -#define UINT16_C(_c) (_c) -#define UINT32_C(_c) __CONCAT(_c, U) -#define UINT64_C(_c) __CONCAT(_c, ULL) - -/* 7.18.4.2 Macros for greatest-width integer constants. */ -#define INTMAX_C(_c) __CONCAT(_c, LL) -#define UINTMAX_C(_c) __CONCAT(_c, ULL) - -//#endif /* __cplusplus || __STDC_CONSTANT_MACROS */ - -#endif /* _SYS_STDINT_H_ */ diff --git a/tee-worker/bitacross/rust-sgx-sdk/common/inc/sys/struct_timespec.h b/tee-worker/bitacross/rust-sgx-sdk/common/inc/sys/struct_timespec.h deleted file mode 100644 index bca02c8809..0000000000 --- a/tee-worker/bitacross/rust-sgx-sdk/common/inc/sys/struct_timespec.h +++ /dev/null @@ -1,37 +0,0 @@ -// -// Copyright © 2005-2020 Rich Felker, et al. -// Licensed under the MIT license. -// - -/* Copyright © 2005-2020 Rich Felker, et al. - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ - -#ifndef _SYS_TIMESPEC_H_ -#define _SYS_TIMESPEC_H_ - -#include - -struct timespec { - __time_t tv_sec; - long tv_nsec; -}; - -#endif diff --git a/tee-worker/bitacross/rust-sgx-sdk/common/inc/sys/types.h b/tee-worker/bitacross/rust-sgx-sdk/common/inc/sys/types.h deleted file mode 100644 index b64f89df04..0000000000 --- a/tee-worker/bitacross/rust-sgx-sdk/common/inc/sys/types.h +++ /dev/null @@ -1,129 +0,0 @@ -/* $OpenBSD: types.h,v 1.31 2008/03/16 19:42:57 otto Exp $ */ -/* $NetBSD: types.h,v 1.29 1996/11/15 22:48:25 jtc Exp $ */ - -/*- - * Copyright (c) 1982, 1986, 1991, 1993 - * The Regents of the University of California. All rights reserved. - * (c) UNIX System Laboratories, Inc. - * All or some portions of this file are derived from material licensed - * to the University of California by American Telephone and Telegraph - * Co. or Unix System Laboratories, Inc. and are reproduced herein with - * the permission of UNIX System Laboratories, Inc. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS - * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY - * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - * - * @(#)types.h 8.4 (Berkeley) 1/21/94 - */ - -#ifndef _SYS_TYPES_H_ -#define _SYS_TYPES_H_ - -#include -#include - -typedef unsigned char u_char; -typedef unsigned short u_short; -typedef unsigned int u_int; -typedef unsigned long u_long; - -typedef unsigned char unchar; /* Sys V compatibility */ -typedef unsigned short ushort; /* Sys V compatibility */ -typedef unsigned int uint; /* Sys V compatibility */ -typedef unsigned long ulong; /* Sys V compatibility */ - -#ifndef _INT8_T_DEFINED_ -#define _INT8_T_DEFINED_ -typedef __int8_t int8_t; -#endif - -#ifndef _UINT8_T_DEFINED_ -#define _UINT8_T_DEFINED_ -typedef __uint8_t uint8_t; -#endif - -#ifndef _INT16_T_DEFINED_ -#define _INT16_T_DEFINED_ -typedef __int16_t int16_t; -#endif - -#ifndef _UINT16_T_DEFINED_ -#define _UINT16_T_DEFINED_ -typedef __uint16_t uint16_t; -#endif - -#ifndef _INT32_T_DEFINED_ -#define _INT32_T_DEFINED_ -typedef __int32_t int32_t; -#endif - -#ifndef _UINT32_T_DEFINED_ -#define _UINT32_T_DEFINED_ -typedef __uint32_t uint32_t; -#endif - -#ifndef _INT64_T_DEFINED_ -#define _INT64_T_DEFINED_ -typedef __int64_t int64_t; -#endif - -#ifndef _UINT64_T_DEFINED_ -#define _UINT64_T_DEFINED_ -typedef __uint64_t uint64_t; -#endif - -#ifndef _INTPTR_T_DEFINED_ -#define _INTPTR_T_DEFINED_ -typedef __intptr_t intptr_t; -#endif - -#ifndef _UINTPTR_T_DEFINED_ -#define _UINTPTR_T_DEFINED_ -typedef __uintptr_t uintptr_t; -#endif - -/* BSD-style unsigned bits types */ -typedef __uint8_t u_int8_t; -typedef __uint16_t u_int16_t; -typedef __uint32_t u_int32_t; -typedef __uint64_t u_int64_t; - - -#ifndef _SIZE_T_DEFINED_ -#define _SIZE_T_DEFINED_ -typedef __size_t size_t; -#endif - -#ifndef _SSIZE_T_DEFINED_ -#define _SSIZE_T_DEFINED_ -typedef __ssize_t ssize_t; -#endif - -#ifndef _OFF_T_DEFINED_ -#define _OFF_T_DEFINED_ -typedef __off_t off_t; -typedef __off64_t off64_t; -#endif - -#endif /* !_SYS_TYPES_H_ */ diff --git a/tee-worker/bitacross/rust-sgx-sdk/common/inc/sys/uio.h b/tee-worker/bitacross/rust-sgx-sdk/common/inc/sys/uio.h deleted file mode 100644 index 2544f06a7d..0000000000 --- a/tee-worker/bitacross/rust-sgx-sdk/common/inc/sys/uio.h +++ /dev/null @@ -1,35 +0,0 @@ -// -// Copyright © 2005-2020 Rich Felker, et al. -// Licensed under the MIT license. -// - -/* Copyright © 2005-2020 Rich Felker, et al. - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ - -#ifndef _SYS_UIO_H_ -#define _SYS_UIO_H_ - -struct iovec { - void *iov_base; - size_t iov_len; -}; - -#endif diff --git a/tee-worker/bitacross/rust-sgx-sdk/common/inc/time.h b/tee-worker/bitacross/rust-sgx-sdk/common/inc/time.h deleted file mode 100644 index 01cfd6e4e9..0000000000 --- a/tee-worker/bitacross/rust-sgx-sdk/common/inc/time.h +++ /dev/null @@ -1,105 +0,0 @@ -/* $OpenBSD: time.h,v 1.18 2006/01/06 18:53:04 millert Exp $ */ -/* $NetBSD: time.h,v 1.9 1994/10/26 00:56:35 cgd Exp $ */ - -/* - * Copyright (c) 1989 The Regents of the University of California. - * All rights reserved. - * - * (c) UNIX System Laboratories, Inc. - * All or some portions of this file are derived from material licensed - * to the University of California by American Telephone and Telegraph - * Co. or Unix System Laboratories, Inc. and are reproduced herein with - * the permission of UNIX System Laboratories, Inc. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS - * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY - * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - * - * @(#)time.h 5.12 (Berkeley) 3/9/91 - */ - -#ifndef _TIME_H_ -#define _TIME_H_ - -#include -#include -#include - -#ifndef NULL -#ifdef __cplusplus -#define NULL 0 -#else -#define NULL ((void *)0) -#endif -#endif - -#if !defined (_CLOCK_T_DEFINED_) && !defined (_CLOCK_T_DEFINED) -#define _CLOCK_T_DEFINED_ -#define _CLOCK_T_DEFINED -typedef __clock_t clock_t; -#endif - -#if !defined (_TIME_T_DEFINED_) && !defined (_TIME_T_DEFINED) -#define _TIME_T_DEFINED_ -#define _TIME_T_DEFINED -typedef __time_t time_t; -#endif - -#if !defined (_SIZE_T_DEFINED_) && !defined (_SIZE_T_DEFINED) -#define _SIZE_T_DEFINED_ -#define _SIZE_T_DEFINED -typedef __size_t size_t; -#endif - -#if !defined (_TM_DEFINED) -#define _TM_DEFINED -struct tm { - int tm_sec; /* seconds after the minute [0-60] */ - int tm_min; /* minutes after the hour [0-59] */ - int tm_hour; /* hours since midnight [0-23] */ - int tm_mday; /* day of the month [1-31] */ - int tm_mon; /* months since January [0-11] */ - int tm_year; /* years since 1900 */ - int tm_wday; /* days since Sunday [0-6] */ - int tm_yday; /* days since January 1 [0-365] */ - int tm_isdst; /* Daylight Saving Time flag */ - /* FIXME: naming issue exists on Fedora/Ubuntu */ - long tm_gmtoff; /* offset from UTC in seconds */ - char *tm_zone; /* timezone abbreviation */ -}; -#endif - -__BEGIN_DECLS - -double _TLIBC_CDECL_ difftime(time_t, time_t); -char * _TLIBC_CDECL_ asctime(const struct tm *); -size_t _TLIBC_CDECL_ strftime(char *, size_t, const char *, const struct tm *); - -/* - * Non-C99 - */ -char * _TLIBC_CDECL_ asctime_r(const struct tm *, char *); - -__END_DECLS - -#endif /* !_TIME_H_ */ diff --git a/tee-worker/bitacross/rust-sgx-sdk/common/inc/unistd.h b/tee-worker/bitacross/rust-sgx-sdk/common/inc/unistd.h deleted file mode 100644 index 2ab3a9a042..0000000000 --- a/tee-worker/bitacross/rust-sgx-sdk/common/inc/unistd.h +++ /dev/null @@ -1,59 +0,0 @@ -/* $OpenBSD: unistd.h,v 1.62 2008/06/25 14:58:54 millert Exp $ */ -/* $NetBSD: unistd.h,v 1.26.4.1 1996/05/28 02:31:51 mrg Exp $ */ - -/*- - * Copyright (c) 1991 The Regents of the University of California. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS - * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY - * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - * - * @(#)unistd.h 5.13 (Berkeley) 6/17/91 - */ - -#ifndef _UNISTD_H_ -#define _UNISTD_H_ - -#include -#include - -__BEGIN_DECLS - -void * _TLIBC_CDECL_ sbrk(intptr_t); - -/* - * Deprecated Non-C99. - */ -_TLIBC_DEPRECATED_FUNCTION_(int _TLIBC_CDECL_, execl, const char *, const char *, ...); -_TLIBC_DEPRECATED_FUNCTION_(int _TLIBC_CDECL_, execlp, const char *, const char *, ...); -_TLIBC_DEPRECATED_FUNCTION_(int _TLIBC_CDECL_, execle, const char *, const char *, ...); -_TLIBC_DEPRECATED_FUNCTION_(int _TLIBC_CDECL_, execv, const char *, char * const *); -_TLIBC_DEPRECATED_FUNCTION_(int _TLIBC_CDECL_, execve, const char *, char * const *, char * const *); -_TLIBC_DEPRECATED_FUNCTION_(int _TLIBC_CDECL_, execvp, const char *, char * const *); - -//_TLIBC_DEPRECATED_FUNCTION_(pid_t _TLIBC_CDECL_, fork, void); /* no pid_t */ - -__END_DECLS - -#endif /* !_UNISTD_H_ */ diff --git a/tee-worker/bitacross/rust-sgx-sdk/common/inc/wchar.h b/tee-worker/bitacross/rust-sgx-sdk/common/inc/wchar.h deleted file mode 100644 index 2db86f28eb..0000000000 --- a/tee-worker/bitacross/rust-sgx-sdk/common/inc/wchar.h +++ /dev/null @@ -1,143 +0,0 @@ -/* $OpenBSD: wchar.h,v 1.11 2010/07/24 09:58:39 guenther Exp $ */ -/* $NetBSD: wchar.h,v 1.16 2003/03/07 07:11:35 tshiozak Exp $ */ - -/*- - * Copyright (c)1999 Citrus Project, - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS - * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY - * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - */ - -/*- - * Copyright (c) 1999, 2000 The NetBSD Foundation, Inc. - * All rights reserved. - * - * This code is derived from software contributed to The NetBSD Foundation - * by Julian Coleman. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS - * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED - * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef _WCHAR_H_ -#define _WCHAR_H_ - -#include -#include -#include /* WCHAR_MAX/WCHAR_MIN */ - -#ifndef NULL -#ifdef __cplusplus -#define NULL 0 -#else -#define NULL ((void *)0) -#endif -#endif - -#if !defined(_WCHAR_T_DEFINED_) && !defined(__cplusplus) -#define _WCHAR_T_DEFINED_ -#ifndef __WCHAR_TYPE__ -#define __WCHAR_TYPE__ int -#endif -typedef __WCHAR_TYPE__ wchar_t; -#endif - -#ifndef _MBSTATE_T_DEFINED_ -#define _MBSTATE_T_DEFINED_ -typedef __mbstate_t mbstate_t; -#endif - -#ifndef _WINT_T_DEFINED_ -#define _WINT_T_DEFINED_ -typedef __wint_t wint_t; -#endif - -#ifndef _SIZE_T_DEFINED_ -#define _SIZE_T_DEFINED_ -typedef __size_t size_t; -#endif - -#ifndef WEOF -#define WEOF ((wint_t)-1) -#endif - -__BEGIN_DECLS - -wint_t _TLIBC_CDECL_ btowc(int); -int _TLIBC_CDECL_ wctob(wint_t); -size_t _TLIBC_CDECL_ mbrlen(const char *, size_t, mbstate_t *); -size_t _TLIBC_CDECL_ mbrtowc(wchar_t *, const char *, size_t, mbstate_t *); -int _TLIBC_CDECL_ mbsinit(const mbstate_t *); -size_t _TLIBC_CDECL_ mbsrtowcs(wchar_t *, const char **, size_t, mbstate_t *); -size_t _TLIBC_CDECL_ wcrtomb(char *, wchar_t, mbstate_t *); -wchar_t * _TLIBC_CDECL_ wcschr(const wchar_t *, wchar_t); -int _TLIBC_CDECL_ wcscmp(const wchar_t *, const wchar_t *); -int _TLIBC_CDECL_ wcscoll(const wchar_t *, const wchar_t *); -size_t _TLIBC_CDECL_ wcscspn(const wchar_t *, const wchar_t *); -size_t _TLIBC_CDECL_ wcslen(const wchar_t *); -wchar_t * _TLIBC_CDECL_ wcsncat(wchar_t *, const wchar_t *, size_t); -int _TLIBC_CDECL_ wcsncmp(const wchar_t *, const wchar_t *, size_t); -wchar_t * _TLIBC_CDECL_ wcsncpy(wchar_t *, const wchar_t *, size_t); -wchar_t * _TLIBC_CDECL_ wcspbrk(const wchar_t *, const wchar_t *); -wchar_t * _TLIBC_CDECL_ wcsrchr(const wchar_t *, wchar_t); -size_t _TLIBC_CDECL_ wcsrtombs(char *, const wchar_t **, size_t, mbstate_t *); -size_t _TLIBC_CDECL_ wcsspn(const wchar_t *, const wchar_t *); -wchar_t * _TLIBC_CDECL_ wcsstr(const wchar_t *, const wchar_t *); -wchar_t * _TLIBC_CDECL_ wcstok(wchar_t *, const wchar_t *, wchar_t **); -size_t _TLIBC_CDECL_ wcsxfrm(wchar_t *, const wchar_t *, size_t); -wchar_t * _TLIBC_CDECL_ wmemchr(const wchar_t *, wchar_t, size_t); -int _TLIBC_CDECL_ wmemcmp(const wchar_t *, const wchar_t *, size_t); -wchar_t * _TLIBC_CDECL_ wmemcpy(wchar_t *, const wchar_t *, size_t); -wchar_t * _TLIBC_CDECL_ wmemmove(wchar_t *, const wchar_t *, size_t); -wchar_t * _TLIBC_CDECL_ wmemset(wchar_t *, wchar_t, size_t); - -int _TLIBC_CDECL_ swprintf(wchar_t *, size_t, const wchar_t *, ...); -int _TLIBC_CDECL_ vswprintf(wchar_t *, size_t, const wchar_t *, __va_list); - -long double _TLIBC_CDECL_ wcstold (const wchar_t *, wchar_t **); -long long _TLIBC_CDECL_ wcstoll (const wchar_t *, wchar_t **, int); -unsigned long long _TLIBC_CDECL_ wcstoull (const wchar_t *, wchar_t **, int); - -/* leagcy version of wcsstr */ -wchar_t * _TLIBC_CDECL_ wcswcs(const wchar_t *, const wchar_t *); - -__END_DECLS - -#endif /* !_WCHAR_H_ */ diff --git a/tee-worker/bitacross/rust-sgx-sdk/common/inc/wctype.h b/tee-worker/bitacross/rust-sgx-sdk/common/inc/wctype.h deleted file mode 100644 index 0ab9497d78..0000000000 --- a/tee-worker/bitacross/rust-sgx-sdk/common/inc/wctype.h +++ /dev/null @@ -1,80 +0,0 @@ -/* $OpenBSD: wctype.h,v 1.5 2006/01/06 18:53:04 millert Exp $ */ -/* $NetBSD: wctype.h,v 1.5 2003/03/02 22:18:11 tshiozak Exp $ */ - -/*- - * Copyright (c)1999 Citrus Project, - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS - * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY - * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - * - * citrus Id: wctype.h,v 1.4 2000/12/21 01:50:21 itojun Exp - */ - -#ifndef _WCTYPE_H_ -#define _WCTYPE_H_ - -#include -#include - -#ifndef _WINT_T_DEFINED_ -#define _WINT_T_DEFINED_ -typedef __wint_t wint_t; -#endif - -#ifndef _WCTRANS_T_DEFINED_ -#define _WCTRANS_T_DEFINED_ -typedef __wctrans_t wctrans_t; -#endif - -#ifndef _WCTYPE_T_DEFINED_ -#define _WCTYPE_T_DEFINED_ -typedef __wctype_t wctype_t; -#endif - -#ifndef WEOF -#define WEOF ((wint_t)-1) -#endif - -__BEGIN_DECLS - -int _TLIBC_CDECL_ iswalnum(wint_t); -int _TLIBC_CDECL_ iswalpha(wint_t); -int _TLIBC_CDECL_ iswblank(wint_t); -int _TLIBC_CDECL_ iswcntrl(wint_t); -int _TLIBC_CDECL_ iswdigit(wint_t); -int _TLIBC_CDECL_ iswgraph(wint_t); -int _TLIBC_CDECL_ iswlower(wint_t); -int _TLIBC_CDECL_ iswprint(wint_t); -int _TLIBC_CDECL_ iswpunct(wint_t); -int _TLIBC_CDECL_ iswspace(wint_t); -int _TLIBC_CDECL_ iswupper(wint_t); -int _TLIBC_CDECL_ iswxdigit(wint_t); -int _TLIBC_CDECL_ iswctype(wint_t, wctype_t); -wint_t _TLIBC_CDECL_ towctrans(wint_t, wctrans_t); -wint_t _TLIBC_CDECL_ towlower(wint_t); -wint_t _TLIBC_CDECL_ towupper(wint_t); -wctrans_t _TLIBC_CDECL_ wctrans(const char *); -wctype_t _TLIBC_CDECL_ wctype(const char *); - -__END_DECLS - -#endif /* _WCTYPE_H_ */ diff --git a/tee-worker/bitacross/rust-sgx-sdk/edl/inc/dirent.h b/tee-worker/bitacross/rust-sgx-sdk/edl/inc/dirent.h deleted file mode 100644 index be63f8332d..0000000000 --- a/tee-worker/bitacross/rust-sgx-sdk/edl/inc/dirent.h +++ /dev/null @@ -1,39 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License.. - -#ifndef _EDL_DIRENT_H -#define _EDL_DIRENT_H - -struct dirent_t -{ - uint64_t d_ino; - int64_t d_off; - unsigned short int d_reclen; - unsigned char d_type; - char d_name[256]; -}; - -struct dirent64_t -{ - uint64_t d_ino; - int64_t d_off; - unsigned short int d_reclen; - unsigned char d_type; - char d_name[256]; -}; - -#endif diff --git a/tee-worker/bitacross/rust-sgx-sdk/edl/inc/stat.h b/tee-worker/bitacross/rust-sgx-sdk/edl/inc/stat.h deleted file mode 100644 index 7f04c3cec9..0000000000 --- a/tee-worker/bitacross/rust-sgx-sdk/edl/inc/stat.h +++ /dev/null @@ -1,65 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License.. - -#ifndef _EDL_STAT_H -#define _EDL_STAT_H - -struct stat_t -{ - uint64_t st_dev; - uint64_t st_ino; - uint64_t st_nlink; - uint32_t st_mode; - uint32_t st_uid; - uint32_t st_gid; - int __pad0; - uint64_t st_rdev; - uint64_t st_size; - int64_t st_blksize; - int64_t st_blocks; - int64_t st_atime; - int64_t st_atime_nsec; - int64_t st_mtime; - int64_t st_mtime_nsec; - int64_t st_ctime; - int64_t st_ctime_nsec; - int64_t __reserved[3]; -}; - -struct stat64_t -{ - uint64_t st_dev; - uint64_t st_ino; - uint64_t st_nlink; - uint32_t st_mode; - uint32_t st_uid; - uint32_t st_gid; - int __pad0; - uint64_t st_rdev; - uint64_t st_size; - int64_t st_blksize; - int64_t st_blocks; - int64_t st_atime; - int64_t st_atime_nsec; - int64_t st_mtime; - int64_t st_mtime_nsec; - int64_t st_ctime; - int64_t st_ctime_nsec; - int64_t __reserved[3]; -}; - -#endif diff --git a/tee-worker/bitacross/rust-sgx-sdk/edl/intel/sgx_dcap_tvl.edl b/tee-worker/bitacross/rust-sgx-sdk/edl/intel/sgx_dcap_tvl.edl deleted file mode 100644 index 7c5c0d8c69..0000000000 --- a/tee-worker/bitacross/rust-sgx-sdk/edl/intel/sgx_dcap_tvl.edl +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright (C) 2011-2020 Intel Corporation. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in - * the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Intel Corporation nor the names of its - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - */ - -enclave { - - include "sgx_qve_header.h" - include "sgx_ql_quote.h" - - - trusted { - - /** - * Verify QvE Report and Identity - * - * @param p_quote[IN] - Pointer to SGX Quote. - * @param quote_size[IN] - Size of the buffer pointed to by p_quote (in bytes). - * @param p_qve_report_info[IN] - The output of API "sgx_qv_verify_quote", it should contain QvE report and nonce - * @param expiration_check_date[IN] - This is the date to verify QvE report data, you should use same value for this API and "sgx_qv_verify_quote" - * @param collateral_expiration_status[IN] - The output of API "sgx_qv_verify_quote" about quote verification collateral's expiration status - * @param quote_verification_result[IN] - The output of API "sgx_qv_verify_quote" about quote verification result - * @param p_supplemental_data[IN] - The output of API "sgx_qv_verify_quote", the pointer to supplemental data - * @param supplemental_data_size[IN] - Size of the buffer pointed to by p_quote (in bytes) - * @param qve_isvsvn_threshold [IN] - The threshold of QvE ISVSVN, the ISVSVN of QvE used to verify quote must be greater or equal to this threshold. You can get latest QvE ISVSVN in QvE Identity (JSON) from Intel PCS. - * - * @return Status code of the operation, one of: - * - SGX_QL_SUCCESS - * - SGX_QL_ERROR_INVALID_PARAMETER - * - SGX_QL_ERROR_REPORT // Error when verifying QvE report - * - SGX_QL_ERROR_UNEXPECTED // Error when comparing QvE report data - * - SGX_QL_QVEIDENTITY_MISMATCH // Error when comparing QvE identity - * - SGX_QL_QVE_OUT_OF_DATE // QvE ISVSVN is smaller than input QvE ISV SVN threshold - **/ - - public quote3_error_t sgx_tvl_verify_qve_report_and_identity( - [in, size=quote_size] const uint8_t *p_quote, - uint32_t quote_size, - [in, count=1] const sgx_ql_qe_report_info_t *p_qve_report_info, - time_t expiration_check_date, - uint32_t collateral_expiration_status, - sgx_ql_qv_result_t quote_verification_result, - [in, size=supplemental_data_size] const uint8_t *p_supplemental_data, - uint32_t supplemental_data_size, - sgx_isv_svn_t qve_isvsvn_threshold); - }; -}; diff --git a/tee-worker/bitacross/rust-sgx-sdk/edl/intel/sgx_pthread.edl b/tee-worker/bitacross/rust-sgx-sdk/edl/intel/sgx_pthread.edl deleted file mode 100644 index 7a097a7396..0000000000 --- a/tee-worker/bitacross/rust-sgx-sdk/edl/intel/sgx_pthread.edl +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright (C) 2011-2019 Intel Corporation. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in - * the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Intel Corporation nor the names of its - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - */ - -enclave { - untrusted { - [cdecl] int pthread_wait_timeout_ocall (unsigned long long waiter, unsigned long long timeout); - [cdecl] int pthread_create_ocall(unsigned long long self); - [cdecl] int pthread_wakeup_ocall(unsigned long long waiter); - }; -}; diff --git a/tee-worker/bitacross/rust-sgx-sdk/edl/intel/sgx_tkey_exchange.edl b/tee-worker/bitacross/rust-sgx-sdk/edl/intel/sgx_tkey_exchange.edl deleted file mode 100644 index 3e18c89582..0000000000 --- a/tee-worker/bitacross/rust-sgx-sdk/edl/intel/sgx_tkey_exchange.edl +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (C) 2011-2019 Intel Corporation. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in - * the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Intel Corporation nor the names of its - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - */ - -enclave { - trusted { - public sgx_status_t sgx_ra_get_ga(sgx_ra_context_t context, - [out] sgx_ec256_public_t *g_a); - - public sgx_status_t sgx_ra_proc_msg2_trusted(sgx_ra_context_t context, - [in]const sgx_ra_msg2_t *p_msg2, /*copy msg2 except quote into enclave */ - [in] const sgx_target_info_t *p_qe_target, - [out] sgx_report_t *p_report, - [out] sgx_quote_nonce_t *p_nonce); - - public sgx_status_t sgx_ra_get_msg3_trusted(sgx_ra_context_t context, - uint32_t quote_size, - [in]sgx_report_t* qe_report, - [user_check]sgx_ra_msg3_t *p_msg3, - uint32_t msg3_size); - }; -}; diff --git a/tee-worker/bitacross/rust-sgx-sdk/edl/intel/sgx_tprotected_fs.edl b/tee-worker/bitacross/rust-sgx-sdk/edl/intel/sgx_tprotected_fs.edl deleted file mode 100644 index 2dfad370a9..0000000000 --- a/tee-worker/bitacross/rust-sgx-sdk/edl/intel/sgx_tprotected_fs.edl +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (C) 2011-2019 Intel Corporation. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in - * the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Intel Corporation nor the names of its - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - */ - -enclave { - from "sgx_tstdc.edl" import *; - untrusted { - void* u_sgxprotectedfs_exclusive_file_open([in, string] const char* filename, uint8_t read_only, [out] int64_t* file_size, [out] int32_t* error_code); - uint8_t u_sgxprotectedfs_check_if_file_exists([in, string] const char* filename); - int32_t u_sgxprotectedfs_fread_node([user_check] void* f, uint64_t node_number, [out, size=node_size] uint8_t* buffer, uint32_t node_size); - int32_t u_sgxprotectedfs_fwrite_node([user_check] void* f, uint64_t node_number, [in, size=node_size] uint8_t* buffer, uint32_t node_size); - int32_t u_sgxprotectedfs_fclose([user_check] void* f); - uint8_t u_sgxprotectedfs_fflush([user_check] void* f); - int32_t u_sgxprotectedfs_remove([in, string] const char* filename); - - void* u_sgxprotectedfs_recovery_file_open([in, string] const char* filename); - uint8_t u_sgxprotectedfs_fwrite_recovery_node([user_check] void* f, [in, count=data_length] uint8_t* data, uint32_t data_length); - int32_t u_sgxprotectedfs_do_file_recovery([in, string] const char* filename, [in, string] const char* recovery_filename, uint32_t node_size); - }; -}; diff --git a/tee-worker/bitacross/rust-sgx-sdk/edl/intel/sgx_tstdc.edl b/tee-worker/bitacross/rust-sgx-sdk/edl/intel/sgx_tstdc.edl deleted file mode 100644 index 4124debcfb..0000000000 --- a/tee-worker/bitacross/rust-sgx-sdk/edl/intel/sgx_tstdc.edl +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (C) 2011-2019 Intel Corporation. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in - * the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Intel Corporation nor the names of its - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - */ - -enclave { - untrusted { - [cdecl] void sgx_oc_cpuidex([out] int cpuinfo[4], int leaf, int subleaf); - - /* Go outside and wait on my untrusted event */ - [cdecl] int sgx_thread_wait_untrusted_event_ocall([user_check] const void *self); - - /* Wake a thread waiting on its untrusted event */ - [cdecl] int sgx_thread_set_untrusted_event_ocall([user_check] const void *waiter); - - /* Wake a thread waiting on its untrusted event, and wait on my untrusted event */ - [cdecl] int sgx_thread_setwait_untrusted_events_ocall([user_check] const void *waiter, [user_check] const void *self); - - /* Wake multiple threads waiting on their untrusted events */ - [cdecl] int sgx_thread_set_multiple_untrusted_events_ocall([in, count = total] const void **waiters, size_t total); - }; -}; diff --git a/tee-worker/bitacross/rust-sgx-sdk/edl/intel/sgx_tswitchless.edl b/tee-worker/bitacross/rust-sgx-sdk/edl/intel/sgx_tswitchless.edl deleted file mode 100644 index a20669ab59..0000000000 --- a/tee-worker/bitacross/rust-sgx-sdk/edl/intel/sgx_tswitchless.edl +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (C) 2011-2019 Intel Corporation. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in - * the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Intel Corporation nor the names of its - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - */ - -enclave { - - trusted { - public sgx_status_t sl_init_switchless([user_check]void* sl_data); - public sgx_status_t sl_run_switchless_tworker(); - }; - -}; diff --git a/tee-worker/bitacross/rust-sgx-sdk/edl/intel/sgx_ttls.edl b/tee-worker/bitacross/rust-sgx-sdk/edl/intel/sgx_ttls.edl deleted file mode 100644 index ca0906f578..0000000000 --- a/tee-worker/bitacross/rust-sgx-sdk/edl/intel/sgx_ttls.edl +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright (C) 2011-2021 Intel Corporation. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in - * the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Intel Corporation nor the names of its - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - */ - -enclave{ - include "sgx_report.h" - include "sgx_qve_header.h" - include "sgx_ql_lib_common.h" - include "sgx_ql_quote.h" - - untrusted { - quote3_error_t sgx_tls_get_qe_target_info_ocall([size = target_info_size, out] sgx_target_info_t *p_target_info, - size_t target_info_size); - - quote3_error_t sgx_tls_get_quote_size_ocall([out] uint32_t *p_quote_size); - - quote3_error_t sgx_tls_get_quote_ocall([size = report_size, in] sgx_report_t* p_report, - size_t report_size, - [size = quote_size, out] uint8_t *p_quote, - uint32_t quote_size); - - quote3_error_t sgx_tls_get_supplemental_data_size_ocall([out] uint32_t *p_supplemental_data_size); - - quote3_error_t sgx_tls_verify_quote_ocall( - [size = quote_size, in] const uint8_t *p_quote, - uint32_t quote_size, - time_t expiration_check_date, - [out] sgx_ql_qv_result_t *p_quote_verification_result, - [size = qve_report_info_size, in, out] sgx_ql_qe_report_info_t *p_qve_report_info, - size_t qve_report_info_size, - [size = supplemental_data_size, out] uint8_t *p_supplemental_data, - uint32_t supplemental_data_size); - - }; -}; diff --git a/tee-worker/bitacross/rust-sgx-sdk/edl/sgx_asyncio.edl b/tee-worker/bitacross/rust-sgx-sdk/edl/sgx_asyncio.edl deleted file mode 100644 index f46373894e..0000000000 --- a/tee-worker/bitacross/rust-sgx-sdk/edl/sgx_asyncio.edl +++ /dev/null @@ -1,33 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -enclave { - - include "sys/epoll.h" - include "poll.h" - - trusted { - /* define ECALLs here. */ - }; - - untrusted { - int u_poll_ocall([out] int *error, [in, out, count=nfds] struct pollfd *fds, nfds_t nfds, int timeout); - int u_epoll_create1_ocall([out] int *error, int flags); - int u_epoll_ctl_ocall([out] int *error, int epfd, int op, int fd, [in] struct epoll_event *event); - int u_epoll_wait_ocall([out] int *error, int epfd, [out, count=maxevents] struct epoll_event *events, int maxevents, int timeout); - }; -}; diff --git a/tee-worker/bitacross/rust-sgx-sdk/edl/sgx_backtrace.edl b/tee-worker/bitacross/rust-sgx-sdk/edl/sgx_backtrace.edl deleted file mode 100644 index 4a9e7ef8c4..0000000000 --- a/tee-worker/bitacross/rust-sgx-sdk/edl/sgx_backtrace.edl +++ /dev/null @@ -1,31 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -enclave { - - from "sgx_fd.edl" import *; - from "sgx_file.edl" import *; - from "sgx_mem.edl" import *; - - trusted { - /* define ECALLs here. */ - }; - - untrusted { - /* define OCALLs here. */ - }; -}; diff --git a/tee-worker/bitacross/rust-sgx-sdk/edl/sgx_env.edl b/tee-worker/bitacross/rust-sgx-sdk/edl/sgx_env.edl deleted file mode 100644 index d4a77cc816..0000000000 --- a/tee-worker/bitacross/rust-sgx-sdk/edl/sgx_env.edl +++ /dev/null @@ -1,40 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -enclave { - - include "pwd.h" - - trusted { - /* define ECALLs here. */ - }; - - untrusted { - char **u_environ_ocall(); - char *u_getenv_ocall([in, string] const char *name); - int u_setenv_ocall([out] int *error, [in, string] const char *name, [in, string] const char *value, int overwrite); - int u_unsetenv_ocall([out] int *error, [in, string] const char *name); - int u_chdir_ocall([out] int *error, [in, string] const char *dir); - char *u_getcwd_ocall([out] int *error, [out, size=buflen] char *buf, size_t buflen); - int u_getpwuid_r_ocall(unsigned int uid, - [out] struct passwd *pwd, - [out, size=buflen] char *buf, - size_t buflen, - [out] struct passwd **passwd_result); - unsigned int u_getuid_ocall(); - }; -}; diff --git a/tee-worker/bitacross/rust-sgx-sdk/edl/sgx_fd.edl b/tee-worker/bitacross/rust-sgx-sdk/edl/sgx_fd.edl deleted file mode 100644 index cd668b71c0..0000000000 --- a/tee-worker/bitacross/rust-sgx-sdk/edl/sgx_fd.edl +++ /dev/null @@ -1,57 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -enclave { - - include "inc/stat.h" - include "sys/uio.h" - include "time.h" - - from "sgx_mem.edl" import *; - - trusted { - /* define ECALLs here. */ - }; - - untrusted { - size_t u_read_ocall([out] int *error, int fd, [user_check] void *buf, size_t count); - size_t u_pread64_ocall([out] int *error, int fd, [user_check] void *buf, size_t count, int64_t offset); - size_t u_readv_ocall([out] int *error, int fd, [in, count=iovcnt] const struct iovec *iov, int iovcnt); - size_t u_preadv64_ocall([out] int *error, int fd, [in, count=iovcnt] const struct iovec *iov, int iovcnt, int64_t offset); - - size_t u_write_ocall([out] int *error, int fd, [user_check] const void *buf, size_t count); - size_t u_pwrite64_ocall([out] int *error, int fd, [user_check] const void *buf, size_t count, int64_t offset); - size_t u_writev_ocall([out] int *error, int fd, [in, count=iovcnt] const struct iovec *iov, int iovcnt); - size_t u_pwritev64_ocall([out] int *error, int fd, [in, count=iovcnt] const struct iovec *iov, int iovcnt, int64_t offset); - - size_t u_sendfile_ocall([out] int *error, int out_fd, int in_fd, [in, out] int64_t *offset, size_t count); - size_t u_copy_file_range_ocall([out] int *error, int fd_in, [in, out] int64_t *off_in, int fd_out, [in, out] int64_t *off_out, size_t len, unsigned int flags); - size_t u_splice_ocall([out] int *error, int fd_in, [in, out] int64_t *off_in, int fd_out, [in, out] int64_t *off_out, size_t len, unsigned int flags); - - int u_fcntl_arg0_ocall([out] int *error, int fd, int cmd); - int u_fcntl_arg1_ocall([out] int *error, int fd, int cmd, int arg); - int u_ioctl_arg0_ocall([out] int *error, int fd, int request); - int u_ioctl_arg1_ocall([out] int *error, int fd, int request, [in, out] int *arg); - - int u_close_ocall([out] int *error, int fd); - int u_isatty_ocall([out] int *error, int fd); - int u_dup_ocall([out] int *error, int oldfd); - int u_eventfd_ocall([out] int *error, unsigned int initval, int flags); - - int u_futimens_ocall([out] int *error, int fd, [in, count=2] const struct timespec *times); - }; -}; diff --git a/tee-worker/bitacross/rust-sgx-sdk/edl/sgx_file.edl b/tee-worker/bitacross/rust-sgx-sdk/edl/sgx_file.edl deleted file mode 100644 index c70ec599a2..0000000000 --- a/tee-worker/bitacross/rust-sgx-sdk/edl/sgx_file.edl +++ /dev/null @@ -1,66 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -enclave { - - include "inc/stat.h" - include "inc/dirent.h" - - trusted { - /* define ECALLs here. */ - }; - - untrusted { - int u_open_ocall([out] int *error, [in, string] const char *pathname, int flags); - int u_open64_ocall([out] int *error, [in, string] const char *path, int oflag, int mode); - int u_openat_ocall([out] int *error, int dirfd, [in, string] const char *pathname, int flags); - - int u_fstat_ocall([out] int *error, int fd, [out] struct stat_t *buf); - int u_fstat64_ocall([out] int *error, int fd, [out] struct stat64_t *buf); - int u_stat_ocall([out] int *error, [in, string] const char *path, [out] struct stat_t *buf); - int u_stat64_ocall([out] int *error, [in, string] const char *path, [out] struct stat64_t *buf); - int u_lstat_ocall([out] int *error, [in, string] const char *path, [out] struct stat_t *buf); - int u_lstat64_ocall([out] int *error, [in, string] const char *path, [out] struct stat64_t *buf); - uint64_t u_lseek_ocall([out] int *error, int fd, int64_t offset, int whence); - int64_t u_lseek64_ocall([out] int *error, int fd, int64_t offset, int whence); - int u_ftruncate_ocall([out] int *error, int fd, int64_t length); - int u_ftruncate64_ocall([out] int *error, int fd, int64_t length); - int u_truncate_ocall([out] int *error, [in, string] const char *path, int64_t length); - int u_truncate64_ocall([out] int *error, [in, string] const char *path, int64_t length); - - int u_fsync_ocall([out] int *error, int fd); - int u_fdatasync_ocall([out] int *error, int fd); - int u_fchmod_ocall([out] int *error, int fd, uint32_t mode); - int u_unlink_ocall([out] int *error, [in, string] const char *pathname); - int u_link_ocall([out] int *error, [in, string] const char *oldpath, [in, string] const char *newpath); - int u_unlinkat_ocall([out] int *error, int dirfd, [in, string] const char *pathname, int flags); - int u_linkat_ocall([out] int *error, int olddirfd, [in, string] const char *oldpath, int newdirfd, [in, string] const char *newpath, int flags); - int u_rename_ocall([out] int *error, [in, string] const char *oldpath, [in, string] const char *newpath); - int u_chmod_ocall([out] int *error, [in, string] const char *path, uint32_t mode); - size_t u_readlink_ocall([out] int *error, [in, string] const char *path, [out, size=bufsz] char *buf, size_t bufsz); - int u_symlink_ocall([out] int *error, [in, string] const char *path1, [in, string] const char *path2); - char *u_realpath_ocall([out] int *error, [in, string] const char *pathname); - int u_mkdir_ocall([out] int *error, [in, string] const char *pathname, uint32_t mode); - int u_rmdir_ocall([out] int *error, [in, string] const char *pathname); - void *u_fdopendir_ocall([out] int *error, int fd); - void *u_opendir_ocall([out] int *error, [in, string] const char *pathname); - int u_readdir64_r_ocall([user_check] void *dirp, [in, out] struct dirent64_t *entry, [out] struct dirent64_t **result); - int u_closedir_ocall([out] int *error, [user_check] void *dirp); - int u_dirfd_ocall([out] int *error, [user_check] void *dirp); - int u_fstatat64_ocall([out] int *error, int dirfd, [in, string] const char *pathname, [out] struct stat64_t *buf, int flags); - }; -}; diff --git a/tee-worker/bitacross/rust-sgx-sdk/edl/sgx_fs.edl b/tee-worker/bitacross/rust-sgx-sdk/edl/sgx_fs.edl deleted file mode 100644 index 2618be9352..0000000000 --- a/tee-worker/bitacross/rust-sgx-sdk/edl/sgx_fs.edl +++ /dev/null @@ -1,31 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -enclave { - - from "sgx_mem.edl" import *; - from "sgx_fd.edl" import *; - from "sgx_file.edl" import *; - - trusted { - /* define ECALLs here. */ - }; - - untrusted { - /* define OCALLs here. */ - }; -}; diff --git a/tee-worker/bitacross/rust-sgx-sdk/edl/sgx_mem.edl b/tee-worker/bitacross/rust-sgx-sdk/edl/sgx_mem.edl deleted file mode 100644 index db55802755..0000000000 --- a/tee-worker/bitacross/rust-sgx-sdk/edl/sgx_mem.edl +++ /dev/null @@ -1,40 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -enclave { - - trusted { - /* define ECALLs here. */ - }; - - untrusted { - void *u_malloc_ocall([out] int *error, size_t size); - void u_free_ocall([user_check] void *p); - - void *u_mmap_ocall([out] int *error, - [user_check] void *start, - size_t length, - int prot, - int flags, - int fd, - int64_t offset); - int u_munmap_ocall([out] int *error, [user_check] void *start, size_t length); - - int u_msync_ocall([out] int *error, [user_check] void *addr, size_t length, int flags); - int u_mprotect_ocall([out] int *error, [user_check] void *addr, size_t length, int prot); - }; -}; diff --git a/tee-worker/bitacross/rust-sgx-sdk/edl/sgx_net.edl b/tee-worker/bitacross/rust-sgx-sdk/edl/sgx_net.edl deleted file mode 100644 index a803b53ac2..0000000000 --- a/tee-worker/bitacross/rust-sgx-sdk/edl/sgx_net.edl +++ /dev/null @@ -1,41 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -enclave { - - include "sys/socket.h" - include "netdb.h" - - from "sgx_socket.edl" import *; - from "sgx_asyncio.edl" import *; - from "sgx_fd.edl" import *; - from "sgx_time.edl" import *; - - trusted { - /* define ECALLs here. */ - }; - - untrusted { - int u_getaddrinfo_ocall([out] int *error, - [in, string] const char *node, - [in, string] const char *service, - [in] const struct addrinfo *hints, - [out] struct addrinfo **res); - void u_freeaddrinfo_ocall([user_check] struct addrinfo *res); - char *u_gai_strerror_ocall(int errcode); - }; -}; diff --git a/tee-worker/bitacross/rust-sgx-sdk/edl/sgx_net_switchless.edl b/tee-worker/bitacross/rust-sgx-sdk/edl/sgx_net_switchless.edl deleted file mode 100644 index ec5c500cfc..0000000000 --- a/tee-worker/bitacross/rust-sgx-sdk/edl/sgx_net_switchless.edl +++ /dev/null @@ -1,92 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -enclave { - - include "sys/socket.h" - include "poll.h" - from "sgx_fs.edl" import *; - from "sgx_time.edl" import *; - from "sgx_mem.edl" import *; - - trusted { - /* define ECALLs here. */ - }; - - untrusted { - - int u_net_socket_ocall([out] int *error, int domain, int ty, int protocol) transition_using_threads; - int u_net_socketpair_ocall([out] int *error, int domain, int ty, int protocol, [out] int sv[2]) transition_using_threads; - int u_net_bind_ocall([out] int *error, int sockfd, [in, size=addrlen] const struct sockaddr *addr, socklen_t addrlen) transition_using_threads; - int u_net_listen_ocall([out] int *error, int sockfd, int backlog) transition_using_threads; - int u_net_accept4_ocall([out] int *error, - int sockfd, - [in, out, size=addrlen_in] struct sockaddr *addr, - socklen_t addrlen_in, - [out] socklen_t *addrlen_out, - int flags) transition_using_threads; - int u_net_connect_ocall([out] int *error, - int sockfd, - [in, size=addrlen] const struct sockaddr *addr, - socklen_t addrlen) transition_using_threads; - size_t u_net_recv_ocall([out] int *error, int sockfd, [out, size=len] void *buf, size_t len, int flags) transition_using_threads; - size_t u_net_recvfrom_ocall([out] int *error, - int sockfd, - [out, size=len] void *buf, - size_t len, - int flags, - [out, size=addrlen_in] struct sockaddr *src_addr, - socklen_t addrlen_in, - [out] socklen_t *addrlen_out) transition_using_threads; - size_t u_net_recvmsg_ocall([out] int *error, int sockfd, [in, out] struct msghdr *msg, int flags) transition_using_threads; - size_t u_net_send_ocall([out] int *error, int sockfd, [in, size=len] const void *buf, size_t len, int flags) transition_using_threads; - size_t u_net_sendto_ocall([out] int *error, - int sockfd, - [in, size=len] const void *buf, - size_t len, - int flags, - [in, size=addrlen] const struct sockaddr *dest_addr, - socklen_t addrlen) transition_using_threads; - size_t u_sendmsg_ocall([out] int *error, int sockfd, [in] const struct msghdr *msg, int flags) transition_using_threads; - int u_net_getsockopt_ocall([out] int *error, - int sockfd, - int level, - int optname, - [out, size=optlen_in] void *optval, - socklen_t optlen_in, - [out] socklen_t *optlen_out) transition_using_threads; - int u_net_setsockopt_ocall([out] int *error, - int sockfd, - int level, - int optname, - [in, size=optlen] const void *optval, - socklen_t optlen) transition_using_threads; - int u_net_getsockname_ocall([out] int *error, - int sockfd, - [out, size=addrlen_in] struct sockaddr *addr, - socklen_t addrlen_in, - [out] socklen_t *addrlen_out) transition_using_threads; - int u_net_getpeername_ocall([out] int *error, - int sockfd, - [out, size=addrlen_in] struct sockaddr *addr, - socklen_t addrlen_in, - [out] socklen_t *addrlen_out) transition_using_threads; - int u_net_shutdown_ocall([out] int *error, int sockfd, int how) transition_using_threads; - int u_net_ioctl_ocall([out] int *error, int fd, int request, [in, out] int *arg) transition_using_threads; - int u_net_poll_ocall([out] int *error, [in, out, count=nfds] struct pollfd *fds, nfds_t nfds, int timeout) transition_using_threads; - }; -}; diff --git a/tee-worker/bitacross/rust-sgx-sdk/edl/sgx_pipe.edl b/tee-worker/bitacross/rust-sgx-sdk/edl/sgx_pipe.edl deleted file mode 100644 index 00c12f5e7c..0000000000 --- a/tee-worker/bitacross/rust-sgx-sdk/edl/sgx_pipe.edl +++ /dev/null @@ -1,31 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -enclave { - - from "sgx_fd.edl" import *; - from "sgx_asyncio.edl" import *; - - trusted { - /* define ECALLs here. */ - }; - - untrusted { - int u_pipe_ocall([out] int *error, [out, count=2] int *pipefd); - int u_pipe2_ocall([out] int *error, [out, count=2] int *pipefd, int flags); - }; -}; diff --git a/tee-worker/bitacross/rust-sgx-sdk/edl/sgx_process.edl b/tee-worker/bitacross/rust-sgx-sdk/edl/sgx_process.edl deleted file mode 100644 index 69123df5d8..0000000000 --- a/tee-worker/bitacross/rust-sgx-sdk/edl/sgx_process.edl +++ /dev/null @@ -1,28 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -enclave { - - trusted { - /* define ECALLs here. */ - - }; - - untrusted { - int u_getpid_ocall(); - }; -}; diff --git a/tee-worker/bitacross/rust-sgx-sdk/edl/sgx_signal.edl b/tee-worker/bitacross/rust-sgx-sdk/edl/sgx_signal.edl deleted file mode 100644 index fd9b0f0d14..0000000000 --- a/tee-worker/bitacross/rust-sgx-sdk/edl/sgx_signal.edl +++ /dev/null @@ -1,43 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -enclave { - include "signal.h" - - trusted { - /* define ECALLs here. */ - public int t_signal_handler_ecall([in]const siginfo_t *info); - }; - - untrusted { - int u_sigaction_ocall([out]int *error, - int signum, - [in] const struct sigaction *act, - [out] struct sigaction *oldact, - uint64_t enclave_id); - - int u_sigprocmask_ocall([out]int *error, - int signum, - [in] const sigset_t *set, - [out] sigset_t *oldset); - - int u_raise_ocall(int signum) allow(t_signal_handler_ecall); - - void u_signal_clear_ocall(uint64_t enclave_id); - }; -}; - diff --git a/tee-worker/bitacross/rust-sgx-sdk/edl/sgx_socket.edl b/tee-worker/bitacross/rust-sgx-sdk/edl/sgx_socket.edl deleted file mode 100644 index 6fc8ff7c85..0000000000 --- a/tee-worker/bitacross/rust-sgx-sdk/edl/sgx_socket.edl +++ /dev/null @@ -1,111 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -enclave { - - include "sys/socket.h" - - from "sgx_mem.edl" import *; - - trusted { - /* define ECALLs here. */ - }; - - untrusted { - int u_socket_ocall([out] int *error, int domain, int ty, int protocol); - int u_socketpair_ocall([out] int *error, int domain, int ty, int protocol, [out] int sv[2]); - int u_bind_ocall([out] int *error, int sockfd, [in, size=addrlen] const struct sockaddr *addr, socklen_t addrlen); - int u_listen_ocall([out] int *error, int sockfd, int backlog); - int u_accept_ocall([out] int *error, - int sockfd, - [in, out, size=addrlen_in] struct sockaddr *addr, - socklen_t addrlen_in, - [out] socklen_t *addrlen_out); - int u_accept4_ocall([out] int *error, - int sockfd, - [in, out, size=addrlen_in] struct sockaddr *addr, - socklen_t addrlen_in, - [out] socklen_t *addrlen_out, - int flags); - int u_connect_ocall([out] int *error, - int sockfd, - [in, size=addrlen] const struct sockaddr *addr, - socklen_t addrlen); - size_t u_recv_ocall([out] int *error, int sockfd,[user_check] void *buf, size_t len, int flags); - size_t u_recvfrom_ocall([out] int *error, - int sockfd, - [user_check] void *buf, - size_t len, - int flags, - [out, size=addrlen_in] struct sockaddr *src_addr, - socklen_t addrlen_in, - [out] socklen_t *addrlen_out); - size_t u_recvmsg_ocall([out] int *error, - int sockfd, - [out, size=msg_namelen] void *msg_name, - socklen_t msg_namelen, - [out] socklen_t* msg_namelen_out, - [in, count=msg_iovlen] struct iovec* msg_iov, - size_t msg_iovlen, - [out, size=msg_controllen] void *msg_control, - size_t msg_controllen, - [out] size_t* msg_controllen_out, - [out] int* msg_flags, - int flags); - size_t u_send_ocall([out] int *error, int sockfd, [user_check] const void *buf, size_t len, int flags); - size_t u_sendto_ocall([out] int *error, - int sockfd, - [user_check] const void *buf, - size_t len, - int flags, - [in, size=addrlen] const struct sockaddr *dest_addr, - socklen_t addrlen); - size_t u_sendmsg_ocall([out] int *error, - int sockfd, - [in, size=msg_namelen] const void* msg_name, - socklen_t msg_namelen, - [in, count=msg_iovlen] const struct iovec* msg_iov, - size_t msg_iovlen, - [in, size=msg_controllen] const void* msg_control, - size_t msg_controllen, - int flags); - int u_getsockopt_ocall([out] int *error, - int sockfd, - int level, - int optname, - [out, size=optlen_in] void *optval, - socklen_t optlen_in, - [out] socklen_t *optlen_out); - int u_setsockopt_ocall([out] int *error, - int sockfd, - int level, - int optname, - [in, size=optlen] const void *optval, - socklen_t optlen); - int u_getsockname_ocall([out] int *error, - int sockfd, - [out, size=addrlen_in] struct sockaddr *addr, - socklen_t addrlen_in, - [out] socklen_t *addrlen_out); - int u_getpeername_ocall([out] int *error, - int sockfd, - [out, size=addrlen_in] struct sockaddr *addr, - socklen_t addrlen_in, - [out] socklen_t *addrlen_out); - int u_shutdown_ocall([out] int *error, int sockfd, int how); - }; -}; diff --git a/tee-worker/bitacross/rust-sgx-sdk/edl/sgx_stdio.edl b/tee-worker/bitacross/rust-sgx-sdk/edl/sgx_stdio.edl deleted file mode 100644 index 5367d9ab97..0000000000 --- a/tee-worker/bitacross/rust-sgx-sdk/edl/sgx_stdio.edl +++ /dev/null @@ -1,29 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -enclave { - - from "sgx_fd.edl" import *; - - trusted { - /* define ECALLs here. */ - }; - - untrusted { - /* define OCALLs here. */ - }; -}; diff --git a/tee-worker/bitacross/rust-sgx-sdk/edl/sgx_sys.edl b/tee-worker/bitacross/rust-sgx-sdk/edl/sgx_sys.edl deleted file mode 100644 index bc74b96843..0000000000 --- a/tee-worker/bitacross/rust-sgx-sdk/edl/sgx_sys.edl +++ /dev/null @@ -1,32 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -enclave { - - include "sched.h" - - trusted { - /* define ECALLs here. */ - }; - - untrusted { - long u_sysconf_ocall([out] int *error, int name); - int u_prctl_ocall([out] int *error, int option, unsigned long arg2, unsigned long arg3, unsigned long arg4, unsigned long arg5); - int u_sched_setaffinity_ocall([out] int *error, pid_t pid, size_t cpusetsize, [in, size=cpusetsize] cpu_set_t *mask); - int u_sched_getaffinity_ocall([out] int *error, pid_t pid, size_t cpusetsize, [out, size=cpusetsize] cpu_set_t *mask); - }; -}; diff --git a/tee-worker/bitacross/rust-sgx-sdk/edl/sgx_thread.edl b/tee-worker/bitacross/rust-sgx-sdk/edl/sgx_thread.edl deleted file mode 100644 index 71512f0e56..0000000000 --- a/tee-worker/bitacross/rust-sgx-sdk/edl/sgx_thread.edl +++ /dev/null @@ -1,32 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -enclave { - - include "time.h" - - from "intel/sgx_pthread.edl" import *; - from "sgx_sys.edl" import *; - - trusted { - /* define ECALLs here. */ - }; - - untrusted { - int u_sched_yield_ocall([out]int *error); - int u_nanosleep_ocall([out]int *error, [in]const struct timespec *req, [out]struct timespec *rem); - }; -}; diff --git a/tee-worker/bitacross/rust-sgx-sdk/edl/sgx_time.edl b/tee-worker/bitacross/rust-sgx-sdk/edl/sgx_time.edl deleted file mode 100644 index adeeeccf92..0000000000 --- a/tee-worker/bitacross/rust-sgx-sdk/edl/sgx_time.edl +++ /dev/null @@ -1,29 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -enclave { - - include "time.h" - - trusted { - /* define ECALLs here. */ - }; - - untrusted { - int u_clock_gettime_ocall([out] int *error, int clk_id, [out] struct timespec *tp); - }; -}; diff --git a/tee-worker/bitacross/rust-sgx-sdk/edl/sgx_tstd.edl b/tee-worker/bitacross/rust-sgx-sdk/edl/sgx_tstd.edl deleted file mode 100644 index 9b74272f50..0000000000 --- a/tee-worker/bitacross/rust-sgx-sdk/edl/sgx_tstd.edl +++ /dev/null @@ -1,38 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -enclave { - - from "sgx_time.edl" import *; - - trusted { - /* define ECALLs here. */ - public void t_global_init_ecall(uint64_t id, [in, size=len] const uint8_t *path, size_t len); - public void t_global_exit_ecall(); - }; - - untrusted { - /* define OCALLs here. */ - int u_thread_set_event_ocall([out] int *error, [user_check] const void *tcs); - int u_thread_wait_event_ocall([out] int *error, [user_check] const void *tcs, [in] const struct timespec *timeout); - int u_thread_set_multiple_events_ocall([out] int *error, [in, count=total] const void **tcss, int total); - int u_thread_setwait_events_ocall([out] int *error, - [user_check] const void *waiter_tcs, - [user_check] const void *self_tcs, - [in] const struct timespec *timeout); - }; -}; diff --git a/tee-worker/bitacross/rust-sgx-sdk/version b/tee-worker/bitacross/rust-sgx-sdk/version deleted file mode 100644 index 78e68ab976..0000000000 --- a/tee-worker/bitacross/rust-sgx-sdk/version +++ /dev/null @@ -1 +0,0 @@ -27bd225ae6dbcd1d0a6d4d9590acc4d73c5195c2 diff --git a/tee-worker/bitacross/scripts/benchmark_local-setup.sh b/tee-worker/bitacross/scripts/benchmark_local-setup.sh deleted file mode 100644 index 40bc700f05..0000000000 --- a/tee-worker/bitacross/scripts/benchmark_local-setup.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/bin/bash -set -e - -pushd .. - -pushd bin -./litentry-worker mrenclave | tee ~/mrenclave.b58 -popd - -ulimit -S -n 4096 - -python3 local-setup/launch.py local-setup/config/benchmark.json & -PID=$! -echo $PID > ./benchmark.pid -echo "Benchmark PID: $PID" - -sleep 40s - -pushd bin -./bitacross-cli -p 9930 -P 2030 trusted --direct --mrenclave "$(cat ~/mrenclave.b58)" benchmark 20 100 -w -popd - -sleep 10s - -if test -f "./benchmark.pid"; then - echo "Killing benchmark process" - kill -s SIGTERM "$(cat ./benchmark.pid)" - rm benchmark.pid -fi - -popd diff --git a/tee-worker/bitacross/scripts/changelog/.gitignore b/tee-worker/bitacross/scripts/changelog/.gitignore deleted file mode 100644 index 4fbcc523b0..0000000000 --- a/tee-worker/bitacross/scripts/changelog/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -changelog.md -*.json -release*.md -.env diff --git a/tee-worker/bitacross/scripts/changelog/Gemfile b/tee-worker/bitacross/scripts/changelog/Gemfile deleted file mode 100644 index f2d7c3bd71..0000000000 --- a/tee-worker/bitacross/scripts/changelog/Gemfile +++ /dev/null @@ -1,21 +0,0 @@ -# frozen_string_literal: true - -source 'https://rubygems.org' - -git_source(:github) { |repo_name| "https://github.com/#{repo_name}" } - -gem 'octokit', '~> 4' - -gem 'git_diff_parser', '~> 3' - -gem 'toml', '~> 0.3.0' - -gem 'rake', group: :dev - -gem 'optparse', '~> 0.1.1' - -gem 'logger', '~> 1.4' - -gem 'test-unit', group: :dev - -gem 'rubocop', group: :dev, require: false diff --git a/tee-worker/bitacross/scripts/changelog/Gemfile.lock b/tee-worker/bitacross/scripts/changelog/Gemfile.lock deleted file mode 100644 index 6c22948a8e..0000000000 --- a/tee-worker/bitacross/scripts/changelog/Gemfile.lock +++ /dev/null @@ -1,82 +0,0 @@ -GEM - remote: https://rubygems.org/ - specs: - addressable (2.8.0) - public_suffix (>= 2.0.2, < 5.0) - ast (2.4.2) - faraday (1.8.0) - faraday-em_http (~> 1.0) - faraday-em_synchrony (~> 1.0) - faraday-excon (~> 1.1) - faraday-httpclient (~> 1.0.1) - faraday-net_http (~> 1.0) - faraday-net_http_persistent (~> 1.1) - faraday-patron (~> 1.0) - faraday-rack (~> 1.0) - multipart-post (>= 1.2, < 3) - ruby2_keywords (>= 0.0.4) - faraday-em_http (1.0.0) - faraday-em_synchrony (1.0.0) - faraday-excon (1.1.0) - faraday-httpclient (1.0.1) - faraday-net_http (1.0.1) - faraday-net_http_persistent (1.2.0) - faraday-patron (1.0.0) - faraday-rack (1.0.0) - git_diff_parser (3.2.0) - logger (1.4.4) - multipart-post (2.1.1) - octokit (4.21.0) - faraday (>= 0.9) - sawyer (~> 0.8.0, >= 0.5.3) - optparse (0.1.1) - parallel (1.21.0) - parser (3.0.2.0) - ast (~> 2.4.1) - parslet (2.0.0) - power_assert (2.0.1) - public_suffix (4.0.6) - rainbow (3.0.0) - rake (13.0.6) - regexp_parser (2.1.1) - rexml (3.3.6) - strscan - rubocop (1.23.0) - parallel (~> 1.10) - parser (>= 3.0.0.0) - rainbow (>= 2.2.2, < 4.0) - regexp_parser (>= 1.8, < 3.0) - rexml - rubocop-ast (>= 1.12.0, < 2.0) - ruby-progressbar (~> 1.7) - unicode-display_width (>= 1.4.0, < 3.0) - rubocop-ast (1.13.0) - parser (>= 3.0.1.1) - ruby-progressbar (1.11.0) - ruby2_keywords (0.0.5) - sawyer (0.8.2) - addressable (>= 2.3.5) - faraday (> 0.8, < 2.0) - strscan (3.1.0) - test-unit (3.5.1) - power_assert - toml (0.3.0) - parslet (>= 1.8.0, < 3.0.0) - unicode-display_width (2.1.0) - -PLATFORMS - x86_64-darwin-20 - x86_64-linux - -DEPENDENCIES - git_diff_parser (~> 3) - logger (~> 1.4) - octokit (~> 4) - optparse (~> 0.1.1) - rake - rubocop - test-unit - toml (~> 0.3.0) - -BUNDLED WITH - 2.2.22 diff --git a/tee-worker/bitacross/scripts/changelog/README.md b/tee-worker/bitacross/scripts/changelog/README.md deleted file mode 100644 index 4776277e70..0000000000 --- a/tee-worker/bitacross/scripts/changelog/README.md +++ /dev/null @@ -1,3 +0,0 @@ -## License - -Everything in this folder is GPL 3.0 licensed. The original has been authored by parity and was taken from here: https://github.com/paritytech/polkadot/tree/master/scripts/ci/changelog. \ No newline at end of file diff --git a/tee-worker/bitacross/scripts/changelog/bin/changelog b/tee-worker/bitacross/scripts/changelog/bin/changelog deleted file mode 100755 index 15b17d6166..0000000000 --- a/tee-worker/bitacross/scripts/changelog/bin/changelog +++ /dev/null @@ -1,84 +0,0 @@ -#!/usr/bin/env ruby - -# frozen_string_literal: true - -# call for instance as: -# ./bin/changelog [] [] -# for instance, for the release notes of v1.2.3: -# ./bin/changelog v1.2.3 -# or -# ./bin/changelog v1.2.3 v1.2.2 -# -# You may set the ENV NO_CACHE to force fetching from Github -# You should also ensure you set the ENV: GITHUB_TOKEN - -require_relative '../lib/changelog' -require 'logger' - -logger = Logger.new($stdout) -logger.level = Logger::DEBUG -logger.debug('Starting') - -owner = 'integritee-network' -repo = 'worker' - -gh_worker = SubRef.new(format('%s/%s', { owner: owner, repo: repo })) -last_release_ref = gh_worker.get_last_ref() - -worker_ref2 = ARGV[0] || 'HEAD' -worker_ref1 = ARGV[1] || last_release_ref - -output = ARGV[2] || 'release-notes.md' - -ENV['REF1'] = worker_ref1 -ENV['REF2'] = worker_ref2 - -pallets_ref1 = gh_worker.get_dependency_reference(worker_ref1, 'pallet-teerex') -pallets_ref2 = gh_worker.get_dependency_reference(worker_ref2, 'pallet-teerex') - -logger.debug("Worker from: #{worker_ref1}") -logger.debug("Worker to: #{worker_ref2}") - -logger.debug("Pallets from: #{pallets_ref1}") -logger.debug("Pallets to: #{pallets_ref2}") - -pallets_data = 'pallets.json' -worker_data = 'worker.json' - -logger.debug("Using PALLETS: #{pallets_data}") -logger.debug("Using WORKER: #{worker_data}") - -logger.warn('NO_CACHE set') if ENV['NO_CACHE'] - -if ENV['NO_CACHE'] || !File.file?(worker_data) - logger.debug(format('Fetching data for Worker into %s', worker_data)) - cmd = format('changelogerator %s/%s -f %s -t %s > %s', - { owner: owner, repo: 'worker', from: worker_ref1, to: worker_ref2, output: worker_data }) - system(cmd) -else - logger.debug("Re-using:#{worker_data}") -end - -if ENV['NO_CACHE'] || !File.file?(pallets_data) - logger.debug(format('Fetching data for Pallets into %s', pallets_data)) - cmd = format('changelogerator %s/%s -f %s -t %s > %s', - { owner: owner, repo: 'pallets', from: pallets_ref1, to: pallets_ref2, output: pallets_data }) - system(cmd) -else - logger.debug("Re-using:#{pallets_data}") -end - -# Here we compose all the pieces together into one -# single big json file. -cmd = format('jq \ - --slurpfile pallets %s \ - --slurpfile worker %s \ - -n \'{ - pallets: $pallets[0], - worker: $worker[0], - }\' > context.json', pallets_data, worker_data) -system(cmd) - -cmd = format('tera --env --env-key env --include-path templates \ - --template templates/template.md.tera context.json > %s', output) -system(cmd) diff --git a/tee-worker/bitacross/scripts/changelog/digests/.gitignore b/tee-worker/bitacross/scripts/changelog/digests/.gitignore deleted file mode 100644 index a6c57f5fb2..0000000000 --- a/tee-worker/bitacross/scripts/changelog/digests/.gitignore +++ /dev/null @@ -1 +0,0 @@ -*.json diff --git a/tee-worker/bitacross/scripts/changelog/digests/.gitkeep b/tee-worker/bitacross/scripts/changelog/digests/.gitkeep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/tee-worker/bitacross/scripts/changelog/lib/changelog.rb b/tee-worker/bitacross/scripts/changelog/lib/changelog.rb deleted file mode 100644 index d7cf92e7d2..0000000000 --- a/tee-worker/bitacross/scripts/changelog/lib/changelog.rb +++ /dev/null @@ -1,38 +0,0 @@ -# frozen_string_literal: true - -# A Class to find Substrate references -class SubRef - require 'octokit' - require 'toml' - - attr_reader :client, :repository - - def initialize(github_repo) - @client = Octokit::Client.new( - access_token: ENV['GITHUB_TOKEN'] - ) - @repository = @client.repository(github_repo) - end - - # This function checks the Cargo.lock of a given - # Rust project, for a given package, and fetches - # the dependency git ref. - def get_dependency_reference(ref, package) - cargo = TOML::Parser.new( - Base64.decode64( - @client.contents( - @repository.full_name, - path: 'Cargo.lock', - query: { ref: ref.to_s } - ).content - ) - ).parsed - cargo['package'].find { |p| p['name'] == package }['source'].split('#').last - end - - # Get the git ref of the last release for the repo. - # repo is given in the form integritee-network/worker - def get_last_ref() - 'refs/tags/' + @client.latest_release(@repository.full_name).tag_name - end -end diff --git a/tee-worker/bitacross/scripts/changelog/templates/_free_notes.md.tera b/tee-worker/bitacross/scripts/changelog/templates/_free_notes.md.tera deleted file mode 100644 index c4a841a992..0000000000 --- a/tee-worker/bitacross/scripts/changelog/templates/_free_notes.md.tera +++ /dev/null @@ -1,10 +0,0 @@ - -{# This file uses the Markdown format with additional templating such as this comment. -#} -{# Such a comment will not show up in the rendered release notes. -#} -{# The content of this file (if any) will be inserted at the top of the release notes -#} -{# and generated for each new release candidate. -#} -{# Ensure you leave an empty line at both top and bottom of this file. -#} - - - - diff --git a/tee-worker/bitacross/scripts/changelog/templates/challenge_level.md.tera b/tee-worker/bitacross/scripts/changelog/templates/challenge_level.md.tera deleted file mode 100644 index c4a8934fd4..0000000000 --- a/tee-worker/bitacross/scripts/changelog/templates/challenge_level.md.tera +++ /dev/null @@ -1,37 +0,0 @@ -{%- import "change.md.tera" as m_c -%} - -{# This macro convert a merge challenge level into readable output #} -{%- macro challenge_level(e, changes) -%} - -{%- if e >= 5 -%} - {%- set level = "‼️ Breaking Changes" -%} - {%- set text = "This release contains **breaking changes**. Be sure to upgrade the affected interfaces." -%} -{%- elif e >= 3 -%} - {%- set level = "❗️ Attention" -%} - {%- set text = "This release contains some non-trivial updates. Be mindful when upgrading." -%} -{%- else -%} - {%- set level = "Trivial" -%} - {%- set text = "This release contains relatively small updates." -%} -{%- endif %} - - - - -{%- if level %} -{{level}}: {{text}} - -{% if e >= 3 %} -The changes motivating this challenge level are: -{% for pr in changes | sort(attribute="merged_at") -%} - {%- if pr.meta.E -%} - {%- if pr.meta.E.value == e %} -- {{ m_c::change(c=pr) }} - {%- endif -%} - {%- endif -%} -{%- endfor -%} -{%- else -%} - -{%- endif -%} -{%- endif -%} - -{%- endmacro level -%} diff --git a/tee-worker/bitacross/scripts/changelog/templates/change.md.tera b/tee-worker/bitacross/scripts/changelog/templates/change.md.tera deleted file mode 100644 index 25cc04edec..0000000000 --- a/tee-worker/bitacross/scripts/changelog/templates/change.md.tera +++ /dev/null @@ -1,42 +0,0 @@ -{# This macro shows ONE change #} -{%- macro change(c, cml="[C]", pal="[P]", wor="[W]") -%} - -{%- if c.meta.C and c.meta.C.value >= 7 -%} -{%- set prio = " ‼️ HIGH" -%} -{%- elif c.meta.C and c.meta.C.value >= 3 -%} -{%- set prio = " ❗️ Medium" -%} -{%- elif c.meta.C and c.meta.C.value < 3 -%} -{%- set prio = " Low" -%} -{%- else -%} -{%- set prio = "" -%} -{%- endif -%} - - -{%- if c.html_url is containing("worker") -%} -{%- set repo = wor -%} -{%- elif c.html_url is containing("pallets") -%} -{%- set repo = pal -%} -{%- else -%} -{%- set repo = " " -%} -{%- endif -%} - -{# For now don't show pallets or worker #} -{%- set repo = " " -%} - -{%- if c.meta.E and c.meta.E.value >= 7 -%} -{%- set challenge = " 💥 breaking changes " -%} -{%- elif c.meta.E and c.meta.E.value == 6 -%} -{%- set challenge = " ⚡ breaks parentchain interface " -%} -{%- elif c.meta.E and c.meta.E.value == 5 -%} -{%- set challenge = " 🔥 breaks public rpc api " -%} -{%- elif c.meta.E and c.meta.E.value >= 3 -%} -{%- set challenge = " 📢 attention required " -%} -{%- elif c.meta.E and c.meta.E.value < 3 -%} -{%- set challenge = " ✅ easy merge " -%} -{%- else -%} -{%- set challenge = "" -%} -{%- endif -%} - - -{{- repo }} {{ challenge }}[`#{{c.number}}`]({{c.html_url}}) {{- prio }} - {{ c.title | capitalize | truncate(length=120, end="…") }} -{%- endmacro change -%} \ No newline at end of file diff --git a/tee-worker/bitacross/scripts/changelog/templates/changes.md.tera b/tee-worker/bitacross/scripts/changelog/templates/changes.md.tera deleted file mode 100644 index 1dcb6ea978..0000000000 --- a/tee-worker/bitacross/scripts/changelog/templates/changes.md.tera +++ /dev/null @@ -1,23 +0,0 @@ -{# This include generates the section showing the changes #} -## Changes - -{# for not now printed until pallet is actually included #} -{# ### Legend #} - -{# - {{ WOR }} Worker #} -{# - {{ PAL }} Pallet #} - -{% include "changes_applibs.md.tera" %} - -{% include "changes_client.md.tera" %} - -{% include "changes_core.md.tera" %} - -{% include "changes_evm.md.tera" %} - -{% include "changes_offchain.md.tera" %} - -{% include "changes_sidechain.md.tera" %} - - -{% include "changes_misc.md.tera" %} diff --git a/tee-worker/bitacross/scripts/changelog/templates/changes_applibs.md.tera b/tee-worker/bitacross/scripts/changelog/templates/changes_applibs.md.tera deleted file mode 100644 index db393f764e..0000000000 --- a/tee-worker/bitacross/scripts/changelog/templates/changes_applibs.md.tera +++ /dev/null @@ -1,17 +0,0 @@ -{% import "change.md.tera" as m_c -%} -### App-Libs - -{#- The changes are sorted by merge date #} -{%- for pr in changes | sort(attribute="merged_at") %} - -{%- if pr.meta.B %} - {%- if pr.meta.B.value == 0 %} - {#- We skip silent ones -#} - {%- else -%} - - {%- if pr.meta.A.value == 2 %} -- {{ m_c::change(c=pr) }} - {%- endif -%} - {% endif -%} - {% endif -%} -{% endfor %} diff --git a/tee-worker/bitacross/scripts/changelog/templates/changes_client.md.tera b/tee-worker/bitacross/scripts/changelog/templates/changes_client.md.tera deleted file mode 100644 index 5e96861812..0000000000 --- a/tee-worker/bitacross/scripts/changelog/templates/changes_client.md.tera +++ /dev/null @@ -1,17 +0,0 @@ -{% import "change.md.tera" as m_c -%} -### Client - -{#- The changes are sorted by merge date #} -{%- for pr in changes | sort(attribute="merged_at") %} - -{%- if pr.meta.B %} - {%- if pr.meta.B.value == 0 %} - {#- We skip silent ones -#} - {%- else -%} - - {%- if pr.meta.A.value == 1 %} -- {{ m_c::change(c=pr) }} - {%- endif -%} - {% endif -%} - {% endif -%} -{% endfor %} diff --git a/tee-worker/bitacross/scripts/changelog/templates/changes_core.md.tera b/tee-worker/bitacross/scripts/changelog/templates/changes_core.md.tera deleted file mode 100644 index f88447b9e9..0000000000 --- a/tee-worker/bitacross/scripts/changelog/templates/changes_core.md.tera +++ /dev/null @@ -1,17 +0,0 @@ -{% import "change.md.tera" as m_c -%} -### Core - -{#- The changes are sorted by merge date #} -{%- for pr in changes | sort(attribute="merged_at") %} - -{%- if pr.meta.B %} - {%- if pr.meta.B.value == 0 %} - {#- We skip silent ones -#} - {%- else -%} - - {%- if pr.meta.A.value == 0 %} -- {{ m_c::change(c=pr) }} - {%- endif -%} - {% endif -%} - {% endif -%} -{% endfor %} diff --git a/tee-worker/bitacross/scripts/changelog/templates/changes_evm.md.tera b/tee-worker/bitacross/scripts/changelog/templates/changes_evm.md.tera deleted file mode 100644 index 92747435fd..0000000000 --- a/tee-worker/bitacross/scripts/changelog/templates/changes_evm.md.tera +++ /dev/null @@ -1,17 +0,0 @@ -{% import "change.md.tera" as m_c -%} -### EVM Feature - -{#- The changes are sorted by merge date #} -{%- for pr in changes | sort(attribute="merged_at") %} - -{%- if pr.meta.B %} - {%- if pr.meta.B.value == 0 %} - {#- We skip silent ones -#} - {%- else -%} - - {%- if pr.meta.A.value == 6 %} -- {{ m_c::change(c=pr) }} - {%- endif -%} - {% endif -%} - {% endif -%} -{% endfor %} diff --git a/tee-worker/bitacross/scripts/changelog/templates/changes_misc.md.tera b/tee-worker/bitacross/scripts/changelog/templates/changes_misc.md.tera deleted file mode 100644 index 1beb2efd91..0000000000 --- a/tee-worker/bitacross/scripts/changelog/templates/changes_misc.md.tera +++ /dev/null @@ -1,37 +0,0 @@ -{%- import "change.md.tera" as m_c -%} - -{%- set_global misc_count = 0 -%} -{#- First pass to count #} -{%- for pr in changes -%} - {%- if pr.meta.B %} - {%- if pr.meta.B.value == 0 -%} - {#- We skip silent ones -#} - {%- else -%} -{%- set_global misc_count = misc_count + 1 -%} - {% endif -%} - {% endif -%} -{% endfor -%} - -### Misc - -{% if misc_count > 10 %} -There are other misc. changes. You can expand the list below to view them all. -
Other misc. changes -{% endif -%} - -{#- The changes are sorted by merge date #} -{%- for pr in changes | sort(attribute="merged_at") %} - {%- if pr.meta.B %} - {%- if pr.meta.B.value == 0 %} - {#- We skip silent ones -#} - {%- else -%} - {%- if pr.meta.B.value >= 1 %} -- {{ m_c::change(c=pr) }} - {%- endif -%} - {% endif -%} - {% endif -%} -{% endfor %} - -{% if misc_count > 10 %} -
-{% endif -%} diff --git a/tee-worker/bitacross/scripts/changelog/templates/changes_offchain.md.tera b/tee-worker/bitacross/scripts/changelog/templates/changes_offchain.md.tera deleted file mode 100644 index d298752043..0000000000 --- a/tee-worker/bitacross/scripts/changelog/templates/changes_offchain.md.tera +++ /dev/null @@ -1,17 +0,0 @@ -{% import "change.md.tera" as m_c -%} -### Offchain - -{#- The changes are sorted by merge date #} -{%- for pr in changes | sort(attribute="merged_at") %} - -{%- if pr.meta.B %} - {%- if pr.meta.B.value == 0 %} - {#- We skip silent ones -#} - {%- else -%} - - {%- if pr.meta.A.value == 4 %} -- {{ m_c::change(c=pr) }} - {%- endif -%} - {% endif -%} - {% endif -%} -{% endfor %} diff --git a/tee-worker/bitacross/scripts/changelog/templates/changes_sidechain.md.tera b/tee-worker/bitacross/scripts/changelog/templates/changes_sidechain.md.tera deleted file mode 100644 index f953cfbcdf..0000000000 --- a/tee-worker/bitacross/scripts/changelog/templates/changes_sidechain.md.tera +++ /dev/null @@ -1,17 +0,0 @@ -{% import "change.md.tera" as m_c -%} -### Sidechain - -{#- The changes are sorted by merge date #} -{%- for pr in changes | sort(attribute="merged_at") %} - -{%- if pr.meta.B %} - {%- if pr.meta.B.value == 0 %} - {#- We skip silent ones -#} - {%- else -%} - - {%- if pr.meta.A.value == 3 %} -- {{ m_c::change(c=pr) }} - {%- endif -%} - {% endif -%} - {% endif -%} -{% endfor %} diff --git a/tee-worker/bitacross/scripts/changelog/templates/debug.md.tera b/tee-worker/bitacross/scripts/changelog/templates/debug.md.tera deleted file mode 100644 index 41f3702d7c..0000000000 --- a/tee-worker/bitacross/scripts/changelog/templates/debug.md.tera +++ /dev/null @@ -1,8 +0,0 @@ -{%- set to_ignore = changes | filter(attribute="meta.B.value", value=0) %} - - diff --git a/tee-worker/bitacross/scripts/changelog/templates/global_challenge_level.md.tera b/tee-worker/bitacross/scripts/changelog/templates/global_challenge_level.md.tera deleted file mode 100644 index d2108dce4d..0000000000 --- a/tee-worker/bitacross/scripts/changelog/templates/global_challenge_level.md.tera +++ /dev/null @@ -1,26 +0,0 @@ -{% import "challenge_level.md.tera" as m_p -%} -## Upgrade Challenge Level - -{%- set worker_prio = 0 -%} -{%- set pallet_prio = 0 -%} - -{# We fetch the various levels #} -{%- if worker.meta.E -%} -{%- set worker_level = worker.meta.E.max -%} -{%- else -%} -{%- set worker_level = 0 -%} -{%- endif -%} -{%- if pallet.meta.E -%} -{%- set pallet_level = pallet.meta.E.max -%} -{%- else -%} -{%- set pallet_level = 0 -%} -{%- endif -%} - -{# We compute the global level #} -{%- set global_level = worker_level -%} -{%- if pallet_level > global_level -%} -{%- set global_level = pallet_level -%} -{%- endif -%} - -{#- We show the result #} -{{ m_p::challenge_level(e=global_level, changes=changes) }} diff --git a/tee-worker/bitacross/scripts/changelog/templates/global_priority.md.tera b/tee-worker/bitacross/scripts/changelog/templates/global_priority.md.tera deleted file mode 100644 index 87a6d52aaf..0000000000 --- a/tee-worker/bitacross/scripts/changelog/templates/global_priority.md.tera +++ /dev/null @@ -1,27 +0,0 @@ -{% import "high_priority.md.tera" as m_p -%} -## Upgrade Priority - -{%- set worker_prio = 0 -%} -{%- set pallet_prio = 0 -%} - -{# We fetch the various priorities #} -{%- if worker.meta.C -%} -{%- set worker_prio = worker.meta.C.max -%} -{%- else -%} -{%- set worker_prio = 0 -%} -{%- endif -%} -{%- if pallet.meta.C -%} -{%- set pallet_prio = pallet.meta.C.max -%} -{%- else -%} -{%- set pallet_prio = 0 -%} -{%- endif -%} - -{# We compute the global priority #} -{%- set global_prio = worker_prio -%} -{%- if pallet_prio > global_prio -%} -{%- set global_prio = pallet_prio -%} -{%- endif -%} - - -{#- We show the result #} -{{ m_p::high_priority(p=global_prio, changes=changes) }} diff --git a/tee-worker/bitacross/scripts/changelog/templates/high_priority.md.tera b/tee-worker/bitacross/scripts/changelog/templates/high_priority.md.tera deleted file mode 100644 index 117d335efd..0000000000 --- a/tee-worker/bitacross/scripts/changelog/templates/high_priority.md.tera +++ /dev/null @@ -1,38 +0,0 @@ -{%- import "change.md.tera" as m_c -%} - -{# This macro convert a priority level into readable output #} -{%- macro high_priority(p, changes) -%} - -{%- if p >= 7 -%} - {%- set prio = "‼️ HIGH" -%} - {%- set text = "This is a **high priority** release and you must upgrade as as soon as possible." -%} -{%- elif p >= 3 -%} - {%- set prio = "❗️ Medium" -%} - {%- set text = "This is a medium priority release and you should upgrade in a timely manner." -%} -{%- else -%} - {%- set prio = "Low" -%} - {%- set text = "This is a low priority release and you may upgrade at your convenience." -%} -{%- endif %} - - - -{%- if prio %} -{{prio}}: {{text}} - -{% if p >= 3 %} -The changes motivating this priority level are: -{% for pr in changes | sort(attribute="merged_at") -%} - {%- if pr.meta.C -%} - {%- if pr.meta.C.value == p %} -- {{ m_c::change(c=pr) }} -{%- if pr.meta.B and pr.meta.B.value == 7 %} (RUNTIME) -{% endif %} - {%- endif -%} - {%- endif -%} -{%- endfor -%} -{%- else -%} - -{%- endif -%} -{%- endif -%} - -{%- endmacro priority -%} diff --git a/tee-worker/bitacross/scripts/changelog/templates/pre_release.md.tera b/tee-worker/bitacross/scripts/changelog/templates/pre_release.md.tera deleted file mode 100644 index 7d4ad42dd8..0000000000 --- a/tee-worker/bitacross/scripts/changelog/templates/pre_release.md.tera +++ /dev/null @@ -1,11 +0,0 @@ -{%- if env.PRE_RELEASE == "true" -%} -
⚠️ This is a pre-release - -**Release candidates** are **pre-releases** and may not be final. -Although they are reasonably tested, there may be additional changes or issues -before an official release is tagged. Use at your own discretion, and consider -only using final releases on critical production infrastructure. -
-{% else -%} - -{%- endif %} diff --git a/tee-worker/bitacross/scripts/changelog/templates/template.md.tera b/tee-worker/bitacross/scripts/changelog/templates/template.md.tera deleted file mode 100644 index 2c61f3d5a1..0000000000 --- a/tee-worker/bitacross/scripts/changelog/templates/template.md.tera +++ /dev/null @@ -1,33 +0,0 @@ -{# This is the entry point of the template -#} - -{% include "pre_release.md.tera" -%} - -{% if env.PRE_RELEASE == "true" -%} -This pre-release contains the changes from `{{ env.REF1 | replace(from="refs/tags/", to="") }}` to `{{ env.REF2 | -replace(from="refs/tags/", to="") }}`. -{%- else -%} -This release contains the changes from `{{ env.REF1 | replace(from="refs/tags/", to="") }}` to `{{ env.REF2 | -replace(from="refs/tags/", to="") }}`. -{% endif -%} - -{# -- For now no pallet changes included -- #} -{# {%- set changes = worker.changes | concat(with=pallet.changes) -%}##} -{%- set changes = worker.changes -%} -{%- include "debug.md.tera" -%} - -{%- set CML = "[C]" -%} -{%- set WOR = "[W]" -%} -{%- set PAL = "[P]" -%} - -{# -- Manual free notes section -- #} -{% include "_free_notes.md.tera" -%} - -{# -- Important automatic section -- #} -{% include "global_priority.md.tera" -%} - -{# -- Important automatic section -- #} -{% include "global_challenge_level.md.tera" -%} - -{# --------------------------------- #} - -{% include "changes.md.tera" -%} diff --git a/tee-worker/bitacross/scripts/init_env.sh b/tee-worker/bitacross/scripts/init_env.sh deleted file mode 100755 index 9b68a64b22..0000000000 --- a/tee-worker/bitacross/scripts/init_env.sh +++ /dev/null @@ -1,15 +0,0 @@ -#!/bin/bash - -# script that sets the correct environment variables to execute other scripts - -export SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )" -export PROJ_ROOT="$(dirname "$SCRIPT_DIR")" -export CLIENT_DIR="$PROJ_ROOT/cli" -export LOG_DIR="$PROJ_ROOT/log" -export CI_DIR="$PROJ_ROOT/ci" -export RUST_LOG=info,ws=warn,substrate_api_client=warn,ac_node_api=warn - -echo "Set environment variables:" -echo " BASH_SCRIPT_DIR: $SCRIPT_DIR" -echo " PROJ_ROOT: $PROJ_ROOT" -echo " CLIENT_DIR: $CLIENT_DIR" \ No newline at end of file diff --git a/tee-worker/bitacross/scripts/launch.sh b/tee-worker/bitacross/scripts/launch.sh deleted file mode 100755 index f91405f3d3..0000000000 --- a/tee-worker/bitacross/scripts/launch.sh +++ /dev/null @@ -1,90 +0,0 @@ -#!/usr/bin/env bash - -set -euo pipefail - -PARACHAIN="paseo" -ROOTDIR=$(git rev-parse --show-toplevel) -ROOTDIR="${ROOTDIR}/tee-worker" - -function usage() { - echo "Usage: $0 " - echo "" - echo " All mode apply to ${PARACHAIN} context." - echo " dev: start worker(s) together with local ${PARACHAIN} for development" - echo " staging: start worker(s) sync with staging ${PARACHAIN} on tee-staging server" - echo " prod: start worker(s) sync with production ${PARACHAIN} on polkadot.js" - echo " mock: start worker(s) together with local ${PARACHAIN} for development" -} - -function start_local_parachain() { - cd ${ROOTDIR} - echo "------------------------------------------------------------" - echo "Start local parachain: ${PARACHAIN} ..." - # TODO: only `paseo` is supported for the moment. And it's hard-coded inside `start_parachain.sh` - ./../local-setup/start_parachain.sh - if [ $? -ne 0 ]; then - exit 1 - fi -} - -function start_worker_for_dev() { - start_local_parachain - cd ${ROOTDIR} - worker_num=2 - echo "------------------------------------------------------------" - echo "Start ${worker_num} workers with dev ${PARACHAIN} ..." - ./scripts/launch_local_worker.sh -c true -n ${worker_num} -m "dev" -} - -function start_worker_for_staging() { - cd ${ROOTDIR} - worker_num=2 - # staging_parachain_url - url="wss://tee-staging.litentry.io" - # staging_parachain_port - port=443 - echo "------------------------------------------------------------" - echo "Start ${worker_num} workers with staging ${PARACHAIN} ..." - ./scripts/launch_local_worker.sh -c true -n ${worker_num} -u ${url} -p ${port} -m "staging" -} - -function start_worker_for_prod() { - cd ${ROOTDIR} - worker_num=2 - # production_parachain_url - url="wss://rpc.${PARACHAIN}-parachain-sg.litentry.io" - # production_parachain_port - port=443 - echo "------------------------------------------------------------" - echo "Start ${worker_num} workers with production ${PARACHAIN} ..." - ./scripts/launch_local_worker.sh -c true -n ${worker_num} -u ${url} -p ${port} -m "prod" -} - -function start_worker_for_mock() { - start_local_parachain - cd ${ROOTDIR} - worker_num=2 - echo "------------------------------------------------------------" - echo "Start ${worker_num} workers with local ${PARACHAIN} ..." - ./scripts/launch_local_worker.sh -c true -n ${worker_num} -m "mock" -} - - -[ $# -ne 1 ] && (usage; exit 1) -MODE=$1 - -if [ "$MODE" = "dev" ] || [ "$MODE" = "staging" ] || [ "$MODE" = "prod" ] || [ "$MODE" = "mock" ]; then - echo "Launch in $MODE mode" - start_worker_for_$MODE -else - echo "Unknow mode: $MODE" - usage; exit 1 -fi - -echo "Done" - - - - - - diff --git a/tee-worker/bitacross/scripts/launch_local_worker.sh b/tee-worker/bitacross/scripts/launch_local_worker.sh deleted file mode 100755 index b1dfe788f6..0000000000 --- a/tee-worker/bitacross/scripts/launch_local_worker.sh +++ /dev/null @@ -1,138 +0,0 @@ -#!/usr/bin/env bash - -# TODO: Sanity check of parameters -while getopts ":c:n:u:p:m:" opt; do - case $opt in - c) - cleanup_flag=$OPTARG - ;; - n) - worker_num=$OPTARG - ;; - u) - node_url=$OPTARG - ;; - p) - node_port=$OPTARG - ;; - m) - mode=$OPTARG - ;; - esac -done - -CLEANUP=${cleanup_flag:-true} -WORKER_NUM=${worker_num:-1} - -NODE_URL=${node_url:-"ws://127.0.0.1"} # "ws://host.docker.internal" -NODE_PORT=${node_port:-"9944"} # "9946" - -# Fixed values: -ENCLAVE_ENDPOINT="localhost" -MU_RA_PORT="3443" -UNTRUSTED_HTTP_PORT="4545" -TRUSTED_WORKER_PORT="2000" -UNTRUSTED_WORKER_PORT="3000" - -F_CLEAN="" -FSUBCMD_DEV="" -FSUBCMD_REQ_STATE="" - -WAIT_INTERVAL_SECONDS=10 -WAIT_ROUNDS=20 - -if [ "${CLEANUP}" = 'true' ]; then - F_CLEAN="--clean-reset" - FSUBCMD_DEV="--dev" -fi - -function wait_worker_is_initialized() -{ - for index in $(seq 1 $WAIT_ROUNDS); do - state=$(curl -s http://localhost:$1/is_initialized) - if [ "$state" == "I am initialized." ]; then - echo "Initialization successful: $state" - return - else - echo "sleep $WAIT_INTERVAL_SECONDS" - sleep $WAIT_INTERVAL_SECONDS - fi - done - echo - echo "Worker initialization failed" - exit 1 -} - -echo "Number of WORKER_NUM: ${WORKER_NUM}" -############################################################################## -### Start execution -############################################################################## - -ROOTDIR=$(git rev-parse --show-toplevel) -ROOTDIR="${ROOTDIR}/tee-worker" -RUST_LOG="info,litentry_worker=debug,ws=warn,sp_io=error,substrate_api_client=warn,\ -itc_parentchain_light_client=info,\ -jsonrpsee_ws_client=warn,jsonrpsee_ws_server=warn,enclave_runtime=debug,ita_stf=debug,\ -its_rpc_handler=warn,itc_rpc_client=warn,its_consensus_common=debug,its_state=warn,\ -its_consensus_aura=warn,aura*=warn,its_consensus_slots=warn,\ -itp_attestation_handler=debug,http_req=debug,itc_rest_client=debug,\ -itp_top_pool=debug,itc_parentchain_indirect_calls_executor=debug" - -# Create the log directory, in case not existed. -mkdir -p ${ROOTDIR}/log - -for ((i = 0; i < ${WORKER_NUM}; i++)); do - worker_name="worker${i}" - echo "" - echo "--------------------setup worker(${worker_name})----------------------------------------" - - if ((i > 0)); then - FSUBCMD_REQ_STATE="--request-state" - fi - - if [ "${CLEANUP}" = 'true' ]; then - echo "clear dir: ${ROOTDIR}/tmp/${worker_name}" - rm -rf "${ROOTDIR}"/tmp/"${worker_name}" - fi - mkdir -p "${ROOTDIR}"/tmp/"${worker_name}" - for Item in 'enclave.signed.so' 'key.txt' 'spid.txt' 'litentry-worker' 'bitacross-cli'; do - cp "${ROOTDIR}/bin/${Item}" "${ROOTDIR}"/tmp/"${worker_name}" - done - - cd "${ROOTDIR}"/tmp/${worker_name} || exit - echo "enter ${ROOTDIR}/tmp/${worker_name}" - - mu_ra_port=$((${MU_RA_PORT} + i)) - untrusted_http_port=$((${UNTRUSTED_HTTP_PORT} + i)) - trusted_worker_port=$((${TRUSTED_WORKER_PORT} + i)) - untrusted_worker_port=$((${UNTRUSTED_WORKER_PORT} + i)) - echo "${worker_name} ports: - mu-ra-port: ${mu_ra_port} - untrusted-http-port: ${untrusted_http_port} - trusted-worker-port: ${trusted_worker_port} - untrusted-worker-port: ${untrusted_worker_port} - " - - launch_command="RUST_LOG=${RUST_LOG} ./litentry-worker ${F_CLEAN} --ws-external \ ---mu-ra-external-address ${ENCLAVE_ENDPOINT} \ ---mu-ra-port ${mu_ra_port} \ ---node-port ${NODE_PORT} \ ---node-url ${NODE_URL} \ ---trusted-external-address wss://${ENCLAVE_ENDPOINT} \ ---trusted-worker-port ${trusted_worker_port} \ ---untrusted-external-address ws://${ENCLAVE_ENDPOINT} \ ---untrusted-http-port ${untrusted_http_port} \ ---untrusted-worker-port ${untrusted_worker_port} \ -run --skip-ra ${FSUBCMD_DEV} ${FSUBCMD_REQ_STATE}" - - echo "${worker_name} command: ${launch_command}" - eval "${launch_command}" > "${ROOTDIR}"/log/${worker_name}.log 2>&1 & - echo "${worker_name}(litentry-worker) started successfully. log: ${ROOTDIR}/log/${worker_name}.log" - - if ((${WORKER_NUM} > 0)); then - wait_worker_is_initialized ${untrusted_http_port} - fi -done - -echo "" -echo "--- Setup work(s) done ---" diff --git a/tee-worker/bitacross/scripts/litentry/release/ReadMe.md b/tee-worker/bitacross/scripts/litentry/release/ReadMe.md deleted file mode 100644 index 3faea84187..0000000000 --- a/tee-worker/bitacross/scripts/litentry/release/ReadMe.md +++ /dev/null @@ -1,106 +0,0 @@ - -# Release package - - -## Step 0: Preparation - -This package is generated from [litentry-parachain](https://github.com/litentry/litentry-parachain) -From the root folder ~/litentry-parachain/tee-worker/: -``` -make release-pkg -``` -A release package will be generated, within which there are: - -- enclave.sign.so -- litentry-worker -- config.json.eg -- prepare.sh - -
- -## Step 1: Deploy on production - -Before starting the workers, please make sure the target parachain is already up and accessable. As well as the following directory/files: - -| Name | Value | Comment | -|-----|------|---| -| WORKER_DIR | /opt/worker | Working directory of workers | -| CONFIG_DIR | /opt/configs | Config directory which contains the following 4 secret files | -| -| CONFIG | config.json | Configs for twitter/discord/data provider/etc. url/keys. Take reference from config.json.eg | -| ACCOUNT | account.json | Substrate account exported json file | -| INTEL_KEY | key_production.txt | Intel SGX production key. Need to apply from Intel | -| INTEL_SPI | spid_production.txt | Intel SGX production spid. Need to apply from Intel | - -
- -1. Extract the release package to one target location. Worker will be executed from there. Then execute `prepare.sh`: - ``` - ./prepare.sh - ``` - This script will generate out `MRENCLAVE` hex value (mrenclave.txt) and `Enclave Account` info (account.txt). They will be used later by ts scripts to setup enclave account. -
- -2. Startup options. - - The service will start up like this example: - ``` - RUST_LOG=info,litentry_worker=debug,ws=warn,sp_io=error,substrate_api_client=warn,itc_parentchain_light_client=info,jsonrpsee_ws_client=warn,jsonrpsee_ws_server=warn,enclave_runtime=debug,ita_stf=debug,its_rpc_handler=warn,itc_rpc_client=warn,its_consensus_common=debug,its_state=warn,its_consensus_aura=warn,aura*=warn,its_consensus_slots=warn,itp_attestation_handler=debug,http_req=debug,lc_mock_server=warn,itc_rest_client=debug,lc_credentials=debug,lc_identity_verification=debug,lc_stf_task_receiver=debug,lc_stf_task_sender=debug,lc_data_providers=debug,itp_top_pool=debug,itc_parentchain_indirect_calls_executor=debug ./litentry-worker --clean-reset --ws-external --mu-ra-external-address localhost --mu-ra-port 3443 --node-port 9944 --node-url ws://127.0.0.1 --trusted-external-address wss://localhost --trusted-worker-port 2000 --untrusted-external-address ws://localhost --untrusted-http-port 4545 --untrusted-worker-port 3000 run --skip-ra --dev - ``` - The first part is RUST_LOG info. In production env, most of them will be disabled. Or `RUST_LOG=info` is enough. - - Starting from `./litentry-worker`, the following is the real startup options: - - ``` - USAGE: - litentry-worker [FLAGS] [OPTIONS] - - FLAGS: - -c, --clean-reset Cleans and purges any previous state and key files and generates them anew before starting. - --enable-metrics Enable the metrics HTTP server to serve metrics - --help Prints help information - -V, --version Prints version information - --ws-external Set this flag in case the worker should listen to external requests. - - OPTIONS: - -i, --metrics-port - Set the port on which the metrics are served. [default: 8787] - - -M, --mu-ra-external-address - Set the mutual remote attestation worker address to be retrieved by a trusted rpc call. If no port is given, the same as in `mu-ra-port` will be used. - -r, --mu-ra-port - Set the websocket port to listen for mu-ra requests [default: 3443] - - -p, --node-port - Set the websocket port to listen for substrate events [default: 9944] - - -u, --node-url - Set the node server protocol and IP address [default: ws://127.0.0.1] - - -T, --trusted-external-address - Set the trusted worker address to be advertised on the parentchain. If no port is given, the same as in - `trusted-worker-port` will be used. - -P, --trusted-worker-port - Set the trusted websocket port of the worker, running directly in the enclave. [default: 2000] - - -U, --untrusted-external-address - Set the untrusted worker address to be retrieved by a trusted rpc call. If no port is given, the same as in - `untrusted-worker-port` will be used. - -h, --untrusted-http-port Set the port for the untrusted HTTP server - -w, --untrusted-worker-port - Set the untrusted websocket port of the worker [default: 2001] - - SUBCOMMANDS: - dump-ra Perform RA and dump cert to disk - help Prints this message or the help of the given subcommand(s) - init-shard Initialize new shard (do this only if you run the first worker for that shard). if shard is not - specified, the MRENCLAVE is used instead - migrate-shard Migrate shard - mrenclave Dump mrenclave to stdout. base58 encoded. - request-state join a shard by requesting key provisioning from another worker - run Start the litentry-worker - shielding-key Get the public RSA3072 key from the TEE to be used to encrypt requests - signing-key Get the public ed25519 key the TEE uses to sign messages and extrinsics - test Run tests involving the enclave - ``` - diff --git a/tee-worker/bitacross/scripts/litentry/release/build.sh b/tee-worker/bitacross/scripts/litentry/release/build.sh deleted file mode 100755 index aafd70210d..0000000000 --- a/tee-worker/bitacross/scripts/litentry/release/build.sh +++ /dev/null @@ -1,50 +0,0 @@ -#!/bin/bash - -# this script builds the release artefacts for TEE client and/or the enclave - -set -euo pipefail - -function usage() { - echo "Usage: $0 if-build-worker if-build-enclave" - echo "Example:" - echo " $0 true true" -} - -[ $# -ne 2 ] && (usage; exit 1) - -echo "build worker: $1" -echo "build enclave: $2" - -ROOTDIR=$(git rev-parse --show-toplevel) -WORKERDIR="$ROOTDIR/tee-worker" - -# hardcoded sgx signing key, adjust it accordingly if you call the script manually -SGX_COMMERCIAL_KEY="/opt/enclave_release/sgx_sign_key.pem" - -if [ ! -f "$SGX_COMMERCIAL_KEY" ]; then - echo "Cannot find SGX sign key under $SGX_COMMERCIAL_KEY" - exit 1 -fi - -DESTDIR="$WORKERDIR/enclave_release" -[ -d "$DESTDIR" ] && rm -rf "$DESTDIR" -mkdir -p "$DESTDIR" - -cd "$WORKERDIR" - -make clean - -export SGX_PRODUCTION=1 -export SGX_COMMERCIAL_KEY="$SGX_COMMERCIAL_KEY" -if [ "$1" = "true" ]; then - make service - cp bin/litentry-worker "$DESTDIR" -fi -if [ "$2" = "true" ]; then - make bin/enclave.signed.so - cp bin/enclave.signed.so "$DESTDIR" - make mrenclave 2>&1 | grep MRENCLAVE | awk '{print $2}' > "$DESTDIR/mrenclave.txt" -fi - -echo "Build tee done" -ls -l "$DESTDIR" diff --git a/tee-worker/bitacross/scripts/litentry/release/deploy.sh b/tee-worker/bitacross/scripts/litentry/release/deploy.sh deleted file mode 100755 index efd6b329c4..0000000000 --- a/tee-worker/bitacross/scripts/litentry/release/deploy.sh +++ /dev/null @@ -1,559 +0,0 @@ -#!/bin/bash - -set -eo pipefail - -# This script is used to perform actions on the target host, including: -# - generate: generate the systemd service files from the template -# - restart: restart the parachain, or the worker, or both -# - upgrade-worker: uprade the worker0 to the rev in local repo -# -# TODO: -# the combinations of flags are not yet well verified/organised, especially the following: -# --only-worker -# --build -# --discard - -# ------------------------------ -# path setting -# ------------------------------ - -ROOTDIR=$(git rev-parse --show-toplevel) -BASEDIR=/opt/litentry -PARACHAIN_BASEDIR="$BASEDIR/parachain" -WORKER_BASEDIR="$BASEDIR/worker" -BACKUP_BASEDIR="$BASEDIR/backup" -LOG_BACKUP_BASEDIR="$BACKUP_BASEDIR/log" -WORKER_BACKUP_BASEDIR="$BACKUP_BASEDIR/worker" -RELAYCHAIN_ALICE_BASEDIR="$PARACHAIN_BASEDIR/relay-alice" -RELAYCHAIN_BOB_BASEDIR="$PARACHAIN_BASEDIR/relay-bob" -PARACHAIN_ALICE_BASEDIR="$PARACHAIN_BASEDIR/para-alice" - -# ------------------------------ -# default arg setting -# ------------------------------ - -BUILD=false -DISCARD=false -WORKER_CONFIG= -CHAIN=paseo -ONLY_WORKER=false -PARACHAIN_HOST=localhost -PARACHAIN_PORT=9944 -DOCKER_IMAGE=litentry/litentry-parachain:tee-prod -COPY_FROM_DOCKER=false -PRODUCTION=false -ACTION= - -# ------------------------------ -# Some global setting -# ------------------------------ - -WORKER_COUNT= -PARACHAIN_ID= -OLD_MRENCLAVE= -NEW_MRENCLAVE= -OLD_SHARD= -LATEST_FINALIZED_BLOCK= - -SGX_SDK=/opt/intel/sgxsdk -SGX_ENCLAVE_SIGNER=$SGX_SDK/bin/x64/sgx_sign - -# ------------------------------ -# main() -# ------------------------------ - -function main { - # 0/ check if $USER has sudo - if sudo -l -U $USER 2>/dev/null | grep -q 'may run the following'; then - source "$SGX_SDK/environment" - else - echo "$USER doesn't have sudo permission" - exit 1 - fi - - # 1/ create folders if missing - sudo mkdir -p "$BASEDIR" - sudo chown $USER:$GROUPS "$BASEDIR" - for d in "$LOG_BACKUP_BASEDIR" "$WORKER_BACKUP_BASEDIR" "$RELAYCHAIN_ALICE_BASEDIR" "$RELAYCHAIN_BOB_BASEDIR" \ - "$PARACHAIN_ALICE_BASEDIR" "$WORKER_BASEDIR"; do - mkdir -p "$d" - done - - # 2/ parse command lines - echo "Parsing command line ..." - while [ $# -gt 0 ]; do - case "$1" in - -h|--help) - display_help - exit 0 - ;; - -b|--build) - BUILD=true - shift - ;; - -d|--discard) - DISCARD=true - shift - ;; - -c|--config) - WORKER_CONFIG="$(realpath -s $2)" - shift 2 - ;; - -a|--only-worker) - ONLY_WORKER=true - shift - ;; - -x|--chain) - CHAIN="$2" - shift 2 - ;; - -p|--parachain-port) - PARACHAIN_PORT="$2" - shift 2 - ;; - -z|--parachain-host) - PARACHAIN_HOST="$2" - shift 2 - ;; - -v|--copy-from-docker) - COPY_FROM_DOCKER=true - DOCKER_IMAGE="$2" - shift 2 - ;; - --prod) - PRODUCTION=true - shift - ;; - generate|restart|upgrade-worker) - ACTION="$1" - shift - ;; - *) - echo "Error: unknown option or subcommand $1" - display_help - exit 1 - ;; - esac - done - - # 3/ sanity checks - if [ ! -f "$WORKER_CONFIG" ]; then - echo "Worker config not found: $WORKER_CONFIG" - exit 1 - fi - - WORKER_COUNT=$(cat "$WORKER_CONFIG" | jq '.workers | length') - echo "Worker count: $WORKER_COUNT" - - # TODO: check flags conflict, e.g. - # - having `--discard` together with `upgrade-worker` doesn't make sense - # - `upgrade-worker` should ignore the `--only-worker` flag - - # 4/ main business logic - case "$ACTION" in - generate) - backup_services - generate_services - exit - ;; - restart) - backup_logs - backup_workers - stop_services - prune - build - setup_working_dir - if [ "$ONLY_WORKER" = true ]; then - remove_clean_reset - fi - restart_services - exit - ;; - upgrade-worker) - # build the new worker, the code must be under $ROOTDIR/tee-worker already - build_worker - # update the schedule - set_scheduled_enclave - - # wait until sidechain stalls - wait_for_sidechain - backup_workers - stop_worker_services - get_old_mrenclave - # TODO: actually we only need the copy-up - setup_working_dir - migrate_shard - remove_clean_reset - restart_services - exit - ;; - *) - echo "Unknown action: $ACTION" - exit 1 ;; - esac -} - -# ------------------------------ -# helper functions -# ------------------------------ - -function print_divider { - echo "------------------------------------------------------------" -} - -function display_help { - echo "usage: ./deploy.sh [options]" - echo "" - echo "subcommands:" - echo " generate Generate the parachain and worker systemd files" - echo " restart Restart the services" - echo " upgrade-worker Upgrade the worker" - echo "" - echo "options:" - echo " -h, --help Display this help message and exit" - echo " -b, --build Build the parachain and worker binaries (default: false)" - echo " -d, --discard Clean the existing state for parachain and worker (default: false)" - echo " -c, --config Config file for the worker" - echo " -a, --only-worker Start only the worker (default: false)" - echo " -x, --chain Chain type for launching the parachain network (default: paseo)" - echo " -h, --parachain-host Parachain ws URL (default: localhost)" - echo " -p, --parachain-port Parachain ws port (default: 9944)" - echo " -v, --copy-from-docker Copy the parachain binary from a docker image (default: litentry/litentry-parachain:tee-prod)" - echo " --prod Use a prod configuration to build and run the worker (default: false)" - echo "" - echo "examples:" - echo " ./deploy.sh generate --config tmp.json" - echo " ./deploy.sh restart --config tmp.json --discard --build" - echo " ./deploy.sh restart --config tmp.json --only-worker" - echo " ./deploy.sh upgrade-worker --config tmp.json --only-worker" - echo "" - echo "notes:" - echo " - This script requires an OS that supports systemd." - echo " - It is mandatory to provide a JSON config file for the worker." - echo " - jq is required to be installed on the system " - echo "" - echo "For more information or assistance, please contact Litentry parachain team." -} - -# TODO: in fact, this function only backs up the parachain logs -# maybe we want to remove it as it's not so critical anyway -function backup_logs { - echo "Backing up logs ..." - now=$(date +"%Y%m%d-%H%M%S") - outdir="$LOG_BACKUP_BASEDIR/log-$now" - mkdir -p "$outdir" - cp "$PARACHAIN_BASEDIR"/*.log "$outdir" || true - echo "Logs backed up into $outdir" -} - -function backup_workers { - echo "Backing up workers ..." - now=$(date +"%Y%m%d-%H%M%S") - cd "$WORKER_BASEDIR" || exit - for i in $(ls -d * 2>/dev/null); do - outdir="$WORKER_BACKUP_BASEDIR/$i-$now" - cp -rf "$i" "$outdir" - echo "Worker backed up into $outdir" - done -} - -function backup_services { - echo "Backing up services ..." - now=$(date +"%Y%m%d-%H%M%S") - cd /etc/systemd/system || exit - outdir="$WORKER_BACKUP_BASEDIR/service-$now" - mkdir -p "$outdir" - for f in para-alice.service relay-alice.service relay-bob.service $(ls worker*.service 2>/dev/null); do - cp "$f" "$outdir" || true - done -} - -function prune { - if [ "$DISCARD" = true ]; then - echo "Pruning the existing state ..." - rm -rf "$PARACHAIN_BASEDIR"/* - rm -rf "$WORKER_BASEDIR"/* - fi -} - -function generate_services { - echo "Generating systemd service files ..." - cd "$ROOTDIR/tee-worker/scripts/litentry/release" - cp template/* . - sed -i "s/CHAIN/$CHAIN/g" *.service - sed -i "s/USER/$USER/g" *.service - for ((i = 0; i < WORKER_COUNT; i++)); do - cp worker.service worker$i.service - sed -i "s/NUMBER/$i/g" worker$i.service - # populate args - flags=$(cat "$WORKER_CONFIG" | jq -r ".workers[$i].flags[]") - subcommand_flags=$(cat "$WORKER_CONFIG" | jq -r ".workers[$i].subcommand_flags[]") - args= - for flag in $flags; do - args+=" $flag" - done - args+=" run" - for subcommand_flag in $subcommand_flags; do - args+=" $subcommand_flag" - done - sed -i "s;ARGS;$args;" worker$i.service - done - rm worker.service - sudo cp *.service -f /etc/systemd/system/ - rm *.service - sudo systemctl daemon-reload - echo "Done, please check files under /etc/systemd/system/" - echo "Restart the services to take effect" -} - -function build_worker { - echo "Building worker ..." - cd $ROOTDIR/tee-worker/ || exit - if [ "$PRODUCTION" = true ]; then - # we will get an error if SGX_COMMERCIAL_KEY is not set for prod - SGX_PRODUCTION=1 make - else - # use SW mode for dev - SGX_MODE=SW make - fi -} - -# TODO: take github rev into consideration -function build { - if [ "$BUILD" = true ]; then - echo "Building the parachain and worker binaries ..." - - # download polkadot - echo "Downloading polkadot binary ..." - - for f in polkadot-execute-worker polkadot-prepare-worker polkadot; do - url="https://github.com/paritytech/polkadot-sdk/releases/download/polkadot-v1.1.0/$f" - polkadot_bin="$PARACHAIN_BASEDIR/$f" - wget -O "$polkadot_bin" -q "$url" - chmod a+x "$polkadot_bin" - if [ ! -s "$polkadot_bin" ]; then - echo "$polkadot_bin is 0 bytes, download URL: $url" && exit 1 - fi - done - - if ! "$polkadot_bin" --version &> /dev/null; then - echo "Cannot execute $polkadot_bin, wrong executable?" && exit 1 - fi - - # pull or build parachain - if [ "$COPY_FROM_DOCKER" = true ]; then - echo "Pulling binary from $DOCKER_IMAGE ..." - docker pull "$DOCKER_IMAGE" - docker cp "$(docker create --rm $DOCKER_IMAGE):/usr/local/bin/litentry-collator" "$PARACHAIN_BASEDIR" - else - echo "Building parachain binary ..." - cd "$ROOTDIR" || exit - if [ "$PRODUCTION" = true ]; then - cargo build --locked --profile production - else - pwd - make build-node - fi - cp "$ROOTDIR/target/release/litentry-collator" "$PARACHAIN_BASEDIR" - fi - chmod a+x "$PARACHAIN_BASEDIR/litentry-collator" - fi -} - -function restart_services { - sudo systemctl daemon-reload - if [ "$ONLY_WORKER" = false ]; then - echo "Restarting parachain services ..." - - cd "$PARACHAIN_BASEDIR" || exit - ./polkadot build-spec --chain rococo-local --disable-default-bootnode --raw > rococo-local-chain-spec.json - ./litentry-collator export-genesis-state --chain $CHAIN-dev > genesis-state - ./litentry-collator export-genesis-wasm --chain $CHAIN-dev > genesis-wasm - - sudo systemctl restart relay-alice.service - sleep 5 - sudo systemctl restart relay-bob.service - sleep 5 - sudo systemctl restart para-alice.service - sleep 5 - register_parachain - fi - - echo "Restarting worker services ..." - for ((i = 0; i < WORKER_COUNT; i++)); do - sudo systemctl restart "worker$i.service" - sleep 5 - done - echo "Done" -} - -function stop_worker_services { - echo "Stopping worker services ..." - for ((i = 0; i < WORKER_COUNT; i++)); do - sudo systemctl stop "worker$i.service" - sleep 5 - done -} - -function stop_parachain_services { - echo "Stopping parachain services ..." - sudo systemctl stop para-alice.service relay-alice.service relay-bob.service -} - -function stop_services { - stop_worker_services - - # TODO: it means we can't stop parachain service alone - # this needs to be done directly via `systemctl` - if [ "$ONLY_WORKER" = false ]; then - stop_parachain_services - fi -} - -function register_parachain { - echo "Register parathread now ..." - cd "$ROOTDIR" || exit - export PARACHAIN_ID=$(grep -i "${CHAIN}_para_id" primitives/core/src/lib.rs | sed 's/.* = //;s/\;.*//') - cd "$ROOTDIR/ts-tests" || exit - if [[ -z "$NODE_ENV" ]]; then - echo "NODE_ENV=ci" > .env - else - echo "NODE_ENV=$NODE_ENV" > .env - fi - # The genesis state path file needs to be updated as it is hardcoded to be /tmp/parachain_dev - jq --arg genesis_state "$PARACHAIN_BASEDIR/genesis-state" --arg genesis_wasm "$PARACHAIN_BASEDIR/genesis-wasm" '.genesis_state_path = $genesis_state | .genesis_wasm_path = $genesis_wasm' config.ci.json > config.ci.json.1 - mv config.ci.json.1 config.ci.json - pnpm install - pnpm run register-parathread 2>&1 | tee "$PARACHAIN_BASEDIR/register-parathread.log" - print_divider - - echo "Upgrade parathread to parachain now ..." - # Wait for 90s to allow onboarding finish, after that we do the upgrade - sleep 90 - pnpm run upgrade-parathread 2>&1 | tee "$PARACHAIN_BASEDIR/upgrade-parathread.log" - print_divider - - echo "done. please check $PARACHAIN_BASEDIR for generated files if need" - print_divider - git restore config.ci.json -} - -function setup_working_dir { - echo "Setting up working dir ..." - cd "$ROOTDIR/tee-worker/bin" || exit - - if [ "$PRODUCTION" = false ]; then - for f in 'key.txt' 'spid.txt'; do - [ -f "$f" ] || touch "$f" - done - fi - - for ((i = 0; i < WORKER_COUNT; i++)); do - worker_dir="$WORKER_BASEDIR/w$i" - mkdir -p "$worker_dir" - for f in 'key.txt' 'spid.txt' 'enclave.signed.so' 'litentry-worker'; do - [ -f "$f" ] && cp -f "$f" "$worker_dir" - done - - cd "$worker_dir" - [ -f light_client_db.bin/db.bin.backup ] && cp -f light_client_db.bin/db.bin.backup light_client_db.bin/db.bin - - enclave_account=$(./litentry-worker signing-key | grep -oP '^Enclave account: \K.*$$') - - if [ "$PRODUCTION" = true ]; then - echo "Transferring balance to the enclave account $enclave_account ..." - cd $ROOTDIR/scripts/ts-utils/ || exit - pnpm install - pnpm exec ts-node transfer.ts $enclave_account - fi - done -} - -function get_old_mrenclave { - cd "$WORKER_BASEDIR/w0" || exit - OLD_SHARD=$(./litentry-worker mrenclave) - $SGX_ENCLAVE_SIGNER dump -enclave ./enclave.signed.so -dumpfile df.out - OLD_MRENCLAVE=$($ROOTDIR/tee-worker/extract_identity < df.out | awk '{print $2}') - rm df.out - echo "old shard: $OLD_SHARD" - echo "old mrenclave: $OLD_MRENCLAVE" -} - -function set_scheduled_enclave { - echo "Setting scheduled enclave ..." - cd $ROOTDIR/tee-worker || exit - NEW_MRENCLAVE=$(make mrenclave 2>&1 | grep MRENCLAVE | awk '{print $2}') - echo "new mrenclave: $NEW_MRENCLAVE" - - latest_sidechain_block - - echo "Setting up the new worker on chain ..." - cd $ROOTDIR/ts-tests/ || exit - pnpm install - pnpm run setup-enclave $NEW_MRENCLAVE $SCHEDULED_UPDATE_BLOCK -} - -function wait_for_sidechain { - echo "Waiting for sidechain to reach block $SCHEDULED_UPDATE_BLOCK ..." - found=false - for _ in $(seq 1 30); do - sleep 20 - block_number=$(grep -F 'Enclave produced sidechain blocks' $WORKER_BASEDIR/w0/worker.log | tail -n 1 | sed 's/.*\[//;s/]//') - echo "current sidechain block: $block_number" - if [ $((block_number+1)) -eq $SCHEDULED_UPDATE_BLOCK ]; then - echo "we should stall soon ..." - fi - if tail -n 50 $WORKER_BASEDIR/w0/worker.log | grep -q "Skipping sidechain block $SCHEDULED_UPDATE_BLOCK due to mismatch MRENCLAVE"; then - echo "we reach $SCHEDULED_UPDATE_BLOCK now" - found=true - break - fi - done - if [ $found = false ]; then - echo "not reached, timeout" - exit 1 - fi -} - -function migrate_shard { - echo "Migrating shards for workers ..." - for ((i = 0; i < WORKER_COUNT; i++)); do - cd "$WORKER_BASEDIR/w$i" || exit - echo "old MRENCLAVE: $OLD_MRENCLAVE" - echo "new MRENCLAVE: $NEW_MRENCLAVE" - ./litentry-worker migrate-shard --old-shard $OLD_MRENCLAVE --new-shard $NEW_MRENCLAVE - - cd shards || exit - rm -rf $OLD_SHARD - done - echo "Done" -} - -function remove_clean_reset { - echo "Removing --clean-reset flag for workers ..." - for ((i = 0; i < WORKER_COUNT; i++)); do - sudo sed -i 's/--clean-reset//' /etc/systemd/system/worker$i.service - done - echo "Done" -} - -# TODO: here we only read worker0 logs here -function latest_sidechain_block { - block_number=$(grep -F 'Enclave produced sidechain blocks' $WORKER_BASEDIR/w0/worker.log | tail -n 1 | sed 's/.*\[//;s/]//') - SCHEDULED_UPDATE_BLOCK=$((block_number + 30)) - echo "Current sidechain block: $block_number, scheduled update block: $SCHEDULED_UPDATE_BLOCK" -} - -# TODO: unused -function _latest_parentchain_block { - # JSON-RPC request payload - request='{"jsonrpc":"2.0","id":1,"method":"chain_getHeader","params":[]}' - - # Make the JSON-RPC request and retrieve the latest finalized block - response=$(curl -s -H "Content-Type: application/json" -d "$request" http://$PARACHAIN_HOST:$PARACHAIN_PORT) - hex_number=$(echo "$response" | grep -oP '(?<="number":")[^"]+') - LATEST_FINALIZED_BLOCK=$(printf "%d" "$hex_number") - echo "Current parachain block: $LATEST_FINALIZED_BLOCK" -} - -main "$@" diff --git a/tee-worker/bitacross/scripts/litentry/release/prepare.sh b/tee-worker/bitacross/scripts/litentry/release/prepare.sh deleted file mode 100755 index e9817e8d71..0000000000 --- a/tee-worker/bitacross/scripts/litentry/release/prepare.sh +++ /dev/null @@ -1,50 +0,0 @@ -#!/bin/bash -set -euo pipefail - - -# This WORKER_DIR is the directory where worker will start from. -WORKER_DIR=/opt/worker/ - -# CONFIG_DIR provides all the necessary private secret files. -# They should only exist on the running machine. -CONFIG_DIR=/opt/configs/ -CONFIG=$CONFIG_DIR/config.json -ACCOUNT=$CONFIG_DIR/private_account.json -INTEL_KEY=$CONFIG_DIR/key_production.txt -INTEL_SPID=$CONFIG_DIR/spid_production.txt - -############################################################################## -# Don't edit anything from here -if [[ ! -e "$WORKER_DIR" ]]; then - mkdir -p $WORKER_DIR -fi - -for Item in $CONFIG $ACCOUNT $INTEL_KEY $INTEL_SPID; do - if [[ ! -e "$Item" ]]; then - echo "Error: $Item is not a valid path." - exit 1 - fi -done - -# Generate keys and copy around. -SRC_DIR=$(dirname "$0") -cd $SRC_DIR - -./litentry-worker signing-key | grep -oP '^Enclave account: \K.*$$' > enclave_account.txt -echo "Enclave account is prepared inside enclave_account.txt" - -./litentry-worker shielding-key - -for Item in 'enclave.signed.so' 'litentry-worker' 'aes_key_sealed.bin' 'ed25519_key_sealed.bin' 'enclave-shielding-pubkey.json' 'enclave-signing-pubkey.bin' 'rsa3072_key_sealed.bin' 'sidechain_db'; do - cp -r "${Item}" "${WORKER_DIR}" -done - -cp $CONFIG "${WORKER_DIR}/config.json" -cp $INTEL_KEY "${WORKER_DIR}/key_production.txt" -cp $INTEL_SPID "${WORKER_DIR}/spid_production.txt" - -# Comment out for the moment. Need to adapt together with PR-1587 ts-utils. -cp $ACCOUNT "${WORKER_DIR}/ts-utils/private_account.json" -cp "enclave_account.txt" "${WORKER_DIR}/ts-utils/enclave_account.txt" -cp "mrenclave.txt" "${WORKER_DIR}/ts-utils/mrenclave.txt" - diff --git a/tee-worker/bitacross/scripts/litentry/release/template/para-alice.service b/tee-worker/bitacross/scripts/litentry/release/template/para-alice.service deleted file mode 100644 index cb8eb6659b..0000000000 --- a/tee-worker/bitacross/scripts/litentry/release/template/para-alice.service +++ /dev/null @@ -1,15 +0,0 @@ -[Unit] -Description=Litentry Parachain - -[Service] -Type=simple -User=USER -WorkingDirectory=/opt/litentry/parachain -ExecStart=/opt/litentry/parachain/litentry-collator --base-path /opt/litentry/parachain/para-alice --alice --collator --force-authoring --chain CHAIN-dev --unsafe-rpc-external --rpc-cors=all --ws-max-connections 3000 --port 30333 --rpc-port 9944 --execution wasm --state-pruning archive --blocks-pruning archive -- --execution wasm --chain /opt/litentry/parachain/rococo-local-chain-spec.json --port 30332 --rpc-port 9943 -Restart=always -RestartSec=120 -StandardOutput=append:/opt/litentry/parachain/para.alice.log -StandardError=inherit - -[Install] -WantedBy=multi-user.target diff --git a/tee-worker/bitacross/scripts/litentry/release/template/relay-alice.service b/tee-worker/bitacross/scripts/litentry/release/template/relay-alice.service deleted file mode 100644 index ce87068c59..0000000000 --- a/tee-worker/bitacross/scripts/litentry/release/template/relay-alice.service +++ /dev/null @@ -1,15 +0,0 @@ -[Unit] -Description=Litentry Relaychain Alice - -[Service] -Type=simple -User=USER -WorkingDirectory=/opt/litentry/parachain -ExecStart=/opt/litentry/parachain/polkadot --base-path /opt/litentry/parachain/relay-alice --chain /opt/litentry/parachain/rococo-local-chain-spec.json --alice --port 30336 --rpc-port 9946 -Restart=always -RestartSec=120 -StandardOutput=append:/opt/litentry/parachain/relay.alice.log -StandardError=inherit - -[Install] -WantedBy=multi-user.target diff --git a/tee-worker/bitacross/scripts/litentry/release/template/relay-bob.service b/tee-worker/bitacross/scripts/litentry/release/template/relay-bob.service deleted file mode 100644 index 889f96378e..0000000000 --- a/tee-worker/bitacross/scripts/litentry/release/template/relay-bob.service +++ /dev/null @@ -1,15 +0,0 @@ -[Unit] -Description=Litentry Relaychain Bob - -[Service] -Type=simple -User=USER -WorkingDirectory=/opt/litentry/parachain -ExecStart=/opt/litentry/parachain/polkadot --base-path /opt/litentry/parachain/relay-bob --chain /opt/litentry/parachain/rococo-local-chain-spec.json --bob --port 30337 --rpc-port 9947 -Restart=always -RestartSec=120 -StandardOutput=append:/opt/litentry/parachain/relay.bob.log -StandardError=inherit - -[Install] -WantedBy=multi-user.target diff --git a/tee-worker/bitacross/scripts/litentry/release/template/worker.service b/tee-worker/bitacross/scripts/litentry/release/template/worker.service deleted file mode 100644 index e218d60278..0000000000 --- a/tee-worker/bitacross/scripts/litentry/release/template/worker.service +++ /dev/null @@ -1,14 +0,0 @@ -[Unit] -Description=Litentry TEE worker - -[Service] -Type=simple -User=USER -Environment='RUST_LOG=info,litentry_worker=debug,ws=warn,sp_io=error,substrate_api_client=warn,itc_parentchain_light_client=info,jsonrpsee_ws_client=warn,jsonrpsee_ws_server=warn,enclave_runtime=debug,ita_stf=debug,its_rpc_handler=warn,itc_rpc_client=warn,its_consensus_common=debug,its_state=warn,its_consensus_aura=warn,aura*=warn,its_consensus_slots=warn,itp_attestation_handler=debug,http_req=debug,lc_mock_server=warn,itc_rest_client=debug,lc_credentials=debug,lc_identity_verification=debug,lc_stf_task_receiver=debug,lc_stf_task_sender=debug,lc_data_providers=debug,itp_top_pool=debug,itc_parentchain_indirect_calls_executor=debug' -WorkingDirectory=/opt/litentry/worker/wNUMBER -ExecStart=/bin/bash -c 'cd /opt/litentry/worker/wNUMBER && source /opt/intel/sgxsdk/environment && ./litentry-worker ARGS' -StandardOutput=append:/opt/litentry/worker/wNUMBER/worker.log -StandardError=inherit - -[Install] -WantedBy=multi-user.target \ No newline at end of file diff --git a/tee-worker/bitacross/scripts/litentry/ubuntu_setup.sh b/tee-worker/bitacross/scripts/litentry/ubuntu_setup.sh deleted file mode 100755 index ef02a6418e..0000000000 --- a/tee-worker/bitacross/scripts/litentry/ubuntu_setup.sh +++ /dev/null @@ -1,71 +0,0 @@ -#!/bin/bash - -set -eo pipefail - -# most is copied from -# https://github.com/apache/incubator-teaclave-sgx-sdk/blob/v1.1.4/dockerfile/Dockerfile.2004.nightly - -# install rust -curl -s https://sh.rustup.rs -sSf | sh -s -- -y -# shellcheck source=${HOME}/.cargo/env -source ${HOME}/.cargo/env -rustup show - -# install substrate build deps -sudo apt-get update -sudo apt-get install -y cmake pkg-config libssl-dev git clang libclang-dev gnupg2 protobuf-compiler - -# install llvm -sudo apt-get update -wget https://apt.llvm.org/llvm.sh && chmod +x llvm.sh && sudo ./llvm.sh 10 - -# override binutils -wget https://download.01.org/intel-sgx/sgx-linux/2.20/as.ld.objdump.r4.tar.gz -tar xzf as.ld.objdump.r4.tar.gz -sudo cp -f external/toolset/ubuntu20.04/* /usr/bin/ - -# install sgx_sdk -SDK_URL="https://download.01.org/intel-sgx/sgx-linux/2.20/distro/ubuntu20.04-server/sgx_linux_x64_sdk_2.20.100.4.bin" -curl -o sdk.sh $SDK_URL -chmod a+x sdk.sh -echo -e 'no\n/opt' | ./sdk.sh -source /opt/sgxsdk/environment - -# install runtime sgx libs (psw) -CODENAME=focal -VERSION=2.20.100.4-focal1 -DCAP_VERSION=1.17.100.4-focal1 - -curl -fsSL https://download.01.org/intel-sgx/sgx_repo/ubuntu/intel-sgx-deb.key | sudo apt-key add - && \ -sudo add-apt-repository "deb https://download.01.org/intel-sgx/sgx_repo/ubuntu $CODENAME main" && \ -sudo apt-get update && \ -sudo apt-get install -y \ - libsgx-headers=$VERSION \ - libsgx-ae-epid=$VERSION \ - libsgx-ae-le=$VERSION \ - libsgx-ae-pce=$VERSION \ - libsgx-aesm-ecdsa-plugin=$VERSION \ - libsgx-aesm-epid-plugin=$VERSION \ - libsgx-aesm-launch-plugin=$VERSION \ - libsgx-aesm-pce-plugin=$VERSION \ - libsgx-aesm-quote-ex-plugin=$VERSION \ - libsgx-enclave-common=$VERSION \ - libsgx-enclave-common-dev=$VERSION \ - libsgx-epid=$VERSION \ - libsgx-epid-dev=$VERSION \ - libsgx-launch=$VERSION \ - libsgx-launch-dev=$VERSION \ - libsgx-quote-ex=$VERSION \ - libsgx-quote-ex-dev=$VERSION \ - libsgx-uae-service=$VERSION \ - libsgx-urts=$VERSION \ - sgx-aesm-service=$VERSION \ - libsgx-ae-qe3=$DCAP_VERSION \ - libsgx-pce-logic=$DCAP_VERSION \ - libsgx-qe3-logic=$DCAP_VERSION \ - libsgx-ra-network=$DCAP_VERSION \ - libsgx-ra-uefi=$DCAP_VERSION -mkdir -p /var/run/aesmd || true - -# store env -echo "$(env)" >> $GITHUB_ENV \ No newline at end of file diff --git a/tee-worker/bitacross/scripts/m6.sh b/tee-worker/bitacross/scripts/m6.sh deleted file mode 100755 index d6ed56786d..0000000000 --- a/tee-worker/bitacross/scripts/m6.sh +++ /dev/null @@ -1,23 +0,0 @@ -#!/bin/bash -set -euo pipefail - -# Runs M6 demo: Either set `CLIENT_DIR` env var directly or run script with: -# -# source ./init_env.sh && ./m6.sh - -echo "$CLIENT_DIR" - -cd "$CLIENT_DIR" || exit - -LOG_1="${LOG_1:-$LOG_DIR/m6_demo_shielding_unshielding_1.log}" -LOG_2="${LOG_2:-$LOG_DIR/m6_demo_shielding_unshielding_2.log}" - -echo "[m6.sh] printing to logs:" -echo " $LOG_1" -echo " $LOG_2" - -touch "$LOG_1" -touch "$LOG_2" - -./demo_shielding_unshielding.sh -p 9944 -P 2000 -C ./../bin/bitacross-cli -t first 2>&1 | tee "$LOG_1" -./demo_shielding_unshielding.sh -p 9944 -P 3000 -C ./../bin/bitacross-cli -t second 2>&1 | tee "$LOG_2" diff --git a/tee-worker/bitacross/scripts/m8.sh b/tee-worker/bitacross/scripts/m8.sh deleted file mode 100755 index 402875a8c8..0000000000 --- a/tee-worker/bitacross/scripts/m8.sh +++ /dev/null @@ -1,21 +0,0 @@ -#!/bin/bash -set -euo pipefail - -# Runs M8 demo: Either set `CLIENT_DIR` env var directly or run script with: -# -# source ./init_env.sh && ./m8.sh - -cd "$CLIENT_DIR" || exit - -LOG_1="${LOG_1:-$LOG_DIR/m8_demo_direct_call_1.log}" -LOG_2="${LOG_2:-$LOG_DIR/m8_demo_direct_call_2.log}" - -echo "[m8.sh] printing to logs:" -echo " $LOG_1" -echo " $LOG_2" - -touch "$LOG_1" -touch "$LOG_2" - -./demo_direct_call.sh -p 9944 -P 2000 -C ./../bin/bitacross-cli -t first 2>&1 | tee "$LOG_1" -./demo_direct_call.sh -p 9944 -P 3000 -C ./../bin/bitacross-cli -t second 2>&1 | tee "$LOG_2" diff --git a/tee-worker/bitacross/scripts/polkadot_update.sh b/tee-worker/bitacross/scripts/polkadot_update.sh deleted file mode 100755 index 0ba52f86e3..0000000000 --- a/tee-worker/bitacross/scripts/polkadot_update.sh +++ /dev/null @@ -1,97 +0,0 @@ -#!/bin/bash - -# A script to automate the polkadot update for our repository as far as possible -# Needs the diener and sd (sed replacement) tool. Install with: -# cargo install diener -# cargo install sd - -# These are the values that need to be adjusted for an update -CHECKOUT_DIR="$HOME/polkadot_update2" -DEVELOPER_ID="tn" -OLD_VERSION_NUMBER="0.9.27" -NEW_VERSION_NUMBER="0.9.28" -NEW_NIGHTLY_VERSION="2022-09-12" - -OLD_POLKADOT_VERSION_NUMBER="polkadot-v${OLD_VERSION_NUMBER}" -NEW_POLKADOT_VERSION_NUMBER="polkadot-v${NEW_VERSION_NUMBER}" -DEVELOPMENT_BRANCH="${DEVELOPER_ID}/${NEW_POLKADOT_VERSION_NUMBER}" - -# Make sure that the directory does not exist. We don't want to mess up existing stuff -if [ -d "${CHECKOUT_DIR}" ]; then - echo "Directory ${CHECKOUT_DIR} already exists. Please delete directory first." - exit 1 -fi - -mkdir "${CHECKOUT_DIR}" -pushd "${CHECKOUT_DIR}" - -git clone https://github.com/integritee-network/integritee-node.git -git clone https://github.com/integritee-network/pallets.git -git clone https://github.com/integritee-network/parachain.git -git clone https://github.com/scs/substrate-api-client.git -git clone https://github.com/integritee-network/worker.git - -declare -a REPO_NAMES=("integritee-node" "pallets" "parachain" "substrate-api-client" "worker" ) - -# Create new branch for all repos -for REPO in ${REPO_NAMES[@]}; do - pushd ${REPO};git checkout -b ${DEVELOPMENT_BRANCH};popd -done - -# Update the polkadot version -# We cannot combine the flags into a single call. Don't use the all flag because it relly changes all dependencies -diener update --cumulus --branch ${NEW_POLKADOT_VERSION_NUMBER} -diener update --substrate --branch ${NEW_POLKADOT_VERSION_NUMBER} -# Polkadot uses another branch pattern, because why not... -diener update --polkadot --branch "release-v${NEW_VERSION_NUMBER}" - -# Add commit for all repos -for REPO in ${REPO_NAMES[@]}; do - pushd ${REPO};git add -A;git commit -m "Update polkadot version (Auto generated commit)";popd -done - -# Execute cargo update for all repos. Currently not active as it is not clear when is the "right moment" to do this -#for REPO in ${REPO_NAMES[@]}; do -# pushd ${REPO};cargo update;popd -#done - -# Add commit for all repos -#for REPO in ${REPO_NAMES[@]}; do -# pushd ${REPO};git add -A;git commit -m "Run cargo update (Auto generated)";popd -#done - -#set -o xtrace -# Update internal dependencies by doing search replace -for REPO in ${REPO_NAMES[@]}; do - SEARCH_STRING_VERSION="${REPO}\", branch = \"${OLD_POLKADOT_VERSION_NUMBER}\"" - SEARCH_STRING_VERSION_GIT="${REPO}.git\", branch = \"${OLD_POLKADOT_VERSION_NUMBER}\"" - SEARCH_STRING_MASTER="${REPO}\", branch = \"master\"" - SEARCH_STRING_MASTER_GIT="${REPO}.git\", branch = \"master\"" - REPLACE_STRING="${REPO}.git\", branch = \"${DEVELOPMENT_BRANCH}\"" - sd "${SEARCH_STRING_VERSION}" "${REPLACE_STRING}" $(find . -type f -name 'Cargo.toml') - sd "${SEARCH_STRING_VERSION_GIT}" "${REPLACE_STRING}" $(find . -type f -name 'Cargo.toml') - sd "${SEARCH_STRING_MASTER}" "${REPLACE_STRING}" $(find . -type f -name 'Cargo.toml') - sd "${SEARCH_STRING_MASTER_GIT}" "${REPLACE_STRING}" $(find . -type f -name 'Cargo.toml') -done - -# Add commit for all repos -for REPO in ${REPO_NAMES[@]}; do - pushd ${REPO};git add -A;git commit -m "Update versions for internal dependencies (Auto generated commit)";popd -done - -NIGHTLY_SEARCH_STRING="channel = \"nightly-.*\"" -NIGHTLY_SEARCH_STRING="channel = \"nightly-${NEW_NIGHTLY_VERSION}\"" -sd "${NIGHTLY_SEARCH_STRING}" "${NIGTHLY_NEW_STRING}" $(find . -type f -name 'rust-toolchain.toml') - -# Add commit for all repos -for REPO in ${REPO_NAMES[@]}; do - pushd ${REPO};git add -A;git commit -m "Update rust toolchain to new nightly version (Auto generated commit)";popd -done - -echo "" -echo "" -echo "Search results for old version number ${OLD_VERSION_NUMBER} in Cargo.toml files:" -# Exclude the lock files as they still refer to the old version -grep -F -r --exclude *.lock "${OLD_VERSION_NUMBER}" . - -popd diff --git a/tee-worker/bitacross/scripts/sidechain.sh b/tee-worker/bitacross/scripts/sidechain.sh deleted file mode 100755 index 908c538eb1..0000000000 --- a/tee-worker/bitacross/scripts/sidechain.sh +++ /dev/null @@ -1,17 +0,0 @@ -#!/bin/bash -set -euo pipefail - -# Runs sidechain demo: Either set `CLIENT_DIR` env var directly or run script with: -# -# source ./init_env.sh && ./sidechain.sh - -cd "$CLIENT_DIR" || exit - -LOG="${LOG:-$LOG_DIR/sidechain_demo.log}" - -echo "[sidechain.sh] printing to logs:" -echo " $LOG" - -touch "$LOG" - -./demo_sidechain.sh -p 9944 -A 2000 -B 3000 -C ./../bin/bitacross-cli 2>&1 | tee "$LOG" \ No newline at end of file diff --git a/tee-worker/bitacross/scripts/test_transfer/README.md b/tee-worker/bitacross/scripts/test_transfer/README.md deleted file mode 100644 index 13ff80ca8e..0000000000 --- a/tee-worker/bitacross/scripts/test_transfer/README.md +++ /dev/null @@ -1,6 +0,0 @@ -## Test transfer from Alice to random account - -## Install -```bash -npm install -``` diff --git a/tee-worker/bitacross/scripts/test_transfer/package-lock.json b/tee-worker/bitacross/scripts/test_transfer/package-lock.json deleted file mode 100644 index 237b27764d..0000000000 --- a/tee-worker/bitacross/scripts/test_transfer/package-lock.json +++ /dev/null @@ -1,1322 +0,0 @@ -{ - "name": "test_transfer", - "version": "1.0.0", - "lockfileVersion": 2, - "requires": true, - "packages": { - "": { - "name": "test_transfer", - "version": "1.0.0", - "license": "ISC", - "dependencies": { - "@polkadot/api": "^10.9.1", - "@polkadot/keyring": "^12.3.2", - "@polkadot/util-crypto": "^12.3.2" - } - }, - "node_modules/@noble/curves": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/@noble/curves/-/curves-1.1.0.tgz", - "integrity": "sha512-091oBExgENk/kGj3AZmtBDMpxQPDtxQABR2B9lb1JbVTs6ytdzZNwvhxQ4MWasRNEzlbEH8jCWFCwhF/Obj5AA==", - "dependencies": { - "@noble/hashes": "1.3.1" - }, - "funding": { - "url": "https://paulmillr.com/funding/" - } - }, - "node_modules/@noble/hashes": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.3.1.tgz", - "integrity": "sha512-EbqwksQwz9xDRGfDST86whPBgM65E0OH/pCgqW0GBVzO22bNE+NuIbeTb714+IfSjU3aRk47EUvXIb5bTsenKA==", - "engines": { - "node": ">= 16" - }, - "funding": { - "url": "https://paulmillr.com/funding/" - } - }, - "node_modules/@polkadot/api": { - "version": "10.9.1", - "resolved": "https://registry.npmjs.org/@polkadot/api/-/api-10.9.1.tgz", - "integrity": "sha512-ND/2UqZBWvtt4PfV03OStTKg0mxmPk4UpMAgJKutdgsz/wP9CYJ1KbjwFgPNekL9JnzbKQsWyQNPVrcw7kQk8A==", - "dependencies": { - "@polkadot/api-augment": "10.9.1", - "@polkadot/api-base": "10.9.1", - "@polkadot/api-derive": "10.9.1", - "@polkadot/keyring": "^12.3.1", - "@polkadot/rpc-augment": "10.9.1", - "@polkadot/rpc-core": "10.9.1", - "@polkadot/rpc-provider": "10.9.1", - "@polkadot/types": "10.9.1", - "@polkadot/types-augment": "10.9.1", - "@polkadot/types-codec": "10.9.1", - "@polkadot/types-create": "10.9.1", - "@polkadot/types-known": "10.9.1", - "@polkadot/util": "^12.3.1", - "@polkadot/util-crypto": "^12.3.1", - "eventemitter3": "^5.0.1", - "rxjs": "^7.8.1", - "tslib": "^2.5.3" - }, - "engines": { - "node": ">=16" - } - }, - "node_modules/@polkadot/api-augment": { - "version": "10.9.1", - "resolved": "https://registry.npmjs.org/@polkadot/api-augment/-/api-augment-10.9.1.tgz", - "integrity": "sha512-kRZZvCFVcN4hAH4dJ+Qzfdy27/4EEq3oLDf3ihj0LTVrAezSWcKPGE3EVFy+Mn6Lo4SUc7RVyoKvIUhSk2l4Dg==", - "dependencies": { - "@polkadot/api-base": "10.9.1", - "@polkadot/rpc-augment": "10.9.1", - "@polkadot/types": "10.9.1", - "@polkadot/types-augment": "10.9.1", - "@polkadot/types-codec": "10.9.1", - "@polkadot/util": "^12.3.1", - "tslib": "^2.5.3" - }, - "engines": { - "node": ">=16" - } - }, - "node_modules/@polkadot/api-base": { - "version": "10.9.1", - "resolved": "https://registry.npmjs.org/@polkadot/api-base/-/api-base-10.9.1.tgz", - "integrity": "sha512-Q3m2KzlceMK2kX8bhnUZWk3RT6emmijeeFZZQgCePpEcrSeNjnqG4qjuTPgkveaOkUT8MAoDc5Avuzcc2jlW9g==", - "dependencies": { - "@polkadot/rpc-core": "10.9.1", - "@polkadot/types": "10.9.1", - "@polkadot/util": "^12.3.1", - "rxjs": "^7.8.1", - "tslib": "^2.5.3" - }, - "engines": { - "node": ">=16" - } - }, - "node_modules/@polkadot/api-derive": { - "version": "10.9.1", - "resolved": "https://registry.npmjs.org/@polkadot/api-derive/-/api-derive-10.9.1.tgz", - "integrity": "sha512-mRud1UZCFIc4Z63qAoGSIHh/foyUYADfy1RQYCmPpeFKfIdCIrHpd7xFdJXTOMYOS0BwlM6u4qli/ZT4XigezQ==", - "dependencies": { - "@polkadot/api": "10.9.1", - "@polkadot/api-augment": "10.9.1", - "@polkadot/api-base": "10.9.1", - "@polkadot/rpc-core": "10.9.1", - "@polkadot/types": "10.9.1", - "@polkadot/types-codec": "10.9.1", - "@polkadot/util": "^12.3.1", - "@polkadot/util-crypto": "^12.3.1", - "rxjs": "^7.8.1", - "tslib": "^2.5.3" - }, - "engines": { - "node": ">=16" - } - }, - "node_modules/@polkadot/keyring": { - "version": "12.3.2", - "resolved": "https://registry.npmjs.org/@polkadot/keyring/-/keyring-12.3.2.tgz", - "integrity": "sha512-NTdtDeI0DP9l/45hXynNABeP5VB8piw5YR+CbUxK2e36xpJWVXwbcOepzslg5ghE9rs8UKJb30Z/HqTU4sBY0Q==", - "dependencies": { - "@polkadot/util": "12.3.2", - "@polkadot/util-crypto": "12.3.2", - "tslib": "^2.5.3" - }, - "engines": { - "node": ">=16" - }, - "peerDependencies": { - "@polkadot/util": "12.3.2", - "@polkadot/util-crypto": "12.3.2" - } - }, - "node_modules/@polkadot/networks": { - "version": "12.3.2", - "resolved": "https://registry.npmjs.org/@polkadot/networks/-/networks-12.3.2.tgz", - "integrity": "sha512-uCkyybKoeEm1daKr0uT/9oNDHDDzCy2/ZdVl346hQqfdR1Ct3BaxMjxqvdmb5N8aCw0cBWSfgsxAYtw8ESmllQ==", - "dependencies": { - "@polkadot/util": "12.3.2", - "@substrate/ss58-registry": "^1.40.0", - "tslib": "^2.5.3" - }, - "engines": { - "node": ">=16" - } - }, - "node_modules/@polkadot/rpc-augment": { - "version": "10.9.1", - "resolved": "https://registry.npmjs.org/@polkadot/rpc-augment/-/rpc-augment-10.9.1.tgz", - "integrity": "sha512-MaLHkNlyqN20ZRYr6uNd1BZr1OsrnX9qLAmsl0mcrri1vPGRH6VHjfFH1RBLkikpWD82v17g0l2hLwdV1ZHMcw==", - "dependencies": { - "@polkadot/rpc-core": "10.9.1", - "@polkadot/types": "10.9.1", - "@polkadot/types-codec": "10.9.1", - "@polkadot/util": "^12.3.1", - "tslib": "^2.5.3" - }, - "engines": { - "node": ">=16" - } - }, - "node_modules/@polkadot/rpc-core": { - "version": "10.9.1", - "resolved": "https://registry.npmjs.org/@polkadot/rpc-core/-/rpc-core-10.9.1.tgz", - "integrity": "sha512-ZtA8B8SfXSAwVkBlCcKRHw0eSM7ec/sbiNOM5GasXPeRujUgT7lOwSH2GbUZSqe9RfRDMp6DvO9c2JoGc3LLWw==", - "dependencies": { - "@polkadot/rpc-augment": "10.9.1", - "@polkadot/rpc-provider": "10.9.1", - "@polkadot/types": "10.9.1", - "@polkadot/util": "^12.3.1", - "rxjs": "^7.8.1", - "tslib": "^2.5.3" - }, - "engines": { - "node": ">=16" - } - }, - "node_modules/@polkadot/rpc-provider": { - "version": "10.9.1", - "resolved": "https://registry.npmjs.org/@polkadot/rpc-provider/-/rpc-provider-10.9.1.tgz", - "integrity": "sha512-4QzT2QzD+320+eT6b79sGAA85Tt3Bb8fQvse4r5Mom2iiBd2SO81vOhxSAOaIe4GUsw25VzFJmsbe7+OObItdg==", - "dependencies": { - "@polkadot/keyring": "^12.3.1", - "@polkadot/types": "10.9.1", - "@polkadot/types-support": "10.9.1", - "@polkadot/util": "^12.3.1", - "@polkadot/util-crypto": "^12.3.1", - "@polkadot/x-fetch": "^12.3.1", - "@polkadot/x-global": "^12.3.1", - "@polkadot/x-ws": "^12.3.1", - "eventemitter3": "^5.0.1", - "mock-socket": "^9.2.1", - "nock": "^13.3.1", - "tslib": "^2.5.3" - }, - "engines": { - "node": ">=16" - }, - "optionalDependencies": { - "@substrate/connect": "0.7.26" - } - }, - "node_modules/@polkadot/types": { - "version": "10.9.1", - "resolved": "https://registry.npmjs.org/@polkadot/types/-/types-10.9.1.tgz", - "integrity": "sha512-AG33i2ZGGfq7u+5rkAdGrXAQHHl844/Yv+junH5ZzX69xiCoWO1bH/yzDUNBdpki2GlACWvF9nLYh3F2tVF93w==", - "dependencies": { - "@polkadot/keyring": "^12.3.1", - "@polkadot/types-augment": "10.9.1", - "@polkadot/types-codec": "10.9.1", - "@polkadot/types-create": "10.9.1", - "@polkadot/util": "^12.3.1", - "@polkadot/util-crypto": "^12.3.1", - "rxjs": "^7.8.1", - "tslib": "^2.5.3" - }, - "engines": { - "node": ">=16" - } - }, - "node_modules/@polkadot/types-augment": { - "version": "10.9.1", - "resolved": "https://registry.npmjs.org/@polkadot/types-augment/-/types-augment-10.9.1.tgz", - "integrity": "sha512-OY9/jTMFRFqYdkUnfcGwqMLC64A0Q25bjvCuVQCVjsPFKE3wl0Kt5rNT01eV2UmLXrR6fY0xWbR2w80bLA7CIQ==", - "dependencies": { - "@polkadot/types": "10.9.1", - "@polkadot/types-codec": "10.9.1", - "@polkadot/util": "^12.3.1", - "tslib": "^2.5.3" - }, - "engines": { - "node": ">=16" - } - }, - "node_modules/@polkadot/types-codec": { - "version": "10.9.1", - "resolved": "https://registry.npmjs.org/@polkadot/types-codec/-/types-codec-10.9.1.tgz", - "integrity": "sha512-mJ5OegKGraY1FLvEa8FopRCr3pQrhDkcn5RNOjmgJQozENVeRaxhk0NwxYz7IojFvSDnKnc6lNQfKaaSe5pLHg==", - "dependencies": { - "@polkadot/util": "^12.3.1", - "@polkadot/x-bigint": "^12.3.1", - "tslib": "^2.5.3" - }, - "engines": { - "node": ">=16" - } - }, - "node_modules/@polkadot/types-create": { - "version": "10.9.1", - "resolved": "https://registry.npmjs.org/@polkadot/types-create/-/types-create-10.9.1.tgz", - "integrity": "sha512-OVz50MGTTuiuVnRP/zAx4CTuLioc0hsiwNwqN2lNhmIJGtnQ4Vy/7mQRsIWehiYz6g0Vzzm5B3qWkTXO1NSN5w==", - "dependencies": { - "@polkadot/types-codec": "10.9.1", - "@polkadot/util": "^12.3.1", - "tslib": "^2.5.3" - }, - "engines": { - "node": ">=16" - } - }, - "node_modules/@polkadot/types-known": { - "version": "10.9.1", - "resolved": "https://registry.npmjs.org/@polkadot/types-known/-/types-known-10.9.1.tgz", - "integrity": "sha512-zCMVWc4pJtkbMFPu72bD4IhvV/gkHXPX3C5uu92WdmCfnn0vEIEsMKWlVXVVvQQZKAqvs/awpqIfrUtEViOGEA==", - "dependencies": { - "@polkadot/networks": "^12.3.1", - "@polkadot/types": "10.9.1", - "@polkadot/types-codec": "10.9.1", - "@polkadot/types-create": "10.9.1", - "@polkadot/util": "^12.3.1", - "tslib": "^2.5.3" - }, - "engines": { - "node": ">=16" - } - }, - "node_modules/@polkadot/types-support": { - "version": "10.9.1", - "resolved": "https://registry.npmjs.org/@polkadot/types-support/-/types-support-10.9.1.tgz", - "integrity": "sha512-XsieuLDsszvMZQlleacQBfx07i/JkwQV/UxH9q8Hz7Okmaz9pEVEW1h3ka2/cPuC7a4l32JhaORBUYshBZNdJg==", - "dependencies": { - "@polkadot/util": "^12.3.1", - "tslib": "^2.5.3" - }, - "engines": { - "node": ">=16" - } - }, - "node_modules/@polkadot/util": { - "version": "12.3.2", - "resolved": "https://registry.npmjs.org/@polkadot/util/-/util-12.3.2.tgz", - "integrity": "sha512-y/JShcGyOamCUiSIg++XZuLHt1ktSKBaSH2K5Nw5NXlgP0+7am+GZzqPB8fQ4qhYLruEOv+YRiz0GC1Zr9S+wg==", - "dependencies": { - "@polkadot/x-bigint": "12.3.2", - "@polkadot/x-global": "12.3.2", - "@polkadot/x-textdecoder": "12.3.2", - "@polkadot/x-textencoder": "12.3.2", - "@types/bn.js": "^5.1.1", - "bn.js": "^5.2.1", - "tslib": "^2.5.3" - }, - "engines": { - "node": ">=16" - } - }, - "node_modules/@polkadot/util-crypto": { - "version": "12.3.2", - "resolved": "https://registry.npmjs.org/@polkadot/util-crypto/-/util-crypto-12.3.2.tgz", - "integrity": "sha512-pTpx+YxolY0BDT4RcGmgeKbHHD/dI6Ll9xRsqmVdIjpcVVY20uDNTyXs81ZNtfKgyod1y9JQkfNv2Dz9iEpTkQ==", - "dependencies": { - "@noble/curves": "1.1.0", - "@noble/hashes": "1.3.1", - "@polkadot/networks": "12.3.2", - "@polkadot/util": "12.3.2", - "@polkadot/wasm-crypto": "^7.2.1", - "@polkadot/wasm-util": "^7.2.1", - "@polkadot/x-bigint": "12.3.2", - "@polkadot/x-randomvalues": "12.3.2", - "@scure/base": "1.1.1", - "tslib": "^2.5.3" - }, - "engines": { - "node": ">=16" - }, - "peerDependencies": { - "@polkadot/util": "12.3.2" - } - }, - "node_modules/@polkadot/wasm-bridge": { - "version": "7.2.1", - "resolved": "https://registry.npmjs.org/@polkadot/wasm-bridge/-/wasm-bridge-7.2.1.tgz", - "integrity": "sha512-uV/LHREDBGBbHrrv7HTki+Klw0PYZzFomagFWII4lp6Toj/VCvRh5WMzooVC+g/XsBGosAwrvBhoModabyHx+A==", - "dependencies": { - "@polkadot/wasm-util": "7.2.1", - "tslib": "^2.5.0" - }, - "engines": { - "node": ">=16" - }, - "peerDependencies": { - "@polkadot/util": "*", - "@polkadot/x-randomvalues": "*" - } - }, - "node_modules/@polkadot/wasm-crypto": { - "version": "7.2.1", - "resolved": "https://registry.npmjs.org/@polkadot/wasm-crypto/-/wasm-crypto-7.2.1.tgz", - "integrity": "sha512-SA2+33S9TAwGhniKgztVN6pxUKpGfN4Tre/eUZGUfpgRkT92wIUT2GpGWQE+fCCqGQgADrNiBcwt6XwdPqMQ4Q==", - "dependencies": { - "@polkadot/wasm-bridge": "7.2.1", - "@polkadot/wasm-crypto-asmjs": "7.2.1", - "@polkadot/wasm-crypto-init": "7.2.1", - "@polkadot/wasm-crypto-wasm": "7.2.1", - "@polkadot/wasm-util": "7.2.1", - "tslib": "^2.5.0" - }, - "engines": { - "node": ">=16" - }, - "peerDependencies": { - "@polkadot/util": "*", - "@polkadot/x-randomvalues": "*" - } - }, - "node_modules/@polkadot/wasm-crypto-asmjs": { - "version": "7.2.1", - "resolved": "https://registry.npmjs.org/@polkadot/wasm-crypto-asmjs/-/wasm-crypto-asmjs-7.2.1.tgz", - "integrity": "sha512-z/d21bmxyVfkzGsKef/FWswKX02x5lK97f4NPBZ9XBeiFkmzlXhdSnu58/+b1sKsRAGdW/Rn/rTNRDhW0GqCAg==", - "dependencies": { - "tslib": "^2.5.0" - }, - "engines": { - "node": ">=16" - }, - "peerDependencies": { - "@polkadot/util": "*" - } - }, - "node_modules/@polkadot/wasm-crypto-init": { - "version": "7.2.1", - "resolved": "https://registry.npmjs.org/@polkadot/wasm-crypto-init/-/wasm-crypto-init-7.2.1.tgz", - "integrity": "sha512-GcEXtwN9LcSf32V9zSaYjHImFw16hCyo2Xzg4GLLDPPeaAAfbFr2oQMgwyDbvBrBjLKHVHjsPZyGhXae831amw==", - "dependencies": { - "@polkadot/wasm-bridge": "7.2.1", - "@polkadot/wasm-crypto-asmjs": "7.2.1", - "@polkadot/wasm-crypto-wasm": "7.2.1", - "@polkadot/wasm-util": "7.2.1", - "tslib": "^2.5.0" - }, - "engines": { - "node": ">=16" - }, - "peerDependencies": { - "@polkadot/util": "*", - "@polkadot/x-randomvalues": "*" - } - }, - "node_modules/@polkadot/wasm-crypto-wasm": { - "version": "7.2.1", - "resolved": "https://registry.npmjs.org/@polkadot/wasm-crypto-wasm/-/wasm-crypto-wasm-7.2.1.tgz", - "integrity": "sha512-DqyXE4rSD0CVlLIw88B58+HHNyrvm+JAnYyuEDYZwCvzUWOCNos/DDg9wi/K39VAIsCCKDmwKqkkfIofuOj/lA==", - "dependencies": { - "@polkadot/wasm-util": "7.2.1", - "tslib": "^2.5.0" - }, - "engines": { - "node": ">=16" - }, - "peerDependencies": { - "@polkadot/util": "*" - } - }, - "node_modules/@polkadot/wasm-util": { - "version": "7.2.1", - "resolved": "https://registry.npmjs.org/@polkadot/wasm-util/-/wasm-util-7.2.1.tgz", - "integrity": "sha512-FBSn/3aYJzhN0sYAYhHB8y9JL8mVgxLy4M1kUXYbyo+8GLRQEN5rns8Vcb8TAlIzBWgVTOOptYBvxo0oj0h7Og==", - "dependencies": { - "tslib": "^2.5.0" - }, - "engines": { - "node": ">=16" - }, - "peerDependencies": { - "@polkadot/util": "*" - } - }, - "node_modules/@polkadot/x-bigint": { - "version": "12.3.2", - "resolved": "https://registry.npmjs.org/@polkadot/x-bigint/-/x-bigint-12.3.2.tgz", - "integrity": "sha512-JLqLgfGXe/x+hZJETd5ZqfpVsbwyMsH5Nn1Q20ineMMjXN/ig+kVR8Mc15LXBMuw4g7LldFW6UUrotWnuMI8Yw==", - "dependencies": { - "@polkadot/x-global": "12.3.2", - "tslib": "^2.5.3" - }, - "engines": { - "node": ">=16" - } - }, - "node_modules/@polkadot/x-fetch": { - "version": "12.3.2", - "resolved": "https://registry.npmjs.org/@polkadot/x-fetch/-/x-fetch-12.3.2.tgz", - "integrity": "sha512-3IEuZ5S+RI/t33NsdPLIIa5COfDCfpUW2sbaByEczn75aD1jLqJZSEDwiBniJ2osyNd4uUxBf6e5jw7LAZeZJg==", - "dependencies": { - "@polkadot/x-global": "12.3.2", - "node-fetch": "^3.3.1", - "tslib": "^2.5.3" - }, - "engines": { - "node": ">=16" - } - }, - "node_modules/@polkadot/x-global": { - "version": "12.3.2", - "resolved": "https://registry.npmjs.org/@polkadot/x-global/-/x-global-12.3.2.tgz", - "integrity": "sha512-yVZq6oIegjlyh5rUZiTklgu+fL+W/DG1ypEa02683tUCB3avV5cA3PAHKptMSlb6FpweHu37lKKrqfAWrraDxg==", - "dependencies": { - "tslib": "^2.5.3" - }, - "engines": { - "node": ">=16" - } - }, - "node_modules/@polkadot/x-randomvalues": { - "version": "12.3.2", - "resolved": "https://registry.npmjs.org/@polkadot/x-randomvalues/-/x-randomvalues-12.3.2.tgz", - "integrity": "sha512-ywjIs8CWpvOGmq+3cGCNPOHxAjPHdBUiXyDccftx5BRVdmtbt36gK/V84bKr6Xs73FGu0jprUAOSRRsLZX/3dg==", - "dependencies": { - "@polkadot/x-global": "12.3.2", - "tslib": "^2.5.3" - }, - "engines": { - "node": ">=16" - }, - "peerDependencies": { - "@polkadot/util": "12.3.2", - "@polkadot/wasm-util": "*" - } - }, - "node_modules/@polkadot/x-textdecoder": { - "version": "12.3.2", - "resolved": "https://registry.npmjs.org/@polkadot/x-textdecoder/-/x-textdecoder-12.3.2.tgz", - "integrity": "sha512-lY5bfA5xArJRWEJlYOlQQMJeTjWD8s0yMhchirVgf5xj8Id9vPGeUoneH+VFDEwgXxrqBvDFJ4smN4T/r6a/fg==", - "dependencies": { - "@polkadot/x-global": "12.3.2", - "tslib": "^2.5.3" - }, - "engines": { - "node": ">=16" - } - }, - "node_modules/@polkadot/x-textencoder": { - "version": "12.3.2", - "resolved": "https://registry.npmjs.org/@polkadot/x-textencoder/-/x-textencoder-12.3.2.tgz", - "integrity": "sha512-iP3qEBiHzBckQ9zeY7ZHRWuu7mCEg5SMpOugs6UODRk8sx6KHzGQYlghBbWLit0uppPDVE0ifEwZ2n73djJHWQ==", - "dependencies": { - "@polkadot/x-global": "12.3.2", - "tslib": "^2.5.3" - }, - "engines": { - "node": ">=16" - } - }, - "node_modules/@polkadot/x-ws": { - "version": "12.3.2", - "resolved": "https://registry.npmjs.org/@polkadot/x-ws/-/x-ws-12.3.2.tgz", - "integrity": "sha512-yM9Z64pLNlHpJE43+Xtr+iUXmYpFFY5u5hrke2PJt13O48H8f9Vb9cRaIh94appLyICoS0aekGhDkGH+MCspBA==", - "dependencies": { - "@polkadot/x-global": "12.3.2", - "tslib": "^2.5.3", - "ws": "^8.13.0" - }, - "engines": { - "node": ">=16" - } - }, - "node_modules/@scure/base": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/@scure/base/-/base-1.1.1.tgz", - "integrity": "sha512-ZxOhsSyxYwLJj3pLZCefNitxsj093tb2vq90mp2txoYeBqbcjDjqFhyM8eUjq/uFm6zJ+mUuqxlS2FkuSY1MTA==", - "funding": [ - { - "type": "individual", - "url": "https://paulmillr.com/funding/" - } - ] - }, - "node_modules/@substrate/connect": { - "version": "0.7.26", - "resolved": "https://registry.npmjs.org/@substrate/connect/-/connect-0.7.26.tgz", - "integrity": "sha512-uuGSiroGuKWj1+38n1kY5HReer5iL9bRwPCzuoLtqAOmI1fGI0hsSI2LlNQMAbfRgr7VRHXOk5MTuQf5ulsFRw==", - "optional": true, - "dependencies": { - "@substrate/connect-extension-protocol": "^1.0.1", - "eventemitter3": "^4.0.7", - "smoldot": "1.0.4" - } - }, - "node_modules/@substrate/connect-extension-protocol": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/@substrate/connect-extension-protocol/-/connect-extension-protocol-1.0.1.tgz", - "integrity": "sha512-161JhCC1csjH3GE5mPLEd7HbWtwNSPJBg3p1Ksz9SFlTzj/bgEwudiRN2y5i0MoLGCIJRYKyKGMxVnd29PzNjg==", - "optional": true - }, - "node_modules/@substrate/connect/node_modules/eventemitter3": { - "version": "4.0.7", - "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-4.0.7.tgz", - "integrity": "sha512-8guHBZCwKnFhYdHr2ysuRWErTwhoN2X8XELRlrRwpmfeY2jjuUN4taQMsULKUVo1K4DvZl+0pgfyoysHxvmvEw==", - "optional": true - }, - "node_modules/@substrate/ss58-registry": { - "version": "1.40.0", - "resolved": "https://registry.npmjs.org/@substrate/ss58-registry/-/ss58-registry-1.40.0.tgz", - "integrity": "sha512-QuU2nBql3J4KCnOWtWDw4n1K4JU0T79j54ZZvm/9nhsX6AIar13FyhsaBfs6QkJ2ixTQAnd7TocJIoJRWbqMZA==" - }, - "node_modules/@types/bn.js": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/@types/bn.js/-/bn.js-5.1.1.tgz", - "integrity": "sha512-qNrYbZqMx0uJAfKnKclPh+dTwK33KfLHYqtyODwd5HnXOjnkhc4qgn3BrK6RWyGZm5+sIFE7Q7Vz6QQtJB7w7g==", - "dependencies": { - "@types/node": "*" - } - }, - "node_modules/@types/node": { - "version": "20.3.1", - "resolved": "https://registry.npmjs.org/@types/node/-/node-20.3.1.tgz", - "integrity": "sha512-EhcH/wvidPy1WeML3TtYFGR83UzjxeWRen9V402T8aUGYsCHOmfoisV3ZSg03gAFIbLq8TnWOJ0f4cALtnSEUg==" - }, - "node_modules/bn.js": { - "version": "5.2.1", - "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-5.2.1.tgz", - "integrity": "sha512-eXRvHzWyYPBuB4NBy0cmYQjGitUrtqwbvlzP3G6VFnNRbsZQIxQ10PbKKHt8gZ/HW/D/747aDl+QkDqg3KQLMQ==" - }, - "node_modules/data-uri-to-buffer": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-4.0.1.tgz", - "integrity": "sha512-0R9ikRb668HB7QDxT1vkpuUBtqc53YyAwMwGeUFKRojY/NWKvdZ+9UYtRfGmhqNbRkTSVpMbmyhXipFFv2cb/A==", - "engines": { - "node": ">= 12" - } - }, - "node_modules/debug": { - "version": "4.3.4", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz", - "integrity": "sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==", - "dependencies": { - "ms": "2.1.2" - }, - "engines": { - "node": ">=6.0" - }, - "peerDependenciesMeta": { - "supports-color": { - "optional": true - } - } - }, - "node_modules/eventemitter3": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-5.0.1.tgz", - "integrity": "sha512-GWkBvjiSZK87ELrYOSESUYeVIc9mvLLf/nXalMOS5dYrgZq9o5OVkbZAVM06CVxYsCwH9BDZFPlQTlPA1j4ahA==" - }, - "node_modules/fetch-blob": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/fetch-blob/-/fetch-blob-3.2.0.tgz", - "integrity": "sha512-7yAQpD2UMJzLi1Dqv7qFYnPbaPx7ZfFK6PiIxQ4PfkGPyNyl2Ugx+a/umUonmKqjhM4DnfbMvdX6otXq83soQQ==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/jimmywarting" - }, - { - "type": "paypal", - "url": "https://paypal.me/jimmywarting" - } - ], - "dependencies": { - "node-domexception": "^1.0.0", - "web-streams-polyfill": "^3.0.3" - }, - "engines": { - "node": "^12.20 || >= 14.13" - } - }, - "node_modules/formdata-polyfill": { - "version": "4.0.10", - "resolved": "https://registry.npmjs.org/formdata-polyfill/-/formdata-polyfill-4.0.10.tgz", - "integrity": "sha512-buewHzMvYL29jdeQTVILecSaZKnt/RJWjoZCF5OW60Z67/GmSLBkOFM7qh1PI3zFNtJbaZL5eQu1vLfazOwj4g==", - "dependencies": { - "fetch-blob": "^3.1.2" - }, - "engines": { - "node": ">=12.20.0" - } - }, - "node_modules/json-stringify-safe": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz", - "integrity": "sha512-ZClg6AaYvamvYEE82d3Iyd3vSSIjQ+odgjaTzRuO3s7toCdFKczob2i0zCh7JE8kWn17yvAWhUVxvqGwUalsRA==" - }, - "node_modules/lodash": { - "version": "4.17.21", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", - "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==" - }, - "node_modules/mock-socket": { - "version": "9.2.1", - "resolved": "https://registry.npmjs.org/mock-socket/-/mock-socket-9.2.1.tgz", - "integrity": "sha512-aw9F9T9G2zpGipLLhSNh6ZpgUyUl4frcVmRN08uE1NWPWg43Wx6+sGPDbQ7E5iFZZDJW5b5bypMeAEHqTbIFag==", - "engines": { - "node": ">= 8" - } - }, - "node_modules/ms": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", - "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" - }, - "node_modules/nock": { - "version": "13.3.1", - "resolved": "https://registry.npmjs.org/nock/-/nock-13.3.1.tgz", - "integrity": "sha512-vHnopocZuI93p2ccivFyGuUfzjq2fxNyNurp7816mlT5V5HF4SzXu8lvLrVzBbNqzs+ODooZ6OksuSUNM7Njkw==", - "dependencies": { - "debug": "^4.1.0", - "json-stringify-safe": "^5.0.1", - "lodash": "^4.17.21", - "propagate": "^2.0.0" - }, - "engines": { - "node": ">= 10.13" - } - }, - "node_modules/node-domexception": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/node-domexception/-/node-domexception-1.0.0.tgz", - "integrity": "sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/jimmywarting" - }, - { - "type": "github", - "url": "https://paypal.me/jimmywarting" - } - ], - "engines": { - "node": ">=10.5.0" - } - }, - "node_modules/node-fetch": { - "version": "3.3.1", - "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-3.3.1.tgz", - "integrity": "sha512-cRVc/kyto/7E5shrWca1Wsea4y6tL9iYJE5FBCius3JQfb/4P4I295PfhgbJQBLTx6lATE4z+wK0rPM4VS2uow==", - "dependencies": { - "data-uri-to-buffer": "^4.0.0", - "fetch-blob": "^3.1.4", - "formdata-polyfill": "^4.0.10" - }, - "engines": { - "node": "^12.20.0 || ^14.13.1 || >=16.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/node-fetch" - } - }, - "node_modules/pako": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/pako/-/pako-2.1.0.tgz", - "integrity": "sha512-w+eufiZ1WuJYgPXbV/PO3NCMEc3xqylkKHzp8bxp1uW4qaSNQUkwmLLEc3kKsfz8lpV1F8Ht3U1Cm+9Srog2ug==", - "optional": true - }, - "node_modules/propagate": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/propagate/-/propagate-2.0.1.tgz", - "integrity": "sha512-vGrhOavPSTz4QVNuBNdcNXePNdNMaO1xj9yBeH1ScQPjk/rhg9sSlCXPhMkFuaNNW/syTvYqsnbIJxMBfRbbag==", - "engines": { - "node": ">= 8" - } - }, - "node_modules/rxjs": { - "version": "7.8.1", - "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-7.8.1.tgz", - "integrity": "sha512-AA3TVj+0A2iuIoQkWEK/tqFjBq2j+6PO6Y0zJcvzLAFhEFIO3HL0vls9hWLncZbAAbK0mar7oZ4V079I/qPMxg==", - "dependencies": { - "tslib": "^2.1.0" - } - }, - "node_modules/smoldot": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/smoldot/-/smoldot-1.0.4.tgz", - "integrity": "sha512-N3TazI1C4GGrseFH/piWyZCCCRJTRx2QhDfrUKRT4SzILlW5m8ayZ3QTKICcz1C/536T9cbHHJyP7afxI6Mi1A==", - "optional": true, - "dependencies": { - "pako": "^2.0.4", - "ws": "^8.8.1" - } - }, - "node_modules/tslib": { - "version": "2.5.3", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.5.3.tgz", - "integrity": "sha512-mSxlJJwl3BMEQCUNnxXBU9jP4JBktcEGhURcPR6VQVlnP0FdDEsIaz0C35dXNGLyRfrATNofF0F5p2KPxQgB+w==" - }, - "node_modules/web-streams-polyfill": { - "version": "3.2.1", - "resolved": "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-3.2.1.tgz", - "integrity": "sha512-e0MO3wdXWKrLbL0DgGnUV7WHVuw9OUvL4hjgnPkIeEvESk74gAITi5G606JtZPp39cd8HA9VQzCIvA49LpPN5Q==", - "engines": { - "node": ">= 8" - } - }, - "node_modules/ws": { - "version": "8.13.0", - "resolved": "https://registry.npmjs.org/ws/-/ws-8.13.0.tgz", - "integrity": "sha512-x9vcZYTrFPC7aSIbj7sRCYo7L/Xb8Iy+pW0ng0wt2vCJv7M9HOMy0UoN3rr+IFC7hb7vXoqS+P9ktyLLLhO+LA==", - "engines": { - "node": ">=10.0.0" - }, - "peerDependencies": { - "bufferutil": "^4.0.1", - "utf-8-validate": ">=5.0.2" - }, - "peerDependenciesMeta": { - "bufferutil": { - "optional": true - }, - "utf-8-validate": { - "optional": true - } - } - } - }, - "dependencies": { - "@noble/curves": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/@noble/curves/-/curves-1.1.0.tgz", - "integrity": "sha512-091oBExgENk/kGj3AZmtBDMpxQPDtxQABR2B9lb1JbVTs6ytdzZNwvhxQ4MWasRNEzlbEH8jCWFCwhF/Obj5AA==", - "requires": { - "@noble/hashes": "1.3.1" - } - }, - "@noble/hashes": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.3.1.tgz", - "integrity": "sha512-EbqwksQwz9xDRGfDST86whPBgM65E0OH/pCgqW0GBVzO22bNE+NuIbeTb714+IfSjU3aRk47EUvXIb5bTsenKA==" - }, - "@polkadot/api": { - "version": "10.9.1", - "resolved": "https://registry.npmjs.org/@polkadot/api/-/api-10.9.1.tgz", - "integrity": "sha512-ND/2UqZBWvtt4PfV03OStTKg0mxmPk4UpMAgJKutdgsz/wP9CYJ1KbjwFgPNekL9JnzbKQsWyQNPVrcw7kQk8A==", - "requires": { - "@polkadot/api-augment": "10.9.1", - "@polkadot/api-base": "10.9.1", - "@polkadot/api-derive": "10.9.1", - "@polkadot/keyring": "^12.3.1", - "@polkadot/rpc-augment": "10.9.1", - "@polkadot/rpc-core": "10.9.1", - "@polkadot/rpc-provider": "10.9.1", - "@polkadot/types": "10.9.1", - "@polkadot/types-augment": "10.9.1", - "@polkadot/types-codec": "10.9.1", - "@polkadot/types-create": "10.9.1", - "@polkadot/types-known": "10.9.1", - "@polkadot/util": "^12.3.1", - "@polkadot/util-crypto": "^12.3.1", - "eventemitter3": "^5.0.1", - "rxjs": "^7.8.1", - "tslib": "^2.5.3" - } - }, - "@polkadot/api-augment": { - "version": "10.9.1", - "resolved": "https://registry.npmjs.org/@polkadot/api-augment/-/api-augment-10.9.1.tgz", - "integrity": "sha512-kRZZvCFVcN4hAH4dJ+Qzfdy27/4EEq3oLDf3ihj0LTVrAezSWcKPGE3EVFy+Mn6Lo4SUc7RVyoKvIUhSk2l4Dg==", - "requires": { - "@polkadot/api-base": "10.9.1", - "@polkadot/rpc-augment": "10.9.1", - "@polkadot/types": "10.9.1", - "@polkadot/types-augment": "10.9.1", - "@polkadot/types-codec": "10.9.1", - "@polkadot/util": "^12.3.1", - "tslib": "^2.5.3" - } - }, - "@polkadot/api-base": { - "version": "10.9.1", - "resolved": "https://registry.npmjs.org/@polkadot/api-base/-/api-base-10.9.1.tgz", - "integrity": "sha512-Q3m2KzlceMK2kX8bhnUZWk3RT6emmijeeFZZQgCePpEcrSeNjnqG4qjuTPgkveaOkUT8MAoDc5Avuzcc2jlW9g==", - "requires": { - "@polkadot/rpc-core": "10.9.1", - "@polkadot/types": "10.9.1", - "@polkadot/util": "^12.3.1", - "rxjs": "^7.8.1", - "tslib": "^2.5.3" - } - }, - "@polkadot/api-derive": { - "version": "10.9.1", - "resolved": "https://registry.npmjs.org/@polkadot/api-derive/-/api-derive-10.9.1.tgz", - "integrity": "sha512-mRud1UZCFIc4Z63qAoGSIHh/foyUYADfy1RQYCmPpeFKfIdCIrHpd7xFdJXTOMYOS0BwlM6u4qli/ZT4XigezQ==", - "requires": { - "@polkadot/api": "10.9.1", - "@polkadot/api-augment": "10.9.1", - "@polkadot/api-base": "10.9.1", - "@polkadot/rpc-core": "10.9.1", - "@polkadot/types": "10.9.1", - "@polkadot/types-codec": "10.9.1", - "@polkadot/util": "^12.3.1", - "@polkadot/util-crypto": "^12.3.1", - "rxjs": "^7.8.1", - "tslib": "^2.5.3" - } - }, - "@polkadot/keyring": { - "version": "12.3.2", - "resolved": "https://registry.npmjs.org/@polkadot/keyring/-/keyring-12.3.2.tgz", - "integrity": "sha512-NTdtDeI0DP9l/45hXynNABeP5VB8piw5YR+CbUxK2e36xpJWVXwbcOepzslg5ghE9rs8UKJb30Z/HqTU4sBY0Q==", - "requires": { - "@polkadot/util": "12.3.2", - "@polkadot/util-crypto": "12.3.2", - "tslib": "^2.5.3" - } - }, - "@polkadot/networks": { - "version": "12.3.2", - "resolved": "https://registry.npmjs.org/@polkadot/networks/-/networks-12.3.2.tgz", - "integrity": "sha512-uCkyybKoeEm1daKr0uT/9oNDHDDzCy2/ZdVl346hQqfdR1Ct3BaxMjxqvdmb5N8aCw0cBWSfgsxAYtw8ESmllQ==", - "requires": { - "@polkadot/util": "12.3.2", - "@substrate/ss58-registry": "^1.40.0", - "tslib": "^2.5.3" - } - }, - "@polkadot/rpc-augment": { - "version": "10.9.1", - "resolved": "https://registry.npmjs.org/@polkadot/rpc-augment/-/rpc-augment-10.9.1.tgz", - "integrity": "sha512-MaLHkNlyqN20ZRYr6uNd1BZr1OsrnX9qLAmsl0mcrri1vPGRH6VHjfFH1RBLkikpWD82v17g0l2hLwdV1ZHMcw==", - "requires": { - "@polkadot/rpc-core": "10.9.1", - "@polkadot/types": "10.9.1", - "@polkadot/types-codec": "10.9.1", - "@polkadot/util": "^12.3.1", - "tslib": "^2.5.3" - } - }, - "@polkadot/rpc-core": { - "version": "10.9.1", - "resolved": "https://registry.npmjs.org/@polkadot/rpc-core/-/rpc-core-10.9.1.tgz", - "integrity": "sha512-ZtA8B8SfXSAwVkBlCcKRHw0eSM7ec/sbiNOM5GasXPeRujUgT7lOwSH2GbUZSqe9RfRDMp6DvO9c2JoGc3LLWw==", - "requires": { - "@polkadot/rpc-augment": "10.9.1", - "@polkadot/rpc-provider": "10.9.1", - "@polkadot/types": "10.9.1", - "@polkadot/util": "^12.3.1", - "rxjs": "^7.8.1", - "tslib": "^2.5.3" - } - }, - "@polkadot/rpc-provider": { - "version": "10.9.1", - "resolved": "https://registry.npmjs.org/@polkadot/rpc-provider/-/rpc-provider-10.9.1.tgz", - "integrity": "sha512-4QzT2QzD+320+eT6b79sGAA85Tt3Bb8fQvse4r5Mom2iiBd2SO81vOhxSAOaIe4GUsw25VzFJmsbe7+OObItdg==", - "requires": { - "@polkadot/keyring": "^12.3.1", - "@polkadot/types": "10.9.1", - "@polkadot/types-support": "10.9.1", - "@polkadot/util": "^12.3.1", - "@polkadot/util-crypto": "^12.3.1", - "@polkadot/x-fetch": "^12.3.1", - "@polkadot/x-global": "^12.3.1", - "@polkadot/x-ws": "^12.3.1", - "@substrate/connect": "0.7.26", - "eventemitter3": "^5.0.1", - "mock-socket": "^9.2.1", - "nock": "^13.3.1", - "tslib": "^2.5.3" - } - }, - "@polkadot/types": { - "version": "10.9.1", - "resolved": "https://registry.npmjs.org/@polkadot/types/-/types-10.9.1.tgz", - "integrity": "sha512-AG33i2ZGGfq7u+5rkAdGrXAQHHl844/Yv+junH5ZzX69xiCoWO1bH/yzDUNBdpki2GlACWvF9nLYh3F2tVF93w==", - "requires": { - "@polkadot/keyring": "^12.3.1", - "@polkadot/types-augment": "10.9.1", - "@polkadot/types-codec": "10.9.1", - "@polkadot/types-create": "10.9.1", - "@polkadot/util": "^12.3.1", - "@polkadot/util-crypto": "^12.3.1", - "rxjs": "^7.8.1", - "tslib": "^2.5.3" - } - }, - "@polkadot/types-augment": { - "version": "10.9.1", - "resolved": "https://registry.npmjs.org/@polkadot/types-augment/-/types-augment-10.9.1.tgz", - "integrity": "sha512-OY9/jTMFRFqYdkUnfcGwqMLC64A0Q25bjvCuVQCVjsPFKE3wl0Kt5rNT01eV2UmLXrR6fY0xWbR2w80bLA7CIQ==", - "requires": { - "@polkadot/types": "10.9.1", - "@polkadot/types-codec": "10.9.1", - "@polkadot/util": "^12.3.1", - "tslib": "^2.5.3" - } - }, - "@polkadot/types-codec": { - "version": "10.9.1", - "resolved": "https://registry.npmjs.org/@polkadot/types-codec/-/types-codec-10.9.1.tgz", - "integrity": "sha512-mJ5OegKGraY1FLvEa8FopRCr3pQrhDkcn5RNOjmgJQozENVeRaxhk0NwxYz7IojFvSDnKnc6lNQfKaaSe5pLHg==", - "requires": { - "@polkadot/util": "^12.3.1", - "@polkadot/x-bigint": "^12.3.1", - "tslib": "^2.5.3" - } - }, - "@polkadot/types-create": { - "version": "10.9.1", - "resolved": "https://registry.npmjs.org/@polkadot/types-create/-/types-create-10.9.1.tgz", - "integrity": "sha512-OVz50MGTTuiuVnRP/zAx4CTuLioc0hsiwNwqN2lNhmIJGtnQ4Vy/7mQRsIWehiYz6g0Vzzm5B3qWkTXO1NSN5w==", - "requires": { - "@polkadot/types-codec": "10.9.1", - "@polkadot/util": "^12.3.1", - "tslib": "^2.5.3" - } - }, - "@polkadot/types-known": { - "version": "10.9.1", - "resolved": "https://registry.npmjs.org/@polkadot/types-known/-/types-known-10.9.1.tgz", - "integrity": "sha512-zCMVWc4pJtkbMFPu72bD4IhvV/gkHXPX3C5uu92WdmCfnn0vEIEsMKWlVXVVvQQZKAqvs/awpqIfrUtEViOGEA==", - "requires": { - "@polkadot/networks": "^12.3.1", - "@polkadot/types": "10.9.1", - "@polkadot/types-codec": "10.9.1", - "@polkadot/types-create": "10.9.1", - "@polkadot/util": "^12.3.1", - "tslib": "^2.5.3" - } - }, - "@polkadot/types-support": { - "version": "10.9.1", - "resolved": "https://registry.npmjs.org/@polkadot/types-support/-/types-support-10.9.1.tgz", - "integrity": "sha512-XsieuLDsszvMZQlleacQBfx07i/JkwQV/UxH9q8Hz7Okmaz9pEVEW1h3ka2/cPuC7a4l32JhaORBUYshBZNdJg==", - "requires": { - "@polkadot/util": "^12.3.1", - "tslib": "^2.5.3" - } - }, - "@polkadot/util": { - "version": "12.3.2", - "resolved": "https://registry.npmjs.org/@polkadot/util/-/util-12.3.2.tgz", - "integrity": "sha512-y/JShcGyOamCUiSIg++XZuLHt1ktSKBaSH2K5Nw5NXlgP0+7am+GZzqPB8fQ4qhYLruEOv+YRiz0GC1Zr9S+wg==", - "requires": { - "@polkadot/x-bigint": "12.3.2", - "@polkadot/x-global": "12.3.2", - "@polkadot/x-textdecoder": "12.3.2", - "@polkadot/x-textencoder": "12.3.2", - "@types/bn.js": "^5.1.1", - "bn.js": "^5.2.1", - "tslib": "^2.5.3" - } - }, - "@polkadot/util-crypto": { - "version": "12.3.2", - "resolved": "https://registry.npmjs.org/@polkadot/util-crypto/-/util-crypto-12.3.2.tgz", - "integrity": "sha512-pTpx+YxolY0BDT4RcGmgeKbHHD/dI6Ll9xRsqmVdIjpcVVY20uDNTyXs81ZNtfKgyod1y9JQkfNv2Dz9iEpTkQ==", - "requires": { - "@noble/curves": "1.1.0", - "@noble/hashes": "1.3.1", - "@polkadot/networks": "12.3.2", - "@polkadot/util": "12.3.2", - "@polkadot/wasm-crypto": "^7.2.1", - "@polkadot/wasm-util": "^7.2.1", - "@polkadot/x-bigint": "12.3.2", - "@polkadot/x-randomvalues": "12.3.2", - "@scure/base": "1.1.1", - "tslib": "^2.5.3" - } - }, - "@polkadot/wasm-bridge": { - "version": "7.2.1", - "resolved": "https://registry.npmjs.org/@polkadot/wasm-bridge/-/wasm-bridge-7.2.1.tgz", - "integrity": "sha512-uV/LHREDBGBbHrrv7HTki+Klw0PYZzFomagFWII4lp6Toj/VCvRh5WMzooVC+g/XsBGosAwrvBhoModabyHx+A==", - "requires": { - "@polkadot/wasm-util": "7.2.1", - "tslib": "^2.5.0" - } - }, - "@polkadot/wasm-crypto": { - "version": "7.2.1", - "resolved": "https://registry.npmjs.org/@polkadot/wasm-crypto/-/wasm-crypto-7.2.1.tgz", - "integrity": "sha512-SA2+33S9TAwGhniKgztVN6pxUKpGfN4Tre/eUZGUfpgRkT92wIUT2GpGWQE+fCCqGQgADrNiBcwt6XwdPqMQ4Q==", - "requires": { - "@polkadot/wasm-bridge": "7.2.1", - "@polkadot/wasm-crypto-asmjs": "7.2.1", - "@polkadot/wasm-crypto-init": "7.2.1", - "@polkadot/wasm-crypto-wasm": "7.2.1", - "@polkadot/wasm-util": "7.2.1", - "tslib": "^2.5.0" - } - }, - "@polkadot/wasm-crypto-asmjs": { - "version": "7.2.1", - "resolved": "https://registry.npmjs.org/@polkadot/wasm-crypto-asmjs/-/wasm-crypto-asmjs-7.2.1.tgz", - "integrity": "sha512-z/d21bmxyVfkzGsKef/FWswKX02x5lK97f4NPBZ9XBeiFkmzlXhdSnu58/+b1sKsRAGdW/Rn/rTNRDhW0GqCAg==", - "requires": { - "tslib": "^2.5.0" - } - }, - "@polkadot/wasm-crypto-init": { - "version": "7.2.1", - "resolved": "https://registry.npmjs.org/@polkadot/wasm-crypto-init/-/wasm-crypto-init-7.2.1.tgz", - "integrity": "sha512-GcEXtwN9LcSf32V9zSaYjHImFw16hCyo2Xzg4GLLDPPeaAAfbFr2oQMgwyDbvBrBjLKHVHjsPZyGhXae831amw==", - "requires": { - "@polkadot/wasm-bridge": "7.2.1", - "@polkadot/wasm-crypto-asmjs": "7.2.1", - "@polkadot/wasm-crypto-wasm": "7.2.1", - "@polkadot/wasm-util": "7.2.1", - "tslib": "^2.5.0" - } - }, - "@polkadot/wasm-crypto-wasm": { - "version": "7.2.1", - "resolved": "https://registry.npmjs.org/@polkadot/wasm-crypto-wasm/-/wasm-crypto-wasm-7.2.1.tgz", - "integrity": "sha512-DqyXE4rSD0CVlLIw88B58+HHNyrvm+JAnYyuEDYZwCvzUWOCNos/DDg9wi/K39VAIsCCKDmwKqkkfIofuOj/lA==", - "requires": { - "@polkadot/wasm-util": "7.2.1", - "tslib": "^2.5.0" - } - }, - "@polkadot/wasm-util": { - "version": "7.2.1", - "resolved": "https://registry.npmjs.org/@polkadot/wasm-util/-/wasm-util-7.2.1.tgz", - "integrity": "sha512-FBSn/3aYJzhN0sYAYhHB8y9JL8mVgxLy4M1kUXYbyo+8GLRQEN5rns8Vcb8TAlIzBWgVTOOptYBvxo0oj0h7Og==", - "requires": { - "tslib": "^2.5.0" - } - }, - "@polkadot/x-bigint": { - "version": "12.3.2", - "resolved": "https://registry.npmjs.org/@polkadot/x-bigint/-/x-bigint-12.3.2.tgz", - "integrity": "sha512-JLqLgfGXe/x+hZJETd5ZqfpVsbwyMsH5Nn1Q20ineMMjXN/ig+kVR8Mc15LXBMuw4g7LldFW6UUrotWnuMI8Yw==", - "requires": { - "@polkadot/x-global": "12.3.2", - "tslib": "^2.5.3" - } - }, - "@polkadot/x-fetch": { - "version": "12.3.2", - "resolved": "https://registry.npmjs.org/@polkadot/x-fetch/-/x-fetch-12.3.2.tgz", - "integrity": "sha512-3IEuZ5S+RI/t33NsdPLIIa5COfDCfpUW2sbaByEczn75aD1jLqJZSEDwiBniJ2osyNd4uUxBf6e5jw7LAZeZJg==", - "requires": { - "@polkadot/x-global": "12.3.2", - "node-fetch": "^3.3.1", - "tslib": "^2.5.3" - } - }, - "@polkadot/x-global": { - "version": "12.3.2", - "resolved": "https://registry.npmjs.org/@polkadot/x-global/-/x-global-12.3.2.tgz", - "integrity": "sha512-yVZq6oIegjlyh5rUZiTklgu+fL+W/DG1ypEa02683tUCB3avV5cA3PAHKptMSlb6FpweHu37lKKrqfAWrraDxg==", - "requires": { - "tslib": "^2.5.3" - } - }, - "@polkadot/x-randomvalues": { - "version": "12.3.2", - "resolved": "https://registry.npmjs.org/@polkadot/x-randomvalues/-/x-randomvalues-12.3.2.tgz", - "integrity": "sha512-ywjIs8CWpvOGmq+3cGCNPOHxAjPHdBUiXyDccftx5BRVdmtbt36gK/V84bKr6Xs73FGu0jprUAOSRRsLZX/3dg==", - "requires": { - "@polkadot/x-global": "12.3.2", - "tslib": "^2.5.3" - } - }, - "@polkadot/x-textdecoder": { - "version": "12.3.2", - "resolved": "https://registry.npmjs.org/@polkadot/x-textdecoder/-/x-textdecoder-12.3.2.tgz", - "integrity": "sha512-lY5bfA5xArJRWEJlYOlQQMJeTjWD8s0yMhchirVgf5xj8Id9vPGeUoneH+VFDEwgXxrqBvDFJ4smN4T/r6a/fg==", - "requires": { - "@polkadot/x-global": "12.3.2", - "tslib": "^2.5.3" - } - }, - "@polkadot/x-textencoder": { - "version": "12.3.2", - "resolved": "https://registry.npmjs.org/@polkadot/x-textencoder/-/x-textencoder-12.3.2.tgz", - "integrity": "sha512-iP3qEBiHzBckQ9zeY7ZHRWuu7mCEg5SMpOugs6UODRk8sx6KHzGQYlghBbWLit0uppPDVE0ifEwZ2n73djJHWQ==", - "requires": { - "@polkadot/x-global": "12.3.2", - "tslib": "^2.5.3" - } - }, - "@polkadot/x-ws": { - "version": "12.3.2", - "resolved": "https://registry.npmjs.org/@polkadot/x-ws/-/x-ws-12.3.2.tgz", - "integrity": "sha512-yM9Z64pLNlHpJE43+Xtr+iUXmYpFFY5u5hrke2PJt13O48H8f9Vb9cRaIh94appLyICoS0aekGhDkGH+MCspBA==", - "requires": { - "@polkadot/x-global": "12.3.2", - "tslib": "^2.5.3", - "ws": "^8.13.0" - } - }, - "@scure/base": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/@scure/base/-/base-1.1.1.tgz", - "integrity": "sha512-ZxOhsSyxYwLJj3pLZCefNitxsj093tb2vq90mp2txoYeBqbcjDjqFhyM8eUjq/uFm6zJ+mUuqxlS2FkuSY1MTA==" - }, - "@substrate/connect": { - "version": "0.7.26", - "resolved": "https://registry.npmjs.org/@substrate/connect/-/connect-0.7.26.tgz", - "integrity": "sha512-uuGSiroGuKWj1+38n1kY5HReer5iL9bRwPCzuoLtqAOmI1fGI0hsSI2LlNQMAbfRgr7VRHXOk5MTuQf5ulsFRw==", - "optional": true, - "requires": { - "@substrate/connect-extension-protocol": "^1.0.1", - "eventemitter3": "^4.0.7", - "smoldot": "1.0.4" - }, - "dependencies": { - "eventemitter3": { - "version": "4.0.7", - "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-4.0.7.tgz", - "integrity": "sha512-8guHBZCwKnFhYdHr2ysuRWErTwhoN2X8XELRlrRwpmfeY2jjuUN4taQMsULKUVo1K4DvZl+0pgfyoysHxvmvEw==", - "optional": true - } - } - }, - "@substrate/connect-extension-protocol": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/@substrate/connect-extension-protocol/-/connect-extension-protocol-1.0.1.tgz", - "integrity": "sha512-161JhCC1csjH3GE5mPLEd7HbWtwNSPJBg3p1Ksz9SFlTzj/bgEwudiRN2y5i0MoLGCIJRYKyKGMxVnd29PzNjg==", - "optional": true - }, - "@substrate/ss58-registry": { - "version": "1.40.0", - "resolved": "https://registry.npmjs.org/@substrate/ss58-registry/-/ss58-registry-1.40.0.tgz", - "integrity": "sha512-QuU2nBql3J4KCnOWtWDw4n1K4JU0T79j54ZZvm/9nhsX6AIar13FyhsaBfs6QkJ2ixTQAnd7TocJIoJRWbqMZA==" - }, - "@types/bn.js": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/@types/bn.js/-/bn.js-5.1.1.tgz", - "integrity": "sha512-qNrYbZqMx0uJAfKnKclPh+dTwK33KfLHYqtyODwd5HnXOjnkhc4qgn3BrK6RWyGZm5+sIFE7Q7Vz6QQtJB7w7g==", - "requires": { - "@types/node": "*" - } - }, - "@types/node": { - "version": "20.3.1", - "resolved": "https://registry.npmjs.org/@types/node/-/node-20.3.1.tgz", - "integrity": "sha512-EhcH/wvidPy1WeML3TtYFGR83UzjxeWRen9V402T8aUGYsCHOmfoisV3ZSg03gAFIbLq8TnWOJ0f4cALtnSEUg==" - }, - "bn.js": { - "version": "5.2.1", - "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-5.2.1.tgz", - "integrity": "sha512-eXRvHzWyYPBuB4NBy0cmYQjGitUrtqwbvlzP3G6VFnNRbsZQIxQ10PbKKHt8gZ/HW/D/747aDl+QkDqg3KQLMQ==" - }, - "data-uri-to-buffer": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-4.0.1.tgz", - "integrity": "sha512-0R9ikRb668HB7QDxT1vkpuUBtqc53YyAwMwGeUFKRojY/NWKvdZ+9UYtRfGmhqNbRkTSVpMbmyhXipFFv2cb/A==" - }, - "debug": { - "version": "4.3.4", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz", - "integrity": "sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==", - "requires": { - "ms": "2.1.2" - } - }, - "eventemitter3": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-5.0.1.tgz", - "integrity": "sha512-GWkBvjiSZK87ELrYOSESUYeVIc9mvLLf/nXalMOS5dYrgZq9o5OVkbZAVM06CVxYsCwH9BDZFPlQTlPA1j4ahA==" - }, - "fetch-blob": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/fetch-blob/-/fetch-blob-3.2.0.tgz", - "integrity": "sha512-7yAQpD2UMJzLi1Dqv7qFYnPbaPx7ZfFK6PiIxQ4PfkGPyNyl2Ugx+a/umUonmKqjhM4DnfbMvdX6otXq83soQQ==", - "requires": { - "node-domexception": "^1.0.0", - "web-streams-polyfill": "^3.0.3" - } - }, - "formdata-polyfill": { - "version": "4.0.10", - "resolved": "https://registry.npmjs.org/formdata-polyfill/-/formdata-polyfill-4.0.10.tgz", - "integrity": "sha512-buewHzMvYL29jdeQTVILecSaZKnt/RJWjoZCF5OW60Z67/GmSLBkOFM7qh1PI3zFNtJbaZL5eQu1vLfazOwj4g==", - "requires": { - "fetch-blob": "^3.1.2" - } - }, - "json-stringify-safe": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz", - "integrity": "sha512-ZClg6AaYvamvYEE82d3Iyd3vSSIjQ+odgjaTzRuO3s7toCdFKczob2i0zCh7JE8kWn17yvAWhUVxvqGwUalsRA==" - }, - "lodash": { - "version": "4.17.21", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", - "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==" - }, - "mock-socket": { - "version": "9.2.1", - "resolved": "https://registry.npmjs.org/mock-socket/-/mock-socket-9.2.1.tgz", - "integrity": "sha512-aw9F9T9G2zpGipLLhSNh6ZpgUyUl4frcVmRN08uE1NWPWg43Wx6+sGPDbQ7E5iFZZDJW5b5bypMeAEHqTbIFag==" - }, - "ms": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", - "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" - }, - "nock": { - "version": "13.3.1", - "resolved": "https://registry.npmjs.org/nock/-/nock-13.3.1.tgz", - "integrity": "sha512-vHnopocZuI93p2ccivFyGuUfzjq2fxNyNurp7816mlT5V5HF4SzXu8lvLrVzBbNqzs+ODooZ6OksuSUNM7Njkw==", - "requires": { - "debug": "^4.1.0", - "json-stringify-safe": "^5.0.1", - "lodash": "^4.17.21", - "propagate": "^2.0.0" - } - }, - "node-domexception": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/node-domexception/-/node-domexception-1.0.0.tgz", - "integrity": "sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==" - }, - "node-fetch": { - "version": "3.3.1", - "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-3.3.1.tgz", - "integrity": "sha512-cRVc/kyto/7E5shrWca1Wsea4y6tL9iYJE5FBCius3JQfb/4P4I295PfhgbJQBLTx6lATE4z+wK0rPM4VS2uow==", - "requires": { - "data-uri-to-buffer": "^4.0.0", - "fetch-blob": "^3.1.4", - "formdata-polyfill": "^4.0.10" - } - }, - "pako": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/pako/-/pako-2.1.0.tgz", - "integrity": "sha512-w+eufiZ1WuJYgPXbV/PO3NCMEc3xqylkKHzp8bxp1uW4qaSNQUkwmLLEc3kKsfz8lpV1F8Ht3U1Cm+9Srog2ug==", - "optional": true - }, - "propagate": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/propagate/-/propagate-2.0.1.tgz", - "integrity": "sha512-vGrhOavPSTz4QVNuBNdcNXePNdNMaO1xj9yBeH1ScQPjk/rhg9sSlCXPhMkFuaNNW/syTvYqsnbIJxMBfRbbag==" - }, - "rxjs": { - "version": "7.8.1", - "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-7.8.1.tgz", - "integrity": "sha512-AA3TVj+0A2iuIoQkWEK/tqFjBq2j+6PO6Y0zJcvzLAFhEFIO3HL0vls9hWLncZbAAbK0mar7oZ4V079I/qPMxg==", - "requires": { - "tslib": "^2.1.0" - } - }, - "smoldot": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/smoldot/-/smoldot-1.0.4.tgz", - "integrity": "sha512-N3TazI1C4GGrseFH/piWyZCCCRJTRx2QhDfrUKRT4SzILlW5m8ayZ3QTKICcz1C/536T9cbHHJyP7afxI6Mi1A==", - "optional": true, - "requires": { - "pako": "^2.0.4", - "ws": "^8.8.1" - } - }, - "tslib": { - "version": "2.5.3", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.5.3.tgz", - "integrity": "sha512-mSxlJJwl3BMEQCUNnxXBU9jP4JBktcEGhURcPR6VQVlnP0FdDEsIaz0C35dXNGLyRfrATNofF0F5p2KPxQgB+w==" - }, - "web-streams-polyfill": { - "version": "3.2.1", - "resolved": "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-3.2.1.tgz", - "integrity": "sha512-e0MO3wdXWKrLbL0DgGnUV7WHVuw9OUvL4hjgnPkIeEvESk74gAITi5G606JtZPp39cd8HA9VQzCIvA49LpPN5Q==" - }, - "ws": { - "version": "8.13.0", - "resolved": "https://registry.npmjs.org/ws/-/ws-8.13.0.tgz", - "integrity": "sha512-x9vcZYTrFPC7aSIbj7sRCYo7L/Xb8Iy+pW0ng0wt2vCJv7M9HOMy0UoN3rr+IFC7hb7vXoqS+P9ktyLLLhO+LA==", - "requires": {} - } - } -} diff --git a/tee-worker/bitacross/scripts/test_transfer/package.json b/tee-worker/bitacross/scripts/test_transfer/package.json deleted file mode 100644 index a3e2b769b8..0000000000 --- a/tee-worker/bitacross/scripts/test_transfer/package.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "name": "test_transfer", - "version": "1.0.0", - "description": "", - "main": "index.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "author": "", - "license": "ISC", - "dependencies": { - "@polkadot/api": "^10.9.1", - "@polkadot/keyring": "^12.3.2", - "@polkadot/util-crypto": "^12.3.2" - } -} diff --git a/tee-worker/bitacross/scripts/test_transfer/transfer.js b/tee-worker/bitacross/scripts/test_transfer/transfer.js deleted file mode 100644 index ed0801fb68..0000000000 --- a/tee-worker/bitacross/scripts/test_transfer/transfer.js +++ /dev/null @@ -1,53 +0,0 @@ -// Import the API & Provider and some utility functions -const { ApiPromise } = require('@polkadot/api'); - -const { Keyring } = require('@polkadot/keyring'); - -// Utility function for random values -const { randomAsU8a } = require('@polkadot/util-crypto'); - -// Some constants we are using in this sample -const AMOUNT = 1000000000000; - -async function main () { - // Create the API and wait until ready - const api = await ApiPromise.create(); - - // Create an instance of a testing keyring - const keyring = new Keyring({ type: 'sr25519', ss58Format: 42 }); - const alice = keyring.addFromUri('//Alice'); - - // Access the publicKey and address - const { publicKey, address } = alice; - - console.log('Alice Public Key:', publicKey); - console.log('Alice Address:', address); - - const { nonce, data: balance } = await api.query.system.account(publicKey); - - // Create a new random recipient - const recipient = keyring.addFromSeed(randomAsU8a(32)).address; - - console.log('Sending', AMOUNT, 'from', address, 'who has a balance of', balance.free, 'to', recipient, 'with nonce', nonce.toString()); - - api.tx.balances - .transferKeepAlive(recipient, AMOUNT) - .signAndSend(alice, { nonce }, ({ events = [], status }) => { - console.log('Transaction status:', status.type); - - if (status.isInBlock) { - console.log('Included at block hash', status.asInBlock.toHex()); - console.log('Events:'); - - events.forEach(({ event: { data, method, section }, phase }) => { - console.log('\t', phase.toString(), `: ${section}.${method}`, data.toString()); - }); - } else if (status.isFinalized) { - console.log('Finalized block hash', status.asFinalized.toHex()); - - process.exit(0); - } - }); -} - -main().catch(console.error); diff --git a/tee-worker/bitacross/service/Cargo.toml b/tee-worker/bitacross/service/Cargo.toml deleted file mode 100644 index 28aa4f6ecf..0000000000 --- a/tee-worker/bitacross/service/Cargo.toml +++ /dev/null @@ -1,94 +0,0 @@ -[package] -name = 'bitacross-worker' -version = '0.1.0' -authors = ['Trust Computing GmbH ', 'Integritee AG '] -build = 'build.rs' -edition = '2021' - -[dependencies] -async-trait = "0.1.50" -base58 = "0.2" -clap = { version = "2.33", features = ["yaml"] } -codec = { package = "parity-scale-codec", workspace = true } -dirs = "3.0.2" -env_logger = { workspace = true } -futures = { workspace = true, features = ["std"] } -hex = { workspace = true, features = ["std"] } -humantime = "2.1" -jsonrpsee = { version = "0.2.0", features = ["client", "ws-server", "macros"] } -lazy_static = { workspace = true } -log = { workspace = true, features = ["std"] } -parking_lot = "0.12.1" -parse_duration = "2.1.1" -prometheus = { version = "0.13.0", features = ["process"], default-features = false } # Enabling std lead to protobuf dependency conflicts with substrate, and we don't need it. -rayon = "1.10.0" -regex = "1.9.5" -scale-info = { workspace = true } -serde = { workspace = true, features = ["std"] } -serde_derive = { workspace = true } -serde_json = { workspace = true, features = ["std"] } -thiserror = { workspace = true } -tokio = { version = "1.6.1", features = ["full"] } -url = "2.5.0" -warp = "=0.3.5" - -ipfs-api = "0.11.0" - -sgx_crypto_helper = { workspace = true, features = ["ucrypto_help"] } -sgx_types = { workspace = true } - -ita-parentchain-interface = { package = "bc-ita-parentchain-interface", path = "../app-libs/parentchain-interface" } -itc-parentchain = { package = "bc-itc-parentchain", path = "../core/parentchain/parentchain-crate" } -itc-rest-client = { workspace = true, features = ["std"] } -itc-rpc-client = { workspace = true } -itp-api-client-types = { workspace = true, features = ["std"] } -itp-enclave-api = { package = "bc-itp-enclave-api", path = "../core-primitives/enclave-api" } -itp-enclave-metrics = { workspace = true, features = ["std"] } -itp-node-api = { workspace = true, features = ["std"] } -itp-settings = { workspace = true } -itp-stf-interface = { workspace = true, features = ["std"] } -itp-storage = { workspace = true, features = ["std"] } -itp-time-utils = { workspace = true, features = ["std"] } -itp-types = { workspace = true, features = ["std"] } -itp-utils = { workspace = true, features = ["std"] } - -substrate-api-client = { workspace = true } - -frame-support = { workspace = true, features = ["std"] } -sp-consensus-grandpa = { workspace = true, features = ["std"] } -sp-core = { workspace = true, features = ["std", "full_crypto"] } -sp-keyring = { workspace = true } -sp-runtime = { workspace = true, features = ["std"] } - -# litentry -config = "0.13.3" -litentry-primitives = { workspace = true, features = ["std"] } - -[features] -default = [] -offchain-worker = ["itp-settings/offchain-worker"] -development = [ - "itp-settings/development", - "litentry-primitives/development", -] -dcap = [] -attesteer = ["dcap"] -# Must be enabled to build a binary and link it with the enclave successfully. -# This flag is set in the makefile. -# -# Must not be enabled to run cargo test without an sgx-sdk providing environment -# https://github.com/rust-lang/cargo/issues/2549. -# -# It has been chosen to not make this a default feature because this makes test execution -# more ergonomic as we can simply do `cargo test` on the whole workspace like this. -link-binary = [ - "itp-enclave-api/implement-ffi", -] - -[dev-dependencies] -# crates.io -anyhow = "1.0.40" -mockall = "0.11" -# local -itc-parentchain-test = { workspace = true, features = ["std"] } -itp-sgx-crypto = { workspace = true, features = ["std"] } diff --git a/tee-worker/bitacross/service/build.rs b/tee-worker/bitacross/service/build.rs deleted file mode 100644 index 1fb664ecc0..0000000000 --- a/tee-worker/bitacross/service/build.rs +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (C) 2017-2018 Baidu, Inc. All Rights Reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions -// are met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in -// the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Baidu, Inc., nor the names of its -// contributors may be used to endorse or promote products derived -// from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -fn main() { - // All the linker options are now defined in `itp-enclave-api-ffi` -} diff --git a/tee-worker/bitacross/service/src/account_funding.rs b/tee-worker/bitacross/service/src/account_funding.rs deleted file mode 100644 index 61a3e8780f..0000000000 --- a/tee-worker/bitacross/service/src/account_funding.rs +++ /dev/null @@ -1,182 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use crate::error::{Error, ServiceResult}; -use codec::Encode; -use itp_node_api::api_client::{AccountApi, ParentchainApi}; -use itp_settings::worker::REGISTERING_FEE_FACTOR_FOR_INIT_FUNDS; -use itp_types::{ - parentchain::{AccountId, Balance, ParentchainId}, - Moment, -}; -use log::*; -use sp_core::{ - crypto::{AccountId32, Ss58Codec}, - Pair, -}; -use sp_keyring::AccountKeyring; -use sp_runtime::{MultiAddress, Saturating}; -use std::{thread, time::Duration}; -use substrate_api_client::{ - ac_compose_macros::compose_extrinsic, ac_primitives::Bytes, extrinsic::BalancesExtrinsics, - GetBalance, GetStorage, GetTransactionPayment, SubmitAndWatch, XtStatus, -}; - -const SGX_RA_PROOF_MAX_LEN: usize = 5000; -const MAX_URL_LEN: usize = 256; -/// Information about the enclave on-chain account. -pub trait EnclaveAccountInfo { - fn free_balance(&self) -> ServiceResult; -} - -pub struct EnclaveAccountInfoProvider { - node_api: ParentchainApi, - account_id: AccountId32, -} - -impl EnclaveAccountInfo for EnclaveAccountInfoProvider { - fn free_balance(&self) -> ServiceResult { - self.node_api.get_free_balance(&self.account_id).map_err(|e| e.into()) - } -} - -impl EnclaveAccountInfoProvider { - pub fn new(node_api: ParentchainApi, account_id: AccountId32) -> Self { - EnclaveAccountInfoProvider { node_api, account_id } - } -} - -/// evaluate if the enclave should have more funds and how much more -/// in --dev mode: let Alice pay for missing funds -/// in production mode: wait for manual transfer before continuing -pub fn setup_reasonable_account_funding( - api: &ParentchainApi, - accountid: &AccountId32, - parentchain_id: ParentchainId, - is_development_mode: bool, -) -> ServiceResult<()> { - loop { - let needed = estimate_funds_needed_to_run_for_a_while(api, accountid, parentchain_id)?; - let free = api.get_free_balance(accountid)?; - let missing_funds = needed.saturating_sub(free); - - if missing_funds < needed * 2 / 3 { - return Ok(()) - } - - if is_development_mode { - info!("[{:?}] Alice will grant {:?} to {:?}", parentchain_id, missing_funds, accountid); - bootstrap_funds_from_alice(api, accountid, missing_funds)?; - } else { - error!( - "[{:?}] Enclave account needs funding. please send at least {:?} to {:?}", - parentchain_id, missing_funds, accountid - ); - thread::sleep(Duration::from_secs(10)); - } - } -} - -fn estimate_funds_needed_to_run_for_a_while( - api: &ParentchainApi, - accountid: &AccountId32, - parentchain_id: ParentchainId, -) -> ServiceResult { - let existential_deposit = api.get_existential_deposit()?; - info!("[{:?}] Existential deposit is = {:?}", parentchain_id, existential_deposit); - - let mut min_required_funds: Balance = existential_deposit; - - let transfer_fee = estimate_transfer_fee(api)?; - info!("[{:?}] a single transfer costs {:?}", parentchain_id, transfer_fee); - min_required_funds += 1000 * transfer_fee; - - // TODO(Litentry P-628): shall we charge RA fee? - info!("[{:?}] not adding RA fees for now", parentchain_id); - - info!( - "[{:?}] we estimate the funding requirement for the primary validateer (worst case) to be {:?}", - parentchain_id, - min_required_funds - ); - Ok(min_required_funds) -} - -pub fn estimate_fee(api: &ParentchainApi, encoded_extrinsic: Vec) -> Result { - let reg_fee_details = api.get_fee_details(&encoded_extrinsic.into(), None)?; - match reg_fee_details { - Some(details) => match details.inclusion_fee { - Some(fee) => Ok(fee.inclusion_fee()), - None => Err(Error::Custom( - "Inclusion fee for the registration of the enclave is None!".into(), - )), - }, - None => - Err(Error::Custom("Fee Details for the registration of the enclave is None !".into())), - } -} - -/// Alice sends some funds to the account. only for dev chains testing -fn bootstrap_funds_from_alice( - api: &ParentchainApi, - accountid: &AccountId32, - funding_amount: u128, -) -> Result<(), Error> { - let alice = AccountKeyring::Alice.pair(); - let alice_acc = AccountId32::from(*alice.public().as_array_ref()); - - let alice_free = api.get_free_balance(&alice_acc)?; - info!(" Alice's free balance = {:?}", alice_free); - let nonce = api.get_account_next_index(&alice_acc)?; - info!(" Alice's Account Nonce is {}", nonce); - - if funding_amount > alice_free { - println!( - "funding amount is too high: please change EXISTENTIAL_DEPOSIT_FACTOR_FOR_INIT_FUNDS ({:?})", - funding_amount - ); - return Err(Error::ApplicationSetup) - } - - let mut alice_signer_api = api.clone(); - alice_signer_api.set_signer(alice.into()); - - println!("[+] send extrinsic: bootstrap funding Enclave from Alice's funds"); - let xt = alice_signer_api - .balance_transfer_allow_death(MultiAddress::Id(accountid.clone()), funding_amount); - let xt_report = alice_signer_api.submit_and_watch_extrinsic_until(xt, XtStatus::Finalized)?; - info!( - "[<] L1 extrinsic success. extrinsic hash: {:?} / status: {:?}", - xt_report.extrinsic_hash, xt_report.status - ); - // Verify funds have arrived. - let free_balance = alice_signer_api.get_free_balance(accountid); - trace!("TEE's NEW free balance = {:?}", free_balance); - - Ok(()) -} - -/// precise estimation of a single transfer fee -pub fn estimate_transfer_fee(api: &ParentchainApi) -> Result { - let encoded_xt: Bytes = api - .balance_transfer_allow_death(AccountId::from([0u8; 32]).into(), 1000000000000) - .encode() - .into(); - let tx_fee = api.get_fee_details(&encoded_xt, None).unwrap().unwrap().inclusion_fee.unwrap(); - let transfer_fee = tx_fee.base_fee + tx_fee.len_fee + tx_fee.adjusted_weight_fee; - Ok(transfer_fee) -} diff --git a/tee-worker/bitacross/service/src/cli.yml b/tee-worker/bitacross/service/src/cli.yml deleted file mode 100644 index f3764fbeef..0000000000 --- a/tee-worker/bitacross/service/src/cli.yml +++ /dev/null @@ -1,212 +0,0 @@ -name: "litentry-worker" -version: "0.0.1" -about: Worker using Intel SGX TEE for litentry parachain node -authors: "Trust Computing GmbH " - -# AppSettings can be defined as a list and are **not** ascii case sensitive -settings: - - ColoredHelp - - SubcommandRequired - -# All subcommands must be listed in the 'subcommand:' object, where the key to -# the list is the name of the subcommand, and all settings for that command are -# part of a Hash -args: - - node-url: - short: u - long: node-url - help: Set the url and the protocol of the RPC endpoint. - takes_value: true - default_value: "ws://127.0.0.1" - - node-port: - short: p - long: node-port - help: Set the port of the RPC endpoint. - takes_value: true - default_value: "9944" - - target-a-parentchain-rpc-url: - long: target-a-parentchain-rpc-url - help: Set the url and the protocol of an optional Target A parentchain RPC endpoint that contains your business logic specific pallets. - takes_value: true - required: false - - target-a-parentchain-rpc-port: - long: target-a-parentchain-rpc-port - help: Set the port of the optional Target A parentchain RPC endpoint. - takes_value: true - required: false - - target-b-parentchain-rpc-url: - long: target-b-parentchain-rpc-url - help: Set the url and the protocol of an optional Target B parentchain RPC endpoint that contains your business logic specific pallets. - takes_value: true - required: false - - target-b-parentchain-rpc-port: - long: target-b-parentchain-rpc-port - help: Set the port of the optional Target B parentchain RPC endpoint. - takes_value: true - required: false - - data-dir: - short: d - long: data-dir - help: Data dir where the worker stores it's keys and other data. - takes_value: true - - ws-external: - long: ws-external - help: Set this flag in case the worker should listen to external requests. - - mu-ra-port: - short: r - long: mu-ra-port - help: Set the websocket port to listen for mu-ra requests - takes_value: true - default_value: "3443" - - trusted-worker-port: - short: P - long: trusted-worker-port - help: Set the trusted websocket port of the worker, running directly in the enclave. - takes_value: true - default_value: "2000" - - untrusted-worker-port: - short: w - long: untrusted-worker-port - help: Set the untrusted websocket port of the worker - takes_value: true - default_value: "2001" - - trusted-external-address: - short: T - long: trusted-external-address - help: Set the trusted worker address to be advertised on the parentchain. If no port is given, the same as in `trusted-worker-port` will be used. - takes_value: true - required: false - - untrusted-external-address: - short: U - long: untrusted-external-address - help: Set the untrusted worker address to be retrieved by a trusted rpc call. If no port is given, the same as in `untrusted-worker-port` will be used. - takes_value: true - required: false - - mu-ra-external-address: - short: M - long: mu-ra-external-address - help: Set the mutual remote attestation worker address to be retrieved by a trusted rpc call. If no port is given, the same as in `mu-ra-port` will be used. - takes_value: true - required: false - - enable-metrics: - long: enable-metrics - help: Enable the metrics HTTP server to serve metrics - - metrics-port: - short: i - long: metrics-port - help: Set the port on which the metrics are served. - takes_value: true - default_value: "8787" - required: false - - untrusted-http-port: - short: h - long: untrusted-http-port - help: Set the port for the untrusted HTTP server - takes_value: true - required: false - - clean-reset: - long: clean-reset - short: c - help: Cleans and purges any previous state and key files and generates them anew before starting. - - parentchain-start-block: - long: parentchain-start-block - help: Set the parentchain block number to start syncing with - takes_value: true - required: false - default_value: "0" - - ceremony-commands-thread-count: - long: ceremony-commands-thread-count - help: Number of threads to spawn for ceremony commands handling - takes_value: true - default_value: "4" - required: false - - ceremony-events-thread-count: - long: ceremony-events-thread-count - help: Number of threads to spawn for ceremony events handling - takes_value: true - default_value: "20" - required: false - -subcommands: - - run: - about: Start the litentry-worker - args: - - skip-ra: - long: skip-ra - help: skip remote attestation. Set this flag if running enclave in SW mode - - shard: - required: false - index: 1 - help: shard identifier base58 encoded. Defines the state that this worker shall operate on. Default is mrenclave - - dev: - long: dev - short: d - help: Set this flag if running in development mode to bootstrap enclave account on parentchain via //Alice. - - request-state: - long: request-state - short: r - help: Run the worker and request key and state provisioning from another worker. - - request-state: - about: (Deprecated - TODO) join a shard by requesting key provisioning from another worker - args: - - shard: - long: shard - required: false - help: shard identifier base58 encoded. Defines the state that this worker shall operate on. Default is mrenclave - - skip-ra: - long: skip-ra - help: skip remote attestation. Set this flag if running enclave in SW mode - - shielding-key: - about: Get the public RSA3072 key from the TEE to be used to encrypt requests - - signing-key: - about: Get the public ed25519 key the TEE uses to sign messages and extrinsics - - dump-ra: - about: Perform RA and dump cert to disk - - wallet: - about: Print the bitcoin and ethereum custodian wallet key information, only works in non-prod - - init-wallet: - about: Init eth, btc, ton wallets from BTC_KEY, ETH_KEY, TON_KEY env variables, only works in non-prod - - mrenclave: - about: Dump mrenclave to stdout. base58 encoded. - - init-shard: - about: Initialize new shard (do this only if you run the first worker for that shard). if shard is not specified, the MRENCLAVE is used instead - args: - - shard: - required: false - multiple: true - index: 1 - help: shard identifier base58 encoded - - migrate-shard: - about: Migrate state from old shards to the new(current) shard, which is identical to mrenclave - - test: - about: Run tests involving the enclave - takes_value: true - args: - - all: - short: a - long: all - help: Run all tests (beware, all corrupts the counter state for some whatever reason...) - takes_value: false - - unit: - short: u - long: unit - help: Run unit tests - takes_value: false - - ecall: - short: e - long: ecall - help: Run enclave ecall tests - takes_value: false - - integration: - short: i - long: integration - help: Run integration tests - takes_value: false - - provisioning-server: - long: provisioning-server - help: Run TEE server for MU-RA key provisioning - takes_value: false - - provisioning-client: - long: provisioning-client - help: Run TEE client for MU-RA key provisioning - takes_value: false diff --git a/tee-worker/bitacross/service/src/config.rs b/tee-worker/bitacross/service/src/config.rs deleted file mode 100644 index 92b37cc262..0000000000 --- a/tee-worker/bitacross/service/src/config.rs +++ /dev/null @@ -1,617 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use clap::ArgMatches; -use itc_rest_client::rest_client::Url; -use itp_types::{parentchain::ParentchainId, ShardIdentifier}; -use parse_duration::parse; -use serde::{Deserialize, Serialize}; -use std::{ - fs, - path::{Path, PathBuf}, - time::Duration, -}; - -static DEFAULT_NODE_URL: &str = "ws://127.0.0.1"; -static DEFAULT_NODE_PORT: &str = "9944"; -static DEFAULT_TRUSTED_PORT: &str = "2000"; -static DEFAULT_UNTRUSTED_PORT: &str = "2001"; -static DEFAULT_MU_RA_PORT: &str = "3443"; -static DEFAULT_METRICS_PORT: &str = "8787"; -static DEFAULT_UNTRUSTED_HTTP_PORT: &str = "4545"; -static DEFAULT_PARENTCHAIN_START_BLOCK: &str = "0"; - -#[derive(Clone, Debug, PartialEq)] -pub struct Config { - pub litentry_rpc_url: String, - pub litentry_rpc_port: String, - pub target_a_parentchain_rpc_url: Option, - pub target_a_parentchain_rpc_port: Option, - pub target_b_parentchain_rpc_url: Option, - pub target_b_parentchain_rpc_port: Option, - pub worker_ip: String, - /// Trusted worker address that will be advertised on the parentchain. - pub trusted_external_worker_address: Option, - /// Port to directly communicate with the trusted tls server inside the enclave. - pub trusted_worker_port: String, - /// Untrusted worker address that will be returned by the dedicated trusted ws rpc call. - pub untrusted_external_worker_address: Option, - /// Port to the untrusted ws of the validateer. - pub untrusted_worker_port: String, - /// Mutual remote attestation address that will be returned by the dedicated trusted ws rpc call. - pub mu_ra_external_address: Option, - /// Port for mutual-remote attestation requests. - pub mu_ra_port: String, - /// Enable the metrics server - pub enable_metrics_server: bool, - /// Port for the metrics server - pub metrics_server_port: String, - /// Port for the untrusted HTTP server (e.g. for `is_initialized`) - pub untrusted_http_port: String, - /// Data directory used by all the services. - pub data_dir: PathBuf, - /// Config of the 'run' subcommand - pub run_config: Option, - - /// the parentchain block number to start syncing with - pub parentchain_start_block: String, - - /// Number of threads to spawn for ceremony commands handling - pub ceremony_commands_thread_count: u8, - - /// Number of threads to spawn for ceremony events handling - pub ceremony_events_thread_count: u8, -} - -#[allow(clippy::too_many_arguments)] -impl Config { - pub fn new( - litentry_rpc_url: String, - litentry_rpc_port: String, - target_a_parentchain_rpc_url: Option, - target_a_parentchain_rpc_port: Option, - target_b_parentchain_rpc_url: Option, - target_b_parentchain_rpc_port: Option, - worker_ip: String, - trusted_external_worker_address: Option, - trusted_worker_port: String, - untrusted_external_worker_address: Option, - untrusted_worker_port: String, - mu_ra_external_address: Option, - mu_ra_port: String, - enable_metrics_server: bool, - metrics_server_port: String, - untrusted_http_port: String, - data_dir: PathBuf, - run_config: Option, - parentchain_start_block: String, - ceremony_commands_thread_count: u8, - ceremony_events_thread_count: u8, - ) -> Self { - Self { - litentry_rpc_url, - litentry_rpc_port, - target_a_parentchain_rpc_url, - target_a_parentchain_rpc_port, - target_b_parentchain_rpc_url, - target_b_parentchain_rpc_port, - worker_ip, - trusted_external_worker_address, - trusted_worker_port, - untrusted_external_worker_address, - untrusted_worker_port, - mu_ra_external_address, - mu_ra_port, - enable_metrics_server, - metrics_server_port, - untrusted_http_port, - data_dir, - run_config, - parentchain_start_block, - ceremony_commands_thread_count, - ceremony_events_thread_count, - } - } - - /// Integritee RPC endpoint (including ws://). - pub fn litentry_rpc_endpoint(&self) -> String { - format!("{}:{}", self.litentry_rpc_url, self.litentry_rpc_port) - } - - pub fn target_a_parentchain_rpc_endpoint(&self) -> Option { - if self.target_a_parentchain_rpc_url.is_some() - && self.target_a_parentchain_rpc_port.is_some() - { - return Some(format!( - "{}:{}", - // Can be done better, but this code is obsolete anyhow with clap v4. - self.target_a_parentchain_rpc_url.clone().unwrap(), - self.target_a_parentchain_rpc_port.clone().unwrap() - )) - }; - - None - } - - pub fn target_b_parentchain_rpc_endpoint(&self) -> Option { - if self.target_b_parentchain_rpc_url.is_some() - && self.target_b_parentchain_rpc_port.is_some() - { - return Some(format!( - "{}:{}", - // Can be done better, but this code is obsolete anyhow with clap v4. - self.target_b_parentchain_rpc_url.clone().unwrap(), - self.target_b_parentchain_rpc_port.clone().unwrap() - )) - }; - - None - } - - pub fn trusted_worker_url_internal(&self) -> String { - // use the same scheme as `trusted_worker_url_external` - let url = url::Url::parse(self.trusted_worker_url_external().as_str()).unwrap(); - format!("{}://{}:{}", url.scheme(), self.worker_ip, self.trusted_worker_port) - } - - /// Returns the trusted worker url that should be addressed by external clients. - pub fn trusted_worker_url_external(&self) -> String { - match &self.trusted_external_worker_address { - Some(external_address) => ensure_ws_or_wss(external_address), - None => format!("wss://{}:{}", self.worker_ip, self.trusted_worker_port), // fallback to wss - } - } - - pub fn untrusted_worker_url(&self) -> String { - // use the same scheme as `untrusted_worker_url_external` - let url = url::Url::parse(self.untrusted_worker_url_external().as_str()).unwrap(); - format!("{}://{}:{}", url.scheme(), self.worker_ip, self.untrusted_worker_port) - } - - /// Returns the untrusted worker url that should be addressed by external clients. - pub fn untrusted_worker_url_external(&self) -> String { - match &self.untrusted_external_worker_address { - Some(external_address) => ensure_ws_or_wss(external_address), - None => format!("ws://{}:{}", self.worker_ip, self.untrusted_worker_port), // fallback to ws - } - } - - pub fn mu_ra_url(&self) -> String { - format!("{}:{}", self.worker_ip, self.mu_ra_port) - } - - /// Returns the mutual remote attestion worker url that should be addressed by external workers. - pub fn mu_ra_url_external(&self) -> String { - match &self.mu_ra_external_address { - Some(external_address) => external_address.to_string(), - None => format!("{}:{}", self.worker_ip, self.mu_ra_port), - } - } - - pub fn data_dir(&self) -> &Path { - self.data_dir.as_path() - } - - pub fn run_config(&self) -> &Option { - &self.run_config - } - - pub fn enable_metrics_server(&self) -> bool { - self.enable_metrics_server - } - - pub fn try_parse_metrics_server_port(&self) -> Option { - self.metrics_server_port.parse::().ok() - } - - pub fn try_parse_untrusted_http_server_port(&self) -> Option { - self.untrusted_http_port.parse::().ok() - } - - pub fn try_parse_parentchain_start_block(&self) -> Option { - self.parentchain_start_block.parse::().ok() - } -} - -impl From<&ArgMatches<'_>> for Config { - fn from(m: &ArgMatches<'_>) -> Self { - let trusted_port = m.value_of("trusted-worker-port").unwrap_or(DEFAULT_TRUSTED_PORT); - let untrusted_port = m.value_of("untrusted-worker-port").unwrap_or(DEFAULT_UNTRUSTED_PORT); - let mu_ra_port = m.value_of("mu-ra-port").unwrap_or(DEFAULT_MU_RA_PORT); - let is_metrics_server_enabled = m.is_present("enable-metrics"); - let metrics_server_port = m.value_of("metrics-port").unwrap_or(DEFAULT_METRICS_PORT); - let untrusted_http_port = - m.value_of("untrusted-http-port").unwrap_or(DEFAULT_UNTRUSTED_HTTP_PORT); - - let data_dir = match m.value_of("data-dir") { - Some(d) => { - let p = PathBuf::from(d); - if !p.exists() { - log::info!("Creating new data-directory for the service {}.", p.display()); - fs::create_dir_all(p.as_path()).unwrap(); - } else { - log::info!("Starting service in existing directory {}.", p.display()); - } - p - }, - None => { - log::warn!("[Config] defaulting to data-dir = PWD because it was previous behaviour. This might change soon.\ - Please pass the data-dir explicitly to ensure nothing breaks in your setup."); - pwd() - }, - }; - - let run_config = m.subcommand_matches("run").map(RunConfig::from); - - let parentchain_start_block = - m.value_of("parentchain-start-block").unwrap_or(DEFAULT_PARENTCHAIN_START_BLOCK); - - let ceremony_commands_thread_count = - m.value_of("ceremony-commands-thread-count").unwrap_or("4").parse().unwrap(); - let ceremony_events_thread_count = - m.value_of("ceremony-events-thread-count").unwrap_or("20").parse().unwrap(); - - Self::new( - m.value_of("node-url").unwrap_or(DEFAULT_NODE_URL).into(), - m.value_of("node-port").unwrap_or(DEFAULT_NODE_PORT).into(), - m.value_of("target-a-parentchain-rpc-url").map(Into::into), - m.value_of("target-a-parentchain-rpc-port").map(Into::into), - m.value_of("target-b-parentchain-rpc-url").map(Into::into), - m.value_of("target-b-parentchain-rpc-port").map(Into::into), - if m.is_present("ws-external") { "0.0.0.0".into() } else { "127.0.0.1".into() }, - m.value_of("trusted-external-address") - .map(|url| add_port_if_necessary(url, trusted_port)), - trusted_port.to_string(), - m.value_of("untrusted-external-address") - .map(|url| add_port_if_necessary(url, untrusted_port)), - untrusted_port.to_string(), - m.value_of("mu-ra-external-address") - .map(|url| add_port_if_necessary(url, mu_ra_port)), - mu_ra_port.to_string(), - is_metrics_server_enabled, - metrics_server_port.to_string(), - untrusted_http_port.to_string(), - data_dir, - run_config, - parentchain_start_block.to_string(), - ceremony_commands_thread_count, - ceremony_events_thread_count, - ) - } -} - -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -pub struct RunConfig { - /// Skip remote attestation. Set this flag if running enclave in SW mode - skip_ra: bool, - /// Set this flag if running in development mode to bootstrap enclave account on parentchain via //Alice. - dev: bool, - /// Shard identifier base58 encoded. Defines the shard that this worker operates on. Default is mrenclave. - shard: Option, - /// Marblerun's Prometheus endpoint base URL - marblerun_base_url: Option, - /// parentchain which should be used for shielding/unshielding the stf's native token - pub shielding_target: Option, -} - -impl RunConfig { - pub fn skip_ra(&self) -> bool { - self.skip_ra - } - - pub fn dev(&self) -> bool { - self.dev - } - - pub fn shard(&self) -> Option<&str> { - self.shard.as_deref() - } - - pub fn marblerun_base_url(&self) -> &str { - // This conflicts with the default port of a substrate node, but it is indeed the - // default port of marblerun too: - // https://github.com/edgelesssys/marblerun/blob/master/docs/docs/workflows/monitoring.md?plain=1#L26 - self.marblerun_base_url.as_deref().unwrap_or("http://localhost:9944") - } -} - -impl From<&ArgMatches<'_>> for RunConfig { - fn from(m: &ArgMatches<'_>) -> Self { - let skip_ra = m.is_present("skip-ra"); - let dev = m.is_present("dev"); - let shard = m.value_of("shard").map(|s| s.to_string()); - - let marblerun_base_url = m.value_of("marblerun-url").map(|i| { - Url::parse(i) - .unwrap_or_else(|e| panic!("marblerun-url parsing error: {:?}", e)) - .to_string() - }); - - let shielding_target = m.value_of("shielding-target").map(|i| match i { - "litentry" => ParentchainId::Litentry, - "target_a" => ParentchainId::TargetA, - "target_b" => ParentchainId::TargetB, - _ => panic!( - "failed to parse shielding-target: {} must be one of litentry|target_a|target_b", - i - ), - }); - - Self { skip_ra, dev, shard, marblerun_base_url, shielding_target } - } -} - -fn add_port_if_necessary(url: &str, port: &str) -> String { - // [Option("ws(s)"), ip, Option(port)] - match url.split(':').count() { - 3 => url.to_string(), - 2 => { - if url.contains("ws") { - // url is of format ws://127.0.0.1, no port added - format!("{}:{}", url, port) - } else { - // url is of format 127.0.0.1:4000, port was added - url.to_string() - } - }, - 1 => format!("{}:{}", url, port), - _ => panic!("Invalid worker url format in url input {:?}", url), - } -} - -fn ensure_ws_or_wss(url_str: &str) -> String { - let url = url::Url::parse(url_str) - .map_err(|e| { - println!("Parse url [{}] error: {}", url_str, e); - }) - .unwrap(); - - if url.scheme() != "wss" && url.scheme() != "ws" { - panic!("Parse url [{}] error: expect ws or wss, but get {}", url_str, url.scheme()); - } - url.into() -} - -pub fn pwd() -> PathBuf { - std::env::current_dir().expect("works on all supported platforms; qed.") -} - -#[cfg(test)] -mod test { - use super::*; - use std::{assert_matches::assert_matches, collections::HashMap}; - - #[test] - fn check_correct_config_assignment_for_empty_input() { - let empty_args = ArgMatches::default(); - let config = Config::from(&empty_args); - let expected_worker_ip = "127.0.0.1"; - - assert_eq!(config.litentry_rpc_url, DEFAULT_NODE_URL); - assert_eq!(config.litentry_rpc_port, DEFAULT_NODE_PORT); - assert_eq!(config.target_a_parentchain_rpc_url, None); - assert_eq!(config.target_a_parentchain_rpc_port, None); - assert_eq!(config.target_b_parentchain_rpc_url, None); - assert_eq!(config.target_b_parentchain_rpc_port, None); - assert_eq!(config.trusted_worker_port, DEFAULT_TRUSTED_PORT); - assert_eq!(config.untrusted_worker_port, DEFAULT_UNTRUSTED_PORT); - assert_eq!(config.mu_ra_port, DEFAULT_MU_RA_PORT); - assert_eq!(config.worker_ip, expected_worker_ip); - assert!(config.trusted_external_worker_address.is_none()); - assert!(config.untrusted_external_worker_address.is_none()); - assert!(config.mu_ra_external_address.is_none()); - assert!(!config.enable_metrics_server); - assert_eq!(config.untrusted_http_port, DEFAULT_UNTRUSTED_HTTP_PORT); - assert_eq!(config.data_dir, pwd()); - assert!(config.run_config.is_none()); - assert_eq!(config.parentchain_start_block, DEFAULT_PARENTCHAIN_START_BLOCK); - } - - #[test] - fn worker_ip_is_set_correctly_for_set_ws_external_flag() { - let expected_worker_ip = "0.0.0.0"; - - let mut args = ArgMatches::default(); - args.args = HashMap::from([("ws-external", Default::default())]); - let config = Config::from(&args); - - assert_eq!(config.worker_ip, expected_worker_ip); - } - - #[test] - fn check_correct_config_assignment_for_given_input() { - let node_ip = "ws://12.1.58.1"; - let node_port = "111111"; - let trusted_ext_addr = "wss://1.1.1.2:700"; - let trusted_port = "7119"; - let untrusted_ext_addr = "ws://1.723.3.1:11"; - let untrusted_port = "9119"; - let mu_ra_ext_addr = "1.1.3.1:1000"; - let mu_ra_port = "99"; - let untrusted_http_port = "4321"; - - let parentchain_start_block = "30"; - - let mut args = ArgMatches::default(); - args.args = HashMap::from([ - ("node-url", Default::default()), - ("node-port", Default::default()), - ("ws-external", Default::default()), - ("trusted-external-address", Default::default()), - ("untrusted-external-address", Default::default()), - ("mu-ra-external-address", Default::default()), - ("mu-ra-port", Default::default()), - ("untrusted-worker-port", Default::default()), - ("trusted-worker-port", Default::default()), - ("untrusted-http-port", Default::default()), - ("mock-server-port", Default::default()), - ("parentchain-start-block", Default::default()), - ]); - // Workaround because MatchedArg is private. - args.args.get_mut("node-url").unwrap().vals = vec![node_ip.into()]; - args.args.get_mut("node-port").unwrap().vals = vec![node_port.into()]; - args.args.get_mut("trusted-external-address").unwrap().vals = vec![trusted_ext_addr.into()]; - args.args.get_mut("untrusted-external-address").unwrap().vals = - vec![untrusted_ext_addr.into()]; - args.args.get_mut("mu-ra-external-address").unwrap().vals = vec![mu_ra_ext_addr.into()]; - args.args.get_mut("mu-ra-port").unwrap().vals = vec![mu_ra_port.into()]; - args.args.get_mut("untrusted-worker-port").unwrap().vals = vec![untrusted_port.into()]; - args.args.get_mut("trusted-worker-port").unwrap().vals = vec![trusted_port.into()]; - args.args.get_mut("untrusted-http-port").unwrap().vals = vec![untrusted_http_port.into()]; - args.args.get_mut("parentchain-start-block").unwrap().vals = - vec![parentchain_start_block.into()]; - - let config = Config::from(&args); - - assert_eq!(config.litentry_rpc_url, node_ip); - assert_eq!(config.litentry_rpc_port, node_port); - assert_eq!(config.trusted_worker_port, trusted_port); - assert_eq!(config.untrusted_worker_port, untrusted_port); - assert_eq!(config.mu_ra_port, mu_ra_port); - assert_eq!(config.trusted_external_worker_address, Some(trusted_ext_addr.to_string())); - assert_eq!(config.untrusted_external_worker_address, Some(untrusted_ext_addr.to_string())); - assert_eq!(config.mu_ra_external_address, Some(mu_ra_ext_addr.to_string())); - assert_eq!(config.untrusted_http_port, untrusted_http_port.to_string()); - assert_eq!(config.parentchain_start_block, parentchain_start_block.to_string()); - } - - #[test] - fn default_run_config_is_correct() { - let empty_args = ArgMatches::default(); - let run_config = RunConfig::from(&empty_args); - - assert_eq!(run_config.dev, false); - assert_eq!(run_config.skip_ra, false); - assert!(run_config.shard.is_none()); - } - - #[test] - fn run_config_parsing_works() { - let shard_identifier = "shard-identifier"; - - let mut args = ArgMatches::default(); - args.args = HashMap::from([ - ("dev", Default::default()), - ("skip-ra", Default::default()), - ("shard", Default::default()), - ]); - // Workaround because MatchedArg is private. - args.args.get_mut("shard").unwrap().vals = vec![shard_identifier.into()]; - - let run_config = RunConfig::from(&args); - - assert_eq!(run_config.dev, true); - assert_eq!(run_config.skip_ra, true); - assert_eq!(run_config.shard.unwrap(), shard_identifier.to_string()); - } - - #[test] - fn external_addresses_are_returned_correctly_if_not_set() { - let trusted_port = "7119"; - let untrusted_port = "9119"; - let mu_ra_port = "99"; - let expected_worker_ip = "127.0.0.1"; - - let mut args = ArgMatches::default(); - args.args = HashMap::from([ - ("mu-ra-port", Default::default()), - ("untrusted-worker-port", Default::default()), - ("trusted-worker-port", Default::default()), - ]); - // Workaround because MatchedArg is private. - args.args.get_mut("mu-ra-port").unwrap().vals = vec![mu_ra_port.into()]; - args.args.get_mut("untrusted-worker-port").unwrap().vals = vec![untrusted_port.into()]; - args.args.get_mut("trusted-worker-port").unwrap().vals = vec![trusted_port.into()]; - - let config = Config::from(&args); - - assert_eq!( - config.trusted_worker_url_external(), - format!("wss://{}:{}", expected_worker_ip, trusted_port) - ); - assert_eq!( - config.untrusted_worker_url_external(), - format!("ws://{}:{}", expected_worker_ip, untrusted_port) - ); - assert_eq!(config.mu_ra_url_external(), format!("{}:{}", expected_worker_ip, mu_ra_port)); - } - - #[test] - fn external_addresses_are_returned_correctly_if_set() { - let trusted_ext_addr = "wss://1.1.1.2:700/"; - let untrusted_ext_addr = "ws://1.123.3.1:11/"; - let mu_ra_ext_addr = "1.1.3.1:1000"; - - let mut args = ArgMatches::default(); - args.args = HashMap::from([ - ("trusted-external-address", Default::default()), - ("untrusted-external-address", Default::default()), - ("mu-ra-external-address", Default::default()), - ]); - // Workaround because MatchedArg is private. - args.args.get_mut("trusted-external-address").unwrap().vals = vec![trusted_ext_addr.into()]; - args.args.get_mut("untrusted-external-address").unwrap().vals = - vec![untrusted_ext_addr.into()]; - args.args.get_mut("mu-ra-external-address").unwrap().vals = vec![mu_ra_ext_addr.into()]; - - let config = Config::from(&args); - - assert_eq!(config.trusted_worker_url_external(), trusted_ext_addr); - assert_eq!(config.untrusted_worker_url_external(), untrusted_ext_addr); - assert_eq!(config.mu_ra_url_external(), mu_ra_ext_addr); - } - - #[test] - fn ensure_no_port_is_added_to_url_with_port() { - let url = "ws://hello:4000"; - let port = "0"; - - let resulting_url = add_port_if_necessary(url, port); - - assert_eq!(resulting_url, url); - } - - #[test] - fn ensure_port_is_added_to_url_without_port() { - let url = "wss://hello"; - let port = "0"; - - let resulting_url = add_port_if_necessary(url, port); - - assert_eq!(resulting_url, format!("{}:{}", url, port)); - } - - #[test] - fn ensure_no_port_is_added_to_url_with_port_without_prefix() { - let url = "hello:10001"; - let port = "012"; - - let resulting_url = add_port_if_necessary(url, port); - - assert_eq!(resulting_url, url); - } - - #[test] - fn ensure_port_is_added_to_url_without_port_without_prefix() { - let url = "hello_world"; - let port = "10"; - - let resulting_url = add_port_if_necessary(url, port); - - assert_eq!(resulting_url, format!("{}:{}", url, port)); - } -} diff --git a/tee-worker/bitacross/service/src/enclave/api.rs b/tee-worker/bitacross/service/src/enclave/api.rs deleted file mode 100644 index 86030f8d8d..0000000000 --- a/tee-worker/bitacross/service/src/enclave/api.rs +++ /dev/null @@ -1,116 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use crate::config::Config; -use itp_enclave_api::{enclave_base::EnclaveBase, error::Error as EnclaveApiError, EnclaveResult}; -use itp_settings::files::{ENCLAVE_FILE, ENCLAVE_TOKEN}; -use log::*; -use sgx_types::*; -use std::{ - fs::File, - io::{Read, Write}, - path::PathBuf, -}; - -use itp_enclave_api::{Enclave, SgxEnclave}; - -pub fn enclave_init(config: &Config) -> EnclaveResult { - const LEN: usize = 1024; - let mut launch_token = [0; LEN]; - let mut launch_token_updated = 0; - - // Step 1: try to retrieve the launch token saved by last transaction - // if there is no token, then create a new one. - // - // try to get the token saved in $HOME */ - let mut home_dir = PathBuf::new(); - let use_token = match dirs::home_dir() { - Some(path) => { - info!("[+] Home dir is {}", path.display()); - home_dir = path; - true - }, - None => { - error!("[-] Cannot get home dir"); - false - }, - }; - let token_file = home_dir.join(ENCLAVE_TOKEN); - if use_token { - match File::open(&token_file) { - Err(_) => { - info!( - "[-] Token file {} not found! Will create one.", - token_file.as_path().to_str().unwrap() - ); - }, - Ok(mut f) => { - info!("[+] Open token file success! "); - match f.read(&mut launch_token) { - Ok(LEN) => { - info!("[+] Token file valid!"); - }, - _ => info!("[+] Token file invalid, will create new token file"), - } - }, - } - } - - // Step 2: call sgx_create_enclave to initialize an enclave instance - // Debug Support: 1 = debug mode, 0 = not debug mode - #[cfg(feature = "development")] - let debug = 1; - #[cfg(not(feature = "development"))] - let debug = 0; - - let mut misc_attr = - sgx_misc_attribute_t { secs_attr: sgx_attributes_t { flags: 0, xfrm: 0 }, misc_select: 0 }; - let enclave = (SgxEnclave::create( - ENCLAVE_FILE, - debug, - &mut launch_token, - &mut launch_token_updated, - &mut misc_attr, - )) - .map_err(EnclaveApiError::Sgx)?; - - // Step 3: save the launch token if it is updated - if use_token && launch_token_updated != 0 { - // reopen the file with write capability - match File::create(&token_file) { - Ok(mut f) => match f.write_all(&launch_token) { - Ok(()) => info!("[+] Saved updated launch token!"), - Err(_) => error!("[-] Failed to save updated launch token!"), - }, - Err(_) => { - warn!("[-] Failed to save updated enclave token, but doesn't matter"); - }, - } - } - - // create an enclave API and initialize it - let enclave_api = Enclave::new(enclave); - enclave_api.init( - &config.mu_ra_url_external(), - &config.untrusted_worker_url_external(), - &config.data_dir().display().to_string(), - config.ceremony_commands_thread_count, - config.ceremony_events_thread_count, - )?; - - Ok(enclave_api) -} diff --git a/tee-worker/bitacross/service/src/enclave/mod.rs b/tee-worker/bitacross/service/src/enclave/mod.rs deleted file mode 100644 index bb9ba4fe84..0000000000 --- a/tee-worker/bitacross/service/src/enclave/mod.rs +++ /dev/null @@ -1,20 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -#[cfg(feature = "link-binary")] -pub mod api; -pub mod tls_ra; diff --git a/tee-worker/bitacross/service/src/enclave/tls_ra.rs b/tee-worker/bitacross/service/src/enclave/tls_ra.rs deleted file mode 100644 index f7ff454ecb..0000000000 --- a/tee-worker/bitacross/service/src/enclave/tls_ra.rs +++ /dev/null @@ -1,117 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ -use itp_enclave_api::{ - error::Error, - remote_attestation::{RemoteAttestation, TlsRemoteAttestation}, - EnclaveResult, -}; -use itp_types::ShardIdentifier; -use log::*; -use sgx_types::*; -use std::{ - net::{TcpListener, TcpStream}, - os::unix::io::AsRawFd, - time::Duration, -}; - -pub fn enclave_run_state_provisioning_server( - enclave_api: &E, - sign_type: sgx_quote_sign_type_t, - quoting_enclave_target_info: Option<&sgx_target_info_t>, - quote_size: Option<&u32>, - addr: &str, - skip_ra: bool, -) { - info!("Starting MU-RA-Server on: {}", addr); - let listener = match TcpListener::bind(addr) { - Ok(l) => l, - Err(e) => { - error!("error starting MU-RA server on {}: {}", addr, e); - return - }, - }; - loop { - match listener.accept() { - Ok((socket, addr)) => { - info!("[MU-RA-Server] a worker at {} is requesting key provisioning", addr); - // there is some race condition, lets wait until local state gets updated (signers are registered and updated locally through indirect calls) - std::thread::sleep(Duration::from_secs(3)); - let result = enclave_api.run_state_provisioning_server( - socket.as_raw_fd(), - sign_type, - quoting_enclave_target_info, - quote_size, - skip_ra, - ); - - match result { - Ok(_) => { - debug!("[MU-RA-Server] ECALL success!"); - }, - Err(e) => { - error!("[MU-RA-Server] ECALL Enclave Failed {:?}!", e); - }, - } - }, - Err(e) => error!("couldn't get client: {:?}", e), - } - } -} - -pub fn enclave_request_state_provisioning( - enclave_api: &E, - sign_type: sgx_quote_sign_type_t, - addr: &str, - shard: &ShardIdentifier, - skip_ra: bool, -) -> EnclaveResult<()> { - info!("[MU-RA-Client] Requesting key provisioning from {}", addr); - - let stream = TcpStream::connect(addr).map_err(|e| Error::Other(Box::new(e)))?; - - #[cfg(not(feature = "dcap"))] - let get_quote_data = false; - #[cfg(feature = "dcap")] - let get_quote_data = !skip_ra; - - let quoting_enclave_target_info = if get_quote_data { - match enclave_api.qe_get_target_info() { - Ok(quote_size) => Some(quote_size), - Err(e) => return Err(e), - } - } else { - None - }; - - let quote_size = if get_quote_data { - match enclave_api.qe_get_quote_size() { - Ok(quote_size) => Some(quote_size), - Err(e) => return Err(e), - } - } else { - None - }; - - enclave_api.request_state_provisioning( - stream.as_raw_fd(), - sign_type, - quoting_enclave_target_info.as_ref(), - quote_size.as_ref(), - shard, - skip_ra, - ) -} diff --git a/tee-worker/bitacross/service/src/error.rs b/tee-worker/bitacross/service/src/error.rs deleted file mode 100644 index 975d32f267..0000000000 --- a/tee-worker/bitacross/service/src/error.rs +++ /dev/null @@ -1,65 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ - -use codec::Error as CodecError; -use itp_node_api::api_client::ApiClientError; -use itp_types::{parentchain::Hash, ShardIdentifier}; - -pub type ServiceResult = Result; - -#[derive(Debug, thiserror::Error)] -pub enum Error { - #[error("{0}")] - Codec(#[from] CodecError), - #[error("{0:?}")] - ApiClient(ApiClientError), - #[error("Node API terminated subscription unexpectedly")] - ApiSubscriptionDisconnected, - #[error("Enclave API error: {0}")] - EnclaveApi(#[from] itp_enclave_api::error::Error), - #[error("Trusted Rpc Client error: {0}")] - TrustedRpcClient(#[from] itc_rpc_client::error::Error), - #[error("{0}")] - JsonRpSeeClient(#[from] jsonrpsee::types::Error), - #[error("{0}")] - Serialization(#[from] serde_json::Error), - #[error("{0}")] - FromUtf8(#[from] std::string::FromUtf8Error), - #[error("Application setup error!")] - ApplicationSetup, - #[error("Failed to find any peer worker")] - NoPeerWorkerFound, - #[error("No worker for shard {0} found on parentchain")] - NoWorkerForShardFound(ShardIdentifier), - #[error("Returned empty parentchain block vec after sync, even though there have been blocks given as input")] - EmptyChunk, - #[error("Could not find genesis header of the parentchain")] - MissingGenesisHeader, - #[error("Could not find last finalized block of the parentchain")] - MissingLastFinalizedBlock, - #[error("Could not find block in parentchain")] - UnknownBlockHeader(Hash), - #[error("Enclave has not enough funds to send extrinsic")] - LowEnclaveBalance, - #[error("{0}")] - Custom(Box), -} - -impl From for Error { - fn from(error: ApiClientError) -> Self { - Error::ApiClient(error) - } -} diff --git a/tee-worker/bitacross/service/src/globals/mod.rs b/tee-worker/bitacross/service/src/globals/mod.rs deleted file mode 100644 index ee250661c5..0000000000 --- a/tee-worker/bitacross/service/src/globals/mod.rs +++ /dev/null @@ -1,19 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - Copyright (C) 2017-2019 Baidu, Inc. All Rights Reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -pub mod tokio_handle; diff --git a/tee-worker/bitacross/service/src/globals/tokio_handle.rs b/tee-worker/bitacross/service/src/globals/tokio_handle.rs deleted file mode 100644 index 54e49d985e..0000000000 --- a/tee-worker/bitacross/service/src/globals/tokio_handle.rs +++ /dev/null @@ -1,108 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - Copyright (C) 2017-2019 Baidu, Inc. All Rights Reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use lazy_static::lazy_static; -use parking_lot::RwLock; -use tokio::runtime::Handle; - -lazy_static! { - static ref TOKIO_HANDLE: RwLock> = RwLock::new(None); -} - -/// Wrapper for accessing a tokio handle -pub trait GetTokioHandle { - fn get_handle(&self) -> Handle; -} - -/// implementation, using a static global variable internally -/// -pub struct GlobalTokioHandle; - -/// these are the static (global) accessors -/// reduce their usage where possible and use an instance of TokioHandleAccessorImpl or the trait -impl GlobalTokioHandle { - /// this needs to be called once at application startup! - pub fn initialize() { - let rt = tokio::runtime::Builder::new_multi_thread() - .enable_all() - .worker_threads(2) - .build() - .unwrap(); - *TOKIO_HANDLE.write() = Some(rt); - } - - /// static / global getter of the handle (try to keep private!, use trait to access handle) - fn read_handle() -> Handle { - TOKIO_HANDLE - .read() - .as_ref() - .expect("Tokio handle has not been initialized!") - .handle() - .clone() - } -} - -impl GetTokioHandle for GlobalTokioHandle { - fn get_handle(&self) -> Handle { - GlobalTokioHandle::read_handle() - } -} - -/// Implementation for a scoped Tokio handle. -/// -/// -pub struct ScopedTokioHandle { - tokio_runtime: tokio::runtime::Runtime, -} - -impl Default for ScopedTokioHandle { - fn default() -> Self { - ScopedTokioHandle { tokio_runtime: tokio::runtime::Runtime::new().unwrap() } - } -} - -impl GetTokioHandle for ScopedTokioHandle { - fn get_handle(&self) -> Handle { - self.tokio_runtime.handle().clone() - } -} - -#[cfg(test)] -mod tests { - - use super::*; - - #[tokio::test] - async fn given_initialized_tokio_handle_when_runtime_goes_out_of_scope_then_async_handle_is_valid( - ) { - // initialize the global handle - // be aware that if you write more tests here, the global state will be shared across multiple threads - // which cargo test spawns. So it can lead to failing tests. - // solution: either get rid of the global state, or write all test functionality in this single test function - { - GlobalTokioHandle::initialize(); - } - - let handle = GlobalTokioHandle.get_handle(); - - let result = handle.spawn_blocking(|| "now running on a worker thread").await; - - assert!(result.is_ok()); - assert!(!result.unwrap().is_empty()) - } -} diff --git a/tee-worker/bitacross/service/src/initialized_service.rs b/tee-worker/bitacross/service/src/initialized_service.rs deleted file mode 100644 index 2aca3876ac..0000000000 --- a/tee-worker/bitacross/service/src/initialized_service.rs +++ /dev/null @@ -1,109 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -//! Service to determine if the integritee services is initialized and registered on the node, -//! hosted on a http server. - -use crate::error::ServiceResult; -use log::*; -use parking_lot::RwLock; -use std::{default::Default, marker::PhantomData, net::SocketAddr, sync::Arc}; -use warp::Filter; - -pub async fn start_is_initialized_server( - initialization_handler: Arc, - port: u16, -) -> ServiceResult<()> -where - Handler: IsInitialized + Send + Sync + 'static, -{ - let is_initialized_route = warp::path!("is_initialized").and_then(move || { - let handler_clone = initialization_handler.clone(); - async move { - if handler_clone.is_initialized() { - Ok("I am initialized.") - } else { - Err(warp::reject::not_found()) - } - } - }); - - let socket_addr: SocketAddr = ([0, 0, 0, 0], port).into(); - - info!("Running initialized server on: {:?}", socket_addr); - warp::serve(is_initialized_route).run(socket_addr).await; - - info!("Initialized server shut down"); - Ok(()) -} - -/// Trait to query of a worker is considered fully initialized. -pub trait IsInitialized { - fn is_initialized(&self) -> bool; -} - -/// Tracker for initialization. Used by components that ensure these steps were taken. -pub trait TrackInitialization { - fn registered_on_parentchain(&self); - - fn worker_for_shard_registered(&self); -} - -#[derive(Default)] -pub struct InitializationHandler { - registered_on_parentchain: RwLock, - worker_for_shard_registered: RwLock, -} - -impl TrackInitialization for InitializationHandler { - fn registered_on_parentchain(&self) { - let mut registered_lock = self.registered_on_parentchain.write(); - *registered_lock = true; - } - - fn worker_for_shard_registered(&self) { - let mut registered_lock = self.worker_for_shard_registered.write(); - *registered_lock = true; - } -} - -impl IsInitialized for InitializationHandler { - fn is_initialized(&self) -> bool { - *self.registered_on_parentchain.read() - } -} - -#[cfg(test)] -mod tests { - - use super::*; - - #[test] - fn default_handler_is_initialized_returns_false() { - let offchain_worker_handler = InitializationHandler::default(); - - assert!(!offchain_worker_handler.is_initialized()); - } - - #[test] - fn parentchain_registration_is_enough_for_initialized() { - let initialization_handler = InitializationHandler::default(); - initialization_handler.registered_on_parentchain(); - - assert!(initialization_handler.is_initialized()); - } -} diff --git a/tee-worker/bitacross/service/src/main.rs b/tee-worker/bitacross/service/src/main.rs deleted file mode 100644 index 378869c22f..0000000000 --- a/tee-worker/bitacross/service/src/main.rs +++ /dev/null @@ -1,48 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -#![cfg_attr(test, feature(assert_matches))] -#![allow(unused)] - -mod account_funding; -mod config; -mod enclave; -mod error; -mod globals; -mod initialized_service; -mod ocall_bridge; -mod parentchain_handler; -mod prometheus_metrics; -mod setup; -mod sync_state; -mod tests; -mod utils; -mod worker; -mod worker_peers_updater; - -#[cfg(feature = "link-binary")] -pub mod main_impl; - -#[cfg(feature = "link-binary")] -fn main() { - main_impl::main(); -} - -#[cfg(not(feature = "link-binary"))] -fn main() { - panic!("tried to run the binary without linking. Make sure to pass `--features link-binary`") -} diff --git a/tee-worker/bitacross/service/src/main_impl.rs b/tee-worker/bitacross/service/src/main_impl.rs deleted file mode 100644 index 663f2df117..0000000000 --- a/tee-worker/bitacross/service/src/main_impl.rs +++ /dev/null @@ -1,942 +0,0 @@ -#[cfg(not(feature = "dcap"))] -use crate::utils::check_files; -use crate::{ - account_funding::{setup_reasonable_account_funding, EnclaveAccountInfoProvider}, - config::Config, - enclave::{ - api::enclave_init, - tls_ra::{enclave_request_state_provisioning, enclave_run_state_provisioning_server}, - }, - error::Error, - globals::tokio_handle::{GetTokioHandle, GlobalTokioHandle}, - initialized_service::{ - start_is_initialized_server, InitializationHandler, IsInitialized, TrackInitialization, - }, - ocall_bridge::{ - bridge_api::Bridge as OCallBridge, component_factory::OCallBridgeComponentFactory, - }, - parentchain_handler::{HandleParentchain, ParentchainHandler}, - prometheus_metrics::{start_metrics_server, EnclaveMetricsReceiver, MetricsHandler}, - setup, sync_state, tests, - utils::extract_shard, - worker::Worker, - worker_peers_updater::WorkerPeersRegistry, -}; -use base58::ToBase58; -use clap::{load_yaml, App, ArgMatches}; -use codec::{Decode, Encode}; -use ita_parentchain_interface::integritee::{Hash, Header}; -use itp_enclave_api::{ - enclave_base::EnclaveBase, - remote_attestation::{RemoteAttestation, TlsRemoteAttestation}, - sidechain::Sidechain, - Enclave, -}; -use itp_node_api::{ - api_client::{AccountApi, PalletTeebagApi, ParentchainApi}, - metadata::NodeMetadata, - node_api_factory::{CreateNodeApi, NodeApiFactory}, -}; -use litentry_primitives::{Enclave as TeebagEnclave, ShardIdentifier, WorkerType}; -use log::*; -use regex::Regex; -use serde_json::Value; -use sgx_types::*; -use sp_runtime::traits::Header as HeaderT; -use substrate_api_client::{ - api::XtStatus, rpc::HandleSubscription, GetAccountInformation, GetBalance, GetChainInfo, - SubmitAndWatch, SubscribeChain, SubscribeEvents, -}; - -#[cfg(feature = "dcap")] -use litentry_primitives::extract_tcb_info_from_raw_dcap_quote; - -use crate::error::ServiceResult; -use itp_types::parentchain::{AccountId, Balance, ParentchainId}; -use sp_core::{ - crypto::{AccountId32, Ss58Codec}, - Pair, -}; -use sp_keyring::AccountKeyring; -use sp_runtime::MultiSigner; -use std::{ - collections::HashSet, fmt::Debug, path::PathBuf, str, str::Utf8Error, sync::Arc, thread, - time::Duration, -}; -use substrate_api_client::ac_node_api::{EventRecord, Phase::ApplyExtrinsic}; - -const VERSION: &str = env!("CARGO_PKG_VERSION"); - -#[cfg(feature = "link-binary")] -pub type EnclaveWorker = Worker; - -pub(crate) fn main() { - // Setup logging - env_logger::builder() - .format_timestamp(Some(env_logger::TimestampPrecision::Millis)) - .init(); - - let yml = load_yaml!("cli.yml"); - let matches = App::from_yaml(yml).get_matches(); - - let config = Config::from(&matches); - - GlobalTokioHandle::initialize(); - - // log this information, don't println because some python scripts for GA rely on the - // stdout from the service - #[cfg(not(feature = "development"))] - info!("*** Starting service in SGX production mode"); - #[cfg(feature = "development")] - info!("*** Starting service in SGX debug mode"); - - let mut lockfile = PathBuf::from(config.data_dir()); - lockfile.push("worker.lock"); - while std::fs::metadata(lockfile.clone()).is_ok() { - println!("lockfile is present, will wait for it to disappear {:?}", lockfile); - thread::sleep(std::time::Duration::from_secs(5)); - } - - let clean_reset = matches.is_present("clean-reset"); - if clean_reset { - crate::setup::purge_files_from_dir(config.data_dir()).unwrap(); - } - - // build the entire dependency tree - let tokio_handle = Arc::new(GlobalTokioHandle {}); - let node_api_factory = - Arc::new(NodeApiFactory::new(config.litentry_rpc_endpoint(), AccountKeyring::Alice.pair())); - let enclave = Arc::new(enclave_init(&config).unwrap()); - let initialization_handler = Arc::new(InitializationHandler::default()); - let worker = Arc::new(EnclaveWorker::new( - config.clone(), - enclave.clone(), - node_api_factory.clone(), - initialization_handler.clone(), - HashSet::new(), - )); - let peer_updater = Arc::new(WorkerPeersRegistry::new(worker)); - let enclave_metrics_receiver = Arc::new(EnclaveMetricsReceiver {}); - - let maybe_target_a_parentchain_api_factory = config - .target_a_parentchain_rpc_endpoint() - .map(|url| Arc::new(NodeApiFactory::new(url, AccountKeyring::Alice.pair()))); - - let maybe_target_b_parentchain_api_factory = config - .target_b_parentchain_rpc_endpoint() - .map(|url| Arc::new(NodeApiFactory::new(url, AccountKeyring::Alice.pair()))); - - // initialize o-call bridge with a concrete factory implementation - OCallBridge::initialize(Arc::new(OCallBridgeComponentFactory::new( - node_api_factory.clone(), - maybe_target_a_parentchain_api_factory, - maybe_target_b_parentchain_api_factory, - enclave.clone(), - peer_updater, - tokio_handle.clone(), - enclave_metrics_receiver, - ))); - - #[cfg(feature = "dcap")] - let quoting_enclave_target_info = match enclave.qe_get_target_info() { - Ok(target_info) => Some(target_info), - Err(e) => { - warn!("Setting up DCAP - qe_get_target_info failed with error: {:?}, continuing.", e); - None - }, - }; - #[cfg(feature = "dcap")] - let quote_size = match enclave.qe_get_quote_size() { - Ok(size) => Some(size), - Err(e) => { - warn!("Setting up DCAP - qe_get_quote_size failed with error: {:?}, continuing.", e); - None - }, - }; - - #[cfg(not(feature = "dcap"))] - let quoting_enclave_target_info = None; - #[cfg(not(feature = "dcap"))] - let quote_size = None; - - if let Some(run_config) = config.run_config() { - let shard = extract_shard(run_config.shard(), enclave.as_ref()); - - println!("Worker Config: {:?}", config); - - if clean_reset { - setup::initialize_shard_and_keys(enclave.as_ref(), &shard).unwrap(); - } - - let node_api = - node_api_factory.create_api().expect("Failed to create parentchain node API"); - - start_worker::<_, _, _>( - config, - &shard, - enclave, - node_api, - tokio_handle, - initialization_handler, - quoting_enclave_target_info, - quote_size, - ); - } else if let Some(smatches) = matches.subcommand_matches("request-state") { - println!("*** Requesting state from a registered worker \n"); - let node_api = - node_api_factory.create_api().expect("Failed to create parentchain node API"); - sync_state::sync_state::<_, _>( - &node_api, - &extract_shard(smatches.value_of("shard"), enclave.as_ref()), - enclave.as_ref(), - smatches.is_present("skip-ra"), - ); - } else if matches.is_present("shielding-key") { - setup::generate_shielding_key_file(enclave.as_ref()); - } else if matches.is_present("signing-key") { - setup::generate_signing_key_file(enclave.as_ref()); - let tee_accountid = enclave_account(enclave.as_ref()); - println!("Enclave signing account: {:}", &tee_accountid.to_ss58check()); - } else if matches.is_present("dump-ra") { - info!("*** Perform RA and dump cert to disk"); - #[cfg(not(feature = "dcap"))] - enclave.dump_ias_ra_cert_to_disk().unwrap(); - #[cfg(feature = "dcap")] - { - let skip_ra = false; - let dcap_quote = enclave.generate_dcap_ra_quote(skip_ra).unwrap(); - let (fmspc, _tcb_info) = extract_tcb_info_from_raw_dcap_quote(&dcap_quote).unwrap(); - enclave.dump_dcap_collateral_to_disk(fmspc).unwrap(); - enclave.dump_dcap_ra_cert_to_disk().unwrap(); - } - } else if matches.is_present("mrenclave") { - let mrenclave = enclave.get_fingerprint().unwrap(); - let hex_value = hex::encode(mrenclave); - println!("MRENCLAVE hex: {}", hex_value); - println!("MRENCLAVE base58: {}", mrenclave.encode().to_base58()); - } else if let Some(sub_matches) = matches.subcommand_matches("init-shard") { - setup::init_shard( - enclave.as_ref(), - &extract_shard(sub_matches.value_of("shard"), enclave.as_ref()), - ); - } else if let Some(sub_matches) = matches.subcommand_matches("test") { - if sub_matches.is_present("provisioning-server") { - println!("*** Running Enclave MU-RA TLS server\n"); - enclave_run_state_provisioning_server( - enclave.as_ref(), - sgx_quote_sign_type_t::SGX_UNLINKABLE_SIGNATURE, - quoting_enclave_target_info.as_ref(), - quote_size.as_ref(), - &config.mu_ra_url(), - sub_matches.is_present("skip-ra"), - ); - println!("[+] Done!"); - } else if sub_matches.is_present("provisioning-client") { - println!("*** Running Enclave MU-RA TLS client\n"); - let shard = extract_shard(sub_matches.value_of("shard"), enclave.as_ref()); - enclave_request_state_provisioning( - enclave.as_ref(), - sgx_quote_sign_type_t::SGX_UNLINKABLE_SIGNATURE, - &config.mu_ra_url_external(), - &shard, - sub_matches.is_present("skip-ra"), - ) - .unwrap(); - println!("[+] Done!"); - } else { - tests::run_enclave_tests(sub_matches); - } - } else if let Some(sub_matches) = matches.subcommand_matches("migrate-shard") { - let new_shard = extract_shard(None, enclave.as_ref()); - setup::migrate_shard(enclave.as_ref(), &new_shard); - let new_shard_name = new_shard.encode().to_base58(); - setup::remove_old_shards(config.data_dir(), &new_shard_name); - } else if let Some(sub_matches) = matches.subcommand_matches("wallet") { - println!("Bitcoin wallet:"); - let bitcoin_keypair = enclave.get_bitcoin_wallet_pair().unwrap(); - println!("public : 0x{}", hex::encode(bitcoin_keypair.public_bytes())); - println!("private: 0x{}", hex::encode(bitcoin_keypair.private_bytes())); - - println!("Ethereum wallet:"); - let ethereum_keypair = enclave.get_ethereum_wallet_pair().unwrap(); - println!("public : 0x{}", hex::encode(ethereum_keypair.public_bytes())); - println!("private: 0x{}", hex::encode(ethereum_keypair.private_bytes())); - - println!("Ton wallet:"); - let ton_keypair = enclave.get_ton_wallet_pair().unwrap(); - println!("public : 0x{}", hex::encode(ton_keypair.public().0)); - println!("private: 0x{}", hex::encode(ton_keypair.seed())); - } else if let Some(sub_matches) = matches.subcommand_matches("init-wallet") { - println!("Initializing wallets"); - enclave.init_wallets(config.data_dir().to_str().unwrap()).unwrap(); - } else { - println!("For options: use --help"); - } -} - -/// FIXME: needs some discussion (restructuring?) -#[allow(clippy::too_many_arguments)] -fn start_worker( - config: Config, - shard: &ShardIdentifier, - enclave: Arc, - litentry_rpc_api: ParentchainApi, - tokio_handle_getter: Arc, - initialization_handler: Arc, - quoting_enclave_target_info: Option, - quote_size: Option, -) where - T: GetTokioHandle, - E: EnclaveBase + Sidechain + RemoteAttestation + TlsRemoteAttestation + Clone, - InitializationHandler: TrackInitialization + IsInitialized + Sync + Send + 'static, -{ - let run_config = config.run_config().clone().expect("Run config missing"); - let skip_ra = run_config.skip_ra(); - - let flavor_str = "offchain-worker"; - - println!("Litentry Worker for {} v{}", flavor_str, VERSION); - - #[cfg(feature = "dcap")] - println!(" DCAP is enabled"); - #[cfg(not(feature = "dcap"))] - println!(" DCAP is disabled"); - #[cfg(not(feature = "development"))] - println!(" Production Mode is enabled"); - #[cfg(feature = "development")] - println!(" Production Mode is disabled"); - - info!("starting worker on shard {}", shard.encode().to_base58()); - // ------------------------------------------------------------------------ - // check for required files - if !skip_ra { - #[cfg(not(feature = "dcap"))] - check_files(); - } - // ------------------------------------------------------------------------ - // initialize the enclave - let mrenclave = enclave.get_fingerprint().unwrap(); - println!("MRENCLAVE={}", mrenclave.0.to_base58()); - println!("MRENCLAVE in hex {:?}", hex::encode(mrenclave)); - - // ------------------------------------------------------------------------ - // let new workers call us for key provisioning - println!("MU-RA server listening on {}", config.mu_ra_url()); - let is_development_mode = run_config.dev(); - let ra_url = config.mu_ra_url(); - let enclave_api_key_prov = enclave.clone(); - thread::spawn(move || { - enclave_run_state_provisioning_server( - enclave_api_key_prov.as_ref(), - sgx_quote_sign_type_t::SGX_UNLINKABLE_SIGNATURE, - quoting_enclave_target_info.as_ref(), - quote_size.as_ref(), - &ra_url, - skip_ra, - ); - info!("State provisioning server stopped."); - }); - - let tokio_handle = tokio_handle_getter.get_handle(); - - // ------------------------------------------------------------------------ - // Get the public key of our TEE. - let tee_accountid = enclave_account(enclave.as_ref()); - println!("Enclave account {:} ", &tee_accountid.to_ss58check()); - - // ------------------------------------------------------------------------ - // Start `is_initialized` server. - let untrusted_http_server_port = config - .try_parse_untrusted_http_server_port() - .expect("untrusted http server port to be a valid port number"); - let initialization_handler_clone = initialization_handler.clone(); - tokio_handle.spawn(async move { - if let Err(e) = - start_is_initialized_server(initialization_handler_clone, untrusted_http_server_port) - .await - { - error!("Unexpected error in `is_initialized` server: {:?}", e); - } - }); - - // ------------------------------------------------------------------------ - // Start prometheus metrics server. - if config.enable_metrics_server() { - let metrics_handler = Arc::new(MetricsHandler {}); - let metrics_server_port = config - .try_parse_metrics_server_port() - .expect("metrics server port to be a valid port number"); - tokio_handle.spawn(async move { - if let Err(e) = start_metrics_server(metrics_handler, metrics_server_port).await { - error!("Unexpected error in Prometheus metrics server: {:?}", e); - } - }); - } - - // ------------------------------------------------------------------------ - // Start trusted worker rpc server - let direct_invocation_server_addr = config.trusted_worker_url_internal(); - let enclave_for_direct_invocation = enclave.clone(); - thread::spawn(move || { - println!( - "[+] Trusted RPC direct invocation server listening on {}", - direct_invocation_server_addr - ); - enclave_for_direct_invocation - .init_direct_invocation_server(direct_invocation_server_addr) - .unwrap(); - println!("[+] RPC direct invocation server shut down"); - }); - - // ------------------------------------------------------------------------ - // Init parentchain specific stuff. Needed early for parentchain communication. - let (integritee_parentchain_handler, integritee_last_synced_header_at_last_run) = - init_parentchain( - &enclave, - &litentry_rpc_api, - &tee_accountid, - ParentchainId::Litentry, - shard, - ); - - #[cfg(feature = "dcap")] - register_collateral(&litentry_rpc_api, &*enclave, &tee_accountid, is_development_mode, skip_ra); - - let trusted_url = config.trusted_worker_url_external(); - - #[cfg(feature = "attesteer")] - fetch_marblerun_events_every_hour( - litentry_rpc_api.clone(), - enclave.clone(), - tee_accountid.clone(), - is_development_mode, - trusted_url.clone(), - run_config.marblerun_base_url().to_string(), - ); - - // ------------------------------------------------------------------------ - // Perform a remote attestation and get an unchecked extrinsic back. - - if skip_ra { - println!( - "[!] skipping remote attestation. Registering enclave without attestation report." - ); - } else { - println!("[!] creating remote attestation report and create enclave register extrinsic."); - }; - - #[cfg(feature = "dcap")] - enclave.set_sgx_qpl_logging().expect("QPL logging setup failed"); - - let enclave2 = enclave.clone(); - let node_api2 = litentry_rpc_api.clone(); - let tee_accountid2 = tee_accountid.clone(); - let trusted_url2 = trusted_url.clone(); - - #[cfg(not(feature = "dcap"))] - let register_xt = move || enclave2.generate_ias_ra_extrinsic(&trusted_url2, skip_ra).unwrap(); - #[cfg(feature = "dcap")] - let register_xt = move || enclave2.generate_dcap_ra_extrinsic(&trusted_url2, skip_ra).unwrap(); - - let send_register_xt = move || { - println!("[+] Send register enclave extrinsic"); - send_litentry_extrinsic(register_xt(), &node_api2, &tee_accountid2, is_development_mode) - }; - - // Litentry: send the registration extrinsic regardless of being registered or not, - // the reason is the mrenclave could change in between, so we rely on the - // on-chain logic to handle everything. - // this is the same behavior as upstream - let register_enclave_block_hash = - send_register_xt().expect("enclave RA registration must be successful to continue"); - - let api_register_enclave_xt_header = - litentry_rpc_api.get_header(Some(register_enclave_block_hash)).unwrap().unwrap(); - - // TODO: #1451: Fix api-client type hacks - let register_enclave_xt_header = - Header::decode(&mut api_register_enclave_xt_header.encode().as_slice()) - .expect("Can decode previously encoded header; qed"); - - println!( - "[+] Enclave registered at block number: {:?}, hash: {:?}", - register_enclave_xt_header.number(), - register_enclave_xt_header.hash() - ); - // double-check - let my_enclave = litentry_rpc_api - .enclave(&tee_accountid, None) - .unwrap() - .expect("our enclave should be registered at this point"); - trace!("verified that our enclave is registered: {:?}", my_enclave); - - // Litentry: - // the logic differs from upstream a bit here (due to different impl in parachain pallet), - // theoretically the `primary_enclave_identifier_for_shard` should never be empty, unless the previous - // registration failed (e.g. due to unexpected mrenclave). In that case it's expected not to continue with anything. - // - // in case it's non-empty, it relies on the check of `enclave.get_shard_creation_info` to tell if this worker - // has run before - this is similar to upstream. - // There're a few cases: - // 1. `--clean-reset` is set, then the shard should have been initalized earlier already and it's empty state anyway - // 2. `--clean-reset` is not set: - // 2a. `get_shard_creation_info` is empty and we are primary worker => it's never run before => init everything - // 2b. `get_shard_creation_info` is empty and we are non-primary worker => it's never run before => request to sync state - // 2c. `get_shard_creation_info` is non-empty it's run before => do nothing - let (we_are_primary_validateer, re_init_parentchain_needed) = - match litentry_rpc_api - .primary_enclave_identifier_for_shard(WorkerType::BitAcross, shard, None) - .unwrap() - { - Some(account) => { - let first_run = enclave - .get_shard_creation_info(shard) - .unwrap() - .for_parentchain(ParentchainId::Litentry) - .is_none(); - if account == tee_accountid { - println!("We are the primary worker, first_run: {}", first_run); - if first_run { - enclave.init_shard(shard.encode()).unwrap(); - enclave - .init_shard_creation_parentchain_header( - shard, - &ParentchainId::Litentry, - ®ister_enclave_xt_header, - ) - .unwrap(); - debug!("shard config should be initialized on litentry network now"); - (true, true) - } else { - (true, false) - } - } else { - println!("We are NOT primary worker, the primary worker is {}", account); - if first_run { - // obtain provisioning from last active worker as this hasn't been done before - info!("my state doesn't know the creation header of the shard. will request provisioning"); - sync_state::sync_state::<_, _>( - &litentry_rpc_api, - &shard, - enclave.as_ref(), - skip_ra, - ); - } - (false, true) - } - }, - None => { - panic!("No primary enclave account is found - was the enclave successfully registered?"); - }, - }; - debug!("getting shard creation: {:?}", enclave.get_shard_creation_info(shard)); - initialization_handler.registered_on_parentchain(); - - let (integritee_parentchain_handler, integritee_last_synced_header_at_last_run) = - if re_init_parentchain_needed { - // re-initialize integritee parentchain to make sure to use creation_header for fast-sync or the provisioned light client state - init_parentchain( - &enclave, - &litentry_rpc_api, - &tee_accountid, - ParentchainId::Litentry, - shard, - ) - } else { - (integritee_parentchain_handler, integritee_last_synced_header_at_last_run) - }; - - println!("[Litentry:OCW] Finished initializing light client, syncing parentchain..."); - - // Litentry: apply skipped parentchain block - let parentchain_start_block = config - .try_parse_parentchain_start_block() - .expect("parentchain start block to be a valid number"); - - // Syncing all parentchain blocks, this might take a while.. - let last_synced_header = integritee_parentchain_handler - .sync_parentchain_until_latest_finalized( - integritee_last_synced_header_at_last_run, - parentchain_start_block, - *shard, - true, - ) - .unwrap(); - - start_parentchain_header_subscription_thread( - integritee_parentchain_handler, - last_synced_header, - *shard, - ); - info!("skipping shard vault check because not yet supported for offchain worker"); - - let maybe_target_a_rpc_api = if let Some(url) = config.target_a_parentchain_rpc_endpoint() { - Some(init_target_parentchain( - &enclave, - &tee_accountid, - url, - shard, - ParentchainId::TargetA, - is_development_mode, - )) - } else { - None - }; - - let maybe_target_b_rpc_api = if let Some(url) = config.target_b_parentchain_rpc_endpoint() { - Some(init_target_parentchain( - &enclave, - &tee_accountid, - url, - shard, - ParentchainId::TargetB, - is_development_mode, - )) - } else { - None - }; - - // Publish generated custiodian wallets - enclave.publish_wallets(); - enclave.finish_enclave_init(); - - ita_parentchain_interface::event_subscriber::subscribe_to_parentchain_events( - &litentry_rpc_api, - ParentchainId::Litentry, - ); -} - -fn init_target_parentchain( - enclave: &Arc, - tee_account_id: &AccountId32, - url: String, - shard: &ShardIdentifier, - parentchain_id: ParentchainId, - is_development_mode: bool, -) -> ParentchainApi -where - E: EnclaveBase + Sidechain, -{ - println!("Initializing parentchain {:?} with url: {}", parentchain_id, url); - let node_api = NodeApiFactory::new(url, AccountKeyring::Alice.pair()) - .create_api() - .unwrap_or_else(|_| panic!("[{:?}] Failed to create parentchain node API", parentchain_id)); - - setup_reasonable_account_funding( - &node_api, - tee_account_id, - parentchain_id, - is_development_mode, - ) - .unwrap_or_else(|_| { - panic!("[{:?}] Could not fund parentchain enclave account", parentchain_id) - }); - - // we attempt to set shard creation for this parentchain in case it hasn't been done before - let api_head = node_api.get_header(None).unwrap().unwrap(); - // TODO: #1451: Fix api-client type hacks - let head = Header::decode(&mut api_head.encode().as_slice()) - .expect("Can decode previously encoded header; qed"); - // we ignore failure - let _ = enclave.init_shard_creation_parentchain_header(shard, &parentchain_id, &head); - - let (parentchain_handler, last_synched_header) = - init_parentchain(enclave, &node_api, tee_account_id, parentchain_id, shard); - - println!("[{:?}] Finished initializing light client, syncing parentchain...", parentchain_id); - - // Syncing all parentchain blocks, this might take a while.. - let last_synched_header = parentchain_handler - .sync_parentchain_until_latest_finalized(last_synched_header, 0, *shard, true) - .unwrap(); - - start_parentchain_header_subscription_thread( - parentchain_handler.clone(), - last_synched_header, - *shard, - ); - - let parentchain_init_params = parentchain_handler.parentchain_init_params.clone(); - - let node_api_clone = node_api.clone(); - thread::Builder::new() - .name(format!("{:?}_parentchain_event_subscription", parentchain_id)) - .spawn(move || { - ita_parentchain_interface::event_subscriber::subscribe_to_parentchain_events( - &node_api_clone, - parentchain_id, - ) - }) - .unwrap(); - node_api -} - -fn init_parentchain( - enclave: &Arc, - node_api: &ParentchainApi, - tee_account_id: &AccountId32, - parentchain_id: ParentchainId, - shard: &ShardIdentifier, -) -> (Arc>, Header) -where - E: EnclaveBase + Sidechain, -{ - let parentchain_handler = Arc::new( - ParentchainHandler::new_with_automatic_light_client_allocation( - node_api.clone(), - enclave.clone(), - parentchain_id, - *shard, - ) - .unwrap(), - ); - let last_synced_header = parentchain_handler.init_parentchain_components().unwrap(); - println!("[{:?}] last synced parentchain block: {}", parentchain_id, last_synced_header.number); - - let nonce = node_api.get_account_next_index(tee_account_id).unwrap(); - info!("[{:?}] Enclave nonce = {:?}", parentchain_id, nonce); - enclave.set_nonce(nonce, parentchain_id).unwrap_or_else(|_| { - panic!("[{:?}] Could not set nonce of enclave. Returning here...", parentchain_id) - }); - - let metadata = node_api.metadata().clone(); - let runtime_spec_version = node_api.runtime_version().spec_version; - let runtime_transaction_version = node_api.runtime_version().transaction_version; - enclave - .set_node_metadata( - NodeMetadata::new(metadata, runtime_spec_version, runtime_transaction_version).encode(), - parentchain_id, - ) - .unwrap_or_else(|_| { - panic!("[{:?}] Could not set the node metadata in the enclave", parentchain_id) - }); - - (parentchain_handler, last_synced_header) -} - -/// Start polling loop to wait until we have a worker for a shard registered on -/// the parentchain (TEEBAG EnclaveIdentifier). This is the pre-requisite to be -/// considered initialized and ready for the next worker to start (in sidechain mode only). -fn spawn_worker_for_shard_polling( - shard: &ShardIdentifier, - node_api: ParentchainApi, - initialization_handler: Arc, -) where - InitializationHandler: TrackInitialization + Sync + Send + 'static, -{ - let shard_for_initialized = *shard; - thread::spawn(move || { - const POLL_INTERVAL_SECS: u64 = 2; - - loop { - info!("Polling for worker for shard ({} seconds interval)", POLL_INTERVAL_SECS); - if let Ok(Some(_account)) = node_api.primary_enclave_identifier_for_shard( - WorkerType::BitAcross, - &shard_for_initialized, - None, - ) { - // Set that the service is initialized. - initialization_handler.worker_for_shard_registered(); - println!("[+] Found `WorkerForShard` on parentchain state",); - break - } - thread::sleep(Duration::from_secs(POLL_INTERVAL_SECS)); - } - }); -} - -#[cfg(feature = "attesteer")] -fn fetch_marblerun_events_every_hour( - api: ParentchainApi, - enclave: Arc, - accountid: AccountId32, - is_development_mode: bool, - url: String, - marblerun_base_url: String, -) where - E: RemoteAttestation + Clone + Sync + Send + 'static, -{ - let enclave = enclave.clone(); - let handle = thread::spawn(move || { - const POLL_INTERVAL_5_MINUTES_IN_SECS: u64 = 5 * 60; - loop { - info!("Polling marblerun events for quotes to register"); - register_quotes_from_marblerun( - &api, - enclave.clone(), - &accountid, - is_development_mode, - url.clone(), - &marblerun_base_url, - ); - - thread::sleep(Duration::from_secs(POLL_INTERVAL_5_MINUTES_IN_SECS)); - } - }); - - handle.join().unwrap() -} -#[cfg(feature = "attesteer")] -fn register_quotes_from_marblerun( - api: &ParentchainApi, - enclave: Arc, - accountid: &AccountId32, - is_development_mode: bool, - url: String, - marblerun_base_url: &str, -) { - let enclave = enclave.as_ref(); - let events = crate::prometheus_metrics::fetch_marblerun_events(marblerun_base_url) - .map_err(|e| { - info!("Fetching events from Marblerun failed with: {:?}, continuing with 0 events.", e); - }) - .unwrap_or_default(); - let quotes: Vec<&[u8]> = - events.iter().map(|event| event.get_quote_without_prepended_bytes()).collect(); - - for quote in quotes { - match enclave.generate_dcap_ra_extrinsic_from_quote(url.clone(), "e) { - Ok(xt) => { - send_litentry_extrinsic(xt, api, accountid, is_development_mode); - }, - Err(e) => { - error!("Extracting information from quote failed: {}", e) - }, - } - } -} -#[cfg(feature = "dcap")] -fn register_collateral( - api: &ParentchainApi, - enclave: &dyn RemoteAttestation, - accountid: &AccountId32, - is_development_mode: bool, - skip_ra: bool, -) { - //TODO generate_dcap_ra_quote() does not really need skip_ra, rethink how many layers skip_ra should be passed along - if !skip_ra { - let dcap_quote = enclave.generate_dcap_ra_quote(skip_ra).unwrap(); - let (fmspc, _tcb_info) = extract_tcb_info_from_raw_dcap_quote(&dcap_quote).unwrap(); - println!("[>] DCAP setup: register QE collateral"); - let uxt = enclave.generate_register_quoting_enclave_extrinsic(fmspc).unwrap(); - send_litentry_extrinsic(uxt, api, accountid, is_development_mode); - - println!("[>] DCAP setup: register TCB info"); - let uxt = enclave.generate_register_tcb_info_extrinsic(fmspc).unwrap(); - send_litentry_extrinsic(uxt, api, accountid, is_development_mode); - } -} - -fn send_litentry_extrinsic( - extrinsic: Vec, - api: &ParentchainApi, - fee_payer: &AccountId32, - is_development_mode: bool, -) -> ServiceResult { - let fee = crate::account_funding::estimate_fee(api, extrinsic.clone())?; - let ed = api.get_existential_deposit()?; - let free = api.get_free_balance(fee_payer)?; - let missing_funds = fee.saturating_add(ed).saturating_sub(free); - info!("[Litentry] send extrinsic"); - debug!("fee: {:?}, ed: {:?}, free: {:?} => missing: {:?}", fee, ed, free, missing_funds); - trace!( - " encoded extrinsic len: {}, payload: 0x{:}", - extrinsic.len(), - hex::encode(extrinsic.clone()) - ); - - if missing_funds > 0 { - setup_reasonable_account_funding( - api, - fee_payer, - ParentchainId::Litentry, - is_development_mode, - )? - } - - match api.submit_and_watch_opaque_extrinsic_until(&extrinsic.into(), XtStatus::Finalized) { - Ok(xt_report) => { - info!( - "[+] L1 extrinsic success. extrinsic hash: {:?} / status: {:?}", - xt_report.extrinsic_hash, xt_report.status - ); - xt_report.block_hash.ok_or(Error::Custom("no extrinsic hash returned".into())) - }, - Err(e) => { - panic!("Extrinsic failed {:?} parentchain genesis: {:?}", e, api.genesis_hash()); - }, - } -} - -fn start_parentchain_header_subscription_thread( - parentchain_handler: Arc>, - last_synced_header: Header, - shard: ShardIdentifier, -) { - let parentchain_id = *parentchain_handler.parentchain_id(); - thread::Builder::new() - .name(format!("{:?}_parentchain_sync_loop", parentchain_id)) - .spawn(move || { - if let Err(e) = - subscribe_to_parentchain_new_headers(parentchain_handler, last_synced_header, shard) - { - error!( - "[{:?}] parentchain block syncing terminated with a failure: {:?}", - parentchain_id, e - ); - } - println!("[!] [{:?}] parentchain block syncing has terminated", parentchain_id); - }) - .unwrap(); -} - -/// Subscribe to the node API finalized heads stream and trigger a parent chain sync -/// upon receiving a new header. -fn subscribe_to_parentchain_new_headers( - parentchain_handler: Arc>, - mut last_synced_header: Header, - shard: ShardIdentifier, -) -> Result<(), Error> { - // TODO: this should be implemented by parentchain_handler directly, and not via - // exposed parentchain_api - let mut subscription = parentchain_handler - .parentchain_api() - .subscribe_finalized_heads() - .map_err(Error::ApiClient)?; - - // TODO(Kai@Litentry): - // originally we had an outer loop to try to handle the disconnection, - // see https://github.com/litentry/litentry-parachain/commit/b8059d0fad928e4bba99178451cd0d473791c437 - // but I reverted it because: - // - no graceful shutdown, we could have many mpsc channel when it doesn't go right - // - we might have multiple `sync_parentchain` running concurrently, which causes chaos in enclave side - // - I still feel it's only a workaround, not a perfect solution - // - // TODO: now the sync will panic if disconnected - it heavily relys on the worker-restart to work (even manually) - let parentchain_id = parentchain_handler.parentchain_id(); - loop { - let new_header = subscription - .next() - .ok_or(Error::ApiSubscriptionDisconnected)? - .map_err(|e| Error::ApiClient(e.into()))?; - - info!( - "[{:?}] Received finalized header update ({}), syncing parent chain...", - parentchain_id, new_header.number - ); - - last_synced_header = parentchain_handler.sync_parentchain_until_latest_finalized( - last_synced_header, - 0, - shard, - false, - )?; - } -} - -/// Get the public signing key of the TEE. -pub fn enclave_account(enclave_api: &E) -> AccountId32 { - let tee_public = enclave_api.get_ecc_signing_pubkey().unwrap(); - trace!("[+] Got ed25519 account of TEE = {}", tee_public.to_ss58check()); - AccountId32::from(*tee_public.as_array_ref()) -} diff --git a/tee-worker/bitacross/service/src/ocall_bridge/bridge_api.rs b/tee-worker/bitacross/service/src/ocall_bridge/bridge_api.rs deleted file mode 100644 index b3d3a68efa..0000000000 --- a/tee-worker/bitacross/service/src/ocall_bridge/bridge_api.rs +++ /dev/null @@ -1,236 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - Copyright (C) 2017-2019 Baidu, Inc. All Rights Reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use itp_enclave_api::remote_attestation::QveReport; -use lazy_static::lazy_static; -use log::*; -use parking_lot::RwLock; -use sgx_types::*; -use std::{sync::Arc, vec::Vec}; - -#[cfg(test)] -use mockall::predicate::*; -#[cfg(test)] -use mockall::*; - -lazy_static! { - /// global state for the component factory - /// access is always routed through 'Bridge', do not use directly! - static ref COMPONENT_FACTORY: RwLock>> = - RwLock::new(None); -} - -/// The Bridge is the static/global interface to inject concrete implementations -/// (or rather the factories for them) - this is done at startup of the worker. -/// On the other side, it is used by the o-call FFI to retrieve the state and forward calls -/// to their respective implementation. -pub struct Bridge; - -impl Bridge { - pub fn get_ra_api() -> Arc { - trace!("Requesting RemoteAttestation OCall API instance"); - - COMPONENT_FACTORY - .read() - .as_ref() - .expect("Component factory has not been set. Use `initialize()`") - .get_ra_api() - } - - pub fn get_oc_api() -> Arc { - trace!("Requesting WorkerOnChain OCall API instance"); - - COMPONENT_FACTORY - .read() - .as_ref() - .expect("Component factory has not been set. Use `initialize()`") - .get_oc_api() - } - - pub fn get_ipfs_api() -> Arc { - trace!("Requesting IPFS OCall API instance"); - - COMPONENT_FACTORY - .read() - .as_ref() - .expect("Component factory has not been set. Use `initialize()`") - .get_ipfs_api() - } - - pub fn get_metrics_api() -> Arc { - COMPONENT_FACTORY - .read() - .as_ref() - .expect("Component factory has not been set. Use `initialize()`") - .get_metrics_api() - } - - pub fn initialize(component_factory: Arc) { - trace!("Initializing OCall bridge with component factory"); - - *COMPONENT_FACTORY.write() = Some(component_factory); - } -} - -/// Factory trait (abstract factory) that creates instances -/// of all the components of the OCall Bridge -pub trait GetOCallBridgeComponents { - /// remote attestation OCall API - fn get_ra_api(&self) -> Arc; - - /// on chain (parentchain) OCall API - fn get_oc_api(&self) -> Arc; - - /// ipfs OCall API - fn get_ipfs_api(&self) -> Arc; - - /// Metrics OCall API. - fn get_metrics_api(&self) -> Arc; -} - -/// OCall bridge errors -#[derive(Debug, thiserror::Error)] -pub enum OCallBridgeError { - #[error("GetQuote Error: {0}")] - GetQuote(sgx_status_t), - #[error("InitQuote Error: {0}")] - InitQuote(sgx_status_t), - #[error("GetUpdateInfo Error: {0}")] - GetUpdateInfo(sgx_status_t), - #[error("GetIasSocket Error: {0}")] - GetIasSocket(String), - #[error("UpdateMetric Error: {0}")] - UpdateMetric(String), - #[error("Propose sidechain block failed: {0}")] - ProposeSidechainBlock(String), - #[error("Failed to fetch sidechain blocks from peer: {0}")] - FetchSidechainBlocksFromPeer(String), - #[error("Sending extrinsics to parentchain failed: {0}")] - SendExtrinsicsToParentchain(String), - #[error("IPFS Error: {0}")] - IpfsError(String), - #[error("DirectInvocation Error: {0}")] - DirectInvocationError(String), - #[error(transparent)] - Codec(#[from] codec::Error), - #[error("Node API factory error: {0}")] - NodeApiFactory(#[from] itp_node_api::node_api_factory::NodeApiFactoryError), - #[error("Target A parentchain not initialized")] - TargetAParentchainNotInitialized, - #[error("Target B parentchain not initialized")] - TargetBParentchainNotInitialized, -} - -impl From for sgx_status_t { - fn from(o: OCallBridgeError) -> sgx_status_t { - match o { - OCallBridgeError::GetQuote(s) => s, - OCallBridgeError::InitQuote(s) => s, - OCallBridgeError::GetUpdateInfo(s) => s, - _ => sgx_status_t::SGX_ERROR_UNEXPECTED, - } - } -} - -pub type OCallBridgeResult = Result; - -/// Trait for all the OCalls related to remote attestation -#[cfg_attr(test, automock)] -pub trait RemoteAttestationBridge { - /// initialize the quote - fn init_quote(&self) -> OCallBridgeResult<(sgx_target_info_t, sgx_epid_group_id_t)>; - - /// get the intel attestation service socket - fn get_ias_socket(&self) -> OCallBridgeResult; - - /// retrieve the quote from intel - fn get_quote( - &self, - revocation_list: Vec, - report: sgx_report_t, - quote_type: sgx_quote_sign_type_t, - spid: sgx_spid_t, - quote_nonce: sgx_quote_nonce_t, - ) -> OCallBridgeResult<(sgx_report_t, Vec)>; - - /// retrieve the quote from dcap server - fn get_dcap_quote(&self, report: sgx_report_t, quote_size: u32) -> OCallBridgeResult>; - - // Retrieve verification of quote - fn get_qve_report_on_quote( - &self, - quote: Vec, - current_time: i64, - quote_collateral: &sgx_ql_qve_collateral_t, - qve_report_info: sgx_ql_qe_report_info_t, - supplemental_data_size: u32, - ) -> OCallBridgeResult; - - /// -- - fn get_update_info( - &self, - platform_blob: sgx_platform_info_t, - enclave_trusted: i32, - ) -> OCallBridgeResult; -} - -/// Trait for all the OCalls related to parentchain operations -#[cfg_attr(test, automock)] -pub trait WorkerOnChainBridge { - fn worker_request( - &self, - request: Vec, - parentchain_id: Vec, - ) -> OCallBridgeResult>; - - fn send_to_parentchain( - &self, - extrinsics_encoded: Vec, - parentchain_id: Vec, - watch_until: Vec, - ) -> OCallBridgeResult>; -} - -/// Trait for updating metrics from inside the enclave. -#[cfg_attr(test, automock)] -pub trait MetricsBridge { - fn update_metric(&self, metric_encoded: Vec) -> OCallBridgeResult<()>; -} - -/// type for IPFS -pub type Cid = [u8; 46]; - -/// Trait for all the OCalls related to IPFS -#[cfg_attr(test, automock)] -pub trait IpfsBridge { - fn write_to_ipfs(&self, data: &'static [u8]) -> OCallBridgeResult; - - fn read_from_ipfs(&self, cid: Cid) -> OCallBridgeResult<()>; -} - -/// Trait for the direct invocation OCalls -#[cfg_attr(test, automock)] -pub trait DirectInvocationBridge { - fn update_status_event( - &self, - hash_vec: Vec, - status_update_vec: Vec, - ) -> OCallBridgeResult<()>; - - fn send_status(&self, hash_vec: Vec, status_vec: Vec) -> OCallBridgeResult<()>; -} diff --git a/tee-worker/bitacross/service/src/ocall_bridge/component_factory.rs b/tee-worker/bitacross/service/src/ocall_bridge/component_factory.rs deleted file mode 100644 index d82d108937..0000000000 --- a/tee-worker/bitacross/service/src/ocall_bridge/component_factory.rs +++ /dev/null @@ -1,117 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - Copyright (C) 2017-2019 Baidu, Inc. All Rights Reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use crate::{ - globals::tokio_handle::GetTokioHandle, - ocall_bridge::{ - bridge_api::{ - GetOCallBridgeComponents, IpfsBridge, MetricsBridge, RemoteAttestationBridge, - WorkerOnChainBridge, - }, - ipfs_ocall::IpfsOCall, - metrics_ocall::MetricsOCall, - remote_attestation_ocall::RemoteAttestationOCall, - worker_on_chain_ocall::WorkerOnChainOCall, - }, - prometheus_metrics::ReceiveEnclaveMetrics, - worker_peers_updater::PeersRegistry, -}; -use itp_enclave_api::{enclave_base::EnclaveBase, remote_attestation::RemoteAttestationCallBacks}; -use itp_node_api::node_api_factory::CreateNodeApi; -use std::sync::Arc; - -/// Concrete implementation, should be moved out of the OCall Bridge, into the worker -/// since the OCall bridge itself should not know any concrete types to ensure -/// our dependency graph is worker -> ocall bridge -pub struct OCallBridgeComponentFactory< - NodeApi, - EnclaveApi, - WorkerPeersRegistry, - TokioHandle, - MetricsReceiver, -> { - integritee_rpc_api_factory: Arc, - target_a_parentchain_rpc_api_factory: Option>, - target_b_parentchain_rpc_api_factory: Option>, - enclave_api: Arc, - peers_registry: Arc, - tokio_handle: Arc, - metrics_receiver: Arc, -} - -impl - OCallBridgeComponentFactory -{ - #[allow(clippy::too_many_arguments)] - pub fn new( - integritee_rpc_api_factory: Arc, - target_a_parentchain_rpc_api_factory: Option>, - target_b_parentchain_rpc_api_factory: Option>, - enclave_api: Arc, - peers_registry: Arc, - tokio_handle: Arc, - metrics_receiver: Arc, - ) -> Self { - OCallBridgeComponentFactory { - integritee_rpc_api_factory, - target_a_parentchain_rpc_api_factory, - target_b_parentchain_rpc_api_factory, - enclave_api, - peers_registry, - tokio_handle, - metrics_receiver, - } - } -} - -impl - GetOCallBridgeComponents - for OCallBridgeComponentFactory< - NodeApi, - EnclaveApi, - WorkerPeersRegistry, - TokioHandle, - MetricsReceiver, - > where - NodeApi: CreateNodeApi + 'static, - EnclaveApi: EnclaveBase + RemoteAttestationCallBacks + 'static, - WorkerPeersRegistry: PeersRegistry + 'static, - TokioHandle: GetTokioHandle + 'static, - MetricsReceiver: ReceiveEnclaveMetrics + 'static, -{ - fn get_ra_api(&self) -> Arc { - Arc::new(RemoteAttestationOCall::new(self.enclave_api.clone())) - } - - fn get_oc_api(&self) -> Arc { - Arc::new(WorkerOnChainOCall::new( - self.enclave_api.clone(), - self.integritee_rpc_api_factory.clone(), - self.target_a_parentchain_rpc_api_factory.clone(), - self.target_b_parentchain_rpc_api_factory.clone(), - )) - } - - fn get_ipfs_api(&self) -> Arc { - Arc::new(IpfsOCall {}) - } - - fn get_metrics_api(&self) -> Arc { - Arc::new(MetricsOCall::new(self.metrics_receiver.clone())) - } -} diff --git a/tee-worker/bitacross/service/src/ocall_bridge/ffi/get_ias_socket.rs b/tee-worker/bitacross/service/src/ocall_bridge/ffi/get_ias_socket.rs deleted file mode 100644 index 4b48d2b1ad..0000000000 --- a/tee-worker/bitacross/service/src/ocall_bridge/ffi/get_ias_socket.rs +++ /dev/null @@ -1,86 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - Copyright (C) 2017-2019 Baidu, Inc. All Rights Reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use crate::ocall_bridge::bridge_api::{Bridge, RemoteAttestationBridge}; -use log::*; -use sgx_types::{c_int, sgx_status_t}; -use std::sync::Arc; - -#[no_mangle] -pub extern "C" fn ocall_get_ias_socket(ret_fd: *mut c_int) -> sgx_status_t { - get_ias_socket(ret_fd, Bridge::get_ra_api()) // inject the RA API (global state) -} - -fn get_ias_socket(ret_fd: *mut c_int, ra_api: Arc) -> sgx_status_t { - debug!(" Entering ocall_get_ias_socket"); - let socket_result = ra_api.get_ias_socket(); - - return match socket_result { - Ok(s) => { - unsafe { - *ret_fd = s; - } - sgx_status_t::SGX_SUCCESS - }, - Err(e) => { - error!("[-] Failed to get IAS socket: {:?}", e); - return e.into() - }, - } -} - -#[cfg(test)] -mod tests { - - use super::*; - use crate::ocall_bridge::bridge_api::{MockRemoteAttestationBridge, OCallBridgeError}; - use std::sync::Arc; - - #[test] - fn get_socket_sets_pointer_result() { - let expected_socket = 4321i32; - - let mut ra_ocall_api_mock = MockRemoteAttestationBridge::new(); - ra_ocall_api_mock - .expect_get_ias_socket() - .times(1) - .returning(move || Ok(expected_socket)); - - let mut ias_sock: i32 = 0; - - let ret_status = get_ias_socket(&mut ias_sock as *mut i32, Arc::new(ra_ocall_api_mock)); - - assert_eq!(ret_status, sgx_status_t::SGX_SUCCESS); - assert_eq!(ias_sock, expected_socket); - } - - #[test] - fn given_error_from_ocall_impl_then_return_sgx_error() { - let mut ra_ocall_api_mock = MockRemoteAttestationBridge::new(); - ra_ocall_api_mock - .expect_get_ias_socket() - .times(1) - .returning(|| Err(OCallBridgeError::GetIasSocket("test error".to_string()))); - - let mut ias_sock: i32 = 0; - let ret_status = get_ias_socket(&mut ias_sock as *mut i32, Arc::new(ra_ocall_api_mock)); - - assert_ne!(ret_status, sgx_status_t::SGX_SUCCESS); - assert_eq!(ias_sock, 0); - } -} diff --git a/tee-worker/bitacross/service/src/ocall_bridge/ffi/get_quote.rs b/tee-worker/bitacross/service/src/ocall_bridge/ffi/get_quote.rs deleted file mode 100644 index abf2954170..0000000000 --- a/tee-worker/bitacross/service/src/ocall_bridge/ffi/get_quote.rs +++ /dev/null @@ -1,140 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - Copyright (C) 2017-2019 Baidu, Inc. All Rights Reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use crate::ocall_bridge::bridge_api::{Bridge, RemoteAttestationBridge}; -use log::*; -use sgx_types::{sgx_quote_nonce_t, sgx_quote_sign_type_t, sgx_report_t, sgx_spid_t, sgx_status_t}; -use std::{slice, sync::Arc}; - -/// p_quote must be a pre-allocated memory region of size `maxlen` -#[no_mangle] -pub unsafe extern "C" fn ocall_get_quote( - p_sigrl: *const u8, - sigrl_len: u32, - p_report: *const sgx_report_t, - quote_type: sgx_quote_sign_type_t, - p_spid: *const sgx_spid_t, - p_nonce: *const sgx_quote_nonce_t, - p_qe_report: *mut sgx_report_t, - p_quote: *mut u8, - maxlen: u32, - p_quote_len: *mut u32, -) -> sgx_status_t { - get_quote( - p_sigrl, - sigrl_len, - p_report, - quote_type, - p_spid, - p_nonce, - p_qe_report, - p_quote, - maxlen, - p_quote_len, - Bridge::get_ra_api(), // inject the RA API (global state) - ) -} - -#[allow(clippy::too_many_arguments)] -fn get_quote( - p_sigrl: *const u8, - sigrl_len: u32, - p_report: *const sgx_report_t, - quote_type: sgx_quote_sign_type_t, - p_spid: *const sgx_spid_t, - p_nonce: *const sgx_quote_nonce_t, - p_qe_report: *mut sgx_report_t, - p_quote: *mut u8, - maxlen: u32, - p_quote_len: *mut u32, - ra_api: Arc, -) -> sgx_status_t { - debug!(" Entering ocall_get_quote"); - - let revocation_list: Vec = - unsafe { slice::from_raw_parts(p_sigrl, sigrl_len as usize).to_vec() }; - - let report = unsafe { *p_report }; - let spid = unsafe { *p_spid }; - let quote_nonce = unsafe { *p_nonce }; - - let get_quote_result = - match ra_api.get_quote(revocation_list, report, quote_type, spid, quote_nonce) { - Ok(r) => r, - Err(e) => { - error!("[-] Failed to get quote: {:?}", e); - return e.into() - }, - }; - - let quote = get_quote_result.1; - - if quote.len() as u32 > maxlen { - return sgx_status_t::SGX_ERROR_FAAS_BUFFER_TOO_SHORT - } - - let quote_slice = unsafe { slice::from_raw_parts_mut(p_quote, quote.len()) }; - quote_slice.clone_from_slice(quote.as_slice()); - - unsafe { - *p_qe_report = get_quote_result.0; - *p_quote_len = quote.len() as u32; - }; - - sgx_status_t::SGX_SUCCESS -} - -#[no_mangle] -pub unsafe extern "C" fn ocall_get_dcap_quote( - p_report: *const sgx_report_t, - p_quote: *mut u8, - quote_size: u32, -) -> sgx_status_t { - get_dcap_quote( - p_report, - p_quote, - quote_size, - Bridge::get_ra_api(), // inject the RA API (global state) - ) -} - -fn get_dcap_quote( - p_report: *const sgx_report_t, - p_quote: *mut u8, - quote_size: u32, - ra_api: Arc, -) -> sgx_status_t { - let report = unsafe { *p_report }; - - let quote = match ra_api.get_dcap_quote(report, quote_size) { - Ok(r) => r, - Err(e) => { - error!("Failed to get dcap quote: {:?}", e); - return e.into() - }, - }; - - if quote.len() as u32 > quote_size { - return sgx_status_t::SGX_ERROR_FAAS_BUFFER_TOO_SHORT - } - - let quote_slice = unsafe { slice::from_raw_parts_mut(p_quote, quote.len()) }; - quote_slice.clone_from_slice(quote.as_slice()); - - sgx_status_t::SGX_SUCCESS -} diff --git a/tee-worker/bitacross/service/src/ocall_bridge/ffi/get_qve_report_on_quote.rs b/tee-worker/bitacross/service/src/ocall_bridge/ffi/get_qve_report_on_quote.rs deleted file mode 100755 index 2b73894830..0000000000 --- a/tee-worker/bitacross/service/src/ocall_bridge/ffi/get_qve_report_on_quote.rs +++ /dev/null @@ -1,100 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - Copyright (C) 2017-2019 Baidu, Inc. All Rights Reserved. - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - http://www.apache.org/licenses/LICENSE-2.0 - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ - -use crate::ocall_bridge::bridge_api::{Bridge, RemoteAttestationBridge}; -use log::*; -use sgx_types::*; -use std::{slice, sync::Arc}; - -#[no_mangle] -pub unsafe extern "C" fn ocall_get_qve_report_on_quote( - p_quote: *const u8, - quote_len: u32, - current_time: i64, - p_quote_collateral: *const sgx_ql_qve_collateral_t, - p_collateral_expiration_status: *mut u32, - p_quote_verification_result: *mut sgx_ql_qv_result_t, - p_qve_report_info: *mut sgx_ql_qe_report_info_t, - p_supplemental_data: *mut u8, - supplemental_data_size: u32, -) -> sgx_status_t { - get_qve_report_on_quote( - p_quote, - quote_len, - current_time, - p_quote_collateral, - p_collateral_expiration_status, - p_quote_verification_result, - p_qve_report_info, - p_supplemental_data, - supplemental_data_size, - Bridge::get_ra_api(), // inject the RA API (global state) - ) -} - -#[allow(clippy::too_many_arguments)] -fn get_qve_report_on_quote( - p_quote: *const u8, - quote_len: u32, - current_time: i64, - p_quote_collateral: *const sgx_ql_qve_collateral_t, - p_collateral_expiration_status: *mut u32, - p_quote_verification_result: *mut sgx_ql_qv_result_t, - p_qve_report_info: *mut sgx_ql_qe_report_info_t, - p_supplemental_data: *mut u8, - supplemental_data_size: u32, - ra_api: Arc, -) -> sgx_status_t { - debug!("Entering ocall_get_qve_report_on_quote"); - if p_quote.is_null() - || quote_len == 0 - || p_quote_collateral.is_null() - || p_collateral_expiration_status.is_null() - || p_quote_verification_result.is_null() - || p_qve_report_info.is_null() - || p_supplemental_data.is_null() - || supplemental_data_size == 0 - { - return sgx_status_t::SGX_ERROR_INVALID_PARAMETER - } - let quote: Vec = unsafe { slice::from_raw_parts(p_quote, quote_len as usize).to_vec() }; - let quote_collateral = unsafe { &*p_quote_collateral }; - let qve_report_info = unsafe { *p_qve_report_info }; - - let qve_report = match ra_api.get_qve_report_on_quote( - quote, - current_time, - quote_collateral, - qve_report_info, - supplemental_data_size, - ) { - Ok(return_values) => return_values, - Err(e) => { - error!("Failed to get quote: {:?}", e); - return e.into() - }, - }; - - let supplemental_data_slice = - unsafe { slice::from_raw_parts_mut(p_supplemental_data, supplemental_data_size as usize) }; - supplemental_data_slice.clone_from_slice(qve_report.supplemental_data.as_slice()); - - unsafe { - *p_collateral_expiration_status = qve_report.collateral_expiration_status; - *p_quote_verification_result = qve_report.quote_verification_result; - *p_qve_report_info = qve_report.qve_report_info_return_value; - }; - - sgx_status_t::SGX_SUCCESS -} diff --git a/tee-worker/bitacross/service/src/ocall_bridge/ffi/get_update_info.rs b/tee-worker/bitacross/service/src/ocall_bridge/ffi/get_update_info.rs deleted file mode 100644 index 55a9c7bfb4..0000000000 --- a/tee-worker/bitacross/service/src/ocall_bridge/ffi/get_update_info.rs +++ /dev/null @@ -1,61 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - Copyright (C) 2017-2019 Baidu, Inc. All Rights Reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use crate::ocall_bridge::bridge_api::{Bridge, RemoteAttestationBridge}; -use log::*; -use sgx_types::{sgx_platform_info_t, sgx_status_t, sgx_update_info_bit_t}; -use std::sync::Arc; - -#[no_mangle] -pub extern "C" fn ocall_get_update_info( - p_platform_blob: *const sgx_platform_info_t, - enclave_trusted: i32, - p_update_info: *mut sgx_update_info_bit_t, -) -> sgx_status_t { - get_update_info( - p_platform_blob, - enclave_trusted, - p_update_info, - Bridge::get_ra_api(), // inject the RA API (global state) - ) -} - -fn get_update_info( - p_platform_blob: *const sgx_platform_info_t, - enclave_trusted: i32, - p_update_info: *mut sgx_update_info_bit_t, - ra_api: Arc, -) -> sgx_status_t { - debug!(" Entering ocall_get_update_info"); - - let platform_blob = unsafe { *p_platform_blob }; - - let update_info_result = match ra_api.get_update_info(platform_blob, enclave_trusted) { - Ok(r) => r, - Err(e) => { - error!("[-] Failed to get update info: {:?}", e); - return e.into() - }, - }; - - unsafe { - *p_update_info = update_info_result; - } - - sgx_status_t::SGX_SUCCESS -} diff --git a/tee-worker/bitacross/service/src/ocall_bridge/ffi/init_quote.rs b/tee-worker/bitacross/service/src/ocall_bridge/ffi/init_quote.rs deleted file mode 100644 index 095e01af6d..0000000000 --- a/tee-worker/bitacross/service/src/ocall_bridge/ffi/init_quote.rs +++ /dev/null @@ -1,85 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - Copyright (C) 2017-2019 Baidu, Inc. All Rights Reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use crate::ocall_bridge::bridge_api::{Bridge, RemoteAttestationBridge}; -use log::*; -use sgx_types::{sgx_epid_group_id_t, sgx_status_t, sgx_target_info_t}; -use std::sync::Arc; - -#[no_mangle] -pub unsafe extern "C" fn ocall_sgx_init_quote( - ret_ti: *mut sgx_target_info_t, - ret_gid: *mut sgx_epid_group_id_t, -) -> sgx_status_t { - sgx_init_quote(ret_ti, ret_gid, Bridge::get_ra_api()) // inject the RA API (global state) -} - -fn sgx_init_quote( - ret_ti: *mut sgx_target_info_t, - ret_gid: *mut sgx_epid_group_id_t, - ra_api: Arc, -) -> sgx_status_t { - debug!(" Entering ocall_sgx_init_quote"); - let init_result = match ra_api.init_quote() { - Ok(r) => r, - Err(e) => { - error!("[-] Failed to init quote: {:?}", e); - return e.into() - }, - }; - - unsafe { - *ret_ti = init_result.0; - *ret_gid = init_result.1; - } - - sgx_status_t::SGX_SUCCESS -} - -#[cfg(test)] -mod tests { - - use super::*; - use crate::ocall_bridge::bridge_api::MockRemoteAttestationBridge; - use std::sync::Arc; - - #[test] - fn init_quote_sets_results() { - let mut ra_ocall_api_mock = MockRemoteAttestationBridge::new(); - ra_ocall_api_mock - .expect_init_quote() - .times(1) - .returning(|| Ok((dummy_target_info(), [8u8; 4]))); - - let mut ti: sgx_target_info_t = sgx_target_info_t::default(); - let mut eg: sgx_epid_group_id_t = sgx_epid_group_id_t::default(); - - let ret_status = sgx_init_quote( - &mut ti as *mut sgx_target_info_t, - &mut eg as *mut sgx_epid_group_id_t, - Arc::new(ra_ocall_api_mock), - ); - - assert_eq!(ret_status, sgx_status_t::SGX_SUCCESS); - assert_eq!(eg, [8u8; 4]); - } - - fn dummy_target_info() -> sgx_target_info_t { - sgx_target_info_t::default() - } -} diff --git a/tee-worker/bitacross/service/src/ocall_bridge/ffi/ipfs.rs b/tee-worker/bitacross/service/src/ocall_bridge/ffi/ipfs.rs deleted file mode 100644 index e264b49db2..0000000000 --- a/tee-worker/bitacross/service/src/ocall_bridge/ffi/ipfs.rs +++ /dev/null @@ -1,76 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - Copyright (C) 2017-2019 Baidu, Inc. All Rights Reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use crate::ocall_bridge::bridge_api::{Bridge, Cid, IpfsBridge}; -use log::*; -use sgx_types::sgx_status_t; -use std::{slice, sync::Arc}; - -/// C-API exposed for o-call from enclave -#[no_mangle] -pub unsafe extern "C" fn ocall_write_ipfs( - enc_state: *const u8, - enc_state_size: u32, - cid: *mut u8, - cid_size: u32, -) -> sgx_status_t { - write_ipfs(enc_state, enc_state_size, cid, cid_size, Bridge::get_ipfs_api()) -} - -/// C-API exposed for o-call from enclave -#[no_mangle] -pub unsafe extern "C" fn ocall_read_ipfs(cid: *const u8, cid_size: u32) -> sgx_status_t { - read_ipfs(cid, cid_size, Bridge::get_ipfs_api()) -} - -fn write_ipfs( - enc_state: *const u8, - enc_state_size: u32, - cid: *mut u8, - cid_size: u32, - ipfs_api: Arc, -) -> sgx_status_t { - let state = unsafe { slice::from_raw_parts(enc_state, enc_state_size as usize) }; - let cid = unsafe { slice::from_raw_parts_mut(cid, cid_size as usize) }; - - return match ipfs_api.write_to_ipfs(state) { - Ok(r) => { - cid.clone_from_slice(&r); - sgx_status_t::SGX_SUCCESS - }, - Err(e) => { - error!("OCall to write_ipfs failed: {:?}", e); - sgx_status_t::SGX_ERROR_UNEXPECTED - }, - } -} - -fn read_ipfs(cid: *const u8, cid_size: u32, ipfs_api: Arc) -> sgx_status_t { - let _cid = unsafe { slice::from_raw_parts(cid, cid_size as usize) }; - - let mut cid: Cid = [0; 46]; - cid.clone_from_slice(_cid); - - match ipfs_api.read_from_ipfs(cid) { - Ok(_) => sgx_status_t::SGX_SUCCESS, - Err(e) => { - error!("OCall to read_ipfs failed: {:?}", e); - sgx_status_t::SGX_ERROR_UNEXPECTED - }, - } -} diff --git a/tee-worker/bitacross/service/src/ocall_bridge/ffi/mod.rs b/tee-worker/bitacross/service/src/ocall_bridge/ffi/mod.rs deleted file mode 100644 index b18f24bf15..0000000000 --- a/tee-worker/bitacross/service/src/ocall_bridge/ffi/mod.rs +++ /dev/null @@ -1,32 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - Copyright (C) 2017-2019 Baidu, Inc. All Rights Reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -//! Foreign Function interface for all the OCalls. -//! Implementations of C-API functions, that can be called from the Enclave. -//! These should just be wrappers that transform the C-API structures and call the -//! actual implementation of the OCalls (using the traits defined in the bridge_api). - -pub mod get_ias_socket; -pub mod get_quote; -pub mod get_qve_report_on_quote; -pub mod get_update_info; -pub mod init_quote; -pub mod ipfs; -pub mod send_to_parentchain; -pub mod update_metric; -pub mod worker_request; diff --git a/tee-worker/bitacross/service/src/ocall_bridge/ffi/send_to_parentchain.rs b/tee-worker/bitacross/service/src/ocall_bridge/ffi/send_to_parentchain.rs deleted file mode 100644 index 2fc6c0511f..0000000000 --- a/tee-worker/bitacross/service/src/ocall_bridge/ffi/send_to_parentchain.rs +++ /dev/null @@ -1,86 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - Copyright (C) 2017-2019 Baidu, Inc. All Rights Reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use crate::ocall_bridge::bridge_api::{Bridge, WorkerOnChainBridge}; -use itp_utils::write_slice_and_whitespace_pad; -use log::*; -use sgx_types::{c_int, sgx_status_t}; -use std::{slice, sync::Arc, vec::Vec}; - -/// # Safety -/// -/// FFI are always unsafe -#[no_mangle] -pub unsafe extern "C" fn ocall_send_to_parentchain( - extrinsics_encoded: *const u8, - extrinsics_encoded_size: u32, - parentchain_id: *const u8, - parentchain_id_size: u32, - watch_until: *const u8, - watch_until_size: u32, - response: *mut u8, - resp_size: u32, -) -> sgx_status_t { - send_to_parentchain( - extrinsics_encoded, - extrinsics_encoded_size, - parentchain_id, - parentchain_id_size, - watch_until, - watch_until_size, - response, - resp_size, - Bridge::get_oc_api(), - ) -} - -#[allow(clippy::too_many_arguments)] -fn send_to_parentchain( - extrinsics_encoded: *const u8, - extrinsics_encoded_size: u32, - parentchain_id: *const u8, - parentchain_id_size: u32, - watch_until: *const u8, - watch_until_size: u32, - response: *mut u8, - resp_size: u32, - oc_api: Arc, -) -> sgx_status_t { - let extrinsics_encoded_vec: Vec = unsafe { - Vec::from(slice::from_raw_parts(extrinsics_encoded, extrinsics_encoded_size as usize)) - }; - let parentchain_id: Vec = - unsafe { Vec::from(slice::from_raw_parts(parentchain_id, parentchain_id_size as usize)) }; - let watch_until: Vec = - unsafe { Vec::from(slice::from_raw_parts(watch_until, watch_until_size as usize)) }; - - match oc_api.send_to_parentchain(extrinsics_encoded_vec, parentchain_id, watch_until) { - Ok(r) => { - let resp_slice = unsafe { slice::from_raw_parts_mut(response, resp_size as usize) }; - if let Err(e) = write_slice_and_whitespace_pad(resp_slice, r) { - error!("Failed to transfer send_to_parentchain response to o-call buffer: {:?}", e); - return sgx_status_t::SGX_ERROR_UNEXPECTED - } - sgx_status_t::SGX_SUCCESS - }, - Err(e) => { - error!("send extrinsics_encoded failed: {:?}", e); - sgx_status_t::SGX_ERROR_UNEXPECTED - }, - } -} diff --git a/tee-worker/bitacross/service/src/ocall_bridge/ffi/update_metric.rs b/tee-worker/bitacross/service/src/ocall_bridge/ffi/update_metric.rs deleted file mode 100644 index 0b97de74f9..0000000000 --- a/tee-worker/bitacross/service/src/ocall_bridge/ffi/update_metric.rs +++ /dev/null @@ -1,50 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - Copyright (C) 2017-2019 Baidu, Inc. All Rights Reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use crate::ocall_bridge::bridge_api::{Bridge, MetricsBridge}; -use log::*; -use sgx_types::sgx_status_t; -use std::{slice, sync::Arc}; - -/// # Safety -/// -/// FFI are always unsafe -#[no_mangle] -pub unsafe extern "C" fn ocall_update_metric( - metric_ptr: *const u8, - metric_size: u32, -) -> sgx_status_t { - update_metric(metric_ptr, metric_size, Bridge::get_metrics_api()) -} - -fn update_metric( - metric_ptr: *const u8, - metric_size: u32, - oc_api: Arc, -) -> sgx_status_t { - let metric_encoded: Vec = - unsafe { Vec::from(slice::from_raw_parts(metric_ptr, metric_size as usize)) }; - - match oc_api.update_metric(metric_encoded) { - Ok(_) => sgx_status_t::SGX_SUCCESS, - Err(e) => { - error!("update_metric o-call failed: {:?}", e); - sgx_status_t::SGX_ERROR_UNEXPECTED - }, - } -} diff --git a/tee-worker/bitacross/service/src/ocall_bridge/ffi/worker_request.rs b/tee-worker/bitacross/service/src/ocall_bridge/ffi/worker_request.rs deleted file mode 100644 index 7dbd9be957..0000000000 --- a/tee-worker/bitacross/service/src/ocall_bridge/ffi/worker_request.rs +++ /dev/null @@ -1,77 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - Copyright (C) 2017-2019 Baidu, Inc. All Rights Reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use crate::ocall_bridge::bridge_api::{Bridge, WorkerOnChainBridge}; -use itp_utils::write_slice_and_whitespace_pad; -use log::*; -use sgx_types::sgx_status_t; -use std::{slice, sync::Arc, vec::Vec}; - -/// # Safety -/// -/// FFI are always unsafe -#[no_mangle] -pub unsafe extern "C" fn ocall_worker_request( - request: *const u8, - req_size: u32, - parentchain_id: *const u8, - parentchain_id_size: u32, - response: *mut u8, - resp_size: u32, -) -> sgx_status_t { - worker_request( - request, - req_size, - parentchain_id, - parentchain_id_size, - response, - resp_size, - Bridge::get_oc_api(), - ) -} - -fn worker_request( - request: *const u8, - req_size: u32, - parentchain_id: *const u8, - parentchain_id_size: u32, - response: *mut u8, - resp_size: u32, - oc_api: Arc, -) -> sgx_status_t { - let request_vec: Vec = - unsafe { Vec::from(slice::from_raw_parts(request, req_size as usize)) }; - - let parentchain_id: Vec = - unsafe { Vec::from(slice::from_raw_parts(parentchain_id, parentchain_id_size as usize)) }; - - match oc_api.worker_request(request_vec, parentchain_id) { - Ok(r) => { - let resp_slice = unsafe { slice::from_raw_parts_mut(response, resp_size as usize) }; - if let Err(e) = write_slice_and_whitespace_pad(resp_slice, r) { - error!("Failed to transfer worker request response to o-call buffer: {:?}", e); - return sgx_status_t::SGX_ERROR_UNEXPECTED - } - sgx_status_t::SGX_SUCCESS - }, - Err(e) => { - error!("Worker request failed: {:?}", e); - sgx_status_t::SGX_ERROR_UNEXPECTED - }, - } -} diff --git a/tee-worker/bitacross/service/src/ocall_bridge/ipfs_ocall.rs b/tee-worker/bitacross/service/src/ocall_bridge/ipfs_ocall.rs deleted file mode 100644 index 1dc1d9beab..0000000000 --- a/tee-worker/bitacross/service/src/ocall_bridge/ipfs_ocall.rs +++ /dev/null @@ -1,112 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - Copyright (C) 2017-2019 Baidu, Inc. All Rights Reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use crate::ocall_bridge::bridge_api::{Cid, IpfsBridge, OCallBridgeError, OCallBridgeResult}; -use futures::TryStreamExt; -use ipfs_api::IpfsClient; -use log::*; -use std::{ - fs::File, - io::{Cursor, Write}, - str, - sync::mpsc::channel, -}; - -pub struct IpfsOCall; - -impl IpfsBridge for IpfsOCall { - fn write_to_ipfs(&self, data: &'static [u8]) -> OCallBridgeResult { - debug!(" Entering ocall_write_ipfs"); - write_to_ipfs(data) - } - - fn read_from_ipfs(&self, cid: Cid) -> OCallBridgeResult<()> { - debug!("Entering ocall_read_ipfs"); - - let result = read_from_ipfs(cid); - match result { - Ok(res) => { - let filename = str::from_utf8(&cid).map_err(|_| { - OCallBridgeError::IpfsError("Could not convert cid bytes".to_string()) - })?; - create_file(filename, &res).map_err(OCallBridgeError::IpfsError) - }, - Err(_) => Err(OCallBridgeError::IpfsError("failed to read from IPFS".to_string())), - } - } -} - -fn create_file(filename: &str, result: &[u8]) -> Result<(), String> { - match File::create(filename) { - Ok(mut f) => f - .write_all(result) - .map_or_else(|e| Err(format!("failed writing to file: {}", e)), |_| Ok(())), - Err(e) => Err(format!("failed to create file: {}", e)), - } -} - -#[tokio::main] -async fn write_to_ipfs(data: &'static [u8]) -> OCallBridgeResult { - // Creates an `IpfsClient` connected to the endpoint specified in ~/.ipfs/api. - // If not found, tries to connect to `localhost:5001`. - let client = IpfsClient::default(); - - match client.version().await { - Ok(version) => info!("version: {:?}", version.version), - Err(e) => eprintln!("error getting version: {}", e), - } - - let datac = Cursor::new(data); - let (tx, rx) = channel(); - - match client.add(datac).await { - Ok(res) => { - info!("Result Hash {}", res.hash); - tx.send(res.hash.into_bytes()).map_err(|e| { - OCallBridgeError::IpfsError(format!( - "Could not get result from IPFS, reason: {:?}", - e - )) - })? - }, - Err(e) => eprintln!("error adding file: {}", e), - } - let mut cid: Cid = [0; 46]; - let result = &rx.recv().map_err(|e| { - OCallBridgeError::IpfsError(format!("Could not get result from IPFS, reason: {:?}", e)) - })?; - cid.clone_from_slice(result); - Ok(cid) -} - -#[tokio::main] -pub async fn read_from_ipfs(cid: Cid) -> Result, String> { - // Creates an `IpfsClient` connected to the endpoint specified in ~/.ipfs/api. - // If not found, tries to connect to `localhost:5001`. - let client = IpfsClient::default(); - let h = str::from_utf8(&cid).map_err(|_| "Could not convert cid bytes".to_string())?; - - info!("Fetching content from: {}", h); - - client - .cat(h) - .map_ok(|chunk| chunk.to_vec()) - .map_err(|e| e.to_string()) - .try_concat() - .await -} diff --git a/tee-worker/bitacross/service/src/ocall_bridge/metrics_ocall.rs b/tee-worker/bitacross/service/src/ocall_bridge/metrics_ocall.rs deleted file mode 100644 index a06deff339..0000000000 --- a/tee-worker/bitacross/service/src/ocall_bridge/metrics_ocall.rs +++ /dev/null @@ -1,51 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - Copyright (C) 2017-2019 Baidu, Inc. All Rights Reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use crate::{ - ocall_bridge::bridge_api::{MetricsBridge, OCallBridgeError, OCallBridgeResult}, - prometheus_metrics::ReceiveEnclaveMetrics, -}; -use codec::Decode; -use itp_enclave_metrics::EnclaveMetric; -use std::sync::Arc; - -pub struct MetricsOCall { - receiver: Arc, -} - -impl MetricsOCall { - pub fn new(receiver: Arc) -> Self { - MetricsOCall { receiver } - } -} - -impl MetricsBridge for MetricsOCall -where - MetricsReceiver: ReceiveEnclaveMetrics, -{ - fn update_metric(&self, metric_encoded: Vec) -> OCallBridgeResult<()> { - let metric: EnclaveMetric = - Decode::decode(&mut metric_encoded.as_slice()).map_err(|e| { - OCallBridgeError::UpdateMetric(format!("Failed to decode metric: {:?}", e)) - })?; - - self.receiver.receive_enclave_metric(metric).map_err(|e| { - OCallBridgeError::UpdateMetric(format!("Failed to receive enclave metric: {:?}", e)) - }) - } -} diff --git a/tee-worker/bitacross/service/src/ocall_bridge/mod.rs b/tee-worker/bitacross/service/src/ocall_bridge/mod.rs deleted file mode 100644 index db5775cec3..0000000000 --- a/tee-worker/bitacross/service/src/ocall_bridge/mod.rs +++ /dev/null @@ -1,28 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - Copyright (C) 2017-2019 Baidu, Inc. All Rights Reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -// TODO This entire module should be extracted to a separate crate and re-named to o-call tunnel, see #288 and #316 - -pub mod bridge_api; -pub mod component_factory; - -mod ffi; -mod ipfs_ocall; -mod metrics_ocall; -mod remote_attestation_ocall; -mod worker_on_chain_ocall; diff --git a/tee-worker/bitacross/service/src/ocall_bridge/remote_attestation_ocall.rs b/tee-worker/bitacross/service/src/ocall_bridge/remote_attestation_ocall.rs deleted file mode 100644 index 0310f7ad18..0000000000 --- a/tee-worker/bitacross/service/src/ocall_bridge/remote_attestation_ocall.rs +++ /dev/null @@ -1,150 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - Copyright (C) 2017-2019 Baidu, Inc. All Rights Reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use crate::ocall_bridge::bridge_api::{ - OCallBridgeError, OCallBridgeResult, RemoteAttestationBridge, -}; -use itp_enclave_api::remote_attestation::{QveReport, RemoteAttestationCallBacks}; -use log::debug; -use sgx_types::*; -use std::{ - net::{SocketAddr, TcpStream}, - os::unix::io::IntoRawFd, - sync::Arc, -}; - -pub struct RemoteAttestationOCall { - enclave_api: Arc, -} - -impl RemoteAttestationOCall { - pub fn new(enclave_api: Arc) -> Self { - RemoteAttestationOCall { enclave_api } - } -} - -impl RemoteAttestationBridge for RemoteAttestationOCall -where - E: RemoteAttestationCallBacks, -{ - fn init_quote(&self) -> OCallBridgeResult<(sgx_target_info_t, sgx_epid_group_id_t)> { - debug!("RemoteAttestationBridge: init quote"); - self.enclave_api.init_quote().map_err(|e| match e { - itp_enclave_api::error::Error::Sgx(s) => OCallBridgeError::InitQuote(s), - _ => OCallBridgeError::InitQuote(sgx_status_t::SGX_ERROR_UNEXPECTED), - }) - } - - fn get_ias_socket(&self) -> OCallBridgeResult { - let port = 443; - let hostname = "api.trustedservices.intel.com"; - - let addr = lookup_ipv4(hostname, port).map_err(OCallBridgeError::GetIasSocket)?; - - let stream = TcpStream::connect(addr).map_err(|_| { - OCallBridgeError::GetIasSocket("[-] Connect tls server failed!".to_string()) - })?; - - Ok(stream.into_raw_fd()) - } - - fn get_quote( - &self, - revocation_list: Vec, - report: sgx_report_t, - quote_type: sgx_quote_sign_type_t, - spid: sgx_spid_t, - quote_nonce: sgx_quote_nonce_t, - ) -> OCallBridgeResult<(sgx_report_t, Vec)> { - debug!("RemoteAttestationBridge: get quote type: {:?}", quote_type); - let real_quote_len = - self.enclave_api.calc_quote_size(revocation_list.clone()).map_err(|e| match e { - itp_enclave_api::error::Error::Sgx(s) => OCallBridgeError::GetQuote(s), - _ => OCallBridgeError::GetQuote(sgx_status_t::SGX_ERROR_UNEXPECTED), - })?; - - debug!("RemoteAttestationBridge: real quote length: {}", real_quote_len); - self.enclave_api - .get_quote(revocation_list, report, quote_type, spid, quote_nonce, real_quote_len) - .map_err(|e| match e { - itp_enclave_api::error::Error::Sgx(s) => OCallBridgeError::GetQuote(s), - _ => OCallBridgeError::GetQuote(sgx_status_t::SGX_ERROR_UNEXPECTED), - }) - } - - fn get_dcap_quote(&self, report: sgx_report_t, quote_size: u32) -> OCallBridgeResult> { - debug!("RemoteAttestationBridge: get dcap quote, size: {}", quote_size); - - self.enclave_api.get_dcap_quote(report, quote_size).map_err(|e| match e { - itp_enclave_api::error::Error::Sgx(s) => OCallBridgeError::GetQuote(s), - _ => OCallBridgeError::GetQuote(sgx_status_t::SGX_ERROR_UNEXPECTED), - }) - } - - fn get_qve_report_on_quote( - &self, - quote: Vec, - current_time: i64, - quote_collateral: &sgx_ql_qve_collateral_t, - qve_report_info: sgx_ql_qe_report_info_t, - supplemental_data_size: u32, - ) -> OCallBridgeResult { - debug!("RemoteAttestationBridge: get qve report on quote, length: {}", quote.len()); - - self.enclave_api - .get_qve_report_on_quote( - quote, - current_time, - quote_collateral, - qve_report_info, - supplemental_data_size, - ) - .map_err(|e| match e { - itp_enclave_api::error::Error::Sgx(s) => OCallBridgeError::GetQuote(s), - _ => OCallBridgeError::GetQuote(sgx_status_t::SGX_ERROR_UNEXPECTED), - }) - } - - fn get_update_info( - &self, - platform_blob: sgx_platform_info_t, - enclave_trusted: i32, - ) -> OCallBridgeResult { - debug!("RemoteAttestationBridge: get update into"); - - self.enclave_api - .get_update_info(platform_blob, enclave_trusted) - .map_err(|e| match e { - itp_enclave_api::error::Error::Sgx(s) => OCallBridgeError::GetUpdateInfo(s), - _ => OCallBridgeError::GetUpdateInfo(sgx_status_t::SGX_ERROR_UNEXPECTED), - }) - } -} - -fn lookup_ipv4(host: &str, port: u16) -> Result { - use std::net::ToSocketAddrs; - - let addrs = (host, port).to_socket_addrs().map_err(|e| format!("{:?}", e))?; - for addr in addrs { - if let SocketAddr::V4(_) = addr { - return Ok(addr) - } - } - - Err("Cannot lookup address".to_string()) -} diff --git a/tee-worker/bitacross/service/src/ocall_bridge/worker_on_chain_ocall.rs b/tee-worker/bitacross/service/src/ocall_bridge/worker_on_chain_ocall.rs deleted file mode 100644 index 750de6d147..0000000000 --- a/tee-worker/bitacross/service/src/ocall_bridge/worker_on_chain_ocall.rs +++ /dev/null @@ -1,297 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - Copyright (C) 2017-2019 Baidu, Inc. All Rights Reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use crate::ocall_bridge::bridge_api::{OCallBridgeError, OCallBridgeResult, WorkerOnChainBridge}; -use codec::{Decode, Encode}; -use itp_api_client_types::ParentchainApi; -use itp_enclave_api::enclave_base::EnclaveBase; -use itp_node_api::{ - api_client::{AccountApi, ExtrinsicReport, XtStatus}, - node_api_factory::CreateNodeApi, -}; -use itp_types::{ - parentchain::{AccountId, ParentchainId}, - WorkerRequest, WorkerResponse, -}; -use log::*; -use sp_core::H256; -use sp_runtime::OpaqueExtrinsic; -use std::{sync::Arc, thread, vec::Vec}; -use substrate_api_client::{ - ac_primitives::serde_impls::StorageKey, GetAccountInformation, GetChainInfo, GetStorage, - SubmitAndWatch, SubmitExtrinsic, -}; - -#[cfg(feature = "link-binary")] -use crate::main_impl::enclave_account; - -pub struct WorkerOnChainOCall { - enclave_api: Arc, - integritee_api_factory: Arc, - target_a_parentchain_api_factory: Option>, - target_b_parentchain_api_factory: Option>, -} - -impl WorkerOnChainOCall { - pub fn new( - enclave_api: Arc, - integritee_api_factory: Arc, - target_a_parentchain_api_factory: Option>, - target_b_parentchain_api_factory: Option>, - ) -> Self { - WorkerOnChainOCall { - enclave_api, - integritee_api_factory, - target_a_parentchain_api_factory, - target_b_parentchain_api_factory, - } - } -} - -impl WorkerOnChainOCall { - pub fn create_api(&self, parentchain_id: ParentchainId) -> OCallBridgeResult { - Ok(match parentchain_id { - ParentchainId::Litentry => self.integritee_api_factory.create_api()?, - ParentchainId::TargetA => self - .target_a_parentchain_api_factory - .as_ref() - .ok_or(OCallBridgeError::TargetAParentchainNotInitialized) - .and_then(|f| f.create_api().map_err(Into::into))?, - ParentchainId::TargetB => self - .target_b_parentchain_api_factory - .as_ref() - .ok_or(OCallBridgeError::TargetBParentchainNotInitialized) - .and_then(|f| f.create_api().map_err(Into::into))?, - }) - } -} - -impl WorkerOnChainBridge for WorkerOnChainOCall -where - E: EnclaveBase, - F: CreateNodeApi, -{ - fn worker_request( - &self, - request: Vec, - parentchain_id: Vec, - ) -> OCallBridgeResult> { - trace!(" Entering ocall_worker_request"); - - let requests: Vec = Decode::decode(&mut request.as_slice())?; - if requests.is_empty() { - debug!("requests is empty, returning empty vector"); - return Ok(Vec::::new().encode()) - } - - let parentchain_id = ParentchainId::decode(&mut parentchain_id.as_slice())?; - - let api = self.create_api(parentchain_id)?; - - let resp: Vec>> = requests - .into_iter() - .map(|req| match req { - WorkerRequest::ChainStorage(key, hash) => WorkerResponse::ChainStorage( - key.clone(), - api.get_opaque_storage_by_key(StorageKey(key.clone()), hash).unwrap(), - api.get_storage_proof_by_keys(vec![StorageKey(key)], hash).unwrap().map( - |read_proof| read_proof.proof.into_iter().map(|bytes| bytes.0).collect(), - ), - ), - WorkerRequest::ChainStorageKeys(key, hash) => { - let keys: Vec> = match api.get_keys(StorageKey(key), hash) { - Ok(Some(keys)) => keys.iter().map(String::encode).collect(), - _ => Default::default(), - }; - WorkerResponse::ChainStorageKeys(keys) - }, - WorkerRequest::ChainStorageKeysPaged(prefix, count, start_key, hash) => { - let keys: Vec> = match api.get_storage_keys_paged( - Some(StorageKey(prefix)), - count, - start_key.map(StorageKey), - hash, - ) { - Ok(keys) => keys.iter().map(|k| k.0.to_vec()).collect(), - _ => Default::default(), - }; - WorkerResponse::ChainStorageKeys(keys) - }, - WorkerRequest::ChainHeader(block_hash) => { - let header = match api.get_header(block_hash) { - Ok(Some(header)) => Some(header.encode()), - _ => None, - }; - WorkerResponse::ChainHeader(header) - }, - WorkerRequest::ChainAccountNonce(encoded_account_id) => { - let maybe_nonce = match AccountId::decode(&mut encoded_account_id.as_slice()) { - Ok(account_id) => api.get_account_nonce(&account_id).ok(), - _ => { - error!("[ChainAccountNonce] account_id could not be decoded"); - None - }, - }; - WorkerResponse::ChainAccountNonce(maybe_nonce) - }, - }) - .collect(); - - let encoded_response: Vec = resp.encode(); - - Ok(encoded_response) - } - - fn send_to_parentchain( - &self, - extrinsics_encoded: Vec, - parentchain_id: Vec, - watch_until: Vec, - ) -> OCallBridgeResult> { - let maybe_watch_until: Option = Decode::decode(&mut watch_until.as_slice()) - .map_err(|_| { - OCallBridgeError::SendExtrinsicsToParentchain( - "Could not decode watch_until".to_string(), - ) - })?; - let extrinsics: Vec = Decode::decode(&mut extrinsics_encoded.as_slice()) - .map_err(|_| { - OCallBridgeError::SendExtrinsicsToParentchain("Could not decode extrinsics".to_string()) - })?; - let mut extrinsic_reports: Vec> = Vec::new(); - let parentchain_id = ParentchainId::decode(&mut parentchain_id.as_slice())?; - debug!( - "Enclave wants to send {} extrinsics to parentchain: {:?}. watch_until: {:?}", - extrinsics.len(), - parentchain_id, - maybe_watch_until - ); - let api = self.create_api(parentchain_id)?; - let mut send_extrinsic_failed = false; - - for call in extrinsics.into_iter() { - if let Some(xt_status) = maybe_watch_until { - match api.submit_and_watch_opaque_extrinsic_until( - &call.encode().into(), - xt_status.into(), - ) { - Ok(report) => extrinsic_reports.push(report.into()), - Err(e) => { - error!( - "Could not send extrinsic to {:?}: {:?}, error: {:?}", - parentchain_id, - serde_json::to_string(&call), - e - ); - send_extrinsic_failed = true; - }, - } - } else if let Err(e) = api.submit_opaque_extrinsic(&call.encode().into()) { - error!( - "Could not send extrinsic to {:?}: {:?}, error: {:?}", - parentchain_id, - serde_json::to_string(&call), - e - ); - send_extrinsic_failed = true; - } - } - - // Try to reset nonce, see - // - https://github.com/litentry/litentry-parachain/issues/1036 - // - https://github.com/integritee-network/worker/issues/970 - // It has to be done in a separate thread as nested ECALL/OCALL is disallowed - // - // This workaround is likely to cause duplicate nonce or "transaction outdated" error in the parentchain - // tx pool, because the retrieved on-chain nonce doesn't count the pending tx, meanwhile the extrinsic factory - // keeps composing new extrinsics. So the nonce used for composing the new extrinsics can collide with the nonce - // in the already submitted tx. As a result, a few txs could be dropped during the parentchain tx pool processing. - // Not to mention the thread dispatch delay and network delay (query on-chain nonce). - // - // However, we still consider it better than the current situation, where the nonce never gets rectified and - // all following extrinsics will be blocked. Moreover, the txs sent to the parentchain are mostly - // "notification extrinsics" and don't cause chain state change, therefore we deem it less harmful to drop them. - // The worst case is some action is wrongly intepreted as "failed" (because F/E doesn't get the event in time) - // while it actually succeeds. In that case, the user needs to re-do the extrinsic, which is suboptimal, - // but still better than the chain stalling. - // - // To have a better synchronisation handling we probably need a sending queue in extrinsic factory that - // can be paused on demand (or wait for the nonce synchronisation). - // - // Another small thing that can be improved is to use rpc.system.accountNextIndex instead of system.account.nonce - // see https://polkadot.js.org/docs/api/cookbook/tx/#how-do-i-take-the-pending-tx-pool-into-account-in-my-nonce - #[cfg(feature = "link-binary")] - if send_extrinsic_failed { - // drop &self lifetime - let node_api_factory_cloned = self.integritee_api_factory.clone(); - let enclave_cloned = self.enclave_api.clone(); - thread::spawn(move || { - let api = node_api_factory_cloned.create_api().unwrap(); - let enclave_account = enclave_account(enclave_cloned.as_ref()); - warn!("send_extrinsic failed, try to reset nonce ..."); - match api.get_account_next_index(&enclave_account) { - Ok(nonce) => { - warn!("query on-chain nonce OK, reset nonce to: {}", nonce); - if let Err(e) = enclave_cloned.set_nonce(nonce, ParentchainId::Litentry) { - warn!("failed to reset nonce due to: {:?}", e); - } - }, - Err(e) => warn!("query on-chain nonce failed: {:?}", e), - } - }); - } - - Ok(extrinsic_reports.encode()) - } -} - -#[cfg(test)] -mod tests { - - use super::*; - use crate::tests::mocks::enclave_api_mock::EnclaveMock; - use itp_node_api::{ - api_client::ParentchainApi, - node_api_factory::{CreateNodeApi, Result as NodeApiResult}, - }; - use mockall::mock; - - #[test] - fn given_empty_worker_request_when_submitting_then_return_empty_response() { - mock! { - NodeApiFactory {} - impl CreateNodeApi for NodeApiFactory { - fn create_api(&self) -> NodeApiResult; - } - } - - let mock_enclave = Arc::new(EnclaveMock {}); - let mock_node_api_factory = Arc::new(MockNodeApiFactory::new()); - - let on_chain_ocall = - WorkerOnChainOCall::new(mock_enclave, mock_node_api_factory, None, None); - - let response = on_chain_ocall - .worker_request(Vec::::new().encode(), ParentchainId::Litentry.encode()) - .unwrap(); - - assert!(!response.is_empty()); // the encoded empty vector is not empty - let decoded_response: Vec = Decode::decode(&mut response.as_slice()).unwrap(); - assert!(decoded_response.is_empty()); // decode the response, and we get an empty vector again - } -} diff --git a/tee-worker/bitacross/service/src/parentchain_handler.rs b/tee-worker/bitacross/service/src/parentchain_handler.rs deleted file mode 100644 index 7e0bc5242e..0000000000 --- a/tee-worker/bitacross/service/src/parentchain_handler.rs +++ /dev/null @@ -1,350 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - Copyright (C) 2017-2019 Baidu, Inc. All Rights Reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use crate::error::{Error, ServiceResult}; -use codec::{Decode, Encode}; -use humantime::format_duration; -use ita_parentchain_interface::integritee::Header; -use itp_api_client_types::ParentchainApi; -use itp_enclave_api::{enclave_base::EnclaveBase, sidechain::Sidechain}; -use itp_node_api::api_client::ChainApi; -use itp_storage::StorageProof; -use itp_time_utils::duration_now; -use itp_types::{ - parentchain::{GrandpaParams, ParentchainId, ParentchainInitParams, SimpleParams}, - ShardIdentifier, -}; -use log::*; -use rayon::prelude::*; -use sp_consensus_grandpa::VersionedAuthorityList; -use sp_runtime::traits::Header as HeaderTrait; -use std::{cmp::min, sync::Arc, time::Duration}; -use substrate_api_client::{ - ac_primitives::{Block, Header as HeaderT}, - GetChainInfo, -}; - -const BLOCK_SYNC_BATCH_SIZE: u32 = 1000; - -pub trait HandleParentchain { - /// Initializes all parentchain specific components on the enclave side. - /// Returns the latest synced block header. - fn init_parentchain_components(&self) -> ServiceResult
; - - /// Fetches the parentchain blocks to sync from the parentchain and feeds them to the enclave. - /// Returns the latest synced block header. - /// - /// Litentry: `overriden_start_block` to forcibly start from the given parentchain block number - fn sync_parentchain_until_latest_finalized( - &self, - last_synced_header: Header, - overriden_start_block: u32, - shard: ShardIdentifier, - immediate_import: bool, - ) -> ServiceResult
; - - /// Syncs and directly imports parentchain blocks from the latest synced header - /// until at least the specified until_header. - /// - /// Litentry: `overriden_start_block` to forcibly start from the given parentchain block number - fn await_sync_and_import_parentchain_until_at_least( - &self, - last_synced_header: &Header, - until_header: &Header, - overriden_start_block: u32, - shard: ShardIdentifier, - ) -> ServiceResult
; -} - -/// Handles the interaction between parentchain and enclave. -pub(crate) struct ParentchainHandler { - parentchain_api: ParentchainApi, - enclave_api: Arc, - pub parentchain_init_params: ParentchainInitParams, -} - -// #TODO: #1451: Reintroduce `ParentchainApi: ChainApi` once there is no trait bound conflict -// any more with the api-clients own trait definitions. -impl ParentchainHandler -where - EnclaveApi: EnclaveBase, -{ - pub fn new( - parentchain_api: ParentchainApi, - enclave_api: Arc, - parentchain_init_params: ParentchainInitParams, - ) -> Self { - Self { parentchain_api, enclave_api, parentchain_init_params } - } - - // FIXME: Necessary in the future? Fix with #1080 - pub fn new_with_automatic_light_client_allocation( - parentchain_api: ParentchainApi, - enclave_api: Arc, - id: ParentchainId, - shard: ShardIdentifier, - ) -> ServiceResult { - let genesis_hash = parentchain_api.get_genesis_hash()?; - let genesis_header = - parentchain_api.header(Some(genesis_hash))?.ok_or(Error::MissingGenesisHeader)?; - - let parentchain_init_params: ParentchainInitParams = if parentchain_api - .is_grandpa_available()? - { - let grandpas = parentchain_api.grandpa_authorities(Some(genesis_hash))?; - let grandpa_proof = parentchain_api.grandpa_authorities_proof(Some(genesis_hash))?; - - debug!("[{:?}] Grandpa Authority List: \n {:?} \n ", id, grandpas); - - let authority_list = VersionedAuthorityList::from(grandpas); - - ( - id, - shard, - GrandpaParams::new( - // #TODO: #1451: clean up type hacks - Header::decode(&mut genesis_header.encode().as_slice())?, - authority_list.into(), - grandpa_proof, - ), - ) - .into() - } else { - ( - id, - shard, - SimpleParams::new( - // #TODO: #1451: clean up type hacks - Header::decode(&mut genesis_header.encode().as_slice())?, - ), - ) - .into() - }; - - Ok(Self::new(parentchain_api, enclave_api, parentchain_init_params)) - } - - pub fn parentchain_api(&self) -> &ParentchainApi { - &self.parentchain_api - } - - pub fn parentchain_id(&self) -> &ParentchainId { - self.parentchain_init_params.id() - } -} - -impl HandleParentchain for ParentchainHandler -where - EnclaveApi: Sidechain + EnclaveBase, -{ - fn init_parentchain_components(&self) -> ServiceResult
{ - Ok(self - .enclave_api - .init_parentchain_components(self.parentchain_init_params.clone())?) - } - - fn sync_parentchain_until_latest_finalized( - &self, - last_synced_header: Header, - overriden_start_block: u32, - shard: ShardIdentifier, - immediate_import: bool, - ) -> ServiceResult
{ - let id = self.parentchain_id(); - trace!("[{:?}] Getting current head", id); - let curr_block = self - .parentchain_api - .last_finalized_block()? - .ok_or(Error::MissingLastFinalizedBlock)?; - let curr_block_number = curr_block.block.header().number(); - let last_synced_header_number = last_synced_header.number; - // verify that the last_synced_header is indeed a block from this chain - self.parentchain_api - .get_block(Some(last_synced_header.hash()))? - .ok_or_else(|| Error::UnknownBlockHeader(last_synced_header.hash()))?; - - info!( - "[{:?}] Syncing blocks from {} to {}", - id, last_synced_header_number, curr_block_number - ); - let creation_info = self.enclave_api.get_shard_creation_info(&shard)?; - let maybe_creation_block = if let Some(creation_block) = creation_info.for_parentchain(*id) - { - trace!("[{:?}] shard creation block: {:?}", id, creation_block); - Some(creation_block) - } else { - None - }; - - let start_time = duration_now(); - let mut until_synced_header = last_synced_header; - let mut start_block = until_synced_header.number + 1; - if overriden_start_block > start_block { - start_block = overriden_start_block; - // ask the enclave to ignore the parentchain block import validation until `overriden_start_block` - // TODO: maybe ignoring the next block import is enough, since the given `overriden_start_block` - // should be the very first parentchain block to be imported - self.enclave_api - .ignore_parentchain_block_import_validation_until(overriden_start_block)?; - } - - loop { - let chunk_range = - start_block..min(start_block + BLOCK_SYNC_BATCH_SIZE, curr_block_number); - - let start_fetch_time = duration_now(); - - let block_chunk_to_sync = chunk_range - .into_par_iter() - .filter_map(|block_number| { - self.parentchain_api - .get_block_by_number(block_number) - .expect("failed to get block") - }) - .collect::>(); - - debug!( - "[{:?}] Fetched {} blocks in {}", - id, - block_chunk_to_sync.len(), - format_duration(duration_now().saturating_sub(start_fetch_time)) - ); - - if block_chunk_to_sync.len() == BLOCK_SYNC_BATCH_SIZE as usize { - let now = duration_now(); - let total_blocks = curr_block_number.saturating_sub(last_synced_header_number); - let remaining_blocks = curr_block_number.saturating_sub(until_synced_header.number); - let remaining_time_estimate: Duration = (now.saturating_sub(start_time)) - .saturating_mul(remaining_blocks) - / (total_blocks.saturating_sub(remaining_blocks) + 1); - info!( - "[{:?}] syncing parentchain to {}. already synced until block {}. immediate import={}. est. remaining: {}", - id, curr_block_number, until_synced_header.number, immediate_import, format_duration(remaining_time_estimate) - ); - } - debug!( - "[{:?}] Found {} block(s) to sync in this chunk. immediate import={} ", - id, - block_chunk_to_sync.len(), - immediate_import - ); - if block_chunk_to_sync.is_empty() { - return Ok(until_synced_header) - } - - let skip_invocations = if let Some(creation_block) = maybe_creation_block { - let max_blocknumber_in_chunk = - block_chunk_to_sync.last().map_or_else(|| 0, |b| b.block.header.number()); - if max_blocknumber_in_chunk < creation_block.number { - trace!("skipping invocations for fast-sync for blocks older than shard creation: {} < {}", max_blocknumber_in_chunk, creation_block.number); - true - } else { - false - } - } else { - false - }; - - let events_chunk_to_sync: Vec> = if skip_invocations { - vec![] - } else { - let evs = block_chunk_to_sync - .par_iter() - .map(|block| { - self.parentchain_api.get_events_for_block(Some(block.block.header.hash())) - }) - .collect::, _>>()?; - debug!("[{:?}] Found {} event vector(s) to sync in this chunk", id, evs.len()); - evs - }; - - let events_proofs_chunk_to_sync: Vec = if skip_invocations { - vec![] - } else { - block_chunk_to_sync - .par_iter() - .map(|block| { - self.parentchain_api.get_events_value_proof(Some(block.block.header.hash())) - }) - .collect::, _>>()? - }; - - let sync_start_time = duration_now(); - - self.enclave_api.sync_parentchain( - block_chunk_to_sync.as_slice(), - events_chunk_to_sync.as_slice(), - events_proofs_chunk_to_sync.as_slice(), - self.parentchain_id(), - immediate_import, - )?; - - info!( - "[{:?}] Synced parentchain batch in {}", - id, - format_duration(duration_now().saturating_sub(sync_start_time)) - ); - - let api_client_until_synced_header = block_chunk_to_sync - .last() - .map(|b| b.block.header.clone()) - .ok_or(Error::EmptyChunk)?; - - // #TODO: #1451: fix api/client types - until_synced_header = - Header::decode(&mut api_client_until_synced_header.encode().as_slice()) - .expect("Can decode previously encoded header; qed"); - - start_block = until_synced_header.number + 1; - info!( - "[{:?}] Synced {} out of {} finalized parentchain blocks", - id, until_synced_header.number, curr_block_number, - ); - } - } - - fn await_sync_and_import_parentchain_until_at_least( - &self, - last_synced_header: &Header, - until_header: &Header, - overriden_start_block: u32, - shard: ShardIdentifier, - ) -> ServiceResult
{ - let id = self.parentchain_id(); - - trace!( - "[{:?}] last synced block number: {}. synching until {}", - id, - last_synced_header.number, - until_header.number - ); - let mut last_synced_header = last_synced_header.clone(); - - while last_synced_header.number() < until_header.number() { - last_synced_header = self.sync_parentchain_until_latest_finalized( - last_synced_header, - overriden_start_block, - shard, - true, - )?; - info!("[{:?}] synced block number: #{}", id, last_synced_header.number); - std::thread::sleep(std::time::Duration::from_secs(1)); - } - Ok(last_synced_header) - } -} diff --git a/tee-worker/bitacross/service/src/prometheus_metrics.rs b/tee-worker/bitacross/service/src/prometheus_metrics.rs deleted file mode 100644 index 6f0444bfe6..0000000000 --- a/tee-worker/bitacross/service/src/prometheus_metrics.rs +++ /dev/null @@ -1,210 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -//! Service for prometheus metrics, hosted on a http server. - -use crate::{ - account_funding::EnclaveAccountInfo, - error::{Error, ServiceResult}, -}; -use async_trait::async_trait; -use codec::{Decode, Encode}; -#[cfg(feature = "attesteer")] -use core::time::Duration; -use frame_support::scale_info::TypeInfo; -#[cfg(feature = "dcap")] -use itc_rest_client::{ - http_client::{DefaultSend, HttpClient}, - rest_client::{RestClient, Url as URL}, - RestGet, RestPath, -}; -use itp_enclave_metrics::EnclaveMetric; -use lazy_static::lazy_static; -use log::*; -use prometheus::{ - proto::MetricFamily, register_counter, register_histogram, register_histogram_vec, - register_int_gauge, register_int_gauge_vec, Counter, Histogram, HistogramVec, IntGauge, - IntGaugeVec, -}; -use serde::{Deserialize, Serialize}; -use std::{net::SocketAddr, sync::Arc}; -use warp::{Filter, Rejection, Reply}; - -lazy_static! { - /// Register all the prometheus metrics we want to monitor (aside from the default process ones). - static ref ENCLAVE_PARENTCHAIN_BLOCK_IMPORT_TIME: Histogram = - register_histogram!("bitacross_worker_enclave_parentchain_block_import_time", "Time taken to import parentchain block") - .unwrap(); - static ref MUSIG2_CEREMONIES_STARTED: Counter = - register_counter!("bitacross_worker_ceremonies_started", "Musig2 ceremonies started") - .unwrap(); - static ref MUSIG2_CEREMONIES_FAILED: Counter = - register_counter!("bitacross_worker_ceremonies_failed", "Musig2 ceremonies failed") - .unwrap(); - static ref MUSIG2_CEREMONIES_TIMED_OUT: Counter = - register_counter!("bitacross_worker_ceremonies_timed_out", "Musig2 ceremonies timed out") - .unwrap(); - static ref MUSIG2_CEREMONY_DURATION: Histogram = - register_histogram!("bitacross_worker_ceremony_duration", "Time taken to perform musig2 ceremony", vec![0.0005, 0.005, 0.01, 0.025, 0.05, 0.1]) - .unwrap(); - - -} - -pub async fn start_metrics_server( - metrics_handler: Arc, - port: u16, -) -> ServiceResult<()> -where - MetricsHandler: HandleMetrics + Send + Sync + 'static, -{ - let metrics_route = warp::path!("metrics").and_then(move || { - let handler_clone = metrics_handler.clone(); - async move { handler_clone.handle_metrics().await } - }); - let socket_addr: SocketAddr = ([0, 0, 0, 0], port).into(); - - info!("Running prometheus metrics server on: {:?}", socket_addr); - warp::serve(metrics_route).run(socket_addr).await; - - info!("Prometheus metrics server shut down"); - Ok(()) -} - -#[async_trait] -pub trait HandleMetrics { - type ReplyType: Reply; - - async fn handle_metrics(&self) -> Result; -} - -/// Metrics handler implementation. -pub struct MetricsHandler {} - -#[async_trait] -impl HandleMetrics for MetricsHandler { - type ReplyType = String; - - async fn handle_metrics(&self) -> Result { - let default_metrics = match gather_metrics_into_reply(&prometheus::gather()) { - Ok(r) => r, - Err(e) => { - error!("Failed to gather prometheus metrics: {:?}", e); - String::default() - }, - }; - - Ok(default_metrics) - } -} - -fn gather_metrics_into_reply(metrics: &[MetricFamily]) -> ServiceResult { - use prometheus::Encoder; - let encoder = prometheus::TextEncoder::new(); - - let mut buffer = Vec::new(); - encoder.encode(metrics, &mut buffer).map_err(|e| { - Error::Custom(format!("Failed to encode prometheus metrics: {:?}", e).into()) - })?; - - let result_string = String::from_utf8(buffer).map_err(|e| { - Error::Custom( - format!("Failed to convert Prometheus encoded metrics to UTF8: {:?}", e).into(), - ) - })?; - - Ok(result_string) -} - -/// Trait to receive metric updates from inside the enclave. -pub trait ReceiveEnclaveMetrics { - fn receive_enclave_metric(&self, metric: EnclaveMetric) -> ServiceResult<()>; -} - -pub struct EnclaveMetricsReceiver; - -impl ReceiveEnclaveMetrics for EnclaveMetricsReceiver { - fn receive_enclave_metric(&self, metric: EnclaveMetric) -> ServiceResult<()> { - match metric { - EnclaveMetric::ParentchainBlockImportTime(time) => - ENCLAVE_PARENTCHAIN_BLOCK_IMPORT_TIME.observe(time.as_secs_f64()), - EnclaveMetric::Musig2CeremonyStarted => MUSIG2_CEREMONIES_STARTED.inc(), - EnclaveMetric::Musig2CeremonyFailed => MUSIG2_CEREMONIES_FAILED.inc(), - EnclaveMetric::Musig2CeremonyTimedout(count) => - for i in 0..count { - MUSIG2_CEREMONIES_TIMED_OUT.inc() - }, - EnclaveMetric::Musig2CeremonyDuration(time) => - MUSIG2_CEREMONY_DURATION.observe(time.as_secs_f64()), - _ => warn!("Not supported metric: {:?}", metric), - } - Ok(()) - } -} - -#[derive(Serialize, Deserialize, Debug)] -struct PrometheusMarblerunEvents(pub Vec); - -#[cfg(feature = "attesteer")] -impl RestPath<&str> for PrometheusMarblerunEvents { - fn get_path(path: &str) -> Result { - Ok(format!("{}", path)) - } -} - -#[cfg(feature = "attesteer")] -pub fn fetch_marblerun_events(base_url: &str) -> Result, Error> { - let base_url = URL::parse(&base_url).map_err(|e| { - Error::Custom( - format!("Failed to parse marblerun prometheus endpoint base URL: {:?}", e).into(), - ) - })?; - let timeout = 3u64; - let http_client = - HttpClient::new(DefaultSend {}, true, Some(Duration::from_secs(timeout)), None, None); - - let mut rest_client = RestClient::new(http_client, base_url.clone()); - let events: PrometheusMarblerunEvents = rest_client.get("events").map_err(|e| { - Error::Custom( - format!("Failed to fetch marblerun prometheus events from: {}, error: {}", base_url, e) - .into(), - ) - })?; - - Ok(events.0) -} - -#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Encode, Decode, TypeInfo)] -pub struct PrometheusMarblerunEvent { - pub time: String, - pub activation: PrometheusMarblerunEventActivation, -} - -#[cfg(feature = "attesteer")] -impl PrometheusMarblerunEvent { - pub fn get_quote_without_prepended_bytes(&self) -> &[u8] { - let marblerun_magic_prepended_header_size = 16usize; - &self.activation.quote.as_bytes()[marblerun_magic_prepended_header_size..] - } -} -#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Encode, Decode, TypeInfo)] -#[serde(rename_all = "camelCase")] -pub struct PrometheusMarblerunEventActivation { - pub marble_type: String, - pub uuid: String, - pub quote: String, -} diff --git a/tee-worker/bitacross/service/src/setup.rs b/tee-worker/bitacross/service/src/setup.rs deleted file mode 100644 index 94548b7bd8..0000000000 --- a/tee-worker/bitacross/service/src/setup.rs +++ /dev/null @@ -1,276 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - Copyright (C) 2017-2019 Baidu, Inc. All Rights Reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use crate::error::{Error, ServiceResult}; -use itp_settings::files::{ - ENCLAVE_REGISTRY_FILE, LITENTRY_PARENTCHAIN_LIGHT_CLIENT_DB_PATH, RELAYER_REGISTRY_FILE, - SHARDS_PATH, SIGNER_REGISTRY_FILE, TARGET_A_PARENTCHAIN_LIGHT_CLIENT_DB_PATH, - TARGET_B_PARENTCHAIN_LIGHT_CLIENT_DB_PATH, -}; -use std::{fs, path::Path}; - -#[cfg(feature = "link-binary")] -pub(crate) use needs_enclave::{ - generate_shielding_key_file, generate_signing_key_file, init_shard, initialize_shard_and_keys, - migrate_shard, -}; - -#[cfg(feature = "link-binary")] -mod needs_enclave { - use crate::error::{Error, ServiceResult}; - use codec::Encode; - use itp_enclave_api::{enclave_base::EnclaveBase, Enclave}; - use itp_settings::files::{ - LITENTRY_PARENTCHAIN_LIGHT_CLIENT_DB_PATH, SHARDS_PATH, SHIELDING_KEY_FILE, - SIGNING_KEY_FILE, TARGET_A_PARENTCHAIN_LIGHT_CLIENT_DB_PATH, - TARGET_B_PARENTCHAIN_LIGHT_CLIENT_DB_PATH, - }; - use itp_types::ShardIdentifier; - use log::*; - use std::{fs, fs::File, path::Path}; - - /// Initializes the shard and generates the key files. - pub(crate) fn initialize_shard_and_keys( - enclave: &Enclave, - shard_identifier: &ShardIdentifier, - ) -> ServiceResult<()> { - println!("[+] Initialize the shard"); - init_shard(enclave, shard_identifier); - - let pubkey = enclave.get_ecc_signing_pubkey().unwrap(); - debug!("Enclave signing key (public) raw: {:?}", pubkey); - let pubkey = enclave.get_rsa_shielding_pubkey().unwrap(); - debug!("Enclave shielding key (public) raw (may be overwritten later): {:?}", pubkey); - Ok(()) - } - - pub(crate) fn init_shard(enclave: &Enclave, shard_identifier: &ShardIdentifier) { - use base58::ToBase58; - - match enclave.init_shard(shard_identifier.encode()) { - Err(e) => { - println!( - "Failed to initialize shard {:?}: {:?}", - shard_identifier.0.to_base58(), - e - ); - }, - Ok(_) => { - println!("Successfully initialized shard {:?}", shard_identifier.0.to_base58()); - }, - } - } - - pub(crate) fn migrate_shard(enclave: &Enclave, &new_shard: &ShardIdentifier) { - match enclave.migrate_shard(new_shard.encode()) { - Err(e) => { - panic!("Failed to migrate shard {:?}. {:?}", new_shard, e); - }, - Ok(_) => { - println!("Shard {:?} migrated Successfully", new_shard); - }, - } - } - - pub(crate) fn generate_signing_key_file(enclave: &Enclave) { - info!("*** Get the signing key from the TEE\n"); - let pubkey = enclave.get_ecc_signing_pubkey().unwrap(); - debug!("[+] Signing key raw: {:?}", pubkey); - match fs::write(SIGNING_KEY_FILE, pubkey) { - Err(x) => { - error!("[-] Failed to write '{}'. {}", SIGNING_KEY_FILE, x); - }, - _ => { - println!("[+] File '{}' written successfully", SIGNING_KEY_FILE); - }, - } - } - - pub(crate) fn generate_shielding_key_file(enclave: &Enclave) { - info!("*** Get the public key from the TEE\n"); - let pubkey = enclave.get_rsa_shielding_pubkey().unwrap(); - let file = File::create(SHIELDING_KEY_FILE).unwrap(); - match serde_json::to_writer(file, &pubkey) { - Err(x) => { - error!("[-] Failed to write '{}'. {}", SHIELDING_KEY_FILE, x); - }, - _ => { - println!("[+] File '{}' written successfully", SHIELDING_KEY_FILE); - }, - } - } -} - -/// backs up shard directory and restores it after cleaning shards directory -pub(crate) fn remove_old_shards(root_dir: &Path, new_shard_name: &str) { - let shard_backup = root_dir.join("shard_backup"); - let shard_dir = root_dir.join(SHARDS_PATH).join(new_shard_name); - - fs::rename(shard_dir.clone(), shard_backup.clone()).expect("Failed to backup shard"); - remove_dir_if_it_exists(root_dir, SHARDS_PATH).expect("Failed to remove shards directory"); - fs::create_dir_all(root_dir.join(SHARDS_PATH)).expect("Failed to create shards directory"); - fs::rename(shard_backup, shard_dir).expect("Failed to restore shard"); -} - -/// Purge all worker files from `dir`. -pub(crate) fn purge_files_from_dir(dir: &Path) -> ServiceResult<()> { - println!("[+] Performing a clean reset of the worker"); - - println!("[+] Purge all files from previous runs"); - purge_files(dir)?; - - Ok(()) -} - -/// Purge all worker files in a given path. -fn purge_files(root_directory: &Path) -> ServiceResult<()> { - remove_dir_if_it_exists(root_directory, SHARDS_PATH)?; - - remove_dir_if_it_exists(root_directory, LITENTRY_PARENTCHAIN_LIGHT_CLIENT_DB_PATH)?; - remove_dir_if_it_exists(root_directory, TARGET_A_PARENTCHAIN_LIGHT_CLIENT_DB_PATH)?; - remove_dir_if_it_exists(root_directory, TARGET_B_PARENTCHAIN_LIGHT_CLIENT_DB_PATH)?; - - remove_file_if_it_exists(root_directory, RELAYER_REGISTRY_FILE)?; - remove_file_if_it_exists(root_directory, ENCLAVE_REGISTRY_FILE)?; - remove_file_if_it_exists(root_directory, SIGNER_REGISTRY_FILE)?; - Ok(()) -} - -fn remove_dir_if_it_exists(root_directory: &Path, dir_name: &str) -> ServiceResult<()> { - let directory_path = root_directory.join(dir_name); - if directory_path.exists() { - fs::remove_dir_all(directory_path).map_err(|e| Error::Custom(e.into()))?; - } - Ok(()) -} - -fn remove_file_if_it_exists(root_directory: &Path, file_name: &str) -> ServiceResult<()> { - let file = root_directory.join(file_name); - if file.exists() { - fs::remove_file(file).map_err(|e| Error::Custom(e.into()))?; - } - Ok(()) -} - -#[cfg(test)] -mod tests { - use super::*; - use itp_settings::files::{ - SHARDS_PATH, SIGNER_REGISTRY_FILE, TARGET_A_PARENTCHAIN_LIGHT_CLIENT_DB_PATH, - }; - use std::{fs, path::PathBuf}; - - #[test] - fn purge_files_deletes_all_relevant_files() { - let test_directory_handle = - TestDirectoryHandle::new(PathBuf::from("test_purge_files_deletes_all_relevant_files")); - let root_directory = test_directory_handle.path(); - - let shards_path = root_directory.join(SHARDS_PATH); - fs::create_dir_all(&shards_path).unwrap(); - fs::File::create(&shards_path.join("state_1.bin")).unwrap(); - fs::File::create(&shards_path.join("state_2.bin")).unwrap(); - - fs::File::create(&root_directory.join(RELAYER_REGISTRY_FILE)).unwrap(); - fs::File::create(&root_directory.join(ENCLAVE_REGISTRY_FILE)).unwrap(); - fs::File::create(&root_directory.join(SIGNER_REGISTRY_FILE)).unwrap(); - - fs::create_dir_all(&root_directory.join(LITENTRY_PARENTCHAIN_LIGHT_CLIENT_DB_PATH)) - .unwrap(); - fs::create_dir_all(&root_directory.join(TARGET_A_PARENTCHAIN_LIGHT_CLIENT_DB_PATH)) - .unwrap(); - fs::create_dir_all(&root_directory.join(TARGET_B_PARENTCHAIN_LIGHT_CLIENT_DB_PATH)) - .unwrap(); - - purge_files(&root_directory).unwrap(); - - assert!(!shards_path.exists()); - assert!(!root_directory.join(LITENTRY_PARENTCHAIN_LIGHT_CLIENT_DB_PATH).exists()); - assert!(!root_directory.join(TARGET_A_PARENTCHAIN_LIGHT_CLIENT_DB_PATH).exists()); - assert!(!root_directory.join(TARGET_B_PARENTCHAIN_LIGHT_CLIENT_DB_PATH).exists()); - assert!(!root_directory.join(RELAYER_REGISTRY_FILE).exists()); - assert!(!root_directory.join(ENCLAVE_REGISTRY_FILE).exists()); - assert!(!root_directory.join(SIGNER_REGISTRY_FILE).exists()); - } - - #[test] - fn purge_files_succeeds_when_no_files_exist() { - let test_directory_handle = TestDirectoryHandle::new(PathBuf::from( - "test_purge_files_succeeds_when_no_files_exist", - )); - let root_directory = test_directory_handle.path(); - - assert!(purge_files(&root_directory).is_ok()); - } - - #[test] - fn test_remove_old_shards() { - let test_directory_handle = TestDirectoryHandle::new(PathBuf::from("test_backup_shard")); - let root_directory = test_directory_handle.path(); - let shard_1_name = "test_shard_1"; - let shard_2_name = "test_shard_2"; - - let shard_1_dir = root_directory.join(SHARDS_PATH).join(shard_1_name); - fs::create_dir_all(&shard_1_dir).unwrap(); - fs::File::create(shard_1_dir.join("test_state.bin")).unwrap(); - fs::File::create(shard_1_dir.join("test_state_2.bin")).unwrap(); - - let shard_2_dir = root_directory.join(SHARDS_PATH).join(shard_2_name); - fs::create_dir_all(&shard_2_dir).unwrap(); - fs::File::create(shard_2_dir.join("test_state.bin")).unwrap(); - - assert!(root_directory.join(SHARDS_PATH).join(shard_2_name).exists()); - - remove_old_shards(root_directory, shard_1_name); - - assert!(root_directory.join(SHARDS_PATH).join(shard_1_name).exists()); - assert_eq!( - fs::read_dir(root_directory.join(SHARDS_PATH).join(shard_1_name)) - .expect("Failed to read shard directory") - .count(), - 2 - ); - assert!(!root_directory.join(SHARDS_PATH).join(shard_2_name).exists()); - } - - /// Directory handle to automatically initialize a directory - /// and upon dropping the reference, removing it again. - struct TestDirectoryHandle { - path: PathBuf, - } - - impl TestDirectoryHandle { - pub fn new(path: PathBuf) -> Self { - let test_path = std::env::current_dir().unwrap().join(&path); - fs::create_dir_all(&test_path).unwrap(); - TestDirectoryHandle { path: test_path } - } - - pub fn path(&self) -> &PathBuf { - &self.path - } - } - - impl Drop for TestDirectoryHandle { - fn drop(&mut self) { - if self.path.exists() { - fs::remove_dir_all(&self.path).unwrap(); - } - } - } -} diff --git a/tee-worker/bitacross/service/src/sync_state.rs b/tee-worker/bitacross/service/src/sync_state.rs deleted file mode 100644 index e3bb1bcf99..0000000000 --- a/tee-worker/bitacross/service/src/sync_state.rs +++ /dev/null @@ -1,92 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ - -//! Request state keys from a fellow validateer. - -use crate::{ - enclave::tls_ra::enclave_request_state_provisioning, - error::{Error, ServiceResult as Result}, -}; -use futures::executor; -use itc_rpc_client::direct_client::{DirectApi, DirectClient as DirectWorkerApi}; -use itp_enclave_api::{ - enclave_base::EnclaveBase, - remote_attestation::{RemoteAttestation, TlsRemoteAttestation}, -}; -use itp_node_api::api_client::PalletTeebagApi; -use itp_types::{ShardIdentifier, WorkerType}; -use log::info; -use sgx_types::sgx_quote_sign_type_t; -use sp_runtime::MultiSigner; -use std::string::String; - -pub(crate) fn sync_state< - E: TlsRemoteAttestation + EnclaveBase + RemoteAttestation, - NodeApi: PalletTeebagApi, ->( - node_api: &NodeApi, - shard: &ShardIdentifier, - enclave_api: &E, - skip_ra: bool, -) { - let provider_url = - // TODO(Litentry P-629): maybe implement `get_enclave_url_of_last_active` - executor::block_on(get_enclave_url_of_primary_worker_for_shard(node_api, shard)) - .expect("Author of primary worker for shard could not be found"); - - println!("Requesting state provisioning from worker at {}", &provider_url); - - enclave_request_state_provisioning( - enclave_api, - sgx_quote_sign_type_t::SGX_UNLINKABLE_SIGNATURE, - &provider_url, - shard, - skip_ra, - ) - .unwrap(); - println!("[+] State provisioning successfully performed."); -} - -/// Returns the url of the primary worker for the given shard -async fn get_enclave_url_of_primary_worker_for_shard( - node_api: &NodeApi, - shard: &ShardIdentifier, -) -> Result { - let enclave = node_api - .primary_enclave_for_shard(WorkerType::BitAcross, shard, None)? - .ok_or_else(|| Error::NoWorkerForShardFound(*shard))?; - let worker_api_direct = - DirectWorkerApi::new(String::from_utf8_lossy(enclave.url.as_slice()).to_string()); - Ok(worker_api_direct.get_mu_ra_url()?) -} - -/// Returns the url of the first Enclave that matches our own MRENCLAVE. -/// -/// This should be run before we register ourselves as enclave, to ensure we don't get our own url. -async fn get_enclave_url_of_first_registered( - node_api: &NodeApi, - enclave_api: &EnclaveApi, -) -> Result { - let self_mrenclave = enclave_api.get_fingerprint()?; - let first_enclave = node_api - .all_enclaves(WorkerType::BitAcross, None)? - .into_iter() - .find(|e| e.mrenclave == self_mrenclave.to_fixed_bytes()) - .ok_or(Error::NoPeerWorkerFound)?; - let worker_api_direct = - DirectWorkerApi::new(String::from_utf8_lossy(first_enclave.url.as_slice()).to_string()); - Ok(worker_api_direct.get_mu_ra_url()?) -} diff --git a/tee-worker/bitacross/service/src/tests/commons.rs b/tee-worker/bitacross/service/src/tests/commons.rs deleted file mode 100644 index 9f9ec63271..0000000000 --- a/tee-worker/bitacross/service/src/tests/commons.rs +++ /dev/null @@ -1,63 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use serde_derive::{Deserialize, Serialize}; -use sgx_types::*; -use std::str; - -#[cfg(test)] -use crate::config::Config; - -#[derive(Debug, Serialize, Deserialize)] -pub struct Message { - pub account: String, - pub amount: u32, - pub sha256: sgx_sha256_hash_t, -} - -#[cfg(test)] -pub fn local_worker_config( - worker_url: String, - untrusted_worker_port: String, - mu_ra_port: String, -) -> Config { - let mut url = worker_url.split(':'); - - Config::new( - Default::default(), - Default::default(), - Default::default(), - Default::default(), - Default::default(), - Default::default(), - url.next().unwrap().into(), - None, - url.next().unwrap().into(), - None, - untrusted_worker_port, - None, - mu_ra_port, - false, - "8787".to_string(), - "4545".to_string(), - crate::config::pwd(), - None, - "0".to_string(), - 5, - 10, - ) -} diff --git a/tee-worker/bitacross/service/src/tests/mock.rs b/tee-worker/bitacross/service/src/tests/mock.rs deleted file mode 100644 index 0f96dc3f1e..0000000000 --- a/tee-worker/bitacross/service/src/tests/mock.rs +++ /dev/null @@ -1,69 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use itp_node_api::api_client::{ApiResult, PalletTeebagApi}; -use itp_types::{AccountId, Enclave, MrEnclave, ShardIdentifier, WorkerType, H256 as Hash}; -use std::collections::HashSet; - -pub struct TestNodeApi; - -pub const W1_URL: &str = "127.0.0.1:22222"; -pub const W2_URL: &str = "127.0.0.1:33333"; - -pub fn enclaves() -> Vec { - vec![ - Enclave::new(WorkerType::BitAcross).with_url(W1_URL.into()), - Enclave::new(WorkerType::BitAcross).with_url(W2_URL.into()), - ] -} - -impl PalletTeebagApi for TestNodeApi { - type Hash = Hash; - - fn enclave(&self, _account: &AccountId, _at_block: Option) -> ApiResult> { - unreachable!() - } - fn enclave_count(&self, _worker_type: WorkerType, _at_block: Option) -> ApiResult { - unreachable!() - } - - fn all_enclaves( - &self, - _worker_type: WorkerType, - _at_block: Option, - ) -> ApiResult> { - Ok(enclaves()) - } - - fn primary_enclave_identifier_for_shard( - &self, - worker_type: WorkerType, - shard: &ShardIdentifier, - at_block: Option, - ) -> ApiResult> { - unreachable!() - } - - fn primary_enclave_for_shard( - &self, - worker_type: WorkerType, - shard: &ShardIdentifier, - at_block: Option, - ) -> ApiResult> { - unreachable!() - } -} diff --git a/tee-worker/bitacross/service/src/tests/mocks/enclave_api_mock.rs b/tee-worker/bitacross/service/src/tests/mocks/enclave_api_mock.rs deleted file mode 100644 index 8e47e6cada..0000000000 --- a/tee-worker/bitacross/service/src/tests/mocks/enclave_api_mock.rs +++ /dev/null @@ -1,147 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use codec::{Decode, Encode}; -use core::fmt::Debug; -use itp_enclave_api::{enclave_base::EnclaveBase, sidechain::Sidechain, EnclaveResult}; -use itp_settings::worker::MR_ENCLAVE_SIZE; -use itp_sgx_crypto::{ecdsa, schnorr}; -use itp_stf_interface::ShardCreationInfo; -use itp_storage::StorageProof; -use itp_types::{ - parentchain::{ - Balance, Header, ParentchainId, ParentchainInitParams, - ParentchainInitParams::{Parachain, Solochain}, - }, - EnclaveFingerprint, ShardIdentifier, -}; -use sgx_crypto_helper::rsa3072::Rsa3072PubKey; -use sp_core::ed25519; - -/// mock for EnclaveBase - use in tests -pub struct EnclaveMock; - -impl EnclaveBase for EnclaveMock { - fn init( - &self, - _mu_ra_url: &str, - _untrusted_url: &str, - _base_dir: &str, - _ceremony_commands_thread_count: u8, - _ceremony_events_thread_count: u8, - ) -> EnclaveResult<()> { - Ok(()) - } - - fn init_direct_invocation_server(&self, _rpc_server_addr: String) -> EnclaveResult<()> { - unreachable!() - } - - fn init_parentchain_components( - &self, - params: ParentchainInitParams, - ) -> EnclaveResult
{ - let genesis_header_encoded = match params { - Solochain { params, .. } => params.genesis_header.encode(), - Parachain { params, .. } => params.genesis_header.encode(), - }; - let header = Header::decode(&mut genesis_header_encoded.as_slice())?; - Ok(header) - } - - fn init_shard(&self, _shard: Vec) -> EnclaveResult<()> { - unimplemented!() - } - - fn init_shard_creation_parentchain_header( - &self, - shard: &ShardIdentifier, - parentchain_id: &ParentchainId, - header: &Header, - ) -> EnclaveResult<()> { - unimplemented!() - } - - fn get_shard_creation_info(&self, shard: &ShardIdentifier) -> EnclaveResult { - unimplemented!() - } - - fn set_nonce(&self, _: u32, _: ParentchainId) -> EnclaveResult<()> { - unimplemented!() - } - - fn set_node_metadata(&self, _metadata: Vec, _: ParentchainId) -> EnclaveResult<()> { - todo!() - } - - fn get_rsa_shielding_pubkey(&self) -> EnclaveResult { - unreachable!() - } - - fn get_ecc_signing_pubkey(&self) -> EnclaveResult { - unreachable!() - } - - fn get_bitcoin_wallet_pair(&self) -> EnclaveResult { - unreachable!() - } - - fn get_ethereum_wallet_pair(&self) -> EnclaveResult { - unreachable!() - } - - fn get_ton_wallet_pair(&self) -> EnclaveResult { - unreachable!() - } - - fn get_fingerprint(&self) -> EnclaveResult { - Ok([1u8; MR_ENCLAVE_SIZE].into()) - } - - fn publish_wallets(&self) -> EnclaveResult<()> { - unimplemented!() - } - - fn finish_enclave_init(&self) -> EnclaveResult<()> { - unimplemented!() - } - - fn init_wallets(&self, _base_dir: &str) -> EnclaveResult<()> { - unimplemented!() - } - - fn migrate_shard(&self, new_shard: Vec) -> EnclaveResult<()> { - unimplemented!() - } -} - -impl Sidechain for EnclaveMock { - fn sync_parentchain( - &self, - _blocks: &[sp_runtime::generic::SignedBlock], - _events: &[Vec], - _events_proofs: &[StorageProof], - _: &ParentchainId, - _: bool, - ) -> EnclaveResult<()> { - Ok(()) - } - - fn ignore_parentchain_block_import_validation_until(&self, _until: u32) -> EnclaveResult<()> { - todo!() - } -} diff --git a/tee-worker/bitacross/service/src/tests/mocks/initialization_handler_mock.rs b/tee-worker/bitacross/service/src/tests/mocks/initialization_handler_mock.rs deleted file mode 100644 index 79b2797d7b..0000000000 --- a/tee-worker/bitacross/service/src/tests/mocks/initialization_handler_mock.rs +++ /dev/null @@ -1,34 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use crate::initialized_service::{IsInitialized, TrackInitialization}; - -pub struct TrackInitializationMock; - -impl TrackInitialization for TrackInitializationMock { - fn registered_on_parentchain(&self) {} - - fn worker_for_shard_registered(&self) {} -} - -pub struct IsInitializedMock; - -impl IsInitialized for IsInitializedMock { - fn is_initialized(&self) -> bool { - true - } -} diff --git a/tee-worker/bitacross/service/src/tests/mocks/mod.rs b/tee-worker/bitacross/service/src/tests/mocks/mod.rs deleted file mode 100644 index 406392ef62..0000000000 --- a/tee-worker/bitacross/service/src/tests/mocks/mod.rs +++ /dev/null @@ -1,21 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -pub mod enclave_api_mock; -pub mod initialization_handler_mock; -pub mod parentchain_api_mock; -pub mod update_worker_peers_mock; diff --git a/tee-worker/bitacross/service/src/tests/mocks/parentchain_api_mock.rs b/tee-worker/bitacross/service/src/tests/mocks/parentchain_api_mock.rs deleted file mode 100644 index b383c2412c..0000000000 --- a/tee-worker/bitacross/service/src/tests/mocks/parentchain_api_mock.rs +++ /dev/null @@ -1,111 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use itc_parentchain_test::{ParentchainBlockBuilder, ParentchainHeaderBuilder}; -use itp_node_api::api_client::{ApiResult, ChainApi}; -use itp_types::{ - parentchain::{Hash, Header, StorageProof}, - Block, SignedBlock, H256, -}; -use sp_consensus_grandpa::AuthorityList; - -pub struct ParentchainApiMock { - parentchain: Vec, -} - -impl ParentchainApiMock { - // Todo: Remove when #1451 is resolved - #[allow(unused)] - pub(crate) fn new() -> Self { - ParentchainApiMock { parentchain: Vec::new() } - } - - /// Initializes parentchain with a default block chain of a given length. - // Todo: Remove when #1451 is resolved - #[allow(unused)] - pub fn with_default_blocks(mut self, number_of_blocks: u32) -> Self { - self.parentchain = (1..=number_of_blocks) - .map(|n| { - let header = ParentchainHeaderBuilder::default().with_number(n).build(); - ParentchainBlockBuilder::default().with_header(header).build_signed() - }) - .collect(); - self - } -} - -impl ChainApi for ParentchainApiMock { - type Hash = Hash; - type Block = Block; - type Header = Header; - type BlockNumber = u32; - - fn last_finalized_block(&self) -> ApiResult> { - Ok(self.parentchain.last().cloned()) - } - - fn signed_block(&self, _hash: Option) -> ApiResult> { - todo!() - } - - fn get_genesis_hash(&self) -> ApiResult { - todo!() - } - - fn header(&self, _header_hash: Option) -> ApiResult> { - todo!() - } - - fn get_blocks(&self, from: u32, to: u32) -> ApiResult> { - let num_elements = to.checked_sub(from).map(|n| n + 1).unwrap_or(0); - let blocks = self - .parentchain - .iter() - .skip(from as usize) - .take(num_elements as usize) - .cloned() - .collect(); - ApiResult::Ok(blocks) - } - - fn is_grandpa_available(&self) -> ApiResult { - todo!() - } - - fn grandpa_authorities(&self, _hash: Option) -> ApiResult { - todo!() - } - - fn grandpa_authorities_proof(&self, _hash: Option) -> ApiResult { - todo!() - } - - fn get_events_value_proof(&self, _block_hash: Option) -> ApiResult { - Ok(Default::default()) - } - - fn get_events_for_block(&self, _block_hash: Option) -> ApiResult> { - Ok(Default::default()) - } - - fn get_block_by_number( - &self, - block: Self::BlockNumber, - ) -> ApiResult>> { - Ok(self.parentchain.get(block as usize).cloned()) - } -} diff --git a/tee-worker/bitacross/service/src/tests/mocks/update_worker_peers_mock.rs b/tee-worker/bitacross/service/src/tests/mocks/update_worker_peers_mock.rs deleted file mode 100644 index aeff6ff377..0000000000 --- a/tee-worker/bitacross/service/src/tests/mocks/update_worker_peers_mock.rs +++ /dev/null @@ -1,34 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use crate::{ - worker::{Url, WorkerResult}, - worker_peers_updater::PeersRegistry, -}; -use itp_types::ShardIdentifier; - -pub struct WorkerPeersRegistryMock; - -impl PeersRegistry for WorkerPeersRegistryMock { - fn update_peers(&self, _shard: ShardIdentifier) -> WorkerResult<()> { - Ok(()) - } - - fn read_trusted_peers(&self) -> WorkerResult> { - Ok(Vec::new()) - } -} diff --git a/tee-worker/bitacross/service/src/tests/mod.rs b/tee-worker/bitacross/service/src/tests/mod.rs deleted file mode 100644 index 0ef2c4f253..0000000000 --- a/tee-worker/bitacross/service/src/tests/mod.rs +++ /dev/null @@ -1,48 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -pub mod commons; -pub mod mock; - -#[cfg(test)] -pub mod mocks; - -// Todo: Revive when #1451 is resolved -// #[cfg(test)] -// pub mod parentchain_handler_test; - -#[cfg(feature = "link-binary")] -use clap::ArgMatches; - -#[cfg(feature = "link-binary")] -pub fn run_enclave_tests(matches: &ArgMatches) { - use crate::{config::Config, enclave::api::*, setup}; - use itp_enclave_api::enclave_test::EnclaveTest; - - println!("*** Starting Test enclave"); - let config = Config::from(matches); - setup::purge_files_from_dir(config.data_dir()).unwrap(); - let enclave = enclave_init(&config).unwrap(); - - if matches.is_present("all") || matches.is_present("unit") { - println!("Running unit Tests"); - enclave.test_main_entrance().unwrap(); - println!("[+] unit_test ended!"); - } - - println!("[+] All tests ended!"); -} diff --git a/tee-worker/bitacross/service/src/tests/parentchain_handler_test.rs b/tee-worker/bitacross/service/src/tests/parentchain_handler_test.rs deleted file mode 100644 index 30339e92bb..0000000000 --- a/tee-worker/bitacross/service/src/tests/parentchain_handler_test.rs +++ /dev/null @@ -1,51 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use crate::{ - parentchain_handler::{HandleParentchain, ParentchainHandler}, - tests::mocks::{enclave_api_mock::EnclaveMock, parentchain_api_mock::ParentchainApiMock}, -}; -use itc_parentchain::{ - light_client::light_client_init_params::SimpleParams, - primitives::{ParentchainId, ParentchainInitParams}, -}; -use itc_parentchain_test::ParentchainHeaderBuilder; -use itp_node_api::api_client::ChainApi; -use std::sync::Arc; - -#[test] -fn test_number_of_synced_blocks() { - let number_of_blocks = 42; - - let parentchain_api_mock = ParentchainApiMock::new().with_default_blocks(number_of_blocks); - let last_synced_block = - parentchain_api_mock.get_blocks(2, 2).unwrap().first().cloned().unwrap(); - - let enclave_api_mock = EnclaveMock; - let parentchain_params: ParentchainInitParams = - (ParentchainId::Litentry, SimpleParams::new(ParentchainHeaderBuilder::default().build())) - .into(); - - let parentchain_handler = ParentchainHandler::new( - parentchain_api_mock, - Arc::new(enclave_api_mock), - parentchain_params, - ); - - let header = parentchain_handler.sync_parentchain(last_synced_block.block.header).unwrap(); - assert_eq!(header.number, number_of_blocks); -} diff --git a/tee-worker/bitacross/service/src/utils.rs b/tee-worker/bitacross/service/src/utils.rs deleted file mode 100644 index fd0b60fe82..0000000000 --- a/tee-worker/bitacross/service/src/utils.rs +++ /dev/null @@ -1,53 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - Copyright (C) 2017-2019 Baidu, Inc. All Rights Reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -use base58::{FromBase58, ToBase58}; -use itp_enclave_api::enclave_base::EnclaveBase; -use itp_types::ShardIdentifier; -use log::info; - -pub fn extract_shard( - maybe_shard_str: Option<&str>, - enclave_api: &E, -) -> ShardIdentifier { - match maybe_shard_str { - Some(value) => { - let shard_vec = value.from_base58().expect("shard must be hex encoded"); - let mut shard = [0u8; 32]; - shard.copy_from_slice(&shard_vec[..]); - shard.into() - }, - _ => { - let mrenclave = enclave_api.get_fingerprint().unwrap(); - info!("no shard specified. using mrenclave as id: {}", mrenclave.0.to_base58()); - ShardIdentifier::from_slice(&mrenclave[..]) - }, - } -} - -#[cfg(not(feature = "dcap"))] -pub fn check_files() { - use itp_settings::files::{ENCLAVE_FILE, RA_API_KEY_FILE, RA_SPID_FILE}; - use log::debug; - use std::path::Path; - debug!("*** Check files"); - let files = [ENCLAVE_FILE, RA_SPID_FILE, RA_API_KEY_FILE]; - for f in files.iter() { - assert!(Path::new(f).exists(), "File doesn't exist: {}", f); - } -} diff --git a/tee-worker/bitacross/service/src/wasm.rs b/tee-worker/bitacross/service/src/wasm.rs deleted file mode 100644 index fe99445759..0000000000 --- a/tee-worker/bitacross/service/src/wasm.rs +++ /dev/null @@ -1,62 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ - -use sgx_types::*; - -extern "C" { - fn sgxwasm_init(eid: sgx_enclave_id_t, retval: *mut sgx_status_t) -> sgx_status_t; -} - -#[derive(Debug, Serialize, Deserialize)] -pub enum SgxWasmAction { - #[codec(index = 0)] - Call { module: Option>, function: String }, -} - -#[derive(Debug, Serialize, Deserialize)] -pub enum BoundaryValue { - #[codec(index = 0)] - I32(i32), - #[codec(index = 1)] - I64(i64), - #[codec(index = 2)] - F32(u32), - #[codec(index = 3)] - F64(u64), -} - -pub fn sgx_enclave_wasm_init(eid: sgx_enclave_id_t) -> Result<(), String> { - let mut retval: sgx_status_t = sgx_status_t::SGX_SUCCESS; - let result = unsafe { sgxwasm_init(eid, &mut retval) }; - - match result { - sgx_status_t::SGX_SUCCESS => {}, - _ => { - println!("[-] ECALL Enclave Failed {}!", result.as_str()); - panic!("sgx_enclave_wasm_init's ECALL returned unknown error!"); - }, - } - - match retval { - sgx_status_t::SGX_SUCCESS => {}, - _ => { - println!("[-] ECALL Enclave Function return fail: {}!", retval.as_str()); - return Err(format!("ECALL func return error: {}", retval.as_str())) - }, - } - - Ok(()) -} diff --git a/tee-worker/bitacross/service/src/worker.rs b/tee-worker/bitacross/service/src/worker.rs deleted file mode 100644 index f33976001d..0000000000 --- a/tee-worker/bitacross/service/src/worker.rs +++ /dev/null @@ -1,160 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -///! Integritee worker. Inspiration for this design came from parity's substrate Client. -/// -/// This should serve as a proof of concept for a potential refactoring design. Ultimately, everything -/// from the main.rs should be covered by the worker struct here - hidden and split across -/// multiple traits. -use crate::{config::Config, error::Error, initialized_service::TrackInitialization}; -use async_trait::async_trait; -use codec::{Decode, Encode}; -use itc_rpc_client::direct_client::{DirectApi, DirectClient as DirectWorkerApi}; -use itp_enclave_api::enclave_base::EnclaveBase; -use itp_node_api::{api_client::PalletTeebagApi, node_api_factory::CreateNodeApi}; -use itp_types::ShardIdentifier; -use jsonrpsee::{ - types::{to_json_value, traits::Client}, - ws_client::WsClientBuilder, -}; -use litentry_primitives::WorkerType; -use log::*; -use std::{ - collections::HashSet, - sync::{Arc, RwLock}, -}; - -pub type WorkerResult = Result; -pub type Url = String; - -#[derive(Clone, Hash, Eq, PartialEq, Encode, Decode, Debug)] -pub struct PeerUrls { - pub trusted: Url, - pub untrusted: Url, - pub me: bool, -} - -impl PeerUrls { - pub fn new(trusted: Url, untrusted: Url, me: bool) -> Self { - PeerUrls { trusted, untrusted, me } - } -} - -pub struct Worker { - _config: Config, - // unused yet, but will be used when more methods are migrated to the worker - _enclave_api: Arc, - node_api_factory: Arc, - initialization_handler: Arc, - peer_urls: RwLock>, -} - -impl - Worker -{ - pub fn new( - config: Config, - enclave_api: Arc, - node_api_factory: Arc, - initialization_handler: Arc, - peer_urls: HashSet, - ) -> Self { - Self { - _config: config, - _enclave_api: enclave_api, - node_api_factory, - initialization_handler, - peer_urls: RwLock::new(peer_urls), - } - } -} - -/// Looks for new peers and updates them. -pub trait UpdatePeers { - fn search_peers(&self, shard: ShardIdentifier) -> WorkerResult>; - - fn set_peers_urls(&self, peers: HashSet) -> WorkerResult<()>; - - fn update_peers(&self, shard: ShardIdentifier) -> WorkerResult<()> { - let peers = self.search_peers(shard)?; - self.set_peers_urls(peers) - } -} - -pub trait GetPeers { - fn read_peers_urls(&self) -> WorkerResult>; -} - -impl GetPeers - for Worker -where - NodeApiFactory: CreateNodeApi + Send + Sync, - Enclave: EnclaveBase + itp_enclave_api::remote_attestation::TlsRemoteAttestation, -{ - fn read_peers_urls(&self) -> WorkerResult> { - if let Ok(peer_urls) = self.peer_urls.read() { - Ok(peer_urls.clone()) - } else { - Err(Error::Custom("Encountered poisoned lock for peers".into())) - } - } -} - -impl UpdatePeers - for Worker -where - NodeApiFactory: CreateNodeApi + Send + Sync, - Enclave: EnclaveBase + itp_enclave_api::remote_attestation::TlsRemoteAttestation, -{ - fn search_peers(&self, shard: ShardIdentifier) -> WorkerResult> { - let worker_url_external = self._config.trusted_worker_url_external(); - let node_api = self - .node_api_factory - .create_api() - .map_err(|e| Error::Custom(format!("Failed to create NodeApi: {:?}", e).into()))?; - let enclaves = node_api.all_enclaves(WorkerType::BitAcross, None)?; - let mut peer_urls = HashSet::::new(); - for enclave in enclaves { - // FIXME: This is temporary only, as block broadcasting should be moved to trusted ws server. - let enclave_url = String::from_utf8_lossy(enclave.url.as_slice()).to_string(); - trace!("found peer rpc url: {}", enclave_url); - let worker_api_direct = DirectWorkerApi::new(enclave_url.clone()); - match worker_api_direct.get_untrusted_worker_url() { - Ok(untrusted_worker_url) => { - let is_me = enclave_url == worker_url_external; - peer_urls.insert(PeerUrls::new(enclave_url, untrusted_worker_url, is_me)); - }, - Err(e) => { - warn!("Failed to get untrusted worker url (enclave: {}): {:?}", enclave_url, e); - }, - } - } - debug!("found {} peers in shard state for {:?}", peer_urls.len(), shard); - Ok(peer_urls) - } - - fn set_peers_urls(&self, peers: HashSet) -> WorkerResult<()> { - let peers_vec: Vec = peers.clone().into_iter().collect(); - info!("Setting peers urls: {:?}", peers_vec); - - let mut peer_urls = self.peer_urls.write().map_err(|e| { - Error::Custom(format!("Encountered poisoned lock for peers urls: {:?}", e).into()) - })?; - *peer_urls = peers; - Ok(()) - } -} diff --git a/tee-worker/bitacross/service/src/worker_peers_updater.rs b/tee-worker/bitacross/service/src/worker_peers_updater.rs deleted file mode 100644 index fb3671aaab..0000000000 --- a/tee-worker/bitacross/service/src/worker_peers_updater.rs +++ /dev/null @@ -1,57 +0,0 @@ -/* - Copyright 2021 Integritee AG and Supercomputing Systems AG - Copyright (C) 2017-2019 Baidu, Inc. All Rights Reserved. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -*/ - -#[cfg(test)] -use mockall::predicate::*; -#[cfg(test)] -use mockall::*; - -use crate::worker::{GetPeers, UpdatePeers, Url, WorkerResult}; -use itp_types::ShardIdentifier; -use std::sync::Arc; - -/// Updates the peers of the global worker. -#[cfg_attr(test, automock)] -pub trait PeersRegistry { - fn update_peers(&self, shard: ShardIdentifier) -> WorkerResult<()>; - fn read_trusted_peers(&self) -> WorkerResult>; -} - -pub struct WorkerPeersRegistry { - worker: Arc, -} - -impl WorkerPeersRegistry { - pub fn new(worker: Arc) -> Self { - WorkerPeersRegistry { worker } - } -} - -impl PeersRegistry for WorkerPeersRegistry -where - WorkerType: UpdatePeers + GetPeers, -{ - fn update_peers(&self, shard: ShardIdentifier) -> WorkerResult<()> { - self.worker.update_peers(shard) - } - - fn read_trusted_peers(&self) -> WorkerResult> { - let peer_urls = self.worker.read_peers_urls()?; - Ok(peer_urls.into_iter().filter(|urls| !urls.me).map(|urls| urls.trusted).collect()) - } -} diff --git a/tee-worker/bitacross/ts-tests/.editorconfig b/tee-worker/bitacross/ts-tests/.editorconfig deleted file mode 100644 index 347fc689b2..0000000000 --- a/tee-worker/bitacross/ts-tests/.editorconfig +++ /dev/null @@ -1,6 +0,0 @@ -# Editor configuration, see http://editorconfig.org - -[*] -indent_style = space -indent_size = 4 - diff --git a/tee-worker/bitacross/ts-tests/.gitignore b/tee-worker/bitacross/ts-tests/.gitignore deleted file mode 100644 index 3a8fe5ede8..0000000000 --- a/tee-worker/bitacross/ts-tests/.gitignore +++ /dev/null @@ -1 +0,0 @@ -.env.local \ No newline at end of file diff --git a/tee-worker/bitacross/ts-tests/.prettierrc b/tee-worker/bitacross/ts-tests/.prettierrc deleted file mode 100644 index b65f49a91b..0000000000 --- a/tee-worker/bitacross/ts-tests/.prettierrc +++ /dev/null @@ -1,7 +0,0 @@ -{ - "trailingComma": "es5", - "singleQuote": true, - "printWidth": 120, - "tabWidth": 4, - "semi": true -} diff --git a/tee-worker/bitacross/ts-tests/README.md b/tee-worker/bitacross/ts-tests/README.md deleted file mode 100644 index c26dd8f0c2..0000000000 --- a/tee-worker/bitacross/ts-tests/README.md +++ /dev/null @@ -1,23 +0,0 @@ -## Description - -ts-tests of bitacross-worker - -## Environment setup - -- Install [nvm](https://github.com/nvm-sh/nvm) -- Inside the repository, run `nvm use` to set the correct Node version. - - If the version is not installed, run `nvm install`. - -## Prerequisite - -Before running the ts-tests, the client-api types generation needs to be completed. - -See client-api [README.md](https://github.com/litentry/litentry-parachain/blob/dev/tee-worker/identity/client-api/README.md) - -## Installation - -``` -nvm use -corepack enable pnpm -pnpm install -``` \ No newline at end of file diff --git a/tee-worker/bitacross/ts-tests/integration-tests/.env.local.example b/tee-worker/bitacross/ts-tests/integration-tests/.env.local.example deleted file mode 100644 index 87c0179b9f..0000000000 --- a/tee-worker/bitacross/ts-tests/integration-tests/.env.local.example +++ /dev/null @@ -1,5 +0,0 @@ -NODE_ENV = local -ENCLAVE_ENDPOINT = ws://localhost:2000 -PARACHAIN_ENDPOINT = ws://localhost:9944 -BINARY_DIR=../../bin -LITENTRY_CLI_DIR=../../bin/bitacross-cli diff --git a/tee-worker/bitacross/ts-tests/integration-tests/.env.staging b/tee-worker/bitacross/ts-tests/integration-tests/.env.staging deleted file mode 100644 index 53ae73ef81..0000000000 --- a/tee-worker/bitacross/ts-tests/integration-tests/.env.staging +++ /dev/null @@ -1,5 +0,0 @@ -NODE_ENV = staging -ENCLAVE_ENDPOINT = ws://bitacross-worker-1:2011 -PARACHAIN_ENDPOINT = "ws://litentry-node:9912" -BINARY_DIR=/usr/local/bin -LITENTRY_CLI_DIR=/usr/local/bin/bitacross-cli \ No newline at end of file diff --git a/tee-worker/bitacross/ts-tests/integration-tests/.eslintrc.json b/tee-worker/bitacross/ts-tests/integration-tests/.eslintrc.json deleted file mode 100644 index 0e93a1188c..0000000000 --- a/tee-worker/bitacross/ts-tests/integration-tests/.eslintrc.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "extends": ["eslint:recommended", "plugin:@typescript-eslint/recommended"], - "parser": "@typescript-eslint/parser", - "plugins": ["@typescript-eslint"], - "root": true, - "rules": { - /** - It's a temporary solution, folks. We had no choice but to shut it off, - because there's just a liiittle bit too much "any" lurking around in the code. - But fear not, my friends, for this is not the end of the story. - We shall return, armed with determination and resolve, - to tackle those "any" types head-on in the near future. - **/ - "@typescript-eslint/no-explicit-any": ["off"], - "@typescript-eslint/no-non-null-assertion": ["off"], - "@typescript-eslint/no-var-requires": ["off"], - - // explanation: https://typescript-eslint.io/rules/naming-convention/ - "@typescript-eslint/naming-convention": [ - "error", - { - "selector": "typeLike", - "format": ["StrictPascalCase"] - }, - { - "selector": "variable", - "modifiers": ["const"], - "format": ["strictCamelCase", "UPPER_CASE"] - }, - { - "selector": "function", - "format": ["strictCamelCase", "StrictPascalCase"] - }, - { - "selector": "parameter", - "format": ["strictCamelCase"] - } - ] - } -} diff --git a/tee-worker/bitacross/ts-tests/integration-tests/package.json b/tee-worker/bitacross/ts-tests/integration-tests/package.json deleted file mode 100644 index e7f39d9541..0000000000 --- a/tee-worker/bitacross/ts-tests/integration-tests/package.json +++ /dev/null @@ -1,24 +0,0 @@ -{ - "name": "integration-tests", - "license": "ISC", - "type": "module", - "scripts": { - "check-format": "prettier --check .", - "format": "prettier --write .", - "pretest": "eslint .", - "test": "mocha --exit --sort -r ts-node/register --loader=ts-node/esm", - "check-types": "tsc --noEmit" - }, - "dependencies": { - "chai": "^5.1.1", - "dotenv": "^16.4.5", - "mocha": "^10.6.0", - "ws": "^8.18.0" - }, - "devDependencies": { - "prettier": "2.8.1", - "ts-node": "^10.9.1", - "typescript": "5.0.4" - }, - "packageManager": "pnpm@8.7.6" -} diff --git a/tee-worker/bitacross/ts-tests/integration-tests/sign_bitcoin.test.ts b/tee-worker/bitacross/ts-tests/integration-tests/sign_bitcoin.test.ts deleted file mode 100644 index cb041f73db..0000000000 --- a/tee-worker/bitacross/ts-tests/integration-tests/sign_bitcoin.test.ts +++ /dev/null @@ -1,83 +0,0 @@ -import WebSocket from 'ws'; -import { assert } from 'chai'; -import dotenv from 'dotenv'; - -function getWorkerUrls(env: String): String[] { - if (env == 'local') { - let enclaveEndpoint = process.env.ENCLAVE_ENDPOINT!; - const enclaveEndpointParts = enclaveEndpoint.split(':'); - let url = enclaveEndpointParts[0] + ':' + enclaveEndpointParts[1]; - let port = parseInt(enclaveEndpointParts[2]); - return [url + ':' + port, url + ':' + (port + 10), url + ':' + (port + 20)]; - } else { - return ['wss://bitacross-worker-1:2011', 'wss://bitacross-worker-2:2011', 'wss://bitacross-worker-3:2011']; - } -} - -function sleep(time) { - return new Promise((resolve) => setTimeout(resolve, time)); -} - -describe('test-bitcoin', async () => { - // eslint-disable-next-line @typescript-eslint/no-var-requires, no-undef - dotenv.config({ path: `.env.${process.env.NODE_ENV || 'local'}` }); - - const workerUrls = getWorkerUrls(process.env.NODE_ENV as string); - console.log('Using worker urls: ' + workerUrls); - console.log('Start: ' + Date.now()); - // it needs to wait for workers to be ready, todo: use is_initialized - await sleep(60 * 1000); - console.log('Run: ' + Date.now()); - - it('should pass on all workers', async () => { - const worker1 = new WebSocket(workerUrls[0], { - perMessageDeflate: false, - rejectUnauthorized: false, - }); - const worker2 = new WebSocket(workerUrls[1], { - perMessageDeflate: false, - rejectUnauthorized: false, - }); - const worker3 = new WebSocket(workerUrls[2], { - perMessageDeflate: false, - rejectUnauthorized: false, - }); - - let worker1Resolve: any; - let worker1Result = new Promise((resolve, reject) => { - worker1Resolve = resolve; - }); - let worker2Resolve: any; - let worker2Result = new Promise((resolve, reject) => { - worker2Resolve = resolve; - }); - let worker3Resolve: any; - let worker3Result = new Promise((resolve, reject) => { - worker3Resolve = resolve; - }); - - worker1.on('message', (message: any) => { - worker1Resolve(message == '{"jsonrpc":"2.0","result":"0x04010000","id":1}'); - }); - worker2.on('message', (message: any) => { - worker2Resolve(message == '{"jsonrpc":"2.0","result":"0x04010000","id":1}'); - }); - worker3.on('message', (message: any) => { - worker3Resolve(message == '{"jsonrpc":"2.0","result":"0x04010000","id":1}'); - }); - - worker1.on('open', () => { - worker1.send('{"id":1,"jsonrpc":"2.0","method":"bitacross_checkSignBitcoin","params":[]}'); - }); - worker2.on('open', () => { - worker2.send('{"id":1,"jsonrpc":"2.0","method":"bitacross_checkSignBitcoin","params":[]}'); - }); - worker3.on('open', () => { - worker3.send('{"id":1,"jsonrpc":"2.0","method":"bitacross_checkSignBitcoin","params":[]}'); - }); - - await Promise.all([worker1Result, worker2Result, worker3Result]).then(([w1, w2, w3]) => { - assert(w1 && w2 && w3); - }); - }); -}); diff --git a/tee-worker/bitacross/ts-tests/integration-tests/tsconfig.json b/tee-worker/bitacross/ts-tests/integration-tests/tsconfig.json deleted file mode 100644 index 077ab9bb03..0000000000 --- a/tee-worker/bitacross/ts-tests/integration-tests/tsconfig.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "compilerOptions": { - "target": "ESNext", - "module": "ESNext", - "moduleResolution": "Node", - "declaration": true, - "strict": true, - "skipLibCheck": true, - "esModuleInterop": true, - "allowSyntheticDefaultImports": true, - "resolveJsonModule": true, - "baseUrl": "." - }, - "ts-node": { - "esm": true, - "experimentalResolver": true, - "experimentalSpecifierResolution": "node", - "transpileOnly": true - } -} diff --git a/tee-worker/bitacross/ts-tests/package.json b/tee-worker/bitacross/ts-tests/package.json deleted file mode 100644 index 346af2afda..0000000000 --- a/tee-worker/bitacross/ts-tests/package.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "type": "module", - "license": "ISC", - "scripts": { - "format": "pnpm run --recursive format", - "check-format": "pnpm run --recursive check-format" - }, - "packageManager": "pnpm@8.7.6" -} diff --git a/tee-worker/bitacross/ts-tests/pnpm-lock.yaml b/tee-worker/bitacross/ts-tests/pnpm-lock.yaml deleted file mode 100644 index befebb7204..0000000000 --- a/tee-worker/bitacross/ts-tests/pnpm-lock.yaml +++ /dev/null @@ -1,706 +0,0 @@ -lockfileVersion: '6.0' - -settings: - autoInstallPeers: true - excludeLinksFromLockfile: false - -importers: - - .: {} - - integration-tests: - dependencies: - chai: - specifier: ^5.1.1 - version: 5.1.1 - dotenv: - specifier: ^16.4.5 - version: 16.4.5 - mocha: - specifier: ^10.6.0 - version: 10.6.0 - ws: - specifier: ^8.18.0 - version: 8.18.0 - devDependencies: - prettier: - specifier: 2.8.1 - version: 2.8.1 - ts-node: - specifier: ^10.9.1 - version: 10.9.2(@types/node@20.14.10)(typescript@5.0.4) - typescript: - specifier: 5.0.4 - version: 5.0.4 - -packages: - - /@cspotcode/source-map-support@0.8.1: - resolution: {integrity: sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==} - engines: {node: '>=12'} - dependencies: - '@jridgewell/trace-mapping': 0.3.9 - dev: true - - /@jridgewell/resolve-uri@3.1.2: - resolution: {integrity: sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==} - engines: {node: '>=6.0.0'} - dev: true - - /@jridgewell/sourcemap-codec@1.4.15: - resolution: {integrity: sha512-eF2rxCRulEKXHTRiDrDy6erMYWqNw4LPdQ8UQA4huuxaQsVeRPFl2oM8oDGxMFhJUWZf9McpLtJasDDZb/Bpeg==} - dev: true - - /@jridgewell/trace-mapping@0.3.9: - resolution: {integrity: sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==} - dependencies: - '@jridgewell/resolve-uri': 3.1.2 - '@jridgewell/sourcemap-codec': 1.4.15 - dev: true - - /@tsconfig/node10@1.0.11: - resolution: {integrity: sha512-DcRjDCujK/kCk/cUe8Xz8ZSpm8mS3mNNpta+jGCA6USEDfktlNvm1+IuZ9eTcDbNk41BHwpHHeW+N1lKCz4zOw==} - dev: true - - /@tsconfig/node12@1.0.11: - resolution: {integrity: sha512-cqefuRsh12pWyGsIoBKJA9luFu3mRxCA+ORZvA4ktLSzIuCUtWVxGIuXigEwO5/ywWFMZ2QEGKWvkZG1zDMTag==} - dev: true - - /@tsconfig/node14@1.0.3: - resolution: {integrity: sha512-ysT8mhdixWK6Hw3i1V2AeRqZ5WfXg1G43mqoYlM2nc6388Fq5jcXyr5mRsqViLx/GJYdoL0bfXD8nmF+Zn/Iow==} - dev: true - - /@tsconfig/node16@1.0.4: - resolution: {integrity: sha512-vxhUy4J8lyeyinH7Azl1pdd43GJhZH/tP2weN8TntQblOY+A0XbT8DJk1/oCPuOOyg/Ja757rG0CgHcWC8OfMA==} - dev: true - - /@types/node@20.14.10: - resolution: {integrity: sha512-MdiXf+nDuMvY0gJKxyfZ7/6UFsETO7mGKF54MVD/ekJS6HdFtpZFBgrh6Pseu64XTb2MLyFPlbW6hj8HYRQNOQ==} - dependencies: - undici-types: 5.26.5 - dev: true - - /acorn-walk@8.3.3: - resolution: {integrity: sha512-MxXdReSRhGO7VlFe1bRG/oI7/mdLV9B9JJT0N8vZOhF7gFRR5l3M8W9G8JxmKV+JC5mGqJ0QvqfSOLsCPa4nUw==} - engines: {node: '>=0.4.0'} - dependencies: - acorn: 8.12.1 - dev: true - - /acorn@8.12.1: - resolution: {integrity: sha512-tcpGyI9zbizT9JbV6oYE477V6mTlXvvi0T0G3SNIYE2apm/G5huBa1+K89VGeovbg+jycCrfhl3ADxErOuO6Jg==} - engines: {node: '>=0.4.0'} - hasBin: true - dev: true - - /ansi-colors@4.1.3: - resolution: {integrity: sha512-/6w/C21Pm1A7aZitlI5Ni/2J6FFQN8i1Cvz3kHABAAbw93v/NlvKdVOqz7CCWz/3iv/JplRSEEZ83XION15ovw==} - engines: {node: '>=6'} - dev: false - - /ansi-regex@5.0.1: - resolution: {integrity: sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==} - engines: {node: '>=8'} - dev: false - - /ansi-styles@4.3.0: - resolution: {integrity: sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==} - engines: {node: '>=8'} - dependencies: - color-convert: 2.0.1 - dev: false - - /anymatch@3.1.3: - resolution: {integrity: sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==} - engines: {node: '>= 8'} - dependencies: - normalize-path: 3.0.0 - picomatch: 2.3.1 - dev: false - - /arg@4.1.3: - resolution: {integrity: sha512-58S9QDqG0Xx27YwPSt9fJxivjYl432YCwfDMfZ+71RAqUrZef7LrKQZ3LHLOwCS4FLNBplP533Zx895SeOCHvA==} - dev: true - - /argparse@2.0.1: - resolution: {integrity: sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==} - dev: false - - /assertion-error@2.0.1: - resolution: {integrity: sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==} - engines: {node: '>=12'} - dev: false - - /balanced-match@1.0.2: - resolution: {integrity: sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==} - dev: false - - /binary-extensions@2.3.0: - resolution: {integrity: sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw==} - engines: {node: '>=8'} - dev: false - - /brace-expansion@2.0.1: - resolution: {integrity: sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA==} - dependencies: - balanced-match: 1.0.2 - dev: false - - /braces@3.0.3: - resolution: {integrity: sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==} - engines: {node: '>=8'} - dependencies: - fill-range: 7.1.1 - dev: false - - /browser-stdout@1.3.1: - resolution: {integrity: sha512-qhAVI1+Av2X7qelOfAIYwXONood6XlZE/fXaBSmW/T5SzLAmCgzi+eiWE7fUvbHaeNBQH13UftjpXxsfLkMpgw==} - dev: false - - /camelcase@6.3.0: - resolution: {integrity: sha512-Gmy6FhYlCY7uOElZUSbxo2UCDH8owEk996gkbrpsgGtrJLM3J7jGxl9Ic7Qwwj4ivOE5AWZWRMecDdF7hqGjFA==} - engines: {node: '>=10'} - dev: false - - /chai@5.1.1: - resolution: {integrity: sha512-pT1ZgP8rPNqUgieVaEY+ryQr6Q4HXNg8Ei9UnLUrjN4IA7dvQC5JB+/kxVcPNDHyBcc/26CXPkbNzq3qwrOEKA==} - engines: {node: '>=12'} - dependencies: - assertion-error: 2.0.1 - check-error: 2.1.1 - deep-eql: 5.0.2 - loupe: 3.1.1 - pathval: 2.0.0 - dev: false - - /chalk@4.1.2: - resolution: {integrity: sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==} - engines: {node: '>=10'} - dependencies: - ansi-styles: 4.3.0 - supports-color: 7.2.0 - dev: false - - /check-error@2.1.1: - resolution: {integrity: sha512-OAlb+T7V4Op9OwdkjmguYRqncdlx5JiofwOAUkmTF+jNdHwzTaTs4sRAGpzLF3oOz5xAyDGrPgeIDFQmDOTiJw==} - engines: {node: '>= 16'} - dev: false - - /chokidar@3.6.0: - resolution: {integrity: sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==} - engines: {node: '>= 8.10.0'} - dependencies: - anymatch: 3.1.3 - braces: 3.0.3 - glob-parent: 5.1.2 - is-binary-path: 2.1.0 - is-glob: 4.0.3 - normalize-path: 3.0.0 - readdirp: 3.6.0 - optionalDependencies: - fsevents: 2.3.3 - dev: false - - /cliui@7.0.4: - resolution: {integrity: sha512-OcRE68cOsVMXp1Yvonl/fzkQOyjLSu/8bhPDfQt0e0/Eb283TKP20Fs2MqoPsr9SwA595rRCA+QMzYc9nBP+JQ==} - dependencies: - string-width: 4.2.3 - strip-ansi: 6.0.1 - wrap-ansi: 7.0.0 - dev: false - - /color-convert@2.0.1: - resolution: {integrity: sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==} - engines: {node: '>=7.0.0'} - dependencies: - color-name: 1.1.4 - dev: false - - /color-name@1.1.4: - resolution: {integrity: sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==} - dev: false - - /create-require@1.1.1: - resolution: {integrity: sha512-dcKFX3jn0MpIaXjisoRvexIJVEKzaq7z2rZKxf+MSr9TkdmHmsU4m2lcLojrj/FHl8mk5VxMmYA+ftRkP/3oKQ==} - dev: true - - /debug@4.3.5(supports-color@8.1.1): - resolution: {integrity: sha512-pt0bNEmneDIvdL1Xsd9oDQ/wrQRkXDT4AUWlNZNPKvW5x/jyO9VFXkJUP07vQ2upmw5PlaITaPKc31jK13V+jg==} - engines: {node: '>=6.0'} - peerDependencies: - supports-color: '*' - peerDependenciesMeta: - supports-color: - optional: true - dependencies: - ms: 2.1.2 - supports-color: 8.1.1 - dev: false - - /decamelize@4.0.0: - resolution: {integrity: sha512-9iE1PgSik9HeIIw2JO94IidnE3eBoQrFJ3w7sFuzSX4DpmZ3v5sZpUiV5Swcf6mQEF+Y0ru8Neo+p+nyh2J+hQ==} - engines: {node: '>=10'} - dev: false - - /deep-eql@5.0.2: - resolution: {integrity: sha512-h5k/5U50IJJFpzfL6nO9jaaumfjO/f2NjK/oYB2Djzm4p9L+3T9qWpZqZ2hAbLPuuYq9wrU08WQyBTL5GbPk5Q==} - engines: {node: '>=6'} - dev: false - - /diff@4.0.2: - resolution: {integrity: sha512-58lmxKSA4BNyLz+HHMUzlOEpg09FV+ev6ZMe3vJihgdxzgcwZ8VoEEPmALCZG9LmqfVoNMMKpttIYTVG6uDY7A==} - engines: {node: '>=0.3.1'} - dev: true - - /diff@5.2.0: - resolution: {integrity: sha512-uIFDxqpRZGZ6ThOk84hEfqWoHx2devRFvpTZcTHur85vImfaxUbTW9Ryh4CpCuDnToOP1CEtXKIgytHBPVff5A==} - engines: {node: '>=0.3.1'} - dev: false - - /dotenv@16.4.5: - resolution: {integrity: sha512-ZmdL2rui+eB2YwhsWzjInR8LldtZHGDoQ1ugH85ppHKwpUHL7j7rN0Ti9NCnGiQbhaZ11FpR+7ao1dNsmduNUg==} - engines: {node: '>=12'} - dev: false - - /emoji-regex@8.0.0: - resolution: {integrity: sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==} - dev: false - - /escalade@3.1.2: - resolution: {integrity: sha512-ErCHMCae19vR8vQGe50xIsVomy19rg6gFu3+r3jkEO46suLMWBksvVyoGgQV+jOfl84ZSOSlmv6Gxa89PmTGmA==} - engines: {node: '>=6'} - dev: false - - /escape-string-regexp@4.0.0: - resolution: {integrity: sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==} - engines: {node: '>=10'} - dev: false - - /fill-range@7.1.1: - resolution: {integrity: sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==} - engines: {node: '>=8'} - dependencies: - to-regex-range: 5.0.1 - dev: false - - /find-up@5.0.0: - resolution: {integrity: sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==} - engines: {node: '>=10'} - dependencies: - locate-path: 6.0.0 - path-exists: 4.0.0 - dev: false - - /flat@5.0.2: - resolution: {integrity: sha512-b6suED+5/3rTpUBdG1gupIl8MPFCAMA0QXwmljLhvCUKcUvdE4gWky9zpuGCcXHOsz4J9wPGNWq6OKpmIzz3hQ==} - hasBin: true - dev: false - - /fs.realpath@1.0.0: - resolution: {integrity: sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==} - dev: false - - /fsevents@2.3.3: - resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==} - engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} - os: [darwin] - requiresBuild: true - dev: false - optional: true - - /get-caller-file@2.0.5: - resolution: {integrity: sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==} - engines: {node: 6.* || 8.* || >= 10.*} - dev: false - - /get-func-name@2.0.2: - resolution: {integrity: sha512-8vXOvuE167CtIc3OyItco7N/dpRtBbYOsPsXCz7X/PMnlGjYjSGuZJgM1Y7mmew7BKf9BqvLX2tnOVy1BBUsxQ==} - dev: false - - /glob-parent@5.1.2: - resolution: {integrity: sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==} - engines: {node: '>= 6'} - dependencies: - is-glob: 4.0.3 - dev: false - - /glob@8.1.0: - resolution: {integrity: sha512-r8hpEjiQEYlF2QU0df3dS+nxxSIreXQS1qRhMJM0Q5NDdR386C7jb7Hwwod8Fgiuex+k0GFjgft18yvxm5XoCQ==} - engines: {node: '>=12'} - deprecated: Glob versions prior to v9 are no longer supported - dependencies: - fs.realpath: 1.0.0 - inflight: 1.0.6 - inherits: 2.0.4 - minimatch: 5.1.6 - once: 1.4.0 - dev: false - - /has-flag@4.0.0: - resolution: {integrity: sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==} - engines: {node: '>=8'} - dev: false - - /he@1.2.0: - resolution: {integrity: sha512-F/1DnUGPopORZi0ni+CvrCgHQ5FyEAHRLSApuYWMmrbSwoN2Mn/7k+Gl38gJnR7yyDZk6WLXwiGod1JOWNDKGw==} - hasBin: true - dev: false - - /inflight@1.0.6: - resolution: {integrity: sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==} - deprecated: This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful. - dependencies: - once: 1.4.0 - wrappy: 1.0.2 - dev: false - - /inherits@2.0.4: - resolution: {integrity: sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==} - dev: false - - /is-binary-path@2.1.0: - resolution: {integrity: sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==} - engines: {node: '>=8'} - dependencies: - binary-extensions: 2.3.0 - dev: false - - /is-extglob@2.1.1: - resolution: {integrity: sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==} - engines: {node: '>=0.10.0'} - dev: false - - /is-fullwidth-code-point@3.0.0: - resolution: {integrity: sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==} - engines: {node: '>=8'} - dev: false - - /is-glob@4.0.3: - resolution: {integrity: sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==} - engines: {node: '>=0.10.0'} - dependencies: - is-extglob: 2.1.1 - dev: false - - /is-number@7.0.0: - resolution: {integrity: sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==} - engines: {node: '>=0.12.0'} - dev: false - - /is-plain-obj@2.1.0: - resolution: {integrity: sha512-YWnfyRwxL/+SsrWYfOpUtz5b3YD+nyfkHvjbcanzk8zgyO4ASD67uVMRt8k5bM4lLMDnXfriRhOpemw+NfT1eA==} - engines: {node: '>=8'} - dev: false - - /is-unicode-supported@0.1.0: - resolution: {integrity: sha512-knxG2q4UC3u8stRGyAVJCOdxFmv5DZiRcdlIaAQXAbSfJya+OhopNotLQrstBhququ4ZpuKbDc/8S6mgXgPFPw==} - engines: {node: '>=10'} - dev: false - - /js-yaml@4.1.0: - resolution: {integrity: sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==} - hasBin: true - dependencies: - argparse: 2.0.1 - dev: false - - /locate-path@6.0.0: - resolution: {integrity: sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==} - engines: {node: '>=10'} - dependencies: - p-locate: 5.0.0 - dev: false - - /log-symbols@4.1.0: - resolution: {integrity: sha512-8XPvpAA8uyhfteu8pIvQxpJZ7SYYdpUivZpGy6sFsBuKRY/7rQGavedeB8aK+Zkyq6upMFVL/9AW6vOYzfRyLg==} - engines: {node: '>=10'} - dependencies: - chalk: 4.1.2 - is-unicode-supported: 0.1.0 - dev: false - - /loupe@3.1.1: - resolution: {integrity: sha512-edNu/8D5MKVfGVFRhFf8aAxiTM6Wumfz5XsaatSxlD3w4R1d/WEKUTydCdPGbl9K7QG/Ca3GnDV2sIKIpXRQcw==} - dependencies: - get-func-name: 2.0.2 - dev: false - - /make-error@1.3.6: - resolution: {integrity: sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw==} - dev: true - - /minimatch@5.1.6: - resolution: {integrity: sha512-lKwV/1brpG6mBUFHtb7NUmtABCb2WZZmm2wNiOA5hAb8VdCS4B3dtMWyvcoViccwAW/COERjXLt0zP1zXUN26g==} - engines: {node: '>=10'} - dependencies: - brace-expansion: 2.0.1 - dev: false - - /mocha@10.6.0: - resolution: {integrity: sha512-hxjt4+EEB0SA0ZDygSS015t65lJw/I2yRCS3Ae+SJ5FrbzrXgfYwJr96f0OvIXdj7h4lv/vLCrH3rkiuizFSvw==} - engines: {node: '>= 14.0.0'} - hasBin: true - dependencies: - ansi-colors: 4.1.3 - browser-stdout: 1.3.1 - chokidar: 3.6.0 - debug: 4.3.5(supports-color@8.1.1) - diff: 5.2.0 - escape-string-regexp: 4.0.0 - find-up: 5.0.0 - glob: 8.1.0 - he: 1.2.0 - js-yaml: 4.1.0 - log-symbols: 4.1.0 - minimatch: 5.1.6 - ms: 2.1.3 - serialize-javascript: 6.0.2 - strip-json-comments: 3.1.1 - supports-color: 8.1.1 - workerpool: 6.5.1 - yargs: 16.2.0 - yargs-parser: 20.2.9 - yargs-unparser: 2.0.0 - dev: false - - /ms@2.1.2: - resolution: {integrity: sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==} - dev: false - - /ms@2.1.3: - resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==} - dev: false - - /normalize-path@3.0.0: - resolution: {integrity: sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==} - engines: {node: '>=0.10.0'} - dev: false - - /once@1.4.0: - resolution: {integrity: sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==} - dependencies: - wrappy: 1.0.2 - dev: false - - /p-limit@3.1.0: - resolution: {integrity: sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==} - engines: {node: '>=10'} - dependencies: - yocto-queue: 0.1.0 - dev: false - - /p-locate@5.0.0: - resolution: {integrity: sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==} - engines: {node: '>=10'} - dependencies: - p-limit: 3.1.0 - dev: false - - /path-exists@4.0.0: - resolution: {integrity: sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==} - engines: {node: '>=8'} - dev: false - - /pathval@2.0.0: - resolution: {integrity: sha512-vE7JKRyES09KiunauX7nd2Q9/L7lhok4smP9RZTDeD4MVs72Dp2qNFVz39Nz5a0FVEW0BJR6C0DYrq6unoziZA==} - engines: {node: '>= 14.16'} - dev: false - - /picomatch@2.3.1: - resolution: {integrity: sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==} - engines: {node: '>=8.6'} - dev: false - - /prettier@2.8.1: - resolution: {integrity: sha512-lqGoSJBQNJidqCHE80vqZJHWHRFoNYsSpP9AjFhlhi9ODCJA541svILes/+/1GM3VaL/abZi7cpFzOpdR9UPKg==} - engines: {node: '>=10.13.0'} - hasBin: true - dev: true - - /randombytes@2.1.0: - resolution: {integrity: sha512-vYl3iOX+4CKUWuxGi9Ukhie6fsqXqS9FE2Zaic4tNFD2N2QQaXOMFbuKK4QmDHC0JO6B1Zp41J0LpT0oR68amQ==} - dependencies: - safe-buffer: 5.2.1 - dev: false - - /readdirp@3.6.0: - resolution: {integrity: sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==} - engines: {node: '>=8.10.0'} - dependencies: - picomatch: 2.3.1 - dev: false - - /require-directory@2.1.1: - resolution: {integrity: sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==} - engines: {node: '>=0.10.0'} - dev: false - - /safe-buffer@5.2.1: - resolution: {integrity: sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==} - dev: false - - /serialize-javascript@6.0.2: - resolution: {integrity: sha512-Saa1xPByTTq2gdeFZYLLo+RFE35NHZkAbqZeWNd3BpzppeVisAqpDjcp8dyf6uIvEqJRd46jemmyA4iFIeVk8g==} - dependencies: - randombytes: 2.1.0 - dev: false - - /string-width@4.2.3: - resolution: {integrity: sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==} - engines: {node: '>=8'} - dependencies: - emoji-regex: 8.0.0 - is-fullwidth-code-point: 3.0.0 - strip-ansi: 6.0.1 - dev: false - - /strip-ansi@6.0.1: - resolution: {integrity: sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==} - engines: {node: '>=8'} - dependencies: - ansi-regex: 5.0.1 - dev: false - - /strip-json-comments@3.1.1: - resolution: {integrity: sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==} - engines: {node: '>=8'} - dev: false - - /supports-color@7.2.0: - resolution: {integrity: sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==} - engines: {node: '>=8'} - dependencies: - has-flag: 4.0.0 - dev: false - - /supports-color@8.1.1: - resolution: {integrity: sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==} - engines: {node: '>=10'} - dependencies: - has-flag: 4.0.0 - dev: false - - /to-regex-range@5.0.1: - resolution: {integrity: sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==} - engines: {node: '>=8.0'} - dependencies: - is-number: 7.0.0 - dev: false - - /ts-node@10.9.2(@types/node@20.14.10)(typescript@5.0.4): - resolution: {integrity: sha512-f0FFpIdcHgn8zcPSbf1dRevwt047YMnaiJM3u2w2RewrB+fob/zePZcrOyQoLMMO7aBIddLcQIEK5dYjkLnGrQ==} - hasBin: true - peerDependencies: - '@swc/core': '>=1.2.50' - '@swc/wasm': '>=1.2.50' - '@types/node': '*' - typescript: '>=2.7' - peerDependenciesMeta: - '@swc/core': - optional: true - '@swc/wasm': - optional: true - dependencies: - '@cspotcode/source-map-support': 0.8.1 - '@tsconfig/node10': 1.0.11 - '@tsconfig/node12': 1.0.11 - '@tsconfig/node14': 1.0.3 - '@tsconfig/node16': 1.0.4 - '@types/node': 20.14.10 - acorn: 8.12.1 - acorn-walk: 8.3.3 - arg: 4.1.3 - create-require: 1.1.1 - diff: 4.0.2 - make-error: 1.3.6 - typescript: 5.0.4 - v8-compile-cache-lib: 3.0.1 - yn: 3.1.1 - dev: true - - /typescript@5.0.4: - resolution: {integrity: sha512-cW9T5W9xY37cc+jfEnaUvX91foxtHkza3Nw3wkoF4sSlKn0MONdkdEndig/qPBWXNkmplh3NzayQzCiHM4/hqw==} - engines: {node: '>=12.20'} - hasBin: true - dev: true - - /undici-types@5.26.5: - resolution: {integrity: sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA==} - dev: true - - /v8-compile-cache-lib@3.0.1: - resolution: {integrity: sha512-wa7YjyUGfNZngI/vtK0UHAN+lgDCxBPCylVXGp0zu59Fz5aiGtNXaq3DhIov063MorB+VfufLh3JlF2KdTK3xg==} - dev: true - - /workerpool@6.5.1: - resolution: {integrity: sha512-Fs4dNYcsdpYSAfVxhnl1L5zTksjvOJxtC5hzMNl+1t9B8hTJTdKDyZ5ju7ztgPy+ft9tBFXoOlDNiOT9WUXZlA==} - dev: false - - /wrap-ansi@7.0.0: - resolution: {integrity: sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==} - engines: {node: '>=10'} - dependencies: - ansi-styles: 4.3.0 - string-width: 4.2.3 - strip-ansi: 6.0.1 - dev: false - - /wrappy@1.0.2: - resolution: {integrity: sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==} - dev: false - - /ws@8.18.0: - resolution: {integrity: sha512-8VbfWfHLbbwu3+N6OKsOMpBdT4kXPDDB9cJk2bJ6mh9ucxdlnNvH1e+roYkKmN9Nxw2yjz7VzeO9oOz2zJ04Pw==} - engines: {node: '>=10.0.0'} - peerDependencies: - bufferutil: ^4.0.1 - utf-8-validate: '>=5.0.2' - peerDependenciesMeta: - bufferutil: - optional: true - utf-8-validate: - optional: true - dev: false - - /y18n@5.0.8: - resolution: {integrity: sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==} - engines: {node: '>=10'} - dev: false - - /yargs-parser@20.2.9: - resolution: {integrity: sha512-y11nGElTIV+CT3Zv9t7VKl+Q3hTQoT9a1Qzezhhl6Rp21gJ/IVTW7Z3y9EWXhuUBC2Shnf+DX0antecpAwSP8w==} - engines: {node: '>=10'} - dev: false - - /yargs-unparser@2.0.0: - resolution: {integrity: sha512-7pRTIA9Qc1caZ0bZ6RYRGbHJthJWuakf+WmHK0rVeLkNrrGhfoabBNdue6kdINI6r4if7ocq9aD/n7xwKOdzOA==} - engines: {node: '>=10'} - dependencies: - camelcase: 6.3.0 - decamelize: 4.0.0 - flat: 5.0.2 - is-plain-obj: 2.1.0 - dev: false - - /yargs@16.2.0: - resolution: {integrity: sha512-D1mvvtDG0L5ft/jGWkLpG1+m0eQxOfaBvTNELraWj22wSVUMWxZUvYgJYcKh6jGGIkJFhH4IZPQhR4TKpc8mBw==} - engines: {node: '>=10'} - dependencies: - cliui: 7.0.4 - escalade: 3.1.2 - get-caller-file: 2.0.5 - require-directory: 2.1.1 - string-width: 4.2.3 - y18n: 5.0.8 - yargs-parser: 20.2.9 - dev: false - - /yn@3.1.1: - resolution: {integrity: sha512-Ux4ygGWsu2c7isFWe8Yu1YluJmqVhxqK2cLXNQA5AcC3QfbGNpM7fu0Y8b/z16pXLnFxZYvWhd3fhBY9DLmC6Q==} - engines: {node: '>=6'} - dev: true - - /yocto-queue@0.1.0: - resolution: {integrity: sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==} - engines: {node: '>=10'} - dev: false diff --git a/tee-worker/bitacross/ts-tests/pnpm-workspace.yaml b/tee-worker/bitacross/ts-tests/pnpm-workspace.yaml deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/tee-worker/bitacross/upstream_commit b/tee-worker/bitacross/upstream_commit deleted file mode 100644 index 195f70c5e6..0000000000 --- a/tee-worker/bitacross/upstream_commit +++ /dev/null @@ -1 +0,0 @@ -9a3b032 diff --git a/tee-worker/common/core-primitives/enclave-metrics/src/lib.rs b/tee-worker/common/core-primitives/enclave-metrics/src/lib.rs index 68f55825dc..477eb6c5a9 100644 --- a/tee-worker/common/core-primitives/enclave-metrics/src/lib.rs +++ b/tee-worker/common/core-primitives/enclave-metrics/src/lib.rs @@ -51,9 +51,4 @@ pub enum EnclaveMetric { ParentchainEventProcessed(String), DynamicAssertionSaveTime(Duration), DynamicAssertionGetTime(Duration), - // bitacross - Musig2CeremonyStarted, - Musig2CeremonyFailed, - Musig2CeremonyTimedout(u8), - Musig2CeremonyDuration(Duration), } diff --git a/tee-worker/common/core-primitives/node-api/metadata/src/lib.rs b/tee-worker/common/core-primitives/node-api/metadata/src/lib.rs index 0362f47b5b..a5a0c369a2 100644 --- a/tee-worker/common/core-primitives/node-api/metadata/src/lib.rs +++ b/tee-worker/common/core-primitives/node-api/metadata/src/lib.rs @@ -20,7 +20,7 @@ #![cfg_attr(not(feature = "std"), no_std)] use crate::{ - error::Result, pallet_balances::BalancesCallIndexes, pallet_bitacross::BitAcrossCallIndexes, + error::Result, pallet_balances::BalancesCallIndexes, pallet_evm_assertion::EvmAssertionsCallIndexes, pallet_imp::IMPCallIndexes, pallet_omni_account::OmniAccountCallIndexes, pallet_proxy::ProxyCallIndexes, pallet_system::SystemConstants, pallet_teebag::TeebagCallIndexes, @@ -35,7 +35,6 @@ pub use itp_api_client_types::{Metadata, MetadataError}; pub mod error; pub mod pallet_balances; -pub mod pallet_bitacross; pub mod pallet_evm_assertion; pub mod pallet_imp; pub mod pallet_omni_account; @@ -61,7 +60,6 @@ pub trait NodeMetadataTrait: + BalancesCallIndexes + TimestampCallIndexes + EvmAssertionsCallIndexes - + BitAcrossCallIndexes + OmniAccountCallIndexes { } @@ -76,7 +74,6 @@ impl< + BalancesCallIndexes + TimestampCallIndexes + EvmAssertionsCallIndexes - + BitAcrossCallIndexes + OmniAccountCallIndexes, > NodeMetadataTrait for T { diff --git a/tee-worker/common/core-primitives/node-api/metadata/src/metadata_mocks.rs b/tee-worker/common/core-primitives/node-api/metadata/src/metadata_mocks.rs index 0189d1309d..e15812a093 100644 --- a/tee-worker/common/core-primitives/node-api/metadata/src/metadata_mocks.rs +++ b/tee-worker/common/core-primitives/node-api/metadata/src/metadata_mocks.rs @@ -16,7 +16,7 @@ */ use crate::{ - error::Result, pallet_balances::BalancesCallIndexes, pallet_bitacross::BitAcrossCallIndexes, + error::Result, pallet_balances::BalancesCallIndexes, pallet_evm_assertion::EvmAssertionsCallIndexes, pallet_imp::IMPCallIndexes, pallet_omni_account::OmniAccountCallIndexes, pallet_proxy::ProxyCallIndexes, pallet_system::SystemConstants, pallet_teebag::TeebagCallIndexes, @@ -90,13 +90,6 @@ pub struct NodeMetadataMock { runtime_spec_version: u32, runtime_transaction_version: u32, - bitacross_module: u8, - bitacross_add_relayer: u8, - bitacross_remove_relayer: u8, - btc_wallet_generated: u8, - eth_wallet_generated: u8, - ton_wallet_generated: u8, - omni_account_module: u8, dispatch_as_omni_account: u8, dispatch_as_signed: u8, @@ -158,13 +151,6 @@ impl NodeMetadataMock { runtime_spec_version: 25, runtime_transaction_version: 4, - bitacross_module: 69u8, - bitacross_add_relayer: 0u8, - bitacross_remove_relayer: 1u8, - btc_wallet_generated: 2u8, - eth_wallet_generated: 3u8, - ton_wallet_generated: 4u8, - omni_account_module: 70u8, dispatch_as_omni_account: 0u8, dispatch_as_signed: 1u8, @@ -322,28 +308,6 @@ impl BalancesCallIndexes for NodeMetadataMock { } } -impl BitAcrossCallIndexes for NodeMetadataMock { - fn add_relayer_call_indexes(&self) -> Result<[u8; 2]> { - Ok([self.bitacross_module, self.bitacross_add_relayer]) - } - - fn remove_relayer_call_indexes(&self) -> Result<[u8; 2]> { - Ok([self.bitacross_module, self.bitacross_remove_relayer]) - } - - fn btc_wallet_generated_indexes(&self) -> Result<[u8; 2]> { - Ok([self.bitacross_module, self.btc_wallet_generated]) - } - - fn eth_wallet_generated_indexes(&self) -> Result<[u8; 2]> { - Ok([self.bitacross_module, self.eth_wallet_generated]) - } - - fn ton_wallet_generated_indexes(&self) -> Result<[u8; 2]> { - Ok([self.bitacross_module, self.ton_wallet_generated]) - } -} - impl TimestampCallIndexes for NodeMetadataMock { fn timestamp_set_call_indexes(&self) -> Result<[u8; 2]> { Ok([self.timestamp_module, self.timestamp_set]) diff --git a/tee-worker/common/core-primitives/node-api/metadata/src/pallet_bitacross.rs b/tee-worker/common/core-primitives/node-api/metadata/src/pallet_bitacross.rs deleted file mode 100644 index 0c45043f28..0000000000 --- a/tee-worker/common/core-primitives/node-api/metadata/src/pallet_bitacross.rs +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright 2020-2024 Trust Computing GmbH. -// This file is part of Litentry. -// -// Litentry is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// Litentry is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with Litentry. If not, see . - -// TODO: maybe use macros to simplify this -use crate::{error::Result, NodeMetadata}; - -const BITACROSS: &str = "Bitacross"; - -pub trait BitAcrossCallIndexes { - fn add_relayer_call_indexes(&self) -> Result<[u8; 2]>; - fn remove_relayer_call_indexes(&self) -> Result<[u8; 2]>; - fn btc_wallet_generated_indexes(&self) -> Result<[u8; 2]>; - fn eth_wallet_generated_indexes(&self) -> Result<[u8; 2]>; - fn ton_wallet_generated_indexes(&self) -> Result<[u8; 2]>; -} - -impl BitAcrossCallIndexes for NodeMetadata { - fn add_relayer_call_indexes(&self) -> Result<[u8; 2]> { - self.call_indexes(BITACROSS, "add_relayer") - } - - fn remove_relayer_call_indexes(&self) -> Result<[u8; 2]> { - self.call_indexes(BITACROSS, "remove_relayer") - } - - fn btc_wallet_generated_indexes(&self) -> Result<[u8; 2]> { - self.call_indexes(BITACROSS, "btc_wallet_generated") - } - - fn eth_wallet_generated_indexes(&self) -> Result<[u8; 2]> { - self.call_indexes(BITACROSS, "eth_wallet_generated") - } - - fn ton_wallet_generated_indexes(&self) -> Result<[u8; 2]> { - self.call_indexes(BITACROSS, "ton_wallet_generated") - } -} diff --git a/tee-worker/common/core-primitives/settings/src/lib.rs b/tee-worker/common/core-primitives/settings/src/lib.rs index 55dfb81caf..44300ae631 100644 --- a/tee-worker/common/core-primitives/settings/src/lib.rs +++ b/tee-worker/common/core-primitives/settings/src/lib.rs @@ -50,13 +50,6 @@ pub mod files { pub const RA_DUMP_CERT_DER_FILE: &str = "ra_dump_cert.der"; - // bitacross - pub const RELAYER_REGISTRY_FILE: &str = "relayer_registry_sealed.bin"; - - pub const ENCLAVE_REGISTRY_FILE: &str = "enclave_registry_sealed.bin"; - - pub const SIGNER_REGISTRY_FILE: &str = "signer_registry_sealed.bin"; - // used by worker and enclave pub const SHARDS_PATH: &str = "shards"; diff --git a/tee-worker/common/core-primitives/types/src/parentchain/events.rs b/tee-worker/common/core-primitives/types/src/parentchain/events.rs index 57205832ed..8c379e6359 100644 --- a/tee-worker/common/core-primitives/types/src/parentchain/events.rs +++ b/tee-worker/common/core-primitives/types/src/parentchain/events.rs @@ -6,7 +6,7 @@ use alloc::{format, vec::Vec}; use codec::{Decode, Encode}; use core::fmt::Debug; use itp_utils::{hex::ToHexPrefixed, stringify::account_id_to_string}; -use litentry_primitives::{Address32, Identity, MemberAccount}; +use litentry_primitives::{Address32, MemberAccount}; use sp_core::H160; use substrate_api_client::ac_node_api::StaticEvent; @@ -306,66 +306,3 @@ impl StaticEvent for AssertionCreated { const PALLET: &'static str = "EvmAssertions"; const EVENT: &'static str = "AssertionCreated"; } - -// Bitacross pallet events - -#[derive(Encode, Decode, Debug)] -pub struct RelayerAdded { - pub who: Identity, -} - -impl core::fmt::Display for RelayerAdded { - fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { - if let Some(account_id) = self.who.to_native_account() { - let message = format!("RelayerAdded :: account_id: {:?}", account_id); - write!(f, "{}", message) - } else { - write!(f, "RelayerAdded :: account_id: None") - } - } -} - -impl StaticEvent for RelayerAdded { - const PALLET: &'static str = "Bitacross"; - const EVENT: &'static str = "RelayerAdded"; -} - -#[derive(Encode, Decode, Debug)] -pub struct RelayerRemoved { - pub who: Identity, -} - -impl core::fmt::Display for RelayerRemoved { - fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { - if let Some(account_id) = self.who.to_native_account() { - let message = format!("RelayerRemoved :: account_id: {:?}", account_id); - write!(f, "{}", message) - } else { - write!(f, "RelayerRemoved :: account_id: None") - } - } -} - -impl StaticEvent for RelayerRemoved { - const PALLET: &'static str = "Bitacross"; - const EVENT: &'static str = "RelayerRemoved"; -} - -#[derive(Encode, Decode, Debug)] -pub struct BtcWalletGenerated { - pub pub_key: [u8; 33], - pub account_id: AccountId, -} - -impl core::fmt::Display for BtcWalletGenerated { - fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { - let account_id = account_id_to_string::(&self.account_id); - let message = format!("BtcWalletGenerated :: account_id: {:?}", account_id); - write!(f, "{}", message) - } -} - -impl StaticEvent for BtcWalletGenerated { - const PALLET: &'static str = "Bitacross"; - const EVENT: &'static str = "BtcWalletGenerated"; -} diff --git a/tee-worker/common/core-primitives/types/src/parentchain/mod.rs b/tee-worker/common/core-primitives/types/src/parentchain/mod.rs index 05172aabd5..64a5eddfc4 100644 --- a/tee-worker/common/core-primitives/types/src/parentchain/mod.rs +++ b/tee-worker/common/core-primitives/types/src/parentchain/mod.rs @@ -118,16 +118,10 @@ pub trait FilterEvents { &self, ) -> Result, Self::Error>; - fn get_relayer_added_events(&self) -> Result, Self::Error>; - - fn get_relayers_removed_events(&self) -> Result, Self::Error>; - fn get_enclave_added_events(&self) -> Result, Self::Error>; fn get_enclave_removed_events(&self) -> Result, Self::Error>; - fn get_btc_wallet_generated_events(&self) -> Result, Self::Error>; - fn get_account_store_updated_events(&self) -> Result, Self::Error>; } diff --git a/tee-worker/identity/app-libs/parentchain-interface/src/integritee/event_filter.rs b/tee-worker/identity/app-libs/parentchain-interface/src/integritee/event_filter.rs index f0ae6078dc..c6fcf4d94a 100644 --- a/tee-worker/identity/app-libs/parentchain-interface/src/integritee/event_filter.rs +++ b/tee-worker/identity/app-libs/parentchain-interface/src/integritee/event_filter.rs @@ -98,14 +98,6 @@ impl FilterEvents for FilterableEvents { self.filter() } - fn get_relayer_added_events(&self) -> Result, Self::Error> { - self.filter() - } - - fn get_relayers_removed_events(&self) -> Result, Self::Error> { - self.filter() - } - fn get_enclave_added_events(&self) -> Result, Self::Error> { self.filter() } @@ -114,10 +106,6 @@ impl FilterEvents for FilterableEvents { self.filter() } - fn get_btc_wallet_generated_events(&self) -> Result, Self::Error> { - self.filter() - } - fn get_account_store_updated_events(&self) -> Result, Self::Error> { self.filter() } diff --git a/tee-worker/identity/app-libs/parentchain-interface/src/target_a/event_filter.rs b/tee-worker/identity/app-libs/parentchain-interface/src/target_a/event_filter.rs index 4b86a285e8..95659a3a37 100644 --- a/tee-worker/identity/app-libs/parentchain-interface/src/target_a/event_filter.rs +++ b/tee-worker/identity/app-libs/parentchain-interface/src/target_a/event_filter.rs @@ -96,14 +96,6 @@ impl FilterEvents for FilterableEvents { Ok(Vec::new()) } - fn get_relayer_added_events(&self) -> Result, Self::Error> { - self.filter() - } - - fn get_relayers_removed_events(&self) -> Result, Self::Error> { - self.filter() - } - fn get_enclave_added_events(&self) -> Result, Self::Error> { self.filter() } @@ -112,10 +104,6 @@ impl FilterEvents for FilterableEvents { self.filter() } - fn get_btc_wallet_generated_events(&self) -> Result, Self::Error> { - self.filter() - } - fn get_account_store_updated_events(&self) -> Result, Self::Error> { self.filter() } diff --git a/tee-worker/identity/app-libs/parentchain-interface/src/target_b/event_filter.rs b/tee-worker/identity/app-libs/parentchain-interface/src/target_b/event_filter.rs index 4b86a285e8..95659a3a37 100644 --- a/tee-worker/identity/app-libs/parentchain-interface/src/target_b/event_filter.rs +++ b/tee-worker/identity/app-libs/parentchain-interface/src/target_b/event_filter.rs @@ -96,14 +96,6 @@ impl FilterEvents for FilterableEvents { Ok(Vec::new()) } - fn get_relayer_added_events(&self) -> Result, Self::Error> { - self.filter() - } - - fn get_relayers_removed_events(&self) -> Result, Self::Error> { - self.filter() - } - fn get_enclave_added_events(&self) -> Result, Self::Error> { self.filter() } @@ -112,10 +104,6 @@ impl FilterEvents for FilterableEvents { self.filter() } - fn get_btc_wallet_generated_events(&self) -> Result, Self::Error> { - self.filter() - } - fn get_account_store_updated_events(&self) -> Result, Self::Error> { self.filter() } diff --git a/tee-worker/identity/core/parentchain/indirect-calls-executor/src/mock.rs b/tee-worker/identity/core/parentchain/indirect-calls-executor/src/mock.rs index 25cab5b0e6..16a95d30ce 100644 --- a/tee-worker/identity/core/parentchain/indirect-calls-executor/src/mock.rs +++ b/tee-worker/identity/core/parentchain/indirect-calls-executor/src/mock.rs @@ -66,10 +66,6 @@ impl FilterEvents for MockEvents { Ok(Vec::new()) } - fn get_btc_wallet_generated_events(&self) -> Result, Self::Error> { - Ok(Vec::new()) - } - fn get_enclave_added_events(&self) -> Result, Self::Error> { Ok(Vec::new()) } @@ -78,14 +74,6 @@ impl FilterEvents for MockEvents { Ok(Vec::new()) } - fn get_relayer_added_events(&self) -> Result, Self::Error> { - Ok(Vec::new()) - } - - fn get_relayers_removed_events(&self) -> Result, Self::Error> { - Ok(Vec::new()) - } - fn get_account_store_updated_events(&self) -> Result, Self::Error> { Ok(Vec::new()) }