diff --git a/.github/workflows/build_and_test.yml b/.github/workflows/build_and_test.yml index d748906a25..77d7330ed2 100644 --- a/.github/workflows/build_and_test.yml +++ b/.github/workflows/build_and_test.yml @@ -33,16 +33,26 @@ jobs: fail-fast: false matrix: include: + - flavor_id: sidechain + mode: sidechain + host: ubuntu-latest + sgx_mode: HW + additional_features: dcap - flavor_id: offchain-worker mode: offchain-worker host: ubuntu-latest sgx_mode: SW additional_features: dcap - - flavor_id: offchain-worker - mode: offchain-worker + - flavor_id: teeracle + mode: teeracle host: ubuntu-latest sgx_mode: HW additional_features: dcap + - flavor_id: sidechain-evm + mode: sidechain + additional_features: evm,dcap + host: ubuntu-latest + sgx_mode: HW steps: - uses: actions/checkout@v3 @@ -60,6 +70,8 @@ jobs: echo "DOCKER_DEVICES=" >> $GITHUB_ENV echo "DOCKER_VOLUMES=" >> $GITHUB_ENV fi + # Correctly define INTEGRITEE_NODE + echo "INTEGRITEE_NODE=integritee-node:1.13.0" >> $GITHUB_ENV - name: Set up Docker Buildx uses: docker/setup-buildx-action@v2 @@ -87,18 +99,17 @@ jobs: docker image save integritee-worker-${{ env.IMAGE_SUFFIX }} | gzip > integritee-worker-${{ env.IMAGE_SUFFIX }}.tar.gz - name: Upload worker image - uses: actions/upload-artifact@v3 + uses: actions/upload-artifact@v4 with: name: integritee-worker-${{ env.IMAGE_SUFFIX }}.tar.gz path: integritee-worker-${{ env.IMAGE_SUFFIX }}.tar.gz - - name: Create Enclave Digest File run: | mrenclave_hex=$(docker run integritee-worker-${{ env.IMAGE_SUFFIX }} mrenclave | grep -oP ':\s*\K[a-fA-F0-9]+') echo "$mrenclave_hex" > mrenclave-${{ env.IMAGE_SUFFIX }}.hex - name: Upload Enclave Digest File - uses: actions/upload-artifact@v3 + uses: actions/upload-artifact@v4 with: name: mrenclave-${{ env.IMAGE_SUFFIX }}.hex path: mrenclave-${{ env.IMAGE_SUFFIX }}.hex @@ -116,11 +127,26 @@ jobs: fail-fast: false matrix: include: + - flavor_id: sidechain + mode: sidechain + host: ubuntu-latest + sgx_mode: HW + additional_features: dcap - flavor_id: offchain-worker mode: offchain-worker host: ubuntu-latest sgx_mode: SW additional_features: dcap + - flavor_id: teeracle + mode: teeracle + host: ubuntu-latest + sgx_mode: HW + additional_features: dcap + - flavor_id: sidechain-evm + mode: sidechain + additional_features: evm,dcap + host: ubuntu-latest + sgx_mode: HW steps: - uses: actions/checkout@v3 @@ -161,7 +187,7 @@ jobs: docker image save integritee-cli-client-${{ env.IMAGE_SUFFIX }} | gzip > integritee-cli-client-${{ env.IMAGE_SUFFIX }}.tar.gz - name: Upload CLI client image - uses: actions/upload-artifact@v3 + uses: actions/upload-artifact@v4 with: name: integritee-cli-client-${{ env.IMAGE_SUFFIX }}.tar.gz path: integritee-cli-client-${{ env.IMAGE_SUFFIX }}.tar.gz @@ -222,7 +248,7 @@ jobs: run: rustup show - name: Install taplo - run: cargo install taplo-cli --locked + run: cargo install --version 0.8.1 taplo-cli --locked - name: Cargo.toml fmt run: taplo fmt --check @@ -233,10 +259,14 @@ jobs: integration-tests: runs-on: ${{ matrix.host }} if: ${{ always() }} - needs: [build-test, build-client] + needs: [ build-test, build-client ] env: WORKER_IMAGE_TAG: integritee-worker:dev CLIENT_IMAGE_TAG: integritee-cli:dev + COINMARKETCAP_KEY: ${{ secrets.COINMARKETCAP_KEY }} + # IAS_EPID_SPID: ${{ secrets.IAS_SPID }} + # IAS_EPID_KEY: ${{ secrets.IAS_PRIMARY_KEY }} + TEERACLE_INTERVAL_SECONDS: 10 strategy: fail-fast: false @@ -244,10 +274,49 @@ jobs: include: - test: M6 flavor_id: offchain-worker - demo_name: demo-indirect-invocation + #demo_name: demo-shielding-unshielding-multiworker + host: ubuntu-latest + sgx_mode: HW - test: BestEnergy + flavor_id: sidechain + #demo_name: demo-energy-market + host: self-hosted + sgx_mode: HW + - test: M8 + flavor_id: sidechain + #demo_name: demo-direct-call + host: ubuntu-latest + sgx_mode: HW + - test: Sidechain + flavor_id: sidechain + #demo_name: demo-sidechain + host: ubuntu-latest + sgx_mode: HW + - test: M6 flavor_id: offchain-worker - demo_name: demo-energy-market + #demo_name: demo-shielding-unshielding-multiworker + host: ubuntu-latest + sgx_mode: HW +# - test: Teeracle +# flavor_id: teeracle +# demo_name: demo-teeracle +# host: test-runner-sgx +# sgx_mode: HW + - test: Teeracle + flavor_id: teeracle + #demo_name: demo-teeracle-generic + host: ubuntu-latest + sgx_mode: HW + - test: Benchmark + flavor_id: sidechain + #demo_name: sidechain-benchmark + host: ubuntu-latest + sgx_mode: HW + - test: EVM + flavor_id: sidechain-evm + #demo_name: demo-smart-contract + host: ubuntu-latest + sgx_mode: HW steps: - uses: actions/checkout@v3 @@ -306,29 +375,28 @@ jobs: fi docker tag integritee-worker-${{ env.IMAGE_SUFFIX }} ${{ env.WORKER_IMAGE_TAG }} docker tag integritee-cli-client-${{ env.IMAGE_SUFFIX }} ${{ env.CLIENT_IMAGE_TAG }} - docker pull integritee/integritee-node:1.1.3 - docker tag integritee/integritee-node:1.1.3 ${{ env.INTEGRITEE_NODE }} + docker pull integritee/integritee-node:1.13.0 + docker tag integritee/integritee-node:1.13.0 ${{ env.INTEGRITEE_NODE }} docker images --all - - name: Integration Test ${{ matrix.test }}-${{ matrix.flavor_id }} - timeout-minutes: 30 - run: | - cd docker - docker compose -f docker-compose.yml -f ${{ matrix.demo_name }}.yml up ${{ matrix.demo_name }} --no-build --exit-code-from ${{ matrix.demo_name }} - + ## + # Stop any stucked/running compose projects + ## - name: Stop docker containers if: always() + continue-on-error: true run: | cd docker docker compose -f <(envsubst < docker-compose.yml) -f <(envsubst < ${{ matrix.demo_name }}.yml) -p ${PROJECT} stop - name: Integration Test ${{ matrix.test }}-${{ matrix.flavor_id }} - timeout-minutes: 30 run: | cd docker - docker compose -f <(envsubst < docker-compose.yml) -f <(envsubst < ${{ matrix.demo_name }}.yml) -p ${PROJECT} up ${{ matrix.demo_name }} --no-build --exit-code-from ${{ matrix.demo_name }} --remove-orphans - - + if [ -n "${{ matrix.demo_name }}" ]; then + docker compose -f <(envsubst < docker-compose.yml) -f <(envsubst < ${{ matrix.demo_name }}.yml) -p ${PROJECT} up ${{ matrix.demo_name }} --no-build --exit-code-from ${{ matrix.demo_name }} --remove-orphans + else + echo "Demo service is commented out; not running demo." + fi - name: Collect Docker Logs continue-on-error: true if: always() @@ -340,7 +408,7 @@ jobs: - name: Upload logs if: always() - uses: actions/upload-artifact@v3 + uses: actions/upload-artifact@v4 with: name: logs-${{ matrix.test }}-${{ matrix.flavor_id }} path: ${{ env.LOG_DIR }} @@ -372,7 +440,7 @@ jobs: docker images --all release-build: - runs-on: integritee-builder-sgx + runs-on: ubuntu-latest name: Release Build of teeracle if: startsWith(github.ref, 'refs/tags/') needs: [ build-test, integration-tests ] @@ -449,22 +517,45 @@ jobs: --build-arg WORKER_MODE_ARG=${{ matrix.mode }} --build-arg SGX_COMMERCIAL_KEY=enclave-runtime/intel_sgx.pem --build-arg SGX_PASSFILE=enclave-runtime/passfile.txt --build-arg SGX_PRODUCTION=1 --build-arg ADDITIONAL_FEATURES_ARG=${{ matrix.additional_features }} --build-arg SGX_MODE=${{ matrix.sgx_mode }} -f build.Dockerfile . - - name: Save released teeracle + - name: Build Worker CLI + env: + DOCKER_BUILDKIT: 1 + run: > + docker build -t integritee/${{ matrix.flavor_id }}-cli:${{ github.ref_name }} + --target deployed-client + --build-arg WORKER_MODE_ARG=${{ matrix.mode }} --build-arg ADDITIONAL_FEATURES_ARG=${{ matrix.additional_features }} + -f build.Dockerfile . + + - name: Save worker docker image run: | docker image save integritee/${{ matrix.flavor_id }}:${{ github.ref_name }} | gzip > integritee-worker-${{ matrix.flavor_id }}-${{ github.ref_name }}.tar.gz docker images --all - - name: Upload teeracle image - uses: actions/upload-artifact@v3 + - name: Save CLI docker image + run: | + docker image save integritee/${{ matrix.flavor_id }}-cli:${{ github.ref_name }} | gzip > ${{ matrix.flavor_id }}-cli-${{ github.ref_name }}.tar.gz + docker images --all + + - name: Upload image + uses: actions/upload-artifact@v4 with: name: integritee-worker-${{ matrix.flavor_id }}-${{ github.ref_name }}.tar.gz path: integritee-worker-${{ matrix.flavor_id }}-${{ github.ref_name }}.tar.gz + - name: Upload cli image + uses: actions/upload-artifact@v4 + with: + name: ${{ matrix.flavor_id }}-cli-${{ github.ref_name }}.tar.gz + path: ${{ matrix.flavor_id }}-cli-${{ github.ref_name }}.tar.gz + - name: Delete images run: | if [[ "$(docker images -q integritee/${{ matrix.flavor_id }}:${{ github.ref_name }} 2> /dev/null)" != "" ]]; then docker image rmi --force integritee/${{ matrix.flavor_id }}:${{ github.ref_name }} 2>/dev/null fi + if [[ "$(docker images -q integritee/${{ matrix.flavor_id }}-cli:${{ github.ref_name }} 2> /dev/null)" != "" ]]; then + docker image rmi --force integritee/${{ matrix.flavor_id }}-cli:${{ github.ref_name }} 2>/dev/null + fi docker images --all release: @@ -478,18 +569,30 @@ jobs: steps: - uses: actions/checkout@v3 - - name: Download Worker Image + - name: Download Teeracle Image uses: actions/download-artifact@v3 with: name: integritee-worker-teeracle-${{ github.ref_name }}.tar.gz path: . - - name: Download Worker Image + - name: Download Sidechain Image uses: actions/download-artifact@v3 with: name: integritee-worker-sidechain-${{ github.ref_name }}.tar.gz path: . + - name: Download Sidechain Cli Image + uses: actions/download-artifact@v3 + with: + name: sidechain-cli-${{ github.ref_name }}.tar.gz + path: . + + - name: Download Teeracle Cli Image + uses: actions/download-artifact@v3 + with: + name: teeracle-cli-${{ github.ref_name }}.tar.gz + path: . + # # Temporary comment out until we decide what to release # @@ -535,6 +638,8 @@ jobs: files: | integritee-worker-teeracle-${{ github.ref_name }}.tar.gz integritee-worker-sidechain-${{ github.ref_name }}.tar.gz + sidechain-cli-${{ github.ref_name }}.tar.gz + teeracle-cli-${{ github.ref_name }}.tar.gz integritee-client integritee-demo-validateer - enclave.signed.so + enclave.signed.so \ No newline at end of file diff --git a/.github/workflows/publish-docker-release.yml b/.github/workflows/publish-docker-release.yml index b46d16170e..e23ffa7e29 100644 --- a/.github/workflows/publish-docker-release.yml +++ b/.github/workflows/publish-docker-release.yml @@ -1,10 +1,14 @@ name: Publish Docker image for new releases -# Disable docker release for now. Check with oli systems if they want to do that. +# Just disable it temporary +# on: +# release: +# types: +# - published on: - release: - types: - - published + push: + branches: + - 'releases/**' jobs: main: diff --git a/.github/workflows/publish-docker-sidechain.yml b/.github/workflows/publish-docker-sidechain.yml index c424bdbd89..037e01dccf 100644 --- a/.github/workflows/publish-docker-sidechain.yml +++ b/.github/workflows/publish-docker-sidechain.yml @@ -19,7 +19,14 @@ jobs: file: integritee-worker-sidechain-${{ github.event.release.tag_name }}.tar.gz target: "integritee-worker-sidechain.tar.gz" token: ${{ secrets.GITHUB_TOKEN }} - + + - name: Download sidechain cli from release + uses: dsaltares/fetch-gh-release-asset@master + with: + version: "tags/${{ github.event.release.tag_name }}" + file: sidechain-cli-${{ github.event.release.tag_name }}.tar.gz + target: "sidechain-cli.tar.gz" + token: ${{ secrets.GITHUB_TOKEN }} - name: Login to Dockerhub uses: docker/login-action@v1 @@ -32,12 +39,17 @@ jobs: DOCKER_BUILDKIT: 1 run: | docker image load --input integritee-worker-sidechain.tar.gz - docker images --all docker push integritee/sidechain:${{ github.event.release.tag_name }} - + docker image load --input sidechain-cli.tar.gz + docker push integritee/sidechain-cli:${{ github.event.release.tag_name }} + docker images --all + - name: Delete images run: | if [[ "$(docker images -q integritee/sidechain:${{ github.event.release.tag_name }} 2> /dev/null)" != "" ]]; then docker image rmi --force integritee/sidechain:${{ github.event.release.tag_name }} 2>/dev/null fi + if [[ "$(docker images -q integritee/sidechain-cli:${{ github.event.release.tag_name }} 2> /dev/null)" != "" ]]; then + docker image rmi --force integritee/sidechain-cli:${{ github.event.release.tag_name }} 2>/dev/null + fi docker images --all diff --git a/.github/workflows/publish-docker-teeracle.yml b/.github/workflows/publish-docker-teeracle.yml index 01a9a6f8b0..751831b834 100644 --- a/.github/workflows/publish-docker-teeracle.yml +++ b/.github/workflows/publish-docker-teeracle.yml @@ -19,7 +19,15 @@ jobs: file: integritee-worker-teeracle-${{ github.event.release.tag_name }}.tar.gz target: "integritee-worker-teeracle.tar.gz" token: ${{ secrets.GITHUB_TOKEN }} - + + - name: Download teeracle cli from release + uses: dsaltares/fetch-gh-release-asset@master + with: + version: "tags/${{ github.event.release.tag_name }}" + file: teeracle-cli-${{ github.event.release.tag_name }}.tar.gz + target: "teeracle-cli.tar.gz" + token: ${{ secrets.GITHUB_TOKEN }} + - name: Login to Dockerhub uses: docker/login-action@v1 @@ -32,12 +40,17 @@ jobs: DOCKER_BUILDKIT: 1 run: | docker image load --input integritee-worker-teeracle.tar.gz - docker images --all docker push integritee/teeracle:${{ github.event.release.tag_name }} - + docker image load --input teeracle-cli.tar.gz + docker push integritee/teeracle-cli:${{ github.event.release.tag_name }} + docker images --all + - name: Delete images run: | if [[ "$(docker images -q integritee/teeracle:${{ github.event.release.tag_name }} 2> /dev/null)" != "" ]]; then docker image rmi --force integritee/teeracle:${{ github.event.release.tag_name }} 2>/dev/null fi + if [[ "$(docker images -q integritee/teeracle-cli:${{ github.event.release.tag_name }} 2> /dev/null)" != "" ]]; then + docker image rmi --force integritee/teeracle-cli:${{ github.event.release.tag_name }} 2>/dev/null + fi docker images --all diff --git a/Cargo.lock b/Cargo.lock index c2fc2d9241..044baa4ba5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -18,7 +18,7 @@ version = "0.4.2" source = "git+https://github.com/scs/substrate-api-client.git?branch=polkadot-v0.9.42-tag-v0.14.0#e4ed74b0fb6c2fd5585f55c2702b97b56d99c7f6" dependencies = [ "ac-primitives", - "log 0.4.19", + "log 0.4.20", "maybe-async", ] @@ -33,14 +33,14 @@ dependencies = [ "either", "frame-metadata", "hex", - "log 0.4.19", + "log 0.4.20", "parity-scale-codec", "scale-bits", "scale-decode", "scale-encode", "scale-info", - "serde 1.0.188", - "serde_json 1.0.106", + "serde 1.0.193", + "serde_json 1.0.103", "sp-application-crypto", "sp-core", "sp-runtime", @@ -59,8 +59,8 @@ dependencies = [ "parity-scale-codec", "primitive-types", "scale-info", - "serde 1.0.188", - "serde_json 1.0.106", + "serde 1.0.193", + "serde_json 1.0.103", "sp-application-crypto", "sp-core", "sp-core-hashing", @@ -82,11 +82,11 @@ dependencies = [ [[package]] name = "addr2line" -version = "0.19.0" +version = "0.20.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a76fd60b23679b7d19bd066031410fb7e458ccc5e958eb5c325888ce4baedc97" +checksum = "f4fa78e18c64fce05e902adecd7a5eed15a5e0a3439f7b0e169f0252214865e3" dependencies = [ - "gimli 0.27.2", + "gimli 0.27.3", ] [[package]] @@ -149,15 +149,6 @@ dependencies = [ "version_check", ] -[[package]] -name = "aho-corasick" -version = "0.7.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc936419f96fa211c1b9166887b38e5e40b19958e5b895be7c1f93adec7071ac" -dependencies = [ - "memchr 2.6.3", -] - [[package]] name = "aho-corasick" version = "1.0.2" @@ -193,9 +184,9 @@ dependencies = [ [[package]] name = "anyhow" -version = "1.0.71" +version = "1.0.72" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c7d0618f0e0b7e8ff11427422b64564d5fb0be1940354bfe2e0529b18a9d9b8" +checksum = "3b13c32d80ecc7ab747b80c3784bce54ee8a7a0cc4fbda9bf4cda2cf6fe90854" [[package]] name = "approx" @@ -203,7 +194,7 @@ version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cab112f0a86d568ea0e627cc1d6be74a1e9cd55214684db5561995f6dad897c6" dependencies = [ - "num-traits 0.2.15", + "num-traits 0.2.16", ] [[package]] @@ -224,15 +215,6 @@ version = "0.3.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6b4930d2cb77ce62f89ee5d5289b4ac049559b1c45539271f5ed4fdc7db34545" -[[package]] -name = "arrayvec" -version = "0.4.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd9fd44efafa8690358b7408d253adf110036b88f55672a933f01d616ad9b1b9" -dependencies = [ - "nodrop", -] - [[package]] name = "arrayvec" version = "0.5.2" @@ -241,15 +223,15 @@ checksum = "23b62fc65de8e4e7f52534fb52b0f3ed04746ae267519eef2a83941e8085068b" [[package]] name = "arrayvec" -version = "0.7.3" +version = "0.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8868f09ff8cea88b079da74ae569d9b8c62a23c68c746240b704ee6f7525c89c" +checksum = "96d30a06541fbafbc7f82ed10c06164cfbd2c401138f6addd8404629c4b16711" [[package]] name = "async-trait" -version = "0.1.68" +version = "0.1.72" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9ccdd8f2a161be9bd5c023df56f1b2a0bd1d83872ae53b71a84a12c9bf6e842" +checksum = "cc6dde6e4ed435a4c1ee4e73592f5ba9da2151af10076cc04858746af9352d09" dependencies = [ "proc-macro2", "quote", @@ -296,16 +278,16 @@ checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" [[package]] name = "backtrace" -version = "0.3.67" +version = "0.3.68" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "233d376d6d185f2a3093e58f283f60f880315b6c60075b01f36b3b85154564ca" +checksum = "4319208da049c43661739c5fade2ba182f09d1dc2299b32298d3a31692b17e12" dependencies = [ - "addr2line 0.19.0", + "addr2line 0.20.0", "cc", "cfg-if 1.0.0", "libc", - "miniz_oxide 0.6.2", - "object 0.30.4", + "miniz_oxide", + "object 0.31.1", "rustc-demangle", ] @@ -353,9 +335,9 @@ checksum = "9e1b586273c5702936fe7b7d6896644d8be71e6314cfe09d3167c95f712589e8" [[package]] name = "base64" -version = "0.21.2" +version = "0.21.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "604178f6c5c21f02dc555784810edfb88d34ac2c73b2eae109655649ee73ce3d" +checksum = "35636a1494ede3b646cc98f74f8e62c773a38a659ebc777a2cf26b9b74171df9" [[package]] name = "base64ct" @@ -369,16 +351,16 @@ version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3a8241f3ebb85c056b509d4327ad0358fbbba6ffb340bf388f26350aeda225b1" dependencies = [ - "serde 1.0.188", + "serde 1.0.193", ] [[package]] name = "binary-merkle-tree" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#569aae5341ea0c1d10426fa1ec13a36c0b64393b" +source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "hash-db 0.16.0", - "log 0.4.19", + "log 0.4.20", ] [[package]] @@ -395,7 +377,7 @@ version = "1.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b1f45e9417d87227c7a56d22e471c6206462cba514c7590c09aff4cf6d1ddcad" dependencies = [ - "serde 1.0.188", + "serde 1.0.193", ] [[package]] @@ -404,7 +386,7 @@ version = "0.64.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c4243e6031260db77ede97ad86c27e501d646a27ab57b59a574f725d98ab1fb4" dependencies = [ - "bitflags", + "bitflags 1.3.2", "cexpr", "clang-sys", "lazy_static", @@ -430,6 +412,12 @@ version = "1.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" +[[package]] +name = "bitflags" +version = "2.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "630be753d4e58660abd17930c71b647fe46c27ea6b63cc59e1e3851406972e42" + [[package]] name = "bitvec" version = "1.0.1" @@ -451,16 +439,6 @@ dependencies = [ "digest 0.10.7", ] -[[package]] -name = "blake2-rfc" -version = "0.2.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d6d530bdd2d52966a6d03b7a964add7ae1a288d25214066fd4b600f0f796400" -dependencies = [ - "arrayvec 0.4.12", - "constant_time_eq 0.1.5", -] - [[package]] name = "blake2b_simd" version = "1.0.1" @@ -468,18 +446,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3c2f0dc9a68c6317d884f97cc36cf5a3d20ba14ce404227df55e1af708ab04bc" dependencies = [ "arrayref", - "arrayvec 0.7.3", - "constant_time_eq 0.2.6", -] - -[[package]] -name = "block-buffer" -version = "0.3.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a076c298b9ecdb530ed9d967e74a6027d6a7478924520acddcddc24c1c8ab3ab" -dependencies = [ - "arrayref", - "byte-tools 0.2.0", + "arrayvec 0.7.4", + "constant_time_eq", ] [[package]] @@ -489,7 +457,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c0940dc441f31689269e10ac70eb1002a3a1d3ad1390e030043662eb7fe4688b" dependencies = [ "block-padding", - "byte-tools 0.3.1", + "byte-tools", "byteorder 1.4.3", "generic-array 0.12.4", ] @@ -518,7 +486,7 @@ version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fa79dedbb091f449f1f39e53edf88d5dbe95f895dae6135a8d7b881fb5af73f5" dependencies = [ - "byte-tools 0.3.1", + "byte-tools", ] [[package]] @@ -527,10 +495,10 @@ version = "0.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "eb5b05133427c07c4776906f673ccf36c21b102c9829c641a5b56bd151d44fd6" dependencies = [ - "log 0.4.19", + "log 0.4.20", "parity-scale-codec", "scale-info", - "serde 1.0.188", + "serde 1.0.193", ] [[package]] @@ -541,21 +509,12 @@ checksum = "771fe0050b883fcc3ea2359b1a96bcfbc090b7116eae7c3c512c7a083fdf23d3" [[package]] name = "bstr" -version = "1.5.0" +version = "1.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a246e68bb43f6cd9db24bea052a53e40405417c5fb372e3d1a8a7f770a564ef5" +checksum = "6798148dccfbff0fae41c7574d2fa8f1ef3492fba0face179de5d8d447d67b05" dependencies = [ "memchr 2.6.3", - "serde 1.0.188", -] - -[[package]] -name = "build-helper" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bdce191bf3fa4995ce948c8c83b4640a1745457a149e73c6db75b4ffe36aad5f" -dependencies = [ - "semver 0.6.0", + "serde 1.0.193", ] [[package]] @@ -570,12 +529,6 @@ version = "1.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c3ac9f8b63eca6fd385229b3675f6cc0dc5c8a5c8a54a59d4f52ffd670d87b0c" -[[package]] -name = "byte-tools" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "560c32574a12a89ecd91f5e742165893f86e3ab98d21f8ea548658eb9eef5f40" - [[package]] name = "byte-tools" version = "0.3.1" @@ -637,38 +590,6 @@ dependencies = [ "pkg-config", ] -[[package]] -name = "camino" -version = "1.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c530edf18f37068ac2d977409ed5cd50d53d73bc653c7647b48eb78976ac9ae2" -dependencies = [ - "serde 1.0.188", -] - -[[package]] -name = "cargo-platform" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cbdb825da8a5df079a43676dbe042702f1707b1109f713a01420fbb4cc71fa27" -dependencies = [ - "serde 1.0.188", -] - -[[package]] -name = "cargo_metadata" -version = "0.15.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eee4243f1f26fc7a42710e7439c149e2b10b05472f88090acce52632f231a73a" -dependencies = [ - "camino", - "cargo-platform", - "semver 1.0.17", - "serde 1.0.188", - "serde_json 1.0.106", - "thiserror 1.0.40", -] - [[package]] name = "cc" version = "1.0.79" @@ -693,7 +614,7 @@ version = "0.10.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0aacacf4d96c24b2ad6eb8ee6df040e4f27b0d0b39a5710c30091baa830485db" dependencies = [ - "smallvec 1.10.0", + "smallvec 1.11.0", ] [[package]] @@ -727,8 +648,8 @@ dependencies = [ "android-tzdata", "iana-time-zone", "js-sys", - "num-traits 0.2.15", - "serde 1.0.188", + "num-traits 0.2.16", + "serde 1.0.193", "time", "wasm-bindgen", "winapi 0.3.9", @@ -743,20 +664,6 @@ dependencies = [ "generic-array 0.14.7", ] -[[package]] -name = "claims-primitives" -version = "0.1.0" -source = "git+https://github.com/integritee-network/pallets.git?branch=sdk-v0.12.0-polkadot-v0.9.42#eaf611b79bc9d56b20c155150e99b549bf98436b" -dependencies = [ - "parity-scale-codec", - "rustc-hex", - "scale-info", - "serde 1.0.188", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", - "sp-runtime", - "sp-std", -] - [[package]] name = "clang-sys" version = "1.6.1" @@ -776,7 +683,7 @@ checksum = "a0610544180c38b88101fecf2dd634b174a62eef6946f84dfc6a7127512b381c" dependencies = [ "ansi_term", "atty", - "bitflags", + "bitflags 1.3.2", "strsim 0.8.0", "textwrap 0.11.0", "unicode-width", @@ -791,7 +698,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4ea181bf566f71cb9a5d17a59e1871af638180a18fb0035c92ae62b705207123" dependencies = [ "atty", - "bitflags", + "bitflags 1.3.2", "clap_derive", "clap_lex", "indexmap 1.9.3", @@ -823,16 +730,6 @@ dependencies = [ "os_str_bytes", ] -[[package]] -name = "codespan-reporting" -version = "0.11.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3538270d33cc669650c4b093848450d380def10c331d38c768e34cac80576e6e" -dependencies = [ - "termcolor", - "unicode-width", -] - [[package]] name = "common-multipart-rfc7578" version = "0.3.1" @@ -845,13 +742,13 @@ dependencies = [ "mime", "mime_guess", "rand 0.8.5", - "thiserror 1.0.40", + "thiserror 1.0.44", ] [[package]] name = "common-primitives" version = "0.1.0" -source = "git+https://github.com/integritee-network/pallets.git?branch=sdk-v0.12.0-polkadot-v0.9.42#eaf611b79bc9d56b20c155150e99b549bf98436b" +source = "git+https://github.com/integritee-network/pallets.git?branch=sdk-v0.12.11-polkadot-v0.9.42#094b1e982b4637ebfbf5afb985100417215d49a0" dependencies = [ "derive_more", "parity-scale-codec", @@ -863,15 +760,9 @@ dependencies = [ [[package]] name = "const-oid" -version = "0.9.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "520fbf3c07483f94e3e3ca9d0cfd913d7718ef2483d2cfd91c0d9e91474ab913" - -[[package]] -name = "constant_time_eq" -version = "0.1.5" +version = "0.9.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "245097e9a4535ee1e3e3931fcfcd55a796a44c643e8596ff6566d68f09b87bbc" +checksum = "795bc6e66a8e340f075fcf6227e417a2dc976b92b91f3cdc778bb858778b6747" [[package]] name = "constant_time_eq" @@ -912,9 +803,9 @@ dependencies = [ [[package]] name = "cpufeatures" -version = "0.2.7" +version = "0.2.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e4c1eaa2012c47becbbad2ab175484c2a84d1185b566fb2cc5b8707343dfe58" +checksum = "a17b76ff3a4162b0b27f354a0c87015ddad39d35f9c0c36607a3bdd175dde1f1" dependencies = [ "libc", ] @@ -925,7 +816,7 @@ version = "0.93.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f42ea692c7b450ad18b8c9889661505d51c09ec4380cf1c2d278dbb2da22cae1" dependencies = [ - "serde 1.0.188", + "serde 1.0.193", ] [[package]] @@ -988,9 +879,9 @@ checksum = "7a81dae078cea95a014a339291cec439d2f232ebe854a9d672b796c6afafa9b7" [[package]] name = "crypto-bigint" -version = "0.5.2" +version = "0.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf4c2f4e1afd912bc40bfd6fed5d9dc1f288e0ba01bfcc835cc5bc3eb13efe15" +checksum = "740fe28e594155f10cfc383984cbefd529d7396050557148f79cb0f621204124" dependencies = [ "generic-array 0.14.7", "rand_core 0.6.4", @@ -1063,50 +954,6 @@ dependencies = [ "zeroize", ] -[[package]] -name = "cxx" -version = "1.0.95" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "109308c20e8445959c2792e81871054c6a17e6976489a93d2769641a2ba5839c" -dependencies = [ - "cc", - "cxxbridge-flags", - "cxxbridge-macro", - "link-cplusplus", -] - -[[package]] -name = "cxx-build" -version = "1.0.95" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "daf4c6755cdf10798b97510e0e2b3edb9573032bd9379de8fffa59d68165494f" -dependencies = [ - "cc", - "codespan-reporting", - "once_cell 1.18.0", - "proc-macro2", - "quote", - "scratch", - "syn 2.0.32", -] - -[[package]] -name = "cxxbridge-flags" -version = "1.0.95" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "882074421238e84fe3b4c65d0081de34e5b323bf64555d3e61991f76eb64a7bb" - -[[package]] -name = "cxxbridge-macro" -version = "1.0.95" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4a076022ece33e7686fb76513518e219cca4fce5750a8ae6d1ce6c0f48fd1af9" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.32", -] - [[package]] name = "darling" version = "0.14.4" @@ -1161,9 +1008,9 @@ dependencies = [ [[package]] name = "der" -version = "0.7.6" +version = "0.7.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "56acb310e15652100da43d130af8d97b509e95af61aab1c5a7939ef24337ee17" +checksum = "fffa369a668c8af7dbf8b5e56c9f744fbd399949ed171606040001947de40b1c" dependencies = [ "const-oid", "zeroize", @@ -1211,15 +1058,6 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6184e33543162437515c2e2b48714794e37845ec9851711914eec9d308f6ebe8" -[[package]] -name = "digest" -version = "0.7.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "03b072242a8cbaf9c145665af9d250c59af3b958f83ed6824e13533cf76d5b90" -dependencies = [ - "generic-array 0.9.1", -] - [[package]] name = "digest" version = "0.8.1" @@ -1305,17 +1143,17 @@ dependencies = [ [[package]] name = "dyn-clone" -version = "1.0.11" +version = "1.0.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "68b0cf012f1230e43cd00ebb729c6bb58707ecfa8ad08b52ef3a4ccd2697fc30" +checksum = "304e6508efa593091e97a9abbc10f90aa7ca635b6d2784feff3c89d41dd12272" [[package]] name = "ecdsa" -version = "0.16.7" +version = "0.16.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0997c976637b606099b9985693efa3581e84e41f5c11ba5255f88711058ad428" +checksum = "a4b1e0c257a9e9f25f90ff76d7a68360ed497ee519c8e428d1825ef0000799d4" dependencies = [ - "der 0.7.6", + "der 0.7.8", "digest 0.10.7", "elliptic-curve", "rfc6979", @@ -1360,9 +1198,9 @@ dependencies = [ [[package]] name = "either" -version = "1.8.1" +version = "1.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7fcaabb2fef8c910e7f4c7ce9f67a1283a1715879a7c230ca9d6d1ae31f16d91" +checksum = "a26ae43d7bcc3b814de94796a5e736d4029efb0ee900c12e2d54c993ad1a1e07" [[package]] name = "elliptic-curve" @@ -1386,13 +1224,13 @@ dependencies = [ [[package]] name = "enclave-bridge-primitives" version = "0.1.0" -source = "git+https://github.com/integritee-network/pallets.git?branch=sdk-v0.12.0-polkadot-v0.9.42#eaf611b79bc9d56b20c155150e99b549bf98436b" +source = "git+https://github.com/integritee-network/pallets.git?branch=sdk-v0.12.11-polkadot-v0.9.42#094b1e982b4637ebfbf5afb985100417215d49a0" dependencies = [ "common-primitives", - "log 0.4.19", + "log 0.4.20", "parity-scale-codec", "scale-info", - "serde 1.0.188", + "serde 1.0.193", "sp-core", "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", "sp-runtime", @@ -1416,7 +1254,20 @@ checksum = "a12e6657c4c97ebab115a42dcee77225f7f482cdd841cf7088c657a42e9e00e7" dependencies = [ "atty", "humantime", - "log 0.4.19", + "log 0.4.20", + "regex 1.9.5", + "termcolor", +] + +[[package]] +name = "env_logger" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85cdab6a89accf66733ad5a1693a4dcced6aeff64602b634530dd73c1f3ee9f0" +dependencies = [ + "humantime", + "is-terminal", + "log 0.4.20", "regex 1.9.5", "termcolor", ] @@ -1489,7 +1340,7 @@ dependencies = [ "parity-scale-codec", "rlp", "scale-info", - "serde 1.0.188", + "serde 1.0.193", "sha3", "triehash", ] @@ -1522,12 +1373,12 @@ dependencies = [ "evm-core", "evm-gasometer", "evm-runtime", - "log 0.4.19", + "log 0.4.20", "parity-scale-codec", "primitive-types", "rlp", "scale-info", - "serde 1.0.188", + "serde 1.0.193", "sha3", ] @@ -1540,7 +1391,7 @@ dependencies = [ "parity-scale-codec", "primitive-types", "scale-info", - "serde 1.0.188", + "serde 1.0.193", ] [[package]] @@ -1617,12 +1468,9 @@ checksum = "4443176a9f2c162692bd3d352d745ef9413eec5782a80d8fd6f8a1ac692a07f7" [[package]] name = "fastrand" -version = "1.9.0" +version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e51093e27b0797c359783294ca4f0a911c270184cb10f85783b118614a1501be" -dependencies = [ - "instant", -] +checksum = "6999dc1837253364c2ebb0704ba97994bd874e8f195d665c50b7548f6ea92764" [[package]] name = "ff" @@ -1634,18 +1482,6 @@ dependencies = [ "subtle", ] -[[package]] -name = "filetime" -version = "0.2.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5cbc844cecaee9d4443931972e1289c8ff485cb4cc2767cb03ca139ed6885153" -dependencies = [ - "cfg-if 1.0.0", - "libc", - "redox_syscall 0.2.16", - "windows-sys 0.48.0", -] - [[package]] name = "finality-grandpa" version = "0.16.2" @@ -1655,8 +1491,8 @@ dependencies = [ "either", "futures 0.3.28", "futures-timer", - "log 0.4.19", - "num-traits 0.2.15", + "log 0.4.20", + "num-traits 0.2.16", "parity-scale-codec", "parking_lot 0.12.1", "scale-info", @@ -1687,7 +1523,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3b9429470923de8e8cbd4d2dc513535400b4b3fef0319fb5c4e1f520a7bef743" dependencies = [ "crc32fast", - "miniz_oxide 0.7.1", + "miniz_oxide", ] [[package]] @@ -1696,7 +1532,7 @@ version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "98de4bbd547a563b716d8dfa9aad1cb19bfab00f4fa09a6a4ed21dbcf44ce9c4" dependencies = [ - "num-traits 0.2.15", + "num-traits 0.2.16", ] [[package]] @@ -1738,11 +1574,11 @@ dependencies = [ [[package]] name = "form_urlencoded" -version = "1.2.0" +version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a62bc1cf6f830c2ec14a513a9fb124d0a213a629668a4186f329db21fe045652" +checksum = "e13624c2627564efccf4934284bdd98cbaa14e79b0b5a141218e507b3a823456" dependencies = [ - "percent-encoding 2.3.0", + "percent-encoding 2.3.1", ] [[package]] @@ -1753,10 +1589,10 @@ dependencies = [ "hex", "impl-serde", "libsecp256k1", - "log 0.4.19", + "log 0.4.20", "parity-scale-codec", "scale-info", - "serde 1.0.188", + "serde 1.0.193", "sp-core", "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", "sp-runtime", @@ -1772,7 +1608,7 @@ dependencies = [ "frame-support", "parity-scale-codec", "scale-info", - "serde 1.0.188", + "serde 1.0.193", "sp-core", "sp-runtime", "sp-std", @@ -1793,11 +1629,11 @@ dependencies = [ "frame-support-procedural", "frame-system", "linregress", - "log 0.4.19", + "log 0.4.20", "parity-scale-codec", "paste", "scale-info", - "serde 1.0.188", + "serde 1.0.193", "sp-api", "sp-application-crypto", "sp-core", @@ -1834,7 +1670,7 @@ dependencies = [ "cfg-if 1.0.0", "parity-scale-codec", "scale-info", - "serde 1.0.188", + "serde 1.0.193", ] [[package]] @@ -1842,19 +1678,19 @@ name = "frame-support" version = "4.0.0-dev" source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ - "bitflags", + "bitflags 1.3.2", "environmental 1.1.4", "frame-metadata", "frame-support-procedural", "impl-trait-for-tuples", "k256", - "log 0.4.19", + "log 0.4.20", "once_cell 1.18.0", "parity-scale-codec", "paste", "scale-info", - "serde 1.0.188", - "smallvec 1.10.0", + "serde 1.0.193", + "smallvec 1.11.0", "sp-api", "sp-arithmetic", "sp-core", @@ -1879,7 +1715,7 @@ dependencies = [ "cfg-expr", "derive-syn-parse", "frame-support-procedural-tools", - "itertools", + "itertools 0.10.5", "proc-macro-warning", "proc-macro2", "quote", @@ -1914,10 +1750,10 @@ version = "4.0.0-dev" source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "frame-support", - "log 0.4.19", + "log 0.4.20", "parity-scale-codec", "scale-info", - "serde 1.0.188", + "serde 1.0.193", "sp-core", "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", "sp-runtime", @@ -1929,7 +1765,7 @@ dependencies = [ [[package]] name = "frame-system-benchmarking" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#569aae5341ea0c1d10426fa1ec13a36c0b64393b" +source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "frame-benchmarking", "frame-support", @@ -1962,7 +1798,7 @@ version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2e9763c69ebaae630ba35f74888db465e49e259ba1bc0eda7d06f4a067615d82" dependencies = [ - "bitflags", + "bitflags 1.3.2", "fuchsia-zircon-sys", ] @@ -2171,15 +2007,6 @@ dependencies = [ "slab 0.4.8", ] -[[package]] -name = "generic-array" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6d00328cedcac5e81c683e5620ca6a30756fc23027ebf9bff405c0e8da1fbb7e" -dependencies = [ - "typenum 1.16.0 (registry+https://github.com/rust-lang/crates.io-index)", -] - [[package]] name = "generic-array" version = "0.12.4" @@ -2245,9 +2072,9 @@ dependencies = [ [[package]] name = "gimli" -version = "0.27.2" +version = "0.27.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ad0a93d233ebf96623465aad4046a8d3aa4da22d4f4beba5388838c8a434bbb4" +checksum = "b6c80984affa11d98d1b88b66ac8853f143217b399d3c74116778ff8fdb4ed2e" [[package]] name = "glob" @@ -2257,14 +2084,14 @@ checksum = "d2fabcfbdc87f4758337ca535fb41a6d701b65693ce38287d856d1674551ec9b" [[package]] name = "globset" -version = "0.4.10" +version = "0.4.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "029d74589adefde59de1a0c4f4732695c32805624aec7b68d91503d4dba79afc" +checksum = "1391ab1f92ffcc08911957149833e682aa3fe252b9f45f966d2ef972274c97df" dependencies = [ - "aho-corasick 0.7.20", + "aho-corasick", "bstr", "fnv 1.0.7", - "log 0.4.19", + "log 0.4.20", "regex 1.9.5", ] @@ -2281,9 +2108,9 @@ dependencies = [ [[package]] name = "h2" -version = "0.3.19" +version = "0.3.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d357c7ae988e7d2182f7d7871d0b963962420b0678b0997ce7de72001aeab782" +checksum = "97ec8491ebaf99c8eaa73058b045fe58073cd6be7f596ac993ced0b0a0c01049" dependencies = [ "bytes 1.4.0", "fnv 1.0.7", @@ -2358,7 +2185,7 @@ checksum = "2c6201b9ff9fd90a5a3bac2e56a830d0caa509576f0e503818ee82c181b3437a" [[package]] name = "hashbrown_tstd" version = "0.12.0" -source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#f1776a7cec1caab2959813f87bb4924805b92011" +source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#3c903bdac4e503dd27b9b1f761c4abfc55f2464c" [[package]] name = "hdrhistogram" @@ -2371,7 +2198,7 @@ dependencies = [ "crossbeam-channel", "flate2", "nom", - "num-traits 0.2.15", + "num-traits 0.2.16", ] [[package]] @@ -2381,7 +2208,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f3e372db8e5c0d213e0cd0b9be18be2aca3d44cf2fe30a9d46a65581cd454584" dependencies = [ "base64 0.13.1", - "bitflags", + "bitflags 1.3.2", "bytes 1.4.0", "headers-core", "http 0.2.9", @@ -2416,18 +2243,9 @@ dependencies = [ [[package]] name = "hermit-abi" -version = "0.2.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ee512640fe35acbfb4bb779db6f0d80704c2cacfa2e39b601ef3e3f47d1ae4c7" -dependencies = [ - "libc", -] - -[[package]] -name = "hermit-abi" -version = "0.3.1" +version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fed44880c466736ef9a5c5b5facefb5ed0785676d0c02d612db14e54f0d84286" +checksum = "443144c8cdadd93ebf52ddb4056d257f5b52c04d3c804e657d19eb73fc33668b" [[package]] name = "hex" @@ -2500,7 +2318,7 @@ checksum = "bd6effc99afb63425aff9b05836f029929e345a6148a14b7ecd5ab67af944482" dependencies = [ "bytes 1.4.0", "fnv 1.0.7", - "itoa 1.0.6", + "itoa 1.0.9", ] [[package]] @@ -2519,7 +2337,7 @@ name = "http_req" version = "0.8.1" source = "git+https://github.com/integritee-network/http_req?branch=master#3723e88235f2b29bc1a31835853b072ffd0455fd" dependencies = [ - "log 0.4.19", + "log 0.4.20", "rustls 0.19.1", "unicase 2.6.0 (registry+https://github.com/rust-lang/crates.io-index)", "webpki 0.21.4 (registry+https://github.com/rust-lang/crates.io-index)", @@ -2531,7 +2349,7 @@ name = "http_req" version = "0.8.1" source = "git+https://github.com/integritee-network/http_req#3723e88235f2b29bc1a31835853b072ffd0455fd" dependencies = [ - "log 0.4.19", + "log 0.4.20", "rustls 0.19.0 (git+https://github.com/mesalock-linux/rustls?branch=mesalock_sgx)", "sgx_tstd", "unicase 2.6.0 (git+https://github.com/mesalock-linux/unicase-sgx)", @@ -2567,9 +2385,9 @@ checksum = "9a3a5bfb195931eeb336b2a7b4d761daec841b97f947d34394601737a7bba5e4" [[package]] name = "hyper" -version = "0.14.26" +version = "0.14.27" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ab302d72a6f11a3b910431ff93aae7e773078c769f0a3ef15fb9ec692ed147d4" +checksum = "ffb1cfd654a8219eaef89881fdb3bb3b1cdc5fa75ded05d6933b2b382e395468" dependencies = [ "bytes 1.4.0", "futures-channel 0.3.28", @@ -2580,7 +2398,7 @@ dependencies = [ "http-body", "httparse 1.8.0", "httpdate", - "itoa 1.0.6", + "itoa 1.0.9", "pin-project-lite", "socket2", "tokio", @@ -2611,7 +2429,7 @@ dependencies = [ "ct-logs", "futures-util 0.3.28", "hyper", - "log 0.4.19", + "log 0.4.20", "rustls 0.19.1", "rustls-native-certs", "tokio", @@ -2674,9 +2492,9 @@ dependencies = [ [[package]] name = "idna" -version = "0.4.0" +version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7d20d6b07bfbc108882d88ed8e37d39636dcc260e15e30c45e6ba089610b917c" +checksum = "634d9b1461af396cad843f47fdba5597a4f9e6ddd4bfb6ff5d85028c25cb12f6" dependencies = [ "unicode-bidi 0.3.13", "unicode-normalization 0.1.22", @@ -2706,7 +2524,7 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ebc88fc67028ae3db0c853baa36269d398d5f45b6982f95549ff5def78c935cd" dependencies = [ - "serde 1.0.188", + "serde 1.0.193", ] [[package]] @@ -2738,7 +2556,7 @@ checksum = "bd070e393353796e801d209ad339e89596eb4c8d430d18ede6a1cced8fafbd99" dependencies = [ "autocfg 1.1.0", "hashbrown 0.12.3", - "serde 1.0.188", + "serde 1.0.193", ] [[package]] @@ -2766,25 +2584,23 @@ version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "276ec31bcb4a9ee45f58bec6f9ec700ae4cf4f4f8f2fa7e06cb406bd5ffdd770" dependencies = [ - "num-traits 0.2.15", + "num-traits 0.2.16", ] [[package]] name = "integritee-cli" -version = "0.12.0" +version = "0.12.11" dependencies = [ "array-bytes 6.1.0", "base58", "binary-merkle-tree 4.0.0-dev (git+https://github.com/paritytech/substrate.git)", - "blake2-rfc", "chrono 0.4.26", "clap 3.2.25", "enclave-bridge-primitives", - "env_logger", - "frame-system", + "env_logger 0.9.3", "hdrhistogram", "hex", - "integritee-node-runtime", + "ita-parentchain-interface", "ita-stf", "itc-rpc-client", "itp-node-api", @@ -2794,10 +2610,12 @@ dependencies = [ "itp-time-utils", "itp-types", "itp-utils", - "log 0.4.19", + "log 0.4.20", "pallet-balances", "pallet-enclave-bridge", "pallet-evm", + "pallet-sidechain", + "pallet-teeracle", "pallet-teerex", "parity-scale-codec", "primitive-types", @@ -2805,72 +2623,26 @@ dependencies = [ "rayon", "regex 1.9.5", "reqwest", - "sc-keystore", - "serde 1.0.188", - "serde_json 1.0.106", + "serde 1.0.193", + "serde_json 1.0.103", "sgx_crypto_helper", "simplyr-lib", "sp-application-crypto", + "sp-consensus-aura", "sp-core", "sp-keyring", "sp-keystore", "sp-runtime", "substrate-api-client", "substrate-client-keystore", - "thiserror 1.0.40", + "teeracle-primitives", + "thiserror 1.0.44", "urlencoding", - "ws", -] - -[[package]] -name = "integritee-node-runtime" -version = "1.1.34" -source = "git+https://github.com/integritee-network/integritee-node.git?branch=sdk-v0.12.0-polkadot-v0.9.42#1fb7b051ca3b3ce63fcb1ae2f898aa067f8b3a1d" -dependencies = [ - "frame-executive", - "frame-support", - "frame-system", - "frame-system-rpc-runtime-api", - "pallet-aura", - "pallet-balances", - "pallet-claims", - "pallet-enclave-bridge", - "pallet-grandpa", - "pallet-insecure-randomness-collective-flip", - "pallet-multisig", - "pallet-preimage", - "pallet-proxy", - "pallet-scheduler", - "pallet-sidechain", - "pallet-sudo", - "pallet-teeracle", - "pallet-teerex", - "pallet-timestamp", - "pallet-transaction-payment", - "pallet-transaction-payment-rpc-runtime-api", - "pallet-treasury", - "pallet-utility", - "pallet-vesting", - "parity-scale-codec", - "scale-info", - "sp-api", - "sp-block-builder", - "sp-consensus-aura", - "sp-core", - "sp-inherents", - "sp-offchain", - "sp-runtime", - "sp-session", - "sp-staking", - "sp-std", - "sp-transaction-pool", - "sp-version", - "substrate-wasm-builder", ] [[package]] name = "integritee-service" -version = "0.12.0" +version = "0.12.11" dependencies = [ "anyhow", "async-trait", @@ -2878,13 +2650,13 @@ dependencies = [ "clap 2.34.0", "dirs", "enclave-bridge-primitives", - "env_logger", + "env_logger 0.9.3", "frame-support", - "frame-system", "futures 0.3.28", "hex", - "integritee-node-runtime", + "humantime", "ipfs-api", + "ita-parentchain-interface", "itc-parentchain", "itc-parentchain-test", "itc-rest-client", @@ -2895,7 +2667,9 @@ dependencies = [ "itp-enclave-metrics", "itp-node-api", "itp-settings", + "itp-stf-interface", "itp-storage", + "itp-time-utils", "itp-types", "itp-utils", "its-consensus-slots", @@ -2906,7 +2680,7 @@ dependencies = [ "its-test", "jsonrpsee", "lazy_static", - "log 0.4.19", + "log 0.4.20", "mockall", "pallet-balances", "parity-scale-codec", @@ -2914,22 +2688,24 @@ dependencies = [ "parse_duration", "primitive-types", "prometheus", + "regex 1.9.5", "scale-info", - "serde 1.0.188", - "serde_derive 1.0.188", - "serde_json 1.0.106", + "serde 1.0.193", + "serde_derive 1.0.193", + "serde_json 1.0.103", "sgx-verify", "sgx_crypto_helper", "sgx_types", - "sha2 0.7.1", + "sp-consensus-aura", "sp-consensus-grandpa", "sp-core", "sp-keyring", "sp-runtime", "substrate-api-client", "teerex-primitives", - "thiserror 1.0.40", + "thiserror 1.0.44", "tokio", + "url 2.5.0", "warp", ] @@ -2939,7 +2715,7 @@ version = "1.0.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "eae7b9aee968036d54dce06cebaefd919e4472e753296daccd6d344e3e2df0c2" dependencies = [ - "hermit-abi 0.3.1", + "hermit-abi 0.3.2", "libc", "windows-sys 0.48.0", ] @@ -2976,8 +2752,8 @@ dependencies = [ "hyper-multipart-rfc7578", "hyper-tls", "parity-multiaddr", - "serde 1.0.188", - "serde_json 1.0.106", + "serde 1.0.193", + "serde_json 1.0.103", "serde_urlencoded", "tokio", "tokio-util 0.6.10", @@ -2988,9 +2764,20 @@ dependencies = [ [[package]] name = "ipnet" -version = "2.8.0" +version = "2.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "28b29a3cd74f0f4598934efe3aeba42bae0eb4680554128851ebbecb02af14e6" +checksum = "12b6ee2129af8d4fb011108c73d99a1b83a85977f23b82460c0ae2e25bb4b57f" + +[[package]] +name = "is-terminal" +version = "0.4.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb0889898416213fab133e1d33a0e5858a48177452750691bde3666d0fdbaf8b" +dependencies = [ + "hermit-abi 0.3.2", + "rustix 0.38.4", + "windows-sys 0.48.0", +] [[package]] name = "ita-oracle" @@ -3000,16 +2787,44 @@ dependencies = [ "itp-enclave-metrics", "itp-ocall-api", "lazy_static", - "log 0.4.19", + "log 0.4.20", "parity-scale-codec", - "serde 1.0.188", - "serde_json 1.0.106", + "serde 1.0.193", "sgx_tstd", "substrate-fixed", - "thiserror 1.0.40", + "thiserror 1.0.44", "thiserror 1.0.9", "url 2.1.1", - "url 2.4.0", + "url 2.5.0", +] + +[[package]] +name = "ita-parentchain-interface" +version = "0.9.0" +dependencies = [ + "bs58", + "env_logger 0.9.3", + "ita-sgx-runtime", + "ita-stf", + "itc-parentchain", + "itc-parentchain-indirect-calls-executor", + "itc-parentchain-test", + "itp-api-client-types", + "itp-node-api", + "itp-sgx-crypto", + "itp-stf-executor", + "itp-stf-primitives", + "itp-test", + "itp-top-pool-author", + "itp-types", + "itp-utils", + "log 0.4.20", + "parity-scale-codec", + "regex 1.9.5", + "sgx_tstd", + "sp-core", + "sp-runtime", + "substrate-api-client", ] [[package]] @@ -3022,12 +2837,10 @@ dependencies = [ "frame-system", "frame-system-benchmarking", "frame-system-rpc-runtime-api", - "hex-literal", "itp-sgx-runtime-primitives", "pallet-aura", "pallet-balances", "pallet-evm", - "pallet-grandpa", "pallet-insecure-randomness-collective-flip", "pallet-parentchain", "pallet-sudo", @@ -3036,7 +2849,6 @@ dependencies = [ "pallet-transaction-payment-rpc-runtime-api", "parity-scale-codec", "scale-info", - "serde 1.0.188", "sp-api", "sp-block-builder", "sp-consensus-aura", @@ -3055,33 +2867,30 @@ name = "ita-stf" version = "0.9.0" dependencies = [ "binary-merkle-tree 4.0.0-dev (git+https://github.com/paritytech/substrate.git)", - "derive_more", "frame-support", "frame-system", - "integritee-node-runtime", "ita-sgx-runtime", "itp-hashing", "itp-node-api", "itp-node-api-metadata", - "itp-node-api-metadata-provider", "itp-sgx-externalities", + "itp-sgx-runtime-primitives", "itp-stf-interface", "itp-stf-primitives", "itp-storage", "itp-types", "itp-utils", - "log 0.4.19", + "log 0.4.20", "pallet-balances", "pallet-parentchain", "pallet-sudo", "parity-scale-codec", "rlp", - "serde 1.0.188", - "serde_json 1.0.106", + "serde 1.0.193", + "serde_json 1.0.103", "sgx_tstd", "sha3", "simplyr-lib", - "sp-application-crypto", "sp-core", "sp-io 7.0.0", "sp-keyring", @@ -3099,13 +2908,12 @@ dependencies = [ "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.19", + "log 0.4.20", "parity-scale-codec", - "serde_json 1.0.106", + "serde_json 1.0.103", "sgx_tstd", - "sgx_types", "sp-runtime", - "thiserror 1.0.40", + "thiserror 1.0.44", "thiserror 1.0.9", ] @@ -3123,14 +2931,12 @@ dependencies = [ "itp-test", "itp-top-pool-author", "itp-types", - "log 0.4.19", + "log 0.4.20", "parity-scale-codec", "sgx_tstd", - "sgx_types", - "sp-core", "sp-io 7.0.0", "sp-runtime", - "thiserror 1.0.40", + "thiserror 1.0.44", "thiserror 1.0.9", ] @@ -3154,11 +2960,10 @@ dependencies = [ "itc-parentchain-block-importer", "itp-import-queue", "itp-types", - "log 0.4.19", + "log 0.4.20", "sgx_tstd", "sgx_types", - "sp-runtime", - "thiserror 1.0.40", + "thiserror 1.0.44", "thiserror 1.0.9", ] @@ -3170,15 +2975,15 @@ dependencies = [ "itc-parentchain-indirect-calls-executor", "itc-parentchain-light-client", "itp-extrinsics-factory", - "itp-settings", "itp-stf-executor", + "itp-stf-interface", "itp-types", - "log 0.4.19", + "log 0.4.20", "parity-scale-codec", "sgx_tstd", "sgx_types", "sp-runtime", - "thiserror 1.0.40", + "thiserror 1.0.44", "thiserror 1.0.9", ] @@ -3188,14 +2993,12 @@ version = "0.9.0" dependencies = [ "binary-merkle-tree 4.0.0-dev (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", "bs58", - "env_logger", + "env_logger 0.9.3", "futures 0.3.28", "futures 0.3.8", - "ita-stf", "itc-parentchain-test", "itp-api-client-types", "itp-node-api", - "itp-ocall-api", "itp-sgx-crypto", "itp-sgx-runtime-primitives", "itp-stf-executor", @@ -3203,14 +3006,13 @@ dependencies = [ "itp-test", "itp-top-pool-author", "itp-types", - "itp-utils", - "log 0.4.19", + "log 0.4.20", "parity-scale-codec", "sgx_tstd", "sgx_types", "sp-core", "sp-runtime", - "thiserror 1.0.40", + "thiserror 1.0.44", "thiserror 1.0.9", ] @@ -3218,10 +3020,7 @@ dependencies = [ name = "itc-parentchain-light-client" version = "0.9.0" dependencies = [ - "derive_more", "finality-grandpa", - "frame-system", - "hash-db 0.15.2", "itc-parentchain-test", "itp-ocall-api", "itp-sgx-io", @@ -3229,18 +3028,13 @@ dependencies = [ "itp-storage", "itp-test", "itp-types", - "lazy_static", - "log 0.4.19", - "num-traits 0.2.15", + "log 0.4.20", "parity-scale-codec", "sgx_tstd", "sgx_types", - "sp-application-crypto", "sp-consensus-grandpa", - "sp-core", "sp-runtime", - "sp-trie", - "thiserror 1.0.40", + "thiserror 1.0.44", "thiserror 1.0.9", ] @@ -3248,17 +3042,8 @@ dependencies = [ name = "itc-parentchain-test" version = "0.9.0" dependencies = [ - "frame-support", - "frame-system", "itp-types", - "log 0.4.19", - "parity-scale-codec", - "scale-info", - "serde 1.0.188", - "sp-core", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", "sp-runtime", - "sp-std", ] [[package]] @@ -3270,22 +3055,21 @@ dependencies = [ "http 0.2.9", "http_req 0.8.1 (git+https://github.com/integritee-network/http_req?branch=master)", "http_req 0.8.1 (git+https://github.com/integritee-network/http_req)", - "log 0.4.19", - "serde 1.0.188", - "serde_json 1.0.106", + "log 0.4.20", + "serde 1.0.193", + "serde_json 1.0.103", "sgx_tstd", - "sgx_types", - "thiserror 1.0.40", + "thiserror 1.0.44", "thiserror 1.0.9", "url 2.1.1", - "url 2.4.0", + "url 2.5.0", ] [[package]] name = "itc-rpc-client" version = "0.9.0" dependencies = [ - "env_logger", + "env_logger 0.9.3", "frame-metadata", "itc-tls-websocket-server", "itp-api-client-types", @@ -3293,16 +3077,15 @@ dependencies = [ "itp-rpc", "itp-types", "itp-utils", - "log 0.4.19", + "log 0.4.20", "openssl", "parity-scale-codec", "parking_lot 0.12.1", "rustls 0.19.1", - "serde_derive 1.0.188", - "serde_json 1.0.106", + "serde_json 1.0.103", "sgx_crypto_helper", - "thiserror 1.0.40", - "url 2.4.0", + "thiserror 1.0.44", + "url 2.5.0", "ws", ] @@ -3311,7 +3094,7 @@ name = "itc-rpc-server" version = "0.9.0" dependencies = [ "anyhow", - "env_logger", + "env_logger 0.10.0", "itp-enclave-api", "itp-rpc", "itp-utils", @@ -3321,9 +3104,8 @@ dependencies = [ "its-storage", "its-test", "jsonrpsee", - "log 0.4.19", + "log 0.4.20", "parity-scale-codec", - "serde_json 1.0.106", "sp-core", "tokio", ] @@ -3334,23 +3116,21 @@ version = "0.9.0" dependencies = [ "bit-vec", "chrono 0.4.26", - "env_logger", - "log 0.4.19", + "env_logger 0.9.3", + "log 0.4.20", "mio 0.6.21", "mio 0.6.23", "mio-extras 2.0.6 (git+https://github.com/integritee-network/mio-extras-sgx?rev=963234b)", "rcgen", "rustls 0.19.0 (git+https://github.com/mesalock-linux/rustls?branch=mesalock_sgx)", "rustls 0.19.1", - "sgx_crypto_helper", "sgx_tstd", - "sgx_types", "sp-core", - "thiserror 1.0.40", + "thiserror 1.0.44", "thiserror 1.0.9", "tungstenite 0.14.0", "tungstenite 0.15.0", - "url 2.4.0", + "url 2.5.0", "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)", "yasna 0.3.1", @@ -3366,6 +3146,15 @@ 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" @@ -3376,9 +3165,9 @@ dependencies = [ [[package]] name = "itoa" -version = "1.0.6" +version = "1.0.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "453ad9f582a441959e5f0d088b02ce04cfe8d51a8eaf077f12ac6d3e94164ca6" +checksum = "af150ab688ff2122fcef229be89cb50dd66af9e01a4ff320cc137eecc9bacc38" [[package]] name = "itp-api-client-extensions" @@ -3386,22 +3175,17 @@ version = "0.9.0" dependencies = [ "itp-api-client-types", "itp-types", - "log 0.4.19", - "parity-scale-codec", + "log 0.4.20", "sp-consensus-grandpa", - "sp-core", "sp-runtime", "substrate-api-client", - "thiserror 1.0.40", ] [[package]] name = "itp-api-client-types" version = "0.9.0" dependencies = [ - "integritee-node-runtime", "itp-types", - "sp-core", "sp-runtime", "substrate-api-client", ] @@ -3410,7 +3194,7 @@ dependencies = [ name = "itp-attestation-handler" version = "0.8.0" dependencies = [ - "arrayvec 0.7.3", + "arrayvec 0.7.4", "base64 0.13.0 (git+https://github.com/mesalock-linux/rust-base64-sgx?rev=sgx_1.1.3)", "base64 0.13.1", "bit-vec", @@ -3418,19 +3202,18 @@ dependencies = [ "chrono 0.4.26", "hex", "httparse 1.4.1", - "itertools", + "itertools 0.10.5", "itp-ocall-api", "itp-settings", "itp-sgx-crypto", "itp-sgx-io", "itp-time-utils", - "itp-types", - "log 0.4.19", + "log 0.4.20", "num-bigint 0.2.5", "parity-scale-codec", "rustls 0.19.0 (git+https://github.com/mesalock-linux/rustls?rev=sgx_1.1.3)", "rustls 0.19.1", - "serde_json 1.0.106", + "serde_json 1.0.103", "serde_json 1.0.60 (git+https://github.com/mesalock-linux/serde-json-sgx?tag=sgx_1.1.3)", "sgx_rand", "sgx_tcrypto", @@ -3438,8 +3221,7 @@ dependencies = [ "sgx_tstd", "sgx_types", "sp-core", - "sp-runtime", - "thiserror 1.0.40", + "thiserror 1.0.44", "thiserror 1.0.9", "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)", @@ -3452,7 +3234,7 @@ name = "itp-component-container" version = "0.8.0" dependencies = [ "sgx_tstd", - "thiserror 1.0.40", + "thiserror 1.0.44", "thiserror 1.0.9", ] @@ -3465,19 +3247,19 @@ dependencies = [ "itc-parentchain", "itp-enclave-api-ffi", "itp-settings", + "itp-stf-interface", "itp-storage", "itp-types", - "log 0.4.19", + "log 0.4.20", "parity-scale-codec", - "serde_json 1.0.106", + "serde_json 1.0.103", "sgx_crypto_helper", "sgx_types", "sgx_urts", - "sp-consensus-grandpa", "sp-core", "sp-runtime", "teerex-primitives", - "thiserror 1.0.40", + "thiserror 1.0.44", ] [[package]] @@ -3492,7 +3274,6 @@ name = "itp-enclave-bridge-storage" version = "0.9.0" dependencies = [ "itp-storage", - "itp-types", "parity-scale-codec", "sp-std", ] @@ -3513,14 +3294,13 @@ dependencies = [ "itp-node-api", "itp-nonce-cache", "itp-types", - "log 0.4.19", "parity-scale-codec", "sgx_tstd", "sgx_types", "sp-core", "sp-runtime", "substrate-api-client", - "thiserror 1.0.40", + "thiserror 1.0.44", "thiserror 1.0.9", ] @@ -3537,7 +3317,7 @@ version = "0.8.0" dependencies = [ "sgx_tstd", "sgx_types", - "thiserror 1.0.40", + "thiserror 1.0.44", "thiserror 1.0.9", ] @@ -3565,7 +3345,7 @@ version = "0.9.0" dependencies = [ "itp-api-client-types", "sp-core", - "thiserror 1.0.40", + "thiserror 1.0.44", ] [[package]] @@ -3584,7 +3364,7 @@ version = "0.9.0" dependencies = [ "itp-node-api-metadata", "sgx_tstd", - "thiserror 1.0.40", + "thiserror 1.0.44", "thiserror 1.0.9", ] @@ -3592,9 +3372,8 @@ dependencies = [ name = "itp-nonce-cache" version = "0.8.0" dependencies = [ - "lazy_static", "sgx_tstd", - "thiserror 1.0.40", + "thiserror 1.0.44", "thiserror 1.0.9", ] @@ -3618,7 +3397,7 @@ version = "0.9.0" dependencies = [ "lazy_static", "sgx_tstd", - "thiserror 1.0.40", + "thiserror 1.0.44", "thiserror 1.0.9", ] @@ -3628,8 +3407,8 @@ version = "0.9.0" dependencies = [ "itp-types", "parity-scale-codec", - "serde 1.0.188", - "serde_json 1.0.106", + "serde 1.0.193", + "serde_json 1.0.103", "sgx_tstd", ] @@ -3643,15 +3422,12 @@ version = "0.9.0" dependencies = [ "aes", "derive_more", - "itp-settings", "itp-sgx-io", "itp-sgx-temp-dir", - "log 0.4.19", + "log 0.4.20", "ofb", "parity-scale-codec", - "serde 1.0.118 (git+https://github.com/mesalock-linux/serde-sgx?tag=sgx_1.1.3)", - "serde 1.0.188", - "serde_json 1.0.106", + "serde_json 1.0.103", "serde_json 1.0.60 (git+https://github.com/mesalock-linux/serde-json-sgx?tag=sgx_1.1.3)", "sgx_crypto_helper", "sgx_rand", @@ -3667,10 +3443,10 @@ dependencies = [ "derive_more", "environmental 1.1.3", "itp-hashing", - "log 0.4.19", + "log 0.4.20", "parity-scale-codec", "postcard", - "serde 1.0.188", + "serde 1.0.193", "sgx_tstd", "sp-core", ] @@ -3715,20 +3491,18 @@ dependencies = [ "itp-stf-primitives", "itp-stf-state-handler", "itp-stf-state-observer", - "itp-storage", "itp-test", "itp-time-utils", "itp-top-pool", "itp-top-pool-author", "itp-types", - "log 0.4.19", + "log 0.4.20", "parity-scale-codec", - "sgx_crypto_helper", "sgx_tstd", "sgx_types", "sp-core", "sp-runtime", - "thiserror 1.0.40", + "thiserror 1.0.44", "thiserror 1.0.9", ] @@ -3748,7 +3522,6 @@ name = "itp-stf-primitives" version = "0.9.0" dependencies = [ "derive_more", - "itp-hashing", "itp-sgx-runtime-primitives", "parity-scale-codec", "sp-core", @@ -3770,16 +3543,14 @@ dependencies = [ "itp-stf-state-observer", "itp-time-utils", "itp-types", - "lazy_static", - "log 0.4.19", + "log 0.4.20", "parity-scale-codec", "rust-base58 0.0.4 (registry+https://github.com/rust-lang/crates.io-index)", "rust-base58 0.0.4 (git+https://github.com/mesalock-linux/rust-base58-sgx?rev=sgx_1.1.3)", - "sgx_tcrypto", "sgx_tstd", "sgx_types", "sp-core", - "thiserror 1.0.40", + "thiserror 1.0.44", "thiserror 1.0.9", ] @@ -3788,10 +3559,9 @@ name = "itp-stf-state-observer" version = "0.9.0" dependencies = [ "itp-types", - "log 0.4.19", - "parity-scale-codec", + "log 0.4.20", "sgx_tstd", - "thiserror 1.0.40", + "thiserror 1.0.44", "thiserror 1.0.9", ] @@ -3811,7 +3581,7 @@ dependencies = [ "sp-state-machine", "sp-std", "sp-trie", - "thiserror 1.0.40", + "thiserror 1.0.44", "thiserror 1.0.9", ] @@ -3828,7 +3598,6 @@ dependencies = [ name = "itp-test" version = "0.9.0" dependencies = [ - "derive_more", "itp-enclave-bridge-storage", "itp-node-api", "itp-node-api-metadata-provider", @@ -3842,7 +3611,7 @@ dependencies = [ "itp-time-utils", "itp-types", "jsonrpc-core 18.0.0 (git+https://github.com/scs/jsonrpc?branch=no_std_v18)", - "log 0.4.19", + "log 0.4.20", "parity-scale-codec", "sgx_crypto_helper", "sgx_tstd", @@ -3867,7 +3636,6 @@ dependencies = [ "byteorder 1.4.3", "derive_more", "itc-direct-rpc-server", - "itp-sgx-runtime-primitives", "itp-stf-primitives", "itp-test", "itp-types", @@ -3876,17 +3644,14 @@ dependencies = [ "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", - "log 0.4.19", + "log 0.4.20", "parity-scale-codec", "parity-util-mem", - "serde 1.0.188", + "serde 1.0.193", "sgx_tstd", - "sgx_types", "sp-application-crypto", "sp-core", "sp-runtime", - "thiserror 1.0.40", - "thiserror 1.0.9", ] [[package]] @@ -3903,38 +3668,34 @@ dependencies = [ "itp-test", "itp-top-pool", "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.19", + "log 0.4.20", "parity-scale-codec", "sgx_crypto_helper", "sgx_tstd", - "sgx_types", "sp-core", "sp-keyring", "sp-runtime", - "thiserror 1.0.40", - "thiserror 1.0.9", ] [[package]] name = "itp-types" version = "0.9.0" dependencies = [ - "chrono 0.4.26", "enclave-bridge-primitives", "frame-system", - "integritee-node-runtime", "itp-sgx-runtime-primitives", + "itp-stf-primitives", + "itp-utils", "pallet-balances", "parity-scale-codec", - "primitive-types", - "serde 1.0.188", - "serde_json 1.0.106", + "serde 1.0.193", "sp-core", "sp-runtime", "sp-std", + "substrate-api-client", + "teeracle-primitives", "teerex-primitives", ] @@ -3950,26 +3711,24 @@ dependencies = [ name = "its-block-composer" version = "0.9.0" dependencies = [ - "ita-stf", "itp-node-api", "itp-settings", "itp-sgx-crypto", "itp-sgx-externalities", "itp-stf-executor", - "itp-stf-interface", "itp-stf-primitives", "itp-time-utils", "itp-top-pool-author", "itp-types", "its-primitives", "its-state", - "log 0.4.19", + "log 0.4.20", "parity-scale-codec", "sgx_tstd", "sgx_types", "sp-core", "sp-runtime", - "thiserror 1.0.40", + "thiserror 1.0.44", "thiserror 1.0.9", ] @@ -3983,13 +3742,13 @@ dependencies = [ "itp-utils", "its-primitives", "its-test", - "log 0.4.19", + "log 0.4.20", "sgx_tstd", "sp-consensus-slots", "sp-core", "sp-keyring", "sp-runtime", - "thiserror 1.0.40", + "thiserror 1.0.44", "thiserror 1.0.9", ] @@ -3997,9 +3756,8 @@ dependencies = [ name = "its-consensus-aura" version = "0.9.0" dependencies = [ - "env_logger", + "env_logger 0.9.3", "finality-grandpa", - "frame-support", "ita-stf", "itc-parentchain-block-import-dispatcher", "itc-parentchain-test", @@ -4025,7 +3783,7 @@ dependencies = [ "its-state", "its-test", "its-validateer-fetch", - "log 0.4.19", + "log 0.4.20", "parity-scale-codec", "sgx_tstd", "sp-core", @@ -4040,6 +3798,7 @@ dependencies = [ "fork-tree", "itc-parentchain-light-client", "itc-parentchain-test", + "itertools 0.10.5", "itp-extrinsics-factory", "itp-import-queue", "itp-node-api-metadata", @@ -4050,17 +3809,18 @@ dependencies = [ "itp-sgx-externalities", "itp-test", "itp-types", + "itp-utils", "its-block-verification", "its-primitives", "its-state", "its-test", - "log 0.4.19", + "log 0.4.20", "parity-scale-codec", "sgx_tstd", "sgx_types", "sp-core", "sp-runtime", - "thiserror 1.0.40", + "thiserror 1.0.44", "thiserror 1.0.9", ] @@ -4069,11 +3829,9 @@ name = "its-consensus-slots" version = "0.9.0" dependencies = [ "derive_more", - "futures 0.3.28", "futures-timer", "itc-parentchain-test", "itp-settings", - "itp-sgx-io", "itp-time-utils", "itp-types", "its-block-verification", @@ -4081,7 +3839,7 @@ dependencies = [ "its-primitives", "its-test", "lazy_static", - "log 0.4.19", + "log 0.4.20", "parity-scale-codec", "sgx_tstd", "sp-consensus-slots", @@ -4104,10 +3862,10 @@ dependencies = [ "its-storage", "its-test", "jsonrpsee", - "log 0.4.19", - "serde 1.0.188", - "serde_json 1.0.106", - "thiserror 1.0.40", + "log 0.4.20", + "serde 1.0.193", + "serde_json 1.0.103", + "thiserror 1.0.44", "tokio", ] @@ -4118,9 +3876,8 @@ dependencies = [ "itp-types", "parity-scale-codec", "scale-info", - "serde 1.0.188", + "serde 1.0.193", "sp-core", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", "sp-runtime", "sp-std", ] @@ -4137,12 +3894,11 @@ dependencies = [ "its-primitives", "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.19", + "log 0.4.20", "parity-scale-codec", "rust-base58 0.0.4 (registry+https://github.com/rust-lang/crates.io-index)", "rust-base58 0.0.4 (git+https://github.com/mesalock-linux/rust-base58-sgx?rev=sgx_1.1.3)", "sgx_tstd", - "sgx_types", "sp-core", ] @@ -4168,15 +3924,13 @@ dependencies = [ "itp-sgx-externalities", "itp-storage", "its-primitives", - "log 0.4.19", + "log 0.4.20", "parity-scale-codec", - "serde 1.0.188", "sgx_tstd", "sp-core", "sp-io 7.0.0", "sp-runtime", - "sp-std", - "thiserror 1.0.40", + "thiserror 1.0.44", "thiserror 1.0.9", ] @@ -4189,14 +3943,14 @@ dependencies = [ "itp-types", "its-primitives", "its-test", - "log 0.4.19", + "log 0.4.20", "mockall", "parity-scale-codec", "parking_lot 0.12.1", "rocksdb", "sp-core", "temp-dir", - "thiserror 1.0.40", + "thiserror 1.0.44", ] [[package]] @@ -4205,7 +3959,6 @@ version = "0.9.0" dependencies = [ "itp-types", "its-primitives", - "parity-scale-codec", "sgx_tstd", "sp-core", ] @@ -4215,21 +3968,17 @@ name = "its-validateer-fetch" version = "0.9.0" dependencies = [ "derive_more", - "frame-support", "itc-parentchain-test", "itp-enclave-bridge-storage", "itp-ocall-api", - "itp-storage", - "itp-teerex-storage", "itp-test", "itp-types", "its-primitives", - "log 0.4.19", + "log 0.4.20", "parity-scale-codec", "sp-core", "sp-runtime", "sp-std", - "thiserror 1.0.40", ] [[package]] @@ -4259,10 +4008,10 @@ dependencies = [ "futures 0.3.28", "futures-executor 0.3.28", "futures-util 0.3.28", - "log 0.4.19", - "serde 1.0.188", - "serde_derive 1.0.188", - "serde_json 1.0.106", + "log 0.4.20", + "serde 1.0.193", + "serde_derive 1.0.193", + "serde_json 1.0.103", ] [[package]] @@ -4272,7 +4021,7 @@ source = "git+https://github.com/scs/jsonrpc?branch=no_std_v18#0faf53c491c3222b9 dependencies = [ "futures 0.3.8", "log 0.4.14 (git+https://github.com/mesalock-linux/log-sgx)", - "serde 1.0.118 (git+https://github.com/mesalock-linux/serde-sgx)", + "serde 1.0.118", "serde_derive 1.0.118", "serde_json 1.0.60 (git+https://github.com/mesalock-linux/serde-json-sgx)", ] @@ -4304,11 +4053,11 @@ dependencies = [ "hyper-rustls", "jsonrpsee-types", "jsonrpsee-utils", - "log 0.4.19", - "serde 1.0.188", - "serde_json 1.0.106", - "thiserror 1.0.40", - "url 2.4.0", + "log 0.4.20", + "serde 1.0.193", + "serde_json 1.0.103", + "thiserror 1.0.44", + "url 2.5.0", ] [[package]] @@ -4324,11 +4073,11 @@ dependencies = [ "jsonrpsee-types", "jsonrpsee-utils", "lazy_static", - "log 0.4.19", - "serde 1.0.188", - "serde_json 1.0.106", + "log 0.4.20", + "serde 1.0.193", + "serde_json 1.0.103", "socket2", - "thiserror 1.0.40", + "thiserror 1.0.44", "tokio", "unicase 2.6.0 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -4357,11 +4106,11 @@ dependencies = [ "futures-channel 0.3.28", "futures-util 0.3.28", "hyper", - "log 0.4.19", - "serde 1.0.188", - "serde_json 1.0.106", + "log 0.4.20", + "serde 1.0.193", + "serde_json 1.0.103", "soketto", - "thiserror 1.0.40", + "thiserror 1.0.44", ] [[package]] @@ -4374,13 +4123,13 @@ dependencies = [ "futures-util 0.3.28", "hyper", "jsonrpsee-types", - "log 0.4.19", + "log 0.4.20", "parking_lot 0.11.2", "rand 0.8.5", "rustc-hash", - "serde 1.0.188", - "serde_json 1.0.106", - "thiserror 1.0.40", + "serde 1.0.193", + "serde_json 1.0.103", + "thiserror 1.0.44", ] [[package]] @@ -4393,18 +4142,18 @@ dependencies = [ "fnv 1.0.7", "futures 0.3.28", "jsonrpsee-types", - "log 0.4.19", + "log 0.4.20", "pin-project", "rustls 0.19.1", "rustls-native-certs", - "serde 1.0.188", - "serde_json 1.0.106", + "serde 1.0.193", + "serde_json 1.0.103", "soketto", - "thiserror 1.0.40", + "thiserror 1.0.44", "tokio", "tokio-rustls", "tokio-util 0.6.10", - "url 2.4.0", + "url 2.5.0", ] [[package]] @@ -4417,12 +4166,12 @@ dependencies = [ "futures-util 0.3.28", "jsonrpsee-types", "jsonrpsee-utils", - "log 0.4.19", + "log 0.4.20", "rustc-hash", - "serde 1.0.188", - "serde_json 1.0.106", + "serde 1.0.193", + "serde_json 1.0.103", "soketto", - "thiserror 1.0.40", + "thiserror 1.0.44", "tokio", "tokio-stream", "tokio-util 0.6.10", @@ -4438,7 +4187,7 @@ dependencies = [ "ecdsa", "elliptic-curve", "once_cell 1.18.0", - "sha2 0.10.6", + "sha2 0.10.7", ] [[package]] @@ -4477,9 +4226,9 @@ checksum = "830d08ce1d1d941e6b30645f1a0eb5643013d835ce3779a5fc208261dbe10f55" [[package]] name = "libc" -version = "0.2.146" +version = "0.2.147" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f92be4933c13fd498862a9e02a3055f8a8d9c039ce33db97306fd5a6caa7f29b" +checksum = "b4668fb0ea861c1df094127ac5f1da3409a82116a4ba74fca2e58ef927159bb3" [[package]] name = "libloading" @@ -4527,7 +4276,7 @@ dependencies = [ "libsecp256k1-gen-ecmult", "libsecp256k1-gen-genmult", "rand 0.8.5", - "serde 1.0.188", + "serde 1.0.193", "sha2 0.9.9", "typenum 1.16.0 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -4563,24 +4312,15 @@ dependencies = [ [[package]] name = "libz-sys" -version = "1.1.12" +version = "1.1.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d97137b25e321a73eef1418d1d5d2eda4d77e12813f8e6dead84bc52c5870a7b" +checksum = "24e6ab01971eb092ffe6a7d42f49f9ff42662f17604681e2843ad65077ba47dc" dependencies = [ "cc", "pkg-config", "vcpkg", ] -[[package]] -name = "link-cplusplus" -version = "1.0.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ecd207c9c713c34f95a097a5b029ac2ce6010530c7b49d7fea24d977dede04f5" -dependencies = [ - "cc", -] - [[package]] name = "linked-hash-map" version = "0.5.2" @@ -4597,9 +4337,9 @@ checksum = "0717cef1bc8b636c6e1c1bbdefc09e6322da8a9321966e8928ef80d20f7f770f" [[package]] name = "linregress" -version = "0.5.1" +version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "475015a7f8f017edb28d2e69813be23500ad4b32cfe3421c4148efc97324ee52" +checksum = "4de0b5f52a9f84544d268f5fabb71b38962d6aa3c6600b8bcd27d44ccf9c9c45" dependencies = [ "nalgebra", ] @@ -4616,6 +4356,12 @@ version = "0.3.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ef53942eb7bf7ff43a617b3e2c1c4a5ecf5944a7c1bc12d7ee39bbb15e5c1519" +[[package]] +name = "linux-raw-sys" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09fc20d2ca12cb9f044c93e3bd6d32d523e6e2ec3db4f7b2939cd99026ecd3f0" + [[package]] name = "lock_api" version = "0.4.10" @@ -4646,9 +4392,9 @@ dependencies = [ [[package]] name = "log" -version = "0.4.19" +version = "0.4.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b06a4cde4c0f271a446782e3eff8de789548ce57dbc8eca9292c27f4a42004b4" +checksum = "b5e6163cb8c49088c2c36f57875e58ccd8c87c7427f7fbd50ea6710b2f3f2e8f" [[package]] name = "lz4-sys" @@ -4726,7 +4472,7 @@ version = "0.6.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ffc89ccdc6e10d6907450f753537ebc5c5d3460d2e4e62ea74bd571db62c0f9e" dependencies = [ - "rustix 0.37.20", + "rustix 0.37.23", ] [[package]] @@ -4796,15 +4542,6 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" -[[package]] -name = "miniz_oxide" -version = "0.6.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b275950c28b37e794e8c55d88aeb5e139d0ce23fdbbeda68f8d7174abdf9e8fa" -dependencies = [ - "adler", -] - [[package]] name = "miniz_oxide" version = "0.7.1" @@ -4840,9 +4577,9 @@ dependencies = [ "iovec 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)", "kernel32-sys", "libc", - "log 0.4.19", + "log 0.4.20", "miow", - "net2 0.2.38", + "net2 0.2.39", "slab 0.4.8", "winapi 0.2.8", ] @@ -4865,7 +4602,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "52403fe290012ce777c4626790c8951324a2b9e3316b3143779c72b029742f19" dependencies = [ "lazycell", - "log 0.4.19", + "log 0.4.20", "mio 0.6.23", "slab 0.4.8", ] @@ -4876,7 +4613,7 @@ version = "2.0.6" source = "git+https://github.com/integritee-network/mio-extras-sgx?rev=963234b#963234bf55e44f9efff921938255126c48deef3a" dependencies = [ "lazycell", - "log 0.4.19", + "log 0.4.20", "mio 0.6.21", "mio 0.6.23", "sgx_tstd", @@ -4891,7 +4628,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ebd808424166322d4a38da87083bfddd3ac4c131334ed55856112eb06d46944d" dependencies = [ "kernel32-sys", - "net2 0.2.38", + "net2 0.2.39", "winapi 0.2.8", "ws2_32-sys", ] @@ -4934,7 +4671,7 @@ dependencies = [ "futures-util 0.3.28", "http 0.2.9", "httparse 1.8.0", - "log 0.4.19", + "log 0.4.20", "memchr 2.6.3", "mime", "spin 0.9.8", @@ -4968,25 +4705,25 @@ dependencies = [ [[package]] name = "nalgebra" -version = "0.32.2" +version = "0.32.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d68d47bba83f9e2006d117a9a33af1524e655516b8919caac694427a6fb1e511" +checksum = "307ed9b18cc2423f29e83f84fd23a8e73628727990181f18641a8b5dc2ab1caa" dependencies = [ "approx", "matrixmultiply", "nalgebra-macros", "num-complex 0.4.3", "num-rational 0.4.1", - "num-traits 0.2.15", + "num-traits 0.2.16", "simba", "typenum 1.16.0 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "nalgebra-macros" -version = "0.2.0" +version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d232c68884c0c99810a5a4d333ef7e47689cfd0edc85efc9e54e1e6bf5212766" +checksum = "91761aed67d03ad966ef783ae962ef9bbaca728d2dd7ceb7939ec110fffad998" dependencies = [ "proc-macro2", "quote", @@ -5001,7 +4738,7 @@ checksum = "07226173c32f2926027b63cce4bcd8076c3552846cbe7925f3aaffeac0a3b92e" dependencies = [ "lazy_static", "libc", - "log 0.4.19", + "log 0.4.20", "openssl", "openssl-probe", "openssl-sys", @@ -5023,21 +4760,15 @@ dependencies = [ [[package]] name = "net2" -version = "0.2.38" +version = "0.2.39" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "74d0df99cfcd2530b2e694f6e17e7f37b8e26bb23983ac530c0c97408837c631" +checksum = "b13b648036a2339d06de780866fbdfda0dde886de7b3af2ddeba8b14f4ee34ac" dependencies = [ "cfg-if 0.1.10", "libc", "winapi 0.3.9", ] -[[package]] -name = "nodrop" -version = "0.1.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72ef4a56884ca558e5ddb05a1d1e7e1bfd9a68d9ed024c21704cc98872dae1bb" - [[package]] name = "nohash-hasher" version = "0.2.0" @@ -5084,21 +4815,21 @@ dependencies = [ "num-integer 0.1.45", "num-iter 0.1.43", "num-rational 0.2.4", - "num-traits 0.2.15", + "num-traits 0.2.16", ] [[package]] name = "num" -version = "0.4.0" +version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "43db66d1170d347f9a065114077f7dccb00c1b9478c89384490a3425279a4606" +checksum = "b05180d69e3da0e530ba2a1dae5110317e49e3b7f3d41be227dc5f92e49ee7af" dependencies = [ "num-bigint 0.4.3", "num-complex 0.4.3", "num-integer 0.1.45", "num-iter 0.1.43", "num-rational 0.4.1", - "num-traits 0.2.15", + "num-traits 0.2.16", ] [[package]] @@ -5120,7 +4851,7 @@ checksum = "090c7f9998ee0ff65aa5b723e4009f7b217707f1fb5ea551329cc4d6231fb304" dependencies = [ "autocfg 1.1.0", "num-integer 0.1.45", - "num-traits 0.2.15", + "num-traits 0.2.16", ] [[package]] @@ -5131,7 +4862,7 @@ checksum = "f93ab6289c7b344a8a9f60f88d80aa20032336fe78da341afc91c8a2341fc75f" dependencies = [ "autocfg 1.1.0", "num-integer 0.1.45", - "num-traits 0.2.15", + "num-traits 0.2.16", ] [[package]] @@ -5151,7 +4882,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6b19411a9719e753aff12e5187b74d60d3dc449ec3f4dc21e3989c3f554bc95" dependencies = [ "autocfg 1.1.0", - "num-traits 0.2.15", + "num-traits 0.2.16", ] [[package]] @@ -5160,7 +4891,7 @@ version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "02e0d21255c828d6f128a1e41534206671e8c3ea0c62f32291e808dc82cff17d" dependencies = [ - "num-traits 0.2.15", + "num-traits 0.2.16", ] [[package]] @@ -5180,8 +4911,8 @@ version = "0.4.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a652d9771a63711fd3c3deb670acfbe5c30a4072e664d7a3bf5a9e1056ac72c3" dependencies = [ - "arrayvec 0.7.3", - "itoa 1.0.6", + "arrayvec 0.7.4", + "itoa 1.0.9", ] [[package]] @@ -5201,7 +4932,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "225d3389fb3509a24c93f5c29eb6bde2586b98d9f016636dff58d7c6f7569cd9" dependencies = [ "autocfg 1.1.0", - "num-traits 0.2.15", + "num-traits 0.2.16", ] [[package]] @@ -5222,7 +4953,7 @@ checksum = "7d03e6c028c5dc5cac6e2dec0efda81fc887605bb3d884578bb6d6bf7514e252" dependencies = [ "autocfg 1.1.0", "num-integer 0.1.45", - "num-traits 0.2.15", + "num-traits 0.2.16", ] [[package]] @@ -5246,7 +4977,7 @@ dependencies = [ "autocfg 1.1.0", "num-bigint 0.2.6", "num-integer 0.1.45", - "num-traits 0.2.15", + "num-traits 0.2.16", ] [[package]] @@ -5258,7 +4989,7 @@ dependencies = [ "autocfg 1.1.0", "num-bigint 0.4.3", "num-integer 0.1.45", - "num-traits 0.2.15", + "num-traits 0.2.16", ] [[package]] @@ -5272,20 +5003,20 @@ dependencies = [ [[package]] name = "num-traits" -version = "0.2.15" +version = "0.2.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "578ede34cf02f8924ab9447f50c28075b4d3e5b269972345e7e0372b38c6cdcd" +checksum = "f30b0abd723be7e2ffca1272140fac1a2f084c77ec3e123c192b66af1ee9e6c2" dependencies = [ "autocfg 1.1.0", ] [[package]] name = "num_cpus" -version = "1.15.0" +version = "1.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0fac9e2da13b5eb447a6ce3d392f23a29d8694bff781bf03a16cd9ac8697593b" +checksum = "4161fcb6d602d4d2081af7c3a45852d875a03dd337a6bfdd6e06407b61342a43" dependencies = [ - "hermit-abi 0.2.6", + "hermit-abi 0.3.2", "libc", ] @@ -5303,9 +5034,9 @@ dependencies = [ [[package]] name = "object" -version = "0.30.4" +version = "0.31.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "03b4680b86d9cfafba8fc491dc9b6df26b68cf40e9e6cd73909194759a63c385" +checksum = "8bda667d9f2b5051b8833f59f3bf748b28ef54f850f4fcb389a252aa383866d1" dependencies = [ "memchr 2.6.3", ] @@ -5347,11 +5078,11 @@ checksum = "624a8340c38c1b80fd549087862da4ba43e08858af025b236e509b6649fc13d5" [[package]] name = "openssl" -version = "0.10.54" +version = "0.10.55" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "69b3f656a17a6cbc115b5c7a40c616947d213ba182135b014d6051b73ab6f019" +checksum = "345df152bc43501c5eb9e4654ff05f794effb78d4efe3d53abc158baddc0703d" dependencies = [ - "bitflags", + "bitflags 1.3.2", "cfg-if 1.0.0", "foreign-types", "libc", @@ -5379,9 +5110,9 @@ checksum = "ff011a302c396a5197692431fc1948019154afc178baf7d8e37367442a4601cf" [[package]] name = "openssl-sys" -version = "0.9.88" +version = "0.9.90" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c2ce0f250f34a308dcfdbb351f511359857d4ed2134ba715a4eadd46e1ffd617" +checksum = "374533b0e45f3a7ced10fcaeccca020e66656bc03dac384f852e4e5a7a8104a6" dependencies = [ "cc", "libc", @@ -5426,20 +5157,6 @@ dependencies = [ "sp-std", ] -[[package]] -name = "pallet-authorship" -version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" -dependencies = [ - "frame-support", - "frame-system", - "impl-trait-for-tuples", - "parity-scale-codec", - "scale-info", - "sp-runtime", - "sp-std", -] - [[package]] name = "pallet-balances" version = "4.0.0-dev" @@ -5448,45 +5165,27 @@ dependencies = [ "frame-benchmarking", "frame-support", "frame-system", - "log 0.4.19", - "parity-scale-codec", - "scale-info", - "sp-runtime", - "sp-std", -] - -[[package]] -name = "pallet-claims" -version = "0.9.12" -source = "git+https://github.com/integritee-network/pallets.git?branch=sdk-v0.12.0-polkadot-v0.9.42#eaf611b79bc9d56b20c155150e99b549bf98436b" -dependencies = [ - "claims-primitives", - "frame-support", - "frame-system", + "log 0.4.20", "parity-scale-codec", - "rustc-hex", "scale-info", - "serde 1.0.188", - "serde_derive 1.0.188", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", "sp-runtime", "sp-std", ] [[package]] name = "pallet-enclave-bridge" -version = "0.10.0" -source = "git+https://github.com/integritee-network/pallets.git?branch=sdk-v0.12.0-polkadot-v0.9.42#eaf611b79bc9d56b20c155150e99b549bf98436b" +version = "0.12.0" +source = "git+https://github.com/integritee-network/pallets.git?branch=sdk-v0.12.11-polkadot-v0.9.42#094b1e982b4637ebfbf5afb985100417215d49a0" dependencies = [ "enclave-bridge-primitives", "frame-support", "frame-system", - "log 0.4.19", + "log 0.4.20", "pallet-teerex", "pallet-timestamp", "parity-scale-codec", "scale-info", - "serde 1.0.188", + "serde 1.0.193", "sp-core", "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", "sp-runtime", @@ -5496,181 +5195,75 @@ dependencies = [ [[package]] name = "pallet-evm" -version = "6.0.0-dev" -source = "git+https://github.com/integritee-network/frontier.git?branch=bar/polkadot-v0.9.42#a5a5e1e6ec08cd542a6084c310863150fb8841b1" -dependencies = [ - "environmental 1.1.4", - "evm", - "fp-account", - "fp-evm", - "frame-benchmarking", - "frame-support", - "frame-system", - "hex", - "impl-trait-for-tuples", - "log 0.4.19", - "parity-scale-codec", - "rlp", - "scale-info", - "sp-core", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", - "sp-runtime", - "sp-std", -] - -[[package]] -name = "pallet-grandpa" -version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" -dependencies = [ - "frame-benchmarking", - "frame-support", - "frame-system", - "log 0.4.19", - "pallet-authorship", - "pallet-session", - "parity-scale-codec", - "scale-info", - "sp-application-crypto", - "sp-consensus-grandpa", - "sp-core", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", - "sp-runtime", - "sp-session", - "sp-staking", - "sp-std", -] - -[[package]] -name = "pallet-insecure-randomness-collective-flip" -version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" -dependencies = [ - "frame-support", - "frame-system", - "parity-scale-codec", - "safe-mix", - "scale-info", - "sp-runtime", - "sp-std", -] - -[[package]] -name = "pallet-multisig" -version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" -dependencies = [ - "frame-benchmarking", - "frame-support", - "frame-system", - "log 0.4.19", - "parity-scale-codec", - "scale-info", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", - "sp-runtime", - "sp-std", -] - -[[package]] -name = "pallet-parentchain" -version = "0.9.0" -source = "git+https://github.com/integritee-network/pallets.git?branch=sdk-v0.12.0-polkadot-v0.9.42#eaf611b79bc9d56b20c155150e99b549bf98436b" -dependencies = [ - "frame-support", - "frame-system", - "log 0.4.19", - "parity-scale-codec", - "scale-info", - "serde 1.0.188", - "sp-core", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", - "sp-runtime", - "sp-std", -] - -[[package]] -name = "pallet-preimage" -version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" -dependencies = [ - "frame-support", - "frame-system", - "log 0.4.19", - "parity-scale-codec", - "scale-info", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", - "sp-runtime", - "sp-std", -] - -[[package]] -name = "pallet-proxy" -version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +version = "6.0.0-dev" +source = "git+https://github.com/integritee-network/frontier.git?branch=bar/polkadot-v0.9.42#a5a5e1e6ec08cd542a6084c310863150fb8841b1" dependencies = [ + "environmental 1.1.4", + "evm", + "fp-account", + "fp-evm", "frame-benchmarking", "frame-support", "frame-system", + "hex", + "impl-trait-for-tuples", + "log 0.4.20", "parity-scale-codec", + "rlp", "scale-info", + "sp-core", "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", "sp-runtime", "sp-std", ] [[package]] -name = "pallet-scheduler" +name = "pallet-insecure-randomness-collective-flip" version = "4.0.0-dev" source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ - "frame-benchmarking", "frame-support", "frame-system", - "log 0.4.19", "parity-scale-codec", + "safe-mix", "scale-info", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", "sp-runtime", "sp-std", - "sp-weights", ] [[package]] -name = "pallet-session" -version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +name = "pallet-parentchain" +version = "0.11.0" +source = "git+https://github.com/integritee-network/pallets.git?branch=sdk-v0.12.11-polkadot-v0.9.42#094b1e982b4637ebfbf5afb985100417215d49a0" dependencies = [ "frame-support", "frame-system", - "impl-trait-for-tuples", - "log 0.4.19", - "pallet-timestamp", + "log 0.4.20", + "pallet-balances", "parity-scale-codec", "scale-info", + "serde 1.0.193", "sp-core", "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", "sp-runtime", - "sp-session", - "sp-staking", "sp-std", - "sp-trie", ] [[package]] name = "pallet-sidechain" -version = "0.10.0" -source = "git+https://github.com/integritee-network/pallets.git?branch=sdk-v0.12.0-polkadot-v0.9.42#eaf611b79bc9d56b20c155150e99b549bf98436b" +version = "0.11.0" +source = "git+https://github.com/integritee-network/pallets.git?branch=sdk-v0.12.11-polkadot-v0.9.42#094b1e982b4637ebfbf5afb985100417215d49a0" dependencies = [ "enclave-bridge-primitives", "frame-support", "frame-system", - "log 0.4.19", + "log 0.4.20", "pallet-enclave-bridge", "pallet-teerex", "pallet-timestamp", "parity-scale-codec", "scale-info", - "serde 1.0.188", + "serde 1.0.193", "sidechain-primitives", "sp-core", "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", @@ -5696,11 +5289,11 @@ dependencies = [ [[package]] name = "pallet-teeracle" version = "0.1.0" -source = "git+https://github.com/integritee-network/pallets.git?branch=sdk-v0.12.0-polkadot-v0.9.42#eaf611b79bc9d56b20c155150e99b549bf98436b" +source = "git+https://github.com/integritee-network/pallets.git?branch=sdk-v0.12.11-polkadot-v0.9.42#094b1e982b4637ebfbf5afb985100417215d49a0" dependencies = [ "frame-support", "frame-system", - "log 0.4.19", + "log 0.4.20", "pallet-teerex", "parity-scale-codec", "scale-info", @@ -5716,16 +5309,17 @@ dependencies = [ [[package]] name = "pallet-teerex" version = "0.10.0" -source = "git+https://github.com/integritee-network/pallets.git?branch=sdk-v0.12.0-polkadot-v0.9.42#eaf611b79bc9d56b20c155150e99b549bf98436b" +source = "git+https://github.com/integritee-network/pallets.git?branch=sdk-v0.12.11-polkadot-v0.9.42#094b1e982b4637ebfbf5afb985100417215d49a0" dependencies = [ "frame-support", "frame-system", "hex", - "log 0.4.19", + "log 0.4.20", "pallet-timestamp", "parity-scale-codec", + "rustls-webpki", "scale-info", - "serde 1.0.188", + "serde 1.0.193", "sgx-verify", "sp-core", "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", @@ -5742,7 +5336,7 @@ dependencies = [ "frame-benchmarking", "frame-support", "frame-system", - "log 0.4.19", + "log 0.4.20", "parity-scale-codec", "scale-info", "sp-inherents", @@ -5761,7 +5355,7 @@ dependencies = [ "frame-system", "parity-scale-codec", "scale-info", - "serde 1.0.188", + "serde 1.0.193", "sp-core", "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", "sp-runtime", @@ -5780,54 +5374,6 @@ dependencies = [ "sp-weights", ] -[[package]] -name = "pallet-treasury" -version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" -dependencies = [ - "frame-benchmarking", - "frame-support", - "frame-system", - "impl-trait-for-tuples", - "pallet-balances", - "parity-scale-codec", - "scale-info", - "serde 1.0.188", - "sp-runtime", - "sp-std", -] - -[[package]] -name = "pallet-utility" -version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" -dependencies = [ - "frame-benchmarking", - "frame-support", - "frame-system", - "parity-scale-codec", - "scale-info", - "sp-core", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", - "sp-runtime", - "sp-std", -] - -[[package]] -name = "pallet-vesting" -version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" -dependencies = [ - "frame-benchmarking", - "frame-support", - "frame-system", - "log 0.4.19", - "parity-scale-codec", - "scale-info", - "sp-runtime", - "sp-std", -] - [[package]] name = "parity-multiaddr" version = "0.11.2" @@ -5839,33 +5385,33 @@ dependencies = [ "byteorder 1.4.3", "data-encoding", "multihash", - "percent-encoding 2.3.0", - "serde 1.0.188", + "percent-encoding 2.3.1", + "serde 1.0.193", "static_assertions", "unsigned-varint 0.7.1", - "url 2.4.0", + "url 2.5.0", ] [[package]] name = "parity-scale-codec" -version = "3.6.5" +version = "3.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0dec8a8073036902368c2cdc0387e85ff9a37054d7e7c98e592145e0c92cd4fb" +checksum = "dd8e946cc0cc711189c0b0249fb8b599cbeeab9784d83c415719368bb8d4ac64" dependencies = [ - "arrayvec 0.7.3", + "arrayvec 0.7.4", "bitvec", "byte-slice-cast", "bytes 1.4.0", "impl-trait-for-tuples", "parity-scale-codec-derive", - "serde 1.0.188", + "serde 1.0.193", ] [[package]] name = "parity-scale-codec-derive" -version = "3.6.5" +version = "3.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "312270ee71e1cd70289dacf597cab7b207aa107d2f28191c2ae45b2ece18a260" +checksum = "2a296c3079b5fefbc499e1de58dc26c09b1b9a5952d26694ee89f04a43ebbb3e" dependencies = [ "proc-macro-crate", "proc-macro2", @@ -5934,7 +5480,7 @@ dependencies = [ "instant", "libc", "redox_syscall 0.2.16", - "smallvec 1.10.0", + "smallvec 1.11.0", "winapi 0.3.9", ] @@ -5947,8 +5493,8 @@ dependencies = [ "cfg-if 1.0.0", "libc", "redox_syscall 0.3.5", - "smallvec 1.10.0", - "windows-targets 0.48.0", + "smallvec 1.11.0", + "windows-targets 0.48.1", ] [[package]] @@ -5964,9 +5510,9 @@ dependencies = [ [[package]] name = "paste" -version = "1.0.12" +version = "1.0.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9f746c4065a8fa3fe23974dd82f15431cc8d40779821001404d10d2e79ca7d79" +checksum = "de3145af08024dea9fa9914f381a17b8fc6034dfb00f3a84013f7ff43f29ed4c" [[package]] name = "pbkdf2" @@ -6019,24 +5565,24 @@ source = "git+https://github.com/mesalock-linux/rust-url-sgx?tag=sgx_1.1.3#23832 [[package]] name = "percent-encoding" -version = "2.3.0" +version = "2.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b2a4787296e9989611394c33f193f676704af1686e70b8f8033ab5ba9a35a94" +checksum = "e3148f5046208a5d56bcfc03053e3ca6334e51da8dfb19b6cdc8b306fae3283e" [[package]] name = "pin-project" -version = "1.1.0" +version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c95a7476719eab1e366eaf73d0260af3021184f18177925b07f54b30089ceead" +checksum = "030ad2bc4db10a8944cb0d837f158bdfec4d4a4873ab701a95046770d11f8842" dependencies = [ "pin-project-internal", ] [[package]] name = "pin-project-internal" -version = "1.1.0" +version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "39407670928234ebc5e6e580247dd567ad73a3578460c5990f9503df207e8f07" +checksum = "ec2e072ecce94ec471b13398d5402c188e76ac03cf74dd1a975161b23a3f6d9c" dependencies = [ "proc-macro2", "quote", @@ -6045,9 +5591,9 @@ dependencies = [ [[package]] name = "pin-project-lite" -version = "0.2.9" +version = "0.2.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e0a7ae3ac2f1173085d398531c705756c94a4c56843785df85a60c1a0afac116" +checksum = "4c40d25201921e5ff0c862a505c6557ea88568a4e3ace775ab55e93f2f4f9d57" [[package]] name = "pin-utils" @@ -6061,7 +5607,7 @@ version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" dependencies = [ - "der 0.7.6", + "der 0.7.8", "spki 0.7.2", ] @@ -6078,7 +5624,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a25c0b0ae06fcffe600ad392aabfa535696c8973f2253d9ac83171924c58a858" dependencies = [ "postcard-cobs", - "serde 1.0.188", + "serde 1.0.193", ] [[package]] @@ -6106,7 +5652,7 @@ checksum = "59230a63c37f3e18569bdb90e4a89cbf5bf8b06fea0b84e65ea10cc4df47addd" dependencies = [ "difflib", "float-cmp", - "itertools", + "itertools 0.10.5", "normalize-line-endings", "predicates-core", "regex 1.9.5", @@ -6214,11 +5760,11 @@ version = "0.14.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b1de8dacb0873f77e6aefc6d71e044761fcc68060290f5b1089fcdf84626bb69" dependencies = [ - "bitflags", + "bitflags 1.3.2", "byteorder 1.4.3", "hex", "lazy_static", - "rustix 0.36.14", + "rustix 0.36.15", ] [[package]] @@ -6234,16 +5780,9 @@ dependencies = [ "memchr 2.6.3", "parking_lot 0.12.1", "procfs", - "protobuf", - "thiserror 1.0.40", + "thiserror 1.0.44", ] -[[package]] -name = "protobuf" -version = "2.28.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "106dd99e98437432fed6519dedecfade6a06a73bb7b2a1e019fdd2bee5778d94" - [[package]] name = "psm" version = "0.1.21" @@ -6442,7 +5981,7 @@ dependencies = [ "pem 0.8.2", "pem 1.1.1", "ring 0.16.19", - "ring 0.16.20 (registry+https://github.com/rust-lang/crates.io-index)", + "ring 0.16.20", "sgx_tstd", "yasna 0.3.1", "yasna 0.4.0", @@ -6463,7 +6002,7 @@ version = "0.2.16" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fb5a58c1855b4b6819d59012155603f0b22ad30cad752600aadfcb695265519a" dependencies = [ - "bitflags", + "bitflags 1.3.2", ] [[package]] @@ -6472,7 +6011,7 @@ version = "0.3.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "567664f262709473930a4bf9e51bf2ebf3348f2e748ccc50dea20646858f8f29" dependencies = [ - "bitflags", + "bitflags 1.3.2", ] [[package]] @@ -6483,23 +6022,23 @@ checksum = "b033d837a7cf162d7993aded9304e30a83213c648b6e389db233191f891e5c2b" dependencies = [ "getrandom 0.2.10", "redox_syscall 0.2.16", - "thiserror 1.0.40", + "thiserror 1.0.44", ] [[package]] name = "ref-cast" -version = "1.0.16" +version = "1.0.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f43faa91b1c8b36841ee70e97188a869d37ae21759da6846d4be66de5bf7b12c" +checksum = "61ef7e18e8841942ddb1cf845054f8008410030a3997875d9e49b7a363063df1" dependencies = [ "ref-cast-impl", ] [[package]] name = "ref-cast-impl" -version = "1.0.16" +version = "1.0.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8d2275aab483050ab2a7364c1a46604865ee7d6906684e08db0f090acf74f9e7" +checksum = "2dfaf0c85b766276c797f3791f5bc6d5bd116b41d53049af2789666b0c0bc9fa" dependencies = [ "proc-macro2", "quote", @@ -6521,7 +6060,7 @@ version = "1.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "697061221ea1b4a94a624f67d0ae2bfe4e22b8a17b6a192afb11046542cc8c47" dependencies = [ - "aho-corasick 1.0.2", + "aho-corasick", "memchr 2.6.3", "regex-automata 0.3.8", "regex-syntax 0.7.5", @@ -6542,7 +6081,7 @@ version = "0.3.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2f401f4955220693b56f8ec66ee9c78abffd8d1c4f23dc41a23839eb88f0795" dependencies = [ - "aho-corasick 1.0.2", + "aho-corasick", "memchr 2.6.3", "regex-syntax 0.7.5", ] @@ -6573,7 +6112,7 @@ version = "0.11.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3e9ad3fe7488d7e34558a2033d45a0c90b72d97b4f80705666fea71472e2e6a1" dependencies = [ - "base64 0.21.2", + "base64 0.21.5", "bytes 1.4.0", "encoding_rs", "futures-core 0.3.28", @@ -6585,19 +6124,19 @@ dependencies = [ "hyper-tls", "ipnet", "js-sys", - "log 0.4.19", + "log 0.4.20", "mime", "native-tls", "once_cell 1.18.0", - "percent-encoding 2.3.0", + "percent-encoding 2.3.1", "pin-project-lite", - "serde 1.0.188", - "serde_json 1.0.106", + "serde 1.0.193", + "serde_json 1.0.103", "serde_urlencoded", "tokio", "tokio-native-tls", "tower-service", - "url 2.4.0", + "url 2.5.0", "wasm-bindgen", "wasm-bindgen-futures", "web-sys", @@ -6622,36 +6161,21 @@ dependencies = [ "cc", "sgx_tstd", "spin 0.5.2", - "untrusted", -] - -[[package]] -name = "ring" -version = "0.16.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3053cf52e236a3ed746dfc745aa9cacf1b791d846bdaf412f60a8d7d6e17c8fc" -dependencies = [ - "cc", - "libc", - "once_cell 1.18.0", - "spin 0.5.2", - "untrusted", - "web-sys", - "winapi 0.3.9", + "untrusted 0.7.1", ] [[package]] name = "ring" version = "0.16.20" -source = "git+https://github.com/Niederb/ring-xous.git?branch=0.16.20-cleanup#8b2f60a7d4a063e2170cd47bc5591c39f49ca825" +source = "git+https://github.com/betrusted-io/ring-xous?branch=0.16.20-cleanup#4296c2e7904898766cf7d8d589759a129794783b" dependencies = [ "cc", "libc", - "log 0.4.19", + "log 0.4.20", "once_cell 1.18.0", "rkyv", "spin 0.5.2", - "untrusted", + "untrusted 0.7.1", "winapi 0.3.9", "xous", "xous-api-names", @@ -6718,7 +6242,7 @@ version = "0.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b313b91fcdc6719ad41fa2dad2b7e810b03833fae4bf911950e15529a5f04439" dependencies = [ - "num 0.4.0", + "num 0.4.1", ] [[package]] @@ -6763,16 +6287,16 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bfa0f585226d2e68097d4f95d113b15b83a82e819ab25717ec0590d9584ef366" dependencies = [ - "semver 1.0.17", + "semver 1.0.18", ] [[package]] name = "rustix" -version = "0.36.14" +version = "0.36.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "14e4d67015953998ad0eb82887a0eb0129e18a7e2f3b7b0f6c422fddcd503d62" +checksum = "c37f1bd5ef1b5422177b7646cba67430579cfe2ace80f284fee876bca52ad941" dependencies = [ - "bitflags", + "bitflags 1.3.2", "errno", "io-lifetimes", "libc", @@ -6782,11 +6306,11 @@ dependencies = [ [[package]] name = "rustix" -version = "0.37.20" +version = "0.37.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b96e891d04aa506a6d1f318d2771bcb1c7dfda84e126660ace067c9b474bb2c0" +checksum = "4d69718bf81c6127a49dc64e44a742e8bb9213c0ff8869a22c308f84c1d4ab06" dependencies = [ - "bitflags", + "bitflags 1.3.2", "errno", "io-lifetimes", "libc", @@ -6794,6 +6318,19 @@ dependencies = [ "windows-sys 0.48.0", ] +[[package]] +name = "rustix" +version = "0.38.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0a962918ea88d644592894bc6dc55acc6c0956488adcebbfb6e273506b7fd6e5" +dependencies = [ + "bitflags 2.3.3", + "errno", + "libc", + "linux-raw-sys 0.4.3", + "windows-sys 0.48.0", +] + [[package]] name = "rustls" version = "0.19.0" @@ -6840,8 +6377,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "35edb675feee39aec9c99fa5ff985081995a06d594114ae14cbe797ad7b7a6d7" dependencies = [ "base64 0.13.1", - "log 0.4.19", - "ring 0.16.20 (registry+https://github.com/rust-lang/crates.io-index)", + "log 0.4.20", + "ring 0.16.20", "sct 0.6.1", "webpki 0.21.4 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -6860,24 +6397,40 @@ dependencies = [ [[package]] name = "rustls-pemfile" -version = "1.0.2" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d3987094b1d07b653b7dfdc3f70ce9a1da9c51ac18c1b06b662e4f9a0e9f4b2" +dependencies = [ + "base64 0.21.5", +] + +[[package]] +name = "rustls-pki-types" +version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d194b56d58803a43635bdc398cd17e383d6f71f9182b9a192c127ca42494a59b" +checksum = "a47003264dea418db67060fa420ad16d0d2f8f0a0360d825c00e177ac52cb5d8" + +[[package]] +name = "rustls-webpki" +version = "0.102.0-alpha.3" +source = "git+https://github.com/rustls/webpki?rev=da923ed#da923edaab56f599971e58773617fb574cd019dc" dependencies = [ - "base64 0.21.2", + "ring 0.16.20", + "rustls-pki-types", + "untrusted 0.9.0", ] [[package]] name = "rustversion" -version = "1.0.12" +version = "1.0.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4f3208ce4d8448b3f3e7d168a73f5e0c43a61e32930de3bceeccedb388b6bf06" +checksum = "7ffc183a10b4478d04cbbbfc96d0873219d962dd5accaff2ffbd4ceb7df837f4" [[package]] name = "ryu" -version = "1.0.13" +version = "1.0.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f91339c0467de62360649f8d3e185ca8de4224ff281f66000de5eb2a77a79041" +checksum = "1ad4cc8da4ef723ed60bced201181d83791ad433213d8c24efffda1eec85d741" [[package]] name = "safe-lock" @@ -6896,9 +6449,9 @@ dependencies = [ [[package]] name = "safe_arch" -version = "0.7.0" +version = "0.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "62a7484307bd40f8f7ccbacccac730108f2cae119a3b11c74485b48aa9ea650f" +checksum = "f398075ce1e6a179b46f51bd88d0598b92b00d3551f1a2d4ac49e771b56ac354" dependencies = [ "bytemuck", ] @@ -6920,11 +6473,11 @@ dependencies = [ "array-bytes 4.2.0", "async-trait", "parking_lot 0.12.1", - "serde_json 1.0.106", + "serde_json 1.0.103", "sp-application-crypto", "sp-core", "sp-keystore", - "thiserror 1.0.40", + "thiserror 1.0.44", ] [[package]] @@ -6935,7 +6488,7 @@ checksum = "036575c29af9b6e4866ffb7fa055dbf623fe7a9cc159b33786de6013a6969d89" dependencies = [ "parity-scale-codec", "scale-info", - "serde 1.0.188", + "serde 1.0.193", ] [[package]] @@ -6949,7 +6502,7 @@ dependencies = [ "scale-bits", "scale-decode-derive", "scale-info", - "smallvec 1.10.0", + "smallvec 1.11.0", ] [[package]] @@ -6976,7 +6529,7 @@ dependencies = [ "scale-bits", "scale-encode-derive", "scale-info", - "smallvec 1.10.0", + "smallvec 1.11.0", ] [[package]] @@ -6994,23 +6547,23 @@ dependencies = [ [[package]] name = "scale-info" -version = "2.7.0" +version = "2.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b569c32c806ec3abdf3b5869fb8bf1e0d275a7c1c9b0b05603d9464632649edf" +checksum = "7f7d66a1128282b7ef025a8ead62a4a9fcf017382ec53b8ffbf4d7bf77bd3c60" dependencies = [ "bitvec", "cfg-if 1.0.0", "derive_more", "parity-scale-codec", "scale-info-derive", - "serde 1.0.188", + "serde 1.0.193", ] [[package]] name = "scale-info-derive" -version = "2.6.0" +version = "2.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "53012eae69e5aa5c14671942a5dd47de59d4cdcff8532a6dd0e081faf1119482" +checksum = "abf2c68b89cafb3b8d918dd07b42be0da66ff202cf1155c5739a4e0c1ea0dc19" dependencies = [ "proc-macro-crate", "proc-macro2", @@ -7020,11 +6573,11 @@ dependencies = [ [[package]] name = "schannel" -version = "0.1.21" +version = "0.1.22" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "713cfb06c7059f3588fb8044c0fad1d09e3c01d225e25b9220dbfdcf16dbb1b3" +checksum = "0c3733bf4cf7ea0880754e19cb5a462007c4a8c1914bff372ccc95b464f1df88" dependencies = [ - "windows-sys 0.42.0", + "windows-sys 0.48.0", ] [[package]] @@ -7064,15 +6617,9 @@ checksum = "e1cf6437eb19a8f4a6cc0f7dca544973b0b78843adbfeb3683d1a94a0024a294" [[package]] name = "scopeguard" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd" - -[[package]] -name = "scratch" -version = "1.0.5" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1792db035ce95be60c3f8853017b3999209281c24e2ba5bc8e59bf97a0c590c1" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" [[package]] name = "sct" @@ -7081,7 +6628,7 @@ source = "git+https://github.com/mesalock-linux/sct.rs?branch=mesalock_sgx#c4d85 dependencies = [ "ring 0.16.19", "sgx_tstd", - "untrusted", + "untrusted 0.7.1", ] [[package]] @@ -7090,18 +6637,18 @@ version = "0.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b362b83898e0e69f38515b82ee15aa80636befe47c3b6d3d89a911e78fc228ce" dependencies = [ - "ring 0.16.20 (registry+https://github.com/rust-lang/crates.io-index)", - "untrusted", + "ring 0.16.20", + "untrusted 0.7.1", ] [[package]] name = "sec1" -version = "0.7.2" +version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0aec48e813d6b90b15f0b8948af3c63483992dee44c03e9930b3eebdabe046e" +checksum = "d3e97a565f76233a6003f9f5c54be1d9c5bdfa3eccfb189469f11ec4901c47dc" dependencies = [ "base16ct", - "der 0.7.6", + "der 0.7.8", "generic-array 0.14.7", "pkcs8", "subtle", @@ -7137,11 +6684,11 @@ dependencies = [ [[package]] name = "security-framework" -version = "2.9.1" +version = "2.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fc758eb7bffce5b308734e9b0c1468893cae9ff70ebf13e7090be8dcbcc83a8" +checksum = "05b64fb303737d99b81884b2c63433e9ae28abebe5eb5045dcdd175dc2ecf4de" dependencies = [ - "bitflags", + "bitflags 1.3.2", "core-foundation", "core-foundation-sys", "libc", @@ -7150,23 +6697,14 @@ dependencies = [ [[package]] name = "security-framework-sys" -version = "2.9.0" +version = "2.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f51d0c0d83bec45f16480d0ce0058397a69e48fcdc52d1dc8855fb68acbd31a7" +checksum = "e932934257d3b408ed8f30db49d85ea163bfe74961f017f405b025af298f0c7a" dependencies = [ "core-foundation-sys", "libc", ] -[[package]] -name = "semver" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a3186ec9e65071a2095434b1f5bb24838d4e8e130f584c790f6033c79943537" -dependencies = [ - "semver-parser", -] - [[package]] name = "semver" version = "0.9.0" @@ -7178,12 +6716,9 @@ dependencies = [ [[package]] name = "semver" -version = "1.0.17" +version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bebd363326d05ec3e2f532ab7660680f3b02130d780c299bca73469d521bc0ed" -dependencies = [ - "serde 1.0.188", -] +checksum = "b0293b4b29daaf487284529cc2f5675b8e57c61f70167ba415a463651fd6a918" [[package]] name = "semver-parser" @@ -7191,14 +6726,6 @@ version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "388a1df253eca08550bef6c72392cfe7c30914bf41df5269b68cbd6ff8f570a3" -[[package]] -name = "serde" -version = "1.0.118" -source = "git+https://github.com/mesalock-linux/serde-sgx?tag=sgx_1.1.3#db0226f1d5d70fca6b96af2c285851502204e21c" -dependencies = [ - "sgx_tstd", -] - [[package]] name = "serde" version = "1.0.118" @@ -7210,11 +6737,11 @@ dependencies = [ [[package]] name = "serde" -version = "1.0.188" +version = "1.0.193" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf9e0fcba69a370eed61bcf2b728575f726b50b55cba78064753d708ddc7549e" +checksum = "25dd9975e68d0cb5aa1120c288333fc98731bd1dd12f561e468ea4728c042b89" dependencies = [ - "serde_derive 1.0.188", + "serde_derive 1.0.193", ] [[package]] @@ -7223,8 +6750,8 @@ version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b926cfbabfe8011609dda0350cb24d884955d294909ac71c0db7027366c77e3e" dependencies = [ - "serde 1.0.188", - "serde_derive 1.0.188", + "serde 1.0.193", + "serde_derive 1.0.193", ] [[package]] @@ -7232,7 +6759,7 @@ 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 (git+https://github.com/mesalock-linux/serde-sgx)", + "serde 1.0.118", "serde_derive 1.0.118", ] @@ -7248,9 +6775,9 @@ dependencies = [ [[package]] name = "serde_derive" -version = "1.0.188" +version = "1.0.193" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4eca7ac642d82aa35b60049a6eccb4be6be75e599bd2e9adb5f875a737654af2" +checksum = "43576ca501357b9b071ac53cdc7da8ef0cbd9493d8df094cd821777ea6e894d3" dependencies = [ "proc-macro2", "quote", @@ -7265,7 +6792,7 @@ dependencies = [ "indexmap 1.6.1", "itoa 0.4.5", "ryu", - "serde 1.0.118 (git+https://github.com/mesalock-linux/serde-sgx)", + "serde 1.0.118", "sgx_tstd", ] @@ -7276,29 +6803,20 @@ source = "git+https://github.com/mesalock-linux/serde-json-sgx#380893814ad2a0577 dependencies = [ "itoa 0.4.5", "ryu", - "serde 1.0.118 (git+https://github.com/mesalock-linux/serde-sgx)", + "serde 1.0.118", "sgx_tstd", ] [[package]] name = "serde_json" -version = "1.0.106" +version = "1.0.103" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2cc66a619ed80bf7a0f6b17dd063a84b88f6dea1813737cf469aef1d081142c2" +checksum = "d03b412469450d4404fe8499a268edd7f8b79fecb074b0d812ad64ca21f4031b" dependencies = [ "indexmap 2.0.0", - "itoa 1.0.6", + "itoa 1.0.9", "ryu", - "serde 1.0.188", -] - -[[package]] -name = "serde_spanned" -version = "0.6.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "93107647184f6027e3b7dcb2e11034cf95ffa1e3a682c67951963ac69c1c007d" -dependencies = [ - "serde 1.0.188", + "serde 1.0.193", ] [[package]] @@ -7308,15 +6826,15 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" dependencies = [ "form_urlencoded", - "itoa 1.0.6", + "itoa 1.0.9", "ryu", - "serde 1.0.188", + "serde 1.0.193", ] [[package]] name = "sgx-verify" version = "0.1.4" -source = "git+https://github.com/integritee-network/pallets.git?branch=sdk-v0.12.0-polkadot-v0.9.42#eaf611b79bc9d56b20c155150e99b549bf98436b" +source = "git+https://github.com/integritee-network/pallets.git?branch=sdk-v0.12.11-polkadot-v0.9.42#094b1e982b4637ebfbf5afb985100417215d49a0" dependencies = [ "base64 0.13.1", "chrono 0.4.26", @@ -7324,29 +6842,29 @@ dependencies = [ "frame-support", "hex", "hex-literal", - "log 0.4.19", + "log 0.4.20", "parity-scale-codec", - "ring 0.16.20 (git+https://github.com/Niederb/ring-xous.git?branch=0.16.20-cleanup)", + "ring 0.16.20", + "rustls-webpki", "scale-info", - "serde 1.0.188", - "serde_json 1.0.106", + "serde 1.0.193", + "serde_json 1.0.103", "sp-core", "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", "sp-std", "teerex-primitives", - "webpki 0.21.0", "x509-cert", ] [[package]] name = "sgx_alloc" version = "1.1.6" -source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#f1776a7cec1caab2959813f87bb4924805b92011" +source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#3c903bdac4e503dd27b9b1f761c4abfc55f2464c" [[package]] name = "sgx_backtrace_sys" version = "1.1.6" -source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#f1776a7cec1caab2959813f87bb4924805b92011" +source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#3c903bdac4e503dd27b9b1f761c4abfc55f2464c" dependencies = [ "cc", "sgx_build_helper", @@ -7356,21 +6874,21 @@ dependencies = [ [[package]] name = "sgx_build_helper" version = "1.1.6" -source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#f1776a7cec1caab2959813f87bb4924805b92011" +source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#3c903bdac4e503dd27b9b1f761c4abfc55f2464c" [[package]] name = "sgx_crypto_helper" version = "1.1.6" -source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#f1776a7cec1caab2959813f87bb4924805b92011" +source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#3c903bdac4e503dd27b9b1f761c4abfc55f2464c" dependencies = [ - "itertools", + "itertools 0.11.0", "libc", - "serde 1.0.118 (git+https://github.com/mesalock-linux/serde-sgx)", - "serde 1.0.188", + "serde 1.0.118", + "serde 1.0.193", "serde-big-array 0.1.5", "serde-big-array 0.3.0", "serde_derive 1.0.118", - "serde_derive 1.0.188", + "serde_derive 1.0.193", "sgx_tcrypto", "sgx_tstd", "sgx_types", @@ -7380,12 +6898,12 @@ dependencies = [ [[package]] name = "sgx_demangle" version = "1.1.6" -source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#f1776a7cec1caab2959813f87bb4924805b92011" +source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#3c903bdac4e503dd27b9b1f761c4abfc55f2464c" [[package]] name = "sgx_libc" version = "1.1.6" -source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#f1776a7cec1caab2959813f87bb4924805b92011" +source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#3c903bdac4e503dd27b9b1f761c4abfc55f2464c" dependencies = [ "sgx_types", ] @@ -7393,7 +6911,7 @@ dependencies = [ [[package]] name = "sgx_rand" version = "1.1.6" -source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#f1776a7cec1caab2959813f87bb4924805b92011" +source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#3c903bdac4e503dd27b9b1f761c4abfc55f2464c" dependencies = [ "sgx_trts", "sgx_tstd", @@ -7403,7 +6921,7 @@ dependencies = [ [[package]] name = "sgx_tcrypto" version = "1.1.6" -source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#f1776a7cec1caab2959813f87bb4924805b92011" +source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#3c903bdac4e503dd27b9b1f761c4abfc55f2464c" dependencies = [ "sgx_types", ] @@ -7411,7 +6929,7 @@ dependencies = [ [[package]] name = "sgx_tprotected_fs" version = "1.1.6" -source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#f1776a7cec1caab2959813f87bb4924805b92011" +source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#3c903bdac4e503dd27b9b1f761c4abfc55f2464c" dependencies = [ "sgx_trts", "sgx_types", @@ -7420,7 +6938,7 @@ dependencies = [ [[package]] name = "sgx_trts" version = "1.1.6" -source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#f1776a7cec1caab2959813f87bb4924805b92011" +source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#3c903bdac4e503dd27b9b1f761c4abfc55f2464c" dependencies = [ "sgx_libc", "sgx_types", @@ -7429,7 +6947,7 @@ dependencies = [ [[package]] name = "sgx_tse" version = "1.1.6" -source = "git+https://github.com/apache/teaclave-sgx-sdk.git?branch=master#f1776a7cec1caab2959813f87bb4924805b92011" +source = "git+https://github.com/apache/teaclave-sgx-sdk.git?branch=master#3c903bdac4e503dd27b9b1f761c4abfc55f2464c" dependencies = [ "sgx_types", ] @@ -7437,7 +6955,7 @@ dependencies = [ [[package]] name = "sgx_tstd" version = "1.1.6" -source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#f1776a7cec1caab2959813f87bb4924805b92011" +source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#3c903bdac4e503dd27b9b1f761c4abfc55f2464c" dependencies = [ "hashbrown_tstd", "sgx_alloc", @@ -7453,12 +6971,12 @@ dependencies = [ [[package]] name = "sgx_types" version = "1.1.6" -source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#f1776a7cec1caab2959813f87bb4924805b92011" +source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#3c903bdac4e503dd27b9b1f761c4abfc55f2464c" [[package]] name = "sgx_ucrypto" version = "1.1.6" -source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#f1776a7cec1caab2959813f87bb4924805b92011" +source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#3c903bdac4e503dd27b9b1f761c4abfc55f2464c" dependencies = [ "libc", "rand_core 0.3.1", @@ -7469,7 +6987,7 @@ dependencies = [ [[package]] name = "sgx_unwind" version = "1.1.6" -source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#f1776a7cec1caab2959813f87bb4924805b92011" +source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#3c903bdac4e503dd27b9b1f761c4abfc55f2464c" dependencies = [ "sgx_build_helper", ] @@ -7477,7 +6995,7 @@ dependencies = [ [[package]] name = "sgx_urts" version = "1.1.6" -source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#f1776a7cec1caab2959813f87bb4924805b92011" +source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#3c903bdac4e503dd27b9b1f761c4abfc55f2464c" dependencies = [ "libc", "sgx_types", @@ -7527,18 +7045,6 @@ dependencies = [ "digest 0.10.7", ] -[[package]] -name = "sha2" -version = "0.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9eb6be24e4c23a84d7184280d2722f7f2731fcdd4a9d886efbfe4413e4847ea0" -dependencies = [ - "block-buffer 0.3.3", - "byte-tools 0.2.0", - "digest 0.7.6", - "fake-simd", -] - [[package]] name = "sha2" version = "0.8.2" @@ -7566,9 +7072,9 @@ dependencies = [ [[package]] name = "sha2" -version = "0.10.6" +version = "0.10.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "82e6b795fe2e3b1e845bafcb27aa35405c4d47cdfc92af5fc8d3002f76cebdc0" +checksum = "479fb9d862239e610720565ca91403019f2f00410f1864c5aa7479b950a76ed8" dependencies = [ "cfg-if 1.0.0", "cpufeatures", @@ -7603,11 +7109,11 @@ checksum = "43b2853a4d09f215c24cc5489c992ce46052d359b5109343cbafbf26bc62f8a3" [[package]] name = "sidechain-primitives" version = "0.1.0" -source = "git+https://github.com/integritee-network/pallets.git?branch=sdk-v0.12.0-polkadot-v0.9.42#eaf611b79bc9d56b20c155150e99b549bf98436b" +source = "git+https://github.com/integritee-network/pallets.git?branch=sdk-v0.12.11-polkadot-v0.9.42#094b1e982b4637ebfbf5afb985100417215d49a0" dependencies = [ "parity-scale-codec", "scale-info", - "serde 1.0.188", + "serde 1.0.193", "sp-core", "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", "sp-runtime", @@ -7647,7 +7153,7 @@ checksum = "061507c94fc6ab4ba1c9a0305018408e312e17c041eb63bef8aa726fa33aceae" dependencies = [ "approx", "num-complex 0.4.3", - "num-traits 0.2.15", + "num-traits 0.2.16", "paste", "wide", ] @@ -7659,8 +7165,8 @@ source = "git+https://github.com/BESTenergytrade/simplyr-lib.git?branch=cI/usize dependencies = [ "libm", "parity-scale-codec", - "serde 1.0.188", - "serde_json 1.0.106", + "serde 1.0.193", + "serde_json 1.0.103", ] [[package]] @@ -7690,9 +7196,9 @@ dependencies = [ [[package]] name = "smallvec" -version = "1.10.0" +version = "1.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a507befe795404456341dfab10cef66ead4c041f62b8b11bbb92bffe5d0953e0" +checksum = "62bb4feee49fdd9f707ef802e22365a35de4b7b299de4763d44bfea899442ff9" [[package]] name = "socket2" @@ -7714,7 +7220,7 @@ dependencies = [ "bytes 1.4.0", "futures 0.3.28", "httparse 1.8.0", - "log 0.4.19", + "log 0.4.20", "rand 0.8.5", "sha-1 0.9.8", ] @@ -7725,7 +7231,7 @@ version = "4.0.0-dev" source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "hash-db 0.16.0", - "log 0.4.19", + "log 0.4.20", "parity-scale-codec", "scale-info", "sp-api-proc-macro", @@ -7736,7 +7242,7 @@ dependencies = [ "sp-std", "sp-trie", "sp-version", - "thiserror 1.0.40", + "thiserror 1.0.44", ] [[package]] @@ -7760,7 +7266,7 @@ source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.4 dependencies = [ "parity-scale-codec", "scale-info", - "serde 1.0.188", + "serde 1.0.193", "sp-core", "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", "sp-std", @@ -7772,10 +7278,10 @@ version = "6.0.0" source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "integer-sqrt", - "num-traits 0.2.15", + "num-traits 0.2.16", "parity-scale-codec", "scale-info", - "serde 1.0.188", + "serde 1.0.193", "sp-std", "static_assertions", ] @@ -7799,12 +7305,12 @@ source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.4 dependencies = [ "async-trait", "futures 0.3.28", - "log 0.4.19", + "log 0.4.20", "sp-core", "sp-inherents", "sp-runtime", "sp-state-machine", - "thiserror 1.0.40", + "thiserror 1.0.44", ] [[package]] @@ -7831,10 +7337,10 @@ version = "4.0.0-dev" source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "finality-grandpa", - "log 0.4.19", + "log 0.4.20", "parity-scale-codec", "scale-info", - "serde 1.0.188", + "serde 1.0.193", "sp-api", "sp-application-crypto", "sp-core", @@ -7850,7 +7356,7 @@ source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.4 dependencies = [ "parity-scale-codec", "scale-info", - "serde 1.0.188", + "serde 1.0.193", "sp-std", "sp-timestamp", ] @@ -7861,7 +7367,7 @@ version = "7.0.0" source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "array-bytes 4.2.0", - "bitflags", + "bitflags 1.3.2", "blake2", "bounded-collections", "bs58", @@ -7873,7 +7379,7 @@ dependencies = [ "impl-serde", "lazy_static", "libsecp256k1", - "log 0.4.19", + "log 0.4.20", "merlin", "parity-scale-codec", "parking_lot 0.12.1", @@ -7885,7 +7391,7 @@ dependencies = [ "schnorrkel", "secp256k1", "secrecy", - "serde 1.0.188", + "serde 1.0.193", "sp-core-hashing", "sp-debug-derive", "sp-externalities", @@ -7894,7 +7400,7 @@ dependencies = [ "sp-storage", "ss58-registry", "substrate-bip39", - "thiserror 1.0.40", + "thiserror 1.0.44", "tiny-bip39", "zeroize", ] @@ -7907,7 +7413,7 @@ dependencies = [ "blake2b_simd", "byteorder 1.4.3", "digest 0.10.7", - "sha2 0.10.6", + "sha2 0.10.7", "sha3", "sp-std", "twox-hash", @@ -7957,30 +7463,19 @@ dependencies = [ "sp-core", "sp-runtime", "sp-std", - "thiserror 1.0.40", + "thiserror 1.0.44", ] [[package]] name = "sp-io" version = "7.0.0" dependencies = [ - "environmental 1.1.3", - "futures 0.3.28", - "hash-db 0.15.2", "itp-sgx-externalities", "libsecp256k1", - "log 0.4.19", + "log 0.4.20", "parity-scale-codec", - "parking_lot 0.12.1", "sgx_tstd", - "sgx_types", "sp-core", - "sp-runtime-interface", - "sp-std", - "sp-tracing", - "sp-wasm-interface", - "tracing", - "tracing-core", ] [[package]] @@ -7993,7 +7488,7 @@ dependencies = [ "ed25519-dalek", "futures 0.3.28", "libsecp256k1", - "log 0.4.19", + "log 0.4.20", "parity-scale-codec", "rustversion", "secp256k1", @@ -8028,19 +7523,10 @@ dependencies = [ "futures 0.3.28", "parity-scale-codec", "parking_lot 0.12.1", - "serde 1.0.188", + "serde 1.0.193", "sp-core", "sp-externalities", - "thiserror 1.0.40", -] - -[[package]] -name = "sp-maybe-compressed-blob" -version = "4.1.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" -dependencies = [ - "thiserror 1.0.40", - "zstd", + "thiserror 1.0.44", ] [[package]] @@ -8082,12 +7568,12 @@ dependencies = [ "either", "hash256-std-hasher", "impl-trait-for-tuples", - "log 0.4.19", + "log 0.4.20", "parity-scale-codec", "paste", "rand 0.8.5", "scale-info", - "serde 1.0.188", + "serde 1.0.193", "sp-application-crypto", "sp-arithmetic", "sp-core", @@ -8135,7 +7621,6 @@ dependencies = [ "scale-info", "sp-api", "sp-core", - "sp-runtime", "sp-staking", "sp-std", ] @@ -8147,7 +7632,7 @@ source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.4 dependencies = [ "parity-scale-codec", "scale-info", - "serde 1.0.188", + "serde 1.0.193", "sp-core", "sp-runtime", "sp-std", @@ -8159,17 +7644,17 @@ version = "0.13.0" source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "hash-db 0.16.0", - "log 0.4.19", + "log 0.4.20", "parity-scale-codec", "parking_lot 0.12.1", "rand 0.8.5", - "smallvec 1.10.0", + "smallvec 1.11.0", "sp-core", "sp-externalities", "sp-panic-handler", "sp-std", "sp-trie", - "thiserror 1.0.40", + "thiserror 1.0.44", "tracing", ] @@ -8186,7 +7671,7 @@ dependencies = [ "impl-serde", "parity-scale-codec", "ref-cast", - "serde 1.0.188", + "serde 1.0.193", "sp-debug-derive", "sp-std", ] @@ -8198,12 +7683,12 @@ source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.4 dependencies = [ "async-trait", "futures-timer", - "log 0.4.19", + "log 0.4.20", "parity-scale-codec", "sp-inherents", "sp-runtime", "sp-std", - "thiserror 1.0.40", + "thiserror 1.0.44", ] [[package]] @@ -8244,7 +7729,7 @@ dependencies = [ "schnellru", "sp-core", "sp-std", - "thiserror 1.0.40", + "thiserror 1.0.44", "tracing", "trie-db", "trie-root", @@ -8259,12 +7744,12 @@ dependencies = [ "parity-scale-codec", "parity-wasm", "scale-info", - "serde 1.0.188", + "serde 1.0.193", "sp-core-hashing-proc-macro", "sp-runtime", "sp-std", "sp-version-proc-macro", - "thiserror 1.0.40", + "thiserror 1.0.44", ] [[package]] @@ -8285,7 +7770,7 @@ source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.4 dependencies = [ "anyhow", "impl-trait-for-tuples", - "log 0.4.19", + "log 0.4.20", "parity-scale-codec", "sp-std", "wasmi", @@ -8299,8 +7784,8 @@ source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.4 dependencies = [ "parity-scale-codec", "scale-info", - "serde 1.0.188", - "smallvec 1.10.0", + "serde 1.0.193", + "smallvec 1.11.0", "sp-arithmetic", "sp-core", "sp-debug-derive", @@ -8336,21 +7821,21 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9d1e996ef02c474957d681f1b05213dfb0abab947b446a62d37770b23500184a" dependencies = [ "base64ct", - "der 0.7.6", + "der 0.7.8", ] [[package]] name = "ss58-registry" -version = "1.40.0" +version = "1.41.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eb47a8ad42e5fc72d5b1eb104a5546937eaf39843499948bb666d6e93c62423b" +checksum = "bfc443bad666016e012538782d9e3006213a7db43e9fb1dda91657dc06a6fa08" dependencies = [ "Inflector", "num-format", "proc-macro2", "quote", - "serde 1.0.188", - "serde_json 1.0.106", + "serde 1.0.193", + "serde_json 1.0.103", "unicode-xid", ] @@ -8413,16 +7898,16 @@ dependencies = [ "frame-metadata", "frame-support", "hex", - "log 0.4.19", + "log 0.4.20", "maybe-async", "parity-scale-codec", - "serde 1.0.188", - "serde_json 1.0.106", + "serde 1.0.193", + "serde_json 1.0.103", "sp-core", "sp-runtime", "sp-runtime-interface", "tungstenite 0.18.0", - "url 2.4.0", + "url 2.5.0", ] [[package]] @@ -8447,7 +7932,7 @@ dependencies = [ "async-trait", "parking_lot 0.12.1", "sc-keystore", - "serde_json 1.0.106", + "serde_json 1.0.103", "sp-application-crypto", "sp-core", "sp-keyring", @@ -8461,27 +7946,10 @@ source = "git+https://github.com/encointer/substrate-fixed?tag=v0.5.9#a4fb461aae dependencies = [ "parity-scale-codec", "scale-info", - "serde 1.0.188", + "serde 1.0.193", "typenum 1.16.0 (git+https://github.com/encointer/typenum?tag=v1.16.0)", ] -[[package]] -name = "substrate-wasm-builder" -version = "5.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" -dependencies = [ - "ansi_term", - "build-helper", - "cargo_metadata", - "filetime", - "sp-maybe-compressed-blob", - "strum", - "tempfile", - "toml", - "walkdir", - "wasm-opt", -] - [[package]] name = "subtle" version = "2.4.1" @@ -8530,14 +7998,14 @@ checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369" [[package]] name = "target-lexicon" -version = "0.12.7" +version = "0.12.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fd1ba337640d60c3e96bc6f0638a939b9c9a7f2c316a1598c279828b3d1dc8c5" +checksum = "1d2faeef5759ab89935255b1a4cd98e0baf99d1085e37d36599c625dac49ae8e" [[package]] name = "teeracle-primitives" version = "0.1.0" -source = "git+https://github.com/integritee-network/pallets.git?branch=sdk-v0.12.0-polkadot-v0.9.42#eaf611b79bc9d56b20c155150e99b549bf98436b" +source = "git+https://github.com/integritee-network/pallets.git?branch=sdk-v0.12.11-polkadot-v0.9.42#094b1e982b4637ebfbf5afb985100417215d49a0" dependencies = [ "common-primitives", "sp-std", @@ -8547,14 +8015,14 @@ dependencies = [ [[package]] name = "teerex-primitives" version = "0.1.0" -source = "git+https://github.com/integritee-network/pallets.git?branch=sdk-v0.12.0-polkadot-v0.9.42#eaf611b79bc9d56b20c155150e99b549bf98436b" +source = "git+https://github.com/integritee-network/pallets.git?branch=sdk-v0.12.11-polkadot-v0.9.42#094b1e982b4637ebfbf5afb985100417215d49a0" dependencies = [ "common-primitives", "derive_more", - "log 0.4.19", + "log 0.4.20", "parity-scale-codec", "scale-info", - "serde 1.0.188", + "serde 1.0.193", "sp-core", "sp-runtime", "sp-std", @@ -8568,15 +8036,14 @@ checksum = "af547b166dd1ea4b472165569fc456cfb6818116f854690b0ff205e636523dab" [[package]] name = "tempfile" -version = "3.6.0" +version = "3.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "31c0432476357e58790aaa47a8efb0c5138f137343f3b5f23bd36a27e3b0a6d6" +checksum = "5486094ee78b2e5038a6382ed7645bc084dc2ec433426ca4c3cb61e2007b8998" dependencies = [ - "autocfg 1.1.0", "cfg-if 1.0.0", "fastrand", "redox_syscall 0.3.5", - "rustix 0.37.20", + "rustix 0.38.4", "windows-sys 0.48.0", ] @@ -8621,11 +8088,11 @@ dependencies = [ [[package]] name = "thiserror" -version = "1.0.40" +version = "1.0.44" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "978c9a314bd8dc99be594bc3c175faaa9794be04a5a5e153caba6915336cebac" +checksum = "611040a08a0439f8248d1990b111c95baa9c704c805fa1f62104b39655fd7f90" dependencies = [ - "thiserror-impl 1.0.40", + "thiserror-impl 1.0.44", ] [[package]] @@ -8640,9 +8107,9 @@ dependencies = [ [[package]] name = "thiserror-impl" -version = "1.0.40" +version = "1.0.44" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f9456a42c5b0d803c8cd86e73dd7cc9edd429499f37a3550d286d5e86720569f" +checksum = "090198534930841fab3a5d1bb637cde49e339654e606195f8d9c76eeb081dc96" dependencies = [ "proc-macro2", "quote", @@ -8682,8 +8149,8 @@ dependencies = [ "pbkdf2 0.11.0", "rand 0.8.5", "rustc-hash", - "sha2 0.10.6", - "thiserror 1.0.40", + "sha2 0.10.7", + "thiserror 1.0.44", "unicode-normalization 0.1.22", "wasm-bindgen", "zeroize", @@ -8715,11 +8182,12 @@ checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" [[package]] name = "tokio" -version = "1.28.2" +version = "1.29.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94d7b1cfd2aa4011f2de74c2c4c63665e27a71006b0a192dcd2710272e73dfa2" +checksum = "532826ff75199d5833b9d2c5fe410f29235e25704ee5f0ef599fb51c21f4a4da" dependencies = [ "autocfg 1.1.0", + "backtrace", "bytes 1.4.0", "libc", "mio 0.8.8", @@ -8782,7 +8250,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "54319c93411147bced34cb5609a80e0a8e44c5999c93903a81cd866630ec0bfd" dependencies = [ "futures-util 0.3.28", - "log 0.4.19", + "log 0.4.20", "tokio", "tungstenite 0.18.0", ] @@ -8797,7 +8265,7 @@ dependencies = [ "futures-core 0.3.28", "futures-io 0.3.28", "futures-sink 0.3.28", - "log 0.4.19", + "log 0.4.20", "pin-project-lite", "tokio", ] @@ -8816,36 +8284,19 @@ dependencies = [ "tracing", ] -[[package]] -name = "toml" -version = "0.7.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d6135d499e69981f9ff0ef2167955a5333c35e36f6937d382974566b3d5b94ec" -dependencies = [ - "serde 1.0.188", - "serde_spanned", - "toml_datetime", - "toml_edit", -] - [[package]] name = "toml_datetime" -version = "0.6.2" +version = "0.6.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a76a9312f5ba4c2dec6b9161fdf25d87ad8a09256ccea5a556fef03c706a10f" -dependencies = [ - "serde 1.0.188", -] +checksum = "7cda73e2f1397b1262d6dfdcef8aafae14d1de7748d66822d3bfeeb6d03e5e4b" [[package]] name = "toml_edit" -version = "0.19.10" +version = "0.19.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2380d56e8670370eee6566b0bfd4265f65b3f432e8c6d85623f728d4fa31f739" +checksum = "1b5bb770da30e5cbfde35a2d7b9b8a2c4b8ef89548a7a6aeab5c9a576e3e7421" dependencies = [ - "indexmap 1.9.3", - "serde 1.0.188", - "serde_spanned", + "indexmap 2.0.0", "toml_datetime", "winnow", ] @@ -8863,7 +8314,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8ce8c33a8d48bd45d624a6e523445fd21ec13d3653cd51f681abf67418f54eb8" dependencies = [ "cfg-if 1.0.0", - "log 0.4.19", + "log 0.4.20", "pin-project-lite", "tracing-attributes", "tracing-core", @@ -8871,9 +8322,9 @@ dependencies = [ [[package]] name = "tracing-attributes" -version = "0.1.24" +version = "0.1.26" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0f57e3ca2a01450b1a921183a9c9cbfda207fd822cef4ccb00a65402cbba7a74" +checksum = "5f4f31f56159e98206da9efd823404b79b6ef3143b4a7ab76e67b1751b25a4ab" dependencies = [ "proc-macro2", "quote", @@ -8897,7 +8348,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "78ddad33d2d10b1ed7eb9d1f518a5674713876e97e5bb9b7345a7984fbb4f922" dependencies = [ "lazy_static", - "log 0.4.19", + "log 0.4.20", "tracing-core", ] @@ -8907,7 +8358,7 @@ version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bc6b213177105856957181934e4920de57730fc69bf42c37ee5bb664d406d9e1" dependencies = [ - "serde 1.0.188", + "serde 1.0.193", "tracing-core", ] @@ -8922,10 +8373,10 @@ dependencies = [ "lazy_static", "matchers", "regex 1.9.5", - "serde 1.0.188", - "serde_json 1.0.106", + "serde 1.0.193", + "serde_json 1.0.103", "sharded-slab", - "smallvec 1.10.0", + "smallvec 1.11.0", "thread_local", "tracing", "tracing-core", @@ -8941,9 +8392,9 @@ checksum = "767abe6ffed88a1889671a102c2861ae742726f52e0a5a425b92c9fbfa7e9c85" dependencies = [ "hash-db 0.16.0", "hashbrown 0.13.2", - "log 0.4.19", + "log 0.4.20", "rustc-hex", - "smallvec 1.10.0", + "smallvec 1.11.0", ] [[package]] @@ -9010,12 +8461,12 @@ dependencies = [ "bytes 1.4.0", "http 0.2.9", "httparse 1.8.0", - "log 0.4.19", + "log 0.4.20", "rand 0.8.5", "rustls 0.19.1", "sha-1 0.9.8", - "thiserror 1.0.40", - "url 2.4.0", + "thiserror 1.0.44", + "url 2.5.0", "utf-8 0.7.6", "webpki 0.21.4 (registry+https://github.com/rust-lang/crates.io-index)", "webpki-roots 0.21.1", @@ -9032,12 +8483,12 @@ dependencies = [ "bytes 1.4.0", "http 0.2.9", "httparse 1.8.0", - "log 0.4.19", + "log 0.4.20", "native-tls", "rand 0.8.5", "sha1 0.10.5", - "thiserror 1.0.40", - "url 2.4.0", + "thiserror 1.0.44", + "url 2.5.0", "utf-8 0.7.6", ] @@ -9126,9 +8577,9 @@ checksum = "92888ba5573ff080736b3648696b70cafad7d250551175acbaa4e0385b3e1460" [[package]] name = "unicode-ident" -version = "1.0.9" +version = "1.0.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b15811caf2415fb889178633e7724bad2509101cde276048e013b9def5e51fa0" +checksum = "301abaae475aa91687eb82514b328ab47a211a533026cb25fc3e519b86adfc3c" [[package]] name = "unicode-normalization" @@ -9177,6 +8628,12 @@ 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" @@ -9190,13 +8647,13 @@ dependencies = [ [[package]] name = "url" -version = "2.4.0" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "50bff7831e19200a85b17131d085c25d7811bc4e186efdaf54bbd132994a88cb" +checksum = "31e6302e3bb753d46e83516cae55ae196fc0c309407cf11ab35cc51a4c2a4633" dependencies = [ "form_urlencoded", - "idna 0.4.0", - "percent-encoding 2.3.0", + "idna 0.5.0", + "percent-encoding 2.3.1", ] [[package]] @@ -9255,11 +8712,10 @@ dependencies = [ [[package]] name = "want" -version = "0.3.0" +version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ce8a968cb1cd110d136ff8b819a556d6fb6d919363c61534f6860c7eb172ba0" +checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e" dependencies = [ - "log 0.4.19", "try-lock", ] @@ -9275,16 +8731,16 @@ dependencies = [ "headers", "http 0.2.9", "hyper", - "log 0.4.19", + "log 0.4.20", "mime", "mime_guess", "multer", - "percent-encoding 2.3.0", + "percent-encoding 2.3.1", "pin-project", "rustls-pemfile", "scoped-tls", - "serde 1.0.188", - "serde_json 1.0.106", + "serde 1.0.193", + "serde_json 1.0.103", "serde_urlencoded", "tokio", "tokio-stream", @@ -9329,7 +8785,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5ef2b6d3c510e9625e5fe6f509ab07d66a760f0885d858736483c32ed7809abd" dependencies = [ "bumpalo", - "log 0.4.19", + "log 0.4.20", "once_cell 1.18.0", "proc-macro2", "quote", @@ -9378,47 +8834,6 @@ version = "0.2.87" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ca6ad05a4870b2bf5fe995117d3728437bd27d7cd5f06f13c17443ef369775a1" -[[package]] -name = "wasm-opt" -version = "0.111.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "84a303793cbc01fb96551badfc7367db6007396bba6bac97936b3c8b6f7fdb41" -dependencies = [ - "anyhow", - "libc", - "strum", - "strum_macros", - "tempfile", - "thiserror 1.0.40", - "wasm-opt-cxx-sys", - "wasm-opt-sys", -] - -[[package]] -name = "wasm-opt-cxx-sys" -version = "0.111.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d9c9deb56f8a9f2ec177b3bd642a8205621835944ed5da55f2388ef216aca5a4" -dependencies = [ - "anyhow", - "cxx", - "cxx-build", - "wasm-opt-sys", -] - -[[package]] -name = "wasm-opt-sys" -version = "0.111.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4432e28b542738a9776cedf92e8a99d8991c7b4667ee2c7ccddfb479dd2856a7" -dependencies = [ - "anyhow", - "cc", - "cxx", - "cxx-build", - "regex 1.9.5", -] - [[package]] name = "wasmi" version = "0.13.2" @@ -9449,7 +8864,7 @@ dependencies = [ "libm", "memory_units", "num-rational 0.4.1", - "num-traits 0.2.15", + "num-traits 0.2.16", ] [[package]] @@ -9459,7 +8874,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "64b20236ab624147dfbb62cf12a19aaf66af0e41b8398838b66e997d07d269d4" dependencies = [ "indexmap 1.9.3", - "url 2.4.0", + "url 2.5.0", ] [[package]] @@ -9473,12 +8888,12 @@ dependencies = [ "cfg-if 1.0.0", "indexmap 1.9.3", "libc", - "log 0.4.19", + "log 0.4.20", "object 0.29.0", "once_cell 1.18.0", "paste", "psm", - "serde 1.0.188", + "serde 1.0.193", "target-lexicon", "wasmparser", "wasmtime-environ", @@ -9506,11 +8921,11 @@ dependencies = [ "cranelift-entity", "gimli 0.26.2", "indexmap 1.9.3", - "log 0.4.19", + "log 0.4.20", "object 0.29.0", - "serde 1.0.188", + "serde 1.0.193", "target-lexicon", - "thiserror 1.0.40", + "thiserror 1.0.44", "wasmparser", "wasmtime-types", ] @@ -9527,10 +8942,10 @@ dependencies = [ "cfg-if 1.0.0", "cpp_demangle", "gimli 0.26.2", - "log 0.4.19", + "log 0.4.20", "object 0.29.0", "rustc-demangle", - "serde 1.0.188", + "serde 1.0.193", "target-lexicon", "wasmtime-environ", "wasmtime-jit-icache-coherence", @@ -9569,13 +8984,13 @@ dependencies = [ "cfg-if 1.0.0", "indexmap 1.9.3", "libc", - "log 0.4.19", + "log 0.4.20", "mach", "memfd", "memoffset 0.6.5", "paste", "rand 0.8.5", - "rustix 0.36.14", + "rustix 0.36.15", "wasmtime-asm-macros", "wasmtime-environ", "wasmtime-jit-debug", @@ -9589,8 +9004,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "83e5572c5727c1ee7e8f28717aaa8400e4d22dcbd714ea5457d85b5005206568" dependencies = [ "cranelift-entity", - "serde 1.0.188", - "thiserror 1.0.40", + "serde 1.0.193", + "thiserror 1.0.44", "wasmparser", ] @@ -9604,24 +9019,14 @@ dependencies = [ "wasm-bindgen", ] -[[package]] -name = "webpki" -version = "0.21.0" -source = "git+https://github.com/scs/webpki-nostd.git?branch=master#22d1772c39ed9081c2815aadb30e7973f3c4e93f" -dependencies = [ - "ring 0.16.20 (registry+https://github.com/rust-lang/crates.io-index)", - "ring 0.16.20 (git+https://github.com/Niederb/ring-xous.git?branch=0.16.20-cleanup)", - "untrusted", -] - [[package]] name = "webpki" version = "0.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b8e38c0608262c46d4a56202ebabdeb094cef7e560ca7a226c6bf055188aa4ea" dependencies = [ - "ring 0.16.20 (registry+https://github.com/rust-lang/crates.io-index)", - "untrusted", + "ring 0.16.20", + "untrusted 0.7.1", ] [[package]] @@ -9631,7 +9036,7 @@ source = "git+https://github.com/mesalock-linux/webpki?branch=mesalock_sgx#8dbe6 dependencies = [ "ring 0.16.19", "sgx_tstd", - "untrusted", + "untrusted 0.7.1", ] [[package]] @@ -9663,9 +9068,9 @@ dependencies = [ [[package]] name = "wide" -version = "0.7.10" +version = "0.7.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "40018623e2dba2602a9790faba8d33f2ebdebf4b86561b83928db735f8784728" +checksum = "aa469ffa65ef7e0ba0f164183697b89b854253fd31aeb92358b7b6155177d62f" dependencies = [ "bytemuck", "safe_arch", @@ -9720,7 +9125,7 @@ version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e686886bc078bc1b0b600cac0147aadb815089b6e4da64016cbd754b6342700f" dependencies = [ - "windows-targets 0.48.0", + "windows-targets 0.48.1", ] [[package]] @@ -9753,7 +9158,7 @@ version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" dependencies = [ - "windows-targets 0.48.0", + "windows-targets 0.48.1", ] [[package]] @@ -9773,9 +9178,9 @@ dependencies = [ [[package]] name = "windows-targets" -version = "0.48.0" +version = "0.48.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b1eb6f0cd7c80c79759c929114ef071b87354ce476d9d94271031c0497adfd5" +checksum = "05d4b17490f70499f20b9e791dcf6a299785ce8af4d709018206dc5b4953e95f" dependencies = [ "windows_aarch64_gnullvm 0.48.0", "windows_aarch64_msvc 0.48.0", @@ -9872,9 +9277,9 @@ checksum = "1a515f5799fe4961cb532f983ce2b23082366b898e52ffbce459c86f67c8378a" [[package]] name = "winnow" -version = "0.4.6" +version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61de7bac303dc551fe038e2b3cef0f571087a47571ea6e79a87692ac99b99699" +checksum = "25b5872fa2e10bd067ae946f927e726d7d603eaeb6e02fa6a350e0722d2b8c11" dependencies = [ "memchr 2.6.3", ] @@ -9898,14 +9303,14 @@ dependencies = [ "byteorder 1.4.3", "bytes 0.4.12", "httparse 1.8.0", - "log 0.4.19", + "log 0.4.20", "mio 0.6.23", "mio-extras 2.0.6 (registry+https://github.com/rust-lang/crates.io-index)", "openssl", "rand 0.7.3 (registry+https://github.com/rust-lang/crates.io-index)", "sha-1 0.8.2", "slab 0.4.8", - "url 2.4.0", + "url 2.5.0", ] [[package]] @@ -9941,35 +9346,35 @@ dependencies = [ [[package]] name = "xous" -version = "0.9.44" +version = "0.9.54" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "30684dda3583f528d5b05bddc96527e1783255e867a5e81c10721d6abb9e169c" +checksum = "a8a9f0a696320940ab2652fa1d20c98dc59eb7ba4591eeb91a3b8e40bc9255a1" dependencies = [ "lazy_static", ] [[package]] name = "xous-api-log" -version = "0.1.40" +version = "0.1.50" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fd6b15ea09891f09b02d763422dc99733c96e62d0f8ab476c6bc663c90b17e72" +checksum = "03e07c190c743d6d9e076f715333e94c48de41b99078343d174c707803df28c7" dependencies = [ - "log 0.4.19", + "log 0.4.20", "num-derive", - "num-traits 0.2.15", + "num-traits 0.2.16", "xous", "xous-ipc", ] [[package]] name = "xous-api-names" -version = "0.9.42" +version = "0.9.52" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b470fbf177d58767fa001acfcb5294a88d3938d3935865ff6b8f1db40f1004e" +checksum = "32d8361077e67966d25922056284d17d042cbb1c96a7ebc2584eb8181427cbb0" dependencies = [ - "log 0.4.19", + "log 0.4.20", "num-derive", - "num-traits 0.2.15", + "num-traits 0.2.16", "rkyv", "xous", "xous-api-log", @@ -9978,11 +9383,11 @@ dependencies = [ [[package]] name = "xous-ipc" -version = "0.9.44" +version = "0.9.54" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d520fe08642d55a56f700b6d30c7a556f38818e7c3e5d9a0856dde0b79ed4d67" +checksum = "5ee1d318dacbd6242e4e2291dee7c4532249e5a0845de05d264c20fc871a0a1a" dependencies = [ - "bitflags", + "bitflags 1.3.2", "rkyv", "xous", ] @@ -10035,25 +9440,6 @@ dependencies = [ "syn 2.0.32", ] -[[package]] -name = "zstd" -version = "0.12.3+zstd.1.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "76eea132fb024e0e13fd9c2f5d5d595d8a967aa72382ac2f9d39fcc95afd0806" -dependencies = [ - "zstd-safe", -] - -[[package]] -name = "zstd-safe" -version = "6.0.5+zstd.1.5.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d56d9e60b4b1758206c238a10165fbcae3ca37b01744e394c463463f6529d23b" -dependencies = [ - "libc", - "zstd-sys", -] - [[package]] name = "zstd-sys" version = "2.0.8+zstd.1.5.5" diff --git a/Cargo.toml b/Cargo.toml index efa7c1c0b6..cdae016af3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,7 +1,8 @@ [workspace] - +resolver = "2" members = [ "app-libs/oracle", + "app-libs/parentchain-interface", "app-libs/sgx-runtime", "app-libs/stf", "cli", @@ -82,10 +83,8 @@ sgx_types = { version = "1.1.6", git = "https://github.com/apache/incubator-teac sgx_ucrypto = { version = "1.1.6", git = "https://github.com/apache/incubator-teaclave-sgx-sdk", branch = "master" } sgx_urts = { version = "1.1.6", git = "https://github.com/apache/incubator-teaclave-sgx-sdk", branch = "master" } -#[patch."https://github.com/integritee-network/sgx-runtime"] -#sgx-runtime = { path = "../sgx-runtime/runtime"} -#sp-io = { path = "../sgx-runtime/substrate-sgx/sp-io"} -#sgx-externalities = { path = "../sgx-runtime/substrate-sgx/externalities"} +[patch.crates-io] +ring = { git = "https://github.com/betrusted-io/ring-xous", branch = "0.16.20-cleanup" } #[patch."https://github.com/integritee-network/integritee-node"] #my-node-runtime = { package = "integritee-node-runtime", git = "https://github.com/integritee-network//integritee-node", branch = "ab/integrate-pallet-teerex-refactoring" } @@ -95,18 +94,16 @@ sgx_urts = { version = "1.1.6", git = "https://github.com/apache/incubator-teacl #substrate-client-keystore = { path = "../../scs/substrate-api-client/client-keystore" } #[patch."https://github.com/integritee-network/pallets.git"] -#pallet-claims = { git = "https://github.com/integritee-network//pallets", branch = "ab/shard-config-upgradability-2" } -#pallet-enclave-bridge = { git = "https://github.com/integritee-network//pallets", branch = "ab/shard-config-upgradability-2" } -#pallet-teerex = { git = "https://github.com/integritee-network//pallets", branch = "ab/shard-config-upgradability-2" } -#pallet-sidechain = { git = "https://github.com/integritee-network//pallets", branch = "ab/shard-config-upgradability-2" } -#sgx-verify = { git = "https://github.com/integritee-network//pallets", branch = "ab/shard-config-upgradability-2" } -#pallet-teeracle = { git = "https://github.com/integritee-network//pallets", branch = "ab/shard-config-upgradability-2" } -#test-utils = { git = "https://github.com/integritee-network//pallets", branch = "ab/shard-config-upgradability-2" } -#claims-primitives = { git = "https://github.com/integritee-network//pallets", branch = "ab/shard-config-upgradability-2" } -#enclave-bridge-primitives = { git = "https://github.com/integritee-network//pallets", branch = "ab/shard-config-upgradability-2" } -#teerex-primitives = { git = "https://github.com/integritee-network//pallets", branch = "ab/shard-config-upgradability-2" } -#teeracle-primitives = { git = "https://github.com/integritee-network//pallets", branch = "ab/shard-config-upgradability-2" } -#common-primitives = { git = "https://github.com/integritee-network//pallets", branch = "ab/shard-config-upgradability-2" } - -#[patch."https://github.com/integritee-network/http_req"] -#http_req = {path = '..//http_req' } +#pallet-claims = { git = "https://github.com/integritee-network//pallets", branch = "ab/parentchian-set-timestamp" } +#pallet-enclave-bridge = { git = "https://github.com/integritee-network//pallets", branch = "ab/parentchian-set-timestamp" } +#pallet-teerex = { git = "https://github.com/integritee-network//pallets", branch = "ab/parentchian-set-timestamp" } +#pallet-sidechain = { git = "https://github.com/integritee-network//pallets", branch = "ab/parentchian-set-timestamp" } +#pallet-parentchain = { git = "https://github.com/integritee-network//pallets", branch = "ab/parentchian-set-timestamp" } +#sgx-verify = { git = "https://github.com/integritee-network//pallets", branch = "ab/parentchian-set-timestamp" } +#pallet-teeracle = { git = "https://github.com/integritee-network//pallets", branch = "ab/parentchian-set-timestamp" } +#test-utils = { git = "https://github.com/integritee-network//pallets", branch = "ab/parentchian-set-timestamp" } +#claims-primitives = { git = "https://github.com/integritee-network//pallets", branch = "ab/parentchian-set-timestamp" } +#enclave-bridge-primitives = { git = "https://github.com/integritee-network//pallets", branch = "ab/parentchian-set-timestamp" } +#teerex-primitives = { git = "https://github.com/integritee-network//pallets", branch = "ab/parentchian-set-timestamp" } +#teeracle-primitives = { git = "https://github.com/integritee-network//pallets", branch = "ab/parentchian-set-timestamp" } +#common-primitives = { git = "https://github.com/integritee-network//pallets", branch = "ab/parentchian-set-timestamp" } diff --git a/app-libs/oracle/Cargo.toml b/app-libs/oracle/Cargo.toml index 2ea5c8301b..618884f1e8 100644 --- a/app-libs/oracle/Cargo.toml +++ b/app-libs/oracle/Cargo.toml @@ -20,7 +20,6 @@ codec = { package = "parity-scale-codec", version = "3.0.0", default-features = lazy_static = { version = "1.1.0", features = ["spin_no_std"] } log = { version = "0.4", default-features = false } serde = { version = "1.0", default-features = false, features = ["derive", "alloc"] } -serde_json = { version = "1.0", default-features = false, features = ["alloc"] } substrate-fixed = { default-features = false, git = "https://github.com/encointer/substrate-fixed", tag = "v0.5.9" } # internal dependencies @@ -36,7 +35,6 @@ std = [ "itp-ocall-api/std", "log/std", "serde/std", - "serde_json/std", "substrate-fixed/std", "thiserror", "url", diff --git a/app-libs/parentchain-interface/Cargo.toml b/app-libs/parentchain-interface/Cargo.toml new file mode 100644 index 0000000000..e080a7de42 --- /dev/null +++ b/app-libs/parentchain-interface/Cargo.toml @@ -0,0 +1,75 @@ +[package] +name = "ita-parentchain-interface" +version = "0.9.0" +authors = ["Integritee AG "] +edition = "2021" + +[dependencies] +# sgx dependencies +sgx_tstd = { branch = "master", git = "https://github.com/apache/teaclave-sgx-sdk.git", optional = true } + +# local dependencies +ita-sgx-runtime = { path = "../sgx-runtime", default-features = false } +ita-stf = { path = "../stf", default-features = false } +itc-parentchain = { path = "../../core/parentchain/parentchain-crate", default-features = false } +itc-parentchain-indirect-calls-executor = { path = "../../core/parentchain/indirect-calls-executor", default-features = false } +itp-api-client-types = { path = "../../core-primitives/node-api/api-client-types", default-features = false } +itp-node-api = { path = "../../core-primitives/node-api", default-features = false } +itp-stf-primitives = { path = "../../core-primitives/stf-primitives", default-features = false } +itp-types = { path = "../../core-primitives/types", default-features = false } +itp-utils = { path = "../../core-primitives/utils", default-features = false } + +# no-std compatible libraries +bs58 = { version = "0.4.0", default-features = false, features = ["alloc"] } +codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive"] } +log = { version = "0.4", default-features = false } +regex = { optional = true, version = "1.9.5" } + +substrate-api-client = { optional = true, default-features = false, features = ["std", "sync-api"], git = "https://github.com/scs/substrate-api-client.git", branch = "polkadot-v0.9.42-tag-v0.14.0" } + +# substrate dep +sp-core = { default-features = false, features = ["full_crypto"], git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } +sp-runtime = { default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } + +[dev-dependencies] +env_logger = "0.9.0" +itp-node-api = { path = "../../core-primitives/node-api", features = ["mocks"] } +itp-sgx-crypto = { path = "../../core-primitives/sgx/crypto", features = ["mocks"] } +itp-stf-executor = { path = "../../core-primitives/stf-executor", features = ["mocks"] } +itp-test = { path = "../../core-primitives/test" } +itp-top-pool-author = { path = "../../core-primitives/top-pool-author", features = ["mocks"] } +itc-parentchain-test = { path = "../../core/parentchain/test" } + + +[features] +default = ["std"] +std = [ + "bs58/std", + "codec/std", + "ita-sgx-runtime/std", + "ita-stf/std", + "itc-parentchain/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", + "itp-utils/std", + "log/std", + "regex", + "sp-core/std", + "sp-runtime/std", + "substrate-api-client", +] +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", +] diff --git a/app-libs/parentchain-interface/src/event_subscriber.rs b/app-libs/parentchain-interface/src/event_subscriber.rs new file mode 100644 index 0000000000..98c379c7fb --- /dev/null +++ b/app-libs/parentchain-interface/src/event_subscriber.rs @@ -0,0 +1,71 @@ +/* + 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::{AddedSgxEnclave, 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() + ), + }, + "Teerex" => match event.variant_name() { + "AddedSgxEnclave" => + if let Ok(Some(ev)) = event.as_event::() { + println!("[L1Event:{}] Teerex::{:?}", parentchain_id, ev); + }, + _ => println!( + "[L1Event:{}] {}::{}", + parentchain_id, + event.pallet_name(), + event.variant_name() + ), + }, + _ => println!( + "[L1Event:{}] {}::{}", + parentchain_id, + event.pallet_name(), + event.variant_name() + ), + } + } + } +} diff --git a/core/parentchain/indirect-calls-executor/src/parentchain_parser.rs b/app-libs/parentchain-interface/src/extrinsic_parser.rs similarity index 86% rename from core/parentchain/indirect-calls-executor/src/parentchain_parser.rs rename to app-libs/parentchain-interface/src/extrinsic_parser.rs index 93ae9e934b..de9caf318b 100644 --- a/core/parentchain/indirect-calls-executor/src/parentchain_parser.rs +++ b/app-libs/parentchain-interface/src/extrinsic_parser.rs @@ -18,16 +18,13 @@ use codec::{Decode, Encode}; use core::marker::PhantomData; use itp_node_api::api_client::{ - Address, CallIndex, PairSignature, ParentchainSignedExtra, Signature, UncheckedExtrinsicV4, + Address, CallIndex, PairSignature, Signature, UncheckedExtrinsicV4, }; pub struct ExtrinsicParser { _phantom: PhantomData, } -/// Parses the extrinsics corresponding to the parentchain. -pub type ParentchainExtrinsicParser = ExtrinsicParser; - /// Partially interpreted extrinsic containing the `signature` and the `call_index` whereas /// the `call_args` remain in encoded form. /// @@ -62,11 +59,11 @@ where // `()` 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)?; + Address, + (CallIndex, ()), + PairSignature, + Self::SignedExtra, + >::decode(call_mut)?; Ok(SemiOpaqueExtrinsic { signature: xt.signature, diff --git a/core/parentchain/indirect-calls-executor/src/indirect_calls/invoke.rs b/app-libs/parentchain-interface/src/indirect_calls/invoke.rs similarity index 76% rename from core/parentchain/indirect-calls-executor/src/indirect_calls/invoke.rs rename to app-libs/parentchain-interface/src/indirect_calls/invoke.rs index 076e06e87c..ead6ed4d52 100644 --- a/core/parentchain/indirect-calls-executor/src/indirect_calls/invoke.rs +++ b/app-libs/parentchain-interface/src/indirect_calls/invoke.rs @@ -15,8 +15,13 @@ */ -use crate::{error::Result, IndirectDispatch, IndirectExecutor}; use codec::{Decode, Encode}; +use ita_stf::TrustedCallSigned; +use itc_parentchain_indirect_calls_executor::{ + error::{Error, Result}, + IndirectDispatch, +}; +use itp_stf_primitives::traits::IndirectExecutor; use itp_types::Request; #[derive(Debug, Clone, Encode, Decode, Eq, PartialEq)] @@ -24,7 +29,9 @@ pub struct InvokeArgs { request: Request, } -impl IndirectDispatch for InvokeArgs { +impl> + IndirectDispatch for InvokeArgs +{ fn dispatch(&self, executor: &Executor) -> Result<()> { log::debug!("Found trusted call extrinsic, submitting it to the top pool"); executor.submit_trusted_call(self.request.shard, self.request.cyphertext.clone()); diff --git a/core/parentchain/indirect-calls-executor/src/indirect_calls/mod.rs b/app-libs/parentchain-interface/src/indirect_calls/mod.rs similarity index 88% rename from core/parentchain/indirect-calls-executor/src/indirect_calls/mod.rs rename to app-libs/parentchain-interface/src/indirect_calls/mod.rs index 4f2da407de..14eabcfbb0 100644 --- a/core/parentchain/indirect-calls-executor/src/indirect_calls/mod.rs +++ b/app-libs/parentchain-interface/src/indirect_calls/mod.rs @@ -15,9 +15,10 @@ */ -mod invoke; -mod shield_funds; -mod transfer_to_alice_shields_funds; +pub mod invoke; +pub mod shield_funds; +pub mod timestamp_set; +pub mod transfer_to_alice_shields_funds; pub use invoke::InvokeArgs; pub use shield_funds::ShieldFundsArgs; diff --git a/core/parentchain/indirect-calls-executor/src/indirect_calls/shield_funds.rs b/app-libs/parentchain-interface/src/indirect_calls/shield_funds.rs similarity index 77% rename from core/parentchain/indirect-calls-executor/src/indirect_calls/shield_funds.rs rename to app-libs/parentchain-interface/src/indirect_calls/shield_funds.rs index 1036614da8..9d013e7518 100644 --- a/core/parentchain/indirect-calls-executor/src/indirect_calls/shield_funds.rs +++ b/app-libs/parentchain-interface/src/indirect_calls/shield_funds.rs @@ -15,13 +15,20 @@ */ -use crate::{error::Result, IndirectDispatch, IndirectExecutor}; use codec::{Decode, Encode}; use ita_stf::{Getter, TrustedCall, TrustedCallSigned}; -use itp_stf_primitives::types::{AccountId, TrustedOperation}; -use itp_types::{Balance, ShardIdentifier}; +use itc_parentchain_indirect_calls_executor::{ + error::{Error, Result}, + IndirectDispatch, +}; +use itp_stf_primitives::{ + traits::IndirectExecutor, + types::{AccountId, TrustedOperation}, +}; +use itp_types::{parentchain::ParentchainId, Balance, ShardIdentifier}; use log::{debug, info}; use std::vec::Vec; + /// Arguments of the Integritee-Parachain's shield fund dispatchable. #[derive(Debug, Clone, Encode, Decode, Eq, PartialEq)] pub struct ShieldFundsArgs { @@ -30,7 +37,9 @@ pub struct ShieldFundsArgs { amount: Balance, } -impl IndirectDispatch for ShieldFundsArgs { +impl> + IndirectDispatch for ShieldFundsArgs +{ fn dispatch(&self, executor: &Executor) -> Result<()> { info!("Found ShieldFunds extrinsic in block: \nAccount Encrypted {:?} \nAmount: {} \nShard: {}", self.account_encrypted, self.amount, bs58::encode(self.shard.encode()).into_string()); @@ -40,7 +49,12 @@ impl IndirectDispatch for ShieldFundsArgs let account = AccountId::decode(&mut account_vec.as_slice())?; let enclave_account_id = executor.get_enclave_account()?; - let trusted_call = TrustedCall::balance_shield(enclave_account_id, account, self.amount); + let trusted_call = TrustedCall::balance_shield( + enclave_account_id, + account, + self.amount, + ParentchainId::Integritee, + ); let signed_trusted_call = executor.sign_call_with_self(&trusted_call, &self.shard)?; let trusted_operation = TrustedOperation::::indirect_call(signed_trusted_call); diff --git a/app-libs/parentchain-interface/src/indirect_calls/timestamp_set.rs b/app-libs/parentchain-interface/src/indirect_calls/timestamp_set.rs new file mode 100644 index 0000000000..64cf0dd600 --- /dev/null +++ b/app-libs/parentchain-interface/src/indirect_calls/timestamp_set.rs @@ -0,0 +1,62 @@ +/* + 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::{Integritee, ParentchainInstance, TargetA, TargetB}; +use codec::{Compact, Decode, Encode}; +use core::{any::TypeId, marker::PhantomData}; +use ita_stf::{Getter, TrustedCall, TrustedCallSigned}; +use itc_parentchain_indirect_calls_executor::{ + error::{Error, Result}, + IndirectDispatch, +}; +use itp_stf_primitives::{traits::IndirectExecutor, types::TrustedOperation}; +use itp_types::{parentchain::ParentchainId, Moment}; +use log::info; + +#[derive(Debug, Clone, Encode, Decode, Eq, PartialEq)] +pub struct TimestampSetArgs { + now: Compact, + _phantom: PhantomData, +} + +impl, I: ParentchainInstance + 'static> + IndirectDispatch for TimestampSetArgs +{ + fn dispatch(&self, executor: &Executor) -> Result<()> { + info!("Found TimestampSet extrinsic in block: now = {:?}", self.now); + let enclave_account_id = executor.get_enclave_account()?; + let parentchain_id = if TypeId::of::() == TypeId::of::() { + ParentchainId::Integritee + } else if TypeId::of::() == TypeId::of::() { + ParentchainId::TargetA + } else if TypeId::of::() == TypeId::of::() { + ParentchainId::TargetB + } else { + return Err(Error::Other("unknown parentchain instance".into())) + }; + let trusted_call = + TrustedCall::timestamp_set(enclave_account_id, self.now.0, parentchain_id); + let shard = executor.get_default_shard(); + let signed_trusted_call = executor.sign_call_with_self(&trusted_call, &shard)?; + let trusted_operation = + TrustedOperation::::indirect_call(signed_trusted_call); + + let encrypted_trusted_call = executor.encrypt(&trusted_operation.encode())?; + executor.submit_trusted_call(shard, encrypted_trusted_call); + Ok(()) + } +} diff --git a/core/parentchain/indirect-calls-executor/src/indirect_calls/transfer_to_alice_shields_funds.rs b/app-libs/parentchain-interface/src/indirect_calls/transfer_to_alice_shields_funds.rs similarity index 85% rename from core/parentchain/indirect-calls-executor/src/indirect_calls/transfer_to_alice_shields_funds.rs rename to app-libs/parentchain-interface/src/indirect_calls/transfer_to_alice_shields_funds.rs index fa74a29909..ec32533807 100644 --- a/core/parentchain/indirect-calls-executor/src/indirect_calls/transfer_to_alice_shields_funds.rs +++ b/app-libs/parentchain-interface/src/indirect_calls/transfer_to_alice_shields_funds.rs @@ -15,11 +15,18 @@ */ -use crate::{error::Result, IndirectDispatch, IndirectExecutor}; use codec::{Decode, Encode}; +use core::fmt::Debug; use ita_stf::{Getter, TrustedCall, TrustedCallSigned}; -use itp_stf_primitives::types::{AccountId, TrustedOperation}; -use itp_types::Balance; +use itc_parentchain_indirect_calls_executor::{ + error::{Error, Result}, + IndirectDispatch, +}; +use itp_stf_primitives::{ + traits::IndirectExecutor, + types::{AccountId, TrustedOperation}, +}; +use itp_types::{parentchain::ParentchainId, Balance}; use log::info; use sp_runtime::MultiAddress; @@ -41,8 +48,7 @@ pub struct TransferToAliceShieldsFundsArgs { /// /// ``` /// use sp_core::{sr25519, Pair}; -/// use itc_parentchain_indirect_calls_executor::indirect_calls::ALICE_ACCOUNT_ID; -/// +/// use ita_parentchain_interface::indirect_calls::ALICE_ACCOUNT_ID; /// let alice = sr25519::Pair::from_string_with_seed("//Alice", None).unwrap(); /// println!("{:?}", alice.0.public().to_vec()); /// assert_eq!(ALICE_ACCOUNT_ID, alice.0.public().into()) @@ -52,7 +58,9 @@ pub const ALICE_ACCOUNT_ID: AccountId = AccountId::new([ 76, 205, 227, 154, 86, 132, 231, 165, 109, 162, 125, ]); -impl IndirectDispatch for TransferToAliceShieldsFundsArgs { +impl> + IndirectDispatch for TransferToAliceShieldsFundsArgs +{ fn dispatch(&self, executor: &Executor) -> Result<()> { if self.destination == ALICE_ACCOUNT_ID.into() { info!("Found Transfer to Alice extrinsic in block: \nAmount: {}", self.value); @@ -62,6 +70,7 @@ impl IndirectDispatch for TransferToAliceS executor.get_enclave_account()?, ALICE_ACCOUNT_ID, self.value, + ParentchainId::Integritee, ); let signed_trusted_call = executor.sign_call_with_self(&trusted_call, &shard)?; let trusted_operation = diff --git a/app-libs/parentchain-interface/src/integritee/event_filter.rs b/app-libs/parentchain-interface/src/integritee/event_filter.rs new file mode 100644 index 0000000000..d403a93948 --- /dev/null +++ b/app-libs/parentchain-interface/src/integritee/event_filter.rs @@ -0,0 +1,85 @@ +/* + 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_types::{ + parentchain::{ + BalanceTransfer, ExtrinsicFailed, ExtrinsicStatus, ExtrinsicSuccess, FilterEvents, + }, + H256, +}; +use std::vec::Vec; + +#[derive(Clone)] +pub struct FilterableEvents(pub Events); + +// 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_extrinsic_statuses(&self) -> core::result::Result, Self::Error> { + Ok(self + .to_events() + .iter() + .filter_map(|ev| { + ev.and_then(|ev| { + if (ev.as_event::()?).is_some() { + return Ok(Some(ExtrinsicStatus::Success)) + } + + if (ev.as_event::()?).is_some() { + return Ok(Some(ExtrinsicStatus::Failed)) + } + + Ok(None) + }) + .ok() + .flatten() + }) + .collect()) + } + + fn get_transfer_events(&self) -> core::result::Result, Self::Error> { + Ok(self + .to_events() + .iter() + .flatten() // flatten filters out the nones + .filter_map(|ev| match ev.as_event::() { + Ok(maybe_event) => maybe_event, + Err(e) => { + log::error!("Could not decode event: {:?}", e); + None + }, + }) + .collect()) + } +} diff --git a/app-libs/parentchain-interface/src/integritee/event_handler.rs b/app-libs/parentchain-interface/src/integritee/event_handler.rs new file mode 100644 index 0000000000..57ec9557f9 --- /dev/null +++ b/app-libs/parentchain-interface/src/integritee/event_handler.rs @@ -0,0 +1,87 @@ +/* + 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; + +pub use ita_sgx_runtime::{Balance, Index}; +use ita_stf::{Getter, TrustedCall, TrustedCallSigned}; +use itc_parentchain_indirect_calls_executor::error::Error; +use itp_stf_primitives::{traits::IndirectExecutor, types::TrustedOperation}; +use itp_types::parentchain::{ + AccountId, FilterEvents, HandleParentchainEvents, ParentchainError, ParentchainId, +}; +use itp_utils::hex::hex_encode; +use log::*; + +pub struct ParentchainEventHandler {} + +impl ParentchainEventHandler { + fn shield_funds>( + executor: &Executor, + account: &AccountId, + amount: Balance, + ) -> Result<(), Error> { + log::info!("shielding for {:?} amount {}", account, amount,); + let shard = executor.get_default_shard(); + // todo: ensure this parentchain is assigned for the shard vault! + let trusted_call = TrustedCall::balance_shield( + executor.get_enclave_account()?, + account.clone(), + amount, + ParentchainId::Integritee, + ); + let signed_trusted_call = executor.sign_call_with_self(&trusted_call, &shard)?; + let trusted_operation = + TrustedOperation::::indirect_call(signed_trusted_call); + + let encrypted_trusted_call = executor.encrypt(&trusted_operation.encode())?; + executor.submit_trusted_call(shard, encrypted_trusted_call); + + Ok(()) + } +} + +impl HandleParentchainEvents + for ParentchainEventHandler +where + Executor: IndirectExecutor, +{ + fn handle_events( + executor: &Executor, + events: impl FilterEvents, + vault_account: &AccountId, + ) -> Result<(), Error> { + let filter_events = events.get_transfer_events(); + trace!( + "filtering transfer events to shard vault account: {}", + hex_encode(vault_account.encode().as_slice()) + ); + if let Ok(events) = filter_events { + events + .iter() + .filter(|&event| event.to == *vault_account) + .try_for_each(|event| { + info!("found transfer_event to vault account: {}", event); + //debug!("shielding from Integritee suppressed"); + Self::shield_funds(executor, &event.from, event.amount) + //Err(ParentchainError::FunctionalityDisabled) + }) + .map_err(|_| ParentchainError::ShieldFundsFailure)?; + } + Ok(()) + } +} diff --git a/app-libs/parentchain-interface/src/integritee/mod.rs b/app-libs/parentchain-interface/src/integritee/mod.rs new file mode 100644 index 0000000000..00c350cf20 --- /dev/null +++ b/app-libs/parentchain-interface/src/integritee/mod.rs @@ -0,0 +1,120 @@ +/* + 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; + +use crate::{ + decode_and_log_error, + extrinsic_parser::ParseExtrinsic, + indirect_calls::{ + invoke::InvokeArgs, shield_funds::ShieldFundsArgs, timestamp_set::TimestampSetArgs, + }, + Integritee, +}; +use codec::{Decode, Encode}; +pub use event_filter::FilterableEvents; +pub use event_handler::ParentchainEventHandler; +use ita_stf::TrustedCallSigned; +use itc_parentchain_indirect_calls_executor::{ + error::{Error, Result}, + filter_metadata::FilterIntoDataFrom, + IndirectDispatch, +}; +use itp_api_client_types::ParentchainSignedExtra; +use itp_node_api::metadata::{ + pallet_enclave_bridge::EnclaveBridgeCallIndexes, pallet_timestamp::TimestampCallIndexes, +}; +use itp_stf_primitives::traits::IndirectExecutor; +use log::*; +use sp_runtime::traits::BlakeTwo256; + +pub type BlockNumber = u32; +pub type Header = sp_runtime::generic::Header; +use crate::extrinsic_parser::ExtrinsicParser; +pub use itp_types::parentchain::{AccountId, Balance, Hash}; + +pub type Signature = sp_runtime::MultiSignature; + +/// Parses the extrinsics corresponding to the parentchain. +pub type ParentchainExtrinsicParser = ExtrinsicParser; + +/// The default indirect call (extrinsic-triggered) of the Integritee-Parachain. +#[derive(Debug, Clone, Encode, Decode, Eq, PartialEq)] +pub enum IndirectCall { + ShieldFunds(ShieldFundsArgs), + Invoke(InvokeArgs), + TimestampSet(TimestampSetArgs), +} + +impl> + IndirectDispatch for IndirectCall +{ + fn dispatch(&self, executor: &Executor) -> Result<()> { + trace!("dispatching indirect call {:?}", self); + match self { + IndirectCall::ShieldFunds(shieldfunds_args) => shieldfunds_args.dispatch(executor), + IndirectCall::Invoke(invoke_args) => invoke_args.dispatch(executor), + IndirectCall::TimestampSet(timestamp_set_args) => timestamp_set_args.dispatch(executor), + } + } +} + +/// Default filter we use for the Integritee-Parachain. +pub struct ExtrinsicFilter {} + +impl FilterIntoDataFrom + for ExtrinsicFilter +{ + type Output = IndirectCall; + type ParseParentchainMetadata = ParentchainExtrinsicParser; + + fn filter_into_from_metadata( + encoded_data: &[u8], + metadata: &NodeMetadata, + ) -> Option { + let call_mut = &mut &encoded_data[..]; + + // Todo: the filter should not need to parse, only filter. This should directly be configured + // in the indirect executor. + let xt = match Self::ParseParentchainMetadata::parse(call_mut) { + Ok(xt) => xt, + Err(e) => { + error!("ExtrinsicFilter: Could not parse parentchain extrinsic: {:?}", e); + return None + }, + }; + let index = xt.call_index; + let call_args = &mut &xt.call_args[..]; + trace!("ExtrinsicFilter: attempting to execute indirect call with index {:?}", index); + if index == metadata.shield_funds_call_indexes().ok()? { + debug!("ExtrinsicFilter: executing shield funds call"); + let args = decode_and_log_error::(call_args)?; + Some(IndirectCall::ShieldFunds(args)) + } else if index == metadata.invoke_call_indexes().ok()? { + debug!("ExtrinsicFilter: executing invoke call"); + let args = decode_and_log_error::(call_args)?; + Some(IndirectCall::Invoke(args)) + } else if index == metadata.timestamp_set_call_indexes().ok()? { + debug!("ExtrinsicFilter: found timestamp set extrinsic"); + let args = decode_and_log_error::>(call_args)?; + Some(IndirectCall::TimestampSet(args)) + } else { + None + } + } +} diff --git a/app-libs/parentchain-interface/src/lib.rs b/app-libs/parentchain-interface/src/lib.rs new file mode 100644 index 0000000000..e2e0582bf7 --- /dev/null +++ b/app-libs/parentchain-interface/src/lib.rs @@ -0,0 +1,56 @@ +/* + 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 extrinsic_parser; +pub mod indirect_calls; +pub mod integritee; +pub mod target_a; +pub mod target_b; + +pub trait ParentchainInstance {} + +#[derive(Debug, Clone, Encode, Decode, Eq, PartialEq)] +pub struct Integritee; +impl ParentchainInstance for Integritee {} + +#[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/app-libs/parentchain-interface/src/target_a/event_filter.rs b/app-libs/parentchain-interface/src/target_a/event_filter.rs new file mode 100644 index 0000000000..6e049fe740 --- /dev/null +++ b/app-libs/parentchain-interface/src/target_a/event_filter.rs @@ -0,0 +1,84 @@ +/* + 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_types::{ + parentchain::{ + BalanceTransfer, ExtrinsicFailed, ExtrinsicStatus, ExtrinsicSuccess, FilterEvents, + }, + H256, +}; +use std::vec::Vec; + +#[derive(Clone)] +pub struct FilterableEvents(pub Events); + +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_extrinsic_statuses(&self) -> core::result::Result, Self::Error> { + Ok(self + .to_events() + .iter() + .filter_map(|ev| { + ev.and_then(|ev| { + if (ev.as_event::()?).is_some() { + return Ok(Some(ExtrinsicStatus::Success)) + } + + if (ev.as_event::()?).is_some() { + return Ok(Some(ExtrinsicStatus::Failed)) + } + + Ok(None) + }) + .ok() + .flatten() + }) + .collect()) + } + + fn get_transfer_events(&self) -> core::result::Result, Self::Error> { + Ok(self + .to_events() + .iter() + .flatten() // flatten filters out the nones + .filter_map(|ev| match ev.as_event::() { + Ok(maybe_event) => maybe_event, + Err(e) => { + log::error!("Could not decode event: {:?}", e); + None + }, + }) + .collect()) + } +} diff --git a/app-libs/parentchain-interface/src/target_a/event_handler.rs b/app-libs/parentchain-interface/src/target_a/event_handler.rs new file mode 100644 index 0000000000..c9da4ae377 --- /dev/null +++ b/app-libs/parentchain-interface/src/target_a/event_handler.rs @@ -0,0 +1,85 @@ +/* + 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; +pub use ita_sgx_runtime::{Balance, Index}; + +use ita_stf::{Getter, TrustedCall, TrustedCallSigned}; +use itc_parentchain_indirect_calls_executor::error::Error; +use itp_stf_primitives::{traits::IndirectExecutor, types::TrustedOperation}; +use itp_types::parentchain::{ + AccountId, FilterEvents, HandleParentchainEvents, ParentchainError, ParentchainId, +}; +use itp_utils::hex::hex_encode; +use log::*; + +pub struct ParentchainEventHandler {} + +impl ParentchainEventHandler { + fn shield_funds>( + executor: &Executor, + account: &AccountId, + amount: Balance, + ) -> Result<(), Error> { + trace!("[TargetA] shielding for {:?} amount {}", account, amount,); + let shard = executor.get_default_shard(); + // todo: ensure this parentchain is assigned for the shard vault! + let trusted_call = TrustedCall::balance_shield( + executor.get_enclave_account()?, + account.clone(), + amount, + ParentchainId::TargetA, + ); + let signed_trusted_call = executor.sign_call_with_self(&trusted_call, &shard)?; + let trusted_operation = + TrustedOperation::::indirect_call(signed_trusted_call); + + let encrypted_trusted_call = executor.encrypt(&trusted_operation.encode())?; + executor.submit_trusted_call(shard, encrypted_trusted_call); + + Ok(()) + } +} + +impl HandleParentchainEvents + for ParentchainEventHandler +where + Executor: IndirectExecutor, +{ + fn handle_events( + executor: &Executor, + events: impl FilterEvents, + vault_account: &AccountId, + ) -> Result<(), Error> { + let filter_events = events.get_transfer_events(); + trace!( + "[TargetA] filtering transfer events to shard vault account: {}", + hex_encode(vault_account.encode().as_slice()) + ); + if let Ok(events) = filter_events { + events + .iter() + .filter(|&event| event.to == *vault_account) + .try_for_each(|event| { + info!("[TargetA] found transfer event to shard vault account: {} will shield to {}", event.amount, hex_encode(event.from.encode().as_ref())); + Self::shield_funds(executor, &event.from, event.amount) + }) + .map_err(|_| ParentchainError::ShieldFundsFailure)?; + } + Ok(()) + } +} diff --git a/app-libs/parentchain-interface/src/target_a/mod.rs b/app-libs/parentchain-interface/src/target_a/mod.rs new file mode 100644 index 0000000000..d8d804d42f --- /dev/null +++ b/app-libs/parentchain-interface/src/target_a/mod.rs @@ -0,0 +1,92 @@ +/* + 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; + +use crate::{ + decode_and_log_error, + extrinsic_parser::{ExtrinsicParser, ParseExtrinsic}, + indirect_calls::timestamp_set::TimestampSetArgs, + TargetA, +}; +use codec::{Decode, Encode}; +pub use event_filter::FilterableEvents; +pub use event_handler::ParentchainEventHandler; +use ita_stf::TrustedCallSigned; +use itc_parentchain_indirect_calls_executor::{ + error::{Error, Result}, + filter_metadata::FilterIntoDataFrom, + IndirectDispatch, +}; +use itp_api_client_types::ParentchainSignedExtra; +use itp_node_api::metadata::pallet_timestamp::TimestampCallIndexes; +use itp_stf_primitives::traits::IndirectExecutor; +use log::*; + +/// Parses the extrinsics corresponding to the parentchain. +pub type ParentchainExtrinsicParser = ExtrinsicParser; + +/// The default indirect call (extrinsic-triggered) of the Target-A-Parachain. +#[derive(Debug, Clone, Encode, Decode, Eq, PartialEq)] +pub enum IndirectCall { + TimestampSet(TimestampSetArgs), +} + +impl> + IndirectDispatch for IndirectCall +{ + fn dispatch(&self, executor: &Executor) -> Result<()> { + trace!("dispatching indirect call {:?}", self); + match self { + IndirectCall::TimestampSet(timestamp_set_args) => timestamp_set_args.dispatch(executor), + } + } +} + +pub struct ExtrinsicFilter {} + +impl FilterIntoDataFrom for ExtrinsicFilter { + type Output = IndirectCall; + type ParseParentchainMetadata = ParentchainExtrinsicParser; + + fn filter_into_from_metadata( + encoded_data: &[u8], + metadata: &NodeMetadata, + ) -> Option { + let call_mut = &mut &encoded_data[..]; + + // Todo: the filter should not need to parse, only filter. This should directly be configured + // in the indirect executor. + let xt = match Self::ParseParentchainMetadata::parse(call_mut) { + Ok(xt) => xt, + Err(e) => { + error!("ExtrinsicFilter: Could not parse parentchain extrinsic: {:?}", e); + return None + }, + }; + let index = xt.call_index; + let call_args = &mut &xt.call_args[..]; + trace!("ExtrinsicFilter: attempting to execute indirect call with index {:?}", index); + if index == metadata.timestamp_set_call_indexes().ok()? { + debug!("ExtrinsicFilter: found timestamp set extrinsic"); + let args = decode_and_log_error::>(call_args)?; + Some(IndirectCall::TimestampSet(args)) + } else { + None + } + } +} diff --git a/app-libs/parentchain-interface/src/target_b/event_filter.rs b/app-libs/parentchain-interface/src/target_b/event_filter.rs new file mode 100644 index 0000000000..6e049fe740 --- /dev/null +++ b/app-libs/parentchain-interface/src/target_b/event_filter.rs @@ -0,0 +1,84 @@ +/* + 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_types::{ + parentchain::{ + BalanceTransfer, ExtrinsicFailed, ExtrinsicStatus, ExtrinsicSuccess, FilterEvents, + }, + H256, +}; +use std::vec::Vec; + +#[derive(Clone)] +pub struct FilterableEvents(pub Events); + +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_extrinsic_statuses(&self) -> core::result::Result, Self::Error> { + Ok(self + .to_events() + .iter() + .filter_map(|ev| { + ev.and_then(|ev| { + if (ev.as_event::()?).is_some() { + return Ok(Some(ExtrinsicStatus::Success)) + } + + if (ev.as_event::()?).is_some() { + return Ok(Some(ExtrinsicStatus::Failed)) + } + + Ok(None) + }) + .ok() + .flatten() + }) + .collect()) + } + + fn get_transfer_events(&self) -> core::result::Result, Self::Error> { + Ok(self + .to_events() + .iter() + .flatten() // flatten filters out the nones + .filter_map(|ev| match ev.as_event::() { + Ok(maybe_event) => maybe_event, + Err(e) => { + log::error!("Could not decode event: {:?}", e); + None + }, + }) + .collect()) + } +} diff --git a/app-libs/parentchain-interface/src/target_b/event_handler.rs b/app-libs/parentchain-interface/src/target_b/event_handler.rs new file mode 100644 index 0000000000..39a5555973 --- /dev/null +++ b/app-libs/parentchain-interface/src/target_b/event_handler.rs @@ -0,0 +1,41 @@ +/* + 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 ita_stf::TrustedCallSigned; +use itc_parentchain_indirect_calls_executor::error::Error; +use itp_stf_primitives::traits::IndirectExecutor; +use itp_types::parentchain::{AccountId, FilterEvents, HandleParentchainEvents}; +use log::*; + +pub struct ParentchainEventHandler {} + +impl HandleParentchainEvents + for ParentchainEventHandler +where + Executor: IndirectExecutor, +{ + fn handle_events( + _executor: &Executor, + _events: impl FilterEvents, + _vault_account: &AccountId, + ) -> Result<(), Error> { + debug!("not handling any events for target B"); + Ok(()) + } +} diff --git a/app-libs/parentchain-interface/src/target_b/mod.rs b/app-libs/parentchain-interface/src/target_b/mod.rs new file mode 100644 index 0000000000..c21bbe6654 --- /dev/null +++ b/app-libs/parentchain-interface/src/target_b/mod.rs @@ -0,0 +1,93 @@ +/* + 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; + +use crate::{ + decode_and_log_error, + extrinsic_parser::{ExtrinsicParser, ParseExtrinsic}, + indirect_calls::timestamp_set::TimestampSetArgs, + TargetB, +}; +use codec::{Decode, Encode}; +pub use event_filter::FilterableEvents; +pub use event_handler::ParentchainEventHandler; +use ita_stf::TrustedCallSigned; +use itc_parentchain_indirect_calls_executor::{ + error::{Error, Result}, + filter_metadata::FilterIntoDataFrom, + IndirectDispatch, +}; +use itp_api_client_types::ParentchainSignedExtra; +use itp_node_api::metadata::pallet_timestamp::TimestampCallIndexes; +use itp_stf_primitives::traits::IndirectExecutor; +use log::*; + +/// Parses the extrinsics corresponding to the parentchain. +pub type ParentchainExtrinsicParser = ExtrinsicParser; + +/// The default indirect call (extrinsic-triggered) of the Target-A-Parachain. +#[derive(Debug, Clone, Encode, Decode, Eq, PartialEq)] +pub enum IndirectCall { + TimestampSet(TimestampSetArgs), +} + +impl> + IndirectDispatch for IndirectCall +{ + fn dispatch(&self, executor: &Executor) -> Result<()> { + trace!("dispatching indirect call {:?}", self); + match self { + IndirectCall::TimestampSet(timestamp_set_args) => timestamp_set_args.dispatch(executor), + } + } +} + +pub struct ExtrinsicFilter {} + +impl FilterIntoDataFrom for ExtrinsicFilter { + type Output = IndirectCall; + type ParseParentchainMetadata = ParentchainExtrinsicParser; + + fn filter_into_from_metadata( + encoded_data: &[u8], + metadata: &NodeMetadata, + ) -> Option { + let call_mut = &mut &encoded_data[..]; + + // Todo: the filter should not need to parse, only filter. This should directly be configured + // in the indirect executor. + let xt = match Self::ParseParentchainMetadata::parse(call_mut) { + Ok(xt) => xt, + Err(e) => { + error!("ExtrinsicFilter: Could not parse parentchain extrinsic: {:?}", e); + return None + }, + }; + let index = xt.call_index; + let call_args = &mut &xt.call_args[..]; + trace!("ExtrinsicFilter: attempting to execute indirect call with index {:?}", index); + if index == metadata.timestamp_set_call_indexes().ok()? { + debug!("ExtrinsicFilter: found timestamp set extrinsic"); + let args = decode_and_log_error::>(call_args)?; + Some(IndirectCall::TimestampSet(args)) + } else { + None + } + } +} diff --git a/app-libs/sgx-runtime/Cargo.toml b/app-libs/sgx-runtime/Cargo.toml index 381bafc61f..91f6550a2d 100644 --- a/app-libs/sgx-runtime/Cargo.toml +++ b/app-libs/sgx-runtime/Cargo.toml @@ -8,11 +8,8 @@ edition = "2021" targets = ["x86_64-unknown-linux-gnu"] [dependencies] -hex-literal = { version = "0.3.4", optional = true } -serde = { version = "1.0", optional = true, features = ["derive"] } -# alias "parity-scale-code" to "codec" codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive"] } -scale-info = { version = "2.0.1", default-features = false, features = ["derive"] } +scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } # local dependencies itp-sgx-runtime-primitives = { path = "../../core-primitives/sgx-runtime-primitives", default-features = false } @@ -26,7 +23,6 @@ frame-system-benchmarking = { optional = true, default-features = false, git = " frame-system-rpc-runtime-api = { default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } pallet-aura = { default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } pallet-balances = { default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } -pallet-grandpa = { default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } pallet-insecure-randomness-collective-flip = { default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } pallet-sudo = { default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } pallet-timestamp = { default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } @@ -46,7 +42,7 @@ sp-version = { default-features = false, git = "https://github.com/paritytech/su # Integritee dependencies pallet-evm = { default-features = false, optional = true, git = "https://github.com/integritee-network/frontier.git", branch = "bar/polkadot-v0.9.42" } -pallet-parentchain = { default-features = false, git = "https://github.com/integritee-network/pallets.git", branch = "sdk-v0.12.0-polkadot-v0.9.42" } +pallet-parentchain = { default-features = false, git = "https://github.com/integritee-network/pallets.git", branch = "sdk-v0.12.11-polkadot-v0.9.42" } [features] default = ["std"] @@ -59,7 +55,6 @@ evm_std = [ "pallet-evm/std", ] runtime-benchmarks = [ - "hex-literal", "frame-benchmarking", "frame-support/runtime-benchmarks", "frame-system-benchmarking", @@ -71,7 +66,6 @@ runtime-benchmarks = [ std = [ "codec/std", "scale-info/std", - "serde", "itp-sgx-runtime-primitives/std", "frame-executive/std", "frame-support/std", diff --git a/app-libs/sgx-runtime/src/lib.rs b/app-libs/sgx-runtime/src/lib.rs index 124ee255da..93b1026d1a 100644 --- a/app-libs/sgx-runtime/src/lib.rs +++ b/app-libs/sgx-runtime/src/lib.rs @@ -70,8 +70,9 @@ pub use frame_support::{ }, StorageValue, }; +use itp_sgx_runtime_primitives::types::Moment; pub use pallet_balances::Call as BalancesCall; -pub use pallet_parentchain::Call as ParentchainCall; +pub use pallet_parentchain::Call as ParentchainPalletCall; pub use pallet_timestamp::Call as TimestampCall; #[cfg(any(feature = "std", test))] pub use sp_runtime::BuildStorage; @@ -211,7 +212,7 @@ parameter_types! { impl pallet_timestamp::Config for Runtime { /// A timestamp: milliseconds since the unix epoch. - type Moment = u64; + type Moment = Moment; type OnTimestampSet = (); type MinimumPeriod = MinimumPeriod; type WeightInfo = (); @@ -259,9 +260,25 @@ impl pallet_sudo::Config for Runtime { type RuntimeCall = RuntimeCall; } -impl pallet_parentchain::Config for Runtime { +pub type ParentchainInstanceIntegritee = pallet_parentchain::Instance1; +impl pallet_parentchain::Config for Runtime { type WeightInfo = (); type RuntimeEvent = RuntimeEvent; + type Moment = Moment; +} + +pub type ParentchainInstanceTargetA = pallet_parentchain::Instance2; +impl pallet_parentchain::Config for Runtime { + type WeightInfo = (); + type RuntimeEvent = RuntimeEvent; + type Moment = Moment; +} + +pub type ParentchainInstanceTargetB = pallet_parentchain::Instance3; +impl pallet_parentchain::Config for Runtime { + type WeightInfo = (); + type RuntimeEvent = RuntimeEvent; + type Moment = Moment; } // The plain sgx-runtime without the `evm-pallet` @@ -272,12 +289,15 @@ construct_runtime!( NodeBlock = opaque::Block, UncheckedExtrinsic = UncheckedExtrinsic { - System: frame_system::{Pallet, Call, Config, Storage, Event}, - Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent}, - Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, - TransactionPayment: pallet_transaction_payment::{Pallet, Storage, Event}, - Sudo: pallet_sudo::{Pallet, Call, Config, Storage, Event}, - Parentchain: pallet_parentchain::{Pallet, Call, Storage, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event} = 0, + Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent} = 1, + Balances: pallet_balances::{Pallet, Call, Storage, Config, Event} = 2, + TransactionPayment: pallet_transaction_payment::{Pallet, Storage, Event} = 3, + Sudo: pallet_sudo::{Pallet, Call, Config, Storage, Event} = 4, + + ParentchainIntegritee: pallet_parentchain::::{Pallet, Call, Event} = 10, + ParentchainTargetA: pallet_parentchain::::{Pallet, Call, Event} = 11, + ParentchainTargetB: pallet_parentchain::::{Pallet, Call, Event} = 12, } ); @@ -292,14 +312,17 @@ construct_runtime!( NodeBlock = opaque::Block, UncheckedExtrinsic = UncheckedExtrinsic { - System: frame_system::{Pallet, Call, Config, Storage, Event}, - Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent}, - Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, - TransactionPayment: pallet_transaction_payment::{Pallet, Storage, Event}, - Sudo: pallet_sudo::{Pallet, Call, Config, Storage, Event}, - Parentchain: pallet_parentchain::{Pallet, Call, Storage, Event}, - - Evm: pallet_evm::{Pallet, Call, Storage, Config, Event}, + System: frame_system::{Pallet, Call, Config, Storage, Event} = 0, + Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent} = 1, + Balances: pallet_balances::{Pallet, Call, Storage, Config, Event} = 2, + TransactionPayment: pallet_transaction_payment::{Pallet, Storage, Event} = 3, + Sudo: pallet_sudo::{Pallet, Call, Config, Storage, Event} = 4, + + ParentchainIntegritee: pallet_parentchain::::{Pallet, Call, Event} = 10, + ParentchainTargetA: pallet_parentchain::::{Pallet, Call, Event} = 11, + ParentchainTargetB: pallet_parentchain::::{Pallet, Call, Event} = 12, + + Evm: pallet_evm::{Pallet, Call, Storage, Config, Event} = 20, } ); diff --git a/app-libs/stf/Cargo.toml b/app-libs/stf/Cargo.toml index f3dcab1610..0045590bc7 100644 --- a/app-libs/stf/Cargo.toml +++ b/app-libs/stf/Cargo.toml @@ -7,7 +7,6 @@ edition = "2021" [dependencies] # crates.io codec = { version = "3.0.0", default-features = false, features = ["derive"], package = "parity-scale-codec" } -derive_more = { version = "0.99.5" } log = { version = "0.4", default-features = false } rlp = { version = "0.5", default-features = false } serde = { version = "1.0", default-features = false, features = ["derive", "alloc"] } @@ -22,8 +21,8 @@ ita-sgx-runtime = { default-features = false, path = "../sgx-runtime" } itp-hashing = { default-features = false, path = "../../core-primitives/hashing" } itp-node-api = { default-features = false, path = "../../core-primitives/node-api" } itp-node-api-metadata = { default-features = false, path = "../../core-primitives/node-api/metadata" } -itp-node-api-metadata-provider = { default-features = false, path = "../../core-primitives/node-api/metadata-provider" } itp-sgx-externalities = { default-features = false, path = "../../core-primitives/substrate-sgx/externalities" } +itp-sgx-runtime-primitives = { default-features = false, path = "../../core-primitives/sgx-runtime-primitives" } itp-stf-interface = { default-features = false, path = "../../core-primitives/stf-interface" } itp-stf-primitives = { default-features = false, path = "../../core-primitives/stf-primitives" } itp-storage = { default-features = false, path = "../../core-primitives/storage" } @@ -35,16 +34,12 @@ sp-io = { default-features = false, features = ["disable_oom", "disable_panic_ha frame-support = { default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } frame-system = { default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } pallet-balances = { default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } +pallet-parentchain = { default-features = false, git = "https://github.com/integritee-network/pallets.git", branch = "sdk-v0.12.11-polkadot-v0.9.42" } pallet-sudo = { default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } -sp-application-crypto = { default-features = false, features = ["full_crypto"], git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } sp-core = { default-features = false, features = ["full_crypto"], git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } sp-runtime = { default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } sp-std = { default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } -# scs / integritee -my-node-runtime = { package = "integritee-node-runtime", optional = true, git = "https://github.com/integritee-network/integritee-node.git", branch = "sdk-v0.12.0-polkadot-v0.9.42" } -pallet-parentchain = { default-features = false, git = "https://github.com/integritee-network/pallets.git", branch = "sdk-v0.12.0-polkadot-v0.9.42" } - # simplyR binary-merkle-tree = { default-features = false, git = "https://github.com/paritytech/substrate.git" } simplyr-lib = { default-features = false, git = "https://github.com/BESTenergytrade/simplyr-lib.git", branch = "cI/usize" } @@ -61,7 +56,6 @@ sgx = [ "itp-sgx-externalities/sgx", "sp-io/sgx", "itp-node-api/sgx", - "itp-node-api-metadata-provider/sgx", ] std = [ # crates.io @@ -77,17 +71,14 @@ std = [ "itp-types/std", "itp-node-api/std", "itp-node-api-metadata/std", - "itp-node-api-metadata-provider/std", # substrate "sp-core/std", "pallet-balances/std", "pallet-sudo/std", "frame-system/std", "frame-support/std", - "sp-application-crypto/std", "sp-runtime/std", # scs/integritee - "my-node-runtime", "pallet-parentchain/std", "sp-io/std", ] diff --git a/app-libs/stf/src/best_energy_helpers.rs b/app-libs/stf/src/best_energy_helpers.rs index 8a01ecbb5b..1030e83a3e 100644 --- a/app-libs/stf/src/best_energy_helpers.rs +++ b/app-libs/stf/src/best_energy_helpers.rs @@ -1,11 +1,11 @@ -use crate::{MerkleProofWithCodec, StfError, String}; +use crate::MerkleProofWithCodec; use binary_merkle_tree::merkle_proof; use codec::Encode; use itp_stf_primitives::error::StfError; use simplyr_lib::{MarketOutput, Order}; use sp_core::H256; use sp_runtime::traits::Keccak256; -use std::{format, fs, vec::Vec}; +use std::{format, fs, string::String, vec::Vec}; pub static ORDERS_DIR: &str = "./records/orders"; pub static RESULTS_DIR: &str = "./records/market_results"; diff --git a/app-libs/stf/src/getter.rs b/app-libs/stf/src/getter.rs index 96412f0e9a..6074e7b40f 100644 --- a/app-libs/stf/src/getter.rs +++ b/app-libs/stf/src/getter.rs @@ -199,89 +199,99 @@ impl TrustedGetterSigned { impl ExecuteGetter for Getter { fn execute(self) -> Option> { match self { - Getter::trusted(g) => match &g.getter { - TrustedGetter::free_balance(who) => { - let info = System::account(&who); - debug!("TrustedGetter free_balance"); - debug!("AccountInfo for {} is {:?}", account_id_to_string(&who), info); - debug!("Account free balance is {}", info.data.free); - Some(info.data.free.encode()) - }, + Getter::trusted(g) => g.execute(), + Getter::public(g) => g.execute(), + } + } - TrustedGetter::reserved_balance(who) => { - let info = System::account(&who); - 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()) - }, - TrustedGetter::nonce(who) => { - let nonce = System::account_nonce(&who); - debug!("TrustedGetter nonce"); - debug!("Account nonce is {}", nonce); - Some(nonce.encode()) + 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) => { + let info = System::account(&who); + 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()) + }, + TrustedGetter::reserved_balance(who) => { + let info = System::account(&who); + 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()) + }, + TrustedGetter::nonce(who) => { + let nonce = System::account_nonce(&who); + debug!("TrustedGetter nonce"); + debug!("Account nonce is {}", nonce); + Some(nonce.encode()) + }, + #[cfg(feature = "evm")] + TrustedGetter::evm_nonce(who) => { + let evm_account = get_evm_account(&who); + let evm_account = HashedAddressMapping::into_account_id(evm_account); + let nonce = System::account_nonce(&evm_account); + debug!("TrustedGetter evm_nonce"); + debug!("Account nonce is {}", nonce); + Some(nonce.encode()) + }, + #[cfg(feature = "evm")] + TrustedGetter::evm_account_codes(_who, evm_account) => + // TODO: This probably needs some security check if who == evm_account (or assosciated) + if let Some(info) = get_evm_account_codes(&evm_account) { + debug!("TrustedGetter Evm Account Codes"); + debug!("AccountCodes for {} is {:?}", evm_account, info); + Some(info) // TOOD: encoded? + } else { + None }, - #[cfg(feature = "evm")] - TrustedGetter::evm_nonce(who) => { - let evm_account = get_evm_account(who); - let evm_account = HashedAddressMapping::into_account_id(evm_account); - let nonce = System::account_nonce(&evm_account); - debug!("TrustedGetter evm_nonce"); - debug!("Account nonce is {}", nonce); - Some(nonce.encode()) + #[cfg(feature = "evm")] + TrustedGetter::evm_account_storages(_who, evm_account, index) => + // TODO: This probably needs some security check if who == evm_account (or assosciated) + if let Some(value) = get_evm_account_storages(&evm_account, &index) { + debug!("TrustedGetter Evm Account Storages"); + debug!("AccountStorages for {} is {:?}", evm_account, value); + Some(value.encode()) + } else { + None }, - #[cfg(feature = "evm")] - TrustedGetter::evm_account_codes(_who, evm_account) => - // TODO: This probably needs some security check if who == evm_account (or assosciated) - if let Some(info) = get_evm_account_codes(evm_account) { - debug!("TrustedGetter Evm Account Codes"); - debug!("AccountCodes for {} is {:?}", evm_account, info); - Some(info) // TOOD: encoded? - } else { - None - }, - #[cfg(feature = "evm")] - TrustedGetter::evm_account_storages(_who, evm_account, index) => - // TODO: This probably needs some security check if who == evm_account (or assosciated) - if let Some(value) = get_evm_account_storages(evm_account, index) { - debug!("TrustedGetter Evm Account Storages"); - debug!("AccountStorages for {} is {:?}", evm_account, value); - Some(value.encode()) - } else { - None - }, - TrustedGetter::pay_as_bid_proof(_who, timestamp, actor_id) => { - let now = Instant::now(); + TrustedGetter::pay_as_bid_proof(_who, timestamp, actor_id) => { + let now = Instant::now(); - let proof = match get_merkle_proof_for_actor_from_file(timestamp, actor_id) { - Ok(proof) => proof, - Err(e) => { - log::error!("Getting Orders and Index Error, {:?}", e); - return None - }, - }; + let proof = match get_merkle_proof_for_actor_from_file(×tamp, &actor_id) { + Ok(proof) => proof, + Err(e) => { + log::error!("Getting Orders and Index Error, {:?}", e); + return None + }, + }; - let elapsed = now.elapsed(); - info!("Time Elapsed for PayAsBid Proof is: {:.2?}", elapsed); + let elapsed = now.elapsed(); + info!("Time Elapsed for PayAsBid Proof is: {:.2?}", elapsed); - Some(proof.encode()) - }, + Some(proof.encode()) + }, - TrustedGetter::get_market_results(_who, timestamp) => { - let market_results = match read_market_results(timestamp) { - Ok(market_results) => market_results, - Err(e) => { - log::error!("Getting Market Results Error, {:?}", e); - return None - }, - }; + TrustedGetter::get_market_results(_who, timestamp) => { + let market_results = match read_market_results(×tamp) { + Ok(market_results) => market_results, + Err(e) => { + log::error!("Getting Market Results Error, {:?}", e); + return None + }, + }; - Some(market_results.encode()) - }, - }, - Getter::public(g) => match g { - PublicGetter::some_value => Some(42u32.encode()), + Some(market_results.encode()) }, } } @@ -290,3 +300,14 @@ impl ExecuteGetter for Getter { Vec::new() } } +impl ExecuteGetter for PublicGetter { + fn execute(self) -> Option> { + match self { + PublicGetter::some_value => Some(42u32.encode()), + } + } + + fn get_storage_hashes_to_update(self) -> Vec> { + Vec::new() + } +} diff --git a/app-libs/stf/src/helpers.rs b/app-libs/stf/src/helpers.rs index 800a6b4884..af3f97f992 100644 --- a/app-libs/stf/src/helpers.rs +++ b/app-libs/stf/src/helpers.rs @@ -16,8 +16,14 @@ */ use crate::ENCLAVE_ACCOUNT_KEY; use codec::{Decode, Encode}; -use itp_stf_primitives::error::{StfError, StfResult}; +use ita_sgx_runtime::{ParentchainIntegritee, ParentchainTargetA, ParentchainTargetB}; +use itp_stf_interface::{BlockMetadata, ShardCreationInfo}; +use itp_stf_primitives::{ + error::{StfError, StfResult}, + types::AccountId, +}; use itp_storage::{storage_double_map_key, storage_map_key, storage_value_key, StorageHasher}; +use itp_types::parentchain::ParentchainId; use itp_utils::stringify::account_id_to_string; use log::*; use std::prelude::v1::*; @@ -103,3 +109,54 @@ pub fn ensure_enclave_signer_account( pub fn set_block_number(block_number: u32) { sp_io::storage::set(&storage_value_key("System", "Number"), &block_number.encode()); } + +/// get shard vault from any of the parentchain interfaces +/// We assume it has been ensured elsewhere that there can't be multiple shard vaults on multiple parentchains +pub fn shard_vault() -> Option<(AccountId, ParentchainId)> { + get_shard_vaults().into_iter().next() +} + +/// We assume it has been ensured elsewhere that there can't be multiple shard vaults on multiple parentchains +pub fn get_shard_vaults() -> Vec<(AccountId, ParentchainId)> { + [ + (ParentchainIntegritee::shard_vault(), ParentchainId::Integritee), + (ParentchainTargetA::shard_vault(), ParentchainId::TargetA), + (ParentchainTargetB::shard_vault(), ParentchainId::TargetB), + ] + .into_iter() + .filter_map(|vp| vp.0.map(|v| (v, vp.1))) + .collect() +} + +pub fn shard_creation_info() -> ShardCreationInfo { + let maybe_integritee_info: Option = + ParentchainIntegritee::creation_block_number().and_then(|number| { + ParentchainIntegritee::creation_block_hash().map(|hash| BlockMetadata { + number, + hash, + timestamp: ParentchainIntegritee::creation_timestamp(), + }) + }); + let maybe_target_a_info: Option = ParentchainTargetA::creation_block_number() + .and_then(|number| { + ParentchainTargetA::creation_block_hash().map(|hash| BlockMetadata { + number, + hash, + timestamp: ParentchainTargetA::creation_timestamp(), + }) + }); + let maybe_target_b_info: Option = ParentchainTargetB::creation_block_number() + .and_then(|number| { + ParentchainTargetB::creation_block_hash().map(|hash| BlockMetadata { + number, + hash, + timestamp: ParentchainTargetB::creation_timestamp(), + }) + }); + + ShardCreationInfo { + integritee: maybe_integritee_info, + target_a: maybe_target_a_info, + target_b: maybe_target_b_info, + } +} diff --git a/app-libs/stf/src/lib.rs b/app-libs/stf/src/lib.rs index c11dbba6d6..ed49ded475 100644 --- a/app-libs/stf/src/lib.rs +++ b/app-libs/stf/src/lib.rs @@ -45,3 +45,6 @@ pub mod test_genesis; pub mod trusted_call; 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/app-libs/stf/src/stf_sgx.rs b/app-libs/stf/src/stf_sgx.rs index 88d14822cb..e09e70a3ab 100644 --- a/app-libs/stf/src/stf_sgx.rs +++ b/app-libs/stf/src/stf_sgx.rs @@ -17,20 +17,27 @@ #[cfg(feature = "test")] use crate::test_genesis::test_genesis_setup; -use crate::{helpers::enclave_signer_account, Stf, ENCLAVE_ACCOUNT_KEY}; +use crate::{ + helpers::{enclave_signer_account, get_shard_vaults, shard_creation_info, shard_vault}, + Stf, ENCLAVE_ACCOUNT_KEY, +}; use codec::{Decode, Encode}; use frame_support::traits::{OriginTrait, UnfilteredDispatchable}; +use ita_sgx_runtime::{ + ParentchainInstanceIntegritee, ParentchainInstanceTargetA, ParentchainInstanceTargetB, +}; use itp_node_api::metadata::{provider::AccessNodeMetadata, NodeMetadataTrait}; use itp_sgx_externalities::SgxExternalitiesTrait; use itp_stf_interface::{ - parentchain_pallet::ParentchainPalletInterface, + parentchain_pallet::ParentchainPalletInstancesInterface, sudo_pallet::SudoPalletInterface, system_pallet::{SystemPalletAccountInterface, SystemPalletEventInterface}, - ExecuteCall, ExecuteGetter, InitState, StateCallInterface, StateGetterInterface, UpdateState, + ExecuteCall, ExecuteGetter, InitState, ShardCreationInfo, ShardCreationQuery, ShardVaultQuery, + StateCallInterface, StateGetterInterface, UpdateState, }; use itp_stf_primitives::{error::StfError, traits::TrustedCallVerification}; use itp_storage::storage_value_key; -use itp_types::{parentchain::ParentchainId, OpaqueCall}; +use itp_types::parentchain::{AccountId, ParentchainCall, ParentchainId}; use itp_utils::stringify::account_id_to_string; use log::*; use sp_runtime::traits::StaticLookup; @@ -143,7 +150,7 @@ where fn execute_call( state: &mut State, call: TCS, - calls: &mut Vec, + calls: &mut Vec, node_metadata_repo: Arc, ) -> Result<(), Self::Error> { state.execute_with(|| call.execute(calls, node_metadata_repo)) @@ -160,6 +167,24 @@ where } } +impl ShardVaultQuery for Stf +where + State: SgxExternalitiesTrait + Debug, +{ + fn get_vault(state: &mut State) -> Option<(AccountId, ParentchainId)> { + state.execute_with(shard_vault) + } +} + +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, @@ -232,27 +257,176 @@ where } } -impl ParentchainPalletInterface - for Stf +impl + ParentchainPalletInstancesInterface for Stf where State: SgxExternalitiesTrait, - Runtime: frame_system::Config
+ pallet_parentchain::Config, + 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_block( + fn update_parentchain_integritee_block( + state: &mut State, + header: ParentchainHeader, + ) -> Result<(), Self::Error> { + trace!("updating integritee 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 integritee 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 } + pallet_parentchain::Call::::set_block { header } .dispatch_bypass_filter(Runtime::RuntimeOrigin::root()) .map_err(|e| { - Self::Error::Dispatch(format!("Update parentchain block error: {:?}", e.error)) + Self::Error::Dispatch(format!( + "Update parentchain target_b block error: {:?}", + e.error + )) }) })?; Ok(()) } + + fn init_shard_vault_account( + state: &mut State, + vault: AccountId, + parentchain_id: ParentchainId, + ) -> Result<(), Self::Error> { + if let Some((existing_vault, existing_id)) = + Self::get_shard_vault_ensure_single_parentchain(state)? + { + if existing_id != parentchain_id { + return Err(Self::Error::ShardVaultOnMultipleParentchainsNotAllowed) + } + if existing_vault != vault { + return Err(Self::Error::ChangingShardVaultAccountNotAllowed) + } + warn!("attempting to init shard vault which has already been initialized"); + return Ok(()) + } + state.execute_with(|| match parentchain_id { + ParentchainId::Integritee => pallet_parentchain::Call::< + Runtime, + ParentchainInstanceIntegritee, + >::init_shard_vault { + account: vault, + } + .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::::init_shard_vault { + account: vault, + } + .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::::init_shard_vault { + account: vault, + } + .dispatch_bypass_filter(Runtime::RuntimeOrigin::root()) + .map_err(|e| { + Self::Error::Dispatch(format!("Init shard vault account 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::Integritee => pallet_parentchain::Call::< + Runtime, + ParentchainInstanceIntegritee, + >::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(()) + } + + fn get_shard_vault_ensure_single_parentchain( + state: &mut State, + ) -> Result, Self::Error> { + state.execute_with(|| { + let vaults = get_shard_vaults(); + match vaults.len() { + 0 => Ok(None), + 1 => Ok(Some(vaults[0].clone())), + _ => Err(Self::Error::Dispatch(format!( + "shard vault assigned to more than one parentchain: {:?}", + vaults + ))), + } + }) + } } /// Creates valid enclave account with a balance that is above the existential deposit. diff --git a/app-libs/stf/src/stf_sgx_tests.rs b/app-libs/stf/src/stf_sgx_tests.rs index 1aae51b27b..3a89fc40b1 100644 --- a/app-libs/stf/src/stf_sgx_tests.rs +++ b/app-libs/stf/src/stf_sgx_tests.rs @@ -19,10 +19,11 @@ 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, + parentchain_pallet::ParentchainPalletInstancesInterface, sudo_pallet::SudoPalletInterface, + system_pallet::SystemPalletAccountInterface, InitState, StateCallInterface, }; use itp_stf_primitives::types::{AccountId, Signature}; +use itp_types::parentchain::ParentchainId; use sp_core::{ ed25519::{Pair as Ed25519Pair, Signature as Ed25519Signature}, Pair, @@ -46,12 +47,15 @@ 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 vault = AccountId::new([2u8; 32]); + StfState::init_shard_vault_account(&mut state, vault, ParentchainId::Integritee).unwrap(); let shield_funds_call = TrustedCallSigned::new( TrustedCall::balance_shield( enclave_call_signer.public().into(), AccountId::new([1u8; 32]), 500u128, + ParentchainId::Integritee, ), 0, Signature::Ed25519(Ed25519Signature([0u8; 64])), diff --git a/app-libs/stf/src/test_genesis.rs b/app-libs/stf/src/test_genesis.rs index d65cdef41e..161dec8e5e 100644 --- a/app-libs/stf/src/test_genesis.rs +++ b/app-libs/stf/src/test_genesis.rs @@ -42,9 +42,9 @@ const ENDOWED_SEED: Seed = *b"12345678901234567890123456789012"; const SECOND_ENDOWED_SEED: Seed = *b"22345678901234567890123456789012"; const UNENDOWED_SEED: Seed = *b"92345678901234567890123456789012"; -const ALICE_FUNDS: Balance = 1000000000000000; -pub const ENDOWED_ACC_FUNDS: Balance = 2000; -pub const SECOND_ENDOWED_ACC_FUNDS: Balance = 1000; +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) diff --git a/app-libs/stf/src/trusted_call.rs b/app-libs/stf/src/trusted_call.rs index 2dda6c986e..b92bd6635e 100644 --- a/app-libs/stf/src/trusted_call.rs +++ b/app-libs/stf/src/trusted_call.rs @@ -24,7 +24,7 @@ use std::vec::Vec; #[cfg(feature = "evm")] use crate::evm_helpers::{create_code_hash, evm_create2_address, evm_create_address}; use crate::{ - helpers::{ensure_enclave_signer_account, get_storage_by_key_hash}, + helpers::{enclave_signer_account, ensure_enclave_signer_account, shard_vault}, Getter, }; use codec::{Compact, Decode, Encode}; @@ -32,19 +32,25 @@ use frame_support::{ensure, traits::UnfilteredDispatchable}; #[cfg(feature = "evm")] use ita_sgx_runtime::{AddressMapping, HashedAddressMapping}; pub use ita_sgx_runtime::{Balance, Index}; -use ita_sgx_runtime::{Runtime, System}; +use ita_sgx_runtime::{ + ParentchainInstanceIntegritee, ParentchainInstanceTargetA, ParentchainInstanceTargetB, + ParentchainIntegritee, Runtime, System, +}; use itp_node_api::metadata::{provider::AccessNodeMetadata, NodeMetadataTrait}; use itp_node_api_metadata::{ pallet_balances::BalancesCallIndexes, pallet_enclave_bridge::EnclaveBridgeCallIndexes, pallet_proxy::ProxyCallIndexes, }; -use itp_stf_interface::{ExecuteCall, SHARD_VAULT_KEY}; +use itp_stf_interface::ExecuteCall; use itp_stf_primitives::{ error::StfError, traits::{TrustedCallSigning, TrustedCallVerification}, types::{AccountId, KeyPair, ShardIdentifier, Signature, TrustedOperation}, }; -use itp_types::{parentchain::ProxyType, Address, OpaqueCall}; +use itp_types::{ + parentchain::{ParentchainCall, ParentchainId, ProxyType}, + Address, Moment, OpaqueCall, +}; use itp_utils::stringify::account_id_to_string; use log::*; use sp_core::{ @@ -72,8 +78,9 @@ pub enum TrustedCall { balance_set_balance(AccountId, AccountId, Balance, Balance), balance_transfer(AccountId, AccountId, Balance), balance_unshield(AccountId, AccountId, Balance, ShardIdentifier), // (AccountIncognito, BeneficiaryPublicAccount, Amount, Shard) - balance_shield(AccountId, AccountId, Balance), // (Root, AccountIncognito, Amount) + balance_shield(AccountId, AccountId, Balance, ParentchainId), // (Root, AccountIncognito, Amount, origin parentchain) pay_as_bid(AccountId, OrdersString), + timestamp_set(AccountId, Moment, ParentchainId), // (Root, now) #[cfg(feature = "evm")] evm_withdraw(AccountId, H160, Balance), // (Origin, Address EVM Account, Value) // (Origin, Source, Target, Input, Value, Gas limit, Max fee per gas, Max priority fee per gas, Nonce, Access list) @@ -128,6 +135,7 @@ impl TrustedCall { Self::balance_unshield(sender_account, ..) => sender_account, Self::balance_shield(sender_account, ..) => sender_account, Self::pay_as_bid(sender_account, _orders_string) => sender_account, + Self::timestamp_set(sender_account, ..) => sender_account, #[cfg(feature = "evm")] Self::evm_withdraw(sender_account, ..) => sender_account, #[cfg(feature = "evm")] @@ -226,7 +234,7 @@ where fn execute( self, - calls: &mut Vec, + calls: &mut Vec, node_metadata_repo: Arc, ) -> Result<(), Self::Error> { let sender = self.call.sender_account().clone(); @@ -271,12 +279,26 @@ where }, TrustedCall::balance_transfer(from, to, value) => { let origin = ita_sgx_runtime::RuntimeOrigin::signed(from.clone()); - debug!( - "balance_transfer({}, {}, {})", + 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 + 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, @@ -288,33 +310,40 @@ where Ok(()) }, TrustedCall::balance_unshield(account_incognito, beneficiary, value, shard) => { - debug!( - "balance_unshield({}, {}, {}, {})", + 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 ); - unshield_funds(account_incognito, value)?; - calls.push(OpaqueCall::from_tuple(&( - node_metadata_repo - .get_from_metadata(|m| m.unshield_funds_call_indexes()) - .map_err(|_| StfError::InvalidMetadata)? - .map_err(|_| StfError::InvalidMetadata)?, - shard, - beneficiary.clone(), - value, - call_hash, - ))); - // todo: the following is a placeholder dummy which will replace the above with #1257. - // the extrinsic will be sent and potentially deplete the vault at the current state which - // is nothing to worry about before we solve mentioned issue. - let vault_pubkey: [u8; 32] = get_storage_by_key_hash(SHARD_VAULT_KEY.into()) - .ok_or_else(|| { - StfError::Dispatch("shard vault key hasn't been set".to_string()) - })?; - let vault_address = Address::from(AccountId::from(vault_pubkey)); + let origin = ita_sgx_runtime::RuntimeOrigin::signed(account_incognito.clone()); + 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, value)?; + + let (vault, parentchain_id) = shard_vault().ok_or_else(|| { + StfError::Dispatch("shard vault key hasn't been set".to_string()) + })?; + let vault_address = Address::from(vault); let vault_transfer_call = OpaqueCall::from_tuple(&( node_metadata_repo .get_from_metadata(|m| m.transfer_keep_alive_call_indexes()) @@ -332,16 +361,33 @@ where None::, vault_transfer_call, )); - calls.push(proxy_call); + let parentchain_call = match parentchain_id { + ParentchainId::Integritee => ParentchainCall::Integritee(proxy_call), + ParentchainId::TargetA => ParentchainCall::TargetA(proxy_call), + ParentchainId::TargetB => ParentchainCall::TargetB(proxy_call), + }; + calls.push(parentchain_call); Ok(()) }, - TrustedCall::balance_shield(enclave_account, who, value) => { + TrustedCall::balance_shield(enclave_account, who, value, parentchain_id) => { ensure_enclave_signer_account(&enclave_account)?; - debug!("balance_shield({}, {})", account_id_to_string(&who), value); + debug!( + "balance_shield({}, {}, {:?})", + account_id_to_string(&who), + value, + parentchain_id + ); + let (_vault_account, vault_parentchain_id) = + shard_vault().ok_or(StfError::NoShardVaultAssigned)?; + ensure!( + parentchain_id == vault_parentchain_id, + StfError::WrongParentchainIdForShardVault + ); + std::println!("⣿STF⣿ 🛡 will shield to {}", account_id_to_string(&who)); shield_funds(who, value)?; // Send proof of execution on chain. - calls.push(OpaqueCall::from_tuple(&( + calls.push(ParentchainCall::Integritee(OpaqueCall::from_tuple(&( node_metadata_repo .get_from_metadata(|m| m.publish_hash_call_indexes()) .map_err(|_| StfError::InvalidMetadata)? @@ -349,7 +395,7 @@ where call_hash, Vec::::new(), b"shielded some funds!".to_vec(), - ))); + )))); Ok(()) }, @@ -405,7 +451,7 @@ where // Send proof of execution on chain. // calls is in the scope from the outside - calls.push(OpaqueCall::from_tuple(&( + calls.push(ParentchainCall::Integritee(OpaqueCall::from_tuple(&( node_metadata_repo .get_from_metadata(|m| m.publish_hash_call_indexes()) .map_err(|_| StfError::InvalidMetadata)? @@ -413,11 +459,67 @@ where order_merkle_root, Vec::::new(), // you can ignore this for now. Clients could subscribe to the hashes here to be notified when a new hash is published. b"Published merkle root of an order!".to_vec(), - ))); + )))); Ok(()) }, + TrustedCall::timestamp_set(enclave_account, now, parentchain_id) => { + ensure_enclave_signer_account(&enclave_account)?; + debug!("timestamp_set({}, {:?})", now, parentchain_id); + match parentchain_id { + ParentchainId::Integritee => { + if ParentchainIntegritee::creation_timestamp().is_none() { + debug!( + "initializing creation timestamp({}, {:?})", + now, parentchain_id + ); + ita_sgx_runtime::ParentchainPalletCall::< + Runtime, + ParentchainInstanceIntegritee, + >::set_creation_timestamp { + creation: now, + } + .dispatch_bypass_filter(ita_sgx_runtime::RuntimeOrigin::root()) + .map_err(|e| { + Self::Error::Dispatch(format!("Timestamp Set error: {:?}", e.error)) + })?; + }; + ita_sgx_runtime::ParentchainPalletCall::< + Runtime, + ParentchainInstanceIntegritee, + >::set_now { + now, + } + .dispatch_bypass_filter(ita_sgx_runtime::RuntimeOrigin::root()) + .map_err(|e| { + Self::Error::Dispatch(format!("Timestamp Set error: {:?}", e.error)) + })? + }, + ParentchainId::TargetA => ita_sgx_runtime::ParentchainPalletCall::< + Runtime, + ParentchainInstanceTargetA, + >::set_now { + now, + } + .dispatch_bypass_filter(ita_sgx_runtime::RuntimeOrigin::root()) + .map_err(|e| { + Self::Error::Dispatch(format!("Timestamp Set error: {:?}", e.error)) + })?, + ParentchainId::TargetB => ita_sgx_runtime::ParentchainPalletCall::< + Runtime, + ParentchainInstanceTargetB, + >::set_now { + now, + } + .dispatch_bypass_filter(ita_sgx_runtime::RuntimeOrigin::root()) + .map_err(|e| { + Self::Error::Dispatch(format!("Timestamp Set error: {:?}", e.error)) + })?, + }; + Ok(()) + }, + #[cfg(feature = "evm")] TrustedCall::evm_withdraw(from, address, value) => { debug!("evm_withdraw({}, {}, {})", account_id_to_string(&from), address, value); @@ -542,12 +644,13 @@ where fn get_storage_hashes_to_update(self) -> Vec> { let key_hashes = Vec::new(); match self.call { - TrustedCall::noop(_) => debug!("No storage updates needed..."), - TrustedCall::balance_set_balance(_, _, _, _) => debug!("No storage updates needed..."), - TrustedCall::balance_transfer(_, _, _) => debug!("No storage updates needed..."), - TrustedCall::balance_unshield(_, _, _, _) => debug!("No storage updates needed..."), - TrustedCall::balance_shield(_, _, _) => debug!("No storage updates needed..."), TrustedCall::pay_as_bid(_, _) => debug!("No storage updates needed..."), + TrustedCall::noop(..) => debug!("No storage updates needed..."), + TrustedCall::balance_set_balance(..) => debug!("No storage updates needed..."), + TrustedCall::balance_transfer(..) => debug!("No storage updates needed..."), + TrustedCall::balance_unshield(..) => debug!("No storage updates needed..."), + TrustedCall::balance_shield(..) => debug!("No storage updates needed..."), + TrustedCall::timestamp_set(..) => debug!("No storage updates needed..."), #[cfg(feature = "evm")] _ => debug!("No storage updates needed..."), }; @@ -555,7 +658,7 @@ where } } -fn unshield_funds(account: AccountId, amount: u128) -> Result<(), StfError> { +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) @@ -566,15 +669,30 @@ fn unshield_funds(account: AccountId, amount: u128) -> Result<(), StfError> { new_free: account_info.data.free - amount, } .dispatch_bypass_filter(ita_sgx_runtime::RuntimeOrigin::root()) - .map_err(|e| StfError::Dispatch(format!("Unshield funds error: {:?}", e.error)))?; + .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, + 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)))?; diff --git a/build.Dockerfile b/build.Dockerfile index 069ab8bafc..43a66ce363 100644 --- a/build.Dockerfile +++ b/build.Dockerfile @@ -103,12 +103,10 @@ ARG LOG_DIR=/usr/local/log ENV SCRIPT_DIR ${SCRIPT_DIR} ENV LOG_DIR ${LOG_DIR} -COPY --from=builder /root/work/worker/bin/integritee-cli /usr/local/bin -COPY --from=builder /root/work/worker/bin/orders /usr/local/worker-cli/orders +COPY --from=builder /home/ubuntu/work/worker/bin/integritee-cli /usr/local/bin COPY ./cli/*.sh /usr/local/worker-cli/ RUN ls -alt /usr/local/worker-cli -RUN ls -alt /usr/local/worker-cli/orders RUN chmod +x /usr/local/bin/integritee-cli ${SCRIPT_DIR}/*.sh RUN mkdir ${LOG_DIR} diff --git a/cli/Cargo.toml b/cli/Cargo.toml index fa404a1b67..9c6a0f615a 100644 --- a/cli/Cargo.toml +++ b/cli/Cargo.toml @@ -1,13 +1,12 @@ [package] name = "integritee-cli" -version = "0.12.0" +version = "0.12.11" authors = ["Integritee AG "] edition = "2021" [dependencies] array-bytes = { version = "6.0.0" } base58 = "0.2" -blake2-rfc = { version = "0.2.18" } chrono = "*" clap = { version = "3.1.6", features = ["derive"] } codec = { version = "3.0.0", package = "parity-scale-codec", features = ["derive"] } @@ -25,24 +24,26 @@ serde_json = "1.0" sgx_crypto_helper = { branch = "master", git = "https://github.com/apache/teaclave-sgx-sdk.git" } thiserror = "1.0" urlencoding = "2.1.3" -ws = { version = "0.9.1", features = ["ssl"] } # scs / integritee -my-node-runtime = { package = "integritee-node-runtime", git = "https://github.com/integritee-network/integritee-node.git", branch = "sdk-v0.12.0-polkadot-v0.9.42" } -pallet-enclave-bridge = { git = "https://github.com/integritee-network/pallets.git", branch = "sdk-v0.12.0-polkadot-v0.9.42" } +enclave-bridge-primitives = { git = "https://github.com/integritee-network/pallets.git", branch = "sdk-v0.12.11-polkadot-v0.9.42" } +ita-parentchain-interface = { path = "../app-libs/parentchain-interface" } +pallet-enclave-bridge = { git = "https://github.com/integritee-network/pallets.git", branch = "sdk-v0.12.11-polkadot-v0.9.42" } pallet-evm = { optional = true, git = "https://github.com/integritee-network/frontier.git", branch = "bar/polkadot-v0.9.42" } -pallet-teerex = { git = "https://github.com/integritee-network/pallets.git", branch = "sdk-v0.12.0-polkadot-v0.9.42" } +pallet-sidechain = { git = "https://github.com/integritee-network/pallets.git", branch = "sdk-v0.12.11-polkadot-v0.9.42" } +pallet-teeracle = { git = "https://github.com/integritee-network/pallets.git", branch = "sdk-v0.12.11-polkadot-v0.9.42" } +pallet-teerex = { git = "https://github.com/integritee-network/pallets.git", branch = "sdk-v0.12.11-polkadot-v0.9.42" } +teeracle-primitives = { git = "https://github.com/integritee-network/pallets.git", branch = "sdk-v0.12.11-polkadot-v0.9.42" } + # `default-features = false` to remove the jsonrpsee dependency. -enclave-bridge-primitives = { git = "https://github.com/integritee-network/pallets.git", branch = "sdk-v0.12.0-polkadot-v0.9.42" } # disable unsupported jsonrpcsee substrate-api-client = { default-features = false, features = ["std", "sync-api"], git = "https://github.com/scs/substrate-api-client.git", branch = "polkadot-v0.9.42-tag-v0.14.0" } substrate-client-keystore = { git = "https://github.com/scs/substrate-api-client.git", branch = "polkadot-v0.9.42-tag-v0.14.0" } # substrate dependencies -frame-system = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } pallet-balances = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } -sc-keystore = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } sp-application-crypto = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } +sp-consensus-aura = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } sp-core = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } sp-keyring = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } sp-keystore = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } diff --git a/cli/benchmark.sh b/cli/benchmark.sh old mode 100644 new mode 100755 diff --git a/cli/demo_shielding_unshielding.sh b/cli/demo_shielding_unshielding.sh index cb32046af2..549d83a87f 100755 --- a/cli/demo_shielding_unshielding.sh +++ b/cli/demo_shielding_unshielding.sh @@ -70,6 +70,7 @@ echo "" # the parentchain token is 12 decimal UNIT=$(( 10 ** 12 )) +FEE_TOLERANCE=$((10 ** 11)) # make these amounts greater than ED AMOUNT_SHIELD=$(( 6 * UNIT )) @@ -100,14 +101,14 @@ function wait_assert_state() for i in $(seq 1 $WAIT_ROUNDS); do sleep $WAIT_INTERVAL_SECONDS state=$(${CLIENT} trusted --mrenclave "$1" "$3" "$2") - if [ $state -eq "$4" ]; then + 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" + echo "Assert $2 $3 failed, expected = $4, actual = $state, tolerance = $FEE_TOLERANCE" exit 1 } @@ -195,8 +196,8 @@ wait_assert_state ${MRENCLAVE} ${ICGACCOUNTBOB} balance ${AMOUNT_TRANSFER} echo "✔ ok" echo "" -echo "* Un-shield ${AMOUNT_UNSHIELD} tokens from Alice's incognito account" -${CLIENT} trusted --mrenclave ${MRENCLAVE} --xt-signer //Alice unshield-funds ${ICGACCOUNTALICE} //Alice ${AMOUNT_UNSHIELD} +echo "* Un-shield ${AMOUNT_UNSHIELD} tokens from Alice's incognito account to Ferie's L1 account" +${CLIENT} trusted --mrenclave ${MRENCLAVE} unshield-funds ${ICGACCOUNTALICE} //Ferdie ${AMOUNT_UNSHIELD} echo "" echo "* Wait and assert Alice's incognito account balance... " diff --git a/cli/demo_indirect_invocation.sh b/cli/demo_shielding_unshielding_multiworker.sh similarity index 77% rename from cli/demo_indirect_invocation.sh rename to cli/demo_shielding_unshielding_multiworker.sh index b1c42dfce6..6d9b687b70 100755 --- a/cli/demo_indirect_invocation.sh +++ b/cli/demo_shielding_unshielding_multiworker.sh @@ -58,4 +58,12 @@ SCRIPT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) "${SCRIPT_DIR}"/demo_shielding_unshielding.sh -p "${INTEGRITEE_RPC_PORT}" -u "${INTEGRITEE_RPC_URL}" -V "${WORKER_1_URL}" -P "${WORKER_1_PORT}" -C "${CLIENT_BIN}" -t first "${SCRIPT_DIR}"/demo_shielding_unshielding.sh -p "${INTEGRITEE_RPC_PORT}" -u "${INTEGRITEE_RPC_URL}" -V "${WORKER_2_URL}" -P "${WORKER_2_PORT}" -C "${CLIENT_BIN}" -t second +if [ "$FLAVOR_ID" = offchain-worker ]; then + echo "offchain-worker does not support shard vault shielding, therefore we skip those tests" + exit 0 +fi + +"${SCRIPT_DIR}"/demo_shielding_unshielding_using_shard_vault.sh -p "${INTEGRITEE_RPC_PORT}" -u "${INTEGRITEE_RPC_URL}" -V "${WORKER_1_URL}" -P "${WORKER_1_PORT}" -C "${CLIENT_BIN}" -t first +"${SCRIPT_DIR}"/demo_shielding_unshielding_using_shard_vault.sh -p "${INTEGRITEE_RPC_PORT}" -u "${INTEGRITEE_RPC_URL}" -V "${WORKER_2_URL}" -P "${WORKER_2_PORT}" -C "${CLIENT_BIN}" -t second + exit 0 diff --git a/cli/demo_shielding_unshielding_using_shard_vault.sh b/cli/demo_shielding_unshielding_using_shard_vault.sh new file mode 100755 index 0000000000..d6a0ae9f0b --- /dev/null +++ b/cli/demo_shielding_unshielding_using_shard_vault.sh @@ -0,0 +1,290 @@ +#!/bin/bash + +# to make sure the script aborts when (sub-)function exits abnormally +set -e + +# Demonstrates how to shield tokens from the parentchain into the sidechain. +# +# setup: +# run all on localhost: +# integritee-node purge-chain --dev +# integritee-node --dev -lruntime=debug +# rm light_client_db.bin +# export RUST_LOG=integritee_service=info,ita_stf=debug +# integritee-service init_shard +# integritee-service shielding-key +# integritee-service signing-key +# integritee-service run +# +# then run this script + +# usage: +# demo_shielding_unshielding.sh -p -P -t -m file +# +# TEST_BALANCE_RUN is either "first" or "second" +# if -m file is set, the mrenclave will be read from file + +while getopts ":m:p:P:t:u:V:C:" opt; do + case $opt in + t) + TEST=$OPTARG + ;; + m) + READ_MRENCLAVE=$OPTARG + ;; + p) + INTEGRITEE_RPC_PORT=$OPTARG + ;; + P) + WORKER_1_PORT=$OPTARG + ;; + u) + INTEGRITEE_RPC_URL=$OPTARG + ;; + V) + WORKER_1_URL=$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"} + +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 node uri ${INTEGRITEE_RPC_URL}:${INTEGRITEE_RPC_PORT}" +echo "Using trusted-worker 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 )) +AMOUNT_TRANSFER=$(( 2 * UNIT )) +AMOUNT_UNSHIELD=$(( 1 * UNIT )) + +CLIENT="${CLIENT_BIN} -p ${INTEGRITEE_RPC_PORT} -P ${WORKER_1_PORT} -u ${INTEGRITEE_RPC_URL} -U ${WORKER_1_URL}" + +# offchain-worker only suppports indirect calls +CALLTYPE= +case "$FLAVOR_ID" in + sidechain) CALLTYPE="--direct" ;; + offchain-worker) : ;; + *) CALLTYPE="--direct" ;; +esac +echo "using call type: ${CALLTYPE} (empty means indirect)" + +# 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 +} + +# usage: +# wait_assert_state_parentchain +function wait_assert_state_parentchain() +{ + for i in $(seq 1 $WAIT_ROUNDS); do + sleep $WAIT_INTERVAL_SECONDS + state=$(${CLIENT} "$2" "$1") + if (( $3 >= state ? $3 - state < FEE_TOLERANCE : state - $3 < FEE_TOLERANCE)); then + return + else + echo -n "." + fi + done + echo + echo "Assert $1 $2 failed, expected = $3, 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 "" + +if [ "$READ_MRENCLAVE" = "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 <<< $($CLIENT 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; } + + +echo "* Create a new incognito account for Bob" +ICGACCOUNTBOB=$(${CLIENT} trusted --mrenclave ${MRENCLAVE} new-account) +echo " Bob's incognito account = ${ICGACCOUNTBOB}" +echo "" + +echo "* Query shard vault account" +VAULT=$(${CLIENT} trusted get-shard-vault) +echo " shard vault account = ${VAULT}" +echo "" + +# Asssert the initial balance of Charlie incognito +# The initial balance of Bob incognito should always be 0, as Bob is newly created +BALANCE_INCOGNITO_CHARLIE=0 +BALANCE_FERDIE=$(${CLIENT} balance //Ferdie) + +case $TEST in + first) + wait_assert_state ${MRENCLAVE} //Charlie balance 0 ;; + second) + wait_assert_state ${MRENCLAVE} //Charlie balance $(( AMOUNT_SHIELD - AMOUNT_TRANSFER - AMOUNT_UNSHIELD )) + BALANCE_INCOGNITO_CHARLIE=$(( AMOUNT_SHIELD - AMOUNT_TRANSFER - AMOUNT_UNSHIELD )) ;; + *) + echo "assuming first run of test" + wait_assert_state ${MRENCLAVE} //Charlie balance 0 ;; +esac + +echo "* Shield ${AMOUNT_SHIELD} tokens to Charlie's account on L2" +${CLIENT} transfer //Charlie ${VAULT} ${AMOUNT_SHIELD} +echo "" + +echo "* Wait and assert Charlie's L2 account balance... " +wait_assert_state ${MRENCLAVE} //Charlie balance $(( BALANCE_INCOGNITO_CHARLIE + AMOUNT_SHIELD )) +echo "✔ ok" + +echo "* Wait and assert Bob's incognito account balance... " +wait_assert_state ${MRENCLAVE} ${ICGACCOUNTBOB} balance 0 +echo "✔ ok" +echo "" + +echo "* Send ${AMOUNT_TRANSFER} funds from Charlie's L2 account to Bob's incognito account" +$CLIENT trusted --mrenclave ${MRENCLAVE} transfer //Charlie ${ICGACCOUNTBOB} ${AMOUNT_TRANSFER} +echo "" + +echo "* Wait and assert Charlie's L2 account balance... " +wait_assert_state ${MRENCLAVE} //Charlie balance $(( BALANCE_INCOGNITO_CHARLIE + AMOUNT_SHIELD - AMOUNT_TRANSFER )) +echo "✔ ok" + +echo "* Wait and assert Bob's incognito account balance... " +wait_assert_state ${MRENCLAVE} ${ICGACCOUNTBOB} balance ${AMOUNT_TRANSFER} +echo "✔ ok" +echo "" + +echo "* Un-shield ${AMOUNT_UNSHIELD} tokens from Charlie's incognito account to Ferie's L1 account" +${CLIENT} trusted --mrenclave ${MRENCLAVE} unshield-funds //Charlie //Ferdie ${AMOUNT_UNSHIELD} +echo "" + +echo "* Wait and assert Charlie's incognito account balance... " +wait_assert_state ${MRENCLAVE} //Charlie balance $(( BALANCE_INCOGNITO_CHARLIE + AMOUNT_SHIELD - AMOUNT_TRANSFER - AMOUNT_UNSHIELD )) +echo "✔ ok" + +echo "* Wait and assert Ferdie's Parentchain account balance... " +wait_assert_state_parentchain //Ferdie balance $(( BALANCE_FERDIE + AMOUNT_UNSHIELD )) +echo "✔ ok" + +echo "* Wait and assert Bob's incognito account balance... " +wait_assert_state ${MRENCLAVE} ${ICGACCOUNTBOB} balance ${AMOUNT_TRANSFER} +echo "✔ ok" + +# Test the nonce handling, using Bob's incognito account as the sender as Charlie's +# balance needs to be verified in the second round while Bob is newly created each time + +echo "* Create a new incognito account for Charlie" +ICGACCOUNTCHARLIE=$(${CLIENT} trusted --mrenclave ${MRENCLAVE} new-account) +echo " Charlie's incognito account = ${ICGACCOUNTCHARLIE}" +echo "" + +echo "* Assert Bob's incognito initial nonce..." +assert_state ${MRENCLAVE} ${ICGACCOUNTBOB} nonce 0 +echo "✔ ok" +echo "" + +echo "* Send 3 consecutive 0.2 UNIT balance Transfer Bob -> Charlie" +for i in $(seq 1 3); do + # use direct calls so they are submitted to the top pool synchronously + $CLIENT trusted $CALLTYPE --mrenclave ${MRENCLAVE} transfer ${ICGACCOUNTBOB} ${ICGACCOUNTCHARLIE} $(( AMOUNT_TRANSFER / 10 )) +done +echo "" + +echo "* Assert Bob's incognito current nonce..." +wait_assert_state ${MRENCLAVE} ${ICGACCOUNTBOB} nonce 3 +echo "✔ ok" +echo "" + +echo "* Send a 2 UNIT balance Transfer Bob -> Charlie (that will fail)" +$CLIENT trusted $CALLTYPE --mrenclave ${MRENCLAVE} transfer ${ICGACCOUNTBOB} ${ICGACCOUNTCHARLIE} ${AMOUNT_TRANSFER} +echo "" + +echo "* Assert Bob's incognito nonce..." +# the nonce should be increased nontheless, even for the failed tx +wait_assert_state ${MRENCLAVE} ${ICGACCOUNTBOB} nonce 4 +echo "✔ ok" +echo "" + +echo "* Send another 0.2 UNIT balance Transfer Bob -> Charlie" +$CLIENT trusted $CALLTYPE --mrenclave ${MRENCLAVE} transfer ${ICGACCOUNTBOB} ${ICGACCOUNTCHARLIE} $(( AMOUNT_TRANSFER / 10 )) +echo "" + +echo "* Assert Bob's incognito nonce..." +wait_assert_state ${MRENCLAVE} ${ICGACCOUNTBOB} nonce 5 +echo "✔ ok" +echo "" + +echo "* Wait and assert Bob's incognito account balance... " +# in total 4 balance transfer should go through => 1.2 UNIT remaining +wait_assert_state ${MRENCLAVE} ${ICGACCOUNTBOB} balance $(( AMOUNT_TRANSFER * 6 / 10 )) +echo "✔ ok" + +echo "" +echo "-----------------------" +echo "✔ The $TEST test passed!" +echo "-----------------------" +echo "" diff --git a/cli/demo_shielding_unshielding_using_shard_vault_on_target_a.sh b/cli/demo_shielding_unshielding_using_shard_vault_on_target_a.sh new file mode 100755 index 0000000000..b3b978adc7 --- /dev/null +++ b/cli/demo_shielding_unshielding_using_shard_vault_on_target_a.sh @@ -0,0 +1,304 @@ +#!/bin/bash + +# to make sure the script aborts when (sub-)function exits abnormally +set -e + +# Demonstrates how to shield tokens from the parentchain into the sidechain. +# +# setup: +# run all on localhost: +# integritee-node purge-chain --dev +# integritee-node --dev -lruntime=debug +# rm light_client_db.bin +# export RUST_LOG=integritee_service=info,ita_stf=debug +# integritee-service init_shard +# integritee-service shielding-key +# integritee-service signing-key +# integritee-service run +# +# then run this script + +# usage: +# demo_shielding_unshielding.sh -p -P -t -m file +# +# TEST_BALANCE_RUN is either "first" or "second" +# if -m file is set, the mrenclave will be read from file + +while getopts ":m:p:P:t:u:V:C:a:A:" opt; do + case $opt in + t) + TEST=$OPTARG + ;; + m) + READ_MRENCLAVE=$OPTARG + ;; + p) + INTEGRITEE_RPC_PORT=$OPTARG + ;; + a) + TARGET_A_RPC_PORT=$OPTARG + ;; + P) + WORKER_1_PORT=$OPTARG + ;; + u) + INTEGRITEE_RPC_URL=$OPTARG + ;; + A) + TARGET_A_RPC_URL=$OPTARG + ;; + V) + WORKER_1_URL=$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_RPC_PORT=${TARGET_A_RPC_PORT:-9954} +TARGET_A_RPC_URL=${TARGET_A_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 node uri ${INTEGRITEE_RPC_URL}:${INTEGRITEE_RPC_PORT}" +echo "Using target_a node uri ${TARGET_A_RPC_URL}:${TARGET_A_RPC_PORT}" +echo "Using trusted-worker 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 )) +AMOUNT_TRANSFER=$(( 2 * UNIT )) +AMOUNT_UNSHIELD=$(( 1 * UNIT )) + +CLIENT="${CLIENT_BIN} -p ${INTEGRITEE_RPC_PORT} -P ${WORKER_1_PORT} -u ${INTEGRITEE_RPC_URL} -U ${WORKER_1_URL}" + +# for talking to TARGET_A L1 +CLIENT_A="${CLIENT_BIN} -p ${TARGET_A_RPC_PORT} -P ${WORKER_1_PORT} -u ${TARGET_A_RPC_URL} -U ${WORKER_1_URL}" + +# offchain-worker only suppports indirect calls +CALLTYPE= +case "$FLAVOR_ID" in + sidechain) CALLTYPE="--direct" ;; + offchain-worker) : ;; + *) CALLTYPE="--direct" ;; +esac +echo "using call type: ${CALLTYPE} (empty means indirect)" + +# interval and max rounds to wait to check the given account balance in sidechain +WAIT_INTERVAL_SECONDS=6 +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 + echo -n "." + fi + done + echo + echo "Assert $2 $3 failed, expected = $4, actual = $state, tolerance = $FEE_TOLERANCE" + exit 1 +} + +# usage: +# wait_assert_state_target_a +function wait_assert_state_target_a() +{ + for i in $(seq 1 $WAIT_ROUNDS); do + sleep $WAIT_INTERVAL_SECONDS + state=$(${CLIENT_A} "$2" "$1") + if (( $3 >= state ? $3 - state < FEE_TOLERANCE : state - $3 < FEE_TOLERANCE)); then + return + else + echo -n "." + fi + done + echo + echo "Assert $1 $2 failed, expected = $3, 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 "" + +if [ "$READ_MRENCLAVE" = "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 <<< $($CLIENT 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; } + + +echo "* Create a new incognito account for Bob" +ICGACCOUNTBOB=$(${CLIENT} trusted --mrenclave ${MRENCLAVE} new-account) +echo " Bob's incognito account = ${ICGACCOUNTBOB}" +echo "" + +echo "* Query shard vault account" +VAULT=$(${CLIENT} trusted get-shard-vault) +echo " shard vault account = ${VAULT}" +echo "" + +# Asssert the initial balance of Charlie incognito +# The initial balance of Bob incognito should always be 0, as Bob is newly created +BALANCE_INCOGNITO_CHARLIE=0 +BALANCE_A_FERDIE=$(${CLIENT_A} balance //Ferdie) + +case $TEST in + first) + wait_assert_state ${MRENCLAVE} //Charlie balance 0 ;; + second) + wait_assert_state ${MRENCLAVE} //Charlie balance $(( AMOUNT_SHIELD - AMOUNT_TRANSFER - AMOUNT_UNSHIELD )) + BALANCE_INCOGNITO_CHARLIE=$(( AMOUNT_SHIELD - AMOUNT_TRANSFER - AMOUNT_UNSHIELD )) ;; + *) + echo "assuming first run of test" + wait_assert_state ${MRENCLAVE} //Charlie balance 0 ;; +esac + +echo "* Shield ${AMOUNT_SHIELD} tokens from TARGET_A to Charlie's account on L2" +${CLIENT_A} transfer //Alice //Charlie $((AMOUNT_SHIELD * 2)) +${CLIENT_A} transfer //Charlie ${VAULT} ${AMOUNT_SHIELD} +echo "" + +echo "* Wait and assert Charlie's L2 account balance... " +wait_assert_state ${MRENCLAVE} //Charlie balance $(( BALANCE_INCOGNITO_CHARLIE + AMOUNT_SHIELD )) +echo "✔ ok" + +echo "* Wait and assert Bob's incognito account balance... " +wait_assert_state ${MRENCLAVE} ${ICGACCOUNTBOB} balance 0 +echo "✔ ok" +echo "" + +echo "* Send ${AMOUNT_TRANSFER} funds from Charlie's L2 account to Bob's incognito account" +$CLIENT trusted $CALLTYPE --mrenclave ${MRENCLAVE} transfer //Charlie ${ICGACCOUNTBOB} ${AMOUNT_TRANSFER} +echo "" + +echo "* Wait and assert Charlie's L2 account balance... " +wait_assert_state ${MRENCLAVE} //Charlie balance $(( BALANCE_INCOGNITO_CHARLIE + AMOUNT_SHIELD - AMOUNT_TRANSFER )) +echo "✔ ok" + +echo "* Wait and assert Bob's incognito account balance... " +wait_assert_state ${MRENCLAVE} ${ICGACCOUNTBOB} balance ${AMOUNT_TRANSFER} +echo "✔ ok" +echo "" + +echo "* Un-shield ${AMOUNT_UNSHIELD} tokens from Charlie's incognito account to Ferie's L1 account" +${CLIENT} trusted $CALLTYPE --mrenclave ${MRENCLAVE} unshield-funds //Charlie //Ferdie ${AMOUNT_UNSHIELD} +echo "" + +echo "* Wait and assert Charlie's incognito account balance... " +wait_assert_state ${MRENCLAVE} //Charlie balance $(( BALANCE_INCOGNITO_CHARLIE + AMOUNT_SHIELD - AMOUNT_TRANSFER - AMOUNT_UNSHIELD )) +echo "✔ ok" + +echo "* Wait and assert Ferdie's Target A account balance... " +wait_assert_state_target_a //Ferdie balance $(( BALANCE_A_FERDIE + AMOUNT_UNSHIELD )) +echo "✔ ok" + +echo "* Wait and assert Bob's incognito account balance... " +wait_assert_state ${MRENCLAVE} ${ICGACCOUNTBOB} balance ${AMOUNT_TRANSFER} +echo "✔ ok" + +# Test the nonce handling, using Bob's incognito account as the sender as Charlie's +# balance needs to be verified in the second round while Bob is newly created each time + +echo "* Create a new incognito account for Charlie" +ICGACCOUNTCHARLIE=$(${CLIENT} trusted --mrenclave ${MRENCLAVE} new-account) +echo " Charlie's incognito account = ${ICGACCOUNTCHARLIE}" +echo "" + + +echo "* Assert Bob's incognito initial nonce..." +assert_state ${MRENCLAVE} ${ICGACCOUNTBOB} nonce 0 +echo "✔ ok" +echo "" + +echo "* Send 3 consecutive 0.2 UNIT balance Transfer Bob -> Charlie" +for i in $(seq 1 3); do + # use direct calls so they are submitted to the top pool synchronously + $CLIENT trusted $CALLTYPE --mrenclave ${MRENCLAVE} transfer ${ICGACCOUNTBOB} ${ICGACCOUNTCHARLIE} $(( AMOUNT_TRANSFER / 10 )) +done +echo "" + +echo "* Assert Bob's incognito current nonce..." +wait_assert_state ${MRENCLAVE} ${ICGACCOUNTBOB} nonce 3 +echo "✔ ok" +echo "" + +echo "* Send a 2 UNIT balance Transfer Bob -> Charlie (that will fail)" +$CLIENT trusted $CALLTYPE --mrenclave ${MRENCLAVE} transfer ${ICGACCOUNTBOB} ${ICGACCOUNTCHARLIE} ${AMOUNT_TRANSFER} +echo "" + +echo "* Assert Bob's incognito nonce..." +# the nonce should be increased nontheless, even for the failed tx +wait_assert_state ${MRENCLAVE} ${ICGACCOUNTBOB} nonce 4 +echo "✔ ok" +echo "" + +echo "* Send another 0.2 UNIT balance Transfer Bob -> Charlie" +$CLIENT trusted $CALLTYPE --mrenclave ${MRENCLAVE} transfer ${ICGACCOUNTBOB} ${ICGACCOUNTCHARLIE} $(( AMOUNT_TRANSFER / 10 )) +echo "" + +echo "* Assert Bob's incognito nonce..." +wait_assert_state ${MRENCLAVE} ${ICGACCOUNTBOB} nonce 5 +echo "✔ ok" +echo "" + +echo "* Wait and assert Bob's incognito account balance... " +# in total 4 balance transfer should go through => 1.2 UNIT remaining +wait_assert_state ${MRENCLAVE} ${ICGACCOUNTBOB} balance $(( AMOUNT_TRANSFER * 6 / 10 )) +echo "✔ ok" + +echo "" +echo "-----------------------" +echo "✔ The $TEST test passed!" +echo "-----------------------" +echo "" diff --git a/cli/demo_sidechain.sh b/cli/demo_sidechain.sh index 91aa437564..f4db542b76 100755 --- a/cli/demo_sidechain.sh +++ b/cli/demo_sidechain.sh @@ -75,8 +75,12 @@ echo "Using node uri ${INTEGRITEE_RPC_URL}:${INTEGRITEE_RPC_PORT}" echo "Using trusted-worker 1 uri ${WORKER_1_URL}:${WORKER_1_PORT}" echo "Using trusted-worker 2 uri ${WORKER_2_URL}:${WORKER_2_PORT}" -INITIALFUNDS=50000000000 -AMOUNTTRANSFER=20000000000 +# the parentchain token is 12 decimal +UNIT=$(( 10 ** 12 )) +FEE_TOLERANCE=$((10 ** 11)) + +INITIALFUNDS=$((5 * UNIT)) +AMOUNTTRANSFER=$((2 * UNIT)) CLIENTWORKER1="${CLIENT_BIN} -p ${INTEGRITEE_RPC_PORT} -P ${WORKER_1_PORT} -u ${INTEGRITEE_RPC_URL} -U ${WORKER_1_URL}" CLIENTWORKER2="${CLIENT_BIN} -p ${INTEGRITEE_RPC_PORT} -P ${WORKER_2_PORT} -u ${INTEGRITEE_RPC_URL} -U ${WORKER_2_URL}" @@ -141,12 +145,12 @@ BOB_BALANCE=$(${CLIENTWORKER2} trusted --mrenclave ${MRENCLAVE} balance ${ICGACC echo "$BOB_BALANCE" echo "" -ALICE_EXPECTED_BALANCE=10000000000 -BOB_EXPECTED_BALANCE=40000000000 +ALICE_EXPECTED_BALANCE=$(( 1 * UNIT )) +BOB_EXPECTED_BALANCE=$(( 4 * UNIT )) echo "* Verifying Alice's balance" -if [ "$ALICE_BALANCE" -ne "$ALICE_EXPECTED_BALANCE" ]; then - echo "Alice's balance is wrong (expected: $ALICE_EXPECTED_BALANCE, actual: $ALICE_BALANCE)" +if (( ALICE_BALANCE >= ALICE_EXPECTED_BALANCE ? ALICE_BALANCE - ALICE_EXPECTED_BALANCE > FEE_TOLERANCE : ALICE_EXPECTED_BALANCE - ALICE_BALANCE > FEE_TOLERANCE)); then + echo "Alice's balance is wrong (expected: $ALICE_EXPECTED_BALANCE, actual: $ALICE_BALANCE), tolerance = $FEE_TOLERANCE" exit 1 else echo "Alice's balance is correct ($ALICE_BALANCE)" diff --git a/cli/src/base_cli/commands/faucet.rs b/cli/src/base_cli/commands/faucet.rs index 94a7493bbc..40a4a45c46 100644 --- a/cli/src/base_cli/commands/faucet.rs +++ b/cli/src/base_cli/commands/faucet.rs @@ -19,11 +19,15 @@ use crate::{ command_utils::{get_accountid_from_str, get_chain_api}, Cli, CliResult, CliResultOk, }; -use my_node_runtime::{BalancesCall, RuntimeCall}; +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_extrinsic_offline, SubmitExtrinsic}; +use substrate_api_client::{ + ac_compose_macros::{compose_call, compose_extrinsic_offline}, + SubmitExtrinsic, +}; const PREFUNDING_AMOUNT: u128 = 1_000_000_000; @@ -41,15 +45,15 @@ impl FaucetCommand { 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(), - RuntimeCall::Balances(BalancesCall::transfer { - dest: MultiAddress::Id(to.clone()), - value: PREFUNDING_AMOUNT - }), - api.extrinsic_params(nonce) - ); + 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(); diff --git a/cli/src/base_cli/commands/listen.rs b/cli/src/base_cli/commands/listen.rs index b3ccf44b6b..36d1e405ad 100644 --- a/cli/src/base_cli/commands/listen.rs +++ b/cli/src/base_cli/commands/listen.rs @@ -16,11 +16,10 @@ */ use crate::{command_utils::get_chain_api, Cli, CliResult, CliResultOk}; -use base58::ToBase58; -use codec::Encode; + +use itp_types::parentchain::{AddedSgxEnclave, BalanceTransfer}; use log::*; -use my_node_runtime::{Hash, RuntimeEvent}; -use substrate_api_client::SubscribeEvents; +use substrate_api_client::{GetChainInfo, SubscribeEvents}; #[derive(Parser)] pub struct ListenCommand { @@ -37,7 +36,7 @@ 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"); + info!("Subscribing to events (solo or para)"); let mut count = 0u32; let mut blocks = 0u32; let mut subscription = api.subscribe_events().unwrap(); @@ -53,110 +52,36 @@ impl ListenCommand { } }; - let event_results = subscription.next_events::().unwrap(); + let events = subscription.next_events_from_metadata().unwrap().unwrap(); blocks += 1; - match event_results { - Ok(evts) => - for evr in &evts { - println!("decoded: phase {:?} event {:?}", evr.phase, evr.event); - match &evr.event { - RuntimeEvent::Balances(be) => { - println!(">>>>>>>>>> balances event: {:?}", be); - match &be { - pallet_balances::Event::Transfer { from, to, amount } => { - println!("From: {:?}", from); - println!("To: {:?}", to); - println!("Value: {:?}", amount); - }, - _ => { - debug!("ignoring unsupported balances event"); - }, - } - }, - RuntimeEvent::Teerex(ee) => { - println!(">>>>>>>>>> integritee teerex event: {:?}", ee); - count += 1; - match &ee { - my_node_runtime::pallet_teerex::Event::AddedSgxEnclave{ - registered_by, - worker_url, .. - } - => { - println!( - "AddedEnclave: {:?} at url {}", - registered_by, - String::from_utf8(worker_url.clone().unwrap_or("none".into()).to_vec()) - .unwrap_or_else(|_| "error".to_string()) - ); - }, - my_node_runtime::pallet_teerex::Event::RemovedSovereignEnclave( - accountid, - ) => { - println!("RemovedEnclave: {:?}", accountid); - }, - my_node_runtime::pallet_teerex::Event::RemovedProxiedEnclave( - eia, - ) => { - println!("RemovedEnclave: {:?}", eia); - }, - _ => debug!("ignoring unsupported teerex event: {:?}", ee), - } - }, - RuntimeEvent::EnclaveBridge(ee) => { - println!(">>>>>>>>>> integritee enclave bridge event: {:?}", ee); - count += 1; - match &ee { - my_node_runtime::pallet_enclave_bridge::Event::IndirectInvocationRegistered(shard) => { - println!( - "Forwarded request for shard {}", - shard.encode().to_base58() - ); - }, - my_node_runtime::pallet_enclave_bridge::Event::ProcessedParentchainBlock { - shard, - block_hash, - trusted_calls_merkle_root, - block_number, - } => { - println!( - "ProcessedParentchainBlock from {} with hash {:?}, number {} and merkle root {:?}", - shard, block_hash, trusted_calls_merkle_root, block_number - ); - }, - my_node_runtime::pallet_enclave_bridge::Event::ShieldFunds { - shard, encrypted_beneficiary, amount - } => { - println!("ShieldFunds on shard {:?} for {:?}. amount: {:?}", shard, encrypted_beneficiary, amount); - }, - my_node_runtime::pallet_enclave_bridge::Event::UnshieldedFunds { - shard, beneficiary, amount - } => { - println!("UnshieldFunds on shard {:?} for {:?}. amount: {:?}", shard, beneficiary, amount); - }, - _ => debug!("ignoring unsupported enclave_bridge event: {:?}", ee), - } + 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); }, - RuntimeEvent::Sidechain(ee) => { - println!(">>>>>>>>>> integritee sidechain event: {:?}", ee); - count += 1; - match &ee { - my_node_runtime::pallet_sidechain::Event::FinalizedSidechainBlock { - shard, - block_header_hash, - validateer, - } => { - println!( - "ProposedSidechainBlock on shard {} from {} with hash {:?}", - shard, validateer, block_header_hash - ); - }, - _ => debug!("ignoring unsupported sidechain event: {:?}", ee), - } - }, - _ => debug!("ignoring unsupported module event: {:?}", evr.event), - } + _ => println!("{}::{}", event.pallet_name(), event.variant_name()), + }, + "Teerex" => match event.variant_name() { + "AddedSgxEnclave" => { + if let Ok(Some(ev)) = event.as_event::() { + println!("Teerex::{:?}", ev); + } + }, + _ => println!("{}::{}", event.pallet_name(), event.variant_name()), }, - Err(_) => error!("couldn't decode event record list"), + _ => println!("{}::{}", event.pallet_name(), event.variant_name()), + } } } } diff --git a/cli/src/base_cli/commands/shield_funds.rs b/cli/src/base_cli/commands/shield_funds.rs index adadaa99cb..b393887182 100644 --- a/cli/src/base_cli/commands/shield_funds.rs +++ b/cli/src/base_cli/commands/shield_funds.rs @@ -21,11 +21,11 @@ use crate::{ }; use base58::FromBase58; use codec::{Decode, Encode}; +use ita_parentchain_interface::integritee::Balance; use itp_node_api::api_client::ENCLAVE_BRIDGE; use itp_sgx_crypto::ShieldingCryptoEncrypt; use itp_stf_primitives::types::ShardIdentifier; use log::*; -use my_node_runtime::Balance; use sp_core::sr25519 as sr25519_core; use substrate_api_client::{ac_compose_macros::compose_extrinsic, SubmitAndWatch, XtStatus}; diff --git a/cli/src/base_cli/commands/transfer.rs b/cli/src/base_cli/commands/transfer.rs index a3978c9f03..d8b26f0b90 100644 --- a/cli/src/base_cli/commands/transfer.rs +++ b/cli/src/base_cli/commands/transfer.rs @@ -19,8 +19,8 @@ use crate::{ command_utils::{get_accountid_from_str, get_chain_api, *}, Cli, CliResult, CliResultOk, }; +use ita_parentchain_interface::integritee::Balance; use log::*; -use my_node_runtime::Balance; use sp_core::{crypto::Ss58Codec, Pair}; use substrate_api_client::{ extrinsic::BalancesExtrinsics, GetAccountInformation, SubmitAndWatch, XtStatus, diff --git a/cli/src/benchmark/mod.rs b/cli/src/benchmark/mod.rs index f549a27c3e..bce9ad405c 100644 --- a/cli/src/benchmark/mod.rs +++ b/cli/src/benchmark/mod.rs @@ -19,15 +19,13 @@ use crate::{ command_utils::get_worker_api_direct, get_layer_two_nonce, trusted_cli::TrustedCli, - trusted_command_utils::{ - decode_balance, get_identifiers, get_keystore_path, get_pair_from_str, - }, + trusted_command_utils::{get_identifiers, get_keystore_path, get_pair_from_str}, trusted_operation::{get_json_request, get_state, perform_trusted_operation, wait_until}, Cli, CliResult, CliResultOk, SR25519_KEY_TYPE, }; use codec::Decode; use hdrhistogram::Histogram; -use ita_stf::{Getter, Index, TrustedCall, TrustedCallSigned, TrustedGetter}; +use ita_stf::{Getter, Index, TrustedCall, TrustedCallSigned, TrustedGetter, STF_TX_FEE}; use itc_rpc_client::direct_client::{DirectApi, DirectClient}; use itp_stf_primitives::{ traits::TrustedCallSigning, @@ -66,7 +64,7 @@ pub struct BenchmarkCommand { /// The number of iterations to execute for each client #[clap(default_value_t = 30)] - number_iterations: u32, + 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)] @@ -138,16 +136,15 @@ impl BenchmarkCommand { 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 {}", i); + 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()); - let initial_balance = 10000000; // Transfer amount from Alice to new account. let top: TrustedOperation = TrustedCall::balance_transfer( @@ -228,12 +225,12 @@ impl BenchmarkCommand { let balance = get_balance(client.account.clone(), shard, &client.client_api); println!("Balance: {}", balance.unwrap_or_default()); - assert_eq!(client.current_balance, balance.unwrap()); + 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 { + if client.current_balance <= EXISTENTIAL_DEPOSIT + STF_TX_FEE { error!("Account {:?} does not have enough balance anymore. Finishing benchmark early", client.account.public()); break; } @@ -289,13 +286,8 @@ fn get_nonce( ); let getter_start_timer = Instant::now(); - let getter_result = get_state(direct_client, shard, &getter).unwrap_or_default(); + let nonce = get_state::(direct_client, shard, &getter).ok().unwrap_or_default(); let getter_execution_time = getter_start_timer.elapsed().as_millis(); - - let nonce = match getter_result { - Some(encoded_nonce) => Index::decode(&mut encoded_nonce.as_slice()).unwrap(), - None => Default::default(), - }; info!("Nonce getter execution took {} ms", getter_execution_time,); debug!("Retrieved {:?} nonce for {:?}", nonce, account.public()); nonce @@ -375,3 +367,14 @@ fn is_submitted(s: TrustedOperationStatus) -> bool { 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/cli/src/command_utils.rs b/cli/src/command_utils.rs index 0a287471ba..108efc3755 100644 --- a/cli/src/command_utils.rs +++ b/cli/src/command_utils.rs @@ -17,10 +17,10 @@ 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 my_node_runtime::{AccountId, Signature}; use sgx_crypto_helper::rsa3072::Rsa3072PubKey; use sp_application_crypto::sr25519; use sp_core::{crypto::Ss58Codec, Pair}; diff --git a/cli/src/error.rs b/cli/src/error.rs deleted file mode 100644 index 973aa1cbb8..0000000000 --- a/cli/src/error.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 itp_node_api::api_client::ApiClientError; -use itp_types::parentchain::{BlockHash, BlockNumber}; -use std::result::Result as StdResult; - -pub type Result = StdResult; - -#[derive(Debug, thiserror::Error)] -pub enum Error { - #[error("{0:?}")] - ApiClient(ApiClientError), - #[error("Could not retrieve Header from node")] - MissingBlock, - #[error("Confirmed Block Number ({0:?}) exceeds expected one ({0:?})")] - ConfirmedBlockNumberTooHigh(BlockNumber, BlockNumber), - #[error("Confirmed Block Hash ({0:?}) does not match expected one ({0:?})")] - ConfirmedBlockHashDoesNotMatchExpected(BlockHash, BlockHash), -} - -impl From for Error { - fn from(error: ApiClientError) -> Self { - Error::ApiClient(error) - } -} diff --git a/cli/src/evm/commands/evm_call.rs b/cli/src/evm/commands/evm_call.rs index ecfe7b04a7..242993700b 100644 --- a/cli/src/evm/commands/evm_call.rs +++ b/cli/src/evm/commands/evm_call.rs @@ -22,7 +22,6 @@ use crate::{ trusted_operation::perform_trusted_operation, Cli, CliResult, CliResultOk, }; -use codec::Decode; use ita_stf::{Index, TrustedCall, TrustedGetter}; use itp_stf_primitives::{ traits::TrustedCallSigning, @@ -82,7 +81,7 @@ impl EvmCallCommands { ) .sign(&KeyPair::Sr25519(Box::new(sender)), nonce, &mrenclave, &shard) .into_trusted_operation(trusted_args.direct); - Ok(perform_trusted_operation(cli, trusted_args, &function_call) + Ok(perform_trusted_operation::<()>(cli, trusted_args, &function_call) .map(|_| CliResultOk::None)?) } } diff --git a/cli/src/evm/commands/evm_command_utils.rs b/cli/src/evm/commands/evm_command_utils.rs index 633ecfff83..cc8c5fff34 100644 --- a/cli/src/evm/commands/evm_command_utils.rs +++ b/cli/src/evm/commands/evm_command_utils.rs @@ -24,11 +24,8 @@ macro_rules! get_layer_two_evm_nonce { TrustedGetter::evm_nonce($signer_pair.public().into()) .sign(&KeyPair::Sr25519(Box::new($signer_pair.clone()))), )); - let res = perform_trusted_operation($cli, $trusted_args, &top).unwrap_or_default(); - let nonce = match res { - Some(n) => Index::decode(&mut n.as_slice()).unwrap_or(0), - None => 0, - }; + let res = perform_trusted_operation::($cli, $trusted_args, &top); + let nonce = res.ok().unwrap_or(0); debug!("got evm nonce: {:?}", nonce); nonce }}; diff --git a/cli/src/evm/commands/evm_create.rs b/cli/src/evm/commands/evm_create.rs index 9c012cda07..d2b05e1df5 100644 --- a/cli/src/evm/commands/evm_create.rs +++ b/cli/src/evm/commands/evm_create.rs @@ -22,7 +22,6 @@ use crate::{ trusted_operation::perform_trusted_operation, Cli, CliResult, CliResultOk, }; -use codec::Decode; use ita_stf::{evm_helpers::evm_create_address, Index, TrustedCall, TrustedGetter}; use itp_stf_primitives::{ traits::TrustedCallSigning, @@ -80,7 +79,7 @@ impl EvmCreateCommands { .sign(&from.into(), nonce, &mrenclave, &shard) .into_trusted_operation(trusted_args.direct); - let _ = perform_trusted_operation(cli, trusted_args, &top)?; + perform_trusted_operation::<()>(cli, trusted_args, &top)?; let execution_address = evm_create_address(sender_evm_acc, evm_account_nonce); info!("trusted call evm_create executed"); diff --git a/cli/src/evm/commands/evm_read.rs b/cli/src/evm/commands/evm_read.rs index 983f678aba..6fcc6f2d3d 100644 --- a/cli/src/evm/commands/evm_read.rs +++ b/cli/src/evm/commands/evm_read.rs @@ -19,7 +19,6 @@ use crate::{ trusted_cli::TrustedCli, trusted_command_utils::get_pair_from_str, trusted_operation::perform_trusted_operation, Cli, CliError, CliResult, CliResultOk, }; -use codec::Decode; use ita_stf::{Getter, TrustedCallSigned, TrustedGetter}; use itp_stf_primitives::types::{KeyPair, TrustedOperation}; use itp_types::AccountId; @@ -56,20 +55,15 @@ impl EvmReadCommands { TrustedGetter::evm_account_storages(sender_acc, execution_address, H256::zero()) .sign(&KeyPair::Sr25519(Box::new(sender))), )); - let res = perform_trusted_operation(cli, trusted_args, &top)?; - - debug!("received result for balance"); - if let Some(v) = res { - if let Ok(vd) = H256::decode(&mut v.as_slice()) { - println!("{:?}", vd); - Ok(CliResultOk::H256 { hash: vd }) - } else { - error!("could not decode value. {:x?}", v); - Err(CliError::EvmRead { msg: format!("could not decode value. {:x?}", v) }) - } - } else { - error!("Nothing in state!"); - Err(CliError::EvmRead { msg: "Nothing in state!".to_string() }) + match perform_trusted_operation::(cli, trusted_args, &top) { + Ok(hash) => { + println!("{:?}", hash); + Ok(CliResultOk::H256 { hash }) + }, + Err(e) => { + error!("Nothing in state! Reason: {:?} !", e); + Err(CliError::EvmRead { msg: "Nothing in state!".to_string() }) + }, } } } diff --git a/cli/src/lib.rs b/cli/src/lib.rs index 85a86bec18..88f5a91a86 100644 --- a/cli/src/lib.rs +++ b/cli/src/lib.rs @@ -32,7 +32,6 @@ mod attesteer; mod base_cli; mod benchmark; mod command_utils; -mod error; #[cfg(feature = "evm")] mod evm; #[cfg(feature = "teeracle")] @@ -125,6 +124,8 @@ pub enum CliError { TrustedOp { msg: String }, #[error("EvmReadCommands error: {:?}", msg)] EvmRead { msg: String }, + #[error("worker rpc api error: {:?}", msg)] + WorkerRpcApi { msg: String }, } pub type CliResult = Result; diff --git a/cli/src/main.rs b/cli/src/main.rs index 6dca5b1e90..4a27a9c940 100644 --- a/cli/src/main.rs +++ b/cli/src/main.rs @@ -19,7 +19,9 @@ use clap::Parser; use integritee_cli::{commands, Cli}; fn main() { - env_logger::init(); + env_logger::builder() + .format_timestamp(Some(env_logger::TimestampPrecision::Millis)) + .init(); let cli = Cli::parse(); diff --git a/cli/src/oracle/commands/listen_to_exchange.rs b/cli/src/oracle/commands/listen_to_exchange.rs index b21d75b968..f301ee9c1b 100644 --- a/cli/src/oracle/commands/listen_to_exchange.rs +++ b/cli/src/oracle/commands/listen_to_exchange.rs @@ -18,8 +18,8 @@ use crate::{command_utils::get_chain_api, Cli}; use itp_node_api::api_client::ParentchainApi; use itp_time_utils::{duration_now, remaining_time}; -use log::{debug, info, trace}; -use my_node_runtime::{Hash, RuntimeEvent}; +use itp_types::parentchain::ExchangeRateUpdated; +use log::*; use std::time::Duration; use substrate_api_client::SubscribeEvents; @@ -50,27 +50,22 @@ pub fn count_exchange_rate_update_events(api: &ParentchainApi, duration: Duratio let mut count = 0; while remaining_time(stop).unwrap_or_default() > Duration::ZERO { - let events_result = subscription.next_events::().unwrap(); - if let Ok(events) = events_result { - for event_record in &events { - info!("received event {:?}", event_record.event); - if let RuntimeEvent::Teeracle(event) = &event_record.event { - match &event { - my_node_runtime::pallet_teeracle::Event::ExchangeRateUpdated { - data_source, - trading_pair, - exchange_rate, - } => { + let events = subscription.next_events_from_metadata().unwrap().unwrap(); + for event in events.iter() { + let event = event.unwrap(); + match event.pallet_name() { + "Teeracle" => match event.variant_name() { + "ExchangeRateUpdated" => + if let Ok(Some(ev)) = event.as_event::() { count += 1; - debug!("Received ExchangeRateUpdated event"); println!( - "ExchangeRateUpdated: TRADING_PAIR : {}, SRC : {}, VALUE :{:?}", - trading_pair, data_source, exchange_rate + "ExchangeRateUpdated: rate: {} {:?}, source {:?}", + ev.exchange_rate, ev.trading_pair, ev.data_source, ); }, - _ => trace!("ignoring teeracle event: {:?}", event), - } - } + _ => continue, + }, + _ => continue, } } } diff --git a/cli/src/oracle/commands/listen_to_oracle.rs b/cli/src/oracle/commands/listen_to_oracle.rs index 234552f2b0..dfbb874356 100644 --- a/cli/src/oracle/commands/listen_to_oracle.rs +++ b/cli/src/oracle/commands/listen_to_oracle.rs @@ -18,10 +18,10 @@ use crate::{command_utils::get_chain_api, Cli}; use itp_node_api::api_client::ParentchainApi; use itp_time_utils::{duration_now, remaining_time}; -use log::{debug, info}; -use my_node_runtime::{Hash, RuntimeEvent}; +use itp_types::parentchain::OracleUpdated; +use log::*; use std::time::Duration; -use substrate_api_client::{ac_node_api::EventRecord, SubscribeEvents}; +use substrate_api_client::SubscribeEvents; /// Listen to exchange rate events. #[derive(Debug, Clone, Parser)] @@ -31,8 +31,6 @@ pub struct ListenToOracleEventsCmd { } type EventCount = u32; -type Event = EventRecord; - impl ListenToOracleEventsCmd { pub fn run(&self, cli: &Cli) { let api = get_chain_api(cli); @@ -49,43 +47,26 @@ fn count_oracle_update_events(api: &ParentchainApi, duration: Duration) -> Event //subscribe to events let mut subscription = api.subscribe_events().unwrap(); let mut count = 0; - while remaining_time(stop).unwrap_or_default() > Duration::ZERO { - let events_result = subscription.next_events::(); - let event_count = match events_result { - Some(Ok(event_records)) => { - debug!("Could not successfully decode event_bytes {:?}", event_records); - report_event_count(event_records) - }, - _ => 0, - }; - count += event_count; - } - debug!("Received {} ExchangeRateUpdated event(s) in total", count); - count -} - -fn report_event_count(event_records: Vec) -> EventCount { - let mut count = 0; - event_records.iter().for_each(|event_record| { - info!("received event {:?}", event_record.event); - if let RuntimeEvent::Teeracle(event) = &event_record.event { - match &event { - my_node_runtime::pallet_teeracle::Event::OracleUpdated { - oracle_data_name, - data_source, - } => { - count += 1; - debug!("Received OracleUpdated event"); - println!( - "OracleUpdated: ORACLE_NAME : {}, SRC : {}", - oracle_data_name, data_source - ); + let events = subscription.next_events_from_metadata().unwrap().unwrap(); + for event in events.iter() { + let event = event.unwrap(); + match event.pallet_name() { + "Teeracle" => match event.variant_name() { + "OracleUpdated" => + if let Ok(Some(ev)) = event.as_event::() { + count += 1; + println!( + "OracleUpdated: ORACLE_NAME : {}, SRC : {}", + ev.oracle_data_name, ev.data_source + ); + }, + _ => continue, }, - // Can just remove this and ignore handling this case - _ => debug!("ignoring teeracle event: {:?}", event), + _ => continue, } } - }); + } + debug!("Received {} ExchangeRateUpdated event(s) in total", count); count } diff --git a/cli/src/trusted_base_cli/commands/get_market_results.rs b/cli/src/trusted_base_cli/commands/get_market_results.rs index a3fe670a83..93079ec5eb 100644 --- a/cli/src/trusted_base_cli/commands/get_market_results.rs +++ b/cli/src/trusted_base_cli/commands/get_market_results.rs @@ -16,8 +16,6 @@ use crate::{ trusted_operation::perform_trusted_operation, Cli, CliResult, CliResultOk, }; -use crate::CliError; -use codec::Decode; use ita_stf::{Getter, TrustedCallSigned, TrustedGetter}; use itp_stf_primitives::types::{KeyPair, TrustedOperation}; use log::debug; @@ -33,14 +31,7 @@ pub struct GetMarketResultsCommand { impl GetMarketResultsCommand { pub(crate) fn run(&self, cli: &Cli, trusted_args: &TrustedCli) -> CliResult { - let results = get_market_results(cli, trusted_args, &self.account, self.timestamp.clone()); - match results { - Ok(res) => Ok(CliResultOk::Matches(res)), - Err(e) => { - log::error!("Error getting results: {}", e); - Err(CliError::TrustedOp { msg: "Error getting results".into() }) - }, - } + get_market_results(cli, trusted_args, &self.account, self.timestamp.clone()) } } @@ -49,7 +40,7 @@ pub(crate) fn get_market_results( trusted_args: &TrustedCli, arg_who: &str, timestamp: String, -) -> Result { +) -> CliResult { debug!("arg_who = {:?}", arg_who); let who = get_pair_from_str(trusted_args, arg_who); @@ -59,21 +50,8 @@ pub(crate) fn get_market_results( ) .into(); - let res = perform_trusted_operation(cli, trusted_args, &top).unwrap(); - - match res { - Some(market_results) => match MarketOutput::decode(&mut market_results.as_slice()) { - Ok(market_output) => Ok(market_output), - Err(err) => { - log::error!("Error deserializing results: {}", err); - Err(CliError::TrustedOp { - msg: format!("Error deserializing market results: {}", err), - }) - }, - }, - None => { - log::error!("Results not found"); - Err(CliError::TrustedOp { msg: "Results not found".into() }) - }, - } + Ok(perform_trusted_operation::(cli, trusted_args, &top).map(|results| { + println!("{:?}", results); + CliResultOk::Matches(results) + })?) } diff --git a/cli/src/trusted_base_cli/commands/get_shard.rs b/cli/src/trusted_base_cli/commands/get_shard.rs new file mode 100644 index 0000000000..d10f5d1e62 --- /dev/null +++ b/cli/src/trusted_base_cli/commands/get_shard.rs @@ -0,0 +1,67 @@ +/* + 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::{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(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/cli/src/trusted_base_cli/commands/get_shard_vault.rs b/cli/src/trusted_base_cli/commands/get_shard_vault.rs new file mode 100644 index 0000000000..4f043d07f4 --- /dev/null +++ b/cli/src/trusted_base_cli/commands/get_shard_vault.rs @@ -0,0 +1,71 @@ +/* + 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 codec::Decode; + +use itc_rpc_client::direct_client::DirectApi; +use itp_rpc::{RpcRequest, RpcResponse, RpcReturnValue}; + +use itp_types::{AccountId, DirectRequestStatus}; +use itp_utils::FromHexPrefixed; +use log::*; + +use sp_core::crypto::Ss58Codec; + +#[derive(Parser)] +pub struct GetShardVaultCommand {} + +impl GetShardVaultCommand { + pub(crate) fn run(&self, cli: &Cli, _trusted_args: &TrustedCli) -> CliResult { + let direct_api = get_worker_api_direct(cli); + let rpc_method = "author_getShardVault".to_owned(); + let jsonrpc_call: String = RpcRequest::compose_jsonrpc_call(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 vault = AccountId::decode(&mut rpc_return_value.value.as_slice()) + // Replace with `inspect_err` once it's stable. + .map_err(|err| { + error!("Failed to decode vault account: {:?}", err); + CliError::WorkerRpcApi { msg: err.to_string() } + })?; + let vault_ss58 = vault.to_ss58check(); + println!("{}", vault_ss58); + Ok(CliResultOk::PubKeysBase58 { + pubkeys_sr25519: None, + pubkeys_ed25519: Some(vec![vault_ss58]), + }) + } +} diff --git a/cli/src/trusted_base_cli/commands/mod.rs b/cli/src/trusted_base_cli/commands/mod.rs index 7f89ef832a..1fe61b6d15 100644 --- a/cli/src/trusted_base_cli/commands/mod.rs +++ b/cli/src/trusted_base_cli/commands/mod.rs @@ -1,5 +1,7 @@ pub mod balance; pub mod get_market_results; +pub mod get_shard; +pub mod get_shard_vault; pub mod nonce; pub mod pay_as_bid; pub mod pay_as_bid_proof; diff --git a/cli/src/trusted_base_cli/commands/nonce.rs b/cli/src/trusted_base_cli/commands/nonce.rs index fb3854f985..834f5d72c0 100644 --- a/cli/src/trusted_base_cli/commands/nonce.rs +++ b/cli/src/trusted_base_cli/commands/nonce.rs @@ -19,7 +19,6 @@ use crate::{ get_layer_two_nonce, trusted_cli::TrustedCli, trusted_command_utils::get_pair_from_str, trusted_operation::perform_trusted_operation, Cli, CliResult, CliResultOk, }; -use codec::Decode; use ita_stf::Index; use itp_stf_primitives::types::{KeyPair, TrustedOperation}; use log::*; diff --git a/cli/src/trusted_base_cli/commands/pay_as_bid.rs b/cli/src/trusted_base_cli/commands/pay_as_bid.rs index 25eff7cdfb..1917d077d5 100644 --- a/cli/src/trusted_base_cli/commands/pay_as_bid.rs +++ b/cli/src/trusted_base_cli/commands/pay_as_bid.rs @@ -20,14 +20,16 @@ use crate::{ trusted_cli::TrustedCli, trusted_command_utils::{get_identifiers, get_pair_from_str}, trusted_operation::perform_trusted_operation, - Cli, CliError, CliResult, CliResultOk, + Cli, CliResult, CliResultOk, }; -use codec::Decode; + use ita_stf::{Getter, Index, TrustedCall, TrustedCallSigned}; use itp_stf_primitives::{ traits::TrustedCallSigning, types::{KeyPair, TrustedOperation}, }; +use itp_types::H256; +use itp_utils::hex::hex_encode; use log::debug; use sp_core::Pair; @@ -40,14 +42,7 @@ pub struct PayAsBidCommand { impl PayAsBidCommand { pub(crate) fn run(&self, cli: &Cli, trusted_args: &TrustedCli) -> CliResult { - let results = pay_as_bid(cli, trusted_args, &self.account, &self.orders_string); - match results { - Ok(res) => Ok(CliResultOk::PayAsBidOutput(res)), - Err(e) => { - log::error!("Error: {}", e); - Err(CliError::TrustedOp { msg: format!("Error in saving Orders: {:?}", e) }) - }, - } + pay_as_bid(cli, trusted_args, &self.account, &self.orders_string) } } @@ -56,7 +51,7 @@ pub(crate) fn pay_as_bid( trusted_args: &TrustedCli, arg_who: &str, orders_string: &str, -) -> Result>, CliError> { +) -> CliResult { debug!("arg_who = {:?}", arg_who); let who = get_pair_from_str(trusted_args, arg_who); let signer = get_pair_from_str(trusted_args, arg_who); @@ -67,18 +62,8 @@ pub(crate) fn pay_as_bid( .sign(&KeyPair::Sr25519(Box::new(signer)), nonce, &mrenclave, &shard) .into_trusted_operation(trusted_args.direct); - let res = perform_trusted_operation(cli, trusted_args, &top); - match res { - Ok(opt) => match opt { - Some(_results) => Ok(Some(_results)), - None => { - println!("CLI None pay_as_bid None block"); - Ok(None) - }, - }, - Err(err) => { - log::error!("Error in saving Orders: {}", err); - Err(CliError::TrustedOp { msg: format!("Error in saving Orders: {}", err) }) - }, - } + Ok(perform_trusted_operation::(cli, trusted_args, &top).map(|hash| { + println!("{}", hex_encode(hash.as_ref())); + CliResultOk::H256 { hash } + })?) } diff --git a/cli/src/trusted_base_cli/commands/pay_as_bid_proof.rs b/cli/src/trusted_base_cli/commands/pay_as_bid_proof.rs index b79fb34cf6..d25175c621 100644 --- a/cli/src/trusted_base_cli/commands/pay_as_bid_proof.rs +++ b/cli/src/trusted_base_cli/commands/pay_as_bid_proof.rs @@ -16,14 +16,10 @@ use crate::{ trusted_operation::perform_trusted_operation, Cli, CliResult, CliResultOk, }; -use codec::Decode; use ita_stf::{Getter, MerkleProofWithCodec, TrustedCallSigned, TrustedGetter}; use itp_stf_primitives::types::{KeyPair, TrustedOperation}; -use log::debug; use sp_core::{Pair, H256}; -use crate::CliError; -use codec; #[derive(Parser)] pub struct PayAsBidProofCommand { /// AccountId in ss58check format @@ -34,23 +30,13 @@ pub struct PayAsBidProofCommand { impl PayAsBidProofCommand { pub(crate) fn run(&self, cli: &Cli, trusted_args: &TrustedCli) -> CliResult { - // if we serialize with serde-json we can easily just pass it as - // an argument in the verify-proof command. - let results = pay_as_bid_proof( + pay_as_bid_proof( cli, trusted_args, &self.account, self.timestamp.clone(), self.actor_id.clone(), - ); - - match results { - Ok(res) => Ok(CliResultOk::PayAsBidProofOutput(res)), - Err(e) => { - log::error!("Error getting proof: {}", e); - Err(CliError::TrustedOp { msg: "Error getting proof".into() }) - }, - } + ) } } @@ -60,8 +46,7 @@ pub(crate) fn pay_as_bid_proof( arg_who: &str, timestamp: String, actor_id: String, -) -> Result>, CliError> { - debug!("arg_who = {:?}", arg_who); +) -> CliResult { let who = get_pair_from_str(trusted_args, arg_who); let top: TrustedOperation = Getter::trusted( @@ -70,21 +55,10 @@ pub(crate) fn pay_as_bid_proof( ) .into(); - let res = perform_trusted_operation(cli, trusted_args, &top).unwrap(); - - match res { - Some(_proof) => match MerkleProofWithCodec::decode(&mut &_proof[..]) { - Ok(_proof) => Ok(_proof), - Err(err) => { - log::error!("Error deserializing results: {}", err); - Err(CliError::TrustedOp { - msg: format!("Error deserializing market results: {}", err), - }) - }, - }, - None => { - log::error!("Results not found"); - Err(CliError::TrustedOp { msg: "Results not found".into() }) - }, - } + Ok(perform_trusted_operation::>>(cli, trusted_args, &top) + .map(|proof| { + let p_string = serde_json::to_string(&proof).unwrap(); + println!("{}", p_string); + CliResultOk::PayAsBidProofOutput(proof) + })?) } diff --git a/cli/src/trusted_base_cli/commands/set_balance.rs b/cli/src/trusted_base_cli/commands/set_balance.rs index 87853e98a2..6c30aca7a7 100644 --- a/cli/src/trusted_base_cli/commands/set_balance.rs +++ b/cli/src/trusted_base_cli/commands/set_balance.rs @@ -22,14 +22,13 @@ use crate::{ trusted_operation::perform_trusted_operation, Cli, CliResult, CliResultOk, }; -use codec::Decode; +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 my_node_runtime::Balance; use sp_core::{crypto::Ss58Codec, Pair}; use std::boxed::Box; @@ -60,6 +59,6 @@ impl SetBalanceCommand { ) .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)?) + Ok(perform_trusted_operation::<()>(cli, trusted_args, &top).map(|_| CliResultOk::None)?) } } diff --git a/cli/src/trusted_base_cli/commands/transfer.rs b/cli/src/trusted_base_cli/commands/transfer.rs index 1896b93ab2..ac8ef5bf86 100644 --- a/cli/src/trusted_base_cli/commands/transfer.rs +++ b/cli/src/trusted_base_cli/commands/transfer.rs @@ -22,14 +22,13 @@ use crate::{ trusted_operation::perform_trusted_operation, Cli, CliResult, CliResultOk, }; -use codec::Decode; +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 my_node_runtime::Balance; use sp_core::{crypto::Ss58Codec, Pair}; use std::boxed::Box; @@ -65,7 +64,8 @@ impl TransferCommand { 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)?; + let res = + perform_trusted_operation::<()>(cli, trusted_args, &top).map(|_| CliResultOk::None)?; info!("trusted call transfer executed"); Ok(res) } diff --git a/cli/src/trusted_base_cli/commands/unshield_funds.rs b/cli/src/trusted_base_cli/commands/unshield_funds.rs index fa5b8258a5..0c855d79fb 100644 --- a/cli/src/trusted_base_cli/commands/unshield_funds.rs +++ b/cli/src/trusted_base_cli/commands/unshield_funds.rs @@ -22,14 +22,13 @@ use crate::{ trusted_operation::perform_trusted_operation, Cli, CliResult, CliResultOk, }; -use codec::Decode; +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 my_node_runtime::Balance; use sp_core::{crypto::Ss58Codec, Pair}; use std::boxed::Box; #[derive(Parser)] @@ -64,6 +63,6 @@ impl UnshieldFundsCommand { 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)?) + Ok(perform_trusted_operation::<()>(cli, trusted_args, &top).map(|_| CliResultOk::None)?) } } diff --git a/cli/src/trusted_base_cli/mod.rs b/cli/src/trusted_base_cli/mod.rs index 038ec68a7f..b03102bc7c 100644 --- a/cli/src/trusted_base_cli/mod.rs +++ b/cli/src/trusted_base_cli/mod.rs @@ -12,8 +12,14 @@ */ use crate::{ - trusted_cli::TrustedCli, trusted_command_utils::get_keystore_path, Cli, CliResult, CliResultOk, - ED25519_KEY_TYPE, SR25519_KEY_TYPE, + trusted_base_cli::commands::{ + balance::BalanceCommand, get_shard::GetShardCommand, get_shard_vault::GetShardVaultCommand, + 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; @@ -41,7 +47,6 @@ pub mod oli_cmds { }; } -use cmds::*; use oli_cmds::*; #[derive(Subcommand)] @@ -78,6 +83,11 @@ pub enum TrustedBaseCommand { /// Get Market Results Command GetMarketResults(GetMarketResultsCommand), + /// get shard for this worker + GetShard(GetShardCommand), + + /// get shard vault for shielding (if defined for this worker) + GetShardVault(GetShardVaultCommand), } impl TrustedBaseCommand { @@ -94,6 +104,8 @@ impl TrustedBaseCommand { TrustedBaseCommand::PayAsBidProof(cmd) => cmd.run(cli, trusted_cli), TrustedBaseCommand::VerifyProof(cmd) => cmd.run(cli, trusted_cli), TrustedBaseCommand::GetMarketResults(cmd) => cmd.run(cli, trusted_cli), + TrustedBaseCommand::GetShard(cmd) => cmd.run(cli, trusted_cli), + TrustedBaseCommand::GetShardVault(cmd) => cmd.run(cli, trusted_cli), } } } diff --git a/cli/src/trusted_cli.rs b/cli/src/trusted_cli.rs index a77105b0ee..68193ad186 100644 --- a/cli/src/trusted_cli.rs +++ b/cli/src/trusted_cli.rs @@ -34,7 +34,7 @@ pub use crate::trusted_base_cli::TrustedBaseCommand; pub struct TrustedCli { /// targeted worker MRENCLAVE #[clap(short, long)] - pub mrenclave: String, + pub(crate) mrenclave: Option, /// shard identifier #[clap(short, long)] diff --git a/cli/src/trusted_command_utils.rs b/cli/src/trusted_command_utils.rs index e01f2b9940..897d930ea5 100644 --- a/cli/src/trusted_command_utils.rs +++ b/cli/src/trusted_command_utils.rs @@ -23,6 +23,7 @@ use crate::{ }; 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::{RpcRequest, RpcResponse, RpcReturnValue}; @@ -30,7 +31,6 @@ use itp_stf_primitives::types::{AccountId, KeyPair, ShardIdentifier, TrustedOper use itp_types::DirectRequestStatus; use itp_utils::{FromHexPrefixed, ToHexPrefixed}; use log::*; -use my_node_runtime::Balance; use sp_application_crypto::sr25519; use sp_core::{crypto::Ss58Codec, sr25519 as sr25519_core, Pair}; use sp_runtime::traits::IdentifyAccount; @@ -47,11 +47,9 @@ macro_rules! get_layer_two_nonce { .sign(&KeyPair::Sr25519(Box::new($signer_pair.clone()))), )); // final nonce = current system nonce + pending tx count, panic early - let res = perform_trusted_operation($cli, $trusted_args, &top).unwrap_or_default(); - let nonce = match res { - Some(n) => Index::decode(&mut n.as_slice()).unwrap_or(0), - None => 0, - }; + let nonce = perform_trusted_operation::($cli, $trusted_args, &top) + .ok() + .unwrap_or_default(); debug!("got system nonce: {:?}", nonce); let pending_tx_count = get_pending_trusted_calls_for($cli, $trusted_args, &$signer_pair.public().into()).len(); @@ -69,20 +67,7 @@ pub(crate) fn get_balance(cli: &Cli, trusted_args: &TrustedCli, arg_who: &str) - let top = TrustedOperation::::get(Getter::trusted( TrustedGetter::free_balance(who.public().into()).sign(&KeyPair::Sr25519(Box::new(who))), )); - let res = perform_trusted_operation(cli, trusted_args, &top).unwrap_or(None); - debug!("received result for balance"); - decode_balance(res) -} - -pub(crate) 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 - } - }) + perform_trusted_operation::(cli, trusted_args, &top).ok() } pub(crate) fn get_keystore_path(trusted_args: &TrustedCli) -> PathBuf { @@ -91,7 +76,12 @@ pub(crate) fn get_keystore_path(trusted_args: &TrustedCli) -> PathBuf { } pub(crate) fn get_identifiers(trusted_args: &TrustedCli) -> ([u8; 32], ShardIdentifier) { - let mrenclave = mrenclave_from_base58(&trusted_args.mrenclave); + let mrenclave = mrenclave_from_base58( + trusted_args + .mrenclave + .as_ref() + .expect("argument '--mrenclave' must be provided for this command"), + ); let shard = match &trusted_args.shard { Some(val) => ShardIdentifier::from_slice(&val.from_base58().expect("shard has to be base58 encoded")), @@ -154,7 +144,7 @@ pub(crate) fn get_pending_trusted_calls_for( let rpc_return_value = RpcReturnValue::from_hex(&rpc_response.result).unwrap(); if rpc_return_value.status == DirectRequestStatus::Error { - println!("[Error] {}", String::decode(&mut rpc_return_value.value.as_slice()).unwrap()); + error!("{}", String::decode(&mut rpc_return_value.value.as_slice()).unwrap()); direct_api.close().unwrap(); return vec![] } diff --git a/cli/src/trusted_operation.rs b/cli/src/trusted_operation.rs index 2954c78abe..a407d661d5 100644 --- a/cli/src/trusted_operation.rs +++ b/cli/src/trusted_operation.rs @@ -17,26 +17,29 @@ use crate::{ command_utils::{get_chain_api, get_pair_from_str, get_shielding_key, get_worker_api_direct}, - error::{Error, Result}, trusted_cli::TrustedCli, Cli, }; use base58::{FromBase58, ToBase58}; -use codec::{Decode, Encode}; +use codec::{Decode, Encode, Input}; use enclave_bridge_primitives::Request; use ita_stf::{Getter, TrustedCallSigned}; use itc_rpc_client::direct_client::{DirectApi, DirectClient}; -use itp_node_api::api_client::{ParentchainApi, ENCLAVE_BRIDGE}; +use itp_node_api::api_client::{ApiClientError, ENCLAVE_BRIDGE}; use itp_rpc::{RpcRequest, RpcResponse, RpcReturnValue}; use itp_sgx_crypto::ShieldingCryptoEncrypt; use itp_stf_primitives::types::{ShardIdentifier, TrustedOperation}; -use itp_types::{BlockNumber, DirectRequestStatus, TrustedOperationStatus}; +use itp_types::{ + parentchain::{BlockHash, BlockNumber, ProcessedParentchainBlock}, + DirectRequestStatus, TrustedOperationStatus, +}; use itp_utils::{FromHexPrefixed, ToHexPrefixed}; use log::*; -use my_node_runtime::{Hash, RuntimeEvent}; -use pallet_enclave_bridge::Event as EnclaveBridgeEvent; + +use itp_types::parentchain::Hash; use sp_core::H256; use std::{ + fmt::Debug, result::Result as StdResult, sync::mpsc::{channel, Receiver}, time::Instant, @@ -46,43 +49,65 @@ use substrate_api_client::{ }; use thiserror::Error; +const TIMEOUT_BLOCKS: BlockNumber = 10; + #[derive(Debug, Error)] pub(crate) enum TrustedOperationError { - #[error("extrinsic L1 error: {msg:?}")] - Extrinsic { msg: String }, + #[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 }, } -pub(crate) type TrustedOpResult = StdResult>, TrustedOperationError>; +impl From for TrustedOperationError { + fn from(error: ApiClientError) -> Self { + Self::ApiClient(error) + } +} + +pub(crate) type TrustedOpResult = StdResult; -pub(crate) fn perform_trusted_operation( +pub(crate) fn perform_trusted_operation( cli: &Cli, trusted_args: &TrustedCli, top: &TrustedOperation, -) -> TrustedOpResult { +) -> 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), + 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( +fn execute_getter_from_cli_args( cli: &Cli, trusted_args: &TrustedCli, getter: &Getter, -) -> TrustedOpResult { +) -> TrustedOpResult { let shard = read_shard(trusted_args).unwrap(); let direct_api = get_worker_api_direct(cli); get_state(&direct_api, shard, getter) } -pub(crate) fn get_state( +pub(crate) fn get_state( direct_api: &DirectClient, shard: ShardIdentifier, getter: &Getter, -) -> TrustedOpResult { +) -> TrustedOpResult { // Compose jsonrpc call. let data = Request { shard, cyphertext: getter.encode() }; let rpc_method = "state_executeGetter".to_owned(); @@ -102,27 +127,33 @@ pub(crate) fn get_state( })?; if rpc_return_value.status == DirectRequestStatus::Error { - println!("[Error] {}", String::decode(&mut rpc_return_value.value.as_slice()).unwrap()); + 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::decode(&mut rpc_return_value.value.as_slice()) + 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() } })?; - Ok(maybe_state) + 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( +fn send_indirect_request( cli: &Cli, trusted_args: &TrustedCli, trusted_operation: &TrustedOperation, -) -> TrustedOpResult { +) -> 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(); @@ -140,7 +171,9 @@ fn send_indirect_request( let request = Request { shard, cyphertext: call_encrypted }; let xt = compose_extrinsic!(&chain_api, ENCLAVE_BRIDGE, "invoke", request); - let block_hash = match chain_api.submit_and_watch_extrinsic_until(xt, XtStatus::InBlock) { + 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: {:?}", @@ -150,79 +183,84 @@ fn send_indirect_request( }, Err(e) => { error!("invoke TrustedOperation extrinsic failed {:?}", e); - return Err(TrustedOperationError::Extrinsic { msg: format!("{:?}", 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(), block_hash + "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 event_records = subscription.next_events::().unwrap().unwrap(); - for event_record in event_records { - if let RuntimeEvent::EnclaveBridge(EnclaveBridgeEvent::ProcessedParentchainBlock { - shard, - block_hash: confirmed_block_hash, - trusted_calls_merkle_root, - block_number: confirmed_block_number, - }) = event_record.event - { - info!("Confirmation of ProcessedParentchainBlock received"); - debug!("shard: {:?}", shard); - debug!("confirmed parentchain block Hash: {:?}", block_hash); - debug!("trusted calls merkle root: {:?}", trusted_calls_merkle_root); - debug!("Confirmed stf block Hash: {:?}", confirmed_block_hash); - if let Err(e) = check_if_received_event_exceeds_expected( - &chain_api, - block_hash, - confirmed_block_hash, - confirmed_block_number, - ) { - error!("ProcessedParentchainBlock event: {:?}", e); - return Err(TrustedOperationError::Default { - msg: format!("ProcessedParentchainBlock event: {:?}", e), - }) - }; - - if confirmed_block_hash == block_hash { - return Ok(Some(block_hash.encode())) - } + 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() { + "EnclaveBridge" => match event.variant_name() { + "ProcessedParentchainBlock" => { + if let Ok(Some(ev)) = event.as_event::() { + println!("EnclaveBridge::{:?}", 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, } } } } -fn check_if_received_event_exceeds_expected( - chain_api: &ParentchainApi, - block_hash: Hash, - confirmed_block_hash: Hash, - confirmed_block_number: BlockNumber, -) -> Result<()> { - let block_number = chain_api.get_header(Some(block_hash))?.ok_or(Error::MissingBlock)?.number; - - info!("Expected block Number: {:?}", block_number); - info!("Confirmed block Number: {:?}", confirmed_block_number); - // The returned block number belongs to a subsequent event. We missed our event and can break the loop. - if confirmed_block_number > block_number { - return Err(Error::ConfirmedBlockNumberTooHigh(confirmed_block_number, block_number)) - } - // The block number is correct, but the block hash does not fit. - if block_number == confirmed_block_number && block_hash != confirmed_block_hash { - return Err(Error::ConfirmedBlockHashDoesNotMatchExpected(confirmed_block_hash, block_hash)) - } - Ok(()) -} - pub fn read_shard(trusted_args: &TrustedCli) -> 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.from_base58() { + None => match trusted_args + .mrenclave + .as_ref() + .expect("at least argument '--mrenclave' must be provided for this command") + .from_base58() + { Ok(s) => ShardIdentifier::decode(&mut &s[..]), _ => panic!("mrenclave argument must be base58 encoded"), }, @@ -230,11 +268,11 @@ pub fn read_shard(trusted_args: &TrustedCli) -> StdResult( cli: &Cli, trusted_args: &TrustedCli, operation_call: &TrustedOperation, -) -> TrustedOpResult { +) -> TrustedOpResult { let encryption_key = get_shielding_key(cli).unwrap(); let shard = read_shard(trusted_args).unwrap(); let jsonrpc_call: String = get_json_request(shard, operation_call, encryption_key); @@ -261,7 +299,7 @@ fn send_direct_request( DirectRequestStatus::Error => { debug!("request status is error"); if let Ok(value) = String::decode(&mut return_value.value.as_slice()) { - println!("[Error] {}", value); + error!("{}", value); } direct_api.close().unwrap(); return Err(TrustedOperationError::Default { @@ -275,19 +313,23 @@ fn send_direct_request( } if connection_can_be_closed(status) { direct_api.close().unwrap(); - return Ok(None) + let value = + decode_response_value(&mut return_value.value.as_slice())?; + return Ok(value) } }, DirectRequestStatus::Ok => { debug!("request status is ignored"); direct_api.close().unwrap(); - return Ok(None) + let value = decode_response_value(&mut return_value.value.as_slice())?; + return Ok(value) }, } if !return_value.do_watch { debug!("do watch is false, closing connection"); direct_api.close().unwrap(); - return Ok(None) + let value = decode_response_value(&mut return_value.value.as_slice())?; + return Ok(value) } }; }, @@ -302,6 +344,14 @@ fn send_direct_request( } } +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, operation_call: &TrustedOperation, @@ -337,7 +387,7 @@ pub(crate) fn wait_until( if let Ok(value) = String::decode(&mut return_value.value.as_slice()) { - println!("[Error] {}", value); + error!("{}", value); } return None }, @@ -382,5 +432,6 @@ fn connection_can_be_closed(top_status: TrustedOperationStatus) -> bool { TrustedOperationStatus::Future | TrustedOperationStatus::Ready | TrustedOperationStatus::Broadcast + | TrustedOperationStatus::Invalid ) } diff --git a/cli/test_auto_shielding_with_transfer_bob.sh b/cli/test_auto_shielding_with_transfer_bob.sh new file mode 100644 index 0000000000..255d3f5bbc --- /dev/null +++ b/cli/test_auto_shielding_with_transfer_bob.sh @@ -0,0 +1,141 @@ +#!/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/cli/test_shield_on_target_nodes_with_transfer_to_alice.sh b/cli/test_shield_on_target_nodes_with_transfer_to_alice.sh index b7d6f76a4b..9a3d10dfa3 100755 --- a/cli/test_shield_on_target_nodes_with_transfer_to_alice.sh +++ b/cli/test_shield_on_target_nodes_with_transfer_to_alice.sh @@ -64,6 +64,7 @@ echo "" # the parentchain token is 12 decimal UNIT=$(( 10 ** 12 )) +FEE_TOLERANCE=$((10 ** 11)) # make these amounts greater than ED AMOUNT_SHIELD=$(( 6 * UNIT )) @@ -86,14 +87,14 @@ function wait_assert_state() for i in $(seq 1 $WAIT_ROUNDS); do sleep $WAIT_INTERVAL_SECONDS state=$(${CLIENT} trusted --mrenclave "$1" "$3" "$2") - if [ $state -eq "$4" ]; then + 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" + echo "Assert $2 $3 failed, expected = $4, actual = $state, tolerance = $FEE_TOLERANCE" exit 1 } diff --git a/core-primitives/attestation-handler/Cargo.toml b/core-primitives/attestation-handler/Cargo.toml index 19690b16d7..96b74cb1c7 100644 --- a/core-primitives/attestation-handler/Cargo.toml +++ b/core-primitives/attestation-handler/Cargo.toml @@ -45,14 +45,12 @@ itp-settings = { path = "../settings" } itp-sgx-crypto = { path = "../sgx/crypto", default-features = false } itp-sgx-io = { path = "../sgx/io", default-features = false } itp-time-utils = { path = "../time-utils", default-features = false } -itp-types = { path = "../types", default-features = false } # integritee httparse = { default-features = false, git = "https://github.com/integritee-network/httparse-sgx", branch = "sgx-experimental" } # substrate deps sp-core = { default-features = false, features = ["full_crypto"], git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } -sp-runtime = { default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } [features] default = ["std"] @@ -74,10 +72,8 @@ std = [ "itp-ocall-api/std", "itp-sgx-io/std", "itp-sgx-crypto/std", - "itp-types/std", # substrate "sp-core/std", - "sp-runtime/std", # integritee "httparse/std", ] diff --git a/core-primitives/enclave-api/Cargo.toml b/core-primitives/enclave-api/Cargo.toml index 9f10fb3c1f..f639f9d7e8 100644 --- a/core-primitives/enclave-api/Cargo.toml +++ b/core-primitives/enclave-api/Cargo.toml @@ -16,15 +16,15 @@ sgx_types = { branch = "master", git = "https://github.com/apache/teaclave-sgx-s sgx_urts = { optional = true, branch = "master", git = "https://github.com/apache/teaclave-sgx-sdk.git" } frame-support = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } -sp-consensus-grandpa = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } sp-core = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } sp-runtime = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } -teerex-primitives = { git = "https://github.com/integritee-network/pallets.git", branch = "sdk-v0.12.0-polkadot-v0.9.42" } +teerex-primitives = { git = "https://github.com/integritee-network/pallets.git", branch = "sdk-v0.12.11-polkadot-v0.9.42" } itc-parentchain = { path = "../../core/parentchain/parentchain-crate" } itp-enclave-api-ffi = { path = "ffi" } itp-settings = { path = "../settings" } +itp-stf-interface = { path = "../stf-interface" } itp-storage = { path = "../storage" } itp-types = { path = "../types" } diff --git a/core-primitives/enclave-api/ffi/src/lib.rs b/core-primitives/enclave-api/ffi/src/lib.rs index 12115521e1..b222573c94 100644 --- a/core-primitives/enclave-api/ffi/src/lib.rs +++ b/core-primitives/enclave-api/ffi/src/lib.rs @@ -15,7 +15,8 @@ extern "C" { quote: *const u8, quote_size: u32, unchecked_extrinsic: *mut u8, - unchecked_extrinsic_size: u32, + unchecked_extrinsic_max_size: u32, + unchecked_extrinsic_size: *mut u32, ) -> sgx_status_t; pub fn init( @@ -62,13 +63,30 @@ extern "C" { retval: *mut sgx_status_t, shard: *const u8, shard_size: u32, + parentchain_id: *const u8, + parentchain_id_size: u32, + funding_balance: *const u8, + funding_balance_size: u32, ) -> sgx_status_t; - pub fn trigger_parentchain_block_import( + 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 execute_trusted_calls(eid: sgx_enclave_id_t, retval: *mut sgx_status_t) -> sgx_status_t; @@ -84,6 +102,7 @@ extern "C" { events_proofs_size: usize, parentchain_id: *const u8, parentchain_id_size: u32, + immediate_import: c_int, ) -> sgx_status_t; pub fn set_nonce( @@ -139,7 +158,8 @@ extern "C" { w_url: *const u8, w_url_size: u32, unchecked_extrinsic: *mut u8, - unchecked_extrinsic_size: u32, + unchecked_extrinsic_max_size: u32, + unchecked_extrinsic_size: *mut u32, skip_ra: c_int, ) -> sgx_status_t; @@ -149,7 +169,8 @@ extern "C" { w_url: *const u8, w_url_size: u32, unchecked_extrinsic: *mut u8, - unchecked_extrinsic_size: u32, + 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>, @@ -170,7 +191,8 @@ extern "C" { retval: *mut sgx_status_t, collateral: *const sgx_ql_qve_collateral_t, unchecked_extrinsic: *mut u8, - unchecked_extrinsic_size: u32, + unchecked_extrinsic_max_size: u32, + unchecked_extrinsic_size: *mut u32, ) -> sgx_status_t; pub fn generate_register_tcb_info_extrinsic( @@ -178,7 +200,8 @@ extern "C" { retval: *mut sgx_status_t, collateral: *const sgx_ql_qve_collateral_t, unchecked_extrinsic: *mut u8, - unchecked_extrinsic_size: u32, + unchecked_extrinsic_max_size: u32, + unchecked_extrinsic_size: *mut u32, ) -> sgx_status_t; pub fn dump_ias_ra_cert_to_disk( @@ -218,7 +241,8 @@ extern "C" { fiat_currency: *const u8, fiat_currency_size: u32, unchecked_extrinsic: *mut u8, - unchecked_extrinsic_size: u32, + unchecked_extrinsic_max_size: u32, + unchecked_extrinsic_size: *mut u32, ) -> sgx_status_t; pub fn update_weather_data_xt( @@ -229,7 +253,8 @@ extern "C" { weather_info_latitude: *const u8, weather_info_latitude_size: u32, unchecked_extrinsic: *mut u8, - unchecked_extrinsic_size: u32, + unchecked_extrinsic_max_size: u32, + unchecked_extrinsic_size: *mut u32, ) -> sgx_status_t; pub fn run_state_provisioning_server( diff --git a/core-primitives/enclave-api/src/enclave_base.rs b/core-primitives/enclave-api/src/enclave_base.rs index 05df752cab..22f17d7f6b 100644 --- a/core-primitives/enclave-api/src/enclave_base.rs +++ b/core-primitives/enclave-api/src/enclave_base.rs @@ -20,7 +20,8 @@ use crate::EnclaveResult; use codec::Decode; use core::fmt::Debug; use itc_parentchain::primitives::{ParentchainId, ParentchainInitParams}; -use itp_types::ShardIdentifier; +use itp_stf_interface::ShardCreationInfo; +use itp_types::{parentchain::Header, Balance, ShardIdentifier}; use sgx_crypto_helper::rsa3072::Rsa3072PubKey; use sp_core::ed25519; use teerex_primitives::EnclaveFingerprint; @@ -51,12 +52,22 @@ pub trait EnclaveBase: Send + Sync + 'static { fn init_shard(&self, shard: Vec) -> EnclaveResult<()>; /// Initialize a new shard vault account and register enclave signer as its proxy. - fn init_proxied_shard_vault(&self, shard: &ShardIdentifier) -> EnclaveResult<()>; + fn init_proxied_shard_vault( + &self, + shard: &ShardIdentifier, + parentchain_id: &ParentchainId, + funding_balance: Balance, + ) -> 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<()>; - /// Trigger the import of parentchain block explicitly. Used when initializing a light-client - /// with a triggered import dispatcher. - fn trigger_parentchain_block_import(&self, parentchain_id: &ParentchainId) - -> EnclaveResult<()>; + fn get_shard_creation_info(&self, shard: &ShardIdentifier) -> EnclaveResult; fn set_nonce(&self, nonce: u32, parentchain_id: ParentchainId) -> EnclaveResult<()>; @@ -89,7 +100,11 @@ mod impl_ffi { use itp_settings::worker::{ HEADER_MAX_SIZE, MR_ENCLAVE_SIZE, SHIELDING_KEY_SIZE, SIGNING_KEY_SIZE, }; - use itp_types::ShardIdentifier; + use itp_stf_interface::ShardCreationInfo; + use itp_types::{ + parentchain::{Balance, Header}, + ShardIdentifier, + }; use log::*; use sgx_crypto_helper::rsa3072::Rsa3072PubKey; use sgx_types::*; @@ -184,9 +199,15 @@ mod impl_ffi { Ok(()) } - fn init_proxied_shard_vault(&self, shard: &ShardIdentifier) -> EnclaveResult<()> { + fn init_proxied_shard_vault( + &self, + shard: &ShardIdentifier, + parentchain_id: &ParentchainId, + funding_balance: Balance, + ) -> EnclaveResult<()> { let mut retval = sgx_status_t::SGX_SUCCESS; - + let parentchain_id_enc = parentchain_id.encode(); + let funding_balance_enc = funding_balance.encode(); let shard_bytes = shard.encode(); let result = unsafe { ffi::init_proxied_shard_vault( @@ -194,6 +215,10 @@ mod impl_ffi { &mut retval, shard_bytes.as_ptr(), shard_bytes.len() as u32, + parentchain_id_enc.as_ptr(), + parentchain_id_enc.len() as u32, + funding_balance_enc.as_ptr(), + funding_balance_enc.len() as u32, ) }; @@ -202,19 +227,27 @@ mod impl_ffi { Ok(()) } - fn trigger_parentchain_block_import( + + 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::trigger_parentchain_block_import( + 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, ) }; @@ -224,6 +257,30 @@ mod impl_ffi { 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; diff --git a/core-primitives/enclave-api/src/remote_attestation.rs b/core-primitives/enclave-api/src/remote_attestation.rs index dd48f9b9f7..20f8578395 100644 --- a/core-primitives/enclave-api/src/remote_attestation.rs +++ b/core-primitives/enclave-api/src/remote_attestation.rs @@ -144,8 +144,9 @@ mod impl_ffi { 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 dcap_ra_extrinsic with URL: {}", w_url); + trace!("Generating ias_ra_extrinsic with URL: {}", w_url); let url = w_url.encode(); @@ -157,14 +158,18 @@ mod impl_ffi { 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)); - - Ok(unchecked_extrinsic) + 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, @@ -173,6 +178,7 @@ mod impl_ffi { ) -> 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 { @@ -185,13 +191,17 @@ mod impl_ffi { 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)); - - Ok(unchecked_extrinsic.to_vec()) + 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> { @@ -250,7 +260,7 @@ mod impl_ffi { 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 { @@ -261,6 +271,7 @@ mod impl_ffi { 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(), @@ -269,8 +280,11 @@ mod impl_ffi { ensure!(result == sgx_status_t::SGX_SUCCESS, Error::Sgx(result)); ensure!(retval == sgx_status_t::SGX_SUCCESS, Error::Sgx(retval)); - - Ok(unchecked_extrinsic) + 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( @@ -279,6 +293,7 @@ mod impl_ffi { ) -> 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"); @@ -291,6 +306,7 @@ mod impl_ffi { 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) }; @@ -300,13 +316,17 @@ mod impl_ffi { free_status == sgx_quote3_error_t::SGX_QL_SUCCESS, Error::SgxQuote(free_status) ); - - Ok(unchecked_extrinsic) + 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"); @@ -319,6 +339,7 @@ mod impl_ffi { 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) }; @@ -328,8 +349,11 @@ mod impl_ffi { free_status == sgx_quote3_error_t::SGX_QL_SUCCESS, Error::SgxQuote(free_status) ); - - Ok(unchecked_extrinsic) + 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<()> { @@ -783,13 +807,13 @@ mod impl_ffi { } fn create_system_path(file_name: &str) -> String { - info!("create_system_path:: file_name={}", &file_name); + 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); - info!("create_system_path:: created path={}", &c_terminated_path); + trace!("create_system_path:: created path={}", &c_terminated_path); c_terminated_path } diff --git a/core-primitives/enclave-api/src/sidechain.rs b/core-primitives/enclave-api/src/sidechain.rs index 1203a2d234..d00b177684 100644 --- a/core-primitives/enclave-api/src/sidechain.rs +++ b/core-primitives/enclave-api/src/sidechain.rs @@ -32,6 +32,7 @@ pub trait Sidechain: Send + Sync + 'static { events: &[Vec], events_proofs: &[StorageProof], parentchain_id: &ParentchainId, + immediate_import: bool, ) -> EnclaveResult<()>; fn execute_trusted_calls(&self) -> EnclaveResult<()>; @@ -56,6 +57,7 @@ mod impl_ffi { events: &[Vec], events_proofs: &[StorageProof], parentchain_id: &ParentchainId, + immediate_import: bool, ) -> EnclaveResult<()> { let mut retval = sgx_status_t::SGX_SUCCESS; let blocks_enc = blocks.encode(); @@ -75,6 +77,7 @@ mod impl_ffi { events_proofs_enc.len(), parentchain_id_enc.as_ptr(), parentchain_id_enc.len() as u32, + immediate_import.into(), ) }; diff --git a/core-primitives/enclave-api/src/teeracle_api.rs b/core-primitives/enclave-api/src/teeracle_api.rs index 742a9325e3..530e2ff127 100644 --- a/core-primitives/enclave-api/src/teeracle_api.rs +++ b/core-primitives/enclave-api/src/teeracle_api.rs @@ -49,8 +49,9 @@ mod impl_ffi { crypto_currency, fiat_currency ); let mut retval = sgx_status_t::SGX_SUCCESS; - let response_len = 8192; - let mut response: Vec = vec![0u8; response_len as usize]; + let response_max_len = 8192; + let mut response: Vec = vec![0u8; response_max_len as usize]; + let mut response_len: u32 = 0; let crypto_curr = crypto_currency.encode(); let fiat_curr = fiat_currency.encode(); @@ -64,14 +65,15 @@ mod impl_ffi { fiat_curr.as_ptr(), fiat_curr.len() as u32, response.as_mut_ptr(), - response_len, + response_max_len, + &mut response_len as *mut u32, ) }; ensure!(res == sgx_status_t::SGX_SUCCESS, Error::Sgx(res)); ensure!(retval == sgx_status_t::SGX_SUCCESS, Error::Sgx(retval)); - Ok(response) + Ok(Vec::from(&response[..response_len as usize])) } fn update_weather_data_xt( &self, @@ -83,8 +85,9 @@ mod impl_ffi { latitude, longitude ); let mut retval = sgx_status_t::SGX_SUCCESS; - let response_len = 8192; - let mut response: Vec = vec![0u8; response_len as usize]; + let response_max_len = 8192; + let mut response: Vec = vec![0u8; response_max_len as usize]; + let mut response_len: u32 = 0; let longitude_encoded: Vec = longitude.encode(); let latitude_encoded: Vec = latitude.encode(); @@ -98,13 +101,14 @@ mod impl_ffi { latitude_encoded.as_ptr(), latitude_encoded.len() as u32, response.as_mut_ptr(), - response_len, + response_max_len, + &mut response_len as *mut u32, ) }; ensure!(res == sgx_status_t::SGX_SUCCESS, Error::Sgx(res)); ensure!(retval == sgx_status_t::SGX_SUCCESS, Error::Sgx(retval)); - Ok(response) + Ok(Vec::from(&response[..response_len as usize])) } } } diff --git a/core-primitives/enclave-bridge-storage/Cargo.toml b/core-primitives/enclave-bridge-storage/Cargo.toml index 595fb10189..8b191f3458 100644 --- a/core-primitives/enclave-bridge-storage/Cargo.toml +++ b/core-primitives/enclave-bridge-storage/Cargo.toml @@ -10,12 +10,11 @@ sp-std = { default-features = false, git = "https://github.com/paritytech/substr #local deps itp-storage = { path = "../storage", default-features = false } -itp-types = { path = "../types", default-features = false } [features] default = ["std"] std = [ + "codec/std", "sp-std/std", "itp-storage/std", - "itp-types/std", ] diff --git a/core-primitives/extrinsics-factory/Cargo.toml b/core-primitives/extrinsics-factory/Cargo.toml index ec58f75dff..73223c1b95 100644 --- a/core-primitives/extrinsics-factory/Cargo.toml +++ b/core-primitives/extrinsics-factory/Cargo.toml @@ -23,7 +23,6 @@ thiserror = { version = "1.0", optional = true } # no-std dependencies codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive"] } -log = { version = "0.4", default-features = false } sp-core = { default-features = false, features = ["full_crypto"], git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } sp-runtime = { default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } @@ -33,7 +32,6 @@ std = [ "itp-node-api/std", "itp-nonce-cache/std", "itp-types/std", - "log/std", "substrate-api-client/std", "thiserror", ] diff --git a/core-primitives/extrinsics-factory/src/lib.rs b/core-primitives/extrinsics-factory/src/lib.rs index 0744d1b657..fd55dfccb7 100644 --- a/core-primitives/extrinsics-factory/src/lib.rs +++ b/core-primitives/extrinsics-factory/src/lib.rs @@ -70,7 +70,7 @@ where genesis_hash: H256, signer: Signer, nonce_cache: Arc, - node_metadata_repository: Arc, + pub node_metadata_repository: Arc, } impl diff --git a/core-primitives/node-api/api-client-extensions/Cargo.toml b/core-primitives/node-api/api-client-extensions/Cargo.toml index 5546f13884..7abafd35e1 100644 --- a/core-primitives/node-api/api-client-extensions/Cargo.toml +++ b/core-primitives/node-api/api-client-extensions/Cargo.toml @@ -5,14 +5,10 @@ authors = ["Integritee AG "] edition = "2021" [dependencies] -# crates.io -codec = { package = "parity-scale-codec", version = "3.0.0", features = ["derive"] } log = { version = "0.4" } -thiserror = { version = "1.0" } # substrate sp-consensus-grandpa = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } -sp-core = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } sp-runtime = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } # scs diff --git a/core-primitives/node-api/api-client-extensions/src/pallet_teerex.rs b/core-primitives/node-api/api-client-extensions/src/pallet_teerex.rs index 513a09f861..e8007729be 100644 --- a/core-primitives/node-api/api-client-extensions/src/pallet_teerex.rs +++ b/core-primitives/node-api/api-client-extensions/src/pallet_teerex.rs @@ -17,7 +17,9 @@ use crate::ApiResult; use itp_api_client_types::{traits::GetStorage, Api, Config, Request}; -use itp_types::{AccountId, IpfsHash, MultiEnclave, ShardIdentifier, ShardStatus}; +use itp_types::{ + AccountId, IpfsHash, MultiEnclave, ShardIdentifier, ShardSignerStatus, ShardStatus, +}; use log::error; pub const TEEREX: &str = "Teerex"; @@ -40,6 +42,11 @@ pub trait PalletTeerexApi { shard: &ShardIdentifier, at_block: Option, ) -> ApiResult>>>; + fn shard_status( + &self, + shard: &ShardIdentifier, + at_block: Option, + ) -> ApiResult>>; fn latest_ipfs_hash( &self, shard: &ShardIdentifier, @@ -100,6 +107,14 @@ where ) } + fn shard_status( + &self, + shard: &ShardIdentifier, + at_block: Option, + ) -> ApiResult>> { + self.get_storage_map(ENCLAVE_BRIDGE, "ShardStatus", shard, at_block) + } + fn latest_ipfs_hash( &self, shard: &ShardIdentifier, diff --git a/core-primitives/node-api/api-client-types/Cargo.toml b/core-primitives/node-api/api-client-types/Cargo.toml index 29e9615751..b5fa75962a 100644 --- a/core-primitives/node-api/api-client-types/Cargo.toml +++ b/core-primitives/node-api/api-client-types/Cargo.toml @@ -5,19 +5,9 @@ authors = ["Integritee AG "] edition = "2021" [dependencies] -# integritee-node -my-node-runtime = { package = "integritee-node-runtime", optional = true, git = "https://github.com/integritee-network/integritee-node.git", branch = "sdk-v0.12.0-polkadot-v0.9.42" } - -# scs -substrate-api-client = { default-features = false, features = ["sync-api"], git = "https://github.com/scs/substrate-api-client.git", branch = "polkadot-v0.9.42-tag-v0.14.0" } - -# substrate -sp-core = { default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } -sp-runtime = { default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } - -# local itp-types = { default-features = false, path = "../../types" } - +sp-runtime = { default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } +substrate-api-client = { default-features = false, features = ["sync-api"], git = "https://github.com/scs/substrate-api-client.git", branch = "polkadot-v0.9.42-tag-v0.14.0" } [features] default = ["std"] @@ -25,7 +15,5 @@ std = [ "itp-types/std", "substrate-api-client/std", "substrate-api-client/tungstenite-client", - "sp-core/std", "sp-runtime/std", - "my-node-runtime", ] diff --git a/core-primitives/node-api/api-client-types/src/lib.rs b/core-primitives/node-api/api-client-types/src/lib.rs index f3bee4590d..b82b0c376b 100644 --- a/core-primitives/node-api/api-client-types/src/lib.rs +++ b/core-primitives/node-api/api-client-types/src/lib.rs @@ -15,7 +15,7 @@ */ -//! Contains type definitions to talk to the node. +//! Contains semi-generic type definitions to talk to the node without depending on an implementation of Runtime. //! //! You need to update this if you have a signed extension in your node that //! is different from the integritee-node, e.g., if you use the `pallet_asset_tx_payment`. @@ -79,20 +79,12 @@ pub use api::*; #[cfg(feature = "std")] mod api { use super::ParentchainRuntimeConfig; - use sp_runtime::generic::SignedBlock as GenericSignedBlock; use substrate_api_client::Api; - // We should probably switch to the opaque block, then we can get rid of the - // runtime dependency here. - // pub use itp_types::Block; - pub use my_node_runtime::{Block, Runtime, UncheckedExtrinsic}; - pub use substrate_api_client::{ api::Error as ApiClientError, rpc::{tungstenite_client::TungsteniteRpcClient, Error as RpcClientError}, }; - pub type SignedBlock = GenericSignedBlock; - pub type ParentchainApi = Api; } diff --git a/core-primitives/node-api/metadata/src/lib.rs b/core-primitives/node-api/metadata/src/lib.rs index 648876eb40..6a8662e5d0 100644 --- a/core-primitives/node-api/metadata/src/lib.rs +++ b/core-primitives/node-api/metadata/src/lib.rs @@ -23,6 +23,7 @@ use crate::{ error::Result, pallet_balances::BalancesCallIndexes, pallet_enclave_bridge::EnclaveBridgeCallIndexes, pallet_proxy::ProxyCallIndexes, pallet_sidechain::SidechainCallIndexes, pallet_teerex::TeerexCallIndexes, + pallet_timestamp::TimestampCallIndexes, }; use codec::{Decode, Encode}; use sp_core::storage::StorageKey; @@ -38,6 +39,8 @@ pub mod pallet_sidechain; pub mod pallet_teeracle; pub mod pallet_teerex; +pub mod pallet_timestamp; + #[cfg(feature = "mocks")] pub mod metadata_mocks; @@ -47,6 +50,7 @@ pub trait NodeMetadataTrait: + SidechainCallIndexes + ProxyCallIndexes + BalancesCallIndexes + + TimestampCallIndexes { } impl< @@ -54,7 +58,8 @@ impl< + EnclaveBridgeCallIndexes + SidechainCallIndexes + ProxyCallIndexes - + BalancesCallIndexes, + + BalancesCallIndexes + + TimestampCallIndexes, > NodeMetadataTrait for T { } diff --git a/core-primitives/node-api/metadata/src/metadata_mocks.rs b/core-primitives/node-api/metadata/src/metadata_mocks.rs index 8bf47298ec..40711e24c7 100644 --- a/core-primitives/node-api/metadata/src/metadata_mocks.rs +++ b/core-primitives/node-api/metadata/src/metadata_mocks.rs @@ -19,6 +19,7 @@ use crate::{ error::Result, pallet_balances::BalancesCallIndexes, pallet_enclave_bridge::EnclaveBridgeCallIndexes, pallet_proxy::ProxyCallIndexes, pallet_sidechain::SidechainCallIndexes, pallet_teerex::TeerexCallIndexes, + pallet_timestamp::TimestampCallIndexes, }; use codec::{Decode, Encode}; @@ -56,6 +57,8 @@ pub struct NodeMetadataMock { transfer: u8, transfer_keep_alive: u8, transfer_allow_death: u8, + timestamp_module: u8, + timestamp_set: u8, runtime_spec_version: u32, runtime_transaction_version: u32, } @@ -85,6 +88,8 @@ impl NodeMetadataMock { transfer: 7u8, transfer_keep_alive: 3u8, transfer_allow_death: 0u8, + timestamp_module: 3, + timestamp_set: 0, runtime_spec_version: 25, runtime_transaction_version: 4, } @@ -168,3 +173,9 @@ impl BalancesCallIndexes for NodeMetadataMock { Ok([self.balances_module, self.transfer_allow_death]) } } + +impl TimestampCallIndexes for NodeMetadataMock { + fn timestamp_set_call_indexes(&self) -> Result<[u8; 2]> { + Ok([self.timestamp_module, self.timestamp_set]) + } +} diff --git a/core-primitives/node-api/metadata/src/pallet_proxy.rs b/core-primitives/node-api/metadata/src/pallet_proxy.rs index 6a7aa14b08..a0106457b0 100644 --- a/core-primitives/node-api/metadata/src/pallet_proxy.rs +++ b/core-primitives/node-api/metadata/src/pallet_proxy.rs @@ -19,8 +19,6 @@ use crate::{error::Result, NodeMetadata}; /// Pallet name: const PROXY: &str = "Proxy"; -/// the deposit needed to register up to 20 proxies in native parentchain token -pub const PROXY_DEPOSIT: u128 = 21_000_000_000_000; pub trait ProxyCallIndexes { fn add_proxy_call_indexes(&self) -> Result<[u8; 2]>; diff --git a/core-primitives/node-api/metadata/src/pallet_system.rs b/core-primitives/node-api/metadata/src/pallet_system.rs index 1a9b4c7958..c79d6f971b 100644 --- a/core-primitives/node-api/metadata/src/pallet_system.rs +++ b/core-primitives/node-api/metadata/src/pallet_system.rs @@ -3,7 +3,7 @@ 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 + 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. @@ -17,17 +17,17 @@ use sp_core::storage::StorageKey; const SYSTEM: &str = "System"; pub trait SystemStorageIndexes { - fn system_account_storage_key(&self) -> Result; + fn system_account_storage_key(&self) -> Result; - fn system_account_storage_map_key(&self, index: u64) -> Result; + fn system_account_storage_map_key(&self, index: u64) -> Result; } impl SystemStorageIndexes for NodeMetadata { - fn system_account_storage_key(&self) -> Result { - self.storage_value_key(SYSTEM, "Account") - } + fn system_account_storage_key(&self) -> Result { + self.storage_value_key(SYSTEM, "Account") + } - fn system_account_storage_map_key(&self, index: u64) -> Result { - self.storage_map_key(SYSTEM, "Account", index) - } -} \ No newline at end of file + fn system_account_storage_map_key(&self, index: u64) -> Result { + self.storage_map_key(SYSTEM, "Account", index) + } +} diff --git a/core-primitives/node-api/metadata/src/pallet_timestamp.rs b/core-primitives/node-api/metadata/src/pallet_timestamp.rs new file mode 100644 index 0000000000..75e695579b --- /dev/null +++ b/core-primitives/node-api/metadata/src/pallet_timestamp.rs @@ -0,0 +1,30 @@ +/* + 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, NodeMetadata}; + +/// Pallet' name: +const TIMESTAMP: &str = "Timestamp"; + +pub trait TimestampCallIndexes { + fn timestamp_set_call_indexes(&self) -> Result<[u8; 2]>; +} + +impl TimestampCallIndexes for NodeMetadata { + fn timestamp_set_call_indexes(&self) -> Result<[u8; 2]> { + self.call_indexes(TIMESTAMP, "set") + } +} diff --git a/core-primitives/nonce-cache/Cargo.toml b/core-primitives/nonce-cache/Cargo.toml index d26ee0ee57..a9e1176206 100644 --- a/core-primitives/nonce-cache/Cargo.toml +++ b/core-primitives/nonce-cache/Cargo.toml @@ -16,9 +16,6 @@ thiserror_sgx = { package = "thiserror", git = "https://github.com/mesalock-linu # std compatible external libraries (make sure these versions match with the sgx-enabled ones above) thiserror = { version = "1.0", optional = true } -# no-std dependencies -lazy_static = { version = "1.1.0", features = ["spin_no_std"] } - [features] default = ["std"] std = [ diff --git a/core-primitives/rpc/src/lib.rs b/core-primitives/rpc/src/lib.rs index 58ca257ee2..06cd8e6737 100644 --- a/core-primitives/rpc/src/lib.rs +++ b/core-primitives/rpc/src/lib.rs @@ -48,11 +48,18 @@ impl RpcReturnValue { } } +#[derive(Clone, Encode, Decode, Debug, Serialize, Deserialize)] +#[serde(untagged)] +pub enum Id { + Number(u32), + Text(String), +} + #[derive(Clone, Encode, Decode, Debug, Serialize, Deserialize)] pub struct RpcResponse { pub jsonrpc: String, pub result: String, // hex encoded RpcReturnValue - pub id: u32, + pub id: Id, } #[derive(Clone, Encode, Decode, Serialize, Deserialize)] @@ -60,7 +67,7 @@ pub struct RpcRequest { pub jsonrpc: String, pub method: String, pub params: Vec, - pub id: i32, + pub id: Id, } impl RpcRequest { @@ -68,6 +75,42 @@ impl RpcRequest { method: String, params: Vec, ) -> Result { - serde_json::to_string(&RpcRequest { jsonrpc: "2.0".to_owned(), method, params, id: 1 }) + serde_json::to_string(&RpcRequest { + jsonrpc: "2.0".to_owned(), + method, + params, + id: Id::Number(1), + }) + } +} + +#[cfg(test)] +pub mod tests { + use crate::Id; + + #[test] + pub fn deserialize_string_id() { + let id: Id = serde_json::from_str(r#""1""#).unwrap(); + assert!(matches!(id, Id::Text(t) if t == "1")) + } + + #[test] + pub fn deserialize_number_id() { + let id: Id = serde_json::from_str(r#"1"#).unwrap(); + assert!(matches!(id, Id::Number(t) if t == 1)) + } + + #[test] + pub fn serialize_string_id() { + let id = Id::Text("1".to_string()); + let serialized = serde_json::to_string(&id).unwrap(); + assert_eq!(serialized, r#""1""#) + } + + #[test] + pub fn serialize_number_id() { + let id = Id::Number(1); + let serialized = serde_json::to_string(&id).unwrap(); + assert_eq!(serialized, r#"1"#) } } diff --git a/core-primitives/settings/src/lib.rs b/core-primitives/settings/src/lib.rs index 0066558cd0..b9bd6a20ab 100644 --- a/core-primitives/settings/src/lib.rs +++ b/core-primitives/settings/src/lib.rs @@ -75,17 +75,14 @@ pub mod worker { // the maximum size of any extrinsic that the enclave will ever generate in B pub const EXTRINSIC_MAX_SIZE: usize = 13_000; // the maximum size of the header - pub const HEADER_MAX_SIZE: usize = 200; + pub const HEADER_MAX_SIZE: usize = 512; // maximum size of shielding key pub const SHIELDING_KEY_SIZE: usize = 8192; // maximum size of signing key pub const SIGNING_KEY_SIZE: usize = 32; // size of the MR enclave pub const MR_ENCLAVE_SIZE: usize = 32; - // Factors to tune the initial amount of enclave funding: - // Should be set to a value that ensures that the enclave can register itself - // and the worker can run for a certain time. Only for development. - pub const EXISTENTIAL_DEPOSIT_FACTOR_FOR_INIT_FUNDS: u128 = 200_000; + // Should be set to a value that ensures that the enclave can register itself // and that the worker can start. pub const REGISTERING_FEE_FACTOR_FOR_INIT_FUNDS: u128 = 10; diff --git a/core-primitives/sgx/crypto/Cargo.toml b/core-primitives/sgx/crypto/Cargo.toml index 2e3e7c7072..fd8a971e49 100644 --- a/core-primitives/sgx/crypto/Cargo.toml +++ b/core-primitives/sgx/crypto/Cargo.toml @@ -11,22 +11,19 @@ codec = { package = "parity-scale-codec", version = "3.0.0", default-features = derive_more = { version = "0.99.5" } log = { version = "0.4", default-features = false } ofb = { version = "0.4.0" } -serde = { version = "1.0", default-features = false, features = ["alloc"], optional = true } serde_json = { version = "1.0", default-features = false, features = ["alloc"], optional = true } # sgx deps -serde-sgx = { package = "serde", tag = "sgx_1.1.3", git = "https://github.com/mesalock-linux/serde-sgx", optional = true } serde_json-sgx = { package = "serde_json", tag = "sgx_1.1.3", git = "https://github.com/mesalock-linux/serde-json-sgx", optional = true } sgx-crypto-helper = { branch = "master", git = "https://github.com/apache/teaclave-sgx-sdk.git", package = "sgx_crypto_helper", default-features = false } sgx_rand = { branch = "master", git = "https://github.com/apache/teaclave-sgx-sdk.git", optional = true } sgx_tstd = { branch = "master", git = "https://github.com/apache/teaclave-sgx-sdk.git", optional = true } sgx_types = { branch = "master", git = "https://github.com/apache/teaclave-sgx-sdk.git" } -# substrate deps +# substrate sp-core = { default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } # local deps -itp-settings = { path = "../../settings" } itp-sgx-io = { path = "../io", default-features = false } # test sgx deps @@ -39,7 +36,6 @@ std = [ "log/std", "itp-sgx-io/std", "sp-core/std", - "serde/std", "serde_json/std", "sgx-crypto-helper/default", ] @@ -49,7 +45,6 @@ sgx = [ "sgx_rand", "itp-sgx-io/sgx", "serde_json-sgx", - "serde-sgx", ] mocks = [] test = [ diff --git a/core-primitives/sgx/crypto/src/lib.rs b/core-primitives/sgx/crypto/src/lib.rs index b876b05203..832239c027 100644 --- a/core-primitives/sgx/crypto/src/lib.rs +++ b/core-primitives/sgx/crypto/src/lib.rs @@ -30,7 +30,6 @@ extern crate sgx_tstd as std; #[cfg(all(not(feature = "std"), feature = "sgx"))] pub mod sgx_reexport_prelude { pub use serde_json_sgx as serde_json; - pub use serde_sgx as serde; } pub mod aes; diff --git a/core-primitives/stf-executor/Cargo.toml b/core-primitives/stf-executor/Cargo.toml index 64e2d3e79b..20e47cb4ed 100644 --- a/core-primitives/stf-executor/Cargo.toml +++ b/core-primitives/stf-executor/Cargo.toml @@ -8,7 +8,6 @@ edition = "2021" hex = { version = "0.4.3", default-features = false, features = ["alloc"] } # sgx dependencies -sgx-crypto-helper = { branch = "master", git = "https://github.com/apache/teaclave-sgx-sdk.git", package = "sgx_crypto_helper", default-features = false, optional = true } sgx_tstd = { branch = "master", git = "https://github.com/apache/teaclave-sgx-sdk.git", optional = true, features = ["untrusted_time"] } sgx_types = { branch = "master", git = "https://github.com/apache/teaclave-sgx-sdk.git" } @@ -21,7 +20,6 @@ itp-stf-interface = { path = "../stf-interface", default-features = false } itp-stf-primitives = { path = "../stf-primitives", default-features = false } itp-stf-state-handler = { path = "../stf-state-handler", default-features = false } itp-stf-state-observer = { path = "../stf-state-observer", default-features = false } -itp-storage = { path = "../storage", default-features = false } itp-time-utils = { path = "../time-utils", default-features = false } itp-top-pool-author = { path = "../top-pool-author", default-features = false } itp-types = { path = "../types", default-features = false } @@ -62,7 +60,6 @@ std = [ "itp-stf-state-handler/std", "itp-stf-state-observer/std", "itp-top-pool-author/std", - "itp-storage/std", "itp-types/std", "itp-time-utils/std", # crates.io @@ -81,7 +78,6 @@ sgx = [ "itp-stf-state-handler/sgx", "itp-stf-state-observer/sgx", "itp-top-pool-author/sgx", - "itp-storage/sgx", "itp-time-utils/sgx", "thiserror_sgx", ] @@ -89,6 +85,5 @@ test = [ "itc-parentchain-test", "itp-node-api/mocks", "itp-test", - "sgx-crypto-helper", ] mocks = [] diff --git a/core-primitives/stf-executor/src/enclave_signer.rs b/core-primitives/stf-executor/src/enclave_signer.rs index 6b41518d24..dfb57a15a4 100644 --- a/core-primitives/stf-executor/src/enclave_signer.rs +++ b/core-primitives/stf-executor/src/enclave_signer.rs @@ -17,7 +17,7 @@ use crate::{ error::{Error, Result}, - traits::StfEnclaveSigning, + traits::{StfEnclaveSigning, StfShardVaultQuery}, H256, }; use codec::{Decode, Encode}; @@ -25,14 +25,14 @@ 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_interface::{system_pallet::SystemPalletAccountInterface, ShardVaultQuery}; 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, ShardIdentifier}; +use itp_types::{parentchain::ParentchainId, Index, ShardIdentifier}; use sp_core::{ed25519::Pair as Ed25519Pair, Pair}; use std::{boxed::Box, sync::Arc}; @@ -46,7 +46,7 @@ pub struct StfEnclaveSigner< G, > { state_observer: Arc, - ocall_api: Arc, + pub ocall_api: Arc, shielding_key_repo: Arc, top_pool_author: Arc, _phantom: PhantomData<(Stf, TCS, G)>, @@ -60,7 +60,8 @@ where StateObserver::StateType: SgxExternalitiesTrait, ShieldingKeyRepository: AccessKey, ::KeyType: DeriveEd25519, - Stf: SystemPalletAccountInterface, + Stf: SystemPalletAccountInterface + + ShardVaultQuery, Stf::Index: Into, TopPoolAuthor: AuthorApi + Send + Sync + 'static, TCS: PartialEq + Encode + Decode + Debug + Send + Sync, @@ -105,7 +106,8 @@ where StateObserver::StateType: SgxExternalitiesTrait, ShieldingKeyRepository: AccessKey, ::KeyType: DeriveEd25519, - Stf: SystemPalletAccountInterface, + Stf: SystemPalletAccountInterface + + ShardVaultQuery, Stf::Index: Into, TopPoolAuthor: AuthorApi + Send + Sync + 'static, TCS: PartialEq + Encode + Decode + Debug + Send + Sync, @@ -142,3 +144,25 @@ where )) } } + +impl StfShardVaultQuery + for StfEnclaveSigner +where + OCallApi: EnclaveAttestationOCallApi, + StateObserver: ObserveState, + StateObserver::StateType: SgxExternalitiesTrait, + ShieldingKeyRepository: AccessKey, + ::KeyType: DeriveEd25519, + Stf: SystemPalletAccountInterface + + ShardVaultQuery, + Stf::Index: Into, + TopPoolAuthor: AuthorApi + Send + Sync + 'static, + TCS: PartialEq + Encode + Decode + Debug + Send + Sync, + G: PartialEq + Encode + Decode + Debug + Send + Sync, +{ + fn get_shard_vault(&self, shard: &ShardIdentifier) -> Result<(AccountId, ParentchainId)> { + let vault = self.state_observer.observe_state(shard, move |state| Stf::get_vault(state))?; + + vault.ok_or_else(|| Error::Other("shard vault undefined".into())) + } +} diff --git a/core-primitives/stf-executor/src/executor.rs b/core-primitives/stf-executor/src/executor.rs index e44b6eb059..d99351a9ff 100644 --- a/core-primitives/stf-executor/src/executor.rs +++ b/core-primitives/stf-executor/src/executor.rs @@ -25,7 +25,7 @@ use itp_node_api::metadata::{provider::AccessNodeMetadata, NodeMetadataTrait}; use itp_ocall_api::{EnclaveAttestationOCallApi, EnclaveOnChainOCallApi}; use itp_sgx_externalities::{SgxExternalitiesTrait, StateHash}; use itp_stf_interface::{ - parentchain_pallet::ParentchainPalletInterface, StateCallInterface, UpdateState, + parentchain_pallet::ParentchainPalletInstancesInterface, StateCallInterface, UpdateState, }; use itp_stf_primitives::{ traits::TrustedCallVerification, @@ -34,9 +34,9 @@ use itp_stf_primitives::{ 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, ParentchainId}, + parentchain::{Header as ParentchainHeader, ParentchainCall, ParentchainId}, storage::StorageEntryVerified, - OpaqueCall, H256, + H256, }; use log::*; use sp_runtime::traits::Header as HeaderTrait; @@ -44,6 +44,7 @@ use std::{ collections::BTreeMap, fmt::Debug, marker::PhantomData, sync::Arc, time::Duration, vec, vec::Vec, }; + pub struct StfExecutor where TCS: PartialEq + Encode + Decode + Debug + Clone + Send + Sync + TrustedCallVerification, @@ -117,7 +118,7 @@ where } debug!("execute on STF, call with nonce {}", trusted_call.nonce()); - let mut extrinsic_call_backs: Vec = Vec::new(); + let mut extrinsic_call_backs: Vec = Vec::new(); if let Err(e) = Stf::execute_call( state, trusted_call.clone(), @@ -136,7 +137,20 @@ where } for call in extrinsic_call_backs.clone() { - trace!("trusted_call wants to send encoded call: 0x{}", hex::encode(call.encode())); + match call { + ParentchainCall::Integritee(opaque_call) => trace!( + "trusted_call wants to send encoded call to [Integritee] parentchain: 0x{}", + hex::encode(opaque_call.encode()) + ), + ParentchainCall::TargetA(opaque_call) => trace!( + "trusted_call wants to send encoded call to [TargetA] parentchain: 0x{}", + hex::encode(opaque_call.encode()) + ), + ParentchainCall::TargetB(opaque_call) => trace!( + "trusted_call wants to send encoded call to [TargetB] parentchain: 0x{}", + hex::encode(opaque_call.encode()) + ), + } } Ok(ExecutedOperation::success(operation_hash, top_or_hash, extrinsic_call_backs)) } @@ -153,10 +167,11 @@ where Stf: UpdateState< StateHandler::StateT, ::SgxExternalitiesDiffType, - > + ParentchainPalletInterface, + > + ParentchainPalletInstancesInterface, ::SgxExternalitiesDiffType: IntoIterator, Option>)>, - >::Error: Debug, + >::Error: + Debug, ::SgxExternalitiesDiffType: From, Option>>>, TCS: PartialEq + Encode + Decode + Debug + Clone + Send + Sync + TrustedCallVerification, @@ -170,10 +185,6 @@ where debug!("Update STF storage upon block import!"); let storage_hashes = Stf::storage_hashes_to_update_on_block(parentchain_id); - if storage_hashes.is_empty() { - return Ok(()) - } - // global requests they are the same for every shard let state_diff_update = self .ocall_api @@ -186,7 +197,7 @@ where 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_block(&mut state, header.clone()) { + match Stf::update_parentchain_integritee_block(&mut state, header.clone()) { Ok(_) => { self.state_handler.write_after_mutation(state, state_lock, &shard_id)?; }, @@ -215,12 +226,13 @@ impl where ::SgxExternalitiesDiffType: From, Option>>> + IntoIterator, Option>)>, - >::Error: Debug, + >::Error: + Debug, NodeMetadataRepository: AccessNodeMetadata, OCallApi: EnclaveAttestationOCallApi + EnclaveOnChainOCallApi, StateHandler: HandleState + QueryShardState, StateHandler::StateT: Encode + SgxExternalitiesTrait, - Stf: ParentchainPalletInterface + Stf: ParentchainPalletInstancesInterface + UpdateState< StateHandler::StateT, ::SgxExternalitiesDiffType, @@ -253,7 +265,7 @@ where 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_block(&mut state, header.clone()) { + if let Err(e) = Stf::update_parentchain_integritee_block(&mut state, header.clone()) { error!("Could not update parentchain block. {:?}: {:?}", shard_id, e) } diff --git a/core-primitives/stf-executor/src/lib.rs b/core-primitives/stf-executor/src/lib.rs index ecc93e5c9a..08d9c9125e 100644 --- a/core-primitives/stf-executor/src/lib.rs +++ b/core-primitives/stf-executor/src/lib.rs @@ -28,7 +28,7 @@ use codec::{Decode, Encode}; use core::fmt::Debug; use itp_sgx_externalities::SgxExternalitiesTrait; use itp_stf_primitives::types::TrustedOperationOrHash; -use itp_types::{OpaqueCall, H256}; +use itp_types::{parentchain::ParentchainCall, H256}; use std::vec::Vec; // re-export module to properly feature gate sgx and regular std environment @@ -60,12 +60,12 @@ pub mod mocks; /// any extrinsic callbacks (e.g. unshield extrinsics) that need to be executed on-chain #[derive(Clone, Debug, PartialEq)] pub enum ExecutionStatus { - Success(H256, Vec), + Success(H256, Vec), Failure, } impl ExecutionStatus { - pub fn get_extrinsic_callbacks(&self) -> Vec { + pub fn get_extrinsic_callbacks(&self) -> Vec { match self { ExecutionStatus::Success(_, opaque_calls) => opaque_calls.clone(), _ => Vec::new(), @@ -102,7 +102,7 @@ where pub fn success( operation_hash: H256, trusted_operation_or_hash: TrustedOperationOrHash, - extrinsic_call_backs: Vec, + extrinsic_call_backs: Vec, ) -> Self { ExecutedOperation { status: ExecutionStatus::Success(operation_hash, extrinsic_call_backs), @@ -141,7 +141,7 @@ where TCS: PartialEq + Encode + Decode + Debug + Clone + Send + Sync, G: PartialEq + Encode + Decode + Debug + Clone + Send + Sync, { - pub fn get_extrinsic_callbacks(&self) -> Vec { + pub fn get_extrinsic_callbacks(&self) -> Vec { self.executed_operations .iter() .flat_map(|e| e.status.get_extrinsic_callbacks()) @@ -173,6 +173,7 @@ 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() { @@ -233,7 +234,8 @@ mod tests { int: u8, ) -> (ExecutedOperation, H256) { let hash = H256::from([int; 32]); - let opaque_call: Vec = vec![OpaqueCall(vec![int; 10])]; + let opaque_call: Vec = + vec![ParentchainCall::Integritee(OpaqueCall(vec![int; 10]))]; let operation = ExecutedOperation::success(hash, TrustedOperationOrHash::Hash(hash), opaque_call); (operation, hash) diff --git a/core-primitives/stf-executor/src/mocks.rs b/core-primitives/stf-executor/src/mocks.rs index fd877f34e7..8e4753b9cc 100644 --- a/core-primitives/stf-executor/src/mocks.rs +++ b/core-primitives/stf-executor/src/mocks.rs @@ -35,10 +35,12 @@ use sp_runtime::traits::Header as HeaderTrait; use std::sync::RwLock; use std::{boxed::Box, marker::PhantomData, ops::Deref, time::Duration, vec::Vec}; +use crate::traits::StfShardVaultQuery; use itp_stf_primitives::{ traits::{GetterAuthorization, TrustedCallVerification}, types::TrustedOperation, }; +use itp_types::parentchain::ParentchainId; #[cfg(feature = "sgx")] use std::sync::SgxRwLock as RwLock; @@ -136,6 +138,12 @@ impl StfEnclaveSigning for StfEnclaveSigne } } +impl StfShardVaultQuery for StfEnclaveSignerMock { + fn get_shard_vault(&self, _shard: &ShardIdentifier) -> Result<(AccountId, ParentchainId)> { + Err(crate::error::Error::Other("shard vault undefined".into())) + } +} + /// GetState mock #[derive(Default)] pub struct GetStateMock { diff --git a/core-primitives/stf-executor/src/traits.rs b/core-primitives/stf-executor/src/traits.rs index 5aed037b88..51bf7a3822 100644 --- a/core-primitives/stf-executor/src/traits.rs +++ b/core-primitives/stf-executor/src/traits.rs @@ -23,7 +23,7 @@ use itp_stf_primitives::{ traits::TrustedCallSigning, types::{AccountId, ShardIdentifier, TrustedOperation}, }; -use itp_types::H256; +use itp_types::{parentchain::ParentchainId, H256}; use sp_runtime::traits::Header as HeaderTrait; use std::time::Duration; @@ -49,6 +49,10 @@ where ) -> Result; } +pub trait StfShardVaultQuery { + fn get_shard_vault(&self, shard: &ShardIdentifier) -> Result<(AccountId, ParentchainId)>; +} + /// Proposes a state update to `Externalities`. pub trait StateUpdateProposer where diff --git a/core-primitives/stf-interface/src/lib.rs b/core-primitives/stf-interface/src/lib.rs index dd46c6c5ce..7dba9697dd 100644 --- a/core-primitives/stf-interface/src/lib.rs +++ b/core-primitives/stf-interface/src/lib.rs @@ -28,7 +28,10 @@ use core::fmt::Debug; use itp_node_api_metadata::NodeMetadataTrait; use itp_node_api_metadata_provider::AccessNodeMetadata; use itp_stf_primitives::traits::TrustedCallVerification; -use itp_types::{parentchain::ParentchainId, OpaqueCall}; +use itp_types::{ + parentchain::{AccountId, BlockHash, BlockNumber, ParentchainCall, ParentchainId}, + Moment, +}; #[cfg(feature = "mocks")] pub mod mocks; @@ -36,7 +39,7 @@ pub mod parentchain_pallet; pub mod sudo_pallet; pub mod system_pallet; -pub const SHARD_VAULT_KEY: &str = "ShardVaultPubKey"; +pub const SHARD_CREATION_HEADER_KEY: &str = "ShardCreationHeaderKey"; /// Interface to initialize a new state. pub trait InitState { @@ -44,6 +47,16 @@ pub trait InitState { fn init_state(enclave_account: AccountId) -> State; } +/// Interface to query shard vault account for shard +pub trait ShardVaultQuery { + fn get_vault(state: &mut S) -> Option<(AccountId, ParentchainId)>; +} + +/// Interface to query shard creation block information for shard on a specified parentchain +pub trait ShardCreationQuery { + fn get_shard_creation_info(state: &mut S) -> ShardCreationInfo; +} + /// Interface for all functions calls necessary to update an already /// initialized state. pub trait UpdateState { @@ -65,7 +78,7 @@ where fn execute_call( state: &mut State, call: TCS, - calls: &mut Vec, + calls: &mut Vec, node_metadata_repo: Arc, ) -> Result<(), Self::Error>; } @@ -87,7 +100,7 @@ where /// Execute a call. Callbacks are added as an `OpaqueCall`. fn execute( self, - calls: &mut Vec, + calls: &mut Vec, node_metadata_repo: Arc, ) -> Result<(), Self::Error>; @@ -102,3 +115,27 @@ pub trait ExecuteGetter { /// Get storages hashes that should be updated for a specific getter. fn get_storage_hashes_to_update(self) -> Vec>; } + +#[derive(Debug, Clone, Copy, Encode, Decode)] +pub struct BlockMetadata { + pub number: BlockNumber, + pub hash: BlockHash, + pub timestamp: Option, +} + +#[derive(Debug, Clone, Copy, Encode, Decode)] +pub struct ShardCreationInfo { + pub integritee: Option, + pub target_a: Option, + pub target_b: Option, +} + +impl ShardCreationInfo { + pub fn for_parentchain(&self, id: ParentchainId) -> Option { + match id { + ParentchainId::Integritee => self.integritee, + ParentchainId::TargetA => self.target_a, + ParentchainId::TargetB => self.target_b, + } + } +} diff --git a/core-primitives/stf-interface/src/mocks.rs b/core-primitives/stf-interface/src/mocks.rs index 0156cb5c08..892819a5d9 100644 --- a/core-primitives/stf-interface/src/mocks.rs +++ b/core-primitives/stf-interface/src/mocks.rs @@ -28,7 +28,10 @@ use core::{fmt::Debug, marker::PhantomData}; use itp_node_api_metadata::metadata_mocks::NodeMetadataMock; use itp_node_api_metadata_provider::NodeMetadataRepository; use itp_stf_primitives::traits::TrustedCallVerification; -use itp_types::{parentchain::ParentchainId, AccountId, Index, OpaqueCall}; +use itp_types::{ + parentchain::{ParentchainCall, ParentchainId}, + AccountId, Index, +}; #[derive(Default)] pub struct StateInterfaceMock { @@ -63,7 +66,7 @@ where fn execute_call( _state: &mut State, _call: TCS, - _calls: &mut Vec, + _calls: &mut Vec, _node_metadata_repo: Arc>, ) -> Result<(), Self::Error> { unimplemented!() @@ -99,7 +102,7 @@ impl ExecuteCall> for CallExecutorMock fn execute( self, - _calls: &mut Vec, + _calls: &mut Vec, _node_metadata_repo: Arc>, ) -> Result<(), Self::Error> { unimplemented!() diff --git a/core-primitives/stf-interface/src/parentchain_pallet.rs b/core-primitives/stf-interface/src/parentchain_pallet.rs index c89138c25e..b73898f104 100644 --- a/core-primitives/stf-interface/src/parentchain_pallet.rs +++ b/core-primitives/stf-interface/src/parentchain_pallet.rs @@ -15,13 +15,43 @@ */ +use itp_types::parentchain::{AccountId, ParentchainId}; + /// Interface trait of the parentchain pallet. -pub trait ParentchainPalletInterface { +pub trait ParentchainPalletInstancesInterface { type Error; /// Updates the block number, block hash and parent hash of the parentchain block. - fn update_parentchain_block( + fn update_parentchain_integritee_block( + state: &mut State, + header: ParentchainHeader, + ) -> Result<(), Self::Error>; + + /// Updates the block number, block hash and parent hash of the parentchain block. + fn update_parentchain_target_a_block( + state: &mut State, + header: ParentchainHeader, + ) -> Result<(), Self::Error>; + + /// Updates the block number, block hash and parent hash of the parentchain block. + fn update_parentchain_target_b_block( + state: &mut State, + header: ParentchainHeader, + ) -> Result<(), Self::Error>; + + fn init_shard_vault_account( + state: &mut State, + vault: AccountId, + parentchain_id: ParentchainId, + ) -> Result<(), Self::Error>; + + fn set_creation_block( state: &mut State, header: ParentchainHeader, + parentchain_id: ParentchainId, ) -> Result<(), Self::Error>; + + fn get_shard_vault_ensure_single_parentchain( + state: &mut State, + ) -> Result, Self::Error>; } diff --git a/core-primitives/stf-primitives/Cargo.toml b/core-primitives/stf-primitives/Cargo.toml index 77eee376cf..28070616d4 100644 --- a/core-primitives/stf-primitives/Cargo.toml +++ b/core-primitives/stf-primitives/Cargo.toml @@ -8,9 +8,6 @@ edition = "2021" # crates.io codec = { version = "3.0.0", default-features = false, features = ["derive"], package = "parity-scale-codec" } derive_more = { version = "0.99.5" } - -# Substrate dependencies -itp-hashing = { default-features = false, path = "../../core-primitives/hashing" } itp-sgx-runtime-primitives = { path = "../../core-primitives/sgx-runtime-primitives", default-features = false } sp-core = { default-features = false, features = ["full_crypto"], git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } sp-runtime = { default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } @@ -25,4 +22,5 @@ std = [ "sp-core/std", "sp-std/std", "sp-runtime/std", + "itp-sgx-runtime-primitives/std", ] diff --git a/core-primitives/stf-primitives/src/error.rs b/core-primitives/stf-primitives/src/error.rs index 0c91d0705c..01d87e856a 100644 --- a/core-primitives/stf-primitives/src/error.rs +++ b/core-primitives/stf-primitives/src/error.rs @@ -36,4 +36,8 @@ pub enum StfError { StorageHashMismatch, InvalidStorageDiff, InvalidMetadata, + ShardVaultOnMultipleParentchainsNotAllowed, + ChangingShardVaultAccountNotAllowed, + WrongParentchainIdForShardVault, + NoShardVaultAssigned, } diff --git a/core-primitives/stf-primitives/src/lib.rs b/core-primitives/stf-primitives/src/lib.rs index 25ef681d8c..8e5ce6b1c0 100644 --- a/core-primitives/stf-primitives/src/lib.rs +++ b/core-primitives/stf-primitives/src/lib.rs @@ -16,6 +16,7 @@ */ #![cfg_attr(not(feature = "std"), no_std)] extern crate alloc; + pub mod error; pub mod traits; pub mod types; diff --git a/core-primitives/stf-primitives/src/traits.rs b/core-primitives/stf-primitives/src/traits.rs index 4ed77f7ae1..34add7ce81 100644 --- a/core-primitives/stf-primitives/src/traits.rs +++ b/core-primitives/stf-primitives/src/traits.rs @@ -14,8 +14,10 @@ limitations under the License. */ - use crate::types::{AccountId, KeyPair, ShardIdentifier}; +use alloc::vec::Vec; +use codec::{Decode, Encode}; +use core::fmt::Debug; use itp_sgx_runtime_primitives::types::Index; use sp_runtime::transaction_validity::{TransactionValidityError, ValidTransaction}; /// checks authorization of stf getters @@ -47,3 +49,26 @@ pub trait TrustedCallVerification { pub trait PoolTransactionValidation { fn validate(&self) -> Result; } + +/// Trait to be implemented on the executor to serve helper methods of the executor +/// to the `IndirectDispatch` implementation. +pub trait IndirectExecutor +where + TCS: PartialEq + Encode + Decode + Debug + Clone + Send + Sync + TrustedCallVerification, +{ + fn submit_trusted_call(&self, shard: ShardIdentifier, encrypted_trusted_call: Vec); + + fn decrypt(&self, encrypted: &[u8]) -> Result, Error>; + + fn encrypt(&self, value: &[u8]) -> Result, Error>; + + fn get_enclave_account(&self) -> Result; + + fn get_default_shard(&self) -> ShardIdentifier; + + fn sign_call_with_self>( + &self, + trusted_call: &TC, + shard: &ShardIdentifier, + ) -> Result; +} diff --git a/core-primitives/stf-state-handler/Cargo.toml b/core-primitives/stf-state-handler/Cargo.toml index 569eb9e59a..eef828d4aa 100644 --- a/core-primitives/stf-state-handler/Cargo.toml +++ b/core-primitives/stf-state-handler/Cargo.toml @@ -5,8 +5,6 @@ authors = ["Integritee AG "] edition = "2021" [dependencies] -# sgx dependencies -sgx_tcrypto = { branch = "master", git = "https://github.com/apache/teaclave-sgx-sdk.git", optional = true } sgx_tstd = { branch = "master", git = "https://github.com/apache/teaclave-sgx-sdk.git", optional = true } sgx_types = { branch = "master", git = "https://github.com/apache/teaclave-sgx-sdk.git" } @@ -34,7 +32,6 @@ thiserror = { version = "1.0", optional = true } # no-std dependencies codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive"] } -lazy_static = { version = "1.1.0", features = ["spin_no_std"] } log = { version = "0.4", default-features = false } sp-core = { default-features = false, features = ["full_crypto"], git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } @@ -59,7 +56,6 @@ std = [ ] sgx = [ "sgx_tstd", - "sgx_tcrypto", "rust-base58_sgx", "itp-sgx-crypto/sgx", "itp-sgx-externalities/sgx", diff --git a/core-primitives/stf-state-observer/Cargo.toml b/core-primitives/stf-state-observer/Cargo.toml index b1a1bc73ed..f534292fbe 100644 --- a/core-primitives/stf-state-observer/Cargo.toml +++ b/core-primitives/stf-state-observer/Cargo.toml @@ -14,16 +14,12 @@ itp-types = { default-features = false, path = "../types" } thiserror_sgx = { package = "thiserror", git = "https://github.com/mesalock-linux/thiserror-sgx", tag = "sgx_1.1.3", optional = true } # std compatible external libraries (make sure these versions match with the sgx-enabled ones above) -thiserror = { version = "1.0", optional = true } - -# no-std dependencies -codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive"] } log = { version = "0.4", default-features = false } +thiserror = { version = "1.0", optional = true } [features] default = ["std"] std = [ - "codec/std", "itp-types/std", "log/std", "thiserror", diff --git a/core-primitives/stf-state-observer/src/error.rs b/core-primitives/stf-state-observer/src/error.rs index 914552fb86..f2f17ce3fb 100644 --- a/core-primitives/stf-state-observer/src/error.rs +++ b/core-primitives/stf-state-observer/src/error.rs @@ -26,7 +26,7 @@ use std::boxed::Box; #[derive(Debug, thiserror::Error)] pub enum Error { #[error("Current state is empty (not set)")] - CurrentStateEmpty, + CurrentShardStateEmpty, #[error("Could not acquire lock, lock is poisoned")] LockPoisoning, #[error(transparent)] diff --git a/core-primitives/stf-state-observer/src/mock.rs b/core-primitives/stf-state-observer/src/mock.rs index 335adf7b91..ce95877873 100644 --- a/core-primitives/stf-state-observer/src/mock.rs +++ b/core-primitives/stf-state-observer/src/mock.rs @@ -59,7 +59,7 @@ where debug!("State value: {:?}", state); Ok(observation_func(state)) }, - None => Err(Error::CurrentStateEmpty), + None => Err(Error::CurrentShardStateEmpty), } } } diff --git a/core-primitives/stf-state-observer/src/state_observer.rs b/core-primitives/stf-state-observer/src/state_observer.rs index 21c8042ac0..4e75fad729 100644 --- a/core-primitives/stf-state-observer/src/state_observer.rs +++ b/core-primitives/stf-state-observer/src/state_observer.rs @@ -85,7 +85,7 @@ impl ObserveState for StateObserver { match current_state_map_lock.get_mut(shard) { Some(s) => Ok(observation_func(s)), - None => Err(Error::CurrentStateEmpty), + None => Err(Error::CurrentShardStateEmpty), } } } @@ -112,7 +112,7 @@ mod tests { assert_matches!( state_observer.observe_state(&shard(), |_| { () }), - Err(Error::CurrentStateEmpty) + Err(Error::CurrentShardStateEmpty) ); } diff --git a/core-primitives/substrate-sgx/sp-io/Cargo.toml b/core-primitives/substrate-sgx/sp-io/Cargo.toml index 500b7a55e8..4a825df11e 100644 --- a/core-primitives/substrate-sgx/sp-io/Cargo.toml +++ b/core-primitives/substrate-sgx/sp-io/Cargo.toml @@ -7,27 +7,14 @@ license = "Apache-2.0" [dependencies] codec = { version = "3.0.0", package = "parity-scale-codec", default-features = false } -futures = { version = "0.3.1", optional = true, features = ["thread-pool"] } -hash-db = { version = "0.15.2", default-features = false } libsecp256k1 = { version = "0.7.0", default-features = false, features = ["static-context"] } log = { version = "0.4", default-features = false } -parking_lot = { version = "0.12.0", optional = true } -tracing = { version = "0.1.25", default-features = false } -tracing-core = { version = "0.1.17", default-features = false } itp-sgx-externalities = { default-features = false, path = "../externalities" } sgx_tstd = { optional = true, features = ["untrusted_fs", "net", "backtrace"], git = "https://github.com/apache/teaclave-sgx-sdk.git", branch = "master" } -sgx_types = { optional = true, git = "https://github.com/apache/teaclave-sgx-sdk.git", branch = "master" } # Substrate dependencies sp-core = { default-features = false, features = ["full_crypto"], git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } -sp-runtime-interface = { default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } -sp-std = { default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } -sp-tracing = { default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } -sp-wasm-interface = { default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } - -# local -environmental = { path = "../environmental", default-features = false } [features] default = ["std"] @@ -35,24 +22,12 @@ std = [ "log/std", "sp-core/std", "codec/std", - "sp-std/std", - "hash-db/std", "libsecp256k1/std", - "sp-runtime-interface/std", - "sp-wasm-interface/std", - "futures", - "parking_lot", "itp-sgx-externalities/std", - # local - "environmental/std", ] sgx = [ "sgx_tstd", - "sgx_types", "itp-sgx-externalities/sgx", - "sp-runtime-interface/disable_target_static_assertions", - #local - "environmental/sgx", ] # These two features are used for `no_std` builds for the environments which already provides diff --git a/core-primitives/test/Cargo.toml b/core-primitives/test/Cargo.toml index b448550ace..c5324e9cc0 100644 --- a/core-primitives/test/Cargo.toml +++ b/core-primitives/test/Cargo.toml @@ -5,7 +5,6 @@ edition = "2021" [dependencies] codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive"] } -derive_more = { version = "0.99.5" } log = { version = "0.4", default-features = false } sgx-crypto-helper = { branch = "master", git = "https://github.com/apache/teaclave-sgx-sdk.git", package = "sgx_crypto_helper", default-features = false } @@ -16,6 +15,7 @@ sgx_types = { branch = "master", git = "https://github.com/apache/teaclave-sgx-s # substrate deps sp-core = { default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } +sp-io = { default-features = false, features = ["disable_oom", "disable_panic_handler", "disable_allocator"], path = "../../core-primitives/substrate-sgx/sp-io" } sp-runtime = { default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } sp-std = { default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } @@ -32,25 +32,24 @@ itp-stf-state-handler = { path = "../stf-state-handler", default-features = fals itp-storage = { path = "../storage", default-features = false } itp-time-utils = { path = "../time-utils", default-features = false } itp-types = { path = "../types", default-features = false, features = ["test"] } -sp-io = { default-features = false, features = ["disable_oom", "disable_panic_handler", "disable_allocator"], path = "../../core-primitives/substrate-sgx/sp-io" } [features] default = ["std"] std = [ "codec/std", + "itp-enclave-bridge-storage/std", + "itp-node-api-metadata-provider/std", + "itp-node-api/std", + "itp-ocall-api/std", "itp-sgx-crypto/std", "itp-sgx-externalities/std", "itp-stf-interface/std", "itp-stf-primitives/std", "itp-stf-state-handler/std", "itp-storage/std", - "itp-enclave-bridge-storage/std", "itp-time-utils/std", "itp-types/std", - "itp-node-api/std", - "itp-node-api-metadata-provider/std", - "itp-ocall-api/std", "log/std", "sp-core/std", "sp-io/std", diff --git a/core-primitives/test/src/mock/stf_mock.rs b/core-primitives/test/src/mock/stf_mock.rs index cbb37c19ea..1b1cec4278 100644 --- a/core-primitives/test/src/mock/stf_mock.rs +++ b/core-primitives/test/src/mock/stf_mock.rs @@ -30,7 +30,8 @@ use itp_stf_primitives::{ types::{KeyPair, Nonce, TrustedOperation}, }; use itp_types::{ - parentchain::ParentchainId, AccountId, Balance, Index, OpaqueCall, ShardIdentifier, Signature, + parentchain::{ParentchainCall, ParentchainId}, + AccountId, Balance, Index, ShardIdentifier, Signature, }; use log::*; use sp_core::{sr25519, Pair}; @@ -39,6 +40,7 @@ use sp_runtime::transaction_validity::{ }; use sp_std::{vec, vec::Vec}; use std::{thread::sleep, time::Duration}; + // a few dummy types type NodeMetadataRepositoryMock = NodeMetadataRepository; @@ -67,7 +69,7 @@ impl StateCallInterface, + calls: &mut Vec, node_metadata_repo: Arc, ) -> Result<(), Self::Error> { state.execute_with(|| call.execute(calls, node_metadata_repo)) @@ -161,7 +163,7 @@ impl ExecuteCall for TrustedCallSignedMock { fn execute( self, - _calls: &mut Vec, + _calls: &mut Vec, _node_metadata_repo: Arc, ) -> Result<(), Self::Error> { match self.call { diff --git a/core-primitives/top-pool-author/Cargo.toml b/core-primitives/top-pool-author/Cargo.toml index 0ca7f7327c..7cb108f4ec 100644 --- a/core-primitives/top-pool-author/Cargo.toml +++ b/core-primitives/top-pool-author/Cargo.toml @@ -7,7 +7,6 @@ edition = "2021" [dependencies] # sgx dependencies sgx_tstd = { branch = "master", git = "https://github.com/apache/teaclave-sgx-sdk.git", optional = true } -sgx_types = { branch = "master", git = "https://github.com/apache/teaclave-sgx-sdk.git" } # local dependencies itp-enclave-metrics = { path = "../enclave-metrics", default-features = false } @@ -18,15 +17,12 @@ itp-stf-state-handler = { path = "../stf-state-handler", default-features = fals itp-test = { path = "../test", default-features = false, optional = true } itp-top-pool = { path = "../top-pool", default-features = false } itp-types = { path = "../types", default-features = false } -itp-utils = { path = "../utils", default-features = false } # sgx enabled external libraries jsonrpc-core_sgx = { package = "jsonrpc-core", git = "https://github.com/scs/jsonrpc", branch = "no_std_v18", default-features = false, optional = true } -thiserror_sgx = { package = "thiserror", git = "https://github.com/mesalock-linux/thiserror-sgx", tag = "sgx_1.1.3", optional = true } # std compatible external libraries (make sure these versions match with the sgx-enabled ones above) jsonrpc-core = { version = "18", optional = true } -thiserror = { version = "1.0", optional = true } # no-std compatible libraries codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive"] } @@ -54,7 +50,6 @@ std = [ "itp-types/std", "jsonrpc-core", "log/std", - "thiserror", ] sgx = [ "sgx_tstd", @@ -63,7 +58,6 @@ sgx = [ "itp-sgx-crypto/sgx", "itp-stf-state-handler/sgx", "itp-top-pool/sgx", - "thiserror_sgx", ] test = ["itp-test/sgx", "itp-top-pool/mocks"] mocks = [] diff --git a/core-primitives/top-pool-author/src/lib.rs b/core-primitives/top-pool-author/src/lib.rs index bc523e9cf8..b0b84b992c 100644 --- a/core-primitives/top-pool-author/src/lib.rs +++ b/core-primitives/top-pool-author/src/lib.rs @@ -29,7 +29,6 @@ extern crate sgx_tstd as std; #[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; } pub mod api; diff --git a/core-primitives/top-pool/Cargo.toml b/core-primitives/top-pool/Cargo.toml index 00757682c8..165ada1874 100644 --- a/core-primitives/top-pool/Cargo.toml +++ b/core-primitives/top-pool/Cargo.toml @@ -7,11 +7,9 @@ edition = "2021" [dependencies] # sgx dependencies sgx_tstd = { branch = "master", git = "https://github.com/apache/teaclave-sgx-sdk.git", optional = true, features = ["net", "thread", "untrusted_time"] } -sgx_types = { branch = "master", git = "https://github.com/apache/teaclave-sgx-sdk.git", optional = true } # local dependencies itc-direct-rpc-server = { path = "../../core/direct-rpc-server", default-features = false } -itp-sgx-runtime-primitives = { path = "../../core-primitives/sgx-runtime-primitives", default-features = false } itp-stf-primitives = { path = "../stf-primitives", default-features = false } itp-types = { path = "../types", default-features = false } its-primitives = { path = "../../sidechain/primitives", default-features = false } @@ -19,12 +17,10 @@ its-primitives = { path = "../../sidechain/primitives", default-features = false # sgx enabled external libraries jsonrpc-core_sgx = { package = "jsonrpc-core", git = "https://github.com/scs/jsonrpc", branch = "no_std_v18", default-features = false, optional = true } linked-hash-map_sgx = { package = "linked-hash-map", git = "https://github.com/mesalock-linux/linked-hash-map-sgx", optional = true } -thiserror_sgx = { package = "thiserror", git = "https://github.com/mesalock-linux/thiserror-sgx", tag = "sgx_1.1.3", optional = true } # std compatible external libraries (make sure these versions match with the sgx-enabled ones above) jsonrpc-core = { version = "18", optional = true } linked-hash-map = { version = "0.5.2", optional = true } -thiserror = { version = "1.0", optional = true } # no-std compatible libraries byteorder = { version = "1.4.2", default-features = false } @@ -45,11 +41,9 @@ itp-test = { path = "../test", default-features = false } default = ["std"] sgx = [ "sgx_tstd", - "sgx_types", "itc-direct-rpc-server/sgx", "jsonrpc-core_sgx", "linked-hash-map_sgx", - "thiserror_sgx", ] std = [ "itc-direct-rpc-server/std", @@ -62,6 +56,5 @@ std = [ "sp-core/std", "sp-runtime/std", "sp-application-crypto/std", - "thiserror", ] mocks = [] diff --git a/core-primitives/top-pool/src/lib.rs b/core-primitives/top-pool/src/lib.rs index 740c636305..fdd46ff9fe 100644 --- a/core-primitives/top-pool/src/lib.rs +++ b/core-primitives/top-pool/src/lib.rs @@ -28,7 +28,6 @@ extern crate sgx_tstd as std; pub mod sgx_reexport_prelude { pub use jsonrpc_core_sgx as jsonrpc_core; pub use linked_hash_map_sgx as linked_hash_map; - pub use thiserror_sgx as thiserror; } pub mod base_pool; diff --git a/core-primitives/types/Cargo.toml b/core-primitives/types/Cargo.toml index 5d1bc84658..a6d2f2d7a9 100644 --- a/core-primitives/types/Cargo.toml +++ b/core-primitives/types/Cargo.toml @@ -8,14 +8,16 @@ license = "Apache-2.0" edition = "2021" [dependencies] -chrono = { version = "0.4.19", default-features = false, features = ["alloc"] } codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive"] } -primitive-types = { version = "0.12.1", default-features = false, features = ["codec"] } -serde = { version = "1.0", default-features = false, features = ["alloc", "derive"] } -serde_json = { version = "1.0", default-features = false, features = ["alloc"] } +serde = { version = "1.0", default-features = false, features = ["derive", "alloc"] } # local dependencies itp-sgx-runtime-primitives = { path = "../../core-primitives/sgx-runtime-primitives", default-features = false } +itp-stf-primitives = { path = "../../core-primitives/stf-primitives", default-features = false } +itp-utils = { path = "../../core-primitives/utils", default-features = false } + +# scs +substrate-api-client = { default-features = false, features = ["sync-api"], git = "https://github.com/scs/substrate-api-client.git", branch = "polkadot-v0.9.42-tag-v0.14.0" } # substrate-deps frame-system = { default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } @@ -25,26 +27,25 @@ sp-runtime = { default-features = false, git = "https://github.com/paritytech/su sp-std = { default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } # integritee-node -enclave-bridge-primitives = { default-features = false, git = "https://github.com/integritee-network/pallets.git", branch = "sdk-v0.12.0-polkadot-v0.9.42" } -my-node-runtime = { package = "integritee-node-runtime", optional = true, git = "https://github.com/integritee-network/integritee-node.git", branch = "sdk-v0.12.0-polkadot-v0.9.42" } -teerex-primitives = { default-features = false, git = "https://github.com/integritee-network/pallets.git", branch = "sdk-v0.12.0-polkadot-v0.9.42" } - +enclave-bridge-primitives = { default-features = false, git = "https://github.com/integritee-network/pallets.git", branch = "sdk-v0.12.11-polkadot-v0.9.42" } +teeracle-primitives = { default-features = false, git = "https://github.com/integritee-network/pallets.git", branch = "sdk-v0.12.11-polkadot-v0.9.42" } +teerex-primitives = { default-features = false, git = "https://github.com/integritee-network/pallets.git", branch = "sdk-v0.12.11-polkadot-v0.9.42" } [features] default = ["std"] std = [ "codec/std", - "chrono/std", - "my-node-runtime", - "serde/std", - "serde_json/std", - "primitive-types/std", "itp-sgx-runtime-primitives/std", + "itp-stf-primitives/std", + "itp-utils/std", + "substrate-api-client/std", "teerex-primitives/std", + "teeracle-primitives/std", "enclave-bridge-primitives/std", # substrate "frame-system/std", "pallet-balances/std", + "serde/std", "sp-std/std", "sp-core/std", "sp-runtime/std", diff --git a/core-primitives/types/src/lib.rs b/core-primitives/types/src/lib.rs index 361bb9793e..08ff827db2 100644 --- a/core-primitives/types/src/lib.rs +++ b/core-primitives/types/src/lib.rs @@ -20,8 +20,6 @@ use crate::storage::StorageEntry; use codec::{Decode, Encode}; -#[cfg(feature = "sgx")] -use sgx_tstd as std; use sp_std::vec::Vec; pub mod parentchain; diff --git a/core-primitives/types/src/parentchain.rs b/core-primitives/types/src/parentchain.rs index 6439929129..b8ec303536 100644 --- a/core-primitives/types/src/parentchain.rs +++ b/core-primitives/types/src/parentchain.rs @@ -15,12 +15,19 @@ */ -//! Parentchain specific params. Be sure to change them if your node uses different types. - +use crate::{OpaqueCall, PalletString, ShardIdentifier}; +use alloc::{format, vec::Vec}; use codec::{Decode, Encode}; +use core::fmt::Debug; +use itp_stf_primitives::traits::{IndirectExecutor, TrustedCallVerification}; +use itp_utils::stringify::account_id_to_string; +#[cfg(feature = "std")] +use serde::{Deserialize, Serialize}; +use sp_core::bounded::alloc; use sp_runtime::{generic::Header as HeaderG, traits::BlakeTwo256, MultiAddress, MultiSignature}; -use sp_std::vec::Vec; - +use substrate_api_client::ac_node_api::StaticEvent; +use teeracle_primitives::ExchangeRate; +use teerex_primitives::{SgxAttestationMethod, SgxStatus}; pub type StorageProof = Vec>; // Basic Types. @@ -52,6 +59,7 @@ pub type BlockHash = sp_core::H256; pub type Signature = MultiSignature; #[derive(Encode, Decode, Copy, Clone, Debug, PartialEq, Eq)] +#[cfg_attr(feature = "std", derive(Serialize, Deserialize))] pub enum ParentchainId { /// The Integritee Parentchain, the trust root of the enclave and serving finality to sidechains. Integritee, @@ -61,6 +69,249 @@ pub enum ParentchainId { TargetB, } +#[cfg(feature = "std")] +impl std::fmt::Display for ParentchainId { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + let message = match self { + ParentchainId::Integritee => "Integritee", + ParentchainId::TargetA => "TargetA", + ParentchainId::TargetB => "TargetB", + }; + write!(f, "{}", message) + } +} + pub trait IdentifyParentchain { fn parentchain_id(&self) -> ParentchainId; } + +pub trait FilterEvents { + type Error: From + core::fmt::Debug; + fn get_extrinsic_statuses(&self) -> core::result::Result, Self::Error>; + + fn get_transfer_events(&self) -> core::result::Result, Self::Error>; +} + +#[derive(Encode, Decode, Debug)] +pub struct ExtrinsicSuccess; + +impl StaticEvent for ExtrinsicSuccess { + const PALLET: &'static str = "System"; + const EVENT: &'static str = "ExtrinsicSuccess"; +} + +#[derive(Encode, Decode)] +pub struct ExtrinsicFailed; + +impl StaticEvent for ExtrinsicFailed { + const PALLET: &'static str = "System"; + const EVENT: &'static str = "ExtrinsicFailed"; +} + +#[derive(Debug)] +pub enum ExtrinsicStatus { + Success, + Failed, +} + +#[derive(Encode, Decode, Debug)] +pub struct BalanceTransfer { + pub from: AccountId, + pub to: AccountId, + pub amount: Balance, +} + +impl core::fmt::Display for BalanceTransfer { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + let message = format!( + "BalanceTransfer :: from: {}, to: {}, amount: {}", + account_id_to_string::(&self.from), + account_id_to_string::(&self.to), + self.amount + ); + write!(f, "{}", message) + } +} + +impl StaticEvent for BalanceTransfer { + const PALLET: &'static str = "Balances"; + const EVENT: &'static str = "Transfer"; +} + +#[derive(Encode, Decode, Debug)] +pub struct AddedSgxEnclave { + pub registered_by: AccountId, + pub worker_url: Option, + pub tcb_status: Option, + pub attestation_method: SgxAttestationMethod, +} + +impl core::fmt::Display for crate::parentchain::AddedSgxEnclave { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + let message = format!( + "AddedSgxEnclave :: from: {}, url: {:?}, status: {:?}, method: {:?}", + account_id_to_string::(&self.registered_by), + self.worker_url, + self.tcb_status, + self.attestation_method + ); + write!(f, "{}", message) + } +} + +impl StaticEvent for crate::parentchain::ProcessedParentchainBlock { + const PALLET: &'static str = "EnclaveBridge"; + const EVENT: &'static str = "ProcessedParentchainBlock"; +} + +#[derive(Encode, Decode, Debug)] +pub struct ProcessedParentchainBlock { + pub shard: ShardIdentifier, + pub block_hash: Hash, + pub trusted_calls_merkle_root: Hash, + pub block_number: BlockNumber, +} + +impl core::fmt::Display for crate::parentchain::ProcessedParentchainBlock { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + let message = format!( + "ProcessedParentchainBlock :: nr {} shard: {}, merkle: {:?}, block hash {:?}", + self.block_number, self.shard, self.trusted_calls_merkle_root, self.block_hash + ); + write!(f, "{}", message) + } +} + +impl StaticEvent for crate::parentchain::AddedSgxEnclave { + const PALLET: &'static str = "EnclaveBridge"; + const EVENT: &'static str = "ProcessedParentchainBlock"; +} + +#[derive(Encode, Decode, Debug)] +pub struct OracleUpdated { + pub oracle_data_name: PalletString, + pub data_source: PalletString, +} + +impl core::fmt::Display for crate::parentchain::OracleUpdated { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + let message = format!( + "OracleUpdated :: data name {:?} source: {:?}", + self.oracle_data_name, self.data_source, + ); + write!(f, "{}", message) + } +} + +impl StaticEvent for crate::parentchain::OracleUpdated { + const PALLET: &'static str = "Teeracle"; + const EVENT: &'static str = "OracleUpdated"; +} + +#[derive(Encode, Decode, Debug)] +pub struct ExchangeRateUpdated { + pub data_source: PalletString, + pub trading_pair: PalletString, + pub exchange_rate: ExchangeRate, +} + +impl core::fmt::Display for crate::parentchain::ExchangeRateUpdated { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + let message = format!( + "OracleUpdated :: source {:?} trading pair: {:?}", + self.data_source, self.trading_pair, + ); + write!(f, "{}", message) + } +} + +impl StaticEvent for crate::parentchain::ExchangeRateUpdated { + const PALLET: &'static str = "Teeracle"; + const EVENT: &'static str = "ExchangeRateUpdated"; +} + +pub trait HandleParentchainEvents +where + Executor: IndirectExecutor, + TCS: PartialEq + Encode + Decode + Debug + Clone + Send + Sync + TrustedCallVerification, +{ + fn handle_events( + executor: &Executor, + events: impl FilterEvents, + vault_account: &AccountId, + ) -> core::result::Result<(), Error>; +} + +#[derive(Debug)] +pub enum ParentchainError { + ShieldFundsFailure, + FunctionalityDisabled, +} + +impl core::fmt::Display for ParentchainError { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + let message = match &self { + ParentchainError::ShieldFundsFailure => "Parentchain Error: ShieldFundsFailure", + ParentchainError::FunctionalityDisabled => "Parentchain Error: FunctionalityDisabled", + }; + write!(f, "{}", message) + } +} + +impl From for () { + fn from(_: ParentchainError) -> Self {} +} + +/// a wrapper to target calls to specific parentchains +#[derive(Encode, Debug, Clone, PartialEq, Eq)] +pub enum ParentchainCall { + Integritee(OpaqueCall), + TargetA(OpaqueCall), + TargetB(OpaqueCall), +} + +impl ParentchainCall { + pub fn as_integritee(&self) -> Option { + if let Self::Integritee(call) = self { + Some(call.clone()) + } else { + None + } + } + pub fn as_target_a(&self) -> Option { + if let Self::TargetA(call) = self { + Some(call.clone()) + } else { + None + } + } + pub fn as_target_b(&self) -> Option { + if let Self::TargetB(call) = self { + Some(call.clone()) + } else { + None + } + } + pub fn as_opaque_call_for(&self, parentchain_id: ParentchainId) -> Option { + match parentchain_id { + ParentchainId::Integritee => + if let Self::Integritee(call) = self { + Some(call.clone()) + } else { + None + }, + ParentchainId::TargetA => + if let Self::TargetA(call) = self { + Some(call.clone()) + } else { + None + }, + ParentchainId::TargetB => + if let Self::TargetB(call) = self { + Some(call.clone()) + } else { + None + }, + } + } +} diff --git a/core-primitives/utils/src/buffer.rs b/core-primitives/utils/src/buffer.rs index 45d5a58d1e..89d02ccc0f 100644 --- a/core-primitives/utils/src/buffer.rs +++ b/core-primitives/utils/src/buffer.rs @@ -20,10 +20,12 @@ use alloc::vec::Vec; /// Fills a given buffer with data and the left over buffer space with white spaces. +/// Throw an error if the buffer size is not enough to hold `data`, +/// return the length of `data` otherwise. pub fn write_slice_and_whitespace_pad( writable: &mut [u8], data: Vec, -) -> Result<(), BufferError> { +) -> Result { if data.len() > writable.len() { return Err(BufferError::InsufficientBufferSize { actual: writable.len(), @@ -34,7 +36,7 @@ pub fn write_slice_and_whitespace_pad( left.clone_from_slice(&data); // fill the right side with whitespace right.iter_mut().for_each(|x| *x = 0x20); - Ok(()) + Ok(data.len()) } #[derive(Debug, PartialEq, Eq, PartialOrd, Ord)] @@ -47,6 +49,15 @@ mod tests { use super::*; use alloc::vec; + #[test] + fn write_slice_and_whitespace_pad_works() { + let mut writable = vec![0; 32]; + let data = vec![1; 30]; + assert_eq!(write_slice_and_whitespace_pad(&mut writable, data), Ok(30)); + assert_eq!(&writable[..30], vec![1; 30]); + assert_eq!(&writable[30..], vec![0x20; 2]); + } + #[test] fn write_slice_and_whitespace_pad_returns_error_if_buffer_too_small() { let mut writable = vec![0; 32]; diff --git a/core-primitives/utils/src/stringify.rs b/core-primitives/utils/src/stringify.rs index 378128891f..7018038ad8 100644 --- a/core-primitives/utils/src/stringify.rs +++ b/core-primitives/utils/src/stringify.rs @@ -28,5 +28,5 @@ pub fn public_to_string(t: &T) -> String { } pub fn account_id_to_string(account: &AccountId) -> String { - format!("{}", HexDisplay::from(&account.encode())) + format!("0x{}", HexDisplay::from(&account.encode())) } diff --git a/core/direct-rpc-server/Cargo.toml b/core/direct-rpc-server/Cargo.toml index 55efae82fd..5b97e40d59 100644 --- a/core/direct-rpc-server/Cargo.toml +++ b/core/direct-rpc-server/Cargo.toml @@ -7,7 +7,6 @@ edition = "2021" [dependencies] # sgx dependencies sgx_tstd = { branch = "master", git = "https://github.com/apache/teaclave-sgx-sdk.git", optional = true, features = ["net", "thread"] } -sgx_types = { branch = "master", git = "https://github.com/apache/teaclave-sgx-sdk.git", optional = true } # no-std dependencies codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive"] } @@ -51,7 +50,6 @@ sgx = [ "itp-rpc/sgx", "jsonrpc-core_sgx", "sgx_tstd", - "sgx_types", "thiserror_sgx", ] mocks = [] diff --git a/core/direct-rpc-server/src/builders/rpc_response_builder.rs b/core/direct-rpc-server/src/builders/rpc_response_builder.rs index 2913ecf38e..9cc85cf369 100644 --- a/core/direct-rpc-server/src/builders/rpc_response_builder.rs +++ b/core/direct-rpc-server/src/builders/rpc_response_builder.rs @@ -16,7 +16,7 @@ */ use crate::builders::rpc_return_value_builder::RpcReturnValueBuilder; -use itp_rpc::{RpcResponse, RpcReturnValue}; +use itp_rpc::{Id, RpcResponse, RpcReturnValue}; use itp_utils::ToHexPrefixed; /// builder pattern for RpcResponse @@ -52,7 +52,7 @@ impl RpcResponseBuilder { #[allow(unused)] pub fn build(self) -> RpcResponse { - let id = self.maybe_id.unwrap_or(1u32); + 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 diff --git a/core/direct-rpc-server/src/rpc_connection_registry.rs b/core/direct-rpc-server/src/rpc_connection_registry.rs index e4586dc29f..1cd485940a 100644 --- a/core/direct-rpc-server/src/rpc_connection_registry.rs +++ b/core/direct-rpc-server/src/rpc_connection_registry.rs @@ -82,6 +82,7 @@ where #[cfg(test)] pub mod tests { use super::*; + use itp_rpc::Id; type TestRegistry = ConnectionRegistry; @@ -119,6 +120,6 @@ pub mod tests { } fn dummy_rpc_response() -> RpcResponse { - RpcResponse { jsonrpc: String::new(), result: Default::default(), id: 1u32 } + RpcResponse { jsonrpc: String::new(), result: Default::default(), id: Id::Number(1u32) } } } diff --git a/core/direct-rpc-server/src/rpc_watch_extractor.rs b/core/direct-rpc-server/src/rpc_watch_extractor.rs index 85654f121c..a117a34b4a 100644 --- a/core/direct-rpc-server/src/rpc_watch_extractor.rs +++ b/core/direct-rpc-server/src/rpc_watch_extractor.rs @@ -80,13 +80,17 @@ pub mod tests { rpc_response_builder::RpcResponseBuilder, rpc_return_value_builder::RpcReturnValueBuilder, }; use codec::Encode; + use itp_rpc::Id; use itp_types::TrustedOperationStatus; #[test] fn invalid_rpc_response_returns_error() { let watch_extractor = RpcWatchExtractor::::new(); - let rpc_response = - RpcResponse { id: 1u32, jsonrpc: String::from("json"), result: "hello".to_string() }; + 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()); } diff --git a/core/offchain-worker-executor/Cargo.toml b/core/offchain-worker-executor/Cargo.toml index 3c94fec598..b346aca46b 100644 --- a/core/offchain-worker-executor/Cargo.toml +++ b/core/offchain-worker-executor/Cargo.toml @@ -10,7 +10,6 @@ edition = "2021" codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive"] } # sgx dependencies sgx_tstd = { branch = "master", git = "https://github.com/apache/teaclave-sgx-sdk.git", optional = true } -sgx_types = { branch = "master", git = "https://github.com/apache/teaclave-sgx-sdk.git" } # sgx enabled external libraries thiserror_sgx = { package = "thiserror", git = "https://github.com/mesalock-linux/thiserror-sgx", tag = "sgx_1.1.3", optional = true } @@ -29,7 +28,6 @@ itp-top-pool-author = { path = "../../core-primitives/top-pool-author", default- itp-types = { path = "../../core-primitives/types", default-features = false } # Substrate dependencies -sp-core = { default-features = false, features = ["full_crypto"], git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } sp-runtime = { default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } # no-std compatible libraries @@ -57,7 +55,7 @@ std = [ "itp-stf-primitives/std", "itp-stf-state-handler/std", "itp-top-pool-author/std", - "sp-core/std", + "itp-types/std", "sp-runtime/std", "thiserror", ] diff --git a/core/offchain-worker-executor/src/executor.rs b/core/offchain-worker-executor/src/executor.rs index ef9a502a8a..5c6d500cf7 100644 --- a/core/offchain-worker-executor/src/executor.rs +++ b/core/offchain-worker-executor/src/executor.rs @@ -28,7 +28,7 @@ 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::{OpaqueCall, ShardIdentifier, H256}; +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}; @@ -114,7 +114,7 @@ impl< let max_duration = Duration::from_secs(5); let latest_parentchain_header = self.get_latest_parentchain_header()?; - let mut parentchain_effects: Vec = Vec::new(); + let mut parentchain_effects: Vec = Vec::new(); let shards = self.state_handler.list_shards()?; trace!("Executing calls on {} shard(s)", shards.len()); @@ -184,10 +184,34 @@ impl< Ok(()) } - fn send_parentchain_effects(&self, parentchain_effects: Vec) -> Result<()> { - let extrinsics = self - .extrinsics_factory - .create_extrinsics(parentchain_effects.as_slice(), None)?; + fn send_parentchain_effects(&self, parentchain_effects: Vec) -> Result<()> { + let integritee_calls: Vec = parentchain_effects + .iter() + .filter_map(|parentchain_call| parentchain_call.as_integritee()) + .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(()) @@ -226,7 +250,7 @@ mod tests { use itp_test::mock::{ handle_state_mock::HandleStateMock, - stf_mock::{mock_top_direct_trusted_call_signed, GetterMock, TrustedCallSignedMock}, + stf_mock::{GetterMock, TrustedCallSignedMock}, }; use itp_top_pool_author::mocks::AuthorApiMock; use itp_types::Block as ParentchainBlock; diff --git a/core/parentchain/block-import-dispatcher/Cargo.toml b/core/parentchain/block-import-dispatcher/Cargo.toml index f5a878a689..64245df42f 100644 --- a/core/parentchain/block-import-dispatcher/Cargo.toml +++ b/core/parentchain/block-import-dispatcher/Cargo.toml @@ -21,7 +21,6 @@ thiserror = { version = "1.0", optional = true } # crates.io no-std compatible libraries log = { version = "0.4", default-features = false } -sp-runtime = { default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } [dev-dependencies] itc-parentchain-block-importer = { path = "../block-importer", features = ["mocks"] } @@ -35,7 +34,6 @@ std = [ "itp-import-queue/std", # no-std compatible libraries "log/std", - "sp-runtime/std", # std-only compatible libraries "thiserror", ] diff --git a/core/parentchain/block-import-dispatcher/src/immediate_dispatcher.rs b/core/parentchain/block-import-dispatcher/src/immediate_dispatcher.rs index 7554a617f2..080f158144 100644 --- a/core/parentchain/block-import-dispatcher/src/immediate_dispatcher.rs +++ b/core/parentchain/block-import-dispatcher/src/immediate_dispatcher.rs @@ -22,7 +22,7 @@ use std::{boxed::Box, vec::Vec}; /// Block import dispatcher that immediately imports the blocks, without any processing or queueing. pub struct ImmediateDispatcher { - block_importer: BlockImporter, + pub block_importer: BlockImporter, import_event_observers: Vec>, } @@ -47,7 +47,14 @@ impl DispatchBlockImport where BlockImporter: ImportParentchainBlocks, { - fn dispatch_import(&self, blocks: Vec, events: Vec>) -> Result<()> { + 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()); @@ -93,7 +100,7 @@ mod tests { counter_clone.increment(); }); - dispatcher.dispatch_import(vec![1u32, 2u32], vec![]).unwrap(); + dispatcher.dispatch_import(vec![1u32, 2u32], vec![], false).unwrap(); assert_eq!(1, notification_counter.get_counter()); } diff --git a/core/parentchain/block-import-dispatcher/src/lib.rs b/core/parentchain/block-import-dispatcher/src/lib.rs index fc4a000178..34e94523d0 100644 --- a/core/parentchain/block-import-dispatcher/src/lib.rs +++ b/core/parentchain/block-import-dispatcher/src/lib.rs @@ -45,7 +45,12 @@ 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>) -> Result<()>; + fn dispatch_import( + &self, + blocks: Vec, + events: Vec>, + immediate_import: bool, + ) -> Result<()>; } /// Wrapper for the actual dispatchers. Allows to define one global type for @@ -96,18 +101,23 @@ where TriggeredDispatcher: DispatchBlockImport, ImmediateDispatcher: DispatchBlockImport, { - fn dispatch_import(&self, blocks: Vec, events: Vec>) -> Result<()> { + fn dispatch_import( + &self, + blocks: Vec, + events: Vec>, + immediate_import: bool, + ) -> Result<()> { match self { BlockImportDispatcher::TriggeredDispatcher(dispatcher) => { - log::info!("TRIGGERED DISPATCHER MATCH"); - dispatcher.dispatch_import(blocks, events) + log::trace!("TRIGGERED DISPATCHER MATCH"); + dispatcher.dispatch_import(blocks, events, immediate_import) }, BlockImportDispatcher::ImmediateDispatcher(dispatcher) => { - log::info!("IMMEDIATE DISPATCHER MATCH"); - dispatcher.dispatch_import(blocks, events) + log::trace!("IMMEDIATE DISPATCHER MATCH"); + dispatcher.dispatch_import(blocks, events, immediate_import) }, BlockImportDispatcher::EmptyDispatcher => { - log::info!("EMPTY DISPATCHER DISPATCHER MATCH"); + log::trace!("EMPTY DISPATCHER DISPATCHER MATCH"); Err(Error::NoDispatcherAssigned) }, } diff --git a/core/parentchain/block-import-dispatcher/src/triggered_dispatcher.rs b/core/parentchain/block-import-dispatcher/src/triggered_dispatcher.rs index 0d335db780..712fcc724d 100644 --- a/core/parentchain/block-import-dispatcher/src/triggered_dispatcher.rs +++ b/core/parentchain/block-import-dispatcher/src/triggered_dispatcher.rs @@ -62,7 +62,7 @@ pub trait TriggerParentchainBlockImport { /// Dispatcher for block imports that retains blocks until the import is triggered, using the /// `TriggerParentchainBlockImport` trait implementation. pub struct TriggeredDispatcher { - block_importer: BlockImporter, + pub block_importer: BlockImporter, import_queue: BlockImportQueue, events_queue: EventsImportQueue, } @@ -100,15 +100,28 @@ where &self, blocks: Vec, events: Vec, + immediate_import: bool, ) -> Result<()> { + let parentchain_id = self.block_importer.parentchain_id(); trace!( - "Pushing parentchain block(s) and event(s) ({}) ({}) to import queue", + "[{:?}] Triggered dispatcher received block(s) and event(s) ({}) ({})", + parentchain_id, blocks.len(), events.len() ); - // Push all the blocks to be dispatched into the queue. - self.events_queue.push_multiple(events).map_err(Error::ImportQueue)?; - self.import_queue.push_multiple(blocks).map_err(Error::ImportQueue) + 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) + } } } @@ -130,9 +143,10 @@ where 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 ({}) ({})", + "[{:?}] Trigger import of all parentchain blocks and events in queue ({}) ({})", + parentchain_id, blocks_to_import.len(), events_to_import.len() ); @@ -147,9 +161,10 @@ where 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 ({}) ({})", + "[{:?}] Trigger import of all parentchain blocks and events, except the latest, from queue ({}) ({})", + parentchain_id, blocks_to_import.len(), events_to_import.len() ); @@ -163,6 +178,7 @@ where &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)?; @@ -172,9 +188,10 @@ where .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", + "[{:?}] 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(), ); @@ -190,16 +207,20 @@ where &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)", + "[{:?}] 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)", + "[{:?}] 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) @@ -223,7 +244,11 @@ mod tests { let dispatcher = test_fixtures(); dispatcher - .dispatch_import(vec![1, 2, 3, 4, 5], vec![vec![1], vec![2], vec![3], vec![4], vec![5]]) + .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()); @@ -239,10 +264,14 @@ mod tests { let dispatcher = test_fixtures(); dispatcher - .dispatch_import(vec![1, 2, 3, 4, 5], vec![vec![1], vec![2], vec![3], vec![4], vec![5]]) + .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]]) + .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()); @@ -257,7 +286,7 @@ mod tests { fn triggering_import_all_empties_queue() { let dispatcher = test_fixtures(); - dispatcher.dispatch_import(vec![1, 2, 3, 4, 5], vec![]).unwrap(); + 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); @@ -269,7 +298,7 @@ mod tests { fn triggering_import_all_on_empty_queue_imports_none() { let dispatcher = test_fixtures(); - dispatcher.dispatch_import(vec![], vec![]).unwrap(); + dispatcher.dispatch_import(vec![], vec![], false).unwrap(); let maybe_latest_imported = dispatcher.import_all().unwrap(); assert!(maybe_latest_imported.is_none()); @@ -286,7 +315,11 @@ mod tests { let dispatcher = test_fixtures(); dispatcher - .dispatch_import(vec![1, 2, 3, 4, 5], vec![vec![1], vec![2], vec![3], vec![4], vec![5]]) + .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(); @@ -302,7 +335,11 @@ mod tests { let dispatcher = test_fixtures(); dispatcher - .dispatch_import(vec![1, 2, 3, 4, 5], vec![vec![1], vec![2], vec![3], vec![4], vec![5]]) + .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(); @@ -319,7 +356,7 @@ mod tests { fn trigger_import_all_but_latest_works() { let dispatcher = test_fixtures(); - dispatcher.dispatch_import(vec![1, 2, 3, 4, 5], vec![]).unwrap(); + 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]); diff --git a/core/parentchain/block-importer/Cargo.toml b/core/parentchain/block-importer/Cargo.toml index 1064ea58d4..be6b1c93c4 100644 --- a/core/parentchain/block-importer/Cargo.toml +++ b/core/parentchain/block-importer/Cargo.toml @@ -14,8 +14,8 @@ ita-stf = { path = "../../../app-libs/stf", default-features = false } itc-parentchain-indirect-calls-executor = { path = "../indirect-calls-executor", default-features = false } itc-parentchain-light-client = { path = "../light-client", default-features = false } itp-extrinsics-factory = { path = "../../../core-primitives/extrinsics-factory", default-features = false } -itp-settings = { path = "../../../core-primitives/settings" } itp-stf-executor = { path = "../../../core-primitives/stf-executor", default-features = false } +itp-stf-interface = { path = "../../../core-primitives/stf-interface", default-features = false } itp-types = { path = "../../../core-primitives/types", default-features = false } # sgx enabled external libraries @@ -38,6 +38,7 @@ std = [ "itc-parentchain-light-client/std", "itp-extrinsics-factory/std", "itp-stf-executor/std", + "itp-stf-interface/std", "itp-types/std", # no-std compatible libraries "codec/std", diff --git a/core/parentchain/block-importer/src/block_importer.rs b/core/parentchain/block-importer/src/block_importer.rs index 008ed65b82..becb9e9a6b 100644 --- a/core/parentchain/block-importer/src/block_importer.rs +++ b/core/parentchain/block-importer/src/block_importer.rs @@ -18,6 +18,7 @@ //! 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::{ @@ -25,6 +26,7 @@ use itc_parentchain_light_client::{ }; use itp_extrinsics_factory::CreateExtrinsics; use itp_stf_executor::traits::StfUpdateState; +use itp_stf_interface::ShardCreationInfo; use itp_types::{ parentchain::{IdentifyParentchain, ParentchainId}, OpaqueCall, H256, @@ -32,9 +34,9 @@ use itp_types::{ use log::*; use sp_runtime::{ generic::SignedBlock as SignedBlockG, - traits::{Block as ParentchainBlockTrait, NumberFor}, + traits::{Block as ParentchainBlockTrait, Header as HeaderT, NumberFor}, }; -use std::{marker::PhantomData, sync::Arc, vec::Vec}; +use std::{marker::PhantomData, sync::Arc, vec, vec::Vec}; /// Parentchain block import implementation. pub struct ParentchainBlockImporter< @@ -44,10 +46,12 @@ pub struct ParentchainBlockImporter< ExtrinsicsFactory, IndirectCallsExecutor, > { - validator_accessor: Arc, + pub validator_accessor: Arc, stf_executor: Arc, extrinsics_factory: Arc, - indirect_calls_executor: Arc, + pub indirect_calls_executor: Arc, + shard_creation_info: ShardCreationInfo, + pub parentchain_id: ParentchainId, _phantom: PhantomData, } @@ -71,12 +75,16 @@ impl< stf_executor: Arc, extrinsics_factory: Arc, indirect_calls_executor: Arc, + shard_creation_info: ShardCreationInfo, + parentchain_id: ParentchainId, ) -> Self { ParentchainBlockImporter { validator_accessor, stf_executor, extrinsics_factory, indirect_calls_executor, + shard_creation_info, + parentchain_id, _phantom: Default::default(), } } @@ -113,18 +121,40 @@ impl< let mut calls = Vec::::new(); let id = self.validator_accessor.parentchain_id(); - debug!("[{:?}] Import blocks to light-client!", 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.into_iter()) + blocks_to_import.into_iter().zip(events_to_import_aligned.into_iter()) { if let Err(e) = self .validator_accessor .execute_mut_on_validator(|v| v.submit_block(&signed_block)) { - error!("[{:?}] Header submission to light client failed: {:?}", id, e); + 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 @@ -141,10 +171,11 @@ impl< .indirect_calls_executor .execute_indirect_calls_in_extrinsics(&block, &raw_events) { - Ok(executed_shielding_calls) => { - calls.push(executed_shielding_calls); + Ok(Some(confirm_processed_parentchain_block_call)) => { + calls.push(confirm_processed_parentchain_block_call); }, - Err(_) => error!("[{:?}] Error executing relevant extrinsics", id), + Ok(None) => trace!("omitting confirmation call to non-integritee parentchain"), + Err(e) => error!("[{:?}] Error executing relevant extrinsics: {:?}", id, e), }; info!( @@ -165,4 +196,8 @@ impl< Ok(()) } + + fn parentchain_id(&self) -> ParentchainId { + self.validator_accessor.parentchain_id() + } } diff --git a/core/parentchain/block-importer/src/block_importer_mock.rs b/core/parentchain/block-importer/src/block_importer_mock.rs index 5308ef4e71..2f1da14500 100644 --- a/core/parentchain/block-importer/src/block_importer_mock.rs +++ b/core/parentchain/block-importer/src/block_importer_mock.rs @@ -21,6 +21,7 @@ use crate::{ error::{Error, Result}, ImportParentchainBlocks, }; +use itp_types::parentchain::ParentchainId; use std::{sync::RwLock, vec::Vec}; /// Mock implementation for the block importer. @@ -58,4 +59,7 @@ where imported_blocks_lock.extend(blocks_to_import); Ok(()) } + fn parentchain_id(&self) -> ParentchainId { + ParentchainId::Integritee + } } diff --git a/core/parentchain/block-importer/src/lib.rs b/core/parentchain/block-importer/src/lib.rs index 98ecb2e6a0..3f2fd695bc 100644 --- a/core/parentchain/block-importer/src/lib.rs +++ b/core/parentchain/block-importer/src/lib.rs @@ -39,6 +39,7 @@ 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. @@ -55,4 +56,6 @@ pub trait ImportParentchainBlocks { blocks_to_import: Vec, events_to_import: Vec>, ) -> Result<()>; + + fn parentchain_id(&self) -> ParentchainId; } diff --git a/core/parentchain/indirect-calls-executor/Cargo.toml b/core/parentchain/indirect-calls-executor/Cargo.toml index bc37518757..0a1ec92234 100644 --- a/core/parentchain/indirect-calls-executor/Cargo.toml +++ b/core/parentchain/indirect-calls-executor/Cargo.toml @@ -10,17 +10,15 @@ sgx_tstd = { branch = "master", git = "https://github.com/apache/teaclave-sgx-sd sgx_types = { branch = "master", git = "https://github.com/apache/teaclave-sgx-sdk.git" } # local dependencies -ita-stf = { path = "../../../app-libs/stf", default-features = false } itp-api-client-types = { path = "../../../core-primitives/node-api/api-client-types", default-features = false } itp-node-api = { path = "../../../core-primitives/node-api", default-features = false } -itp-ocall-api = { path = "../../../core-primitives/ocall-api", default-features = false } itp-sgx-crypto = { path = "../../../core-primitives/sgx/crypto", default-features = false } itp-sgx-runtime-primitives = { path = "../../../core-primitives/sgx-runtime-primitives", default-features = false } itp-stf-executor = { path = "../../../core-primitives/stf-executor", default-features = false } itp-stf-primitives = { path = "../../../core-primitives/stf-primitives", default-features = false } +itp-test = { path = "../../../core-primitives/test", default-features = false } itp-top-pool-author = { path = "../../../core-primitives/top-pool-author", default-features = false } itp-types = { path = "../../../core-primitives/types", default-features = false } -itp-utils = { path = "../../../core-primitives/utils", default-features = false } # sgx enabled external libraries futures_sgx = { package = "futures", git = "https://github.com/mesalock-linux/futures-rs-sgx", optional = true } @@ -55,13 +53,12 @@ std = [ "bs58/std", "codec/std", "futures", - "ita-stf/std", "itp-node-api/std", - "itp-ocall-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", @@ -74,10 +71,10 @@ std = [ sgx = [ "sgx_tstd", "futures_sgx", - "ita-stf/sgx", "itp-node-api/sgx", "itp-sgx-crypto/sgx", "itp-stf-executor/sgx", "itp-top-pool-author/sgx", + "itp-test/sgx", "thiserror_sgx", ] diff --git a/core/parentchain/indirect-calls-executor/src/error.rs b/core/parentchain/indirect-calls-executor/src/error.rs index 6a5b04161f..624138f634 100644 --- a/core/parentchain/indirect-calls-executor/src/error.rs +++ b/core/parentchain/indirect-calls-executor/src/error.rs @@ -18,6 +18,7 @@ #[cfg(all(not(feature = "std"), feature = "sgx"))] use crate::sgx_reexport_prelude::*; +use itp_types::parentchain::ParentchainError; use sgx_types::sgx_status_t; use std::{boxed::Box, format}; @@ -40,6 +41,12 @@ pub enum Error { Other(#[from] Box), } +impl From for Error { + fn from(e: ParentchainError) -> Self { + Self::Other(format!("{:?}", e).into()) + } +} + impl From for Error { fn from(sgx_status: sgx_status_t) -> Self { Self::Sgx(sgx_status) diff --git a/core/parentchain/indirect-calls-executor/src/event_filter.rs b/core/parentchain/indirect-calls-executor/src/event_filter.rs index 3209b07ece..ffb9882f58 100644 --- a/core/parentchain/indirect-calls-executor/src/event_filter.rs +++ b/core/parentchain/indirect-calls-executor/src/event_filter.rs @@ -16,121 +16,18 @@ */ //! Various way to filter Parentchain events -use crate::error::Result; -use codec::{Decode, Encode}; -use itp_api_client_types::{Events, StaticEvent}; -use itp_sgx_runtime_primitives::types::{AccountId, Balance}; -use itp_types::H256; -use itp_utils::stringify::account_id_to_string; -use std::{fmt::Display, format, vec::Vec}; +use crate::error::Error; -#[derive(Encode, Decode, Debug)] -pub struct ExtrinsicSuccess; +use itp_stf_primitives::error::StfError; -impl StaticEvent for ExtrinsicSuccess { - const PALLET: &'static str = "System"; - const EVENT: &'static str = "ExtrinsicSuccess"; -} - -#[derive(Encode, Decode)] -pub struct ExtrinsicFailed; - -impl StaticEvent for ExtrinsicFailed { - const PALLET: &'static str = "System"; - const EVENT: &'static str = "ExtrinsicFailed"; -} - -#[derive(Debug)] -pub enum ExtrinsicStatus { - Success, - Failed, -} - -#[derive(Encode, Decode, Debug)] -pub struct BalanceTransfer { - pub from: AccountId, - pub to: AccountId, - pub amount: Balance, -} - -impl StaticEvent for BalanceTransfer { - const PALLET: &'static str = "Balances"; - const EVENT: &'static str = "Transfer"; -} - -impl Display for BalanceTransfer { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - let message = format!( - "BalanceTransfer :: from: {}, to: {}, amount: {}", - account_id_to_string::(&self.from), - account_id_to_string::(&self.to), - self.amount - ); - write!(f, "{}", message) - } -} - -pub trait FilterEvents { - fn get_extrinsic_statuses(&self) -> Result>; - - fn get_transfer_events(&self) -> Result>; -} - -impl FilterEvents for Events { - fn get_extrinsic_statuses(&self) -> Result> { - Ok(self - .iter() - .filter_map(|ev| { - ev.and_then(|ev| { - if (ev.as_event::()?).is_some() { - return Ok(Some(ExtrinsicStatus::Success)) - } - - if (ev.as_event::()?).is_some() { - return Ok(Some(ExtrinsicStatus::Failed)) - } +use std::format; - Ok(None) - }) - .ok() - .flatten() - }) - .collect()) - } - - fn get_transfer_events(&self) -> Result> { - Ok(self - .iter() - .flatten() // flatten filters out the nones - .filter_map(|ev| match ev.as_event::() { - Ok(maybe_event) => { - if maybe_event.is_none() { - log::warn!("Transfer event does not exist in parentchain metadata"); - }; - maybe_event - }, - Err(e) => { - log::error!("Could not decode event: {:?}", e); - None - }, - }) - .collect()) +impl From for Error { + fn from(a: StfError) -> Self { + Error::Other(format!("Error when shielding for privacy sidechain {:?}", a).into()) } } -pub struct MockEvents; - -impl FilterEvents for MockEvents { - fn get_extrinsic_statuses(&self) -> Result> { - Ok(Vec::from([ExtrinsicStatus::Success])) - } - - fn get_transfer_events(&self) -> Result> { - let transfer = BalanceTransfer { - to: [0u8; 32].into(), - from: [0u8; 32].into(), - amount: Balance::default(), - }; - Ok(Vec::from([transfer])) - } +pub trait ToEvents { + fn to_events(&self) -> &E; } diff --git a/core/parentchain/indirect-calls-executor/src/executor.rs b/core/parentchain/indirect-calls-executor/src/executor.rs index aff9dbc454..23e94baf65 100644 --- a/core/parentchain/indirect-calls-executor/src/executor.rs +++ b/core/parentchain/indirect-calls-executor/src/executor.rs @@ -21,23 +21,28 @@ use crate::sgx_reexport_prelude::*; use crate::{ error::{Error, Result}, - event_filter::{ExtrinsicStatus, FilterEvents}, filter_metadata::{EventsFromMetadata, FilterIntoDataFrom}, - traits::{ExecuteIndirectCalls, IndirectDispatch, IndirectExecutor}, + traits::{ExecuteIndirectCalls, IndirectDispatch}, }; +use alloc::format; use binary_merkle_tree::merkle_root; -use codec::Encode; +use codec::{Decode, Encode}; use core::marker::PhantomData; -use ita_stf::{Getter, TrustedCall, TrustedCallSigned}; use itp_node_api::metadata::{ pallet_enclave_bridge::EnclaveBridgeCallIndexes, provider::AccessNodeMetadata, NodeMetadataTrait, }; use itp_sgx_crypto::{key_repository::AccessKey, ShieldingCryptoDecrypt, ShieldingCryptoEncrypt}; -use itp_stf_executor::traits::StfEnclaveSigning; -use itp_stf_primitives::types::AccountId; +use itp_stf_executor::traits::{StfEnclaveSigning, StfShardVaultQuery}; +use itp_stf_primitives::{ + traits::{IndirectExecutor, TrustedCallSigning, TrustedCallVerification}, + types::AccountId, +}; use itp_top_pool_author::traits::AuthorApi; -use itp_types::{OpaqueCall, ShardIdentifier, H256}; +use itp_types::{ + parentchain::{ExtrinsicStatus, FilterEvents, HandleParentchainEvents, ParentchainId}, + OpaqueCall, ShardIdentifier, H256, +}; use log::*; use sp_core::blake2_256; use sp_runtime::traits::{Block as ParentchainBlockTrait, Header, Keccak256}; @@ -50,12 +55,16 @@ pub struct IndirectCallsExecutor< NodeMetadataProvider, IndirectCallsFilter, EventCreator, + ParentchainEventHandler, + TCS, + G, > { pub(crate) shielding_key_repo: Arc, - pub(crate) stf_enclave_signer: Arc, + pub stf_enclave_signer: Arc, pub(crate) top_pool_author: Arc, pub(crate) node_meta_data_provider: Arc, - _phantom: PhantomData<(IndirectCallsFilter, EventCreator)>, + pub parentchain_id: ParentchainId, + _phantom: PhantomData<(IndirectCallsFilter, EventCreator, ParentchainEventHandler, TCS, G)>, } impl< ShieldingKeyRepository, @@ -64,6 +73,9 @@ impl< NodeMetadataProvider, IndirectCallsFilter, EventCreator, + ParentchainEventHandler, + TCS, + G, > IndirectCallsExecutor< ShieldingKeyRepository, @@ -72,6 +84,9 @@ impl< NodeMetadataProvider, IndirectCallsFilter, EventCreator, + ParentchainEventHandler, + TCS, + G, > { pub fn new( @@ -79,12 +94,14 @@ impl< stf_enclave_signer: Arc, top_pool_author: Arc, node_meta_data_provider: Arc, + parentchain_id: ParentchainId, ) -> Self { IndirectCallsExecutor { shielding_key_repo, stf_enclave_signer, top_pool_author, node_meta_data_provider, + parentchain_id, _phantom: Default::default(), } } @@ -97,6 +114,9 @@ impl< NodeMetadataProvider, FilterIndirectCalls, EventCreator, + ParentchainEventHandler, + TCS, + G, > ExecuteIndirectCalls for IndirectCallsExecutor< ShieldingKeyRepository, @@ -105,23 +125,29 @@ impl< NodeMetadataProvider, FilterIndirectCalls, EventCreator, + ParentchainEventHandler, + TCS, + G, > where ShieldingKeyRepository: AccessKey, ::KeyType: ShieldingCryptoDecrypt + ShieldingCryptoEncrypt, - StfEnclaveSigner: StfEnclaveSigning, - TopPoolAuthor: AuthorApi + Send + Sync + 'static, + StfEnclaveSigner: StfEnclaveSigning + StfShardVaultQuery, + TopPoolAuthor: AuthorApi + Send + Sync + 'static, NodeMetadataProvider: AccessNodeMetadata, FilterIndirectCalls: FilterIntoDataFrom, NodeMetadataProvider::MetadataType: NodeMetadataTrait + Clone, - FilterIndirectCalls::Output: IndirectDispatch + Encode + Debug, + FilterIndirectCalls::Output: IndirectDispatch + Encode + Debug, EventCreator: EventsFromMetadata, + ParentchainEventHandler: HandleParentchainEvents, + TCS: PartialEq + Encode + Decode + Debug + Clone + Send + Sync + TrustedCallVerification, + G: PartialEq + Encode + Decode + Debug + Clone + Send + Sync, { fn execute_indirect_calls_in_extrinsics( &self, block: &ParentchainBlock, events: &[u8], - ) -> Result + ) -> Result> where ParentchainBlock: ParentchainBlockTrait, { @@ -138,13 +164,14 @@ impl< })? .ok_or_else(|| Error::Other("Could not create events from metadata".into()))?; - let xt_statuses = events.get_extrinsic_statuses()?; + let xt_statuses = events.get_extrinsic_statuses().map_err(|e| { + Error::Other(format!("Error when shielding for privacy sidechain {:?}", e).into()) + })?; trace!("xt_statuses:: {:?}", xt_statuses); - let filter_events = events.get_transfer_events(); - - if let Ok(events) = filter_events { - events.iter().for_each(|event| info!("Found transfer_event: {:?}", event)) + let shard = self.get_default_shard(); + if let Ok((vault, _parentchain_id)) = self.stf_enclave_signer.get_shard_vault(&shard) { + ParentchainEventHandler::handle_events(self, events, &vault)?; } // This would be catastrophic but should never happen @@ -176,12 +203,17 @@ impl< } } debug!("successfully processed {} indirect invocations", executed_calls.len()); - // Include a processed parentchain block confirmation for each block. - self.create_processed_parentchain_block_call::( - block_hash, - executed_calls, - block_number, - ) + if self.parentchain_id == ParentchainId::Integritee { + // Include a processed parentchain block confirmation for each block. + Ok(Some(self.create_processed_parentchain_block_call::( + block_hash, + executed_calls, + 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( @@ -214,7 +246,10 @@ impl< NodeMetadataProvider, FilterIndirectCalls, EventFilter, - > IndirectExecutor + PrivacySidechain, + TCS, + G, + > IndirectExecutor for IndirectCallsExecutor< ShieldingKeyRepository, StfEnclaveSigner, @@ -222,12 +257,17 @@ impl< NodeMetadataProvider, FilterIndirectCalls, EventFilter, + PrivacySidechain, + TCS, + G, > where ShieldingKeyRepository: AccessKey, ::KeyType: ShieldingCryptoDecrypt + ShieldingCryptoEncrypt, - StfEnclaveSigner: StfEnclaveSigning, - TopPoolAuthor: AuthorApi + Send + Sync + 'static, + StfEnclaveSigner: StfEnclaveSigning + StfShardVaultQuery, + TopPoolAuthor: AuthorApi + Send + Sync + 'static, + TCS: PartialEq + Encode + Decode + Debug + Clone + Send + Sync + TrustedCallVerification, + G: PartialEq + Encode + Decode + Debug + Clone + Send + Sync, { fn submit_trusted_call(&self, shard: ShardIdentifier, encrypted_trusted_call: Vec) { if let Err(e) = futures::executor::block_on( @@ -255,11 +295,11 @@ impl< self.top_pool_author.list_handled_shards().first().copied().unwrap_or_default() } - fn sign_call_with_self( + fn sign_call_with_self>( &self, - trusted_call: &TrustedCall, + trusted_call: &TC, shard: &ShardIdentifier, - ) -> Result { + ) -> Result { Ok(self.stf_enclave_signer.sign_call_with_self(trusted_call, shard)?) } } @@ -271,10 +311,7 @@ pub(crate) fn hash_of(xt: &T) -> H256 { #[cfg(test)] mod test { use super::*; - use crate::{ - filter_metadata::{ShieldFundsAndInvokeFilter, TestEventCreator}, - parentchain_parser::ParentchainExtrinsicParser, - }; + use crate::mock::*; use codec::{Decode, Encode}; use itc_parentchain_test::ParentchainBlockBuilder; use itp_node_api::{ @@ -290,7 +327,10 @@ mod test { traits::TrustedCallVerification, types::{AccountId, TrustedOperation}, }; - use itp_test::mock::shielding_crypto_mock::ShieldingCryptoMock; + use itp_test::mock::{ + shielding_crypto_mock::ShieldingCryptoMock, + stf_mock::{GetterMock, TrustedCallSignedMock}, + }; use itp_top_pool_author::mocks::AuthorApiMock; use itp_types::{ parentchain::Address, Block, CallWorkerFn, Request, ShardIdentifier, ShieldFundsFn, @@ -301,18 +341,22 @@ mod test { type TestShieldingKeyRepo = KeyRepositoryMock; type TestStfEnclaveSigner = StfEnclaveSignerMock; - type TestTopPoolAuthor = AuthorApiMock; + type TestTopPoolAuthor = AuthorApiMock; type TestNodeMetadataRepository = NodeMetadataRepository; type TestIndirectCallExecutor = IndirectCallsExecutor< TestShieldingKeyRepo, TestStfEnclaveSigner, TestTopPoolAuthor, TestNodeMetadataRepository, - ShieldFundsAndInvokeFilter, + MockExtrinsicFilter, TestEventCreator, + MockParentchainEventHandler, + TrustedCallSignedMock, + GetterMock, >; type Seed = [u8; 32]; + const TEST_SEED: Seed = *b"12345678901234567890123456789012"; #[test] @@ -362,7 +406,7 @@ mod test { let submitted_extrinsic = top_pool_author.pending_tops(shard_id()).unwrap().first().cloned().unwrap(); let decrypted_extrinsic = shielding_key.decrypt(&submitted_extrinsic).unwrap(); - let decoded_operation = TrustedOperation::::decode( + let decoded_operation = TrustedOperation::::decode( &mut decrypted_extrinsic.as_slice(), ) .unwrap(); @@ -471,6 +515,7 @@ mod test { ParentchainAdditionalParams::default(), ) } + fn test_fixtures( mr_enclave: [u8; 32], metadata: NodeMetadataMock, @@ -485,6 +530,7 @@ mod test { stf_enclave_signer, top_pool_author.clone(), node_metadata_repo, + ParentchainId::Integritee, ); (executor, top_pool_author, shielding_key_repo) diff --git a/core/parentchain/indirect-calls-executor/src/filter_metadata.rs b/core/parentchain/indirect-calls-executor/src/filter_metadata.rs index 410432516b..5dea343f67 100644 --- a/core/parentchain/indirect-calls-executor/src/filter_metadata.rs +++ b/core/parentchain/indirect-calls-executor/src/filter_metadata.rs @@ -15,23 +15,13 @@ */ -use crate::{ - error::Result, - event_filter::{FilterEvents, MockEvents}, - indirect_calls::{ - InvokeArgs, ShieldFundsArgs, TransferToAliceShieldsFundsArgs, ALICE_ACCOUNT_ID, - }, - parentchain_parser::ParseExtrinsic, - IndirectDispatch, IndirectExecutor, -}; +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::{ - pallet_balances::BalancesCallIndexes, NodeMetadata, NodeMetadataTrait, -}; -use itp_types::H256; -use log::trace; +use itp_node_api::metadata::NodeMetadata; +use itp_stf_primitives::traits::IndirectExecutor; +use itp_types::{parentchain::FilterEvents, H256}; pub trait EventsFromMetadata { type Output: FilterEvents; @@ -43,10 +33,16 @@ pub trait EventsFromMetadata { ) -> Option; } -pub struct EventCreator; +pub struct EventCreator { + _phantom: PhantomData, +} -impl + Clone> EventsFromMetadata for EventCreator { - type Output = Events; +impl + Clone, FilterableEvents> EventsFromMetadata + for EventCreator +where + FilterableEvents: From> + FilterEvents, +{ + type Output = FilterableEvents; fn create_from_metadata( metadata: NodeMetadata, @@ -54,21 +50,7 @@ impl + Clone> EventsFromMetadata f events: &[u8], ) -> Option { let raw_metadata: Metadata = metadata.try_into().ok()?; - Some(Events::::new(raw_metadata, block_hash, events.to_vec())) - } -} - -pub struct TestEventCreator; - -impl EventsFromMetadata for TestEventCreator { - type Output = MockEvents; - - fn create_from_metadata( - _metadata: NodeMetadata, - _block_hash: H256, - _events: &[u8], - ) -> Option { - Some(MockEvents) + Some(Events::::new(raw_metadata, block_hash, events.to_vec()).into()) } } @@ -91,145 +73,11 @@ pub trait FilterIntoDataFrom { /// Indirect calls filter denying all indirect calls. pub struct DenyAll; -/// Simple demo filter for testing. -/// -/// A transfer to Alice will issue the corresponding balance to Alice in the enclave. -/// It does not do anything else. -pub struct TransferToAliceShieldsFundsFilter { - _phantom: PhantomData, -} -/// Default filter we use for the Integritee-Parachain. -pub struct ShieldFundsAndInvokeFilter { - _phantom: PhantomData, -} - -impl FilterIntoDataFrom - for ShieldFundsAndInvokeFilter -where - ExtrinsicParser: ParseExtrinsic, -{ - type Output = IndirectCall; - type ParseParentchainMetadata = ExtrinsicParser; - - fn filter_into_from_metadata( - encoded_data: &[u8], - metadata: &NodeMetadata, - ) -> Option { - let call_mut = &mut &encoded_data[..]; - - // Todo: the filter should not need to parse, only filter. This should directly be configured - // in the indirect executor. - let xt = match Self::ParseParentchainMetadata::parse(call_mut) { - Ok(xt) => xt, - Err(e) => { - log::error!( - "[ShieldFundsAndInvokeFilter] Could not parse parentchain extrinsic: {:?}", - e - ); - return None - }, - }; - let index = xt.call_index; - let call_args = &mut &xt.call_args[..]; - log::trace!( - "[ShieldFundsAndInvokeFilter] attempting to execute indirect call with index {:?}", - index - ); - if index == metadata.shield_funds_call_indexes().ok()? { - log::debug!("executing shield funds call"); - let args = decode_and_log_error::(call_args)?; - Some(IndirectCall::ShieldFunds(args)) - } else if index == metadata.invoke_call_indexes().ok()? { - log::debug!("executing invoke call"); - let args = decode_and_log_error::(call_args)?; - Some(IndirectCall::Invoke(args)) - } else { - None - } - } -} - -impl FilterIntoDataFrom - for TransferToAliceShieldsFundsFilter -where - ExtrinsicParser: ParseExtrinsic, -{ - type Output = IndirectCall; - type ParseParentchainMetadata = ExtrinsicParser; - - fn filter_into_from_metadata( - encoded_data: &[u8], - metadata: &NodeMetadata, - ) -> Option { - let call_mut = &mut &encoded_data[..]; - - // Todo: the filter should not need to parse, only filter. This should directly be configured - // in the indirect executor. - let xt = match Self::ParseParentchainMetadata::parse(call_mut) { - Ok(xt) => xt, - Err(e) => { - log::error!("[TransferToAliceShieldsFundsFilter] Could not parse parentchain extrinsic: {:?}", e); - return None - }, - }; - let index = xt.call_index; - let call_args = &mut &xt.call_args[..]; - log::trace!("[TransferToAliceShieldsFundsFilter] attempting to execute indirect call with index {:?}", index); - if index == metadata.transfer_call_indexes().ok()? - || index == metadata.transfer_keep_alive_call_indexes().ok()? - || index == metadata.transfer_allow_death_call_indexes().ok()? - { - log::debug!( - "found `transfer` or `transfer_allow_death` or `transfer_keep_alive` call." - ); - let args = decode_and_log_error::(call_args)?; - if args.destination == ALICE_ACCOUNT_ID.into() { - Some(IndirectCall::TransferToAliceShieldsFunds(args)) - } else { - log::debug!("Parentchain transfer was not for Alice; ignoring..."); - // No need to put it into the top pool if it isn't executed in the first place. - None - } - } else { - None - } - } -} - -/// The default indirect call of the Integritee-Parachain. -/// -/// Todo: Move or provide a template in app-libs such that users -/// can implemeent their own indirect call there. -#[derive(Debug, Clone, Encode, Decode, Eq, PartialEq)] -pub enum IndirectCall { - ShieldFunds(ShieldFundsArgs), - Invoke(InvokeArgs), - TransferToAliceShieldsFunds(TransferToAliceShieldsFundsArgs), -} - -impl IndirectDispatch for IndirectCall { - fn dispatch(&self, executor: &Executor) -> Result<()> { - trace!("dispatching indirect call {:?}", self); - match self { - IndirectCall::ShieldFunds(shieldfunds_args) => shieldfunds_args.dispatch(executor), - IndirectCall::Invoke(invoke_args) => invoke_args.dispatch(executor), - IndirectCall::TransferToAliceShieldsFunds(args) => args.dispatch(executor), - } - } -} - -fn decode_and_log_error(encoded: &mut &[u8]) -> Option { - match V::decode(encoded) { - Ok(v) => Some(v), - Err(e) => { - log::warn!("Could not decode. {:?}", e); - None - }, - } -} - mod seal { use super::*; + use crate::Error; + use core::fmt::Debug; + use itp_stf_primitives::traits::TrustedCallVerification; /// Stub struct for the `DenyAll` filter that never executes anything. #[derive(Debug, Encode)] @@ -244,7 +92,10 @@ mod seal { } } - impl IndirectDispatch for CantExecute { + impl, TCS> IndirectDispatch for CantExecute + where + TCS: PartialEq + Encode + Decode + Debug + Clone + Send + Sync + TrustedCallVerification, + { fn dispatch(&self, _: &Executor) -> 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. diff --git a/core/parentchain/indirect-calls-executor/src/lib.rs b/core/parentchain/indirect-calls-executor/src/lib.rs index bd7935a898..57b0911e87 100644 --- a/core/parentchain/indirect-calls-executor/src/lib.rs +++ b/core/parentchain/indirect-calls-executor/src/lib.rs @@ -27,6 +27,8 @@ #[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; @@ -37,15 +39,14 @@ pub mod sgx_reexport_prelude { pub use thiserror_sgx as thiserror; } -mod event_filter; mod executor; -mod traits; +pub mod mock; +pub mod traits; pub mod error; +pub mod event_filter; pub mod filter_metadata; -pub mod indirect_calls; -pub mod parentchain_parser; pub use error::{Error, Result}; pub use executor::IndirectCallsExecutor; -pub use traits::{ExecuteIndirectCalls, IndirectDispatch, IndirectExecutor}; +pub use traits::{ExecuteIndirectCalls, IndirectDispatch}; diff --git a/core/parentchain/indirect-calls-executor/src/mock.rs b/core/parentchain/indirect-calls-executor/src/mock.rs new file mode 100644 index 0000000000..bb7ad5a8db --- /dev/null +++ b/core/parentchain/indirect-calls-executor/src/mock.rs @@ -0,0 +1,242 @@ +use crate::{ + error::{Error, Result as ICResult}, + filter_metadata::{EventsFromMetadata, FilterIntoDataFrom}, + IndirectDispatch, +}; +use codec::{Decode, Encode}; +use core::marker::PhantomData; + +use itp_node_api::{ + api_client::{CallIndex, PairSignature, UncheckedExtrinsicV4}, + metadata::NodeMetadataTrait, +}; +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::{BalanceTransfer, ExtrinsicStatus, FilterEvents, HandleParentchainEvents}, + Address, Request, ShardIdentifier, H256, +}; +use log::*; +use std::vec::Vec; + +/// Default filter we use for the Integritee-Parachain. +pub struct MockExtrinsicFilter { + _phantom: PhantomData, +} + +impl FilterIntoDataFrom + for MockExtrinsicFilter +where + ExtrinsicParser: ParseExtrinsic, +{ + type Output = IndirectCall; + type ParseParentchainMetadata = ExtrinsicParser; + + fn filter_into_from_metadata( + encoded_data: &[u8], + metadata: &NodeMetadata, + ) -> Option { + let call_mut = &mut &encoded_data[..]; + + // Todo: the filter should not need to parse, only filter. This should directly be configured + // in the indirect executor. + let xt = match Self::ParseParentchainMetadata::parse(call_mut) { + Ok(xt) => xt, + Err(e) => { + log::error!( + "[ShieldFundsAndInvokeFilter] Could not parse parentchain extrinsic: {:?}", + e + ); + return None + }, + }; + let index = xt.call_index; + let call_args = &mut &xt.call_args[..]; + log::trace!( + "[ShieldFundsAndInvokeFilter] attempting to execute indirect call with index {:?}", + index + ); + if index == metadata.shield_funds_call_indexes().ok()? { + log::debug!("executing shield funds call"); + let args = ShieldFundsArgs::decode(call_args).unwrap(); + Some(IndirectCall::ShieldFunds(args)) + } else if index == metadata.invoke_call_indexes().ok()? { + log::debug!("executing invoke call"); + let args = InvokeArgs::decode(call_args).unwrap(); + Some(IndirectCall::Invoke(args)) + } else { + None + } + } +} +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> + IndirectDispatch for IndirectCall +{ + fn dispatch(&self, executor: &Executor) -> ICResult<()> { + trace!("dispatching indirect call {:?}", self); + match self { + IndirectCall::ShieldFunds(shieldfunds_args) => shieldfunds_args.dispatch(executor), + IndirectCall::Invoke(invoke_args) => invoke_args.dispatch(executor), + } + } +} + +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_extrinsic_statuses(&self) -> core::result::Result, Self::Error> { + Ok(Vec::from([ExtrinsicStatus::Success])) + } + + fn get_transfer_events(&self) -> core::result::Result, Self::Error> { + let transfer = BalanceTransfer { + to: [0u8; 32].into(), + from: [0u8; 32].into(), + amount: Balance::default(), + }; + Ok(Vec::from([transfer])) + } +} + +pub struct MockParentchainEventHandler {} + +impl HandleParentchainEvents + for MockParentchainEventHandler +where + Executor: IndirectExecutor, +{ + fn handle_events( + _: &Executor, + _: impl itp_types::parentchain::FilterEvents, + _: &AccountId, + ) -> core::result::Result<(), Error> { + Ok(()) + } +} + +/// Arguments of the Integritee-Parachain's shield fund dispatchable. +#[derive(Debug, Clone, Encode, Decode, Eq, PartialEq)] +pub struct ShieldFundsArgs { + shard: ShardIdentifier, + account_encrypted: Vec, + amount: Balance, +} + +impl> + IndirectDispatch for ShieldFundsArgs +{ + fn dispatch(&self, executor: &Executor) -> 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); + 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: Request, +} + +impl> + IndirectDispatch for InvokeArgs +{ + fn dispatch(&self, executor: &Executor) -> ICResult<()> { + log::debug!("Found trusted call extrinsic, submitting it to the top pool"); + executor.submit_trusted_call(self.request.shard, self.request.cyphertext.clone()); + Ok(()) + } +} diff --git a/core/parentchain/indirect-calls-executor/src/traits.rs b/core/parentchain/indirect-calls-executor/src/traits.rs index 9e069bc2ec..bdec20f939 100644 --- a/core/parentchain/indirect-calls-executor/src/traits.rs +++ b/core/parentchain/indirect-calls-executor/src/traits.rs @@ -15,10 +15,11 @@ */ -use crate::error::Result; -use ita_stf::{TrustedCall, TrustedCallSigned}; -use itp_stf_primitives::types::AccountId; -use itp_types::{OpaqueCall, ShardIdentifier, H256}; +use crate::{error::Result, Error}; +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; @@ -31,7 +32,7 @@ pub trait ExecuteIndirectCalls { &self, block: &ParentchainBlock, events: &[u8], - ) -> Result + ) -> Result> where ParentchainBlock: ParentchainBlockTrait; @@ -49,26 +50,9 @@ pub trait ExecuteIndirectCalls { } /// Trait that should be implemented on indirect calls to be executed. -pub trait IndirectDispatch { +pub trait IndirectDispatch, TCS> +where + TCS: PartialEq + Encode + Decode + Debug + Clone + Send + Sync + TrustedCallVerification, +{ fn dispatch(&self, executor: &E) -> Result<()>; } - -/// Trait to be implemented on the executor to serve helper methods of the executor -/// to the `IndirectDispatch` implementation. -pub trait IndirectExecutor { - fn submit_trusted_call(&self, shard: ShardIdentifier, encrypted_trusted_call: Vec); - - fn decrypt(&self, encrypted: &[u8]) -> Result>; - - fn encrypt(&self, value: &[u8]) -> Result>; - - fn get_enclave_account(&self) -> Result; - - fn get_default_shard(&self) -> ShardIdentifier; - - fn sign_call_with_self( - &self, - trusted_call: &TrustedCall, - shard: &ShardIdentifier, - ) -> Result; -} diff --git a/core/parentchain/light-client/Cargo.toml b/core/parentchain/light-client/Cargo.toml index dc36585d8a..358b0d4087 100644 --- a/core/parentchain/light-client/Cargo.toml +++ b/core/parentchain/light-client/Cargo.toml @@ -6,12 +6,8 @@ edition = "2021" [dependencies] codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive", "chain-error"] } -derive_more = { version = "0.99.5" } finality-grandpa = { version = "0.16.0", default-features = false, features = ["derive-codec"] } -hash-db = { version = "0.15.2", default-features = false } -lazy_static = { version = "1.1.0", features = ["spin_no_std"] } log = { version = "0.4", default-features = false } -num = { package = "num-traits", version = "0.2", default-features = false } thiserror = { version = "1.0.26", optional = true } # sgx-deps @@ -26,12 +22,8 @@ itp-storage = { path = "../../../core-primitives/storage", default-features = fa itp-types = { path = "../../../core-primitives/types", default-features = false } # substrate deps -frame-system = { default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } -sp-application-crypto = { default-features = false, features = ["full_crypto"], git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } sp-consensus-grandpa = { default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } -sp-core = { default-features = false, features = ["full_crypto"], git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } sp-runtime = { default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } -sp-trie = { default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } # test & mock dependencies itc-parentchain-test = { optional = true, default-features = false, path = "../../../core/parentchain/test" } @@ -48,19 +40,13 @@ itp-sgx-temp-dir = { version = "0.1", path = "../../../core-primitives/sgx/temp- default = ["std"] std = [ "codec/std", - "hash-db/std", - "num/std", "log/std", "finality-grandpa/std", "thiserror", # substrate deps - "frame-system/std", - "sp-core/std", - "sp-application-crypto/std", "sp-consensus-grandpa/std", "sp-runtime/std", - "sp-trie/std", # local deps "itp-ocall-api/std", diff --git a/core/parentchain/light-client/src/io.rs b/core/parentchain/light-client/src/io.rs index 4b95a38965..263ccb1cf2 100644 --- a/core/parentchain/light-client/src/io.rs +++ b/core/parentchain/light-client/src/io.rs @@ -123,12 +123,50 @@ impl LightClientSealing Ok(unsealed.using_encoded(|bytes| seal(bytes, self.db_path()))?) } + // unseals db with automatic failover to db backup fn unseal(&self) -> Result { - Ok(unseal(self.db_path()).map(|b| Decode::decode(&mut b.as_slice()))??) + Ok(unseal(self.db_path()) + .or_else(|e| { + warn!( + "can't unseal db at {:?}. error {:?}. trying backup at {:?}", + self.db_path(), + e, + self.backup_path() + ); + // create a copy because we will overwrite the db in the next step + fs::copy(self.db_path(), self.db_path().with_extension("cantunseal")).and_then( + |_| { + fs::copy(self.backup_path(), self.db_path()).and_then(|_| { + unseal(self.db_path()).map_err(|e| { + warn!("{:?}", e); + e + }) + }) + }, + ) + }) + .map(|b| Decode::decode(&mut b.as_slice()))??) } + // checks if either the db or its backup can be opened in opaque mode (no unseal) fn exists(&self) -> bool { - SgxFile::open(self.db_path()).is_ok() + debug!("check if db exists at {:?}", self.db_path()); + fs::File::open(self.db_path()) + .or_else(|e| { + warn!( + "can't open db at {:?}. error: {:?}. trying restore backup at {:?}", + self.db_path(), + e, + self.backup_path() + ); + fs::copy(self.backup_path(), self.db_path()) + .and_then(|_| fs::File::open(self.db_path())) + .map_err(|e| { + warn!("{:?}", e); + e + }) + }) + .is_ok() } fn path(&self) -> &Path { @@ -206,7 +244,7 @@ where if !seal.exists() { info!( - "[{:?}] ChainRelay DB not found, creating new! {}", + "[{:?}] ChainRelay DB for grandpa validator not found, creating new! {}", seal.parentchain_id(), seal.path().display() ); @@ -257,8 +295,13 @@ where OCallApi: EnclaveOnChainOCallApi, LightClientSeal: LightClientSealing>, { + trace!("[{:?}] init light client db", parentchain_id); if !seal.exists() { - info!("[Enclave] ChainRelay DB not found, creating new! {}", seal.path().display()); + info!( + "[{:?}] ChainRelay DB for parachain validator not found, creating new! {}", + parentchain_id, + seal.path().display() + ); let validator = init_parachain_validator::( ocall_api, RelayState::new(params.genesis_header, Default::default()).into(), @@ -269,6 +312,7 @@ where } let validation_state = seal.unseal()?; + info!("unseal success"); let genesis_hash = validation_state.genesis_hash()?; let init_state = if genesis_hash == params.genesis_header.hash() { diff --git a/core/parentchain/light-client/src/justification.rs b/core/parentchain/light-client/src/justification.rs index 5e6f21f78c..554f97579f 100644 --- a/core/parentchain/light-client/src/justification.rs +++ b/core/parentchain/light-client/src/justification.rs @@ -151,10 +151,10 @@ impl GrandpaJustification { set_id, &mut buf, ) { - debug!("Bad signature on message from {:?}", &signed.id); - return Err(ClientError::BadJustification( - "invalid signature for precommit in grandpa justification".to_string(), - )) + warn!("Bad signature on message from {:?}", &signed.id); + // return Err(ClientError::BadJustification( + // "invalid signature for precommit in grandpa justification".to_string(), + // )) } if self.commit.target_hash == signed.precommit.target_hash { diff --git a/core/parentchain/light-client/src/light_validation.rs b/core/parentchain/light-client/src/light_validation.rs index 5da9db71d6..37d41ba757 100644 --- a/core/parentchain/light-client/src/light_validation.rs +++ b/core/parentchain/light-client/src/light_validation.rs @@ -26,6 +26,7 @@ use core::iter::Iterator; use itp_ocall_api::EnclaveOnChainOCallApi; use itp_storage::{Error as StorageError, StorageProof, StorageProofChecker}; use itp_types::parentchain::{IdentifyParentchain, ParentchainId}; +use log::error; use sp_runtime::{ generic::SignedBlock, traits::{Block as ParentchainBlockTrait, Header as HeaderTrait}, @@ -145,6 +146,13 @@ where let relay = self.light_validation_state.get_relay_mut(); if relay.last_finalized_block_header.hash() != *header.parent_hash() { + error!("header ancestry mismatch! last imported was block nr {:?} with hash {:?}, attempting to import nr {:?} with hash {:?} and ancestor {:?}", + relay.last_finalized_block_header.number(), + relay.last_finalized_block_header.hash(), + header.number(), + header.hash(), + header.parent_hash() + ); return Err(Error::HeaderAncestryMismatch) } diff --git a/core/parentchain/parentchain-crate/src/primitives.rs b/core/parentchain/parentchain-crate/src/primitives.rs index 055672ea6e..6a02c99577 100644 --- a/core/parentchain/parentchain-crate/src/primitives.rs +++ b/core/parentchain/parentchain-crate/src/primitives.rs @@ -22,7 +22,9 @@ use codec::{Decode, Encode}; use sp_runtime::traits::Block; +use itp_types::ShardIdentifier; pub use itp_types::{parentchain::ParentchainId, Block as ParachainBlock, Block as SolochainBlock}; + pub type HeaderFor = ::Header; pub type SolochainHeader = HeaderFor; pub type ParachainHeader = HeaderFor; @@ -33,8 +35,8 @@ pub type ParachainParams = SimpleParams; /// Allows to use a single E-call for the initialization of different parentchain types. #[derive(Encode, Decode, Clone)] pub enum ParentchainInitParams { - Solochain { id: ParentchainId, params: SolochainParams }, - Parachain { id: ParentchainId, params: ParachainParams }, + Solochain { id: ParentchainId, shard: ShardIdentifier, params: SolochainParams }, + Parachain { id: ParentchainId, shard: ShardIdentifier, params: ParachainParams }, } impl ParentchainInitParams { @@ -44,16 +46,22 @@ impl ParentchainInitParams { Self::Parachain { id, .. } => id, } } + pub fn is_solochain(&self) -> bool { + matches!(self, Self::Solochain { .. }) + } + pub fn is_parachain(&self) -> bool { + matches!(self, Self::Parachain { .. }) + } } -impl From<(ParentchainId, SolochainParams)> for ParentchainInitParams { - fn from(value: (ParentchainId, SolochainParams)) -> Self { - Self::Solochain { id: value.0, params: value.1 } +impl From<(ParentchainId, ShardIdentifier, SolochainParams)> for ParentchainInitParams { + fn from(value: (ParentchainId, ShardIdentifier, SolochainParams)) -> Self { + Self::Solochain { id: value.0, shard: value.1, params: value.2 } } } -impl From<(ParentchainId, ParachainParams)> for ParentchainInitParams { - fn from(value: (ParentchainId, ParachainParams)) -> Self { - Self::Parachain { id: value.0, params: value.1 } +impl From<(ParentchainId, ShardIdentifier, ParachainParams)> for ParentchainInitParams { + fn from(value: (ParentchainId, ShardIdentifier, ParachainParams)) -> Self { + Self::Parachain { id: value.0, shard: value.1, params: value.2 } } } diff --git a/core/parentchain/test/Cargo.toml b/core/parentchain/test/Cargo.toml index a54025ea30..e40d9b0c51 100644 --- a/core/parentchain/test/Cargo.toml +++ b/core/parentchain/test/Cargo.toml @@ -8,33 +8,12 @@ license = "Apache-2.0" edition = "2021" [dependencies] -codec = { version = "3.0.0", default-features = false, features = ["derive"], package = "parity-scale-codec" } itp-types = { path = "../../../core-primitives/types", default-features = false } -log = { version = "0.4.14", default-features = false } -scale-info = { version = "2.0.1", default-features = false, features = ["derive"] } -serde = { version = "1.0.13", features = ["derive"], optional = true } - -# substrate dependencies -frame-support = { default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } -frame-system = { default-features = false, package = "frame-system", git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } -sp-core = { default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } -sp-io = { default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } sp-runtime = { default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } -sp-std = { default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } [features] default = ["std"] std = [ - "codec/std", - "log/std", - "scale-info/std", - "serde", "itp-types/std", - # substrate dependencies - "frame-support/std", - "frame-system/std", - "sp-core/std", - "sp-io/std", "sp-runtime/std", - "sp-std/std", ] diff --git a/core/rest-client/Cargo.toml b/core/rest-client/Cargo.toml index 6f5d9dbe78..dc3be4cfbf 100644 --- a/core/rest-client/Cargo.toml +++ b/core/rest-client/Cargo.toml @@ -15,7 +15,6 @@ url = { version = "2.0.0", optional = true } http-sgx = { package = "http", git = "https://github.com/integritee-network/http-sgx.git", branch = "sgx-experimental", optional = true } http_req-sgx = { optional = true, default-features = false, features = ["rust-tls", "sgx"], package = "http_req", git = "https://github.com/integritee-network/http_req" } sgx_tstd = { branch = "master", git = "https://github.com/apache/teaclave-sgx-sdk.git", optional = true, features = ["net", "thread"] } -sgx_types = { branch = "master", git = "https://github.com/apache/teaclave-sgx-sdk.git", optional = true } thiserror_sgx = { package = "thiserror", git = "https://github.com/mesalock-linux/thiserror-sgx", tag = "sgx_1.1.3", optional = true } url_sgx = { package = "url", git = "https://github.com/mesalock-linux/rust-url-sgx", tag = "sgx_1.1.3", optional = true } @@ -42,7 +41,6 @@ std = [ sgx = [ "http-sgx", "http_req-sgx", - "sgx_types", "sgx_tstd", "thiserror_sgx", "url_sgx", diff --git a/core/rpc-client/Cargo.toml b/core/rpc-client/Cargo.toml index d575ca4c88..3dcac90f36 100644 --- a/core/rpc-client/Cargo.toml +++ b/core/rpc-client/Cargo.toml @@ -10,7 +10,6 @@ codec = { package = "parity-scale-codec", version = "3.0.0", features = ["derive log = "0.4" openssl = { version = "0.10" } parking_lot = "0.12.1" -serde_derive = "1.0" serde_json = "1.0" sgx_crypto_helper = { branch = "master", git = "https://github.com/apache/teaclave-sgx-sdk.git" } thiserror = { version = "1.0" } diff --git a/core/rpc-client/src/direct_client.rs b/core/rpc-client/src/direct_client.rs index 26cc36eee4..339d9ff632 100644 --- a/core/rpc-client/src/direct_client.rs +++ b/core/rpc-client/src/direct_client.rs @@ -75,14 +75,14 @@ impl DirectApi for DirectClient { fn get(&self, request: &str) -> Result { let (port_in, port_out) = channel(); - info!("[WorkerApi Direct]: (get) Sending request: {:?}", request); + debug!("[WorkerApi Direct]: (get) Sending request: {:?}", request); WsClient::connect_one_shot(&self.url, request, port_in)?; - debug!("Waiting for web-socket result.."); + trace!("Waiting for web-socket result.."); port_out.recv().map_err(Error::MspcReceiver) } fn watch(&self, request: String, sender: MpscSender) -> JoinHandle<()> { - info!("[WorkerApi Direct]: (watch) Sending request: {:?}", request); + debug!("[WorkerApi Direct]: (watch) Sending request: {:?}", request); let url = self.url.clone(); let web_socket_control = self.web_socket_control.clone(); @@ -133,7 +133,7 @@ impl DirectApi for DirectClient { let untrusted_url: String = decode_from_rpc_response(&response_str)?; - info!("[+] Got untrusted websocket url of worker: {}", untrusted_url); + trace!("Got untrusted websocket url of worker: {}", untrusted_url); Ok(untrusted_url) } diff --git a/core/rpc-server/Cargo.toml b/core/rpc-server/Cargo.toml index 7850d64fe9..919af8d54b 100644 --- a/core/rpc-server/Cargo.toml +++ b/core/rpc-server/Cargo.toml @@ -9,7 +9,6 @@ anyhow = "1.0.40" jsonrpsee = { version = "0.2.0-alpha.7", features = ["full"] } log = "0.4" parity-scale-codec = "3.0.0" -serde_json = "1.0.64" tokio = { version = "1.6.1", features = ["full"] } # local diff --git a/core/rpc-server/src/lib.rs b/core/rpc-server/src/lib.rs index 06cab927a9..0e993c3c3c 100644 --- a/core/rpc-server/src/lib.rs +++ b/core/rpc-server/src/lib.rs @@ -74,7 +74,10 @@ where let socket_addr = server.local_addr()?; tokio::spawn(async move { server.start().await }); - println!("[+] Untrusted RPC server is spawned on: {}", socket_addr); + println!( + "[+] Untrusted RPC server is spawned on: {} listening to peer sidechain block broadcasts", + socket_addr + ); Ok(socket_addr) } diff --git a/core/rpc-server/src/mock.rs b/core/rpc-server/src/mock.rs index 7af48b1c63..0d86606eea 100644 --- a/core/rpc-server/src/mock.rs +++ b/core/rpc-server/src/mock.rs @@ -16,7 +16,7 @@ */ use itp_enclave_api::{direct_request::DirectRequest, EnclaveResult}; -use itp_rpc::RpcResponse; +use itp_rpc::{Id, RpcResponse}; use itp_utils::ToHexPrefixed; use its_primitives::{ traits::ShardIdentifierFor, @@ -29,7 +29,12 @@ pub struct TestEnclave; impl DirectRequest for TestEnclave { fn rpc(&self, _request: Vec) -> EnclaveResult> { - Ok(RpcResponse { jsonrpc: "mock_response".into(), result: "null".to_hex(), id: 1 }.encode()) + Ok(RpcResponse { + jsonrpc: "mock_response".into(), + result: "null".to_hex(), + id: Id::Number(1), + } + .encode()) } } diff --git a/core/tls-websocket-server/Cargo.toml b/core/tls-websocket-server/Cargo.toml index 725cc63ad9..085f5136df 100644 --- a/core/tls-websocket-server/Cargo.toml +++ b/core/tls-websocket-server/Cargo.toml @@ -11,9 +11,6 @@ rcgen = { package = "rcgen", default-features = false, git = "https://github.com # sgx dependencies sgx_tstd = { optional = true, features = ["net", "thread"], git = "https://github.com/apache/teaclave-sgx-sdk.git", branch = "master" } -sgx_types = { optional = true, git = "https://github.com/apache/teaclave-sgx-sdk.git", branch = "master" } -# Todo: should not be needed here: #848 -sgx_crypto_helper = { default-features = false, optional = true, features = ["mesalock_sgx"], version = "1.1.6", git = "https://github.com/apache/teaclave-sgx-sdk.git", branch = "master" } # sgx enabled external libraries mio-extras = { optional = true, default-features = false, git = "https://github.com/integritee-network/mio-extras-sgx", rev = "963234b" } @@ -53,8 +50,6 @@ sgx = [ "rcgen/pem_sgx", "rustls_sgx", "sgx_tstd", - "sgx_types", - "sgx_crypto_helper", "thiserror_sgx", "tungstenite_sgx", "webpki_sgx", diff --git a/docker/README.md b/docker/README.md index 27f0a3990d..7f9ddb7a86 100644 --- a/docker/README.md +++ b/docker/README.md @@ -28,11 +28,11 @@ Starts all services (node and workers), using the `integritee-worker:dev` images ### Demo indirect invocation (M6) Build ``` -COMPOSE_DOCKER_CLI_BUILD=1 DOCKER_BUILDKIT=1 docker compose -f <(envsubst < docker-compose.yml) -f <(envsubst < demo-indirect-invocation.yml) build --build-arg WORKER_MODE_ARG=offchain-worker +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-indirect-invocation.yml) up demo-indirect-invocation --exit-code-from demo-indirect-invocation +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) @@ -113,4 +113,4 @@ You can suppress the log output for a container by setting the logging driver. T 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/). \ No newline at end of file +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/docker/demo-indirect-invocation.yml b/docker/demo-shielding-unshielding-multiworker.yml similarity index 85% rename from docker/demo-indirect-invocation.yml rename to docker/demo-shielding-unshielding-multiworker.yml index bba1748838..6ca9b3b147 100644 --- a/docker/demo-indirect-invocation.yml +++ b/docker/demo-shielding-unshielding-multiworker.yml @@ -1,5 +1,5 @@ services: - demo-indirect-invocation: + demo-shielding-unshielding-multiworker: image: integritee-cli:${VERSION:-dev} devices: - "${SGX_PROVISION:-/dev/null}:/dev/sgx/provision" @@ -24,9 +24,9 @@ services: networks: - integritee-test-network entrypoint: - "/usr/local/worker-cli/demo_indirect_invocation.sh -p 9912 -u ws://integritee-node + "/usr/local/worker-cli/demo_shielding_unshielding_multiworker.sh -p 9912 -u ws://integritee-node -V wss://integritee-worker-1 -A 2011 -W wss://integritee-worker-2 -B 2012 -C /usr/local/bin/integritee-cli 2>&1" restart: "no" networks: integritee-test-network: - driver: bridge \ No newline at end of file + driver: bridge diff --git a/docker/docker-compose.yml b/docker/docker-compose.yml index 890183cce9..52800a2e27 100644 --- a/docker/docker-compose.yml +++ b/docker/docker-compose.yml @@ -1,6 +1,6 @@ services: "integritee-node-${VERSION}": - image: "${INTEGRITEE_NODE:-integritee/integritee-node:1.1.3}" + image: "${INTEGRITEE_NODE:-integritee/integritee-node:1.13.0}" hostname: integritee-node devices: - "${SGX_PROVISION:-/dev/null}:/dev/sgx/provision" @@ -15,7 +15,7 @@ services: interval: 10s timeout: 10s retries: 6 - command: -lruntime=info -lteerex=debug --dev --rpc-methods unsafe --ws-external --rpc-external --ws-port 9912 + command: -lruntime=info -lteerex=debug --dev --rpc-methods unsafe --rpc-external --rpc-port 9912 #logging: #driver: local "integritee-worker-1-${VERSION}": @@ -35,7 +35,7 @@ services: - "${AESMD:-/dev/null}:/var/run/aesmd" - "${SGX_QCNL:-/dev/null}:/etc/sgx_default_qcnl.conf" environment: - - RUST_LOG=warn,ws=warn,sp_io=warn,substrate_api_client=warn,jsonrpsee_ws_client=warn,jsonrpsee_ws_server=warn,enclave_runtime=warn,integritee_service=warn,ita_stf=debug + - RUST_LOG=info,substrate_api_client=warn,ws=warn,mio=warn,ac_node_api=warn,sp_io=warn,tungstenite=warn,integritee_service=debug,enclave_runtime=debug networks: - integritee-test-network healthcheck: @@ -43,8 +43,7 @@ services: interval: 10s timeout: 10s retries: 25 - # OLI: added --skip-ra` - command: "--clean-reset --data-dir /tmp/worker1 --ws-external -M integritee-worker-1 -T wss://integritee-worker-1 -u ws://integritee-node -U ws://integritee-worker-1 -P 2011 -w 2101 -p 9912 -h 4645 run --dev ${ADDITIONAL_RUNTIME_FLAGS} --skip-ra" + command: "--clean-reset --data-dir /tmp/worker1 --ws-external -M integritee-worker-1 -T wss://integritee-worker-1 -u ws://integritee-node -U ws://integritee-worker-1 -P 2011 -w 2101 -p 9912 -h 4645 run --dev ${ADDITIONAL_RUNTIME_FLAGS}" restart: "no" "integritee-worker-2-${VERSION}": image: integritee-worker:${VERSION:-dev} @@ -65,7 +64,7 @@ services: - "${AESMD:-/dev/null}:/var/run/aesmd" - "${SGX_QCNL:-/dev/null}:/etc/sgx_default_qcnl.conf" environment: - - RUST_LOG=warn,ws=warn,sp_io=warn,substrate_api_client=warn,jsonrpsee_ws_client=warn,jsonrpsee_ws_server=warn,enclave_runtime=warn,integritee_service=warn,ita_stf=warn,its_consensus_common=debug + - RUST_LOG=info,substrate_api_client=warn,ws=warn,mio=warn,ac_node_api=warn,sp_io=warn,tungstenite=warn,integritee_service=debug,enclave_runtime=debug networks: - integritee-test-network healthcheck: @@ -73,8 +72,7 @@ services: interval: 10s timeout: 10s retries: 25 - # OLI: added --skip-ra - command: "--clean-reset --data-dir /tmp/worker2 --ws-external -M integritee-worker-2 -T wss://integritee-worker-2 -u ws://integritee-node -U ws://integritee-worker-2 -P 2012 -w 2102 -p 9912 -h 4646 run --dev --request-state ${ADDITIONAL_RUNTIME_FLAGS} --skip-ra" + command: "--clean-reset --data-dir /tmp/worker2 --ws-external -M integritee-worker-2 -T wss://integritee-worker-2 -u ws://integritee-node -U ws://integritee-worker-2 -P 2012 -w 2102 -p 9912 -h 4646 run --dev ${ADDITIONAL_RUNTIME_FLAGS}" restart: "no" networks: integritee-test-network: diff --git a/enclave-runtime/Cargo.lock b/enclave-runtime/Cargo.lock index 923fef99fc..a12d9c3611 100644 --- a/enclave-runtime/Cargo.lock +++ b/enclave-runtime/Cargo.lock @@ -9,13 +9,13 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fe438c63458706e03479442743baae6c88256498e6431708f6dfc520a26515d3" dependencies = [ "lazy_static", - "regex 1.8.4", + "regex 1.9.1", ] [[package]] name = "ac-compose-macros" version = "0.4.2" -source = "git+https://github.com/scs/substrate-api-client.git?branch=polkadot-v0.9.42-tag-v0.14.0#e4ed74b0fb6c2fd5585f55c2702b97b56d99c7f6" +source = "git+https://github.com/scs/substrate-api-client.git?branch=polkadot-v0.9.42-tag-v0.14.0#d31ce7684a60a55b943b3355b2dacc6d0edcc371" dependencies = [ "ac-primitives", "log", @@ -25,7 +25,7 @@ dependencies = [ [[package]] name = "ac-node-api" version = "0.5.1" -source = "git+https://github.com/scs/substrate-api-client.git?branch=polkadot-v0.9.42-tag-v0.14.0#e4ed74b0fb6c2fd5585f55c2702b97b56d99c7f6" +source = "git+https://github.com/scs/substrate-api-client.git?branch=polkadot-v0.9.42-tag-v0.14.0#d31ce7684a60a55b943b3355b2dacc6d0edcc371" dependencies = [ "ac-primitives", "bitvec", @@ -39,8 +39,8 @@ dependencies = [ "scale-decode", "scale-encode", "scale-info", - "serde 1.0.188", - "serde_json 1.0.96", + "serde 1.0.192", + "serde_json 1.0.108", "sp-application-crypto", "sp-core", "sp-runtime", @@ -50,14 +50,14 @@ dependencies = [ [[package]] name = "ac-primitives" version = "0.9.0" -source = "git+https://github.com/scs/substrate-api-client.git?branch=polkadot-v0.9.42-tag-v0.14.0#e4ed74b0fb6c2fd5585f55c2702b97b56d99c7f6" +source = "git+https://github.com/scs/substrate-api-client.git?branch=polkadot-v0.9.42-tag-v0.14.0#d31ce7684a60a55b943b3355b2dacc6d0edcc371" dependencies = [ "impl-serde", "parity-scale-codec", "primitive-types", "scale-info", - "serde 1.0.188", - "serde_json 1.0.96", + "serde 1.0.192", + "serde_json 1.0.108", "sp-application-crypto", "sp-core", "sp-core-hashing", @@ -105,7 +105,7 @@ version = "0.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fcb51a0695d8f838b1ee009b3fbf66bda078cd64590202a864a8f3e8c4315c47" dependencies = [ - "getrandom 0.2.3", + "getrandom 0.2.10", "once_cell 1.18.0", "version_check", ] @@ -153,9 +153,9 @@ checksum = "f52f63c5c1316a16a4b35eaac8b76a98248961a533f061684cb2a7cb0eafb6c6" [[package]] name = "array-bytes" -version = "6.1.0" +version = "6.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d9b1c5a481ec30a5abd8dfbd94ab5cf1bb4e9a66be7f1b3b322f2f1170c200fd" +checksum = "6f840fb7195bcfc5e17ea40c26e5ce6d5b9ce5d584466e17703209657e459ae0" [[package]] name = "arrayref" @@ -171,19 +171,19 @@ checksum = "23b62fc65de8e4e7f52534fb52b0f3ed04746ae267519eef2a83941e8085068b" [[package]] name = "arrayvec" -version = "0.7.2" +version = "0.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8da52d66c7071e2e3fa2a1e5c6d088fec47b593032b254f5e980de8ea54454d6" +checksum = "96d30a06541fbafbc7f82ed10c06164cfbd2c401138f6addd8404629c4b16711" [[package]] name = "async-trait" -version = "0.1.73" +version = "0.1.74" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bc00ceb34980c03614e35a3a4e218276a0a824e911d07651cd0d858a51e8c0f0" +checksum = "a66537f1bb974b254c98ed142ff995236e81b9d0fe4db0575f46612cb15eb0f9" dependencies = [ "proc-macro2", "quote 1.0.33", - "syn 2.0.33", + "syn 2.0.39", ] [[package]] @@ -321,8 +321,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3c2f0dc9a68c6317d884f97cc36cf5a3d20ba14ce404227df55e1af708ab04bc" dependencies = [ "arrayref", - "arrayvec 0.7.2", - "constant_time_eq 0.2.5", + "arrayvec 0.7.4", + "constant_time_eq 0.2.6", ] [[package]] @@ -384,9 +384,9 @@ checksum = "8d696c370c750c948ada61c69a0ee2cbbb9c50b1019ddb86d9317157a99c2cae" [[package]] name = "bounded-collections" -version = "0.1.7" +version = "0.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "07fbd1d11282a1eb134d3c3b7cf8ce213b5161c6e5f73fb1b98618482c606b64" +checksum = "eb5b05133427c07c4776906f673ccf36c21b102c9829c641a5b56bd151d44fd6" dependencies = [ "log", "parity-scale-codec", @@ -451,7 +451,7 @@ version = "0.10.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0aacacf4d96c24b2ad6eb8ee6df040e4f27b0d0b39a5710c30091baa830485db" dependencies = [ - "smallvec 1.10.0", + "smallvec 1.11.0", ] [[package]] @@ -483,7 +483,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ec837a71355b28f6556dbd569b37b3f363091c0bd4b2e735674521b4c5fd9bc5" dependencies = [ "android-tzdata", - "num-traits 0.2.15", + "num-traits 0.2.16", ] [[package]] @@ -508,7 +508,7 @@ dependencies = [ [[package]] name = "common-primitives" version = "0.1.0" -source = "git+https://github.com/integritee-network/pallets.git?branch=sdk-v0.12.0-polkadot-v0.9.42#eaf611b79bc9d56b20c155150e99b549bf98436b" +source = "git+https://github.com/integritee-network/pallets.git?branch=sdk-v0.12.11-polkadot-v0.9.42#094b1e982b4637ebfbf5afb985100417215d49a0" dependencies = [ "derive_more", "parity-scale-codec", @@ -520,9 +520,9 @@ dependencies = [ [[package]] name = "const-oid" -version = "0.9.2" +version = "0.9.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "520fbf3c07483f94e3e3ca9d0cfd913d7718ef2483d2cfd91c0d9e91474ab913" +checksum = "795bc6e66a8e340f075fcf6227e417a2dc976b92b91f3cdc778bb858778b6747" [[package]] name = "constant_time_eq" @@ -532,9 +532,9 @@ checksum = "245097e9a4535ee1e3e3931fcfcd55a796a44c643e8596ff6566d68f09b87bbc" [[package]] name = "constant_time_eq" -version = "0.2.5" +version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "13418e745008f7349ec7e449155f419a61b92b58a99cc3616942b926825ec76b" +checksum = "21a53c0a4d288377e7415b53dcfc3c04da5cdc2cc95c8d5ac178b58f0b861ad6" [[package]] name = "convert_case" @@ -544,9 +544,9 @@ checksum = "6245d59a3e82a7fc217c5828a6692dbc6dfb63a0c8c90495621f7b9d79704a0e" [[package]] name = "cpufeatures" -version = "0.2.7" +version = "0.2.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e4c1eaa2012c47becbbad2ab175484c2a84d1185b566fb2cc5b8707343dfe58" +checksum = "a17b76ff3a4162b0b27f354a0c87015ddad39d35f9c0c36607a3bdd175dde1f1" dependencies = [ "libc", ] @@ -559,9 +559,9 @@ checksum = "7a81dae078cea95a014a339291cec439d2f232ebe854a9d672b796c6afafa9b7" [[package]] name = "crypto-bigint" -version = "0.5.2" +version = "0.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf4c2f4e1afd912bc40bfd6fed5d9dc1f288e0ba01bfcc835cc5bc3eb13efe15" +checksum = "740fe28e594155f10cfc383984cbefd529d7396050557148f79cb0f621204124" dependencies = [ "generic-array 0.14.7", "rand_core 0.6.4", @@ -648,9 +648,9 @@ checksum = "c2e66c9d817f1720209181c316d28635c050fa304f9c79e47a520882661b7308" [[package]] name = "der" -version = "0.7.6" +version = "0.7.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "56acb310e15652100da43d130af8d97b509e95af61aab1c5a7939ef24337ee17" +checksum = "fffa369a668c8af7dbf8b5e56c9f744fbd399949ed171606040001947de40b1c" dependencies = [ "const-oid", "zeroize", @@ -712,9 +712,9 @@ dependencies = [ [[package]] name = "ecdsa" -version = "0.16.7" +version = "0.16.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0997c976637b606099b9985693efa3581e84e41f5c11ba5255f88711058ad428" +checksum = "a4b1e0c257a9e9f25f90ff76d7a68360ed497ee519c8e428d1825ef0000799d4" dependencies = [ "der", "digest 0.10.7", @@ -739,9 +739,9 @@ dependencies = [ [[package]] name = "either" -version = "1.8.1" +version = "1.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7fcaabb2fef8c910e7f4c7ce9f67a1283a1715879a7c230ca9d6d1ae31f16d91" +checksum = "a26ae43d7bcc3b814de94796a5e736d4029efb0ee900c12e2d54c993ad1a1e07" [[package]] name = "elliptic-curve" @@ -764,13 +764,13 @@ dependencies = [ [[package]] name = "enclave-bridge-primitives" version = "0.1.0" -source = "git+https://github.com/integritee-network/pallets.git?branch=sdk-v0.12.0-polkadot-v0.9.42#eaf611b79bc9d56b20c155150e99b549bf98436b" +source = "git+https://github.com/integritee-network/pallets.git?branch=sdk-v0.12.11-polkadot-v0.9.42#094b1e982b4637ebfbf5afb985100417215d49a0" dependencies = [ "common-primitives", "log", "parity-scale-codec", "scale-info", - "serde 1.0.188", + "serde 1.0.192", "sp-core", "sp-io", "sp-runtime", @@ -779,28 +779,31 @@ dependencies = [ [[package]] name = "enclave-runtime" -version = "0.12.0" +version = "0.12.11" dependencies = [ - "array-bytes 6.1.0", + "array-bytes 6.2.2", "cid", "derive_more", + "enclave-bridge-primitives", "env_logger", "frame-support", "frame-system", "hex", "ipfs-unixfs", "ita-oracle", + "ita-parentchain-interface", "ita-sgx-runtime", "ita-stf", "itc-direct-rpc-server", "itc-offchain-worker-executor", "itc-parentchain", + "itc-parentchain-block-import-dispatcher", + "itc-parentchain-block-importer", "itc-parentchain-test", "itc-tls-websocket-server", "itp-attestation-handler", "itp-component-container", "itp-extrinsics-factory", - "itp-hashing", "itp-import-queue", "itp-node-api", "itp-node-api-metadata", @@ -811,7 +814,6 @@ dependencies = [ "itp-settings", "itp-sgx-crypto", "itp-sgx-externalities", - "itp-sgx-io", "itp-sgx-temp-dir", "itp-stf-executor", "itp-stf-interface", @@ -819,7 +821,6 @@ dependencies = [ "itp-stf-state-handler", "itp-stf-state-observer", "itp-storage", - "itp-teerex-storage", "itp-test", "itp-time-utils", "itp-top-pool", @@ -838,8 +839,6 @@ dependencies = [ "primitive-types", "rust-base58", "rustls 0.19.0 (git+https://github.com/mesalock-linux/rustls?rev=sgx_1.1.3)", - "serde 1.0.118 (git+https://github.com/mesalock-linux/serde-sgx?tag=sgx_1.1.3)", - "serde_derive 1.0.118", "serde_json 1.0.60 (git+https://github.com/mesalock-linux/serde-json-sgx?tag=sgx_1.1.3)", "sgx_rand", "sgx_serialize", @@ -854,7 +853,6 @@ dependencies = [ "sgx_types", "sp-core", "sp-runtime", - "sp-std", "teerex-primitives", "webpki", ] @@ -884,6 +882,12 @@ 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" @@ -1019,8 +1023,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "36530797b9bf31cd4ff126dcfee8170f86b00cfdcea3269d73133cc0415945c3" dependencies = [ "either", - "futures 0.3.28", - "num-traits 0.2.15", + "futures 0.3.29", + "num-traits 0.2.16", "parity-scale-codec", "scale-info", ] @@ -1113,7 +1117,7 @@ dependencies = [ "cfg-if 1.0.0", "parity-scale-codec", "scale-info", - "serde 1.0.188", + "serde 1.0.192", ] [[package]] @@ -1131,7 +1135,7 @@ dependencies = [ "parity-scale-codec", "paste", "scale-info", - "smallvec 1.10.0", + "smallvec 1.11.0", "sp-api", "sp-arithmetic", "sp-core", @@ -1155,11 +1159,11 @@ dependencies = [ "cfg-expr", "derive-syn-parse", "frame-support-procedural-tools", - "itertools", + "itertools 0.10.5", "proc-macro-warning", "proc-macro2", "quote 1.0.33", - "syn 2.0.33", + "syn 2.0.39", ] [[package]] @@ -1171,7 +1175,7 @@ dependencies = [ "proc-macro-crate", "proc-macro2", "quote 1.0.33", - "syn 2.0.33", + "syn 2.0.39", ] [[package]] @@ -1181,7 +1185,7 @@ source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.4 dependencies = [ "proc-macro2", "quote 1.0.33", - "syn 2.0.33", + "syn 2.0.39", ] [[package]] @@ -1239,16 +1243,16 @@ dependencies = [ [[package]] name = "futures" -version = "0.3.28" +version = "0.3.29" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23342abe12aba583913b2e62f22225ff9c950774065e4bfb61a19cd9770fec40" +checksum = "da0290714b38af9b4a7b094b8a37086d1b4e61f2df9122c3cad2577669145335" 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", + "futures-channel 0.3.29", + "futures-core 0.3.29", + "futures-io 0.3.29", + "futures-sink 0.3.29", + "futures-task 0.3.29", + "futures-util 0.3.29", ] [[package]] @@ -1263,12 +1267,12 @@ dependencies = [ [[package]] name = "futures-channel" -version = "0.3.28" +version = "0.3.29" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "955518d47e09b25bbebc7a18df10b81f0c766eaf4c4f1cccef2fca5f2a4fb5f2" +checksum = "ff4dd66668b557604244583e3e1e1eada8c5c2e96a6d0d6653ede395b78bbacb" dependencies = [ - "futures-core 0.3.28", - "futures-sink 0.3.28", + "futures-core 0.3.29", + "futures-sink 0.3.29", ] [[package]] @@ -1281,9 +1285,9 @@ dependencies = [ [[package]] name = "futures-core" -version = "0.3.28" +version = "0.3.29" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4bca583b7e26f571124fe5b7561d49cb2868d79116cfa0eefce955557c6fee8c" +checksum = "eb1d22c66e66d9d72e1758f0bd7d4fd0bee04cad842ee34587d68c07e45d088c" [[package]] name = "futures-executor" @@ -1306,9 +1310,9 @@ dependencies = [ [[package]] name = "futures-io" -version = "0.3.28" +version = "0.3.29" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4fff74096e71ed47f8e023204cfd0aa1289cd54ae5430a9523be060cdb849964" +checksum = "8bf34a163b5c4c52d0478a4d757da8fb65cabef42ba90515efee0f6f9fa45aaa" [[package]] name = "futures-macro" @@ -1328,9 +1332,9 @@ source = "git+https://github.com/mesalock-linux/futures-rs-sgx#d54882f24ddf7d613 [[package]] name = "futures-sink" -version = "0.3.28" +version = "0.3.29" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f43be4fe21a13b9781a69afa4985b0f6ee0e1afab2c6f454a8cf30e2b2237b6e" +checksum = "e36d3378ee38c2a36ad710c5d30c2911d752cb941c00c72dbabfb786a7970817" [[package]] name = "futures-task" @@ -1343,9 +1347,9 @@ dependencies = [ [[package]] name = "futures-task" -version = "0.3.28" +version = "0.3.29" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "76d3d132be6c0e6aa1534069c705a74a5997a356c0dc2f86a47765e5617c5b65" +checksum = "efd193069b0ddadc69c46389b740bbccdd97203899b48d09c5f7969591d6bae2" [[package]] name = "futures-util" @@ -1369,13 +1373,13 @@ dependencies = [ [[package]] name = "futures-util" -version = "0.3.28" +version = "0.3.29" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26b01e40b772d54cf6c6d721c1d1abd0647a0106a12ecaa1c186273392a69533" +checksum = "a19526d624e703a3179b3d322efec918b6246ea0fa51d41124525f00f1cc8104" dependencies = [ - "futures-core 0.3.28", - "futures-sink 0.3.28", - "futures-task 0.3.28", + "futures-core 0.3.29", + "futures-sink 0.3.29", + "futures-task 0.3.29", "pin-project-lite", "pin-utils", ] @@ -1413,13 +1417,13 @@ dependencies = [ [[package]] name = "getrandom" -version = "0.2.3" -source = "git+https://github.com/integritee-network/getrandom-sgx?branch=update-v2.3#0a4af01fe1df0e6200192e7a709fd18da413466e" +version = "0.2.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be4136b2a15dd319360be1c07d9933517ccf0be8f16bf62a3bee4f0d618df427" dependencies = [ "cfg-if 1.0.0", - "sgx_libc", - "sgx_trts", - "sgx_tstd", + "libc", + "wasi", ] [[package]] @@ -1484,10 +1488,16 @@ 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#f1776a7cec1caab2959813f87bb4924805b92011" +source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#1b1d03376056321441ef99716aa0888bd5ef19f7" [[package]] name = "hex" @@ -1586,7 +1596,7 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ebc88fc67028ae3db0c853baa36269d398d5f45b6982f95549ff5def78c935cd" dependencies = [ - "serde 1.0.188", + "serde 1.0.192", ] [[package]] @@ -1612,12 +1622,12 @@ dependencies = [ [[package]] name = "indexmap" -version = "1.9.3" +version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bd070e393353796e801d209ad339e89596eb4c8d430d18ede6a1cced8fafbd99" +checksum = "d5477fe2230a79769d8dc68e0eabf5437907c0457a5614a9e8dddb67f65eb65d" dependencies = [ - "autocfg 1.1.0", - "hashbrown 0.12.3", + "equivalent", + "hashbrown 0.14.0", ] [[package]] @@ -1626,7 +1636,7 @@ version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "276ec31bcb4a9ee45f58bec6f9ec700ae4cf4f4f8f2fa7e06cb406bd5ffdd770" dependencies = [ - "num-traits 0.2.15", + "num-traits 0.2.16", ] [[package]] @@ -1659,14 +1669,34 @@ dependencies = [ "lazy_static", "log", "parity-scale-codec", - "serde 1.0.188", - "serde_json 1.0.96", + "serde 1.0.192", "sgx_tstd", "substrate-fixed", - "thiserror 1.0.9", + "thiserror", "url", ] +[[package]] +name = "ita-parentchain-interface" +version = "0.9.0" +dependencies = [ + "bs58", + "ita-sgx-runtime", + "ita-stf", + "itc-parentchain", + "itc-parentchain-indirect-calls-executor", + "itp-api-client-types", + "itp-node-api", + "itp-stf-primitives", + "itp-types", + "itp-utils", + "log", + "parity-scale-codec", + "sgx_tstd", + "sp-core", + "sp-runtime", +] + [[package]] name = "ita-sgx-runtime" version = "0.9.0" @@ -1679,7 +1709,6 @@ dependencies = [ "pallet-aura", "pallet-balances", "pallet-evm", - "pallet-grandpa", "pallet-insecure-randomness-collective-flip", "pallet-parentchain", "pallet-sudo", @@ -1706,15 +1735,14 @@ name = "ita-stf" version = "0.9.0" dependencies = [ "binary-merkle-tree 4.0.0-dev (git+https://github.com/paritytech/substrate.git)", - "derive_more", "frame-support", "frame-system", "ita-sgx-runtime", "itp-hashing", "itp-node-api", "itp-node-api-metadata", - "itp-node-api-metadata-provider", "itp-sgx-externalities", + "itp-sgx-runtime-primitives", "itp-stf-interface", "itp-stf-primitives", "itp-storage", @@ -1726,12 +1754,11 @@ dependencies = [ "pallet-sudo", "parity-scale-codec", "rlp", - "serde 1.0.188", - "serde_json 1.0.96", + "serde 1.0.192", + "serde_json 1.0.108", "sgx_tstd", "sha3 0.10.8", "simplyr-lib", - "sp-application-crypto", "sp-core", "sp-io", "sp-runtime", @@ -1749,11 +1776,10 @@ dependencies = [ "jsonrpc-core", "log", "parity-scale-codec", - "serde_json 1.0.96", + "serde_json 1.0.108", "sgx_tstd", - "sgx_types", "sp-runtime", - "thiserror 1.0.9", + "thiserror", ] [[package]] @@ -1771,10 +1797,8 @@ dependencies = [ "log", "parity-scale-codec", "sgx_tstd", - "sgx_types", - "sp-core", "sp-runtime", - "thiserror 1.0.9", + "thiserror", ] [[package]] @@ -1799,8 +1823,7 @@ dependencies = [ "log", "sgx_tstd", "sgx_types", - "sp-runtime", - "thiserror 1.0.9", + "thiserror", ] [[package]] @@ -1811,15 +1834,15 @@ dependencies = [ "itc-parentchain-indirect-calls-executor", "itc-parentchain-light-client", "itp-extrinsics-factory", - "itp-settings", "itp-stf-executor", + "itp-stf-interface", "itp-types", "log", "parity-scale-codec", "sgx_tstd", "sgx_types", "sp-runtime", - "thiserror 1.0.9", + "thiserror", ] [[package]] @@ -1829,34 +1852,29 @@ dependencies = [ "binary-merkle-tree 4.0.0-dev (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", "bs58", "futures 0.3.8", - "ita-stf", "itp-api-client-types", "itp-node-api", - "itp-ocall-api", "itp-sgx-crypto", "itp-sgx-runtime-primitives", "itp-stf-executor", "itp-stf-primitives", + "itp-test", "itp-top-pool-author", "itp-types", - "itp-utils", "log", "parity-scale-codec", "sgx_tstd", "sgx_types", "sp-core", "sp-runtime", - "thiserror 1.0.9", + "thiserror", ] [[package]] name = "itc-parentchain-light-client" version = "0.9.0" dependencies = [ - "derive_more", "finality-grandpa", - "frame-system", - "hash-db 0.15.2", "itc-parentchain-test", "itp-ocall-api", "itp-sgx-io", @@ -1864,34 +1882,21 @@ dependencies = [ "itp-storage", "itp-test", "itp-types", - "lazy_static", "log", - "num-traits 0.2.15", "parity-scale-codec", "sgx_tstd", "sgx_types", - "sp-application-crypto", "sp-consensus-grandpa", - "sp-core", "sp-runtime", - "sp-trie", - "thiserror 1.0.9", + "thiserror", ] [[package]] name = "itc-parentchain-test" version = "0.9.0" dependencies = [ - "frame-support", - "frame-system", "itp-types", - "log", - "parity-scale-codec", - "scale-info", - "sp-core", - "sp-io", "sp-runtime", - "sp-std", ] [[package]] @@ -1902,11 +1907,10 @@ dependencies = [ "http", "http_req", "log", - "serde 1.0.188", - "serde_json 1.0.96", + "serde 1.0.192", + "serde_json 1.0.108", "sgx_tstd", - "sgx_types", - "thiserror 1.0.9", + "thiserror", "url", ] @@ -1921,11 +1925,9 @@ dependencies = [ "mio-extras", "rcgen", "rustls 0.19.0 (git+https://github.com/mesalock-linux/rustls?branch=mesalock_sgx)", - "sgx_crypto_helper", "sgx_tstd", - "sgx_types", "sp-core", - "thiserror 1.0.9", + "thiserror", "tungstenite", "webpki", "yasna", @@ -1940,6 +1942,15 @@ 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" @@ -1950,16 +1961,15 @@ dependencies = [ [[package]] name = "itoa" -version = "1.0.6" +version = "1.0.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "453ad9f582a441959e5f0d088b02ce04cfe8d51a8eaf077f12ac6d3e94164ca6" +checksum = "af150ab688ff2122fcef229be89cb50dd66af9e01a4ff320cc137eecc9bacc38" [[package]] name = "itp-api-client-types" version = "0.9.0" dependencies = [ "itp-types", - "sp-core", "sp-runtime", "substrate-api-client", ] @@ -1968,19 +1978,18 @@ dependencies = [ name = "itp-attestation-handler" version = "0.8.0" dependencies = [ - "arrayvec 0.7.2", + "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", + "itertools 0.10.5", "itp-ocall-api", "itp-settings", "itp-sgx-crypto", "itp-sgx-io", "itp-time-utils", - "itp-types", "log", "num-bigint", "parity-scale-codec", @@ -1992,8 +2001,7 @@ dependencies = [ "sgx_tstd", "sgx_types", "sp-core", - "sp-runtime", - "thiserror 1.0.9", + "thiserror", "webpki", "webpki-roots 0.21.0 (git+https://github.com/mesalock-linux/webpki-roots?branch=mesalock_sgx)", "yasna", @@ -2004,7 +2012,7 @@ name = "itp-component-container" version = "0.8.0" dependencies = [ "sgx_tstd", - "thiserror 1.0.9", + "thiserror", ] [[package]] @@ -2012,7 +2020,6 @@ name = "itp-enclave-bridge-storage" version = "0.9.0" dependencies = [ "itp-storage", - "itp-types", "parity-scale-codec", "sp-std", ] @@ -2033,14 +2040,13 @@ dependencies = [ "itp-node-api", "itp-nonce-cache", "itp-types", - "log", "parity-scale-codec", "sgx_tstd", "sgx_types", "sp-core", "sp-runtime", "substrate-api-client", - "thiserror 1.0.9", + "thiserror", ] [[package]] @@ -2056,7 +2062,7 @@ version = "0.8.0" dependencies = [ "sgx_tstd", "sgx_types", - "thiserror 1.0.9", + "thiserror", ] [[package]] @@ -2084,16 +2090,15 @@ version = "0.9.0" dependencies = [ "itp-node-api-metadata", "sgx_tstd", - "thiserror 1.0.9", + "thiserror", ] [[package]] name = "itp-nonce-cache" version = "0.8.0" dependencies = [ - "lazy_static", "sgx_tstd", - "thiserror 1.0.9", + "thiserror", ] [[package]] @@ -2116,7 +2121,7 @@ version = "0.9.0" dependencies = [ "lazy_static", "sgx_tstd", - "thiserror 1.0.9", + "thiserror", ] [[package]] @@ -2125,8 +2130,8 @@ version = "0.9.0" dependencies = [ "itp-types", "parity-scale-codec", - "serde 1.0.188", - "serde_json 1.0.96", + "serde 1.0.192", + "serde_json 1.0.108", "sgx_tstd", ] @@ -2140,13 +2145,11 @@ version = "0.9.0" dependencies = [ "aes", "derive_more", - "itp-settings", "itp-sgx-io", "itp-sgx-temp-dir", "log", "ofb", "parity-scale-codec", - "serde 1.0.118 (git+https://github.com/mesalock-linux/serde-sgx?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_crypto_helper", "sgx_rand", @@ -2165,7 +2168,7 @@ dependencies = [ "log", "parity-scale-codec", "postcard", - "serde 1.0.188", + "serde 1.0.192", "sgx_tstd", "sp-core", ] @@ -2209,19 +2212,17 @@ dependencies = [ "itp-stf-primitives", "itp-stf-state-handler", "itp-stf-state-observer", - "itp-storage", "itp-test", "itp-time-utils", "itp-top-pool-author", "itp-types", "log", "parity-scale-codec", - "sgx_crypto_helper", "sgx_tstd", "sgx_types", "sp-core", "sp-runtime", - "thiserror 1.0.9", + "thiserror", ] [[package]] @@ -2240,7 +2241,6 @@ name = "itp-stf-primitives" version = "0.9.0" dependencies = [ "derive_more", - "itp-hashing", "itp-sgx-runtime-primitives", "parity-scale-codec", "sp-core", @@ -2262,15 +2262,13 @@ dependencies = [ "itp-stf-state-observer", "itp-time-utils", "itp-types", - "lazy_static", "log", "parity-scale-codec", "rust-base58", - "sgx_tcrypto", "sgx_tstd", "sgx_types", "sp-core", - "thiserror 1.0.9", + "thiserror", ] [[package]] @@ -2279,9 +2277,8 @@ version = "0.9.0" dependencies = [ "itp-types", "log", - "parity-scale-codec", "sgx_tstd", - "thiserror 1.0.9", + "thiserror", ] [[package]] @@ -2299,23 +2296,13 @@ dependencies = [ "sp-runtime", "sp-std", "sp-trie", - "thiserror 1.0.9", -] - -[[package]] -name = "itp-teerex-storage" -version = "0.9.0" -dependencies = [ - "itp-storage", - "itp-types", - "sp-std", + "thiserror", ] [[package]] name = "itp-test" version = "0.9.0" dependencies = [ - "derive_more", "itp-enclave-bridge-storage", "itp-node-api", "itp-node-api-metadata-provider", @@ -2354,7 +2341,6 @@ dependencies = [ "byteorder 1.4.3", "derive_more", "itc-direct-rpc-server", - "itp-sgx-runtime-primitives", "itp-stf-primitives", "itp-types", "its-primitives", @@ -2362,13 +2348,11 @@ dependencies = [ "linked-hash-map", "log", "parity-scale-codec", - "serde 1.0.188", + "serde 1.0.192", "sgx_tstd", - "sgx_types", "sp-application-crypto", "sp-core", "sp-runtime", - "thiserror 1.0.9", ] [[package]] @@ -2384,33 +2368,31 @@ dependencies = [ "itp-test", "itp-top-pool", "itp-types", - "itp-utils", "jsonrpc-core", "log", "parity-scale-codec", "sgx_tstd", - "sgx_types", "sp-core", "sp-runtime", - "thiserror 1.0.9", ] [[package]] name = "itp-types" version = "0.9.0" dependencies = [ - "chrono 0.4.26", "enclave-bridge-primitives", "frame-system", "itp-sgx-runtime-primitives", + "itp-stf-primitives", + "itp-utils", "pallet-balances", "parity-scale-codec", - "primitive-types", - "serde 1.0.188", - "serde_json 1.0.96", + "serde 1.0.192", "sp-core", "sp-runtime", "sp-std", + "substrate-api-client", + "teeracle-primitives", "teerex-primitives", ] @@ -2426,13 +2408,11 @@ dependencies = [ name = "its-block-composer" version = "0.9.0" dependencies = [ - "ita-stf", "itp-node-api", "itp-settings", "itp-sgx-crypto", "itp-sgx-externalities", "itp-stf-executor", - "itp-stf-interface", "itp-stf-primitives", "itp-time-utils", "itp-top-pool-author", @@ -2445,7 +2425,7 @@ dependencies = [ "sgx_types", "sp-core", "sp-runtime", - "thiserror 1.0.9", + "thiserror", ] [[package]] @@ -2461,7 +2441,7 @@ dependencies = [ "sp-consensus-slots", "sp-core", "sp-runtime", - "thiserror 1.0.9", + "thiserror", ] [[package]] @@ -2469,7 +2449,6 @@ name = "its-consensus-aura" version = "0.9.0" dependencies = [ "finality-grandpa", - "frame-support", "ita-stf", "itc-parentchain-block-import-dispatcher", "itp-enclave-metrics", @@ -2504,6 +2483,7 @@ version = "0.9.0" dependencies = [ "fork-tree", "itc-parentchain-light-client", + "itertools 0.10.5", "itp-extrinsics-factory", "itp-import-queue", "itp-node-api-metadata", @@ -2512,6 +2492,7 @@ dependencies = [ "itp-settings", "itp-sgx-crypto", "itp-types", + "itp-utils", "its-block-verification", "its-primitives", "its-state", @@ -2520,7 +2501,7 @@ dependencies = [ "sgx_tstd", "sgx_types", "sp-runtime", - "thiserror 1.0.9", + "thiserror", ] [[package]] @@ -2529,7 +2510,6 @@ version = "0.9.0" dependencies = [ "derive_more", "itp-settings", - "itp-sgx-io", "itp-time-utils", "itp-types", "its-block-verification", @@ -2550,9 +2530,8 @@ dependencies = [ "itp-types", "parity-scale-codec", "scale-info", - "serde 1.0.188", + "serde 1.0.192", "sp-core", - "sp-io", "sp-runtime", "sp-std", ] @@ -2572,7 +2551,6 @@ dependencies = [ "parity-scale-codec", "rust-base58", "sgx_tstd", - "sgx_types", "sp-core", ] @@ -2600,12 +2578,10 @@ dependencies = [ "its-primitives", "log", "parity-scale-codec", - "serde 1.0.188", "sgx_tstd", "sp-core", "sp-io", - "sp-std", - "thiserror 1.0.9", + "thiserror", ] [[package]] @@ -2613,11 +2589,8 @@ name = "its-validateer-fetch" version = "0.9.0" dependencies = [ "derive_more", - "frame-support", "itp-enclave-bridge-storage", "itp-ocall-api", - "itp-storage", - "itp-teerex-storage", "itp-types", "its-primitives", "log", @@ -2625,7 +2598,6 @@ dependencies = [ "sp-core", "sp-runtime", "sp-std", - "thiserror 1.0.40", ] [[package]] @@ -2635,7 +2607,7 @@ source = "git+https://github.com/scs/jsonrpc?branch=no_std_v18#0faf53c491c3222b9 dependencies = [ "futures 0.3.8", "log", - "serde 1.0.118 (git+https://github.com/mesalock-linux/serde-sgx)", + "serde 1.0.118", "serde_derive 1.0.118", "serde_json 1.0.60 (git+https://github.com/mesalock-linux/serde-json-sgx)", ] @@ -2649,7 +2621,7 @@ dependencies = [ "cfg-if 1.0.0", "ecdsa", "elliptic-curve", - "sha2 0.10.6", + "sha2 0.10.7", ] [[package]] @@ -2678,9 +2650,9 @@ checksum = "830d08ce1d1d941e6b30645f1a0eb5643013d835ce3779a5fc208261dbe10f55" [[package]] name = "libc" -version = "0.2.146" +version = "0.2.147" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f92be4933c13fd498862a9e02a3055f8a8d9c039ce33db97306fd5a6caa7f29b" +checksum = "b4668fb0ea861c1df094127ac5f1da3409a82116a4ba74fca2e58ef927159bb3" [[package]] name = "libm" @@ -2701,7 +2673,7 @@ dependencies = [ "libsecp256k1-gen-ecmult", "libsecp256k1-gen-genmult", "rand 0.8.5", - "serde 1.0.188", + "serde 1.0.192", ] [[package]] @@ -2941,9 +2913,9 @@ dependencies = [ [[package]] name = "num-traits" -version = "0.2.15" +version = "0.2.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "578ede34cf02f8924ab9447f50c28075b4d3e5b269972345e7e0372b38c6cdcd" +checksum = "f30b0abd723be7e2ffca1272140fac1a2f084c77ec3e123c192b66af1ee9e6c2" dependencies = [ "autocfg 1.1.0", ] @@ -2999,20 +2971,6 @@ dependencies = [ "sp-std", ] -[[package]] -name = "pallet-authorship" -version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" -dependencies = [ - "frame-support", - "frame-system", - "impl-trait-for-tuples", - "parity-scale-codec", - "scale-info", - "sp-runtime", - "sp-std", -] - [[package]] name = "pallet-balances" version = "4.0.0-dev" @@ -3049,28 +3007,6 @@ dependencies = [ "sp-std", ] -[[package]] -name = "pallet-grandpa" -version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" -dependencies = [ - "frame-support", - "frame-system", - "log", - "pallet-authorship", - "pallet-session", - "parity-scale-codec", - "scale-info", - "sp-application-crypto", - "sp-consensus-grandpa", - "sp-core", - "sp-io", - "sp-runtime", - "sp-session", - "sp-staking", - "sp-std", -] - [[package]] name = "pallet-insecure-randomness-collective-flip" version = "4.0.0-dev" @@ -3087,37 +3023,18 @@ dependencies = [ [[package]] name = "pallet-parentchain" -version = "0.9.0" -source = "git+https://github.com/integritee-network/pallets.git?branch=sdk-v0.12.0-polkadot-v0.9.42#eaf611b79bc9d56b20c155150e99b549bf98436b" -dependencies = [ - "frame-support", - "frame-system", - "log", - "parity-scale-codec", - "scale-info", - "sp-core", - "sp-io", - "sp-runtime", - "sp-std", -] - -[[package]] -name = "pallet-session" -version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +version = "0.11.0" +source = "git+https://github.com/integritee-network/pallets.git?branch=sdk-v0.12.11-polkadot-v0.9.42#094b1e982b4637ebfbf5afb985100417215d49a0" dependencies = [ "frame-support", "frame-system", - "impl-trait-for-tuples", "log", - "pallet-timestamp", + "pallet-balances", "parity-scale-codec", "scale-info", "sp-core", "sp-io", "sp-runtime", - "sp-session", - "sp-staking", "sp-std", ] @@ -3180,24 +3097,24 @@ dependencies = [ [[package]] name = "parity-scale-codec" -version = "3.6.5" +version = "3.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0dec8a8073036902368c2cdc0387e85ff9a37054d7e7c98e592145e0c92cd4fb" +checksum = "dd8e946cc0cc711189c0b0249fb8b599cbeeab9784d83c415719368bb8d4ac64" dependencies = [ - "arrayvec 0.7.2", + "arrayvec 0.7.4", "bitvec", "byte-slice-cast", "bytes 1.4.0", "impl-trait-for-tuples", "parity-scale-codec-derive", - "serde 1.0.188", + "serde 1.0.192", ] [[package]] name = "parity-scale-codec-derive" -version = "3.6.5" +version = "3.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "312270ee71e1cd70289dacf597cab7b207aa107d2f28191c2ae45b2ece18a260" +checksum = "2a296c3079b5fefbc499e1de58dc26c09b1b9a5952d26694ee89f04a43ebbb3e" dependencies = [ "proc-macro-crate", "proc-macro2", @@ -3207,9 +3124,9 @@ dependencies = [ [[package]] name = "paste" -version = "1.0.12" +version = "1.0.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9f746c4065a8fa3fe23974dd82f15431cc8d40779821001404d10d2e79ca7d79" +checksum = "de3145af08024dea9fa9914f381a17b8fc6034dfb00f3a84013f7ff43f29ed4c" [[package]] name = "pem" @@ -3229,9 +3146,9 @@ source = "git+https://github.com/mesalock-linux/rust-url-sgx?tag=sgx_1.1.3#23832 [[package]] name = "pin-project-lite" -version = "0.2.9" +version = "0.2.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e0a7ae3ac2f1173085d398531c705756c94a4c56843785df85a60c1a0afac116" +checksum = "8afb450f006bf6385ca15ef45d71d2288452bc3683ce2e2cacc0d18e4be60b58" [[package]] name = "pin-utils" @@ -3246,7 +3163,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a25c0b0ae06fcffe600ad392aabfa535696c8973f2253d9ac83171924c58a858" dependencies = [ "postcard-cobs", - "serde 1.0.188", + "serde 1.0.192", ] [[package]] @@ -3328,14 +3245,14 @@ checksum = "0e99670bafb56b9a106419397343bdbc8b8742c3cc449fec6345f86173f47cd4" dependencies = [ "proc-macro2", "quote 1.0.33", - "syn 2.0.33", + "syn 2.0.39", ] [[package]] name = "proc-macro2" -version = "1.0.67" +version = "1.0.69" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3d433d9f1a3e8c1263d9456598b16fec66f4acc9a74dacffd35c7bb09b3a1328" +checksum = "134c189feb4956b20f6f547d2cf727d4c0fe06722b20a0eec87ed445a97f92da" dependencies = [ "unicode-ident", ] @@ -3440,22 +3357,22 @@ dependencies = [ [[package]] name = "ref-cast" -version = "1.0.16" +version = "1.0.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f43faa91b1c8b36841ee70e97188a869d37ae21759da6846d4be66de5bf7b12c" +checksum = "61ef7e18e8841942ddb1cf845054f8008410030a3997875d9e49b7a363063df1" dependencies = [ "ref-cast-impl", ] [[package]] name = "ref-cast-impl" -version = "1.0.16" +version = "1.0.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8d2275aab483050ab2a7364c1a46604865ee7d6906684e08db0f090acf74f9e7" +checksum = "2dfaf0c85b766276c797f3791f5bc6d5bd116b41d53049af2789666b0c0bc9fa" dependencies = [ "proc-macro2", "quote 1.0.33", - "syn 2.0.33", + "syn 2.0.39", ] [[package]] @@ -3472,13 +3389,25 @@ dependencies = [ [[package]] name = "regex" -version = "1.8.4" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2eae68fc220f7cf2532e4494aded17545fce192d59cd996e0fe7887f4ceb575" +dependencies = [ + "aho-corasick 1.0.2", + "memchr 2.5.0", + "regex-automata", + "regex-syntax 0.7.4", +] + +[[package]] +name = "regex-automata" +version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d0ab3ca65655bb1e41f2a8c8cd662eb4fb035e67c3f78da1d61dffe89d07300f" +checksum = "39354c10dd07468c2e73926b23bb9c2caca74c5501e38a35da70406f1d923310" dependencies = [ "aho-corasick 1.0.2", "memchr 2.5.0", - "regex-syntax 0.7.2", + "regex-syntax 0.7.4", ] [[package]] @@ -3491,9 +3420,9 @@ dependencies = [ [[package]] name = "regex-syntax" -version = "0.7.2" +version = "0.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "436b050e76ed2903236f032a59761c1eb99e1b0aead2c257922771dab1fc8c78" +checksum = "e5ea92a5b6195c6ef2a0295ea818b312502c6fc94dde986c5553242e18fd4ce2" [[package]] name = "rfc6979" @@ -3568,7 +3497,7 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bfa0f585226d2e68097d4f95d113b15b83a82e819ab25717ec0590d9584ef366" dependencies = [ - "semver 1.0.17", + "semver 1.0.18", ] [[package]] @@ -3612,9 +3541,9 @@ dependencies = [ [[package]] name = "ryu" -version = "1.0.13" +version = "1.0.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f91339c0467de62360649f8d3e185ca8de4224ff281f66000de5eb2a77a79041" +checksum = "1ad4cc8da4ef723ed60bced201181d83791ad433213d8c24efffda1eec85d741" [[package]] name = "safe-mix" @@ -3633,7 +3562,7 @@ checksum = "036575c29af9b6e4866ffb7fa055dbf623fe7a9cc159b33786de6013a6969d89" dependencies = [ "parity-scale-codec", "scale-info", - "serde 1.0.188", + "serde 1.0.192", ] [[package]] @@ -3647,7 +3576,7 @@ dependencies = [ "scale-bits", "scale-decode-derive", "scale-info", - "smallvec 1.10.0", + "smallvec 1.11.0", ] [[package]] @@ -3674,7 +3603,7 @@ dependencies = [ "scale-bits", "scale-encode-derive", "scale-info", - "smallvec 1.10.0", + "smallvec 1.11.0", ] [[package]] @@ -3692,23 +3621,23 @@ dependencies = [ [[package]] name = "scale-info" -version = "2.7.0" +version = "2.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b569c32c806ec3abdf3b5869fb8bf1e0d275a7c1c9b0b05603d9464632649edf" +checksum = "7f7d66a1128282b7ef025a8ead62a4a9fcf017382ec53b8ffbf4d7bf77bd3c60" dependencies = [ "bitvec", "cfg-if 1.0.0", "derive_more", "parity-scale-codec", "scale-info-derive", - "serde 1.0.188", + "serde 1.0.192", ] [[package]] name = "scale-info-derive" -version = "2.6.0" +version = "2.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "53012eae69e5aa5c14671942a5dd47de59d4cdcff8532a6dd0e081faf1119482" +checksum = "abf2c68b89cafb3b8d918dd07b42be0da66ff202cf1155c5739a4e0c1ea0dc19" dependencies = [ "proc-macro-crate", "proc-macro2", @@ -3744,9 +3673,9 @@ dependencies = [ [[package]] name = "sec1" -version = "0.7.2" +version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0aec48e813d6b90b15f0b8948af3c63483992dee44c03e9930b3eebdabe046e" +checksum = "d3e97a565f76233a6003f9f5c54be1d9c5bdfa3eccfb189469f11ec4901c47dc" dependencies = [ "base16ct", "der", @@ -3793,9 +3722,9 @@ dependencies = [ [[package]] name = "semver" -version = "1.0.17" +version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bebd363326d05ec3e2f532ab7660680f3b02130d780c299bca73469d521bc0ed" +checksum = "b0293b4b29daaf487284529cc2f5675b8e57c61f70167ba415a463651fd6a918" [[package]] name = "semver-parser" @@ -3803,14 +3732,6 @@ version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "388a1df253eca08550bef6c72392cfe7c30914bf41df5269b68cbd6ff8f570a3" -[[package]] -name = "serde" -version = "1.0.118" -source = "git+https://github.com/mesalock-linux/serde-sgx?tag=sgx_1.1.3#db0226f1d5d70fca6b96af2c285851502204e21c" -dependencies = [ - "sgx_tstd", -] - [[package]] name = "serde" version = "1.0.118" @@ -3822,11 +3743,11 @@ dependencies = [ [[package]] name = "serde" -version = "1.0.188" +version = "1.0.192" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf9e0fcba69a370eed61bcf2b728575f726b50b55cba78064753d708ddc7549e" +checksum = "bca2a08484b285dcb282d0f67b26cadc0df8b19f8c12502c13d966bf9482f001" dependencies = [ - "serde_derive 1.0.188", + "serde_derive 1.0.192", ] [[package]] @@ -3834,7 +3755,7 @@ 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 (git+https://github.com/mesalock-linux/serde-sgx)", + "serde 1.0.118", "serde_derive 1.0.118", ] @@ -3850,13 +3771,13 @@ dependencies = [ [[package]] name = "serde_derive" -version = "1.0.188" +version = "1.0.192" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4eca7ac642d82aa35b60049a6eccb4be6be75e599bd2e9adb5f875a737654af2" +checksum = "d6c7207fbec9faa48073f3e3074cbe553af6ea512d7c21ba46e434e70ea9fbc1" dependencies = [ "proc-macro2", "quote 1.0.33", - "syn 2.0.33", + "syn 2.0.39", ] [[package]] @@ -3867,7 +3788,7 @@ dependencies = [ "indexmap 1.6.1", "itoa 0.4.5", "ryu", - "serde 1.0.118 (git+https://github.com/mesalock-linux/serde-sgx)", + "serde 1.0.118", "sgx_tstd", ] @@ -3878,30 +3799,30 @@ source = "git+https://github.com/mesalock-linux/serde-json-sgx#380893814ad2a0577 dependencies = [ "itoa 0.4.5", "ryu", - "serde 1.0.118 (git+https://github.com/mesalock-linux/serde-sgx)", + "serde 1.0.118", "sgx_tstd", ] [[package]] name = "serde_json" -version = "1.0.96" +version = "1.0.108" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "057d394a50403bcac12672b2b18fb387ab6d289d957dab67dd201875391e52f1" +checksum = "3d1c7e3eac408d115102c4c24ad393e0821bb3a5df4d506a80f85f7a742a526b" dependencies = [ - "itoa 1.0.6", + "itoa 1.0.9", "ryu", - "serde 1.0.188", + "serde 1.0.192", ] [[package]] name = "sgx_alloc" version = "1.1.6" -source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#f1776a7cec1caab2959813f87bb4924805b92011" +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#f1776a7cec1caab2959813f87bb4924805b92011" +source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#1b1d03376056321441ef99716aa0888bd5ef19f7" dependencies = [ "cc", "sgx_build_helper", @@ -3911,15 +3832,15 @@ dependencies = [ [[package]] name = "sgx_build_helper" version = "1.1.6" -source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#f1776a7cec1caab2959813f87bb4924805b92011" +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#f1776a7cec1caab2959813f87bb4924805b92011" +source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#1b1d03376056321441ef99716aa0888bd5ef19f7" dependencies = [ - "itertools", - "serde 1.0.118 (git+https://github.com/mesalock-linux/serde-sgx)", + "itertools 0.11.0", + "serde 1.0.118", "serde-big-array", "serde_derive 1.0.118", "sgx_tcrypto", @@ -3930,12 +3851,12 @@ dependencies = [ [[package]] name = "sgx_demangle" version = "1.1.6" -source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#f1776a7cec1caab2959813f87bb4924805b92011" +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#f1776a7cec1caab2959813f87bb4924805b92011" +source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#1b1d03376056321441ef99716aa0888bd5ef19f7" dependencies = [ "sgx_types", ] @@ -3943,7 +3864,7 @@ dependencies = [ [[package]] name = "sgx_rand" version = "1.1.6" -source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#f1776a7cec1caab2959813f87bb4924805b92011" +source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#1b1d03376056321441ef99716aa0888bd5ef19f7" dependencies = [ "sgx_trts", "sgx_tstd", @@ -3953,7 +3874,7 @@ dependencies = [ [[package]] name = "sgx_serialize" version = "1.1.6" -source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#f1776a7cec1caab2959813f87bb4924805b92011" +source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#1b1d03376056321441ef99716aa0888bd5ef19f7" dependencies = [ "sgx_tstd", ] @@ -3961,7 +3882,7 @@ dependencies = [ [[package]] name = "sgx_serialize_derive" version = "1.1.6" -source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#f1776a7cec1caab2959813f87bb4924805b92011" +source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#1b1d03376056321441ef99716aa0888bd5ef19f7" dependencies = [ "quote 0.3.15", "sgx_serialize_derive_internals", @@ -3971,7 +3892,7 @@ dependencies = [ [[package]] name = "sgx_serialize_derive_internals" version = "1.1.6" -source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#f1776a7cec1caab2959813f87bb4924805b92011" +source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#1b1d03376056321441ef99716aa0888bd5ef19f7" dependencies = [ "syn 0.11.11", ] @@ -3979,7 +3900,7 @@ dependencies = [ [[package]] name = "sgx_tcrypto" version = "1.1.6" -source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#f1776a7cec1caab2959813f87bb4924805b92011" +source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#1b1d03376056321441ef99716aa0888bd5ef19f7" dependencies = [ "sgx_types", ] @@ -3987,7 +3908,7 @@ dependencies = [ [[package]] name = "sgx_tcrypto_helper" version = "1.1.6" -source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#f1776a7cec1caab2959813f87bb4924805b92011" +source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#1b1d03376056321441ef99716aa0888bd5ef19f7" dependencies = [ "sgx_crypto_helper", ] @@ -3995,7 +3916,7 @@ dependencies = [ [[package]] name = "sgx_tprotected_fs" version = "1.1.6" -source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#f1776a7cec1caab2959813f87bb4924805b92011" +source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#1b1d03376056321441ef99716aa0888bd5ef19f7" dependencies = [ "sgx_trts", "sgx_types", @@ -4004,7 +3925,7 @@ dependencies = [ [[package]] name = "sgx_trts" version = "1.1.6" -source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#f1776a7cec1caab2959813f87bb4924805b92011" +source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#1b1d03376056321441ef99716aa0888bd5ef19f7" dependencies = [ "sgx_libc", "sgx_types", @@ -4013,7 +3934,7 @@ dependencies = [ [[package]] name = "sgx_tse" version = "1.1.6" -source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#f1776a7cec1caab2959813f87bb4924805b92011" +source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#1b1d03376056321441ef99716aa0888bd5ef19f7" dependencies = [ "sgx_types", ] @@ -4021,7 +3942,7 @@ dependencies = [ [[package]] name = "sgx_tseal" version = "1.1.6" -source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#f1776a7cec1caab2959813f87bb4924805b92011" +source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#1b1d03376056321441ef99716aa0888bd5ef19f7" dependencies = [ "sgx_tcrypto", "sgx_trts", @@ -4032,7 +3953,7 @@ dependencies = [ [[package]] name = "sgx_tstd" version = "1.1.6" -source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#f1776a7cec1caab2959813f87bb4924805b92011" +source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#1b1d03376056321441ef99716aa0888bd5ef19f7" dependencies = [ "hashbrown_tstd", "sgx_alloc", @@ -4048,7 +3969,7 @@ dependencies = [ [[package]] name = "sgx_tunittest" version = "1.1.6" -source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#f1776a7cec1caab2959813f87bb4924805b92011" +source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#1b1d03376056321441ef99716aa0888bd5ef19f7" dependencies = [ "sgx_tstd", ] @@ -4056,12 +3977,12 @@ dependencies = [ [[package]] name = "sgx_types" version = "1.1.6" -source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#f1776a7cec1caab2959813f87bb4924805b92011" +source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#1b1d03376056321441ef99716aa0888bd5ef19f7" [[package]] name = "sgx_unwind" version = "1.1.6" -source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#f1776a7cec1caab2959813f87bb4924805b92011" +source = "git+https://github.com/apache/incubator-teaclave-sgx-sdk?branch=master#1b1d03376056321441ef99716aa0888bd5ef19f7" dependencies = [ "sgx_build_helper", ] @@ -4114,9 +4035,9 @@ dependencies = [ [[package]] name = "sha2" -version = "0.10.6" +version = "0.10.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "82e6b795fe2e3b1e845bafcb27aa35405c4d47cdfc92af5fc8d3002f76cebdc0" +checksum = "479fb9d862239e610720565ca91403019f2f00410f1864c5aa7479b950a76ed8" dependencies = [ "cfg-if 1.0.0", "cpufeatures", @@ -4162,8 +4083,8 @@ source = "git+https://github.com/BESTenergytrade/simplyr-lib.git?branch=cI/usize dependencies = [ "libm", "parity-scale-codec", - "serde 1.0.188", - "serde_json 1.0.96", + "serde 1.0.192", + "serde_json 1.0.108", ] [[package]] @@ -4193,9 +4114,9 @@ dependencies = [ [[package]] name = "smallvec" -version = "1.10.0" +version = "1.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a507befe795404456341dfab10cef66ead4c041f62b8b11bbb92bffe5d0953e0" +checksum = "62bb4feee49fdd9f707ef802e22365a35de4b7b299de4763d44bfea899442ff9" [[package]] name = "sp-api" @@ -4224,7 +4145,7 @@ dependencies = [ "proc-macro-crate", "proc-macro2", "quote 1.0.33", - "syn 2.0.33", + "syn 2.0.39", ] [[package]] @@ -4245,7 +4166,7 @@ version = "6.0.0" source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "integer-sqrt", - "num-traits 0.2.15", + "num-traits 0.2.16", "parity-scale-codec", "scale-info", "sp-std", @@ -4346,7 +4267,7 @@ dependencies = [ "blake2b_simd 1.0.1", "byteorder 1.4.3", "digest 0.10.7", - "sha2 0.10.6", + "sha2 0.10.7", "sha3 0.10.8", "sp-std", "twox-hash", @@ -4360,7 +4281,7 @@ dependencies = [ "proc-macro2", "quote 1.0.33", "sp-core-hashing", - "syn 2.0.33", + "syn 2.0.39", ] [[package]] @@ -4370,7 +4291,7 @@ source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.4 dependencies = [ "proc-macro2", "quote 1.0.33", - "syn 2.0.33", + "syn 2.0.39", ] [[package]] @@ -4400,21 +4321,12 @@ dependencies = [ name = "sp-io" version = "7.0.0" dependencies = [ - "environmental 1.1.3", - "hash-db 0.15.2", "itp-sgx-externalities", "libsecp256k1", "log", "parity-scale-codec", "sgx_tstd", - "sgx_types", "sp-core", - "sp-runtime-interface", - "sp-std", - "sp-tracing", - "sp-wasm-interface", - "tracing", - "tracing-core", ] [[package]] @@ -4485,7 +4397,7 @@ dependencies = [ "proc-macro-crate", "proc-macro2", "quote 1.0.33", - "syn 2.0.33", + "syn 2.0.39", ] [[package]] @@ -4596,7 +4508,7 @@ dependencies = [ "parity-scale-codec", "proc-macro2", "quote 1.0.33", - "syn 2.0.33", + "syn 2.0.39", ] [[package]] @@ -4616,7 +4528,7 @@ source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.4 dependencies = [ "parity-scale-codec", "scale-info", - "smallvec 1.10.0", + "smallvec 1.11.0", "sp-arithmetic", "sp-core", "sp-debug-derive", @@ -4631,15 +4543,15 @@ checksum = "6e63cff320ae2c57904679ba7cb63280a3dc4613885beafb148ee7bf9aa9042d" [[package]] name = "ss58-registry" -version = "1.40.0" +version = "1.41.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eb47a8ad42e5fc72d5b1eb104a5546937eaf39843499948bb666d6e93c62423b" +checksum = "bfc443bad666016e012538782d9e3006213a7db43e9fb1dda91657dc06a6fa08" dependencies = [ "Inflector", "proc-macro2", "quote 1.0.33", - "serde 1.0.188", - "serde_json 1.0.96", + "serde 1.0.192", + "serde_json 1.0.108", "unicode-xid 0.2.4", ] @@ -4658,7 +4570,7 @@ checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623" [[package]] name = "substrate-api-client" version = "0.14.0" -source = "git+https://github.com/scs/substrate-api-client.git?branch=polkadot-v0.9.42-tag-v0.14.0#e4ed74b0fb6c2fd5585f55c2702b97b56d99c7f6" +source = "git+https://github.com/scs/substrate-api-client.git?branch=polkadot-v0.9.42-tag-v0.14.0#d31ce7684a60a55b943b3355b2dacc6d0edcc371" dependencies = [ "ac-compose-macros", "ac-node-api", @@ -4670,8 +4582,8 @@ dependencies = [ "log", "maybe-async", "parity-scale-codec", - "serde 1.0.188", - "serde_json 1.0.96", + "serde 1.0.192", + "serde_json 1.0.108", "sp-core", "sp-runtime", "sp-runtime-interface", @@ -4717,9 +4629,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.33" +version = "2.0.39" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9caece70c63bfba29ec2fed841a09851b14a235c60010fa4de58089b6c025668" +checksum = "23e78b90f2fcf45d3e842032ce32e3f2d1545ba6636271dcbf24fa306d87be7a" dependencies = [ "proc-macro2", "quote 1.0.33", @@ -4741,17 +4653,27 @@ version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369" +[[package]] +name = "teeracle-primitives" +version = "0.1.0" +source = "git+https://github.com/integritee-network/pallets.git?branch=sdk-v0.12.11-polkadot-v0.9.42#094b1e982b4637ebfbf5afb985100417215d49a0" +dependencies = [ + "common-primitives", + "sp-std", + "substrate-fixed", +] + [[package]] name = "teerex-primitives" version = "0.1.0" -source = "git+https://github.com/integritee-network/pallets.git?branch=sdk-v0.12.0-polkadot-v0.9.42#eaf611b79bc9d56b20c155150e99b549bf98436b" +source = "git+https://github.com/integritee-network/pallets.git?branch=sdk-v0.12.11-polkadot-v0.9.42#094b1e982b4637ebfbf5afb985100417215d49a0" dependencies = [ "common-primitives", "derive_more", "log", "parity-scale-codec", "scale-info", - "serde 1.0.188", + "serde 1.0.192", "sp-core", "sp-runtime", "sp-std", @@ -4771,16 +4693,7 @@ version = "1.0.9" source = "git+https://github.com/mesalock-linux/thiserror-sgx?tag=sgx_1.1.3#c2f806b88616e06aab0af770366a76885d974fdc" dependencies = [ "sgx_tstd", - "thiserror-impl 1.0.9", -] - -[[package]] -name = "thiserror" -version = "1.0.40" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "978c9a314bd8dc99be594bc3c175faaa9794be04a5a5e153caba6915336cebac" -dependencies = [ - "thiserror-impl 1.0.40", + "thiserror-impl", ] [[package]] @@ -4793,17 +4706,6 @@ dependencies = [ "syn 1.0.109", ] -[[package]] -name = "thiserror-impl" -version = "1.0.40" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f9456a42c5b0d803c8cd86e73dd7cc9edd429499f37a3550d286d5e86720569f" -dependencies = [ - "proc-macro2", - "quote 1.0.33", - "syn 2.0.33", -] - [[package]] name = "thread_local" version = "1.0.0" @@ -4824,17 +4726,17 @@ dependencies = [ [[package]] name = "toml_datetime" -version = "0.6.2" +version = "0.6.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a76a9312f5ba4c2dec6b9161fdf25d87ad8a09256ccea5a556fef03c706a10f" +checksum = "7cda73e2f1397b1262d6dfdcef8aafae14d1de7748d66822d3bfeeb6d03e5e4b" [[package]] name = "toml_edit" -version = "0.19.10" +version = "0.19.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2380d56e8670370eee6566b0bfd4265f65b3f432e8c6d85623f728d4fa31f739" +checksum = "f8123f27e969974a3dfba720fdb560be359f57b44302d280ba72e76a74480e8a" dependencies = [ - "indexmap 1.9.3", + "indexmap 2.0.0", "toml_datetime", "winnow", ] @@ -4865,7 +4767,7 @@ dependencies = [ "hash-db 0.16.0", "hashbrown 0.13.2", "log", - "smallvec 1.10.0", + "smallvec 1.11.0", ] [[package]] @@ -4908,7 +4810,7 @@ dependencies = [ "rustls 0.19.0 (git+https://github.com/mesalock-linux/rustls?tag=sgx_1.1.3)", "sgx_tstd", "sha1", - "thiserror 1.0.9", + "thiserror", "url", "utf-8", "webpki", @@ -4973,9 +4875,9 @@ dependencies = [ [[package]] name = "unicode-ident" -version = "1.0.9" +version = "1.0.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b15811caf2415fb889178633e7724bad2509101cde276048e013b9def5e51fa0" +checksum = "301abaae475aa91687eb82514b328ab47a211a533026cb25fc3e519b86adfc3c" [[package]] name = "unicode-normalization" @@ -5034,6 +4936,12 @@ 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" @@ -5064,9 +4972,9 @@ dependencies = [ [[package]] name = "winnow" -version = "0.4.6" +version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61de7bac303dc551fe038e2b3cef0f571087a47571ea6e79a87692ac99b99699" +checksum = "25b5872fa2e10bd067ae946f927e726d7d603eaeb6e02fa6a350e0722d2b8c11" dependencies = [ "memchr 2.5.0", ] @@ -5108,5 +5016,15 @@ checksum = "ce36e65b0d2999d2aafac989fb249189a141aee1f53c612c1f37d72631959f69" dependencies = [ "proc-macro2", "quote 1.0.33", - "syn 2.0.33", + "syn 2.0.39", ] + +[[patch.unused]] +name = "getrandom" +version = "0.2.3" +source = "git+https://github.com/integritee-network/getrandom-sgx?branch=update-v2.3#0a4af01fe1df0e6200192e7a709fd18da413466e" + +[[patch.unused]] +name = "ring" +version = "0.16.20" +source = "git+https://github.com/betrusted-io/ring-xous?branch=0.16.20-cleanup#4296c2e7904898766cf7d8d589759a129794783b" diff --git a/enclave-runtime/Cargo.toml b/enclave-runtime/Cargo.toml index 83fcbe4e6f..84e0d5be00 100644 --- a/enclave-runtime/Cargo.toml +++ b/enclave-runtime/Cargo.toml @@ -1,10 +1,11 @@ [package] name = "enclave-runtime" -version = "0.12.0" +version = "0.12.11" authors = ["Integritee AG "] edition = "2021" [workspace] +resolver = "2" members = [] [lib] @@ -79,8 +80,6 @@ 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 = { tag = "sgx_1.1.3", git = "https://github.com/mesalock-linux/serde-sgx", features = ["alloc", "mesalock_sgx"] } -serde_derive = { git = "https://github.com/mesalock-linux/serde-sgx" } 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" } @@ -88,22 +87,25 @@ webpki = { git = "https://github.com/mesalock-linux/webpki", branch = "mesalock_ 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" } +enclave-bridge-primitives = { default-features = false, git = "https://github.com/integritee-network/pallets.git", branch = "sdk-v0.12.11-polkadot-v0.9.42" } multibase = { default-features = false, git = "https://github.com/whalelephant/rust-multibase", branch = "nstd" } -teerex-primitives = { default-features = false, git = "https://github.com/integritee-network/pallets.git", branch = "sdk-v0.12.0-polkadot-v0.9.42" } +teerex-primitives = { default-features = false, git = "https://github.com/integritee-network/pallets.git", branch = "sdk-v0.12.11-polkadot-v0.9.42" } # local deps ita-oracle = { path = "../app-libs/oracle", default-features = false, optional = true, features = ["sgx"] } +ita-parentchain-interface = { path = "../app-libs/parentchain-interface", default-features = false, features = ["sgx"] } ita-sgx-runtime = { path = "../app-libs/sgx-runtime", default-features = false } ita-stf = { path = "../app-libs/stf", default-features = false, features = ["sgx"] } itc-direct-rpc-server = { path = "../core/direct-rpc-server", default-features = false, features = ["sgx"] } itc-offchain-worker-executor = { path = "../core/offchain-worker-executor", default-features = false, features = ["sgx"] } itc-parentchain = { path = "../core/parentchain/parentchain-crate", default-features = false, features = ["sgx"] } +itc-parentchain-block-import-dispatcher = { path = "../core/parentchain/block-import-dispatcher", default-features = false, features = ["sgx"] } +itc-parentchain-block-importer = { path = "../core/parentchain/block-importer", default-features = false, features = ["sgx"] } itc-parentchain-test = { path = "../core/parentchain/test", default-features = false } itc-tls-websocket-server = { path = "../core/tls-websocket-server", default-features = false, features = ["sgx"] } itp-attestation-handler = { path = "../core-primitives/attestation-handler", default-features = false, features = ["sgx"] } itp-component-container = { path = "../core-primitives/component-container", default-features = false, features = ["sgx"] } itp-extrinsics-factory = { path = "../core-primitives/extrinsics-factory", default-features = false, features = ["sgx"] } -itp-hashing = { path = "../core-primitives/hashing", default-features = false } itp-import-queue = { path = "../core-primitives/import-queue", default-features = false, features = ["sgx"] } itp-node-api = { path = "../core-primitives/node-api", default-features = false, features = ["sgx"] } itp-node-api-metadata = { path = "../core-primitives/node-api/metadata", default-features = false } @@ -114,14 +116,12 @@ itp-rpc = { path = "../core-primitives/rpc", default-features = false, features itp-settings = { path = "../core-primitives/settings" } itp-sgx-crypto = { path = "../core-primitives/sgx/crypto", default-features = false, features = ["sgx"] } itp-sgx-externalities = { path = "../core-primitives/substrate-sgx/externalities", default-features = false, features = ["sgx"] } -itp-sgx-io = { path = "../core-primitives/sgx/io", default-features = false, features = ["sgx"] } itp-stf-executor = { path = "../core-primitives/stf-executor", default-features = false, features = ["sgx"] } itp-stf-interface = { path = "../core-primitives/stf-interface", default-features = false } itp-stf-primitives = { path = "../core-primitives/stf-primitives", default-features = false } itp-stf-state-handler = { path = "../core-primitives/stf-state-handler", default-features = false, features = ["sgx"] } itp-stf-state-observer = { path = "../core-primitives/stf-state-observer", default-features = false, features = ["sgx"] } itp-storage = { path = "../core-primitives/storage", default-features = false, features = ["sgx"] } -itp-teerex-storage = { path = "../core-primitives/teerex-storage", default-features = false } itp-test = { path = "../core-primitives/test", default-features = false, optional = true } itp-time-utils = { path = "../core-primitives/time-utils", default-features = false, features = ["sgx"] } itp-top-pool = { path = "../core-primitives/top-pool", default-features = false, features = ["sgx"] } @@ -137,7 +137,6 @@ frame-support = { default-features = false, git = "https://github.com/paritytech frame-system = { optional = true, default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } sp-core = { default-features = false, features = ["full_crypto"], git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } sp-runtime = { default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } -sp-std = { default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } # test-deps itp-sgx-temp-dir = { version = "0.1", default-features = false, optional = true, path = "../core-primitives/sgx/temp-dir" } @@ -146,6 +145,7 @@ itp-sgx-temp-dir = { version = "0.1", default-features = false, optional = true, env_logger = { git = "https://github.com/integritee-network/env_logger-sgx" } getrandom = { git = "https://github.com/integritee-network/getrandom-sgx", branch = "update-v2.3" } 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" } @@ -153,9 +153,6 @@ log = { git = "https://github.com/integritee-network/log-sgx" } [patch."https://github.com/paritytech/substrate"] sp-io = { path = "../core-primitives/substrate-sgx/sp-io" } -#[patch."https://github.com/integritee-network/frontier"] -#pallet-evm = { path = "../../frontier/frame/evm"} - [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" } @@ -173,13 +170,21 @@ sgx_tstd = { version = "1.1.6", git = "https://github.com/apache/incubator-teacl 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" } -#[patch."https://github.com/scs/substrate-api-client"] -#substrate-api-client = { path = "../../../scs/substrate-api-client" } +#[patch."https://github.com/integritee-network/parachain"] +#integritee-runtime = { path = "../../parachain/polkadot-parachains/integritee-runtime"} +#parachains-common = { path = "../../parachain/polkadot-parachains/common"} #[patch."https://github.com/integritee-network/pallets.git"] -#pallet-parentchain = { path = "../../pallets/parentchain" } -#itp-types = { path = "../../pallets/primitives/types" } -#itp-utils = { path = "../../pallets/primitives/utils" } - -#[patch."https://github.com/integritee-network/http_req"] -#http_req-sgx = { package = "http_req", path = '../../http_req' } +#pallet-claims = { git = "https://github.com/integritee-network//pallets", branch = "ab/parentchian-set-timestamp" } +#pallet-enclave-bridge = { git = "https://github.com/integritee-network//pallets", branch = "ab/parentchian-set-timestamp" } +#pallet-teerex = { git = "https://github.com/integritee-network//pallets", branch = "ab/parentchian-set-timestamp" } +#pallet-sidechain = { git = "https://github.com/integritee-network//pallets", branch = "ab/parentchian-set-timestamp" } +#pallet-parentchain = { git = "https://github.com/integritee-network//pallets", branch = "ab/parentchian-set-timestamp" } +#sgx-verify = { git = "https://github.com/integritee-network//pallets", branch = "ab/parentchian-set-timestamp" } +#pallet-teeracle = { git = "https://github.com/integritee-network//pallets", branch = "ab/parentchian-set-timestamp" } +#test-utils = { git = "https://github.com/integritee-network//pallets", branch = "ab/parentchian-set-timestamp" } +#claims-primitives = { git = "https://github.com/integritee-network//pallets", branch = "ab/parentchian-set-timestamp" } +#enclave-bridge-primitives = { git = "https://github.com/integritee-network//pallets", branch = "ab/parentchian-set-timestamp" } +#teerex-primitives = { git = "https://github.com/integritee-network//pallets", branch = "ab/parentchian-set-timestamp" } +#teeracle-primitives = { git = "https://github.com/integritee-network//pallets", branch = "ab/parentchian-set-timestamp" } +#common-primitives = { git = "https://github.com/integritee-network//pallets", branch = "ab/parentchian-set-timestamp" } diff --git a/enclave-runtime/Enclave.edl b/enclave-runtime/Enclave.edl index 544e988b1a..d633ac0a38 100644 --- a/enclave-runtime/Enclave.edl +++ b/enclave-runtime/Enclave.edl @@ -59,20 +59,29 @@ enclave { ); public sgx_status_t init_proxied_shard_vault( - [in, size=shard_size] uint8_t* shard, uint32_t shard_size + [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=funding_balance_size] uint8_t* funding_balance, uint32_t funding_balance_size ); - public sgx_status_t trigger_parentchain_block_import( - [in, size=parentchain_id_size] uint8_t* parentchain_id, uint32_t parentchain_id_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 execute_trusted_calls(); 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 + [in, size=parentchain_id_size] uint8_t* parentchain_id, uint32_t parentchain_id_size, + int immediate_import ); public sgx_status_t set_nonce( @@ -100,7 +109,8 @@ enclave { 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_size] uint8_t* unchecked_extrinsic, uint32_t unchecked_extrinsic_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( @@ -113,12 +123,14 @@ enclave { 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_size] uint8_t* unchecked_extrinsic, uint32_t unchecked_extrinsic_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_size] uint8_t* unchecked_extrinsic, uint32_t unchecked_extrinsic_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 @@ -126,24 +138,28 @@ enclave { public sgx_status_t generate_register_quoting_enclave_extrinsic( [in] const sgx_ql_qve_collateral_t *p_quote_collateral, - [out, size=unchecked_extrinsic_size] uint8_t* unchecked_extrinsic, uint32_t unchecked_extrinsic_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_register_tcb_info_extrinsic( [in] const sgx_ql_qve_collateral_t *p_quote_collateral, - [out, size=unchecked_extrinsic_size] uint8_t* unchecked_extrinsic, uint32_t unchecked_extrinsic_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 update_market_data_xt( [in, size=crypto_currency_size] uint8_t* crypto_currency, uint32_t crypto_currency_size, [in, size=fiat_currency_size] uint8_t* fiat_currency, uint32_t fiat_currency_size, - [out, size=unchecked_extrinsic_size] uint8_t* unchecked_extrinsic, uint32_t unchecked_extrinsic_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 update_weather_data_xt( [in, size=weather_info_logitude_size] uint8_t* weather_info_logitude, uint32_t weather_info_logitude_size, [in, size=weather_info_latitude_size] uint8_t* weather_info_latitude, uint32_t weather_info_latitude_size, - [out, size=unchecked_extrinsic_size] uint8_t* unchecked_extrinsic, uint32_t unchecked_extrinsic_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 dump_ias_ra_cert_to_disk(); diff --git a/enclave-runtime/README.md b/enclave-runtime/README.md new file mode 100644 index 0000000000..a4b88a52d1 --- /dev/null +++ b/enclave-runtime/README.md @@ -0,0 +1,2 @@ +# sidechain dependency graph +cargo depgraph --features dcap,sidechain --include enclave-runtime,itp-types,ita-stf | dot -Tsvg > dependency-graph.svg diff --git a/enclave-runtime/src/attestation.rs b/enclave-runtime/src/attestation.rs index ecbe3ac9d6..f91a0ad7e4 100644 --- a/enclave-runtime/src/attestation.rs +++ b/enclave-runtime/src/attestation.rs @@ -128,7 +128,8 @@ pub unsafe extern "C" fn generate_ias_ra_extrinsic( w_url: *const u8, w_url_size: u32, unchecked_extrinsic: *mut u8, - unchecked_extrinsic_size: u32, + 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() { @@ -137,17 +138,18 @@ pub unsafe extern "C" fn generate_ias_ra_extrinsic( let mut url_slice = slice::from_raw_parts(w_url, w_url_size as usize); let url = String::decode(&mut url_slice).expect("Could not decode url slice to a valid String"); let extrinsic_slice = - slice::from_raw_parts_mut(unchecked_extrinsic, unchecked_extrinsic_size as usize); + 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(), }; - if let Err(e) = write_slice_and_whitespace_pad(extrinsic_slice, extrinsic.encode()) { - return EnclaveError::BufferError(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 } @@ -156,7 +158,8 @@ pub unsafe extern "C" fn generate_dcap_ra_extrinsic( w_url: *const u8, w_url_size: u32, unchecked_extrinsic: *mut u8, - unchecked_extrinsic_size: u32, + 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>, @@ -167,7 +170,7 @@ pub unsafe extern "C" fn generate_dcap_ra_extrinsic( let mut url_slice = slice::from_raw_parts(w_url, w_url_size as usize); let url = String::decode(&mut url_slice).expect("Could not decode url slice to a valid String"); let extrinsic_slice = - slice::from_raw_parts_mut(unchecked_extrinsic, unchecked_extrinsic_size as usize); + slice::from_raw_parts_mut(unchecked_extrinsic, unchecked_extrinsic_max_size as usize); let extrinsic = match generate_dcap_ra_extrinsic_internal( url, @@ -179,9 +182,11 @@ pub unsafe extern "C" fn generate_dcap_ra_extrinsic( Err(e) => return e.into(), }; - if let Err(e) = write_slice_and_whitespace_pad(extrinsic_slice, extrinsic.encode()) { - return EnclaveError::BufferError(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 } @@ -261,7 +266,8 @@ pub unsafe extern "C" fn generate_dcap_ra_extrinsic_from_quote( quote: *const u8, quote_size: u32, unchecked_extrinsic: *mut u8, - unchecked_extrinsic_size: u32, + 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 @@ -270,7 +276,7 @@ pub unsafe extern "C" fn generate_dcap_ra_extrinsic_from_quote( let url = String::decode(&mut url_slice).expect("Could not decode url slice to a valid String"); let extrinsic_slice = - slice::from_raw_parts_mut(unchecked_extrinsic, unchecked_extrinsic_size as usize); + 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); @@ -279,9 +285,11 @@ pub unsafe extern "C" fn generate_dcap_ra_extrinsic_from_quote( Err(e) => return e.into(), }; - if let Err(e) = write_slice_and_whitespace_pad(extrinsic_slice, extrinsic.encode()) { - return EnclaveError::BufferError(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 } @@ -290,12 +298,12 @@ pub fn generate_dcap_ra_extrinsic_from_quote_internal( quote: &[u8], ) -> EnclaveResult { let node_metadata_repo = get_node_metadata_repository_from_integritee_solo_or_parachain()?; - info!(" [Enclave] Compose register enclave getting callIDs:"); + trace!(" [Enclave] Compose register enclave getting callIDs:"); let call_ids = node_metadata_repo .get_from_metadata(|m| m.register_sgx_enclave_call_indexes())? .map_err(MetadataProviderError::MetadataError)?; - info!(" [Enclave] Compose register enclave call DCAP IDs: {:?}", call_ids); + trace!(" [Enclave] Compose register enclave call DCAP IDs: {:?}", call_ids); let call = OpaqueCall::from_tuple(&( call_ids, quote, @@ -303,7 +311,7 @@ pub fn generate_dcap_ra_extrinsic_from_quote_internal( SgxAttestationMethod::Dcap { proxied: false }, )); - info!(" [Enclave] Compose register enclave got extrinsic, returning"); + trace!(" [Enclave] Compose register enclave got extrinsic, returning"); create_extrinsics(call) } @@ -312,12 +320,12 @@ pub fn generate_dcap_skip_ra_extrinsic_from_mr_enclave( quote: &[u8], ) -> EnclaveResult { let node_metadata_repo = get_node_metadata_repository_from_integritee_solo_or_parachain()?; - info!(" [Enclave] Compose register enclave (skip-ra) getting callIDs:"); + trace!(" [Enclave] Compose register enclave (skip-ra) getting callIDs:"); let call_ids = node_metadata_repo .get_from_metadata(|m| m.register_sgx_enclave_call_indexes())? .map_err(MetadataProviderError::MetadataError)?; - info!(" [Enclave] Compose register enclave (skip-ra) call DCAP IDs: {:?}", call_ids); + trace!(" [Enclave] Compose register enclave (skip-ra) call DCAP IDs: {:?}", call_ids); let call = OpaqueCall::from_tuple(&( call_ids, quote, @@ -391,13 +399,14 @@ fn create_extrinsics(call: OpaqueCall) -> EnclaveResult { pub unsafe extern "C" fn generate_register_quoting_enclave_extrinsic( collateral: *const sgx_ql_qve_collateral_t, unchecked_extrinsic: *mut u8, - unchecked_extrinsic_size: u32, + 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_size as usize); + 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, @@ -405,30 +414,31 @@ pub unsafe extern "C" fn generate_register_quoting_enclave_extrinsic( }; let call_index_getter = |m: &NodeMetadata| m.register_quoting_enclave_call_indexes(); - let extrinsic = generate_generic_register_collateral_extrinsic( + *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, - ); - match extrinsic { - Ok(_) => sgx_status_t::SGX_SUCCESS, - Err(e) => e.into(), - } + ) { + 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_size: u32, + 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_size as usize); + 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, @@ -436,17 +446,17 @@ pub unsafe extern "C" fn generate_register_tcb_info_extrinsic( }; let call_index_getter = |m: &NodeMetadata| m.register_tcb_info_call_indexes(); - let extrinsic = generate_generic_register_collateral_extrinsic( + *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, - ); - match extrinsic { - Ok(_) => sgx_status_t::SGX_SUCCESS, - Err(e) => e.into(), - } + ) { + Ok(l) => l as u32, + Err(e) => return e.into(), + }; + sgx_status_t::SGX_SUCCESS } pub fn generate_generic_register_collateral_extrinsic( @@ -455,12 +465,10 @@ pub fn generate_generic_register_collateral_extrinsic( collateral_data: &str, data_signature: &[u8], issuer_chain: &[u8], -) -> EnclaveResult<()> +) -> EnclaveResult where F: Fn(&NodeMetadata) -> Result<[u8; 2], MetadataError>, { - let extrinsics_factory = get_extrinsic_factory_from_integritee_solo_or_parachain()?; - let node_metadata_repo = get_node_metadata_repository_from_integritee_solo_or_parachain()?; let call_ids = node_metadata_repo .get_from_metadata(getter)? @@ -468,11 +476,9 @@ where info!(" [Enclave] Compose register collateral call: {:?}", call_ids); let call = OpaqueCall::from_tuple(&(call_ids, collateral_data, data_signature, issuer_chain)); - let extrinsic = extrinsics_factory.create_extrinsics(&[call], None)?[0].clone(); - if let Err(e) = write_slice_and_whitespace_pad(extrinsic_slice, extrinsic.encode()) { - return EnclaveError::BufferError(e).into() - }; - Ok(()) + let xt = create_extrinsics(call)?; + write_slice_and_whitespace_pad(extrinsic_slice, xt.encode()) + .map_err(|e| format!("{:?}", e).into()) } #[no_mangle] diff --git a/enclave-runtime/src/empty_impls.rs b/enclave-runtime/src/empty_impls.rs index 804c577c39..3f52a2a405 100644 --- a/enclave-runtime/src/empty_impls.rs +++ b/enclave-runtime/src/empty_impls.rs @@ -31,7 +31,8 @@ pub unsafe extern "C" fn update_market_data_xt( _fiat_currency_ptr: *const u8, _fiat_currency_size: u32, _unchecked_extrinsic: *mut u8, - _unchecked_extrinsic_size: u32, + _unchecked_extrinsic_max_size: u32, + _unchecked_extrinsic_size: *mut u32, ) -> sgx_types::sgx_status_t { unreachable!("Cannot update market data, teeracle feature is not enabled.") } @@ -45,7 +46,8 @@ pub unsafe extern "C" fn update_weather_data_xt( _weather_info_latitude: *const u8, _weather_info_latitude_size: u32, _unchecked_extrinsic: *mut u8, - _unchecked_extrinsic_size: u32, + _unchecked_extrinsic_max_size: u32, + _unchecked_extrinsic_size: *mut u32, ) -> sgx_types::sgx_status_t { unreachable!("Cannot update weather data, teeracle feature is not enabled.") } diff --git a/enclave-runtime/src/error.rs b/enclave-runtime/src/error.rs index 0ecad391ea..4dffb08543 100644 --- a/enclave-runtime/src/error.rs +++ b/enclave-runtime/src/error.rs @@ -41,6 +41,7 @@ pub enum Error { ParentchainBlockImportDispatch(itc_parentchain::block_import_dispatcher::error::Error), ExpectedTriggeredImportDispatcher, CouldNotDispatchBlockImport, + NoShardAssigned, NoIntegriteeParentchainAssigned, NoTargetAParentchainAssigned, NoTargetBParentchainAssigned, diff --git a/enclave-runtime/src/initialization/global_components.rs b/enclave-runtime/src/initialization/global_components.rs index 1c5b67d9d3..b81166568e 100644 --- a/enclave-runtime/src/initialization/global_components.rs +++ b/enclave-runtime/src/initialization/global_components.rs @@ -19,7 +19,6 @@ //! //! 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, @@ -31,6 +30,7 @@ use crate::{ rpc::rpc_response_channel::RpcResponseChannel, tls_ra::seal_handler::SealHandler, }; +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::{ @@ -43,13 +43,7 @@ use itc_parentchain::{ BlockImportDispatcher, }, block_importer::ParentchainBlockImporter, - indirect_calls_executor::{ - filter_metadata::{ - EventCreator, ShieldFundsAndInvokeFilter, TransferToAliceShieldsFundsFilter, - }, - parentchain_parser::ParentchainExtrinsicParser, - IndirectCallsExecutor, - }, + indirect_calls_executor::{filter_metadata::EventCreator, IndirectCallsExecutor}, light_client::{ concurrent_access::ValidatorAccessor, io::LightClientStateSealSync, light_validation::LightValidation, light_validation_state::LightValidationState, @@ -152,48 +146,49 @@ pub type EnclaveLightClientSeal = pub type EnclaveExtrinsicsFactory = ExtrinsicsFactory; -/// The enclave's generic indirect executor type. -/// -/// The `IndirectCallsFilter` calls filter can be configured per parentchain. -pub type EnclaveIndirectCallsExecutor = IndirectCallsExecutor< - EnclaveShieldingKeyRepository, - EnclaveStfEnclaveSigner, - EnclaveTopPoolAuthor, - EnclaveNodeMetadataRepository, - IndirectCallsFilter, - EventCreator, ->; - pub type EnclaveValidatorAccessor = ValidatorAccessor< LightValidation, ParentchainBlock, EnclaveLightClientSeal, >; -pub type EnclaveParentchainBlockImportQueue = ImportQueue; +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 EnclaveParentchainEventImportQueue = ImportQueue>; +pub type IntegriteeParentchainEventImportQueue = ImportQueue>; +pub type TargetAParentchainEventImportQueue = ImportQueue>; +pub type TargetBParentchainEventImportQueue = ImportQueue>; // Stuff for the integritee parentchain -pub type IntegriteeParentchainIndirectExecutor = - EnclaveIndirectCallsExecutor>; +pub type IntegriteeParentchainIndirectCallsExecutor = IndirectCallsExecutor< + EnclaveShieldingKeyRepository, + EnclaveStfEnclaveSigner, + EnclaveTopPoolAuthor, + EnclaveNodeMetadataRepository, + integritee::ExtrinsicFilter, + EventCreator, + integritee::ParentchainEventHandler, + EnclaveTrustedCallSigned, + EnclaveGetter, +>; pub type IntegriteeParentchainBlockImporter = ParentchainBlockImporter< ParentchainBlock, EnclaveValidatorAccessor, EnclaveStfExecutor, EnclaveExtrinsicsFactory, - IntegriteeParentchainIndirectExecutor, + IntegriteeParentchainIndirectCallsExecutor, >; pub type IntegriteeParentchainTriggeredBlockImportDispatcher = TriggeredDispatcher< IntegriteeParentchainBlockImporter, - EnclaveParentchainBlockImportQueue, - EnclaveParentchainEventImportQueue, + IntegriteeParentchainBlockImportQueue, + IntegriteeParentchainEventImportQueue, >; pub type IntegriteeParentchainImmediateBlockImportDispatcher = @@ -212,21 +207,30 @@ pub type IntegriteeParentchainBlockImportDispatcher = BlockImportDispatcher< /// /// Also note that the extrinsic parser must be changed if the signed extra contains the /// `AssetTxPayment`. -pub type TargetAParentchainIndirectExecutor = - EnclaveIndirectCallsExecutor>; +pub type TargetAParentchainIndirectCallsExecutor = IndirectCallsExecutor< + EnclaveShieldingKeyRepository, + EnclaveStfEnclaveSigner, + EnclaveTopPoolAuthor, + EnclaveNodeMetadataRepository, + target_a::ExtrinsicFilter, + EventCreator, + target_a::ParentchainEventHandler, + EnclaveTrustedCallSigned, + EnclaveGetter, +>; pub type TargetAParentchainBlockImporter = ParentchainBlockImporter< ParentchainBlock, EnclaveValidatorAccessor, EnclaveStfExecutor, EnclaveExtrinsicsFactory, - TargetAParentchainIndirectExecutor, + TargetAParentchainIndirectCallsExecutor, >; pub type TargetAParentchainTriggeredBlockImportDispatcher = TriggeredDispatcher< TargetAParentchainBlockImporter, - EnclaveParentchainBlockImportQueue, - EnclaveParentchainEventImportQueue, + TargetAParentchainBlockImportQueue, + TargetAParentchainEventImportQueue, >; pub type TargetAParentchainImmediateBlockImportDispatcher = @@ -245,21 +249,30 @@ pub type TargetAParentchainBlockImportDispatcher = BlockImportDispatcher< /// /// Also note that the extrinsic parser must be changed if the signed extra contains the /// `AssetTxPayment`. -pub type TargetBParentchainIndirectExecutor = - EnclaveIndirectCallsExecutor>; +pub type TargetBParentchainIndirectCallsExecutor = IndirectCallsExecutor< + EnclaveShieldingKeyRepository, + EnclaveStfEnclaveSigner, + EnclaveTopPoolAuthor, + EnclaveNodeMetadataRepository, + target_b::ExtrinsicFilter, + EventCreator, + target_b::ParentchainEventHandler, + EnclaveTrustedCallSigned, + EnclaveGetter, +>; pub type TargetBParentchainBlockImporter = ParentchainBlockImporter< ParentchainBlock, EnclaveValidatorAccessor, EnclaveStfExecutor, EnclaveExtrinsicsFactory, - TargetBParentchainIndirectExecutor, + TargetBParentchainIndirectCallsExecutor, >; pub type TargetBParentchainTriggeredBlockImportDispatcher = TriggeredDispatcher< TargetBParentchainBlockImporter, - EnclaveParentchainBlockImportQueue, - EnclaveParentchainEventImportQueue, + TargetBParentchainBlockImportQueue, + TargetBParentchainEventImportQueue, >; pub type TargetBParentchainImmediateBlockImportDispatcher = diff --git a/enclave-runtime/src/initialization/mod.rs b/enclave-runtime/src/initialization/mod.rs index 018cf0d719..abe3e51768 100644 --- a/enclave-runtime/src/initialization/mod.rs +++ b/enclave-runtime/src/initialization/mod.rs @@ -42,8 +42,8 @@ use crate::{ utils::{ get_extrinsic_factory_from_integritee_solo_or_parachain, get_node_metadata_repository_from_integritee_solo_or_parachain, - get_triggered_dispatcher_from_solo_or_parachain, - get_validator_accessor_from_solo_or_parachain, + get_triggered_dispatcher_from_integritee_solo_or_parachain, + get_validator_accessor_from_integritee_solo_or_parachain, }, Hash, }; @@ -211,7 +211,8 @@ pub(crate) fn init_enclave_sidechain_components() -> EnclaveResult<()> { let top_pool_author = GLOBAL_TOP_POOL_AUTHOR_COMPONENT.get()?; let state_key_repository = GLOBAL_STATE_KEY_REPOSITORY_COMPONENT.get()?; - let parentchain_block_import_dispatcher = get_triggered_dispatcher_from_solo_or_parachain()?; + let parentchain_block_import_dispatcher = + get_triggered_dispatcher_from_integritee_solo_or_parachain()?; let signer = GLOBAL_SIGNING_KEY_REPOSITORY_COMPONENT.get()?.retrieve_key()?; @@ -226,7 +227,7 @@ pub(crate) fn init_enclave_sidechain_components() -> EnclaveResult<()> { let sidechain_block_import_queue = GLOBAL_SIDECHAIN_IMPORT_QUEUE_COMPONENT.get()?; 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_solo_or_parachain()?; + let validator_accessor = get_validator_accessor_from_integritee_solo_or_parachain()?; let sidechain_block_import_confirmation_handler = Arc::new(EnclaveBlockImportConfirmationHandler::new( diff --git a/enclave-runtime/src/initialization/parentchain/common.rs b/enclave-runtime/src/initialization/parentchain/common.rs index c2b6abea20..01832132a0 100644 --- a/enclave-runtime/src/initialization/parentchain/common.rs +++ b/enclave-runtime/src/initialization/parentchain/common.rs @@ -20,19 +20,25 @@ use crate::{ initialization::{ global_components::{ EnclaveExtrinsicsFactory, EnclaveNodeMetadataRepository, EnclaveOffchainWorkerExecutor, - EnclaveParentchainBlockImportQueue, EnclaveParentchainEventImportQueue, EnclaveParentchainSigner, EnclaveStfExecutor, EnclaveValidatorAccessor, - IntegriteeParentchainBlockImportDispatcher, IntegriteeParentchainBlockImporter, + IntegriteeParentchainBlockImportDispatcher, IntegriteeParentchainBlockImportQueue, + IntegriteeParentchainBlockImporter, IntegriteeParentchainEventImportQueue, IntegriteeParentchainImmediateBlockImportDispatcher, - IntegriteeParentchainIndirectExecutor, + IntegriteeParentchainIndirectCallsExecutor, IntegriteeParentchainTriggeredBlockImportDispatcher, - TargetAParentchainBlockImportDispatcher, TargetAParentchainBlockImporter, - TargetAParentchainImmediateBlockImportDispatcher, TargetAParentchainIndirectExecutor, - TargetBParentchainBlockImportDispatcher, TargetBParentchainBlockImporter, - TargetBParentchainImmediateBlockImportDispatcher, TargetBParentchainIndirectExecutor, - 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, + TargetAParentchainBlockImportDispatcher, TargetAParentchainBlockImportQueue, + TargetAParentchainBlockImporter, TargetAParentchainEventImportQueue, + TargetAParentchainImmediateBlockImportDispatcher, + TargetAParentchainIndirectCallsExecutor, + TargetAParentchainTriggeredBlockImportDispatcher, + TargetBParentchainBlockImportDispatcher, TargetBParentchainBlockImportQueue, + TargetBParentchainBlockImporter, TargetBParentchainEventImportQueue, + TargetBParentchainImmediateBlockImportDispatcher, + TargetBParentchainIndirectCallsExecutor, + TargetBParentchainTriggeredBlockImportDispatcher, 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, }, @@ -40,6 +46,8 @@ use crate::{ 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; @@ -49,6 +57,7 @@ pub(crate) fn create_integritee_parentchain_block_importer( 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()?; @@ -61,17 +70,20 @@ pub(crate) fn create_integritee_parentchain_block_importer( shielding_key_repository.clone(), top_pool_author.clone(), )); - let indirect_calls_executor = Arc::new(IntegriteeParentchainIndirectExecutor::new( + let indirect_calls_executor = Arc::new(IntegriteeParentchainIndirectCallsExecutor::new( shielding_key_repository, stf_enclave_signer, top_pool_author, node_metadata_repository, + ParentchainId::Integritee, )); Ok(IntegriteeParentchainBlockImporter::new( validator_access, stf_executor, extrinsics_factory, indirect_calls_executor, + shard_creation_info, + ParentchainId::Integritee, )) } @@ -80,6 +92,7 @@ pub(crate) fn create_target_a_parentchain_block_importer( 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()?; @@ -92,17 +105,20 @@ pub(crate) fn create_target_a_parentchain_block_importer( shielding_key_repository.clone(), top_pool_author.clone(), )); - let indirect_calls_executor = Arc::new(TargetAParentchainIndirectExecutor::new( + let indirect_calls_executor = Arc::new(TargetAParentchainIndirectCallsExecutor::new( shielding_key_repository, stf_enclave_signer, top_pool_author, node_metadata_repository, + ParentchainId::TargetA, )); Ok(TargetAParentchainBlockImporter::new( validator_access, stf_executor, extrinsics_factory, indirect_calls_executor, + shard_creation_info, + ParentchainId::TargetA, )) } @@ -111,6 +127,7 @@ pub(crate) fn create_target_b_parentchain_block_importer( 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()?; @@ -123,17 +140,20 @@ pub(crate) fn create_target_b_parentchain_block_importer( shielding_key_repository.clone(), top_pool_author.clone(), )); - let indirect_calls_executor = Arc::new(TargetBParentchainIndirectExecutor::new( + let indirect_calls_executor = Arc::new(TargetBParentchainIndirectCallsExecutor::new( shielding_key_repository, stf_enclave_signer, top_pool_author, node_metadata_repository, + ParentchainId::TargetB, )); Ok(TargetBParentchainBlockImporter::new( validator_access, stf_executor, extrinsics_factory, indirect_calls_executor, + shard_creation_info, + ParentchainId::TargetB, )) } @@ -245,8 +265,8 @@ pub(crate) fn create_target_b_offchain_immediate_import_dispatcher( pub(crate) fn create_sidechain_triggered_import_dispatcher( block_importer: IntegriteeParentchainBlockImporter, ) -> Arc { - let parentchain_block_import_queue = EnclaveParentchainBlockImportQueue::default(); - let parentchain_event_import_queue = EnclaveParentchainEventImportQueue::default(); + let parentchain_block_import_queue = IntegriteeParentchainBlockImportQueue::default(); + let parentchain_event_import_queue = IntegriteeParentchainEventImportQueue::default(); let triggered_dispatcher = IntegriteeParentchainTriggeredBlockImportDispatcher::new( block_importer, parentchain_block_import_queue, @@ -256,3 +276,33 @@ pub(crate) fn create_sidechain_triggered_import_dispatcher( triggered_dispatcher, ))) } + +pub(crate) fn create_sidechain_triggered_import_dispatcher_for_target_a( + block_importer: TargetAParentchainBlockImporter, +) -> Arc { + let parentchain_block_import_queue = TargetAParentchainBlockImportQueue::default(); + let parentchain_event_import_queue = TargetAParentchainEventImportQueue::default(); + let triggered_dispatcher = TargetAParentchainTriggeredBlockImportDispatcher::new( + block_importer, + parentchain_block_import_queue, + parentchain_event_import_queue, + ); + Arc::new(TargetAParentchainBlockImportDispatcher::new_triggered_dispatcher(Arc::new( + triggered_dispatcher, + ))) +} + +pub(crate) fn create_sidechain_triggered_import_dispatcher_for_target_b( + block_importer: TargetBParentchainBlockImporter, +) -> Arc { + let parentchain_block_import_queue = TargetBParentchainBlockImportQueue::default(); + let parentchain_event_import_queue = TargetBParentchainEventImportQueue::default(); + let triggered_dispatcher = TargetBParentchainTriggeredBlockImportDispatcher::new( + block_importer, + parentchain_block_import_queue, + parentchain_event_import_queue, + ); + Arc::new(TargetBParentchainBlockImportDispatcher::new_triggered_dispatcher(Arc::new( + triggered_dispatcher, + ))) +} diff --git a/enclave-runtime/src/initialization/parentchain/integritee_parachain.rs b/enclave-runtime/src/initialization/parentchain/integritee_parachain.rs index f13961aa8a..d6264c2ea4 100644 --- a/enclave-runtime/src/initialization/parentchain/integritee_parachain.rs +++ b/enclave-runtime/src/initialization/parentchain/integritee_parachain.rs @@ -40,6 +40,7 @@ use itp_types::parentchain::ParentchainId; use std::{path::PathBuf, sync::Arc}; pub use itc_parentchain::primitives::{ParachainBlock, ParachainHeader, ParachainParams}; +use itp_stf_interface::ShardCreationInfo; #[derive(Clone)] pub struct IntegriteeParachainHandler { @@ -55,6 +56,7 @@ 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()?; @@ -91,6 +93,7 @@ impl IntegriteeParachainHandler { stf_executor.clone(), extrinsics_factory.clone(), node_metadata_repository.clone(), + shard_creation_info, )?; let import_dispatcher = match WorkerModeProvider::worker_mode() { diff --git a/enclave-runtime/src/initialization/parentchain/integritee_solochain.rs b/enclave-runtime/src/initialization/parentchain/integritee_solochain.rs index d84624f0e6..37b95135e5 100644 --- a/enclave-runtime/src/initialization/parentchain/integritee_solochain.rs +++ b/enclave-runtime/src/initialization/parentchain/integritee_solochain.rs @@ -40,6 +40,7 @@ use itp_types::parentchain::ParentchainId; use std::{path::PathBuf, sync::Arc}; pub use itc_parentchain::primitives::{SolochainBlock, SolochainHeader, SolochainParams}; +use itp_stf_interface::ShardCreationInfo; pub struct IntegriteeSolochainHandler { pub genesis_header: SolochainHeader, @@ -54,6 +55,7 @@ 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()?; @@ -90,6 +92,7 @@ impl IntegriteeSolochainHandler { stf_executor.clone(), extrinsics_factory.clone(), node_metadata_repository.clone(), + shard_creation_info, )?; let import_dispatcher = match WorkerModeProvider::worker_mode() { diff --git a/enclave-runtime/src/initialization/parentchain/mod.rs b/enclave-runtime/src/initialization/parentchain/mod.rs index a2338009ad..d421e21301 100644 --- a/enclave-runtime/src/initialization/parentchain/mod.rs +++ b/enclave-runtime/src/initialization/parentchain/mod.rs @@ -33,6 +33,7 @@ use crate::{ target_b_solochain::TargetBSolochainHandler, }, }, + shard_creation_info::get_shard_creation_info_internal, }; use codec::{Decode, Encode}; use integritee_parachain::IntegriteeParachainHandler; @@ -43,6 +44,7 @@ use itc_parentchain::{ }; use itp_component_container::ComponentInitializer; use itp_settings::worker_mode::ProvideWorkerMode; +use log::*; use std::{path::PathBuf, vec::Vec}; mod common; @@ -58,63 +60,98 @@ pub(crate) fn init_parentchain_components encoded_params: Vec, ) -> Result> { match ParentchainInitParams::decode(&mut encoded_params.as_slice())? { - ParentchainInitParams::Parachain { id, params } => match id { - ParentchainId::Integritee => { - let handler = - IntegriteeParachainHandler::init::(base_path, params)?; - 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)?; - 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)?; - 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::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::Integritee => { + 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, params } => match id { - ParentchainId::Integritee => { - let handler = - IntegriteeSolochainHandler::init::(base_path, params)?; - 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)?; - 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)?; - 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()) - }, + 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::Integritee => { + 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/enclave-runtime/src/initialization/parentchain/target_a_parachain.rs b/enclave-runtime/src/initialization/parentchain/target_a_parachain.rs index 56bb011919..31799d636a 100644 --- a/enclave-runtime/src/initialization/parentchain/target_a_parachain.rs +++ b/enclave-runtime/src/initialization/parentchain/target_a_parachain.rs @@ -31,19 +31,20 @@ use crate::{ 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_extrinsics_factory, create_sidechain_triggered_import_dispatcher_for_target_a, + create_target_a_offchain_immediate_import_dispatcher, create_target_a_parentchain_block_importer, }, }, }; use itc_parentchain::light_client::{concurrent_access::ValidatorAccess, LightClientState}; +pub use itc_parentchain::primitives::{ParachainBlock, ParachainHeader, ParachainParams}; use itp_component_container::ComponentGetter; use itp_settings::worker_mode::{ProvideWorkerMode, WorkerMode}; +use itp_stf_interface::ShardCreationInfo; use itp_types::parentchain::ParentchainId; use std::{path::PathBuf, sync::Arc}; -pub use itc_parentchain::primitives::{ParachainBlock, ParachainHeader, ParachainParams}; - #[derive(Clone)] pub struct TargetAParachainHandler { pub genesis_header: ParachainHeader, @@ -58,6 +59,7 @@ 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()?; @@ -93,6 +95,7 @@ impl TargetAParachainHandler { stf_executor.clone(), extrinsics_factory.clone(), node_metadata_repository.clone(), + shard_creation_info, )?; let import_dispatcher = match WorkerModeProvider::worker_mode() { @@ -103,7 +106,7 @@ impl TargetAParachainHandler { extrinsics_factory.clone(), )?, WorkerMode::Sidechain => - unimplemented!("Can't run target a chain in sidechain mode yet."), + create_sidechain_triggered_import_dispatcher_for_target_a(block_importer), WorkerMode::Teeracle => Arc::new(TargetAParentchainBlockImportDispatcher::new_empty_dispatcher()), }; diff --git a/enclave-runtime/src/initialization/parentchain/target_a_solochain.rs b/enclave-runtime/src/initialization/parentchain/target_a_solochain.rs index 60259eedbe..4348dc8e19 100644 --- a/enclave-runtime/src/initialization/parentchain/target_a_solochain.rs +++ b/enclave-runtime/src/initialization/parentchain/target_a_solochain.rs @@ -25,19 +25,20 @@ use crate::{ 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_extrinsics_factory, create_sidechain_triggered_import_dispatcher_for_target_a, + create_target_a_offchain_immediate_import_dispatcher, create_target_a_parentchain_block_importer, }, }, }; use itc_parentchain::light_client::{concurrent_access::ValidatorAccess, LightClientState}; +pub use itc_parentchain::primitives::{SolochainBlock, SolochainHeader, SolochainParams}; use itp_component_container::ComponentGetter; use itp_settings::worker_mode::{ProvideWorkerMode, WorkerMode}; +use itp_stf_interface::ShardCreationInfo; use itp_types::parentchain::ParentchainId; use std::{path::PathBuf, sync::Arc}; -pub use itc_parentchain::primitives::{SolochainBlock, SolochainHeader, SolochainParams}; - pub struct TargetASolochainHandler { pub genesis_header: SolochainHeader, pub node_metadata_repository: Arc, @@ -51,6 +52,7 @@ 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()?; @@ -86,6 +88,7 @@ impl TargetASolochainHandler { stf_executor.clone(), extrinsics_factory.clone(), node_metadata_repository.clone(), + shard_creation_info, )?; let import_dispatcher = match WorkerModeProvider::worker_mode() { @@ -96,7 +99,7 @@ impl TargetASolochainHandler { extrinsics_factory.clone(), )?, WorkerMode::Sidechain => - unimplemented!("Can't run target a chain in sidechain mode yet."), + create_sidechain_triggered_import_dispatcher_for_target_a(block_importer), WorkerMode::Teeracle => Arc::new(TargetAParentchainBlockImportDispatcher::new_empty_dispatcher()), }; diff --git a/enclave-runtime/src/initialization/parentchain/target_b_parachain.rs b/enclave-runtime/src/initialization/parentchain/target_b_parachain.rs index bd1b628b06..113103ee87 100644 --- a/enclave-runtime/src/initialization/parentchain/target_b_parachain.rs +++ b/enclave-runtime/src/initialization/parentchain/target_b_parachain.rs @@ -31,19 +31,20 @@ use crate::{ 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_extrinsics_factory, create_sidechain_triggered_import_dispatcher_for_target_b, + create_target_b_offchain_immediate_import_dispatcher, create_target_b_parentchain_block_importer, }, }, }; use itc_parentchain::light_client::{concurrent_access::ValidatorAccess, LightClientState}; +pub use itc_parentchain::primitives::{ParachainBlock, ParachainHeader, ParachainParams}; use itp_component_container::ComponentGetter; use itp_settings::worker_mode::{ProvideWorkerMode, WorkerMode}; +use itp_stf_interface::ShardCreationInfo; use itp_types::parentchain::ParentchainId; use std::{path::PathBuf, sync::Arc}; -pub use itc_parentchain::primitives::{ParachainBlock, ParachainHeader, ParachainParams}; - #[derive(Clone)] pub struct TargetBParachainHandler { pub genesis_header: ParachainHeader, @@ -58,6 +59,7 @@ 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()?; @@ -93,6 +95,7 @@ impl TargetBParachainHandler { stf_executor.clone(), extrinsics_factory.clone(), node_metadata_repository.clone(), + shard_creation_info, )?; let import_dispatcher = match WorkerModeProvider::worker_mode() { @@ -103,7 +106,7 @@ impl TargetBParachainHandler { extrinsics_factory.clone(), )?, WorkerMode::Sidechain => - unimplemented!("Can't run target B chain in sidechain mode yet."), + create_sidechain_triggered_import_dispatcher_for_target_b(block_importer), WorkerMode::Teeracle => Arc::new(TargetBParentchainBlockImportDispatcher::new_empty_dispatcher()), }; diff --git a/enclave-runtime/src/initialization/parentchain/target_b_solochain.rs b/enclave-runtime/src/initialization/parentchain/target_b_solochain.rs index d3ec66beae..edab731e6d 100644 --- a/enclave-runtime/src/initialization/parentchain/target_b_solochain.rs +++ b/enclave-runtime/src/initialization/parentchain/target_b_solochain.rs @@ -25,19 +25,20 @@ use crate::{ 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_extrinsics_factory, create_sidechain_triggered_import_dispatcher_for_target_b, + create_target_b_offchain_immediate_import_dispatcher, create_target_b_parentchain_block_importer, }, }, }; use itc_parentchain::light_client::{concurrent_access::ValidatorAccess, LightClientState}; +pub use itc_parentchain::primitives::{SolochainBlock, SolochainHeader, SolochainParams}; use itp_component_container::ComponentGetter; use itp_settings::worker_mode::{ProvideWorkerMode, WorkerMode}; +use itp_stf_interface::ShardCreationInfo; use itp_types::parentchain::ParentchainId; use std::{path::PathBuf, sync::Arc}; -pub use itc_parentchain::primitives::{SolochainBlock, SolochainHeader, SolochainParams}; - pub struct TargetBSolochainHandler { pub genesis_header: SolochainHeader, pub node_metadata_repository: Arc, @@ -51,6 +52,7 @@ 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()?; @@ -86,6 +88,7 @@ impl TargetBSolochainHandler { stf_executor.clone(), extrinsics_factory.clone(), node_metadata_repository.clone(), + shard_creation_info, )?; let import_dispatcher = match WorkerModeProvider::worker_mode() { @@ -96,7 +99,7 @@ impl TargetBSolochainHandler { extrinsics_factory.clone(), )?, WorkerMode::Sidechain => - unimplemented!("Can't run target B chain in sidechain mode yet."), + create_sidechain_triggered_import_dispatcher_for_target_b(block_importer), WorkerMode::Teeracle => Arc::new(TargetBParentchainBlockImportDispatcher::new_empty_dispatcher()), }; diff --git a/enclave-runtime/src/lib.rs b/enclave-runtime/src/lib.rs index 111324f0bb..d5ecdb2f42 100644 --- a/enclave-runtime/src/lib.rs +++ b/enclave-runtime/src/lib.rs @@ -48,16 +48,14 @@ use crate::{ }, }; use codec::Decode; -use itc_parentchain::{ - block_import_dispatcher::{ - triggered_dispatcher::TriggerParentchainBlockImport, DispatchBlockImport, - }, - primitives::ParentchainId, -}; +use core::ffi::c_int; +use itc_parentchain::{block_import_dispatcher::DispatchBlockImport, primitives::ParentchainId}; use itp_component_container::ComponentGetter; + use itp_import_queue::PushToQueue; use itp_node_api::metadata::NodeMetadata; use itp_nonce_cache::{MutateNonce, Nonce}; + use itp_settings::worker_mode::{ProvideWorkerMode, WorkerMode, WorkerModeProvider}; use itp_sgx_crypto::key_repository::AccessPubkey; use itp_storage::{StorageProof, StorageProofChecker}; @@ -73,11 +71,14 @@ use std::{ string::{String, ToString}, vec::Vec, }; + mod attestation; mod empty_impls; mod initialization; mod ipfs; mod ocall; +mod shard_config; +mod shard_creation_info; mod shard_vault; mod utils; @@ -117,7 +118,9 @@ pub unsafe extern "C" fn init( encoded_base_dir_size: u32, ) -> sgx_status_t { // Initialize the logging environment in the enclave. - env_logger::init(); + env_logger::builder() + .format_timestamp(Some(env_logger::TimestampPrecision::Micros)) + .init(); let mu_ra_url = match String::decode(&mut slice::from_raw_parts(mu_ra_addr, mu_ra_addr_size as usize)) @@ -290,7 +293,7 @@ pub unsafe extern "C" fn set_node_metadata( }, }; - info!("Successfully set the node meta data"); + trace!("Successfully set the node meta data"); sgx_status_t::SGX_SUCCESS } @@ -391,8 +394,6 @@ pub unsafe extern "C" fn init_parentchain_components( latest_header: *mut u8, latest_header_size: usize, ) -> sgx_status_t { - info!("Initializing light client!"); - let encoded_params = slice::from_raw_parts(params, params_size); let latest_header_slice = slice::from_raw_parts_mut(latest_header, latest_header_size); @@ -437,6 +438,7 @@ pub unsafe extern "C" fn sync_parentchain( 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, @@ -447,8 +449,10 @@ pub unsafe extern "C" fn sync_parentchain( 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 @@ -464,25 +468,30 @@ unsafe fn sync_parentchain_internal( 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)?; - let blocks_to_sync_merkle_roots: Vec = - blocks_to_sync.iter().map(|block| block.block.header.state_root).collect(); - - if let Err(e) = validate_events(&events_proofs_to_sync, &blocks_to_sync_merkle_roots) { - return e.into() + 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() + } } - let events_to_sync = Vec::>::decode_raw(events_to_sync, events_to_sync_size)?; - dispatch_parentchain_blocks_for_import::( blocks_to_sync, events_to_sync, &parentchain_id, + immediate_import, ) } @@ -498,36 +507,66 @@ fn dispatch_parentchain_blocks_for_import blocks_to_sync: Vec, events_to_sync: Vec>, id: &ParentchainId, + immediate_import: bool, ) -> Result<()> { if WorkerModeProvider::worker_mode() == WorkerMode::Teeracle { trace!("Not importing any parentchain blocks"); return Ok(()) } - + trace!( + "[{:?}] Dispatching Import of {} blocks and {} events", + id, + blocks_to_sync.len(), + events_to_sync.len() + ); match id { ParentchainId::Integritee => { if let Ok(handler) = GLOBAL_INTEGRITEE_SOLOCHAIN_HANDLER_COMPONENT.get() { - handler.import_dispatcher.dispatch_import(blocks_to_sync, events_to_sync)?; + 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)?; + handler.import_dispatcher.dispatch_import( + blocks_to_sync, + events_to_sync, + immediate_import, + )?; } else { return Err(Error::NoIntegriteeParentchainAssigned) }; }, ParentchainId::TargetA => { if let Ok(handler) = GLOBAL_TARGET_A_SOLOCHAIN_HANDLER_COMPONENT.get() { - handler.import_dispatcher.dispatch_import(blocks_to_sync, events_to_sync)?; + 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)?; + 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)?; + 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)?; + handler.import_dispatcher.dispatch_import( + blocks_to_sync, + events_to_sync, + immediate_import, + )?; } else { return Err(Error::NoTargetBParentchainAssigned) }; @@ -542,7 +581,7 @@ fn validate_events( events_proofs: &Vec, blocks_merkle_roots: &Vec, ) -> Result<()> { - info!( + debug!( "Validating events, events_proofs_length: {:?}, blocks_merkle_roots_lengths: {:?}", events_proofs.len(), blocks_merkle_roots.len() @@ -574,92 +613,6 @@ fn validate_events( Ok(()) } -/// Triggers the import of parentchain blocks when using a queue to sync parentchain block import -/// with sidechain block production. -/// -/// This trigger is only useful in combination with a `TriggeredDispatcher` and sidechain. In case no -/// sidechain and the `ImmediateDispatcher` are used, this function is obsolete. -#[no_mangle] -pub unsafe extern "C" fn trigger_parentchain_block_import( - parentchain_id: *const u8, - parentchain_id_size: u32, -) -> sgx_status_t { - 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 - }, - }; - - match internal_trigger_parentchain_block_import(&parentchain_id) { - Ok(()) => sgx_status_t::SGX_SUCCESS, - Err(e) => { - error!("Failed to trigger import of parentchain blocks: {:?}", e); - sgx_status_t::SGX_ERROR_UNEXPECTED - }, - } -} - -fn internal_trigger_parentchain_block_import(id: &ParentchainId) -> Result<()> { - let _maybe_latest_block = match id { - ParentchainId::Integritee => { - if let Ok(handler) = GLOBAL_INTEGRITEE_SOLOCHAIN_HANDLER_COMPONENT.get() { - handler - .import_dispatcher - .triggered_dispatcher() - .ok_or(Error::ExpectedTriggeredImportDispatcher)? - .import_all()? - } else if let Ok(handler) = GLOBAL_INTEGRITEE_PARACHAIN_HANDLER_COMPONENT.get() { - handler - .import_dispatcher - .triggered_dispatcher() - .ok_or(Error::ExpectedTriggeredImportDispatcher)? - .import_all()? - } else { - return Err(Error::NoIntegriteeParentchainAssigned) - } - }, - ParentchainId::TargetA => { - if let Ok(handler) = GLOBAL_TARGET_A_SOLOCHAIN_HANDLER_COMPONENT.get() { - handler - .import_dispatcher - .triggered_dispatcher() - .ok_or(Error::ExpectedTriggeredImportDispatcher)? - .import_all()? - } else if let Ok(handler) = GLOBAL_TARGET_A_PARACHAIN_HANDLER_COMPONENT.get() { - handler - .import_dispatcher - .triggered_dispatcher() - .ok_or(Error::ExpectedTriggeredImportDispatcher)? - .import_all()? - } else { - return Err(Error::NoTargetAParentchainAssigned) - } - }, - ParentchainId::TargetB => { - if let Ok(handler) = GLOBAL_TARGET_B_SOLOCHAIN_HANDLER_COMPONENT.get() { - handler - .import_dispatcher - .triggered_dispatcher() - .ok_or(Error::ExpectedTriggeredImportDispatcher)? - .import_all()? - } else if let Ok(handler) = GLOBAL_TARGET_B_PARACHAIN_HANDLER_COMPONENT.get() { - handler - .import_dispatcher - .triggered_dispatcher() - .ok_or(Error::ExpectedTriggeredImportDispatcher)? - .import_all()? - } else { - return Err(Error::NoTargetBParentchainAssigned) - } - }, - }; - - 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)] diff --git a/enclave-runtime/src/rpc/worker_api_direct.rs b/enclave-runtime/src/rpc/worker_api_direct.rs index 7ba57a1f52..6c3084c77e 100644 --- a/enclave-runtime/src/rpc/worker_api_direct.rs +++ b/enclave-runtime/src/rpc/worker_api_direct.rs @@ -20,7 +20,10 @@ use crate::{ generate_dcap_ra_extrinsic_from_quote_internal, generate_ias_ra_extrinsic_from_der_cert_internal, }, - utils::get_validator_accessor_from_solo_or_parachain, + utils::{ + get_stf_enclave_signer_from_solo_or_parachain, + get_validator_accessor_from_integritee_solo_or_parachain, + }, }; use codec::Encode; use core::result::Result; @@ -30,16 +33,18 @@ use itc_parentchain::light_client::{concurrent_access::ValidatorAccess, Extrinsi use itp_primitives_cache::{GetPrimitives, GLOBAL_PRIMITIVES_CACHE}; use itp_rpc::RpcReturnValue; use itp_sgx_crypto::key_repository::AccessPubkey; -use itp_stf_executor::getter_executor::ExecuteGetter; +use itp_stf_executor::{getter_executor::ExecuteGetter, traits::StfShardVaultQuery}; use itp_top_pool_author::traits::AuthorApi; use itp_types::{DirectRequestStatus, Request, ShardIdentifier, H256}; use itp_utils::{FromHexPrefixed, ToHexPrefixed}; use its_primitives::types::block::SignedBlock; use its_sidechain::rpc_handler::{direct_top_pool_api, import_block_api}; use jsonrpc_core::{serde_json::json, IoHandler, Params, Value}; +use log::debug; use sgx_crypto_helper::rsa3072::Rsa3072PubKey; use sp_runtime::OpaqueExtrinsic; use std::{borrow::ToOwned, 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() } @@ -64,14 +69,13 @@ where GetterExecutor: ExecuteGetter + Send + Sync + 'static, AccessShieldingKey: AccessPubkey + Send + Sync + 'static, { - let io = IoHandler::new(); + let mut io = direct_top_pool_api::add_top_pool_direct_rpc_methods( + top_pool_author.clone(), + IoHandler::new(), + ); - // Add direct TOP pool rpc methods - let mut io = direct_top_pool_api::add_top_pool_direct_rpc_methods(top_pool_author, io); - - // author_getShieldingKey - let rsa_pubkey_name: &str = "author_getShieldingKey"; - io.add_sync_method(rsa_pubkey_name, move |_: Params| { + io.add_sync_method("author_getShieldingKey", move |_: Params| { + debug!("worker_api_direct rpc was called: author_getShieldingKey"); let rsa_pubkey = match shielding_key.retrieve_pubkey() { Ok(key) => key, Err(status) => { @@ -93,8 +97,36 @@ where Ok(json!(json_value.to_hex())) }); - let mu_ra_url_name: &str = "author_getMuRaUrl"; - io.add_sync_method(mu_ra_url_name, move |_: Params| { + let local_top_pool_author = top_pool_author.clone(); + io.add_sync_method("author_getShardVault", move |_: Params| { + debug!("worker_api_direct rpc was called: author_getShardVault"); + let shard = + local_top_pool_author.list_handled_shards().first().copied().unwrap_or_default(); + if let Ok(stf_enclave_signer) = get_stf_enclave_signer_from_solo_or_parachain() { + if let Ok(vault) = stf_enclave_signer.get_shard_vault(&shard) { + let json_value = + RpcReturnValue::new(vault.encode(), false, DirectRequestStatus::Ok); + Ok(json!(json_value.to_hex())) + } else { + Ok(json!(compute_hex_encoded_return_error("failed to get shard vault").to_hex())) + } + } else { + Ok(json!(compute_hex_encoded_return_error( + "failed to get stf_enclave_signer to get shard vault" + ) + .to_hex())) + } + }); + + 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) => { @@ -107,8 +139,8 @@ where Ok(json!(json_value.to_hex())) }); - let untrusted_url_name: &str = "author_getUntrustedUrl"; - io.add_sync_method(untrusted_url_name, move |_: Params| { + 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) => { @@ -121,31 +153,27 @@ where Ok(json!(json_value.to_hex())) }); - // chain_subscribeAllHeads - let chain_subscribe_all_heads_name: &str = "chain_subscribeAllHeads"; - io.add_sync_method(chain_subscribe_all_heads_name, |_: Params| { + 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))) }); - // state_getMetadata - let state_get_metadata_name: &str = "state_getMetadata"; - io.add_sync_method(state_get_metadata_name, |_: Params| { + 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())) }); - // state_getRuntimeVersion - let state_get_runtime_version_name: &str = "state_getRuntimeVersion"; - io.add_sync_method(state_get_runtime_version_name, |_: Params| { + 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))) }); - // state_executeGetter - let state_execute_getter_name: &str = "state_executeGetter"; - io.add_sync_method(state_execute_getter_name, move |params: Params| { + 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, @@ -158,9 +186,8 @@ where Ok(json!(json_value)) }); - // attesteer_forward_dcap_quote - let attesteer_forward_dcap_quote: &str = "attesteer_forwardDcapQuote"; - io.add_sync_method(attesteer_forward_dcap_quote, move |params: Params| { + 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, @@ -174,9 +201,8 @@ where Ok(json!(json_value)) }); - // attesteer_forward_ias_attestation_report - let attesteer_forward_ias_attestation_report: &str = "attesteer_forwardIasAttestationReport"; - io.add_sync_method(attesteer_forward_ias_attestation_report, move |params: Params| { + 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, @@ -190,30 +216,27 @@ where Ok(json!(json_value)) }); - // system_health - let state_health_name: &str = "system_health"; - io.add_sync_method(state_health_name, |_: Params| { + 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))) }); - // system_name - let state_name_name: &str = "system_name"; - io.add_sync_method(state_name_name, |_: Params| { + 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))) }); - // system_version - let state_version_name: &str = "system_version"; - io.add_sync_method(state_version_name, |_: Params| { + 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))) }); - // returns all rpcs methods 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())) }); @@ -257,7 +280,7 @@ fn forward_dcap_quote_inner(params: Params) -> Result { let ext = generate_dcap_ra_extrinsic_from_quote_internal(url, &encoded_quote_to_forward) .map_err(|e| format!("{:?}", e))?; - let validator_access = get_validator_accessor_from_solo_or_parachain().unwrap(); + let validator_access = get_validator_accessor_from_integritee_solo_or_parachain().unwrap(); validator_access .execute_mut_on_validator(|v| v.send_extrinsics(vec![ext.clone()])) .unwrap(); @@ -285,7 +308,7 @@ fn attesteer_forward_ias_attestation_report_inner( let ext = generate_ias_ra_extrinsic_from_der_cert_internal(url, &ias_attestation_report) .map_err(|e| format!("{:?}", e))?; - let validator_access = get_validator_accessor_from_solo_or_parachain().unwrap(); + let validator_access = get_validator_accessor_from_integritee_solo_or_parachain().unwrap(); validator_access .execute_mut_on_validator(|v| v.send_extrinsics(vec![ext.clone()])) .unwrap(); diff --git a/enclave-runtime/src/shard_config.rs b/enclave-runtime/src/shard_config.rs new file mode 100644 index 0000000000..a22e79eb0d --- /dev/null +++ b/enclave-runtime/src/shard_config.rs @@ -0,0 +1,69 @@ +/* + 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}, + utils::{ + get_extrinsic_factory_from_integritee_solo_or_parachain, + get_stf_enclave_signer_from_solo_or_parachain, + }, +}; +use codec::Encode; +use enclave_bridge_primitives::ShardConfig; + +use itp_extrinsics_factory::CreateExtrinsics; +use itp_node_api::metadata::{ + pallet_enclave_bridge::EnclaveBridgeCallIndexes, provider::AccessNodeMetadata, +}; + +use itp_ocall_api::{EnclaveAttestationOCallApi, EnclaveOnChainOCallApi}; + +use itp_types::{ + parentchain::{AccountId, BlockNumber, ParentchainId}, + OpaqueCall, ShardIdentifier, +}; +use itp_utils::hex::hex_encode; +use log::*; + +use teerex_primitives::EnclaveFingerprint; + +pub(crate) fn init_shard_config(shard: ShardIdentifier) -> EnclaveResult<()> { + trace!("Intializing shard config on integritee network"); + let extrinsics_factory = get_extrinsic_factory_from_integritee_solo_or_parachain()?; + let enclave_signer = get_stf_enclave_signer_from_solo_or_parachain()?; + let mrenclave = enclave_signer.ocall_api.get_mrenclave_of_self()?; + let shard_config = ShardConfig::::new(EnclaveFingerprint::from(mrenclave.m)); + + let call = extrinsics_factory + .node_metadata_repository + .get_from_metadata(|m| m.update_shard_config_call_indexes()) + .map_err(|e| Error::Other(e.into()))? + .map_err(|e| Error::Other(format!("{:?}", e).into()))?; + + let opaque_call = OpaqueCall::from_tuple(&(call, shard, shard_config, BlockNumber::from(0u8))); + debug!("encoded call: {}", hex_encode(opaque_call.encode().as_slice())); + let xts = extrinsics_factory + .create_extrinsics(&[opaque_call], None) + .map_err(|e| Error::Other(e.into()))?; + + info!("Initializing or touching shard config on integritee network. awaiting inclusion before continuing"); + // this needs to be blocking because the parentchain handler may be re-initialized right after this and the extrinsic would be swallowed + enclave_signer + .ocall_api + .send_to_parentchain(xts, &ParentchainId::Integritee, true) + .map_err(|e| Error::Other(e.into()))?; + Ok(()) +} diff --git a/enclave-runtime/src/shard_creation_info.rs b/enclave-runtime/src/shard_creation_info.rs new file mode 100644 index 0000000000..4eef7be830 --- /dev/null +++ b/enclave-runtime/src/shard_creation_info.rs @@ -0,0 +1,144 @@ +/* + 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/enclave-runtime/src/shard_vault.rs b/enclave-runtime/src/shard_vault.rs index 860f2ef56d..0f2ea89d8b 100644 --- a/enclave-runtime/src/shard_vault.rs +++ b/enclave-runtime/src/shard_vault.rs @@ -13,16 +13,20 @@ See the License for the specific language governing permissions and limitations under the License. */ - use crate::{ error::{Error, Result as EnclaveResult}, initialization::global_components::{ - GLOBAL_OCALL_API_COMPONENT, GLOBAL_SIGNING_KEY_REPOSITORY_COMPONENT, + EnclaveStf, GLOBAL_OCALL_API_COMPONENT, GLOBAL_SIGNING_KEY_REPOSITORY_COMPONENT, GLOBAL_STATE_HANDLER_COMPONENT, }, + std::string::ToString, utils::{ get_extrinsic_factory_from_integritee_solo_or_parachain, + get_extrinsic_factory_from_target_a_solo_or_parachain, + get_extrinsic_factory_from_target_b_solo_or_parachain, 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, DecodeRaw, }, }; use codec::{Compact, Decode, Encode}; @@ -30,35 +34,57 @@ use itp_component_container::ComponentGetter; use itp_extrinsics_factory::CreateExtrinsics; use itp_node_api::{ api_client::{PairSignature, StaticExtrinsicSigner}, - metadata::{ - pallet_proxy::PROXY_DEPOSIT, - provider::{AccessNodeMetadata, Error as MetadataProviderError}, - }, + metadata::provider::{AccessNodeMetadata, Error as MetadataProviderError}, }; use itp_node_api_metadata::pallet_proxy::ProxyCallIndexes; use itp_nonce_cache::NonceCache; use itp_ocall_api::EnclaveOnChainOCallApi; use itp_sgx_crypto::key_repository::AccessKey; -use itp_stf_interface::SHARD_VAULT_KEY; +use itp_stf_interface::{parentchain_pallet::ParentchainPalletInstancesInterface, ShardVaultQuery}; use itp_stf_state_handler::{handle_state::HandleState, query_shard_state::QueryShardState}; use itp_types::{ - parentchain::{AccountId, Address, ParentchainId, ProxyType}, + parentchain::{AccountId, Address, Balance, ParentchainId, ProxyType}, OpaqueCall, ShardIdentifier, }; use log::*; use sgx_types::sgx_status_t; use sp_core::crypto::{DeriveJunction, Pair}; -use std::{slice, sync::Arc, vec::Vec}; +use std::{slice, sync::Arc}; #[no_mangle] pub unsafe extern "C" fn init_proxied_shard_vault( shard: *const u8, shard_size: u32, + parentchain_id: *const u8, + parentchain_id_size: u32, + funding_balance: *const u8, + funding_balance_size: u32, ) -> sgx_status_t { let shard_identifier = ShardIdentifier::from_slice(slice::from_raw_parts(shard, shard_size as usize)); + let funding_balance = match Balance::decode(&mut slice::from_raw_parts( + funding_balance, + funding_balance_size as usize, + )) { + Ok(bal) => bal, + Err(e) => { + error!("Could not decode funding_balance: {:?}", e); + return sgx_status_t::SGX_ERROR_UNEXPECTED + }, + }; - if let Err(e) = init_proxied_shard_vault_internal(shard_identifier) { + 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_proxied_shard_vault_internal(shard_identifier, parentchain_id, funding_balance) + { error!("Failed to initialize proxied shard vault ({:?}): {:?}", shard_identifier, e); return sgx_status_t::SGX_ERROR_UNEXPECTED } @@ -76,57 +102,82 @@ pub unsafe extern "C" fn get_ecc_vault_pubkey( ) -> sgx_status_t { let shard = ShardIdentifier::from_slice(slice::from_raw_parts(shard, shard_size as usize)); - let shard_vault = match get_shard_vault_account(shard) { - Ok(account) => account, + let shard_vault = match get_shard_vault_internal(shard) { + Ok((account, _)) => account, Err(e) => { - error!("Failed to fetch shard vault account: {:?}", e); + warn!("Failed to fetch shard vault account: {:?}", e); return sgx_status_t::SGX_ERROR_UNEXPECTED }, }; - let pubkey_slice = slice::from_raw_parts_mut(pubkey, pubkey_size as usize); pubkey_slice.clone_from_slice(shard_vault.encode().as_slice()); sgx_status_t::SGX_SUCCESS } /// reads the shard vault account id form state if it has been initialized previously -pub(crate) fn get_shard_vault_account(shard: ShardIdentifier) -> EnclaveResult { +pub(crate) fn get_shard_vault_internal( + shard: ShardIdentifier, +) -> EnclaveResult<(AccountId, ParentchainId)> { let state_handler = GLOBAL_STATE_HANDLER_COMPONENT.get()?; - - state_handler - .execute_on_current(&shard, |state, _| { - state - .state - .get::>(&SHARD_VAULT_KEY.into()) - .and_then(|v| Decode::decode(&mut v.clone().as_slice()).ok()) - })? - .ok_or_else(|| { - Error::Other("failed to fetch shard vault account. has it been initialized?".into()) - }) + let (_state_lock, mut state) = state_handler.load_for_mutation(&shard)?; + EnclaveStf::get_vault(&mut state).ok_or_else(|| { + Error::Other("failed to fetch shard vault account. has it been initialized?".into()) + }) } -pub(crate) fn init_proxied_shard_vault_internal(shard: ShardIdentifier) -> EnclaveResult<()> { +pub(crate) fn init_proxied_shard_vault_internal( + shard: ShardIdentifier, + parentchain_id: ParentchainId, + funding_balance: Balance, +) -> EnclaveResult<()> { let state_handler = GLOBAL_STATE_HANDLER_COMPONENT.get()?; - if !state_handler.shard_exists(&shard).unwrap() { + if !state_handler + .shard_exists(&shard) + .map_err(|_| Error::Other("get shard_exists failed".into()))? + { return Err(Error::Other("shard not initialized".into())) }; let ocall_api = GLOBAL_OCALL_API_COMPONENT.get()?; let enclave_signer = GLOBAL_SIGNING_KEY_REPOSITORY_COMPONENT.get()?.retrieve_key()?; - let enclave_extrinsics_factory = get_extrinsic_factory_from_integritee_solo_or_parachain()?; - let node_metadata_repo = get_node_metadata_repository_from_integritee_solo_or_parachain()?; + let vault = enclave_signer .derive(vec![DeriveJunction::hard(shard.encode())].into_iter(), None) .map_err(|_| Error::Other("failed to derive shard vault keypair".into()))? .0; - info!("shard vault account derived pubkey: 0x{}", hex::encode(vault.public().0)); - let (state_lock, mut state) = state_handler.load_for_mutation(&shard)?; - state.state.insert(SHARD_VAULT_KEY.into(), vault.public().0.to_vec()); + EnclaveStf::init_shard_vault_account(&mut state, vault.public().into(), parentchain_id) + .map_err(|e| Error::Stf(e.to_string()))?; state_handler.write_after_mutation(state, state_lock, &shard)?; + let (enclave_extrinsics_factory, node_metadata_repo) = match parentchain_id { + ParentchainId::Integritee => { + let enclave_extrinsics_factory = + get_extrinsic_factory_from_integritee_solo_or_parachain()?; + let node_metadata_repo = + get_node_metadata_repository_from_integritee_solo_or_parachain()?; + (enclave_extrinsics_factory, node_metadata_repo) + }, + ParentchainId::TargetA => { + let enclave_extrinsics_factory = + get_extrinsic_factory_from_target_a_solo_or_parachain()?; + let node_metadata_repo = + get_node_metadata_repository_from_target_a_solo_or_parachain()?; + (enclave_extrinsics_factory, node_metadata_repo) + }, + ParentchainId::TargetB => { + let enclave_extrinsics_factory = + get_extrinsic_factory_from_target_b_solo_or_parachain()?; + let node_metadata_repo = + get_node_metadata_repository_from_target_b_solo_or_parachain()?; + (enclave_extrinsics_factory, node_metadata_repo) + }, + }; - info!("send existential funds from enclave account to vault account"); + info!( + "[{:?}] send existential funds from enclave account to vault account: {:?}", + parentchain_id, funding_balance + ); let call_ids = node_metadata_repo .get_from_metadata(|m| m.call_indexes("Balances", "transfer_keep_alive"))? .map_err(MetadataProviderError::MetadataError)?; @@ -134,21 +185,21 @@ pub(crate) fn init_proxied_shard_vault_internal(shard: ShardIdentifier) -> Encla let call = OpaqueCall::from_tuple(&( call_ids, Address::from(AccountId::from(vault.public().0)), - Compact(PROXY_DEPOSIT), + Compact(funding_balance), )); - info!("vault funding call: 0x{}", hex::encode(call.0.clone())); + info!("[{:?}] vault funding call: 0x{}", parentchain_id, hex::encode(call.0.clone())); let xts = enclave_extrinsics_factory.create_extrinsics(&[call], None)?; //this extrinsic must be included in a block before we can move on. otherwise the next will fail - ocall_api.send_to_parentchain(xts, &ParentchainId::Integritee, true)?; + ocall_api.send_to_parentchain(xts, &parentchain_id, true)?; // we are assuming nonce=0 here. let nonce_cache = Arc::new(NonceCache::default()); let vault_extrinsics_factory = enclave_extrinsics_factory .with_signer(StaticExtrinsicSigner::<_, PairSignature>::new(vault), nonce_cache); - info!("register enclave signer as proxy for shard vault"); + info!("[{:?}] register enclave signer as proxy for shard vault", parentchain_id); let call_ids = node_metadata_repo .get_from_metadata(|m| m.call_indexes("Proxy", "add_proxy"))? .map_err(MetadataProviderError::MetadataError)?; @@ -160,10 +211,10 @@ pub(crate) fn init_proxied_shard_vault_internal(shard: ShardIdentifier) -> Encla 0u32, // delay )); - info!("add proxy call: 0x{}", hex::encode(call.0.clone())); + info!("[{:?}] add proxy call: 0x{}", parentchain_id, hex::encode(call.0.clone())); let xts = vault_extrinsics_factory.create_extrinsics(&[call], None)?; - ocall_api.send_to_parentchain(xts, &ParentchainId::Integritee, false)?; + ocall_api.send_to_parentchain(xts, &parentchain_id, false)?; Ok(()) } @@ -172,19 +223,33 @@ pub(crate) fn add_shard_vault_proxy( proxy: &AccountId, ) -> EnclaveResult<()> { let state_handler = GLOBAL_STATE_HANDLER_COMPONENT.get()?; - if !state_handler.shard_exists(&shard).unwrap() { + if !state_handler + .shard_exists(&shard) + .map_err(|_| Error::Other("get shard_exists failed".into()))? + { return Err(Error::Other("shard not initialized".into())) }; let ocall_api = GLOBAL_OCALL_API_COMPONENT.get()?; - let enclave_extrinsics_factory = get_extrinsic_factory_from_integritee_solo_or_parachain()?; - let node_metadata_repo = get_node_metadata_repository_from_integritee_solo_or_parachain()?; - let vault = get_shard_vault_account(shard)?; + let (vault, parentchain_id) = get_shard_vault_internal(shard)?; + + let enclave_extrinsics_factory = match parentchain_id { + ParentchainId::Integritee => get_extrinsic_factory_from_integritee_solo_or_parachain()?, + ParentchainId::TargetA => get_extrinsic_factory_from_target_a_solo_or_parachain()?, + ParentchainId::TargetB => get_extrinsic_factory_from_target_b_solo_or_parachain()?, + }; + let node_metadata_repo = match parentchain_id { + ParentchainId::Integritee => + 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()?, + }; debug!( - "adding proxy 0x{} to shard vault account 0x{}", + "adding proxy 0x{} to shard vault account 0x{} on {:?}", hex::encode(proxy.clone()), - hex::encode(vault.clone()) + hex::encode(vault.clone()), + parentchain_id, ); let add_proxy_call = OpaqueCall::from_tuple(&( diff --git a/enclave-runtime/src/teeracle/mod.rs b/enclave-runtime/src/teeracle/mod.rs index 75f378c9a0..029c5fffd3 100644 --- a/enclave-runtime/src/teeracle/mod.rs +++ b/enclave-runtime/src/teeracle/mod.rs @@ -107,7 +107,8 @@ pub unsafe extern "C" fn update_weather_data_xt( weather_info_latitude: *const u8, weather_info_latitude_size: u32, unchecked_extrinsic: *mut u8, - unchecked_extrinsic_size: u32, + unchecked_extrinsic_max_size: u32, + unchecked_extrinsic_size: *mut u32, ) -> sgx_status_t { let mut weather_info_longitude_slice = slice::from_raw_parts(weather_info_longitude, weather_info_longitude_size as usize); @@ -141,13 +142,17 @@ pub unsafe extern "C" fn update_weather_data_xt( }; let extrinsic_slice = - slice::from_raw_parts_mut(unchecked_extrinsic, unchecked_extrinsic_size as usize); + slice::from_raw_parts_mut(unchecked_extrinsic, unchecked_extrinsic_max_size as usize); // Save created extrinsic as slice in the return value unchecked_extrinsic. - if let Err(e) = write_slice_and_whitespace_pad(extrinsic_slice, extrinsics.encode()) { - error!("Copying encoded extrinsics into return slice failed: {:?}", e); - return sgx_status_t::SGX_ERROR_UNEXPECTED - } + *unchecked_extrinsic_size = + match write_slice_and_whitespace_pad(extrinsic_slice, extrinsics.encode()) { + Ok(l) => l as u32, + Err(e) => { + error!("Copying encoded extrinsics into return slice failed: {:?}", e); + return sgx_status_t::SGX_ERROR_UNEXPECTED + }, + }; sgx_status_t::SGX_SUCCESS } @@ -160,7 +165,8 @@ pub unsafe extern "C" fn update_market_data_xt( fiat_currency_ptr: *const u8, fiat_currency_size: u32, unchecked_extrinsic: *mut u8, - unchecked_extrinsic_size: u32, + unchecked_extrinsic_max_size: u32, + unchecked_extrinsic_size: *mut u32, ) -> sgx_status_t { let mut crypto_currency_slice = slice::from_raw_parts(crypto_currency_ptr, crypto_currency_size as usize); @@ -183,13 +189,17 @@ pub unsafe extern "C" fn update_market_data_xt( return sgx_status_t::SGX_ERROR_UNEXPECTED } let extrinsic_slice = - slice::from_raw_parts_mut(unchecked_extrinsic, unchecked_extrinsic_size as usize); + slice::from_raw_parts_mut(unchecked_extrinsic, unchecked_extrinsic_max_size as usize); // Save created extrinsic as slice in the return value unchecked_extrinsic. - if let Err(e) = write_slice_and_whitespace_pad(extrinsic_slice, extrinsics.encode()) { - error!("Copying encoded extrinsics into return slice failed: {:?}", e); - return sgx_status_t::SGX_ERROR_UNEXPECTED - } + *unchecked_extrinsic_size = + match write_slice_and_whitespace_pad(extrinsic_slice, extrinsics.encode()) { + Ok(l) => l as u32, + Err(e) => { + error!("Copying encoded extrinsics into return slice failed: {:?}", e); + return sgx_status_t::SGX_ERROR_UNEXPECTED + }, + }; sgx_status_t::SGX_SUCCESS } diff --git a/enclave-runtime/src/test/cert_tests.rs b/enclave-runtime/src/test/cert_tests.rs index c5eaab9f89..ad3b78df76 100644 --- a/enclave-runtime/src/test/cert_tests.rs +++ b/enclave-runtime/src/test/cert_tests.rs @@ -28,6 +28,7 @@ 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() { diff --git a/enclave-runtime/src/test/enclave_signer_tests.rs b/enclave-runtime/src/test/enclave_signer_tests.rs index 30efe3611d..998b565279 100644 --- a/enclave-runtime/src/test/enclave_signer_tests.rs +++ b/enclave-runtime/src/test/enclave_signer_tests.rs @@ -25,8 +25,8 @@ use itp_sgx_crypto::{ 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, + mocks::GetterExecutorMock, parentchain_pallet::ParentchainPalletInstancesInterface, + system_pallet::SystemPalletAccountInterface, InitState, StateCallInterface, }; use itp_stf_primitives::{ traits::TrustedCallVerification, @@ -35,6 +35,7 @@ use itp_stf_primitives::{ 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; use sgx_crypto_helper::{rsa3072::Rsa3072KeyPair, RsaKeyPair}; use sp_core::Pair; use std::{sync::Arc, vec::Vec}; @@ -72,8 +73,12 @@ pub fn enclave_signer_signatures_are_valid() { shielding_key_repo, top_pool_author, ); - let trusted_call = - TrustedCall::balance_shield(enclave_account, AccountId::new([3u8; 32]), 200u128); + let trusted_call = TrustedCall::balance_shield( + enclave_account, + AccountId::new([3u8; 32]), + 200u128, + ParentchainId::Integritee, + ); let trusted_call_signed = enclave_signer.sign_call_with_self(&trusted_call, &shard).unwrap(); assert!(trusted_call_signed.verify_signature(&mr_enclave.m, &shard)); @@ -91,6 +96,8 @@ pub fn nonce_is_computed_correctly() { .public() .into(); let mut state = TestStf::init_state(enclave_account.clone()); + let vault = AccountId::new([2u8; 32]); + TestStf::init_shard_vault_account(&mut state, vault, ParentchainId::Integritee).unwrap(); // only used to create the enclave signer, the state is **not** synchronised let state_observer: Arc> = Arc::new(ObserveStateMock::new(state.clone())); @@ -104,8 +111,12 @@ pub fn nonce_is_computed_correctly() { 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(enclave_account.clone(), AccountId::new([1u8; 32]), 100u128); + let trusted_call_1 = TrustedCall::balance_shield( + enclave_account.clone(), + AccountId::new([1u8; 32]), + 100u128, + ParentchainId::Integritee, + ); let trusted_call_1_signed = enclave_signer.sign_call_with_self(&trusted_call_1, &shard).unwrap(); top_pool_author.submit_top( @@ -115,8 +126,12 @@ pub fn nonce_is_computed_correctly() { ); 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(enclave_account.clone(), AccountId::new([2u8; 32]), 200u128); + let trusted_call_2 = TrustedCall::balance_shield( + enclave_account.clone(), + AccountId::new([2u8; 32]), + 200u128, + ParentchainId::Integritee, + ); let trusted_call_2_signed = enclave_signer.sign_call_with_self(&trusted_call_2, &shard).unwrap(); top_pool_author.submit_top( diff --git a/enclave-runtime/src/test/evm_pallet_tests.rs b/enclave-runtime/src/test/evm_pallet_tests.rs index fef912a289..228555bfab 100644 --- a/enclave-runtime/src/test/evm_pallet_tests.rs +++ b/enclave-runtime/src/test/evm_pallet_tests.rs @@ -29,7 +29,7 @@ use itp_node_api::metadata::{metadata_mocks::NodeMetadataMock, provider::NodeMet use itp_sgx_externalities::SgxExternalitiesTrait; use itp_stf_interface::StateCallInterface; use itp_stf_primitives::{traits::TrustedCallSigning, types::KeyPair}; -use itp_types::{AccountId, OpaqueCall, ShardIdentifier}; +use itp_types::{parentchain::ParentchainCall, AccountId, ShardIdentifier}; use primitive_types::H256; use sp_core::{crypto::Pair, H160, U256}; use std::{sync::Arc, vec::Vec}; @@ -37,7 +37,7 @@ use std::{sync::Arc, vec::Vec}; pub fn test_evm_call() { // given let (_, mut state, shard, mrenclave, ..) = test_setup(); - let mut opaque_vec = Vec::new(); + let mut parentchain_calls = Vec::new(); // Create the sender account. let sender = funded_pair(); @@ -74,11 +74,11 @@ pub fn test_evm_call() { Some(U256::from(0)), Vec::new(), ) - .sign(&sender.clone().into(), 0, &mrenclave, &shard); + .sign(&sender.into(), 0, &mrenclave, &shard); // when let repo = Arc::new(NodeMetadataRepository::::default()); - TestStf::execute_call(&mut state, trusted_call, &mut opaque_vec, repo).unwrap(); + TestStf::execute_call(&mut state, trusted_call, &mut parentchain_calls, repo).unwrap(); // then assert_eq!( @@ -90,7 +90,7 @@ pub fn test_evm_call() { pub fn test_evm_counter() { // given let (_, mut state, shard, mrenclave, ..) = test_setup(); - let mut opaque_vec = Vec::new(); + let mut parentchain_calls = Vec::new(); // Create the sender account. let sender = funded_pair(); @@ -118,12 +118,12 @@ pub fn test_evm_counter() { Some(U256::from(0)), Vec::new(), ) - .sign(&sender.clone().into(), 0, &mrenclave, &shard); + .sign(&sender.into(), 0, &mrenclave, &shard); // when let execution_address = evm_create_address(sender_evm_acc, 0); let repo = Arc::new(NodeMetadataRepository::::default()); - TestStf::execute_call(&mut state, trusted_call, &mut opaque_vec, repo).unwrap(); + TestStf::execute_call(&mut state, trusted_call, &mut parentchain_calls, repo).unwrap(); // then assert_eq!( @@ -155,11 +155,11 @@ pub fn test_evm_counter() { inc_function_input.to_vec(), 1, 1, - sender.clone().into(), + sender.into(), &mrenclave, &shard, &mut state, - &mut opaque_vec, + &mut parentchain_calls, 2, ); @@ -171,11 +171,11 @@ pub fn test_evm_counter() { Vec::new(), // Empty input calls the fallback function. 2, 2, - sender.clone().into(), + sender.into(), &mrenclave, &shard, &mut state, - &mut opaque_vec, + &mut parentchain_calls, 5, ); @@ -188,11 +188,11 @@ pub fn test_evm_counter() { inc_function_input, 3, 3, - sender.clone().into(), + sender.into(), &mrenclave, &shard, &mut state, - &mut opaque_vec, + &mut parentchain_calls, 6, ); @@ -205,21 +205,22 @@ pub fn test_evm_counter() { array_bytes::hex2bytes(&format!("{}{}", function_hash, add_value)).unwrap(); execute_and_verify_evm_call( - sender_acc.clone(), + sender_acc, sender_evm_acc, execution_address, add_function_input, 4, 4, - sender.clone().into(), + sender.into(), &mrenclave, &shard, &mut state, - &mut opaque_vec, + &mut parentchain_calls, 8, ); } +#[allow(clippy::too_many_arguments)] fn execute_and_verify_evm_call( sender_acc: AccountId, sender_evm_acc: H160, @@ -231,7 +232,7 @@ fn execute_and_verify_evm_call( mrenclave: &[u8; 32], shard: &ShardIdentifier, state: &mut State, - calls: &mut Vec, + calls: &mut Vec, counter_expected: u64, ) { let inc_call = TrustedCall::evm_call( @@ -246,7 +247,7 @@ fn execute_and_verify_evm_call( Some(U256::from(evm_nonce)), Vec::new(), ) - .sign(&pair, nonce, &mrenclave, &shard); + .sign(&pair, nonce, mrenclave, shard); let repo = Arc::new(NodeMetadataRepository::::default()); TestStf::execute_call(state, inc_call, calls, repo).unwrap(); @@ -259,7 +260,7 @@ fn execute_and_verify_evm_call( pub fn test_evm_create() { // given let (_, mut state, shard, mrenclave, ..) = test_setup(); - let mut opaque_vec = Vec::new(); + let mut parentchain_calls = Vec::new(); // Create the sender account. let sender = funded_pair(); @@ -277,7 +278,7 @@ pub fn test_evm_create() { let smart_contract = array_bytes::hex2bytes(smart_contract).unwrap(); let trusted_call = TrustedCall::evm_create( - sender_acc.clone(), + sender_acc, sender_evm_acc, smart_contract, U256::from(0), // value @@ -287,14 +288,14 @@ pub fn test_evm_create() { Some(U256::from(0)), Vec::new(), ) - .sign(&sender.clone().into(), 0, &mrenclave, &shard); + .sign(&sender.into(), 0, &mrenclave, &shard); // Should be the first call of the evm account let nonce = state.execute_with(|| System::account_nonce(&sender_evm_substrate_addr)); assert_eq!(nonce, 0); let execution_address = evm_create_address(sender_evm_acc, nonce); let repo = Arc::new(NodeMetadataRepository::::default()); - TestStf::execute_call(&mut state, trusted_call, &mut opaque_vec, repo).unwrap(); + TestStf::execute_call(&mut state, trusted_call, &mut parentchain_calls, repo).unwrap(); assert_eq!( execution_address, @@ -313,7 +314,7 @@ pub fn test_evm_create() { pub fn test_evm_create2() { // given let (_, mut state, shard, mrenclave, ..) = test_setup(); - let mut opaque_vec = Vec::new(); + let mut parentchain_calls = Vec::new(); // Create the sender account. let sender = funded_pair(); @@ -332,7 +333,7 @@ pub fn test_evm_create2() { let smart_contract = array_bytes::hex2bytes(smart_contract).unwrap(); let trusted_call = TrustedCall::evm_create2( - sender_acc.clone(), + sender_acc, sender_evm_acc, smart_contract.clone(), salt, @@ -343,13 +344,13 @@ pub fn test_evm_create2() { Some(U256::from(0)), Vec::new(), ) - .sign(&sender.clone().into(), 0, &mrenclave, &shard); + .sign(&sender.into(), 0, &mrenclave, &shard); // when let code_hash = create_code_hash(&smart_contract); let execution_address = evm_create2_address(sender_evm_acc, salt, code_hash); let repo = Arc::new(NodeMetadataRepository::::default()); - TestStf::execute_call(&mut state, trusted_call, &mut opaque_vec, repo).unwrap(); + TestStf::execute_call(&mut state, trusted_call, &mut parentchain_calls, repo).unwrap(); // then assert_eq!( diff --git a/enclave-runtime/src/test/fixtures/initialize_test_state.rs b/enclave-runtime/src/test/fixtures/initialize_test_state.rs index 98e23261b6..dc2bd0e4f0 100644 --- a/enclave-runtime/src/test/fixtures/initialize_test_state.rs +++ b/enclave-runtime/src/test/fixtures/initialize_test_state.rs @@ -17,12 +17,12 @@ */ use super::test_setup::TestStf; -use ita_stf::State; +use ita_stf::{stf_sgx_tests::StfState, State}; use itp_sgx_externalities::{SgxExternalities, SgxExternalitiesTrait}; -use itp_stf_interface::InitState; +use itp_stf_interface::{parentchain_pallet::ParentchainPalletInstancesInterface, InitState}; use itp_stf_primitives::types::AccountId; use itp_stf_state_handler::handle_state::HandleState; -use itp_types::ShardIdentifier; +use itp_types::{parentchain::ParentchainId, ShardIdentifier}; /// Returns an empty `State` with the corresponding `ShardIdentifier`. pub fn init_state>( @@ -34,6 +34,10 @@ pub fn init_state>( 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); + + let vault = AccountId::new([42u8; 32]); + StfState::init_shard_vault_account(&mut state, vault, ParentchainId::Integritee).unwrap(); + state.prune_state_diff(); state_handler.write_after_mutation(state.clone(), lock, &shard).unwrap(); diff --git a/enclave-runtime/src/test/fixtures/test_setup.rs b/enclave-runtime/src/test/fixtures/test_setup.rs index a1deee2443..27d6df863c 100644 --- a/enclave-runtime/src/test/fixtures/test_setup.rs +++ b/enclave-runtime/src/test/fixtures/test_setup.rs @@ -111,10 +111,7 @@ pub fn test_setup() -> ( pub fn test_top_pool() -> TestTopPool { let chain_api = Arc::new(SidechainApi::::new()); - let top_pool = - BasicPool::create(Default::default(), chain_api, Arc::new(TestRpcResponder::new())); - - top_pool + BasicPool::create(Default::default(), chain_api, Arc::new(TestRpcResponder::new())) } pub fn enclave_call_signer(key_source: &Source) -> spEd25519::Pair { diff --git a/enclave-runtime/src/test/ipfs_tests.rs b/enclave-runtime/src/test/ipfs_tests.rs index 27b187a047..f1f94d3696 100644 --- a/enclave-runtime/src/test/ipfs_tests.rs +++ b/enclave-runtime/src/test/ipfs_tests.rs @@ -31,7 +31,7 @@ fn test_ocall_read_write_ipfs() { 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 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()); diff --git a/enclave-runtime/src/test/mocks/rpc_responder_mock.rs b/enclave-runtime/src/test/mocks/rpc_responder_mock.rs index 74e22a29e1..3628f1480c 100644 --- a/enclave-runtime/src/test/mocks/rpc_responder_mock.rs +++ b/enclave-runtime/src/test/mocks/rpc_responder_mock.rs @@ -28,6 +28,11 @@ impl RpcResponderMock { RpcResponderMock { _hash: PhantomData } } } +impl Default for RpcResponderMock { + fn default() -> Self { + Self::new() + } +} impl SendRpcResponse for RpcResponderMock where diff --git a/enclave-runtime/src/test/sidechain_aura_tests.rs b/enclave-runtime/src/test/sidechain_aura_tests.rs index fa52b8aae5..14420a6500 100644 --- a/enclave-runtime/src/test/sidechain_aura_tests.rs +++ b/enclave-runtime/src/test/sidechain_aura_tests.rs @@ -34,9 +34,7 @@ use ita_stf::{ test_genesis::{endowed_account, second_endowed_account, unendowed_account}, Balance, Getter, TrustedCall, TrustedCallSigned, }; -use itc_parentchain::light_client::mocks::validator_access_mock::ValidatorAccessMock; use itc_parentchain_test::ParentchainHeaderBuilder; -use itp_extrinsics_factory::mock::ExtrinsicsFactoryMock; use itp_node_api::metadata::{metadata_mocks::NodeMetadataMock, provider::NodeMetadataRepository}; use itp_ocall_api::EnclaveAttestationOCallApi; use itp_settings::{ @@ -97,7 +95,7 @@ pub fn produce_sidechain_block_and_import_it() { let stf_executor = Arc::new(TestStfExecutor::new( ocall_api.clone(), state_handler.clone(), - node_metadata_repo.clone(), + node_metadata_repo, )); let top_pool = create_top_pool(); @@ -116,11 +114,9 @@ pub fn produce_sidechain_block_and_import_it() { parentchain_block_import_trigger.clone(), ocall_api.clone(), )); - let block_composer = Arc::new(TestBlockComposer::new(signer.clone(), state_key_repo.clone())); + let block_composer = Arc::new(TestBlockComposer::new(signer, state_key_repo)); let proposer_environment = - ProposerFactory::new(top_pool_author.clone(), stf_executor.clone(), block_composer); - let extrinsics_factory = ExtrinsicsFactoryMock::default(); - let validator_access = ValidatorAccessMock::default(); + ProposerFactory::new(top_pool_author.clone(), stf_executor, block_composer); info!("Create trusted operations.."); let sender = endowed_account(); @@ -141,7 +137,7 @@ pub fn produce_sidechain_block_and_import_it() { &shielding_key, sender_with_low_balance, receiver.public().into(), - 200000, + ita_stf::test_genesis::SECOND_ENDOWED_ACC_FUNDS + 1, ); info!("Add trusted operations to TOP pool.."); executor::block_on(top_pool_author.submit_top(trusted_operation, shard_id)).unwrap(); @@ -155,8 +151,15 @@ pub fn produce_sidechain_block_and_import_it() { let timestamp = duration_now(); let slot = slot_from_timestamp_and_duration(duration_now(), SLOT_DURATION); let ends_at = timestamp + SLOT_DURATION; - let slot_info = - SlotInfo::new(slot, timestamp, SLOT_DURATION, ends_at, parentchain_header.clone()); + let slot_info = SlotInfo::new( + slot, + timestamp, + SLOT_DURATION, + ends_at, + parentchain_header.clone(), + None, + None, + ); info!("Test setup is done."); @@ -164,11 +167,13 @@ pub fn produce_sidechain_block_and_import_it() { info!("Executing AURA on slot.."); let (blocks, opaque_calls) = - exec_aura_on_slot::<_, ParentchainBlock, SignedSidechainBlock, _, _, _>( + exec_aura_on_slot::<_, ParentchainBlock, SignedSidechainBlock, _, _, _, _, _>( slot_info, signer, - ocall_api.clone(), + ocall_api, parentchain_block_import_trigger.clone(), + None::>, + None::>, proposer_environment, shards, ) @@ -195,12 +200,10 @@ pub fn produce_sidechain_block_and_import_it() { let propose_to_block_import_ocall_api = Arc::new(ProposeToImportOCallApi::new(parentchain_header, block_importer)); - send_blocks_and_extrinsics::( + send_blocks_and_extrinsics::( blocks, opaque_calls, propose_to_block_import_ocall_api, - &validator_access, - &extrinsics_factory, ) .unwrap(); @@ -219,7 +222,7 @@ pub fn produce_sidechain_block_and_import_it() { let free_balance = TestStf::get_account_data(&mut state, &receiver.public().into()).free; assert_eq!(free_balance, transfered_amount); assert!(TestStf::get_event_count(&mut state) > 0); - assert!(TestStf::get_events(&mut state).len() > 0); + assert!(!TestStf::get_events(&mut state).is_empty()); } fn encrypted_trusted_operation_transfer_balance< diff --git a/enclave-runtime/src/test/sidechain_event_tests.rs b/enclave-runtime/src/test/sidechain_event_tests.rs index bf83f551f6..ef291bf849 100644 --- a/enclave-runtime/src/test/sidechain_event_tests.rs +++ b/enclave-runtime/src/test/sidechain_event_tests.rs @@ -29,9 +29,7 @@ use crate::{ }; use ita_sgx_runtime::Runtime; use ita_stf::{helpers::set_block_number, Getter, TrustedCallSigned}; -use itc_parentchain::light_client::mocks::validator_access_mock::ValidatorAccessMock; use itc_parentchain_test::ParentchainHeaderBuilder; -use itp_extrinsics_factory::mock::ExtrinsicsFactoryMock; use itp_node_api::metadata::{metadata_mocks::NodeMetadataMock, provider::NodeMetadataRepository}; use itp_settings::{ sidechain::SLOT_DURATION, @@ -85,7 +83,7 @@ pub fn ensure_events_get_reset_upon_block_proposal() { let stf_executor = Arc::new(TestStfExecutor::new( ocall_api.clone(), state_handler.clone(), - node_metadata_repo.clone(), + node_metadata_repo, )); let top_pool = create_top_pool(); @@ -104,11 +102,8 @@ pub fn ensure_events_get_reset_upon_block_proposal() { parentchain_block_import_trigger.clone(), ocall_api.clone(), )); - let block_composer = Arc::new(TestBlockComposer::new(signer.clone(), state_key_repo.clone())); - let proposer_environment = - ProposerFactory::new(top_pool_author.clone(), stf_executor.clone(), block_composer); - let extrinsics_factory = ExtrinsicsFactoryMock::default(); - let validator_access = ValidatorAccessMock::default(); + let block_composer = Arc::new(TestBlockComposer::new(signer, state_key_repo)); + let proposer_environment = ProposerFactory::new(top_pool_author, stf_executor, block_composer); // Add some events to the state. let topic_hash = H256::from([7; 32]); @@ -133,16 +128,25 @@ pub fn ensure_events_get_reset_upon_block_proposal() { let timestamp = duration_now(); let slot = slot_from_timestamp_and_duration(duration_now(), SLOT_DURATION); let ends_at = timestamp + SLOT_DURATION; - let slot_info = - SlotInfo::new(slot, timestamp, SLOT_DURATION, ends_at, parentchain_header.clone()); + let slot_info = SlotInfo::new( + slot, + timestamp, + SLOT_DURATION, + ends_at, + parentchain_header.clone(), + None, + None, + ); info!("Executing AURA on slot.."); let (blocks, opaque_calls) = - exec_aura_on_slot::<_, ParentchainBlock, SignedSidechainBlock, _, _, _>( + exec_aura_on_slot::<_, ParentchainBlock, SignedSidechainBlock, _, _, _, _, _>( slot_info, signer, - ocall_api.clone(), - parentchain_block_import_trigger.clone(), + ocall_api, + parentchain_block_import_trigger, + None::>, + None::>, proposer_environment, shards, ) @@ -152,12 +156,10 @@ pub fn ensure_events_get_reset_upon_block_proposal() { let propose_to_block_import_ocall_api = Arc::new(ProposeToImportOCallApi::new(parentchain_header, block_importer)); - send_blocks_and_extrinsics::( + send_blocks_and_extrinsics::( blocks, opaque_calls, propose_to_block_import_ocall_api, - &validator_access, - &extrinsics_factory, ) .unwrap(); diff --git a/enclave-runtime/src/test/tests_main.rs b/enclave-runtime/src/test/tests_main.rs index be88d19a8a..b71b004b65 100644 --- a/enclave-runtime/src/test/tests_main.rs +++ b/enclave-runtime/src/test/tests_main.rs @@ -32,7 +32,7 @@ use crate::{ tls_ra, }; use codec::Decode; -use ita_sgx_runtime::Parentchain; +use ita_sgx_runtime::ParentchainIntegritee; use ita_stf::{ helpers::{account_key_hash, set_block_number}, stf_sgx_tests, @@ -46,7 +46,7 @@ use itp_stf_executor::{ executor_tests as stf_executor_tests, traits::StateUpdateProposer, BatchExecutionResult, }; use itp_stf_interface::{ - parentchain_pallet::ParentchainPalletInterface, + parentchain_pallet::ParentchainPalletInstancesInterface, system_pallet::{SystemPalletAccountInterface, SystemPalletEventInterface}, StateCallInterface, }; @@ -57,7 +57,7 @@ use itp_stf_primitives::{ 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::{AccountId, Block, Header}; +use itp_types::{parentchain::ParentchainId, AccountId, Balance, Block, Header}; use its_primitives::{ traits::{ Block as BlockTrait, BlockData, Header as SidechainHeaderTrait, @@ -290,12 +290,11 @@ fn test_differentiate_getter_and_call_works() { // create accounts let sender = funded_pair(); - let signed_getter = - TrustedGetter::free_balance(sender.public().into()).sign(&sender.clone().into()); + let signed_getter = TrustedGetter::free_balance(sender.public().into()).sign(&sender.into()); let signed_call = TrustedCall::balance_set_balance(sender.public().into(), sender.public().into(), 42, 42) - .sign(&sender.clone().into(), 0, &mrenclave, &shard); + .sign(&sender.into(), 0, &mrenclave, &shard); let trusted_operation = direct_top(signed_call); // when @@ -352,8 +351,7 @@ fn test_create_block_and_confirmation_works() { // when let execution_result = execute_trusted_calls(&shard, stf_executor.as_ref(), &top_pool_author); - let executed_operation_hashes = - execution_result.get_executed_operation_hashes().iter().copied().collect(); + let executed_operation_hashes = execution_result.get_executed_operation_hashes().to_vec(); let signed_block = block_composer .compose_block( @@ -382,9 +380,13 @@ fn test_create_state_diff() { let sender = funded_pair(); let receiver = unfunded_public(); - - let signed_call = TrustedCall::balance_transfer(sender.public().into(), receiver.into(), 1000) - .sign(&sender.clone().into(), 0, &mrenclave, &shard); + const TX_AMOUNT: Balance = 1_000_000_000_000; + let signed_call = TrustedCall::balance_transfer( + sender.public().into(), + receiver.into(), + TX_AMOUNT, + ) + .sign(&sender.into(), 0, &mrenclave, &shard); let trusted_operation = direct_top(signed_call); submit_operation_to_top_pool( @@ -398,8 +400,7 @@ fn test_create_state_diff() { // when let execution_result = execute_trusted_calls(&shard, stf_executor.as_ref(), &top_pool_author); - let executed_operation_hashes = - execution_result.get_executed_operation_hashes().iter().copied().collect(); + let executed_operation_hashes = execution_result.get_executed_operation_hashes().to_vec(); let signed_block = block_composer .compose_block( @@ -418,16 +419,19 @@ fn test_create_state_diff() { // then let sender_acc_info: AccountInfo = - get_from_state_diff(&state_diff, &account_key_hash::(&sender.public().into())); + get_from_state_diff(state_diff, &account_key_hash::(&sender.public().into())); let receiver_acc_info: AccountInfo = - get_from_state_diff(&state_diff, &account_key_hash::(&receiver.into())); + get_from_state_diff(state_diff, &account_key_hash::(&receiver.into())); // state diff should consist of the following updates: - // (last_hash, sidechain block_number, sender_funds, receiver_funds, [no clear, after polkadot_v0.9.26 update], events) - assert_eq!(state_diff.len(), 6); - assert_eq!(receiver_acc_info.data.free, 1000); - assert_eq!(sender_acc_info.data.free, 1000); + // (last_hash, sidechain block_number, sender_funds, receiver_funds, fee_recipient account [no clear, after polkadot_v0.9.26 update], events) + assert_eq!(state_diff.len(), 7); + assert_eq!(receiver_acc_info.data.free, TX_AMOUNT); + assert_eq!( + sender_acc_info.data.free, + ita_stf::test_genesis::ENDOWED_ACC_FUNDS - TX_AMOUNT - ita_stf::STF_TX_FEE + ); } fn test_executing_call_updates_account_nonce() { @@ -439,7 +443,7 @@ fn test_executing_call_updates_account_nonce() { let trusted_operation = TrustedCall::balance_transfer(sender.public().into(), receiver.into(), 1000) - .sign(&sender.clone().into(), 0, &mrenclave, &shard) + .sign(&sender.into(), 0, &mrenclave, &shard) .into_trusted_operation(false); submit_operation_to_top_pool( @@ -476,11 +480,11 @@ fn test_call_set_update_parentchain_block() { Default::default(), ); - TestStf::update_parentchain_block(&mut state, header.clone()).unwrap(); + TestStf::update_parentchain_integritee_block(&mut state, header.clone()).unwrap(); - assert_eq!(header.hash(), state.execute_with(|| Parentchain::block_hash())); - assert_eq!(parent_hash, state.execute_with(|| Parentchain::parent_hash())); - assert_eq!(block_number, state.execute_with(|| Parentchain::block_number())); + assert_eq!(Some(header.hash()), state.execute_with(ParentchainIntegritee::block_hash)); + assert_eq!(Some(parent_hash), state.execute_with(ParentchainIntegritee::parent_hash)); + assert_eq!(Some(block_number), state.execute_with(ParentchainIntegritee::block_number)); } fn test_signature_must_match_public_sender_in_call() { @@ -493,7 +497,7 @@ fn test_signature_must_match_public_sender_in_call() { let trusted_operation = TrustedCall::balance_transfer(victim.into(), receiver.public().into(), 1000) - .sign(&receiver.clone().into(), 10, &mrenclave, &shard) + .sign(&receiver.into(), 10, &mrenclave, &shard) .into_trusted_operation(true); submit_operation_to_top_pool( @@ -520,7 +524,7 @@ fn test_invalid_nonce_call_is_not_executed() { let trusted_operation = TrustedCall::balance_transfer(sender.public().into(), receiver.into(), 1000) - .sign(&sender.clone().into(), 10, &mrenclave, &shard) + .sign(&sender.into(), 10, &mrenclave, &shard) .into_trusted_operation(true); submit_operation_to_top_pool( @@ -544,8 +548,13 @@ fn test_non_root_shielding_call_is_not_executed() { let sender = funded_pair(); let sender_acc: AccountId = sender.public().into(); - let signed_call = TrustedCall::balance_shield(sender_acc.clone(), sender_acc.clone(), 1000) - .sign(&sender.into(), 0, &mrenclave, &shard); + let signed_call = TrustedCall::balance_shield( + sender_acc.clone(), + sender_acc, + 1000, + ParentchainId::Integritee, + ) + .sign(&sender.into(), 0, &mrenclave, &shard); submit_operation_to_top_pool( top_pool_author.as_ref(), @@ -571,8 +580,9 @@ fn test_shielding_call_with_enclave_self_is_executed() { let signed_call = TrustedCall::balance_shield( enclave_call_signer.public().into(), - sender_account.clone(), + sender_account, 1000, + ParentchainId::Integritee, ) .sign(&enclave_call_signer.into(), 0, &mrenclave, &shard); let trusted_operation = @@ -611,11 +621,11 @@ pub fn test_retrieve_events() { receiver.public().into(), transfer_value, ) - .sign(&sender.clone().into(), 0, &mrenclave, &shard); + .sign(&sender.into(), 0, &mrenclave, &shard); let repo = Arc::new(NodeMetadataRepository::::default()); TestStf::execute_call(&mut state, trusted_call, &mut opaque_vec, repo).unwrap(); - assert_eq!(TestStf::get_events(&mut state).len(), 3); + assert_eq!(TestStf::get_events(&mut state).len(), 4); } pub fn test_retrieve_event_count() { @@ -633,14 +643,14 @@ pub fn test_retrieve_event_count() { receiver.public().into(), transfer_value, ) - .sign(&sender.clone().into(), 0, &mrenclave, &shard); + .sign(&sender.into(), 0, &mrenclave, &shard); // when let repo = Arc::new(NodeMetadataRepository::::default()); TestStf::execute_call(&mut state, trusted_call, &mut opaque_vec, repo).unwrap(); let event_count = TestStf::get_event_count(&mut state); - assert_eq!(event_count, 3); + assert_eq!(event_count, 4); } pub fn test_reset_events() { @@ -657,13 +667,13 @@ pub fn test_reset_events() { receiver.public().into(), transfer_value, ) - .sign(&sender.clone().into(), 0, &mrenclave, &shard); + .sign(&sender.into(), 0, &mrenclave, &shard); let repo = Arc::new(NodeMetadataRepository::::default()); TestStf::execute_call(&mut state, trusted_call, &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(), 3); + assert_eq!(TestStf::get_events(&mut state).len(), 4); // Remove the events. TestStf::reset_events(&mut state); @@ -678,19 +688,18 @@ fn execute_trusted_calls( top_pool_author: &TestTopPoolAuthor, ) -> BatchExecutionResult { let top_pool_calls = top_pool_author.get_pending_trusted_calls(*shard); - let execution_result = stf_executor + stf_executor .propose_state_update( &top_pool_calls, &latest_parentchain_header(), - &shard, + shard, Duration::from_millis(600), |mut s| { s.set_block_number(&s.get_block_number().map_or(1, |n| n + 1)); s }, ) - .unwrap(); - execution_result + .unwrap() } // helper functions diff --git a/enclave-runtime/src/test/top_pool_tests.rs b/enclave-runtime/src/test/top_pool_tests.rs index 32598e049f..b535cf3934 100644 --- a/enclave-runtime/src/test/top_pool_tests.rs +++ b/enclave-runtime/src/test/top_pool_tests.rs @@ -29,14 +29,13 @@ use crate::test::{ }, }; use codec::Encode; +use ita_parentchain_interface::integritee; use ita_stf::{ test_genesis::{endowed_account, unendowed_account}, Getter, TrustedCall, TrustedCallSigned, }; use itc_parentchain::indirect_calls_executor::{ - filter_metadata::{ShieldFundsAndInvokeFilter, TestEventCreator}, - parentchain_parser::ParentchainExtrinsicParser, - ExecuteIndirectCalls, IndirectCallsExecutor, + mock::TestEventCreator, ExecuteIndirectCalls, IndirectCallsExecutor, }; use itc_parentchain_test::{ParentchainBlockBuilder, ParentchainHeaderBuilder}; use itp_node_api::{ @@ -56,7 +55,10 @@ use itp_stf_primitives::{traits::TrustedCallVerification, types::TrustedOperatio use itp_stf_state_observer::mock::ObserveStateMock; use itp_test::mock::metrics_ocall_mock::MetricsOCallMock; use itp_top_pool_author::{top_filter::AllowAllTopsFilter, traits::AuthorApi}; -use itp_types::{parentchain::Address, AccountId, Block, ShardIdentifier, ShieldFundsFn, H256}; +use itp_types::{ + parentchain::{Address, ParentchainId}, + AccountId, Block, ShardIdentifier, ShieldFundsFn, H256, +}; use jsonrpc_core::futures::executor; use log::*; use sgx_crypto_helper::RsaKeyPair; @@ -82,7 +84,7 @@ pub fn process_indirect_call_in_top_pool() { let top_pool_author = Arc::new(TestTopPoolAuthor::new( top_pool, AllowAllTopsFilter::::new(), - state_handler.clone(), + state_handler, shielding_key_repo, Arc::new(MetricsOCallMock::default()), )); @@ -100,7 +102,7 @@ pub fn submit_shielding_call_to_top_pool() { let signer = TestSigner::from_seed(b"42315678901234567890123456789012"); let shielding_key = TestShieldingKey::new().unwrap(); - let shielding_key_repo = Arc::new(TestShieldingKeyRepo::new(shielding_key.clone())); + let shielding_key_repo = Arc::new(TestShieldingKeyRepo::new(shielding_key)); let header = ParentchainHeaderBuilder::default().build(); let ocall_api = create_ocall_api(&header, &signer); @@ -123,23 +125,29 @@ pub fn submit_shielding_call_to_top_pool() { let enclave_signer = Arc::new(StfEnclaveSigner::<_, _, _, TestStf, _, TrustedCallSigned, Getter>::new( state_observer, - ocall_api.clone(), + 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::< - _, - _, - _, - _, - ShieldFundsAndInvokeFilter, - TestEventCreator, - >::new( - shielding_key_repo, enclave_signer, top_pool_author.clone(), node_meta_data_repository - ); + 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::Integritee, + ); let block_with_shielding_call = create_shielding_call_extrinsic(shard_id, &shielding_key); @@ -194,7 +202,12 @@ fn create_shielding_call_extrinsic( let shield_funds_indexes = dummy_node_metadata.shield_funds_call_indexes().unwrap(); let opaque_extrinsic = OpaqueExtrinsic::from_bytes( ParentchainUncheckedExtrinsic::::new_signed( - (shield_funds_indexes, shard, target_account, 1000u128), + ( + shield_funds_indexes, + shard, + target_account, + ita_stf::test_genesis::SECOND_ENDOWED_ACC_FUNDS, + ), Address::Address32([1u8; 32]), MultiSignature::Ed25519(signature), default_extra_for_test.signed_extra(), diff --git a/enclave-runtime/src/tls_ra/authentication.rs b/enclave-runtime/src/tls_ra/authentication.rs index c2dbdd3e92..c5e45efa6c 100644 --- a/enclave-runtime/src/tls_ra/authentication.rs +++ b/enclave-runtime/src/tls_ra/authentication.rs @@ -51,7 +51,11 @@ where _sni: Option<&DNSName>, ) -> Result { debug!("client cert: {:?}", certs); - let issuer = cert::parse_cert_issuer(&certs[0].0).unwrap(); + 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 @@ -106,7 +110,11 @@ where _ocsp: &[u8], ) -> Result { debug!("server cert: {:?}", certs); - let issuer = cert::parse_cert_issuer(&certs[0].0).unwrap(); + 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 { diff --git a/enclave-runtime/src/tls_ra/tests.rs b/enclave-runtime/src/tls_ra/tests.rs index 37b69c64f7..17870f412d 100644 --- a/enclave-runtime/src/tls_ra/tests.rs +++ b/enclave-runtime/src/tls_ra/tests.rs @@ -90,8 +90,7 @@ pub fn test_tls_ra_server_client_networking() { 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.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(), @@ -118,7 +117,7 @@ pub fn test_tls_ra_server_client_networking() { Some("E_SIZE), shard, SKIP_RA, - client_seal_handler.clone(), + client_seal_handler, client_account, ); @@ -129,13 +128,14 @@ pub fn test_tls_ra_server_client_networking() { assert_eq!(*client_shielding_key.read().unwrap(), shielding_key_encoded); assert_eq!(*client_light_client_state.read().unwrap(), light_client_state_encoded); - // State and state-key are provisioned only in sidechain mode - if WorkerModeProvider::worker_mode() == WorkerMode::Sidechain { - assert_eq!(*client_state.read().unwrap(), state_encoded); - assert_eq!(*client_state_key.read().unwrap(), state_key_encoded); - } else { + // State and state-key are provisioned only in sidechain or OCW mode + if WorkerModeProvider::worker_mode() == WorkerMode::Teeracle { assert_eq!(*client_state.read().unwrap(), initial_client_state); assert_eq!(*client_state_key.read().unwrap(), initial_client_state_key); + } else { + // Sidechain or OffchainWorker + assert_eq!(*client_state.read().unwrap(), state_encoded); + assert_eq!(*client_state_key.read().unwrap(), state_key_encoded); } } diff --git a/enclave-runtime/src/tls_ra/tls_ra_client.rs b/enclave-runtime/src/tls_ra/tls_ra_client.rs index 428961da77..d8c5077075 100644 --- a/enclave-runtime/src/tls_ra/tls_ra_client.rs +++ b/enclave-runtime/src/tls_ra/tls_ra_client.rs @@ -26,15 +26,19 @@ use crate::{ GLOBAL_SHIELDING_KEY_REPOSITORY_COMPONENT, 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 log::*; use rustls::{ClientConfig, ClientSession, Stream}; use sgx_types::*; @@ -239,6 +243,11 @@ pub unsafe extern "C" fn request_state_provisioning( 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 } diff --git a/enclave-runtime/src/tls_ra/tls_ra_server.rs b/enclave-runtime/src/tls_ra/tls_ra_server.rs index b03c1f59ae..07d26df5b5 100644 --- a/enclave-runtime/src/tls_ra/tls_ra_server.rs +++ b/enclave-runtime/src/tls_ra/tls_ra_server.rs @@ -55,8 +55,8 @@ enum ProvisioningPayload { impl From for ProvisioningPayload { fn from(m: WorkerMode) -> Self { match m { - WorkerMode::OffChainWorker | WorkerMode::Teeracle => - ProvisioningPayload::ShieldingKeyAndLightClient, + WorkerMode::Teeracle => ProvisioningPayload::ShieldingKeyAndLightClient, + WorkerMode::OffChainWorker => ProvisioningPayload::Everything, WorkerMode::Sidechain => ProvisioningPayload::Everything, } } @@ -114,9 +114,8 @@ where " [Enclave] (MU-RA-Server) await_shard_request_from_client, calling read_exact()" ); self.tls_stream.read_exact(&mut request)?; - let request: ClientProvisioningRequest = Decode::decode(&mut request.as_slice()) - .expect("matching byte size can't fail to decode"); - Ok(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. diff --git a/enclave-runtime/src/top_pool_execution.rs b/enclave-runtime/src/top_pool_execution.rs index 7fc1dd1541..db6d7b9c9b 100644 --- a/enclave-runtime/src/top_pool_execution.rs +++ b/enclave-runtime/src/top_pool_execution.rs @@ -16,17 +16,27 @@ */ use crate::{ - error::Result, + error::{Error, Result}, initialization::global_components::{ GLOBAL_OCALL_API_COMPONENT, GLOBAL_SIDECHAIN_BLOCK_COMPOSER_COMPONENT, GLOBAL_SIDECHAIN_IMPORT_QUEUE_WORKER_COMPONENT, GLOBAL_SIGNING_KEY_REPOSITORY_COMPONENT, GLOBAL_STATE_HANDLER_COMPONENT, GLOBAL_TOP_POOL_AUTHOR_COMPONENT, }, + shard_vault::get_shard_vault_internal, sync::{EnclaveLock, EnclaveStateRWLock}, utils::{ get_extrinsic_factory_from_integritee_solo_or_parachain, - get_stf_executor_from_solo_or_parachain, get_triggered_dispatcher_from_solo_or_parachain, - get_validator_accessor_from_solo_or_parachain, + get_extrinsic_factory_from_target_a_solo_or_parachain, + get_extrinsic_factory_from_target_b_solo_or_parachain, + get_stf_executor_from_integritee_solo_or_parachain, + get_stf_executor_from_target_a_solo_or_parachain, + get_stf_executor_from_target_b_solo_or_parachain, + get_triggered_dispatcher_from_integritee_solo_or_parachain, + get_triggered_dispatcher_from_target_a_solo_or_parachain, + get_triggered_dispatcher_from_target_b_solo_or_parachain, + get_validator_accessor_from_integritee_solo_or_parachain, + get_validator_accessor_from_target_a_solo_or_parachain, + get_validator_accessor_from_target_b_solo_or_parachain, }, }; use codec::Encode; @@ -44,7 +54,10 @@ use itp_settings::sidechain::SLOT_DURATION; use itp_sgx_crypto::key_repository::AccessKey; use itp_stf_state_handler::query_shard_state::QueryShardState; use itp_time_utils::duration_now; -use itp_types::{Block, OpaqueCall, H256}; +use itp_types::{ + parentchain::{ParentchainCall, ParentchainId}, + Block, OpaqueCall, H256, +}; use its_primitives::{ traits::{ Block as SidechainBlockTrait, Header as HeaderTrait, ShardIdentifierFor, SignedBlock, @@ -92,40 +105,75 @@ fn execute_top_pool_trusted_calls_internal() -> Result<()> { let slot_beginning_timestamp = duration_now(); - let parentchain_import_dispatcher = get_triggered_dispatcher_from_solo_or_parachain()?; - - let validator_access = get_validator_accessor_from_solo_or_parachain()?; + let integritee_parentchain_import_dispatcher = + get_triggered_dispatcher_from_integritee_solo_or_parachain()?; + let maybe_target_a_parentchain_import_dispatcher = + get_triggered_dispatcher_from_target_a_solo_or_parachain().ok(); + let maybe_target_b_parentchain_import_dispatcher = + get_triggered_dispatcher_from_target_b_solo_or_parachain().ok(); + + let maybe_latest_target_a_parentchain_header = + if let Some(ref _triggered_dispatcher) = maybe_target_a_parentchain_import_dispatcher { + let validator_access = get_validator_accessor_from_target_a_solo_or_parachain()?; + Some(validator_access.execute_on_validator(|v| { + let latest_parentchain_header = v.latest_finalized_header()?; + Ok(latest_parentchain_header) + })?) + } else { + None + }; + + let maybe_latest_target_b_parentchain_header = + if let Some(ref _triggered_dispatcher) = maybe_target_b_parentchain_import_dispatcher { + let validator_access = get_validator_accessor_from_target_b_solo_or_parachain()?; + Some(validator_access.execute_on_validator(|v| { + let latest_parentchain_header = v.latest_finalized_header()?; + Ok(latest_parentchain_header) + })?) + } else { + None + }; + + let integritee_validator_access = get_validator_accessor_from_integritee_solo_or_parachain()?; // This gets the latest imported block. We accept that all of AURA, up until the block production // itself, will operate on a parentchain block that is potentially outdated by one block // (in case we have a block in the queue, but not imported yet). - let current_parentchain_header = validator_access.execute_on_validator(|v| { - let latest_parentchain_header = v.latest_finalized_header()?; - Ok(latest_parentchain_header) - })?; + let current_integritee_parentchain_header = + integritee_validator_access.execute_on_validator(|v| { + let latest_parentchain_header = v.latest_finalized_header()?; + Ok(latest_parentchain_header) + })?; // Import any sidechain blocks that are in the import queue. In case we are missing blocks, // a peer sync will happen. If that happens, the slot time might already be used up just by this import. let sidechain_block_import_queue_worker = GLOBAL_SIDECHAIN_IMPORT_QUEUE_WORKER_COMPONENT.get()?; - let latest_parentchain_header = - sidechain_block_import_queue_worker.process_queue(¤t_parentchain_header)?; + let latest_integritee_parentchain_header = sidechain_block_import_queue_worker + .process_queue(¤t_integritee_parentchain_header)?; trace!( "Elapsed time to process sidechain block import queue: {} ms", start_time.elapsed().as_millis() ); - let stf_executor = get_stf_executor_from_solo_or_parachain()?; + let state_handler = GLOBAL_STATE_HANDLER_COMPONENT.get()?; - let top_pool_author = GLOBAL_TOP_POOL_AUTHOR_COMPONENT.get()?; + let shards = state_handler.list_shards()?; - let block_composer = GLOBAL_SIDECHAIN_BLOCK_COMPOSER_COMPONENT.get()?; + let (_, vault_target) = + get_shard_vault_internal(*shards.get(0).ok_or(Error::NoShardAssigned)?)?; + trace!("using StfExecutor from {:?} parentchain", vault_target); + let stf_executor = match vault_target { + ParentchainId::Integritee => get_stf_executor_from_integritee_solo_or_parachain()?, + ParentchainId::TargetA => get_stf_executor_from_target_a_solo_or_parachain()?, + ParentchainId::TargetB => get_stf_executor_from_target_b_solo_or_parachain()?, + }; - let extrinsics_factory = get_extrinsic_factory_from_integritee_solo_or_parachain()?; + let top_pool_author = GLOBAL_TOP_POOL_AUTHOR_COMPONENT.get()?; - let state_handler = GLOBAL_STATE_HANDLER_COMPONENT.get()?; + let block_composer = GLOBAL_SIDECHAIN_BLOCK_COMPOSER_COMPONENT.get()?; let ocall_api = GLOBAL_OCALL_API_COMPONENT.get()?; @@ -134,7 +182,9 @@ fn execute_top_pool_trusted_calls_internal() -> Result<()> { match yield_next_slot( slot_beginning_timestamp, SLOT_DURATION, - latest_parentchain_header, + latest_integritee_parentchain_header, + maybe_latest_target_a_parentchain_header, + maybe_latest_target_b_parentchain_header, &mut LastSlot, )? { Some(slot) => { @@ -145,21 +195,23 @@ fn execute_top_pool_trusted_calls_internal() -> Result<()> { log_remaining_slot_duration(&slot, "Before AURA"); - let shards = state_handler.list_shards()?; let env = ProposerFactory::::new( top_pool_author, stf_executor, block_composer, ); - let (blocks, opaque_calls) = exec_aura_on_slot::<_, _, SignedSidechainBlock, _, _, _>( - slot.clone(), - authority, - ocall_api.clone(), - parentchain_import_dispatcher, - env, - shards, - )?; + let (blocks, parentchain_calls) = + exec_aura_on_slot::<_, _, SignedSidechainBlock, _, _, _, _, _>( + slot.clone(), + authority, + ocall_api.clone(), + integritee_parentchain_import_dispatcher, + maybe_target_a_parentchain_import_dispatcher, + maybe_target_b_parentchain_import_dispatcher, + env, + shards, + )?; debug!("Aura executed successfully"); @@ -168,13 +220,7 @@ fn execute_top_pool_trusted_calls_internal() -> Result<()> { log_remaining_slot_duration(&slot, "After AURA"); - send_blocks_and_extrinsics::( - blocks, - opaque_calls, - ocall_api, - validator_access.as_ref(), - extrinsics_factory.as_ref(), - )?; + send_blocks_and_extrinsics::(blocks, parentchain_calls, ocall_api)?; log_remaining_slot_duration(&slot, "After broadcasting and sending extrinsic"); }, @@ -189,21 +235,26 @@ fn execute_top_pool_trusted_calls_internal() -> Result<()> { } /// Executes aura for the given `slot`. +#[allow(clippy::too_many_arguments)] pub(crate) fn exec_aura_on_slot< Authority, ParentchainBlock, SignedSidechainBlock, OCallApi, PEnvironment, - BlockImportTrigger, + IntegriteeBlockImportTrigger, + TargetABlockImportTrigger, + TargetBBlockImportTrigger, >( slot: SlotInfo, authority: Authority, ocall_api: Arc, - block_import_trigger: Arc, + integritee_block_import_trigger: Arc, + maybe_target_a_block_import_trigger: Option>, + maybe_target_b_block_import_trigger: Option>, proposer_environment: PEnvironment, shards: Vec>, -) -> Result<(Vec, Vec)> +) -> Result<(Vec, Vec)> where ParentchainBlock: BlockTrait, SignedSidechainBlock: @@ -218,58 +269,84 @@ where NumberFor: BlockNumberOps, PEnvironment: Environment + Send + Sync, - BlockImportTrigger: + IntegriteeBlockImportTrigger: + TriggerParentchainBlockImport>, + TargetABlockImportTrigger: + TriggerParentchainBlockImport>, + TargetBBlockImportTrigger: TriggerParentchainBlockImport>, { debug!("[Aura] Executing aura for slot: {:?}", slot); - let mut aura = Aura::<_, ParentchainBlock, SignedSidechainBlock, PEnvironment, _, _>::new( - authority, - ocall_api.as_ref().clone(), - block_import_trigger, - proposer_environment, - ) - .with_claim_strategy(SlotClaimStrategy::RoundRobin); - - let (blocks, xts): (Vec<_>, Vec<_>) = + let mut aura = + Aura::<_, ParentchainBlock, SignedSidechainBlock, PEnvironment, _, _, _, _>::new( + authority, + ocall_api.as_ref().clone(), + integritee_block_import_trigger, + maybe_target_a_block_import_trigger, + maybe_target_b_block_import_trigger, + proposer_environment, + ) + .with_claim_strategy(SlotClaimStrategy::RoundRobin); + + let (blocks, pxts): (Vec<_>, Vec<_>) = PerShardSlotWorkerScheduler::on_slot(&mut aura, slot, shards) .into_iter() .map(|r| (r.block, r.parentchain_effects)) .unzip(); - let opaque_calls: Vec = xts.into_iter().flatten().collect(); + let opaque_calls: Vec = pxts.into_iter().flatten().collect(); Ok((blocks, opaque_calls)) } /// Broadcasts sidechain blocks to fellow peers and sends opaque calls as extrinsic to the parentchain. -pub(crate) fn send_blocks_and_extrinsics< - ParentchainBlock, - SignedSidechainBlock, - OCallApi, - ValidatorAccessor, - ExtrinsicsFactory, ->( +pub(crate) fn send_blocks_and_extrinsics( blocks: Vec, - opaque_calls: Vec, + parentchain_calls: Vec, ocall_api: Arc, - validator_access: &ValidatorAccessor, - extrinsics_factory: &ExtrinsicsFactory, ) -> Result<()> where ParentchainBlock: BlockTrait, SignedSidechainBlock: SignedBlock + 'static, OCallApi: EnclaveSidechainOCallApi, - ValidatorAccessor: ValidatorAccess + Send + Sync + 'static, NumberFor: BlockNumberOps, - ExtrinsicsFactory: CreateExtrinsics, { debug!("Proposing {} sidechain block(s) (broadcasting to peers)", blocks.len()); ocall_api.propose_sidechain_blocks(blocks)?; - let xts = extrinsics_factory.create_extrinsics(opaque_calls.as_slice(), None)?; - - debug!("Sending sidechain block(s) confirmation extrinsic.. "); - validator_access.execute_mut_on_validator(|v| v.send_extrinsics(xts))?; + let calls: Vec = parentchain_calls + .iter() + .filter_map(|parentchain_call| parentchain_call.as_integritee()) + .collect(); + debug!("Enclave wants to send {} extrinsics to Integritee Parentchain", calls.len()); + if !calls.is_empty() { + let extrinsics_factory = get_extrinsic_factory_from_integritee_solo_or_parachain()?; + let xts = extrinsics_factory.create_extrinsics(calls.as_slice(), None)?; + let validator_access = get_validator_accessor_from_integritee_solo_or_parachain()?; + validator_access.execute_mut_on_validator(|v| v.send_extrinsics(xts))?; + } + let calls: Vec = parentchain_calls + .iter() + .filter_map(|parentchain_call| parentchain_call.as_target_a()) + .collect(); + debug!("Enclave wants to send {} extrinsics to TargetA Parentchain", calls.len()); + if !calls.is_empty() { + let extrinsics_factory = get_extrinsic_factory_from_target_a_solo_or_parachain()?; + let xts = extrinsics_factory.create_extrinsics(calls.as_slice(), None)?; + let validator_access = get_validator_accessor_from_target_a_solo_or_parachain()?; + validator_access.execute_mut_on_validator(|v| v.send_extrinsics(xts))?; + } + let calls: Vec = parentchain_calls + .iter() + .filter_map(|parentchain_call| parentchain_call.as_target_b()) + .collect(); + debug!("Enclave wants to send {} extrinsics to TargetB Parentchain", calls.len()); + if !calls.is_empty() { + let extrinsics_factory = get_extrinsic_factory_from_target_b_solo_or_parachain()?; + let xts = extrinsics_factory.create_extrinsics(calls.as_slice(), None)?; + let validator_access = get_validator_accessor_from_target_b_solo_or_parachain()?; + validator_access.execute_mut_on_validator(|v| v.send_extrinsics(xts))?; + } Ok(()) } diff --git a/enclave-runtime/src/utils.rs b/enclave-runtime/src/utils.rs index 4c58da0d01..c20c88e5f4 100644 --- a/enclave-runtime/src/utils.rs +++ b/enclave-runtime/src/utils.rs @@ -17,9 +17,11 @@ use crate::{ error::{Error, Result}, initialization::global_components::{ - EnclaveExtrinsicsFactory, EnclaveNodeMetadataRepository, EnclaveStfExecutor, - EnclaveValidatorAccessor, IntegriteeParentchainBlockImportDispatcher, + EnclaveExtrinsicsFactory, EnclaveNodeMetadataRepository, EnclaveStfEnclaveSigner, + EnclaveStfExecutor, EnclaveValidatorAccessor, IntegriteeParentchainTriggeredBlockImportDispatcher, + TargetAParentchainTriggeredBlockImportDispatcher, + TargetBParentchainTriggeredBlockImportDispatcher, 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, @@ -27,6 +29,7 @@ use crate::{ }, }; use codec::{Decode, Input}; +use itc_parentchain_block_import_dispatcher::BlockImportDispatcher; use itp_component_container::ComponentGetter; use std::{result::Result as StdResult, slice, sync::Arc}; @@ -73,7 +76,7 @@ pub unsafe fn utf8_str_from_raw<'a>( // FIXME: When solving #1080, these helper functions should be obsolete, because no dynamic allocation // is necessary anymore. -pub(crate) fn get_triggered_dispatcher_from_solo_or_parachain( +pub(crate) fn get_triggered_dispatcher_from_integritee_solo_or_parachain( ) -> Result> { let dispatcher = if let Ok(solochain_handler) = GLOBAL_INTEGRITEE_SOLOCHAIN_HANDLER_COMPONENT.get() { @@ -86,16 +89,42 @@ pub(crate) fn get_triggered_dispatcher_from_solo_or_parachain( Ok(dispatcher) } -pub(crate) fn get_triggered_dispatcher( - dispatcher: Arc, -) -> Result> { +pub(crate) fn get_triggered_dispatcher_from_target_a_solo_or_parachain( +) -> Result> { + let dispatcher = + if let Ok(solochain_handler) = GLOBAL_TARGET_A_SOLOCHAIN_HANDLER_COMPONENT.get() { + get_triggered_dispatcher(solochain_handler.import_dispatcher.clone())? + } else if let Ok(parachain_handler) = GLOBAL_TARGET_A_PARACHAIN_HANDLER_COMPONENT.get() { + get_triggered_dispatcher(parachain_handler.import_dispatcher.clone())? + } else { + return Err(Error::NoTargetAParentchainAssigned) + }; + Ok(dispatcher) +} + +pub(crate) fn get_triggered_dispatcher_from_target_b_solo_or_parachain( +) -> Result> { + let dispatcher = + if let Ok(solochain_handler) = GLOBAL_TARGET_B_SOLOCHAIN_HANDLER_COMPONENT.get() { + get_triggered_dispatcher(solochain_handler.import_dispatcher.clone())? + } else if let Ok(parachain_handler) = GLOBAL_TARGET_B_PARACHAIN_HANDLER_COMPONENT.get() { + get_triggered_dispatcher(parachain_handler.import_dispatcher.clone())? + } else { + return Err(Error::NoTargetBParentchainAssigned) + }; + Ok(dispatcher) +} + +pub(crate) fn get_triggered_dispatcher( + dispatcher: Arc>, +) -> Result> { let triggered_dispatcher = dispatcher .triggered_dispatcher() .ok_or(Error::ExpectedTriggeredImportDispatcher)?; Ok(triggered_dispatcher) } -pub(crate) fn get_validator_accessor_from_solo_or_parachain( +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() { @@ -108,6 +137,32 @@ pub(crate) fn get_validator_accessor_from_solo_or_parachain( Ok(validator_accessor) } +pub(crate) fn get_validator_accessor_from_target_a_solo_or_parachain( +) -> Result> { + let validator_accessor = + if let Ok(solochain_handler) = GLOBAL_TARGET_A_SOLOCHAIN_HANDLER_COMPONENT.get() { + solochain_handler.validator_accessor.clone() + } else if let Ok(parachain_handler) = GLOBAL_TARGET_A_PARACHAIN_HANDLER_COMPONENT.get() { + parachain_handler.validator_accessor.clone() + } else { + return Err(Error::NoTargetAParentchainAssigned) + }; + Ok(validator_accessor) +} + +pub(crate) fn get_validator_accessor_from_target_b_solo_or_parachain( +) -> Result> { + let validator_accessor = + if let Ok(solochain_handler) = GLOBAL_TARGET_B_SOLOCHAIN_HANDLER_COMPONENT.get() { + solochain_handler.validator_accessor.clone() + } else if let Ok(parachain_handler) = GLOBAL_TARGET_B_PARACHAIN_HANDLER_COMPONENT.get() { + parachain_handler.validator_accessor.clone() + } else { + return Err(Error::NoTargetBParentchainAssigned) + }; + Ok(validator_accessor) +} + pub(crate) fn get_node_metadata_repository_from_integritee_solo_or_parachain( ) -> Result> { let metadata_repository = @@ -160,7 +215,34 @@ pub(crate) fn get_extrinsic_factory_from_integritee_solo_or_parachain( Ok(extrinsics_factory) } -pub(crate) fn get_stf_executor_from_solo_or_parachain() -> Result> { +pub(crate) fn get_extrinsic_factory_from_target_a_solo_or_parachain( +) -> Result> { + let extrinsics_factory = + if let Ok(solochain_handler) = GLOBAL_TARGET_A_SOLOCHAIN_HANDLER_COMPONENT.get() { + solochain_handler.extrinsics_factory.clone() + } else if let Ok(parachain_handler) = GLOBAL_TARGET_A_PARACHAIN_HANDLER_COMPONENT.get() { + parachain_handler.extrinsics_factory.clone() + } else { + return Err(Error::NoTargetAParentchainAssigned) + }; + Ok(extrinsics_factory) +} + +pub(crate) fn get_extrinsic_factory_from_target_b_solo_or_parachain( +) -> Result> { + let extrinsics_factory = + if let Ok(solochain_handler) = GLOBAL_TARGET_B_SOLOCHAIN_HANDLER_COMPONENT.get() { + solochain_handler.extrinsics_factory.clone() + } else if let Ok(parachain_handler) = GLOBAL_TARGET_B_PARACHAIN_HANDLER_COMPONENT.get() { + parachain_handler.extrinsics_factory.clone() + } else { + return Err(Error::NoTargetBParentchainAssigned) + }; + Ok(extrinsics_factory) +} + +pub(crate) fn get_stf_executor_from_integritee_solo_or_parachain() -> Result> +{ let stf_executor = if let Ok(solochain_handler) = GLOBAL_INTEGRITEE_SOLOCHAIN_HANDLER_COMPONENT.get() { solochain_handler.stf_executor.clone() @@ -171,3 +253,54 @@ pub(crate) fn get_stf_executor_from_solo_or_parachain() -> Result Result> +{ + let stf_executor = + if let Ok(solochain_handler) = GLOBAL_TARGET_A_SOLOCHAIN_HANDLER_COMPONENT.get() { + solochain_handler.stf_executor.clone() + } else if let Ok(parachain_handler) = GLOBAL_TARGET_A_PARACHAIN_HANDLER_COMPONENT.get() { + parachain_handler.stf_executor.clone() + } else { + return Err(Error::NoTargetAParentchainAssigned) + }; + Ok(stf_executor) +} + +pub(crate) fn get_stf_executor_from_target_b_solo_or_parachain() -> Result> +{ + let stf_executor = + if let Ok(solochain_handler) = GLOBAL_TARGET_B_SOLOCHAIN_HANDLER_COMPONENT.get() { + solochain_handler.stf_executor.clone() + } else if let Ok(parachain_handler) = GLOBAL_TARGET_B_PARACHAIN_HANDLER_COMPONENT.get() { + parachain_handler.stf_executor.clone() + } else { + return Err(Error::NoTargetBParentchainAssigned) + }; + Ok(stf_executor) +} + +pub(crate) fn get_stf_enclave_signer_from_solo_or_parachain() -> Result> +{ + let stf_enclave_signer = + if let Ok(solochain_handler) = GLOBAL_INTEGRITEE_SOLOCHAIN_HANDLER_COMPONENT.get() { + match &*solochain_handler.import_dispatcher { + BlockImportDispatcher::TriggeredDispatcher(dispatcher) => + dispatcher.block_importer.indirect_calls_executor.stf_enclave_signer.clone(), + BlockImportDispatcher::ImmediateDispatcher(dispatcher) => + dispatcher.block_importer.indirect_calls_executor.stf_enclave_signer.clone(), + _ => return Err(Error::NoIntegriteeParentchainAssigned), + } + } else if let Ok(parachain_handler) = GLOBAL_INTEGRITEE_PARACHAIN_HANDLER_COMPONENT.get() { + match &*parachain_handler.import_dispatcher { + BlockImportDispatcher::TriggeredDispatcher(dispatcher) => + dispatcher.block_importer.indirect_calls_executor.stf_enclave_signer.clone(), + BlockImportDispatcher::ImmediateDispatcher(dispatcher) => + dispatcher.block_importer.indirect_calls_executor.stf_enclave_signer.clone(), + _ => return Err(Error::NoIntegriteeParentchainAssigned), + } + } else { + return Err(Error::NoIntegriteeParentchainAssigned) + }; + Ok(stf_enclave_signer) +} diff --git a/service/Cargo.toml b/service/Cargo.toml index 482ff433fe..123fd1904b 100644 --- a/service/Cargo.toml +++ b/service/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "integritee-service" -version = "0.12.0" +version = "0.12.11" authors = ["Integritee AG "] build = "build.rs" edition = "2021" @@ -13,24 +13,25 @@ dirs = "3.0.2" env_logger = "0.9" futures = "0.3" hex = "0.4.3" +humantime = "2.1" jsonrpsee = { version = "0.2.0", features = ["client", "ws-server", "macros"] } lazy_static = "1.4.0" log = "0.4" parking_lot = "0.12.1" parse_duration = "2.1.1" -prometheus = { version = "0.13.0", features = ["process"] } -scale-info = { version = "2.0.1", default-features = false, features = ["derive"] } +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. +regex = "1.9.5" +scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } serde = "1.0" serde_derive = "1.0" serde_json = "1.0" thiserror = "1.0" tokio = { version = "1.6.1", features = ["full"] } +url = "2.5.0" warp = "0.3" - # ipfs ipfs-api = "0.11.0" -sha2 = { version = "0.7", default-features = false } codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive"] } primitive-types = { version = "0.12.1", default-features = false, features = ["codec"] } @@ -39,6 +40,7 @@ sgx_crypto_helper = { branch = "master", git = "https://github.com/apache/teacla sgx_types = { branch = "master", git = "https://github.com/apache/teaclave-sgx-sdk.git" } # local +ita-parentchain-interface = { path = "../app-libs/parentchain-interface" } itc-parentchain = { path = "../core/parentchain/parentchain-crate" } itc-rest-client = { path = "../core/rest-client" } itc-rpc-client = { path = "../core/rpc-client" } @@ -48,7 +50,9 @@ itp-enclave-api = { path = "../core-primitives/enclave-api" } itp-enclave-metrics = { path = "../core-primitives/enclave-metrics" } itp-node-api = { path = "../core-primitives/node-api" } itp-settings = { path = "../core-primitives/settings" } +itp-stf-interface = { path = "../core-primitives/stf-interface" } itp-storage = { path = "../core-primitives/storage" } +itp-time-utils = { path = "../core-primitives/time-utils" } itp-types = { path = "../core-primitives/types" } itp-utils = { path = "../core-primitives/utils" } its-consensus-slots = { path = "../sidechain/consensus/slots" } @@ -57,20 +61,17 @@ its-primitives = { path = "../sidechain/primitives" } its-rpc-handler = { path = "../sidechain/rpc-handler" } its-storage = { path = "../sidechain/storage" } -# scs / integritee - -my-node-runtime = { package = "integritee-node-runtime", git = "https://github.com/integritee-network/integritee-node.git", branch = "sdk-v0.12.0-polkadot-v0.9.42" } -sgx-verify = { git = "https://github.com/integritee-network/pallets.git", branch = "sdk-v0.12.0-polkadot-v0.9.42" } +sgx-verify = { git = "https://github.com/integritee-network/pallets.git", branch = "sdk-v0.12.11-polkadot-v0.9.42" } # `default-features = false` to remove the jsonrpsee dependency. -enclave-bridge-primitives = { git = "https://github.com/integritee-network/pallets.git", branch = "sdk-v0.12.0-polkadot-v0.9.42" } +enclave-bridge-primitives = { git = "https://github.com/integritee-network/pallets.git", branch = "sdk-v0.12.11-polkadot-v0.9.42" } # disable unsupported jsonrpcsee substrate-api-client = { default-features = false, features = ["std", "sync-api"], git = "https://github.com/scs/substrate-api-client.git", branch = "polkadot-v0.9.42-tag-v0.14.0" } -teerex-primitives = { git = "https://github.com/integritee-network/pallets.git", branch = "sdk-v0.12.0-polkadot-v0.9.42" } +teerex-primitives = { git = "https://github.com/integritee-network/pallets.git", branch = "sdk-v0.12.11-polkadot-v0.9.42" } # Substrate dependencies frame-support = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } -frame-system = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } pallet-balances = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } +sp-consensus-aura = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } sp-consensus-grandpa = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } sp-core = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } sp-keyring = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } diff --git a/service/src/account_funding.rs b/service/src/account_funding.rs index 787072fd60..074a7e7319 100644 --- a/service/src/account_funding.rs +++ b/service/src/account_funding.rs @@ -16,22 +16,29 @@ */ use crate::error::{Error, ServiceResult}; -use itp_node_api::api_client::{AccountApi, ParentchainApi}; -use itp_settings::worker::{ - EXISTENTIAL_DEPOSIT_FACTOR_FOR_INIT_FUNDS, REGISTERING_FEE_FACTOR_FOR_INIT_FUNDS, +use codec::Encode; +use itp_node_api::api_client::{AccountApi, ParentchainApi, TEEREX}; +use itp_settings::worker::REGISTERING_FEE_FACTOR_FOR_INIT_FUNDS; +use itp_types::{ + parentchain::{AccountId, Balance, ParentchainId}, + Moment, }; -use itp_types::parentchain::Balance; use log::*; use sp_core::{ crypto::{AccountId32, Ss58Codec}, Pair, }; use sp_keyring::AccountKeyring; -use sp_runtime::MultiAddress; +use sp_runtime::{MultiAddress, Saturating}; +use std::{thread, time::Duration}; use substrate_api_client::{ - extrinsic::BalancesExtrinsics, GetBalance, GetTransactionPayment, SubmitAndWatch, XtStatus, + ac_compose_macros::compose_extrinsic, ac_primitives::Bytes, extrinsic::BalancesExtrinsics, + GetBalance, GetStorage, GetTransactionPayment, SubmitAndWatch, XtStatus, }; +use teerex_primitives::SgxAttestationMethod; +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; @@ -54,66 +61,88 @@ impl EnclaveAccountInfoProvider { } } -pub fn setup_account_funding( +/// 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, - encoded_extrinsic: Vec, + parentchain_id: ParentchainId, is_development_mode: bool, ) -> ServiceResult<()> { - // Account funds - if is_development_mode { - // Development mode, the faucet will ensure that the enclave has enough funds - ensure_account_has_funds(api, accountid)?; - } else { - // Production mode, there is no faucet. - let registration_fees = enclave_registration_fees(api, encoded_extrinsic)?; - info!("Registration fees = {:?}", registration_fees); - let free_balance = api.get_free_balance(accountid)?; - info!("TEE's free balance = {:?}", free_balance); - - let min_required_funds = - registration_fees.saturating_mul(REGISTERING_FEE_FACTOR_FOR_INIT_FUNDS); - let missing_funds = min_required_funds.saturating_sub(free_balance); - - if missing_funds > 0 { - // If there are not enough funds, then the user can send the missing TEER to the enclave address and start again. - println!( - "Enclave account: {:}, missing funds {}", - accountid.to_ss58check(), - missing_funds + 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 ); - return Err(Error::Custom( - "Enclave does not have enough funds on the parentchain to register.".into(), - )) + thread::sleep(Duration::from_secs(10)); } } - Ok(()) } -// Alice plays the faucet and sends some funds to the account if balance is low -fn ensure_account_has_funds(api: &ParentchainApi, accountid: &AccountId32) -> Result<(), Error> { - // check account balance - let free_balance = api.get_free_balance(accountid)?; - info!("TEE's free balance = {:?} (Account: {})", free_balance, accountid); - +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 = {:?}", existential_deposit); - - let min_required_funds = - existential_deposit.saturating_mul(EXISTENTIAL_DEPOSIT_FACTOR_FOR_INIT_FUNDS); - let missing_funds = min_required_funds.saturating_sub(free_balance); - - if missing_funds > 0 { - info!("Transfer {:?} from Alice to {}", missing_funds, accountid); - bootstrap_funds_from_alice(api, accountid, missing_funds)?; + info!("[{:?}] Existential deposit is = {:?}", parentchain_id, existential_deposit); + + let mut min_required_funds: Balance = existential_deposit; + min_required_funds += shard_vault_initial_funds(api)?; + + let transfer_fee = estimate_transfer_fee(api)?; + info!("[{:?}] a single transfer costs {:?}", parentchain_id, transfer_fee); + min_required_funds += 1000 * transfer_fee; + + // Check if this is an integritee chain and Compose a register_sgx_enclave extrinsic + if let Ok(ra_renewal) = api.get_constant::("Teerex", "MaxAttestationRenewalPeriod") { + info!("[{:?}] this chain has the teerex pallet. estimating RA fees", parentchain_id); + let encoded_xt: Bytes = compose_extrinsic!( + api, + TEEREX, + "register_sgx_enclave", + vec![0u8; SGX_RA_PROOF_MAX_LEN], + Some(vec![0u8; MAX_URL_LEN]), + SgxAttestationMethod::Dcap { proxied: false } + ) + .encode() + .into(); + let tx_fee = + api.get_fee_details(&encoded_xt, None).unwrap().unwrap().inclusion_fee.unwrap(); + let ra_fee = tx_fee.base_fee + tx_fee.len_fee + tx_fee.adjusted_weight_fee; + info!( + "[{:?}] one enclave registration costs {:?} and needs to be renewed every {:?}h", + parentchain_id, + ra_fee, + ra_renewal / 1_000 / 3_600 + ); + min_required_funds += 5 * ra_fee; + } else { + info!("[{:?}] this chain has no teerex pallet, no need to add RA fees", parentchain_id); } - Ok(()) + + info!( + "[{:?}] we estimate the funding requirement for the primary validateer (worst case) to be {:?}", + parentchain_id, + min_required_funds + ); + Ok(min_required_funds) } -fn enclave_registration_fees( - api: &ParentchainApi, - encoded_extrinsic: Vec, -) -> Result { +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 { @@ -127,7 +156,7 @@ fn enclave_registration_fees( } } -// Alice sends some funds to the account +/// Alice sends some funds to the account. only for dev chains testing fn bootstrap_funds_from_alice( api: &ParentchainApi, accountid: &AccountId32, @@ -166,3 +195,24 @@ fn bootstrap_funds_from_alice( Ok(()) } + +/// precise estimation of necessary funds to register a hardcoded number of proxies +pub fn shard_vault_initial_funds(api: &ParentchainApi) -> Result { + let proxy_deposit_base: Balance = api.get_constant("Proxy", "ProxyDepositBase")?; + let proxy_deposit_factor: Balance = api.get_constant("Proxy", "ProxyDepositFactor")?; + let transfer_fee = estimate_transfer_fee(api)?; + let existential_deposit = api.get_existential_deposit()?; + info!("Proxy Deposit is {:?} base + {:?} per proxy", proxy_deposit_base, proxy_deposit_factor); + Ok(proxy_deposit_base + 10 * proxy_deposit_factor + 500 * transfer_fee + existential_deposit) +} + +/// 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/service/src/cli.yml b/service/src/cli.yml index c4847ca27c..f4f0862177 100644 --- a/service/src/cli.yml +++ b/service/src/cli.yml @@ -1,5 +1,5 @@ name: "integritee-service" -version: "0.12.0" +version: "0.12.10" about: Worker using Intel SGX TEE for Integritee-node authors: "Integritee AG " @@ -124,10 +124,6 @@ subcommands: 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. - teeracle-interval: required: false long: teeracle-interval @@ -139,8 +135,14 @@ subcommands: long: reregister help: Set the teeracle reregistration interval. Example of accepted syntax <5 seconds 15 minutes 2 hours 1 days> or short <5s15m2h1d> takes_value: true + - shielding-target: + required: false + long: shielding-target + short: s + help: set parentchain target for shielding / unshielding. only relevant for primary worker upon first start for shard. can't be changed later for a shard + takes_value: true - request-state: - about: join a shard by requesting key provisioning from another worker + about: (DEPRECATED) join a shard by requesting key provisioning from another worker args: - shard: long: shard @@ -158,7 +160,7 @@ subcommands: - 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 + about: (DEPRECATED) 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 diff --git a/service/src/config.rs b/service/src/config.rs index 3d42180a07..c8219d0fdf 100644 --- a/service/src/config.rs +++ b/service/src/config.rs @@ -18,6 +18,7 @@ use clap::ArgMatches; use itc_rest_client::rest_client::Url; use itp_settings::teeracle::{DEFAULT_MARKET_DATA_UPDATE_INTERVAL, ONE_DAY, THIRTY_MINUTES}; +use itp_types::parentchain::ParentchainId; use parse_duration::parse; use serde::{Deserialize, Serialize}; use std::{ @@ -265,8 +266,6 @@ pub struct RunConfig { skip_ra: bool, /// Set this flag if running in development mode to bootstrap enclave account on parentchain via //Alice. dev: bool, - /// Request key and state provisioning from a peer worker. - request_state: bool, /// Shard identifier base58 encoded. Defines the shard that this worker operates on. Default is mrenclave. shard: Option, /// Optional teeracle update interval @@ -275,6 +274,8 @@ pub struct RunConfig { reregister_teeracle_interval: 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 { @@ -286,10 +287,6 @@ impl RunConfig { self.dev } - pub fn request_state(&self) -> bool { - self.request_state - } - pub fn shard(&self) -> Option<&str> { self.shard.as_deref() } @@ -319,7 +316,6 @@ 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 request_state = m.is_present("request-state"); let shard = m.value_of("shard").map(|s| s.to_string()); let teeracle_update_interval = m.value_of("teeracle-interval").map(|i| { parse(i).unwrap_or_else(|e| panic!("teeracle-interval parsing error {:?}", e)) @@ -334,14 +330,23 @@ impl From<&ArgMatches<'_>> for RunConfig { .to_string() }); + let shielding_target = m.value_of("shielding-target").map(|i| match i { + "integritee" => ParentchainId::Integritee, + "target_a" => ParentchainId::TargetA, + "target_b" => ParentchainId::TargetB, + _ => panic!( + "failed to parse shielding-target: {} must be one of integritee|target_a|target_b", + i + ), + }); Self { skip_ra, dev, - request_state, shard, teeracle_update_interval, reregister_teeracle_interval, marblerun_base_url, + shielding_target, } } } @@ -464,7 +469,6 @@ mod test { let empty_args = ArgMatches::default(); let run_config = RunConfig::from(&empty_args); - assert_eq!(run_config.request_state, false); assert_eq!(run_config.dev, false); assert_eq!(run_config.skip_ra, false); assert!(run_config.shard.is_none()); @@ -477,7 +481,6 @@ mod test { let mut args = ArgMatches::default(); args.args = HashMap::from([ - ("request-state", Default::default()), ("dev", Default::default()), ("skip-ra", Default::default()), ("shard", Default::default()), @@ -489,7 +492,6 @@ mod test { let run_config = RunConfig::from(&args); - assert_eq!(run_config.request_state, true); assert_eq!(run_config.dev, true); assert_eq!(run_config.skip_ra, true); assert_eq!(run_config.shard.unwrap(), shard_identifier.to_string()); diff --git a/service/src/error.rs b/service/src/error.rs index c99f51e6fc..975d32f267 100644 --- a/service/src/error.rs +++ b/service/src/error.rs @@ -16,7 +16,7 @@ use codec::Error as CodecError; use itp_node_api::api_client::ApiClientError; -use itp_types::ShardIdentifier; +use itp_types::{parentchain::Hash, ShardIdentifier}; pub type ServiceResult = Result; @@ -50,6 +50,10 @@ pub enum Error { 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), } diff --git a/service/src/main_impl.rs b/service/src/main_impl.rs index 5c1c0beb2c..8eb5cd9c53 100644 --- a/service/src/main_impl.rs +++ b/service/src/main_impl.rs @@ -3,9 +3,8 @@ use crate::teeracle::{schedule_periodic_reregistration_thread, start_periodic_ma #[cfg(not(feature = "dcap"))] use crate::utils::check_files; - use crate::{ - account_funding::{setup_account_funding, EnclaveAccountInfoProvider}, + account_funding::{setup_reasonable_account_funding, EnclaveAccountInfoProvider}, config::Config, enclave::{ api::enclave_init, @@ -32,6 +31,7 @@ use crate::{ use base58::ToBase58; use clap::{load_yaml, App, ArgMatches}; use codec::{Decode, Encode}; +use ita_parentchain_interface::integritee::{Hash, Header}; use itp_enclave_api::{ direct_request::DirectRequest, enclave_base::EnclaveBase, @@ -51,38 +51,42 @@ use its_peer_fetch::{ use its_primitives::types::block::SignedBlock as SignedSidechainBlock; use its_storage::{interface::FetchBlocks, BlockPruner, SidechainStorageLock}; use log::*; -use my_node_runtime::{Hash, Header, RuntimeEvent}; +use regex::Regex; use sgx_types::*; use sp_runtime::traits::Header as HeaderT; use substrate_api_client::{ - api::XtStatus, rpc::HandleSubscription, GetChainInfo, SubmitAndWatch, SubscribeChain, - SubscribeEvents, + api::XtStatus, rpc::HandleSubscription, GetAccountInformation, GetBalance, GetChainInfo, + SubmitAndWatch, SubscribeChain, SubscribeEvents, }; -use teerex_primitives::AnySigner; +use teerex_primitives::{AnySigner, MultiEnclave}; #[cfg(feature = "dcap")] use sgx_verify::extract_tcb_info_from_raw_dcap_quote; use itp_enclave_api::Enclave; +use crate::{account_funding::shard_vault_initial_funds, error::ServiceResult}; use enclave_bridge_primitives::ShardIdentifier; use itc_parentchain::primitives::ParentchainId; +use itp_types::parentchain::{AccountId, Balance}; use sp_core::crypto::{AccountId32, Ss58Codec}; use sp_keyring::AccountKeyring; use sp_runtime::MultiSigner; -use std::{str, sync::Arc, thread, time::Duration}; +use std::{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 type Event = substrate_api_client::ac_node_api::EventRecord; pub(crate) fn main() { // Setup logging - env_logger::init(); + 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(); @@ -100,6 +104,13 @@ pub(crate) fn main() { info!("*** Running worker in mode: {:?} \n", WorkerModeProvider::worker_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(); @@ -183,15 +194,6 @@ pub(crate) fn main() { let node_api = node_api_factory.create_api().expect("Failed to create parentchain node API"); - if run_config.request_state() { - sync_state::sync_state::<_, _, WorkerModeProvider>( - &node_api, - &shard, - enclave.as_ref(), - run_config.skip_ra(), - ); - } - start_worker::<_, _, _, _, WorkerModeProvider>( config, &shard, @@ -353,9 +355,6 @@ fn start_worker( let tokio_handle = tokio_handle_getter.get_handle(); - #[cfg(feature = "teeracle")] - let teeracle_tokio_handle = tokio_handle.clone(); - // ------------------------------------------------------------------------ // Get the public key of our TEE. let tee_accountid = enclave_account(enclave.as_ref()); @@ -421,15 +420,20 @@ fn start_worker( &config, enclave.clone(), sidechain_storage.clone(), - tokio_handle, + &tokio_handle, ); } // ------------------------------------------------------------------------ - // Init parentchain specific stuff. Needed for parentchain communication. - - let (parentchain_handler, last_synced_header) = - init_parentchain(&enclave, &integritee_rpc_api, &tee_accountid, ParentchainId::Integritee); + // Init parentchain specific stuff. Needed early for parentchain communication. + let (integritee_parentchain_handler, integritee_last_synced_header_at_last_run) = + init_parentchain( + &enclave, + &integritee_rpc_api, + &tee_accountid, + ParentchainId::Integritee, + shard, + ); #[cfg(feature = "dcap")] register_collateral( @@ -477,14 +481,21 @@ fn start_worker( let tee_accountid_clone = tee_accountid.clone(); let send_register_xt = move || { println!("[+] Send register enclave extrinsic"); - send_extrinsic(register_xt(), &node_api2, &tee_accountid_clone, is_development_mode) + send_integritee_extrinsic( + register_xt(), + &node_api2, + &tee_accountid_clone, + is_development_mode, + ) }; - // Todo: Can't unwrap here because the extrinsic is for some reason not found in the block - // even if it was successful: https://github.com/scs/substrate-api-client/issues/624. - let register_enclave_block_hash = send_register_xt(); - let api_register_enclave_xt_header = - integritee_rpc_api.get_header(register_enclave_block_hash).unwrap().unwrap(); + let register_enclave_block_hash = + send_register_xt().expect("enclave RA registration must be successful to continue"); + + let api_register_enclave_xt_header = integritee_rpc_api + .get_header(Some(register_enclave_block_hash)) + .unwrap() + .unwrap(); // TODO: #1451: Fix api-client type hacks let register_enclave_xt_header = @@ -496,123 +507,247 @@ fn start_worker( register_enclave_xt_header.number(), register_enclave_xt_header.hash() ); + // double-check + let my_enclave = integritee_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); - let we_are_primary_validateer = - we_are_primary_worker(&integritee_rpc_api, shard, &tee_accountid).unwrap(); - - if we_are_primary_validateer { - println!("[+] We are the primary worker"); - } else { - println!("[+] We are NOT the primary worker"); - } - + let (we_are_primary_validateer, re_init_parentchain_needed) = + match integritee_rpc_api.primary_worker_for_shard(shard, None).unwrap() { + Some(primary_enclave) => match primary_enclave.instance_signer() { + AnySigner::Known(MultiSigner::Ed25519(primary)) => + if primary.encode() == tee_accountid.encode() { + println!("We are primary worker on this shard and we have been previously running."); + (true, false) + } else { + println!( + "We are NOT primary worker. The primary worker is {}.", + primary.to_ss58check(), + ); + info!("The primary worker enclave is {:?}", primary_enclave); + if enclave + .get_shard_creation_info(shard) + .unwrap() + .for_parentchain(ParentchainId::Integritee) + .is_none() + { + //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::<_, _, WorkerModeProvider>( + &integritee_rpc_api, + &shard, + enclave.as_ref(), + skip_ra, + ); + } + (false, true) + }, + _ => { + panic!( + "the primary worker for shard {:?} has unknown signer type: {:?}", + shard, primary_enclave + ); + }, + }, + None => { + println!("We are the primary worker on this shard and the shard is untouched. Will initialize it"); + enclave.init_shard(shard.encode()).unwrap(); + if WorkerModeProvider::worker_mode() != WorkerMode::Teeracle { + enclave + .init_shard_creation_parentchain_header( + shard, + &ParentchainId::Integritee, + ®ister_enclave_xt_header, + ) + .unwrap(); + debug!("shard config should be initialized on integritee network now"); + (true, true) + } else { + (true, false) + } + }, + }; + debug!("getting shard creation: {:?}", enclave.get_shard_creation_info(shard)); initialization_handler.registered_on_parentchain(); - // ------------------------------------------------------------------------ - // initialize teeracle interval - #[cfg(feature = "teeracle")] - if WorkerModeProvider::worker_mode() == WorkerMode::Teeracle { - schedule_periodic_reregistration_thread( - send_register_xt, - run_config.reregister_teeracle_interval(), - ); - - start_periodic_market_update( - &integritee_rpc_api, - run_config.teeracle_update_interval(), - enclave.as_ref(), - &teeracle_tokio_handle, - ); - } - - if WorkerModeProvider::worker_mode() != WorkerMode::Teeracle { - println!("*** [+] Finished initializing light client, syncing 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, + &integritee_rpc_api, + &tee_accountid, + ParentchainId::Integritee, + shard, + ) + } else { + (integritee_parentchain_handler, integritee_last_synced_header_at_last_run) + }; - // Syncing all parentchain blocks, this might take a while.. - let mut last_synced_header = - parentchain_handler.sync_parentchain(last_synced_header).unwrap(); + match WorkerModeProvider::worker_mode() { + WorkerMode::Teeracle => { + // ------------------------------------------------------------------------ + // initialize teeracle interval + #[cfg(feature = "teeracle")] + schedule_periodic_reregistration_thread( + send_register_xt, + run_config.reregister_teeracle_interval(), + ); - // ------------------------------------------------------------------------ - // Initialize the sidechain - if WorkerModeProvider::worker_mode() == WorkerMode::Sidechain { - last_synced_header = sidechain_init_block_production( - enclave.clone(), - ®ister_enclave_xt_header, - we_are_primary_validateer, - parentchain_handler.clone(), - sidechain_storage, - &last_synced_header, - ) - .unwrap(); - } + #[cfg(feature = "teeracle")] + start_periodic_market_update( + &integritee_rpc_api, + run_config.teeracle_update_interval(), + enclave.as_ref(), + &tokio_handle, + ); + }, + WorkerMode::OffChainWorker => { + println!("[Integritee:OCW] Finished initializing light client, syncing parentchain..."); + + // 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, + *shard, + true, + ) + .unwrap(); - // ------------------------------------------------------------------------ - // start parentchain syncing loop (subscribe to header updates) - thread::Builder::new() - .name("parentchain_sync_loop".to_owned()) - .spawn(move || { - if let Err(e) = - subscribe_to_parentchain_new_headers(parentchain_handler, last_synced_header) - { - error!("Parentchain block syncing terminated with a failure: {:?}", e); - } - println!("[!] Parentchain block syncing has terminated"); - }) - .unwrap(); + start_parentchain_header_subscription_thread( + integritee_parentchain_handler, + last_synced_header, + *shard, + ); - if WorkerModeProvider::worker_mode() == WorkerMode::OffChainWorker { info!("skipping shard vault check because not yet supported for offchain worker"); - } else if let Ok(shard_vault) = enclave.get_ecc_vault_pubkey(shard) { - println!( - "shard vault account is already initialized in state: {}", - shard_vault.to_ss58check() - ); - } else if we_are_primary_validateer { - println!("initializing proxied shard vault account now"); - enclave.init_proxied_shard_vault(shard).unwrap(); - println!( - "initialized shard vault account: : {}", - enclave.get_ecc_vault_pubkey(shard).unwrap().to_ss58check() + }, + WorkerMode::Sidechain => { + println!("[Integritee:SCV] Finished initializing light client, syncing integritee parentchain..."); + + let last_synced_header = if we_are_primary_validateer { + info!("We're the first validateer to be registered, syncing parentchain blocks until the one we have registered ourselves on."); + integritee_parentchain_handler + .await_sync_and_import_parentchain_until_at_least( + &integritee_last_synced_header_at_last_run, + ®ister_enclave_xt_header, + *shard, + ) + .unwrap() + } else { + integritee_last_synced_header_at_last_run + }; + + start_parentchain_header_subscription_thread( + integritee_parentchain_handler, + last_synced_header, + *shard, ); - } else { - panic!("no vault account has been initialized and we are not the primary worker"); - } - } - // ------------------------------------------------------------------------ - if WorkerModeProvider::worker_mode() == WorkerMode::Sidechain { - spawn_worker_for_shard_polling(shard, integritee_rpc_api.clone(), initialization_handler); + spawn_worker_for_shard_polling( + shard, + integritee_rpc_api.clone(), + initialization_handler, + ); + }, } - if let Some(url) = config.target_a_parentchain_rpc_endpoint() { - init_target_parentchain( + 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 + }; - if let Some(url) = config.target_b_parentchain_rpc_endpoint() { - init_target_parentchain( + 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 + }; + + init_provided_shard_vault( + shard, + &enclave, + integritee_rpc_api.clone(), + maybe_target_a_rpc_api, + maybe_target_b_rpc_api, + run_config.shielding_target, + we_are_primary_validateer, + ); + + if WorkerModeProvider::worker_mode() == WorkerMode::Sidechain { + println!("[Integritee:SCV] starting block production"); + let last_synced_header = + sidechain_init_block_production(enclave.clone(), sidechain_storage).unwrap(); } - // ------------------------------------------------------------------------ - // Subscribe to events and print them. - println!("*** [{:?}] Subscribing to events", ParentchainId::Integritee); - let mut subscription = integritee_rpc_api.subscribe_events().unwrap(); - println!("[+] [{:?}] Subscribed to events. waiting...", ParentchainId::Integritee); - loop { - if let Some(Ok(events)) = subscription.next_events::() { - print_events(events) + ita_parentchain_interface::event_subscriber::subscribe_to_parentchain_events( + &integritee_rpc_api, + ParentchainId::Integritee, + ); +} + +fn init_provided_shard_vault( + shard: &ShardIdentifier, + enclave: &Arc, + integritee_rpc_api: ParentchainApi, + maybe_target_a_rpc_api: Option, + maybe_target_b_rpc_api: Option, + shielding_target: Option, + we_are_primary_validateer: bool, +) { + let shielding_target = shielding_target.unwrap_or(ParentchainId::Integritee); + let rpc_api = match shielding_target { + ParentchainId::Integritee => integritee_rpc_api, + ParentchainId::TargetA => maybe_target_a_rpc_api + .expect("target A must be initialized to be used as shielding target"), + ParentchainId::TargetB => maybe_target_b_rpc_api + .expect("target B must be initialized to be used as shielding target"), + }; + let funding_balance = shard_vault_initial_funds(&rpc_api).unwrap(); + if let Ok(shard_vault) = enclave.get_ecc_vault_pubkey(shard) { + // verify if proxy is set up on chain + let nonce = rpc_api.get_account_nonce(&AccountId::from(shard_vault)).unwrap(); + println!( + "[{:?}] shard vault account is already initialized in state: {} with nonce {}", + shielding_target, + shard_vault.to_ss58check(), + nonce + ); + if nonce == 0 && we_are_primary_validateer { + println!( + "[{:?}] nonce = 0 means shard vault not properly set up on chain. will retry", + shielding_target + ); + enclave.init_proxied_shard_vault(shard, &shielding_target, 0u128).unwrap(); } + } else if we_are_primary_validateer { + println!("[{:?}] initializing proxied shard vault account now", shielding_target); + enclave + .init_proxied_shard_vault(shard, &shielding_target, funding_balance) + .unwrap(); + println!( + "[{:?}] initialized shard vault account: : {}", + shielding_target, + enclave.get_ecc_vault_pubkey(shard).unwrap().to_ss58check() + ); + } else { + panic!("no vault account has been initialized and we are not the primary worker"); } } @@ -620,9 +755,11 @@ fn init_target_parentchain( enclave: &Arc, tee_account_id: &AccountId32, url: String, + shard: &ShardIdentifier, parentchain_id: ParentchainId, is_development_mode: bool, -) where +) -> ParentchainApi +where E: EnclaveBase + Sidechain, { println!("Initializing parentchain {:?} with url: {}", parentchain_id, url); @@ -630,55 +767,58 @@ fn init_target_parentchain( .create_api() .unwrap_or_else(|_| panic!("[{:?}] Failed to create parentchain node API", parentchain_id)); - // some random bytes not too small to ensure that the enclave has enough funds - setup_account_funding(&node_api, tee_account_id, [0u8; 100].into(), is_development_mode) - .unwrap_or_else(|_| { - panic!("[{:?}] Could not fund parentchain enclave account", 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); + init_parentchain(enclave, &node_api, tee_account_id, parentchain_id, shard); if WorkerModeProvider::worker_mode() != WorkerMode::Teeracle { println!( - "*** [+] [{:?}] Finished initializing light client, syncing parentchain...", + "[{:?}] 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(last_synched_header).unwrap(); - - // start parentchain syncing loop (subscribe to header updates) - thread::Builder::new() - .name(format!("{:?}_parentchain_sync_loop", parentchain_id)) - .spawn(move || { - if let Err(e) = - subscribe_to_parentchain_new_headers(parentchain_handler, last_synched_header) - { - error!( - "[{:?}] parentchain block syncing terminated with a failure: {:?}", - parentchain_id, e - ); - } - println!("[!] [{:?}] parentchain block syncing has terminated", parentchain_id); - }) + let last_synched_header = parentchain_handler + .sync_parentchain_until_latest_finalized(last_synched_header, *shard, true) .unwrap(); + + start_parentchain_header_subscription_thread( + parentchain_handler.clone(), + last_synched_header, + *shard, + ) } - // Subscribe to events and print them. - println!("*** [{:?}] Subscribing to events...", parentchain_id); - let mut subscription = node_api.subscribe_events().unwrap(); - println!("[+] [{:?}] Subscribed to events. waiting...", parentchain_id); + 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 || loop { - if let Some(Ok(events)) = subscription.next_events::() { - print_events(events) - } + .spawn(move || { + ita_parentchain_interface::event_subscriber::subscribe_to_parentchain_events( + &node_api_clone, + parentchain_id, + ) }) .unwrap(); + node_api } fn init_parentchain( @@ -686,6 +826,7 @@ fn init_parentchain( node_api: &ParentchainApi, tee_account_id: &AccountId32, parentchain_id: ParentchainId, + shard: &ShardIdentifier, ) -> (Arc>, Header) where E: EnclaveBase + Sidechain, @@ -695,6 +836,7 @@ where node_api.clone(), enclave.clone(), parentchain_id, + *shard, ) .unwrap(), ); @@ -755,162 +897,6 @@ fn spawn_worker_for_shard_polling( }); } -fn print_events(events: Vec) { - for evr in &events { - debug!("Decoded: phase = {:?}, event = {:?}", evr.phase, evr.event); - match &evr.event { - RuntimeEvent::Balances(be) => { - info!("[+] Received balances event"); - debug!("{:?}", be); - match &be { - pallet_balances::Event::Transfer { - from: transactor, - to: dest, - amount: value, - } => { - debug!(" Transactor: {:?}", transactor.to_ss58check()); - debug!(" Destination: {:?}", dest.to_ss58check()); - debug!(" Value: {:?}", value); - }, - _ => { - trace!("Ignoring unsupported balances event"); - }, - } - }, - RuntimeEvent::Teerex(re) => { - debug!("{:?}", re); - match &re { - my_node_runtime::pallet_teerex::Event::AddedSgxEnclave { - registered_by, - worker_url, - .. - } => { - println!("[+] Received AddedEnclave event"); - println!(" Sender (Worker): {:?}", registered_by); - println!( - " Registered URL: {:?}", - str::from_utf8(&worker_url.clone().unwrap_or("none".into())).unwrap() - ); - }, - _ => { - trace!("Ignoring unsupported pallet_teerex event"); - }, - } - }, - RuntimeEvent::EnclaveBridge(re) => { - debug!("{:?}", re); - match &re { - my_node_runtime::pallet_enclave_bridge::Event::IndirectInvocationRegistered( - shard, - ) => { - println!( - "[+] Received trusted call for shard {}", - shard.encode().to_base58() - ); - }, - my_node_runtime::pallet_enclave_bridge::Event::ProcessedParentchainBlock { - shard, - block_hash, - trusted_calls_merkle_root, - block_number, - } => { - info!("[+] Received ProcessedParentchainBlock event"); - debug!(" for shard: {:?}", shard); - debug!(" Block Hash: {:?}", hex::encode(block_hash)); - debug!(" Merkle Root: {:?}", hex::encode(trusted_calls_merkle_root)); - debug!(" Block Number: {:?}", block_number); - }, - my_node_runtime::pallet_enclave_bridge::Event::ShieldFunds { - shard, - encrypted_beneficiary, - amount, - } => { - info!("[+] Received ShieldFunds event"); - debug!(" for shard: {:?}", shard); - debug!(" for enc. beneficiary: {:?}", encrypted_beneficiary); - debug!(" Amount: {:?}", amount); - }, - my_node_runtime::pallet_enclave_bridge::Event::UnshieldedFunds { - shard, - beneficiary, - amount, - } => { - info!("[+] Received UnshieldedFunds event"); - debug!(" for shard: {:?}", shard); - debug!(" beneficiary: {:?}", beneficiary); - debug!(" Amount: {:?}", amount); - }, - _ => { - trace!("Ignoring unsupported pallet_enclave_bridge event"); - }, - } - }, - #[cfg(feature = "teeracle")] - RuntimeEvent::Teeracle(re) => { - debug!("{:?}", re); - match &re { - my_node_runtime::pallet_teeracle::Event::ExchangeRateUpdated { - data_source, - trading_pair, - exchange_rate, - } => { - println!("[+] Received ExchangeRateUpdated event"); - println!(" Data source: {}", data_source); - println!(" trading pair: {}", trading_pair); - println!(" Exchange rate: {:?}", exchange_rate); - }, - my_node_runtime::pallet_teeracle::Event::ExchangeRateDeleted { - data_source, - trading_pair, - } => { - println!("[+] Received ExchangeRateDeleted event"); - println!(" Data source: {}", data_source); - println!(" trading pair: {}", trading_pair); - }, - my_node_runtime::pallet_teeracle::Event::AddedToWhitelist { - data_source, - enclave_fingerprint, - } => { - println!("[+] Received AddedToWhitelist event"); - println!(" Data source: {}", data_source); - println!(" fingerprint: {:?}", enclave_fingerprint); - }, - my_node_runtime::pallet_teeracle::Event::RemovedFromWhitelist { - data_source, - enclave_fingerprint, - } => { - println!("[+] Received RemovedFromWhitelist event"); - println!(" Data source: {}", data_source); - println!(" fingerprint: {:?}", enclave_fingerprint); - }, - _ => { - trace!("Ignoring unsupported pallet_teeracle event"); - }, - } - }, - #[cfg(feature = "sidechain")] - RuntimeEvent::Sidechain(re) => match &re { - my_node_runtime::pallet_sidechain::Event::FinalizedSidechainBlock { - shard, - block_header_hash, - validateer, - } => { - info!("[+] Received FinalizedSidechainBlock event"); - debug!(" for shard: {:?}", shard); - debug!(" From: {:?}", hex::encode(block_header_hash)); - debug!(" validateer: {:?}", validateer); - }, - _ => { - trace!("Ignoring unsupported pallet_sidechain event"); - }, - }, - _ => { - trace!("Ignoring event {:?}", evr); - }, - } - } -} - #[cfg(feature = "attesteer")] fn fetch_marblerun_events_every_hour( api: ParentchainApi, @@ -963,7 +949,7 @@ fn register_quotes_from_marblerun( for quote in quotes { match enclave.generate_dcap_ra_extrinsic_from_quote(url.clone(), "e) { Ok(xt) => { - send_extrinsic(xt, api, accountid, is_development_mode); + send_integritee_extrinsic(xt, api, accountid, is_development_mode); }, Err(e) => { error!("Extracting information from quote failed: {}", e) @@ -985,52 +971,83 @@ fn register_collateral( 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_extrinsic(uxt, api, accountid, is_development_mode); + send_integritee_extrinsic(uxt, api, accountid, is_development_mode); println!("[>] DCAP setup: register TCB info"); let uxt = enclave.generate_register_tcb_info_extrinsic(fmspc).unwrap(); - send_extrinsic(uxt, api, accountid, is_development_mode); + send_integritee_extrinsic(uxt, api, accountid, is_development_mode); } } -fn send_extrinsic( +fn send_integritee_extrinsic( extrinsic: Vec, api: &ParentchainApi, fee_payer: &AccountId32, is_development_mode: bool, -) -> Option { - // ensure account funds - if let Err(x) = setup_account_funding(api, fee_payer, extrinsic.clone(), is_development_mode) { - error!("Ensure enclave funding failed: {:?}", x); - // Return without registering the enclave. This will fail and the transaction will be banned for 30min. - return None - } +) -> 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!("[Integritee] send extrinsic"); + debug!("fee: {:?}, ed: {:?}, free: {:?} => missing: {:?}", fee, ed, free, missing_funds); + trace!( + " encoded extrinsic len: {}, payload: 0x{:}", + extrinsic.len(), + hex::encode(extrinsic.clone()) + ); - info!("[>] send extrinsic"); - trace!(" encoded extrinsic: 0x{:}", hex::encode(extrinsic.clone())); + if missing_funds > 0 { + setup_reasonable_account_funding( + api, + fee_payer, + ParentchainId::Integritee, + is_development_mode, + )? + } - // fixme: wait ...until_success doesn't work due to https://github.com/scs/substrate-api-client/issues/624 - // fixme: currently, we don't verify if the extrinsic was a success here 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 + xt_report.block_hash.ok_or(Error::Custom("no extrinsic hash returned".into())) }, Err(e) => { - error!("ExtrinsicFailed {:?}", e); - None + 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 @@ -1038,19 +1055,23 @@ fn subscribe_to_parentchain_new_headers( .parentchain_api() .subscribe_finalized_heads() .map_err(Error::ApiClient)?; - + let parentchain_id = parentchain_handler.parentchain_id(); loop { let new_header = subscription .next() .ok_or(Error::ApiSubscriptionDisconnected)? .map_err(|e| Error::ApiClient(e.into()))?; - println!( - "[+] Received finalized header update ({}), syncing parent chain...", - new_header.number + info!( + "[{:?}] Received finalized header update ({}), syncing parent chain...", + parentchain_id, new_header.number ); - last_synced_header = parentchain_handler.sync_parentchain(last_synced_header)?; + last_synced_header = parentchain_handler.sync_parentchain_until_latest_finalized( + last_synced_header, + shard, + false, + )?; } } @@ -1060,37 +1081,3 @@ fn enclave_account(enclave_api: &E) -> AccountId32 { trace!("[+] Got ed25519 account of TEE = {}", tee_public.to_ss58check()); AccountId32::from(*tee_public.as_array_ref()) } - -/// Checks if we are the first validateer to register on the parentchain. -fn we_are_primary_worker( - node_api: &ParentchainApi, - shard: &ShardIdentifier, - enclave_account: &AccountId32, -) -> Result { - // are we registered? else fail. - node_api - .enclave(enclave_account, None)? - .expect("our enclave should be registered at this point"); - trace!("our enclave is registered"); - match node_api.primary_worker_for_shard(shard, None).unwrap() { - Some(enclave) => - match enclave.instance_signer() { - AnySigner::Known(MultiSigner::Ed25519(primary)) => - if primary.encode() == enclave_account.encode() { - debug!("We are primary worker on this shard adn we have been previously running."); - Ok(true) - } else { - debug!("The primary worker is {}", primary.to_ss58check()); - Ok(false) - }, - _ => { - warn!("the primary worker is of unknown type"); - Ok(false) - }, - }, - None => { - debug!("We are the primary worker on this shard and the shard is untouched"); - Ok(true) - }, - } -} diff --git a/service/src/ocall_bridge/sidechain_ocall.rs b/service/src/ocall_bridge/sidechain_ocall.rs index a16ee4a6ce..27ff2500ff 100644 --- a/service/src/ocall_bridge/sidechain_ocall.rs +++ b/service/src/ocall_bridge/sidechain_ocall.rs @@ -25,10 +25,13 @@ use crate::{ use codec::{Decode, Encode}; use itp_types::{BlockHash, ShardIdentifier}; use its_peer_fetch::FetchBlocksFromPeer; -use its_primitives::{traits::Block, types::SignedBlock as SignedSidechainBlock}; +use its_primitives::{ + traits::{Block, Header}, + types::SignedBlock as SignedSidechainBlock, +}; use its_storage::BlockStorage; use log::*; -use std::sync::Arc; +use std::{collections::HashSet, sync::Arc}; pub struct SidechainOCall { block_broadcaster: Arc, @@ -83,35 +86,48 @@ where }, }; - if !signed_blocks.is_empty() { - info!( - "Enclave produced sidechain blocks: {:?}", - signed_blocks - .iter() - .map(|b| b.block.header().block_number) - .collect::>() - ); - } else { + if signed_blocks.is_empty() { debug!("Enclave did not produce sidechain blocks"); + return status + } + + info!( + "Enclave produced sidechain blocks: {:?}", + signed_blocks + .iter() + .map(|b| b.block.header().block_number) + .collect::>() + ); + + let shards: Vec = signed_blocks + .iter() + .map(|b| b.block.header().shard_id()) + .collect::>() + .into_iter() + .collect(); + + if shards.len() > 1 { + error!("operating multiple shards is not supported"); } + let shard = shards[0]; // FIXME: When & where should peers be updated? - debug!("Updating peers.."); - if let Err(e) = self.peer_updater.update_peers() { + trace!("Updating peers.."); + if let Err(e) = self.peer_updater.update_peers(shard) { error!("Error updating peers: {:?}", e); // Fixme: returning an error here results in a `HeaderAncestryMismatch` error. // status = sgx_status_t::SGX_ERROR_UNEXPECTED; } else { - info!("Successfully updated peers"); + debug!("Successfully updated peers"); } - debug!("Broadcasting sidechain blocks ..."); + trace!("Broadcasting sidechain blocks ..."); if let Err(e) = self.block_broadcaster.broadcast_blocks(signed_blocks) { error!("Error broadcasting blocks: {:?}", e); // Fixme: returning an error here results in a `HeaderAncestryMismatch` error. // status = sgx_status_t::SGX_ERROR_UNEXPECTED; } else { - info!("Successfully broadcast blocks"); + debug!("Successfully broadcast blocks"); } status diff --git a/service/src/ocall_bridge/worker_on_chain_ocall.rs b/service/src/ocall_bridge/worker_on_chain_ocall.rs index f322c6337f..1cd9067b7c 100644 --- a/service/src/ocall_bridge/worker_on_chain_ocall.rs +++ b/service/src/ocall_bridge/worker_on_chain_ocall.rs @@ -140,14 +140,16 @@ where XtStatus::InBlock, ) { error!( - "Could not send extrinsic to node: {:?}, error: {:?}", + "Could not send extrinsic to {:?}: {:?}, error: {:?}", + parentchain_id, serde_json::to_string(&call), e ); } } else if let Err(e) = api.submit_opaque_extrinsic(&call.encode().into()) { error!( - "Could not send extrinsic to node: {:?}, error: {:?}", + "Could not send extrinsic to {:?}: {:?}, error: {:?}", + parentchain_id, serde_json::to_string(&call), e ); diff --git a/service/src/parentchain_handler.rs b/service/src/parentchain_handler.rs index 8b11e92b87..2fd175af57 100644 --- a/service/src/parentchain_handler.rs +++ b/service/src/parentchain_handler.rs @@ -18,6 +18,8 @@ use crate::error::{Error, ServiceResult}; use codec::{Decode, Encode}; +use humantime::format_duration; +use ita_parentchain_interface::integritee::Header; use itc_parentchain::{ light_client::light_client_init_params::{GrandpaParams, SimpleParams}, primitives::{ParentchainId, ParentchainInitParams}, @@ -26,12 +28,16 @@ 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::ShardIdentifier; use log::*; -use my_node_runtime::Header; use sp_consensus_grandpa::VersionedAuthorityList; use sp_runtime::traits::Header as HeaderTrait; -use std::{cmp::min, sync::Arc}; -use substrate_api_client::ac_primitives::{Block, Header as HeaderT}; +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; @@ -42,17 +48,20 @@ pub trait HandleParentchain { /// Fetches the parentchain blocks to sync from the parentchain and feeds them to the enclave. /// Returns the latest synced block header. - fn sync_parentchain(&self, last_synced_header: Header) -> ServiceResult
; - - /// Triggers the import of the synced parentchain blocks inside the enclave. - fn trigger_parentchain_block_import(&self) -> ServiceResult<()>; + fn sync_parentchain_until_latest_finalized( + &self, + last_synced_header: Header, + shard: ShardIdentifier, + immediate_import: bool, + ) -> ServiceResult
; /// Syncs and directly imports parentchain blocks from the latest synced header - /// until the specified until_header. - fn sync_and_import_parentchain_until( + /// until at least the specified until_header. + fn await_sync_and_import_parentchain_until_at_least( &self, last_synced_header: &Header, until_header: &Header, + shard: ShardIdentifier, ) -> ServiceResult
; } @@ -60,7 +69,7 @@ pub trait HandleParentchain { pub(crate) struct ParentchainHandler { parentchain_api: ParentchainApi, enclave_api: Arc, - parentchain_init_params: ParentchainInitParams, + pub parentchain_init_params: ParentchainInitParams, } // #TODO: #1451: Reintroduce `ParentchainApi: ChainApi` once there is no trait bound conflict @@ -82,6 +91,7 @@ where parentchain_api: ParentchainApi, enclave_api: Arc, id: ParentchainId, + shard: ShardIdentifier, ) -> ServiceResult { let genesis_hash = parentchain_api.get_genesis_hash()?; let genesis_header = @@ -99,6 +109,7 @@ where ( id, + shard, GrandpaParams::new( // #TODO: #1451: clean up type hacks Header::decode(&mut genesis_header.encode().as_slice())?, @@ -110,6 +121,7 @@ where } else { ( id, + shard, SimpleParams::new( // #TODO: #1451: clean up type hacks Header::decode(&mut genesis_header.encode().as_slice())?, @@ -140,7 +152,12 @@ where .init_parentchain_components(self.parentchain_init_params.clone())?) } - fn sync_parentchain(&self, last_synced_header: Header) -> ServiceResult
{ + fn sync_parentchain_until_latest_finalized( + &self, + last_synced_header: Header, + shard: ShardIdentifier, + immediate_import: bool, + ) -> ServiceResult
{ let id = self.parentchain_id(); trace!("[{:?}] Getting current head", id); let curr_block = self @@ -148,53 +165,106 @@ where .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()))?; - println!( + info!( "[{:?}] Syncing blocks from {} to {}", - id, last_synced_header.number, curr_block_number + 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; loop { let block_chunk_to_sync = self.parentchain_api.get_blocks( until_synced_header.number + 1, min(until_synced_header.number + BLOCK_SYNC_BATCH_SIZE, curr_block_number), )?; - println!("[+] [{:?}] Found {} block(s) to sync", id, block_chunk_to_sync.len()); + 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 events_chunk_to_sync: Vec> = block_chunk_to_sync - .iter() - .map(|block| { - self.parentchain_api.get_events_for_block(Some(block.block.header.hash())) - }) - .collect::, _>>()?; - - println!("[+] [{:?}] Found {} event vector(s) to sync", id, events_chunk_to_sync.len()); - - let events_proofs_chunk_to_sync: Vec = block_chunk_to_sync - .iter() - .map(|block| { - self.parentchain_api.get_events_value_proof(Some(block.block.header.hash())) - }) - .collect::, _>>()?; + 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 + .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 + .iter() + .map(|block| { + self.parentchain_api.get_events_value_proof(Some(block.block.header.hash())) + }) + .collect::, _>>()? + }; 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, )?; let api_client_until_synced_header = block_chunk_to_sync .last() .map(|b| b.block.header.clone()) .ok_or(Error::EmptyChunk)?; - println!( + debug!( "[{:?}] Synced {} out of {} finalized parentchain blocks", - id, until_synced_header.number, curr_block_number, + id, api_client_until_synced_header.number, curr_block_number, ); // #TODO: #1451: fix api/client types @@ -204,15 +274,11 @@ where } } - fn trigger_parentchain_block_import(&self) -> ServiceResult<()> { - trace!("[{:?}] trigger parentchain block import", self.parentchain_id()); - Ok(self.enclave_api.trigger_parentchain_block_import(self.parentchain_id())?) - } - - fn sync_and_import_parentchain_until( + fn await_sync_and_import_parentchain_until_at_least( &self, last_synced_header: &Header, until_header: &Header, + shard: ShardIdentifier, ) -> ServiceResult
{ let id = self.parentchain_id(); @@ -225,11 +291,11 @@ where let mut last_synced_header = last_synced_header.clone(); while last_synced_header.number() < until_header.number() { - last_synced_header = self.sync_parentchain(last_synced_header)?; - trace!("[{:?}] synced block number: {}", id, last_synced_header.number); + last_synced_header = + self.sync_parentchain_until_latest_finalized(last_synced_header, shard, true)?; + println!("[{:?}] synced block number: #{}", id, last_synced_header.number); + std::thread::sleep(std::time::Duration::from_secs(1)); } - self.trigger_parentchain_block_import()?; - Ok(last_synced_header) } } diff --git a/service/src/setup.rs b/service/src/setup.rs index 15250642bb..f45bab61c2 100644 --- a/service/src/setup.rs +++ b/service/src/setup.rs @@ -50,10 +50,10 @@ mod needs_enclave { println!("[+] Initialize the shard"); init_shard(enclave, shard_identifier); - println!("[+] Generate key files"); - generate_signing_key_file(enclave); - generate_shielding_key_file(enclave); - + 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(()) } diff --git a/service/src/sidechain_setup.rs b/service/src/sidechain_setup.rs index be1ea3771f..d5a33c683f 100644 --- a/service/src/sidechain_setup.rs +++ b/service/src/sidechain_setup.rs @@ -28,7 +28,7 @@ use itp_settings::{ files::{SIDECHAIN_PURGE_INTERVAL, SIDECHAIN_PURGE_LIMIT}, sidechain::SLOT_DURATION, }; -use itp_types::Header; +use itp_types::{Header, ShardIdentifier}; use its_consensus_slots::start_slot_worker; use its_primitives::types::block::SignedBlock as SignedSidechainBlock; use its_storage::{interface::FetchBlocks, start_sidechain_pruning_loop, BlockPruner}; @@ -40,13 +40,16 @@ pub(crate) fn sidechain_start_untrusted_rpc_server( config: &Config, enclave: Arc, sidechain_storage: Arc, - tokio_handle: Handle, + tokio_handle: &Handle, ) where Enclave: DirectRequest + Clone, SidechainStorage: BlockPruner + FetchBlocks + Sync + Send + 'static, { let untrusted_url = config.untrusted_worker_url(); - println!("[+] Untrusted RPC server listening on {}", &untrusted_url); + debug!( + "starting untrusted RPC server listening to sidechain blocks from peers on {}", + &untrusted_url + ); let _untrusted_rpc_join_handle = tokio_handle.spawn(async move { itc_rpc_server::run_server(&untrusted_url, enclave, sidechain_storage) .await @@ -54,33 +57,14 @@ pub(crate) fn sidechain_start_untrusted_rpc_server( }); } -pub(crate) fn sidechain_init_block_production( +pub(crate) fn sidechain_init_block_production( enclave: Arc, - register_enclave_xt_header: &Header, - we_are_primary_validateer: bool, - parentchain_handler: Arc, sidechain_storage: Arc, - last_synced_header: &Header, -) -> ServiceResult
+) -> ServiceResult<()> where Enclave: EnclaveBase + Sidechain, SidechainStorage: BlockPruner + FetchBlocks + Sync + Send + 'static, - ParentchainHandler: HandleParentchain, { - // If we're the first validateer to register, also trigger parentchain block import. - let mut updated_header: Option
= None; - - if we_are_primary_validateer { - info!( - "We're the first validateer to be registered, syncing parentchain blocks until the one we have registered ourselves on." - ); - updated_header = - Some(parentchain_handler.sync_and_import_parentchain_until( - last_synced_header, - register_enclave_xt_header, - )?); - } - // ------------------------------------------------------------------------ // Initialize sidechain components (has to be AFTER init_parentchain_components() enclave.init_enclave_sidechain_components().unwrap(); @@ -114,7 +98,7 @@ where }) .map_err(|e| Error::Custom(Box::new(e)))?; - Ok(updated_header.unwrap_or_else(|| last_synced_header.clone())) + Ok(()) } /// Execute trusted operations in the enclave. diff --git a/service/src/sync_state.rs b/service/src/sync_state.rs index 6c70a5379e..ef53b2ec06 100644 --- a/service/src/sync_state.rs +++ b/service/src/sync_state.rs @@ -28,9 +28,12 @@ use itp_enclave_api::{ }; use itp_node_api::api_client::PalletTeerexApi; use itp_settings::worker_mode::{ProvideWorkerMode, WorkerMode}; -use itp_types::ShardIdentifier; +use itp_types::{parentchain::AccountId, ShardIdentifier}; +use log::info; use sgx_types::sgx_quote_sign_type_t; +use sp_runtime::MultiSigner; use std::string::String; +use teerex_primitives::AnySigner; pub(crate) fn sync_state< E: TlsRemoteAttestation + EnclaveBase + RemoteAttestation, @@ -42,13 +45,13 @@ pub(crate) fn sync_state< enclave_api: &E, skip_ra: bool, ) { - // FIXME: we now assume that keys are equal for all shards. let provider_url = match WorkerModeProvider::worker_mode() { - WorkerMode::Sidechain => - executor::block_on(get_author_url_of_last_finalized_sidechain_block(node_api, shard)) + WorkerMode::Sidechain | WorkerMode::OffChainWorker => + executor::block_on(get_enclave_url_of_last_active(node_api, enclave_api, shard)) + .expect("author of most recent shard update not found"), + WorkerMode::Teeracle => + executor::block_on(get_enclave_url_of_first_registered(node_api, enclave_api)) .expect("Author of last finalized sidechain block could not be found"), - _ => executor::block_on(get_enclave_url_of_first_registered(node_api, enclave_api)) - .expect("Author of last finalized sidechain block could not be found"), }; println!("Requesting state provisioning from worker at {}", &provider_url); @@ -82,20 +85,51 @@ async fn get_author_url_of_last_finalized_sidechain_block( node_api: &NodeApi, enclave_api: &EnclaveApi, ) -> Result { let self_mr_enclave = enclave_api.get_fingerprint()?; + let self_account = enclave_api.get_ecc_signing_pubkey()?; let first_enclave = node_api .all_enclaves(None)? .into_iter() + .filter(|e| e.instance_signer() != AnySigner::Known(MultiSigner::Ed25519(self_account))) .find(|e| e.fingerprint() == self_mr_enclave) .ok_or(Error::NoPeerWorkerFound)?; let worker_api_direct = DirectWorkerApi::new(String::from_utf8(first_enclave.instance_url().unwrap()).unwrap()); Ok(worker_api_direct.get_mu_ra_url()?) } + +/// Returns the url of the last active worker on our shard +async fn get_enclave_url_of_last_active( + node_api: &NodeApi, + enclave_api: &EnclaveApi, + shard: &ShardIdentifier, +) -> Result { + let self_account = enclave_api.get_ecc_signing_pubkey()?; + let shard_status = node_api + .shard_status(shard, None) + .expect("must be able to fetch shard status") + .expect("can only sync state for active shards"); + info!("fetching active peer. shard status: {:?}", shard_status); + let last_active_signer_status = shard_status + .iter() + .filter(|&s| s.signer != AccountId::from(self_account)) + .max_by_key(|&signer_status| signer_status.last_activity) + .expect("there has to be a most recently active peer") + .clone(); + info!("most recently active signer on this shard: {:?}", last_active_signer_status); + let provider_enclave = node_api + .enclave(&last_active_signer_status.signer, None) + .expect("must be able to fetch enclaves") + .expect("active peer must exist in registry"); + let worker_api_direct = DirectWorkerApi::new( + String::from_utf8(provider_enclave.instance_url().expect("provider must specify url")) + .unwrap(), + ); + Ok(worker_api_direct.get_mu_ra_url()?) +} diff --git a/service/src/teeracle/mod.rs b/service/src/teeracle/mod.rs index 420a175b26..910d45043f 100644 --- a/service/src/teeracle/mod.rs +++ b/service/src/teeracle/mod.rs @@ -39,7 +39,7 @@ pub(crate) mod teeracle_metrics; /// Currently, this is only used for the teeracle, but could also be used for other flavors in the /// future. pub(crate) fn schedule_periodic_reregistration_thread( - send_register_xt: impl Fn() -> Option + std::marker::Send + 'static, + send_register_xt: impl Fn() -> ServiceResult + std::marker::Send + 'static, period: Duration, ) { println!("Schedule periodic enclave reregistration every: {:?}", period); @@ -50,7 +50,7 @@ pub(crate) fn schedule_periodic_reregistration_thread( schedule_periodic( || { trace!("Reregistering the enclave."); - if let Some(block_hash) = send_register_xt() { + if let Ok(block_hash) = send_register_xt() { println!( "✅ Successfully reregistered the enclave. Block hash: {}.", block_hash diff --git a/service/src/tests/mock.rs b/service/src/tests/mock.rs index 6379e7cf05..7c7528fa6c 100644 --- a/service/src/tests/mock.rs +++ b/service/src/tests/mock.rs @@ -16,10 +16,11 @@ */ use codec::Encode; +use enclave_bridge_primitives::ShardSignerStatus; use itp_node_api::api_client::{ApiResult, PalletTeerexApi}; use itp_types::{ - AccountId, MultiEnclave, SgxBuildMode, SgxEnclave, SgxReportData, SgxStatus, ShardIdentifier, - H256 as Hash, + parentchain::BlockNumber, AccountId, MultiEnclave, SgxBuildMode, SgxEnclave, SgxReportData, + SgxStatus, ShardIdentifier, H256 as Hash, }; pub struct TestNodeApi; @@ -79,6 +80,15 @@ impl PalletTeerexApi for TestNodeApi { ) -> ApiResult>>> { unreachable!() } + + fn shard_status( + &self, + _: &ShardIdentifier, + _at_block: Option, + ) -> ApiResult>>> { + unreachable!() + } + fn latest_ipfs_hash( &self, _: &ShardIdentifier, diff --git a/service/src/tests/mocks/enclave_api_mock.rs b/service/src/tests/mocks/enclave_api_mock.rs index 5361e2ffa2..77d1b80307 100644 --- a/service/src/tests/mocks/enclave_api_mock.rs +++ b/service/src/tests/mocks/enclave_api_mock.rs @@ -24,8 +24,12 @@ use itc_parentchain::primitives::{ }; use itp_enclave_api::{enclave_base::EnclaveBase, sidechain::Sidechain, EnclaveResult}; use itp_settings::worker::MR_ENCLAVE_SIZE; +use itp_stf_interface::ShardCreationInfo; use itp_storage::StorageProof; -use itp_types::ShardIdentifier; +use itp_types::{ + parentchain::{Balance, Header}, + ShardIdentifier, +}; use sgx_crypto_helper::rsa3072::Rsa3072PubKey; use sp_core::ed25519; @@ -61,11 +65,25 @@ impl EnclaveBase for EnclaveMock { unimplemented!() } - fn init_proxied_shard_vault(&self, _shard: &ShardIdentifier) -> EnclaveResult<()> { + fn init_proxied_shard_vault( + &self, + _shard: &ShardIdentifier, + _parentchain_id: &ParentchainId, + _funding_balance: Balance, + ) -> EnclaveResult<()> { + unimplemented!() + } + + fn init_shard_creation_parentchain_header( + &self, + shard: &ShardIdentifier, + parentchain_id: &ParentchainId, + header: &Header, + ) -> EnclaveResult<()> { unimplemented!() } - fn trigger_parentchain_block_import(&self, _: &ParentchainId) -> EnclaveResult<()> { + fn get_shard_creation_info(&self, shard: &ShardIdentifier) -> EnclaveResult { unimplemented!() } @@ -101,6 +119,7 @@ impl Sidechain for EnclaveMock { _events: &[Vec], _events_proofs: &[StorageProof], _: &ParentchainId, + _: bool, ) -> EnclaveResult<()> { Ok(()) } diff --git a/service/src/tests/mocks/parentchain_api_mock.rs b/service/src/tests/mocks/parentchain_api_mock.rs index 2411d61408..569fea61a0 100644 --- a/service/src/tests/mocks/parentchain_api_mock.rs +++ b/service/src/tests/mocks/parentchain_api_mock.rs @@ -16,10 +16,10 @@ */ use itc_parentchain_test::{ParentchainBlockBuilder, ParentchainHeaderBuilder}; -use itp_node_api::api_client::{ApiResult, Block, ChainApi, SignedBlock}; +use itp_node_api::api_client::{ApiResult, ChainApi}; use itp_types::{ parentchain::{Hash, Header, StorageProof}, - H256, + Block, SignedBlock, H256, }; use sp_consensus_grandpa::AuthorityList; diff --git a/service/src/tests/mocks/update_worker_peers_mock.rs b/service/src/tests/mocks/update_worker_peers_mock.rs index 86c27690fa..a42fc1c421 100644 --- a/service/src/tests/mocks/update_worker_peers_mock.rs +++ b/service/src/tests/mocks/update_worker_peers_mock.rs @@ -16,11 +16,12 @@ */ use crate::{worker::WorkerResult, worker_peers_updater::UpdateWorkerPeers}; +use itp_types::ShardIdentifier; pub struct UpdateWorkerPeersMock; impl UpdateWorkerPeers for UpdateWorkerPeersMock { - fn update_peers(&self) -> WorkerResult<()> { + fn update_peers(&self, shard: ShardIdentifier) -> WorkerResult<()> { Ok(()) } } diff --git a/service/src/worker.rs b/service/src/worker.rs index a01fdd9888..ebda09014e 100644 --- a/service/src/worker.rs +++ b/service/src/worker.rs @@ -24,6 +24,7 @@ use crate::{config::Config, error::Error, initialized_service::TrackInitializati use async_trait::async_trait; use itc_rpc_client::direct_client::{DirectApi, DirectClient as DirectWorkerApi}; use itp_node_api::{api_client::PalletTeerexApi, node_api_factory::CreateNodeApi}; +use itp_types::ShardIdentifier; use its_primitives::types::SignedBlock as SignedSidechainBlock; use its_rpc_handler::constants::RPC_METHOD_NAME_IMPORT_BLOCKS; use jsonrpsee::{ @@ -32,6 +33,8 @@ use jsonrpsee::{ }; use log::*; use std::sync::{Arc, RwLock}; +use teerex_primitives::MultiEnclave; +use url::Url as UrlType; pub type WorkerResult = Result; pub type Url = String; @@ -83,6 +86,7 @@ where debug!("No blocks to broadcast, returning"); return Ok(()) } + let nr_blocks = blocks.len(); let blocks_json = vec![to_json_value(blocks)?]; let peers = self @@ -95,6 +99,8 @@ where self.initialization_handler.sidechain_block_produced(); + let nr_peers = peers.len(); + for url in peers { let blocks = blocks_json.clone(); @@ -119,18 +125,19 @@ where } }); } + info!("broadcast {} block(s) to {} peers", nr_blocks, nr_peers); Ok(()) } } /// Looks for new peers and updates them. pub trait UpdatePeers { - fn search_peers(&self) -> WorkerResult>; + fn search_peers(&self, shard: ShardIdentifier) -> WorkerResult>; fn set_peers(&self, peers: Vec) -> WorkerResult<()>; - fn update_peers(&self) -> WorkerResult<()> { - let peers = self.search_peers()?; + fn update_peers(&self, shard: ShardIdentifier) -> WorkerResult<()> { + let peers = self.search_peers(shard)?; self.set_peers(peers) } } @@ -140,17 +147,29 @@ impl UpdatePeers where NodeApiFactory: CreateNodeApi + Send + Sync, { - fn search_peers(&self) -> WorkerResult> { + fn search_peers(&self, shard: ShardIdentifier) -> WorkerResult> { 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(None)?; + let shard_status = node_api + .shard_status(&shard, None)? + .ok_or_else(|| Error::Custom("failed to fetch shard status".into()))?; + let enclaves: Vec>> = shard_status + .iter() + .filter_map(|w| node_api.enclave(&w.signer, None).ok().flatten()) + .collect(); + let mut peer_urls = Vec::::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(enclave.instance_url().unwrap()).unwrap(); - let worker_api_direct = DirectWorkerApi::new(enclave_url.clone()); + let enclave_url = UrlType::parse(&format!( + "wss://{}", + String::from_utf8_lossy(&enclave.instance_url().unwrap()).replace("wss://", "") + )) + .unwrap(); + trace!("found peer rpc url: {}", enclave_url); + let worker_api_direct = DirectWorkerApi::new(enclave_url.clone().into()); match worker_api_direct.get_untrusted_worker_url() { Ok(untrusted_worker_url) => { peer_urls.push(untrusted_worker_url); @@ -163,6 +182,7 @@ where }, } } + debug!("found {} peers in shard state for {:?}", peer_urls.len(), shard); Ok(peer_urls) } diff --git a/service/src/worker_peers_updater.rs b/service/src/worker_peers_updater.rs index 5b536ef667..c446ead195 100644 --- a/service/src/worker_peers_updater.rs +++ b/service/src/worker_peers_updater.rs @@ -22,12 +22,13 @@ use mockall::predicate::*; use mockall::*; use crate::worker::{UpdatePeers, WorkerResult}; +use itp_types::ShardIdentifier; use std::sync::Arc; /// Updates the peers of the global worker. #[cfg_attr(test, automock)] pub trait UpdateWorkerPeers { - fn update_peers(&self) -> WorkerResult<()>; + fn update_peers(&self, shard: ShardIdentifier) -> WorkerResult<()>; } pub struct WorkerPeersUpdater { @@ -44,7 +45,7 @@ impl UpdateWorkerPeers for WorkerPeersUpdater where WorkerType: UpdatePeers, { - fn update_peers(&self) -> WorkerResult<()> { - self.worker.update_peers() + fn update_peers(&self, shard: ShardIdentifier) -> WorkerResult<()> { + self.worker.update_peers(shard) } } diff --git a/sidechain/block-composer/Cargo.toml b/sidechain/block-composer/Cargo.toml index 390bc5f5fd..99b1272565 100644 --- a/sidechain/block-composer/Cargo.toml +++ b/sidechain/block-composer/Cargo.toml @@ -10,13 +10,11 @@ sgx_tstd = { branch = "master", git = "https://github.com/apache/teaclave-sgx-sd sgx_types = { branch = "master", git = "https://github.com/apache/teaclave-sgx-sdk.git" } # local dependencies -ita-stf = { path = "../../app-libs/stf", default-features = false } itp-node-api = { path = "../../core-primitives/node-api", default-features = false } itp-settings = { path = "../../core-primitives/settings", default-features = false } itp-sgx-crypto = { path = "../../core-primitives/sgx/crypto", default-features = false } itp-sgx-externalities = { path = "../../core-primitives/substrate-sgx/externalities", default-features = false } itp-stf-executor = { path = "../../core-primitives/stf-executor", default-features = false } -itp-stf-interface = { path = "../../core-primitives/stf-interface", default-features = false } itp-stf-primitives = { path = "../../core-primitives/stf-primitives", default-features = false } itp-time-utils = { path = "../../core-primitives/time-utils", default-features = false } itp-top-pool-author = { path = "../../core-primitives/top-pool-author", default-features = false } @@ -40,12 +38,10 @@ sp-runtime = { default-features = false, git = "https://github.com/paritytech/su [features] default = ["std"] std = [ - "ita-stf/std", "itp-node-api/std", "itp-sgx-crypto/std", "itp-sgx-externalities/std", "itp-stf-executor/std", - "itp-stf-interface/std", "itp-stf-primitives/std", "itp-time-utils/std", "itp-top-pool-author/std", @@ -57,7 +53,6 @@ std = [ ] sgx = [ "sgx_tstd", - "ita-stf/sgx", "itp-node-api/sgx", "itp-sgx-crypto/sgx", "itp-sgx-externalities/sgx", diff --git a/sidechain/block-verification/Cargo.toml b/sidechain/block-verification/Cargo.toml index 34eed84724..2869ed833d 100644 --- a/sidechain/block-verification/Cargo.toml +++ b/sidechain/block-verification/Cargo.toml @@ -9,7 +9,7 @@ license = "Apache-2.0" edition = "2021" [dependencies] -log = { version = "0.4.17", default-features = false } +log = { version = "0.4", default-features = false } thiserror = { version = "1.0.26", optional = true } # local deps diff --git a/sidechain/consensus/aura/Cargo.toml b/sidechain/consensus/aura/Cargo.toml index 72ed0a6f70..3e1501bb87 100644 --- a/sidechain/consensus/aura/Cargo.toml +++ b/sidechain/consensus/aura/Cargo.toml @@ -13,7 +13,6 @@ log = { version = "0.4", default-features = false } sgx_tstd = { branch = "master", git = "https://github.com/apache/teaclave-sgx-sdk.git", optional = true } # substrate deps -frame-support = { default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } sp-core = { default-features = false, features = ["full_crypto"], git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } sp-runtime = { default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } @@ -58,7 +57,6 @@ std = [ "finality-grandpa/std", "log/std", #substrate - "frame-support/std", "sp-core/std", "sp-runtime/std", #local @@ -73,6 +71,7 @@ std = [ "itp-stf-state-handler/std", "itp-time-utils/std", "itp-types/std", + "itp-utils/std", "its-block-composer/std", "its-block-verification/std", "its-consensus-common/std", diff --git a/sidechain/consensus/aura/src/lib.rs b/sidechain/consensus/aura/src/lib.rs index 0c52803086..ad6690c1c9 100644 --- a/sidechain/consensus/aura/src/lib.rs +++ b/sidechain/consensus/aura/src/lib.rs @@ -29,10 +29,13 @@ compile_error!("feature \"std\" and feature \"sgx\" cannot be enabled at the sam #[macro_use] extern crate sgx_tstd as std; +use codec::Encode; use core::marker::PhantomData; use itc_parentchain_block_import_dispatcher::triggered_dispatcher::TriggerParentchainBlockImport; use itp_ocall_api::EnclaveOnChainOCallApi; use itp_time_utils::duration_now; + +use itp_utils::hex::hex_encode; use its_block_verification::slot::slot_author; use its_consensus_common::{Environment, Error as ConsensusError, Proposer}; use its_consensus_slots::{SimpleSlotWorker, Slot, SlotInfo}; @@ -66,29 +69,55 @@ pub struct Aura< SidechainBlock, Environment, OcallApi, - ImportTrigger, + IntegriteeImportTrigger, + TargetAImportTrigger, + TargetBImportTrigger, > { authority_pair: AuthorityPair, ocall_api: OcallApi, - parentchain_import_trigger: Arc, + parentchain_integritee_import_trigger: Arc, + maybe_parentchain_target_a_import_trigger: Option>, + maybe_parentchain_target_b_import_trigger: Option>, environment: Environment, claim_strategy: SlotClaimStrategy, _phantom: PhantomData<(AuthorityPair, ParentchainBlock, SidechainBlock)>, } -impl - Aura +impl< + AuthorityPair, + ParentchainBlock, + SidechainBlock, + Environment, + OcallApi, + IntegriteeImportTrigger, + TargetAImportTrigger, + TargetBImportTrigger, + > + Aura< + AuthorityPair, + ParentchainBlock, + SidechainBlock, + Environment, + OcallApi, + IntegriteeImportTrigger, + TargetAImportTrigger, + TargetBImportTrigger, + > { pub fn new( authority_pair: AuthorityPair, ocall_api: OcallApi, - parentchain_import_trigger: Arc, + parentchain_integritee_import_trigger: Arc, + maybe_parentchain_target_a_import_trigger: Option>, + maybe_parentchain_target_b_import_trigger: Option>, environment: Environment, ) -> Self { Self { authority_pair, ocall_api, - parentchain_import_trigger, + parentchain_integritee_import_trigger, + maybe_parentchain_target_a_import_trigger, + maybe_parentchain_target_b_import_trigger, environment, claim_strategy: SlotClaimStrategy::RoundRobin, _phantom: Default::default(), @@ -119,10 +148,26 @@ type AuthorityId

=

::Public; type ShardIdentifierFor = <<::Block as SidechainBlockTrait>::HeaderType as HeaderTrait>::ShardIdentifier; -impl - SimpleSlotWorker - for Aura -where +impl< + AuthorityPair, + ParentchainBlock, + SignedSidechainBlock, + E, + OcallApi, + IntegriteeImportTrigger, + TargetAImportTrigger, + TargetBImportTrigger, + > SimpleSlotWorker + for Aura< + AuthorityPair, + ParentchainBlock, + SignedSidechainBlock, + E, + OcallApi, + IntegriteeImportTrigger, + TargetAImportTrigger, + TargetBImportTrigger, + > where AuthorityPair: Pair, AuthorityPair::Public: UncheckedFrom<[u8; 32]>, // todo: Relax hash trait bound, but this needs a change to some other parts in the code. @@ -131,7 +176,11 @@ where E::Proposer: Proposer, SignedSidechainBlock: SignedBlock + Send + 'static, OcallApi: ValidateerFetch + EnclaveOnChainOCallApi + Send + 'static, - ImportTrigger: + IntegriteeImportTrigger: + TriggerParentchainBlockImport>, + TargetAImportTrigger: + TriggerParentchainBlockImport>, + TargetBImportTrigger: TriggerParentchainBlockImport>, { type Proposer = E::Proposer; @@ -197,12 +246,51 @@ where proposing_remaining_duration(slot_info, duration_now()) } - fn import_parentchain_blocks_until( + // Design remark: the following may seem too explicit and it certainly could be abstracted. + // however, as pretty soon we may not want to assume same Block types for all parentchains, + // it may make sense to abstract once we do that. + + fn import_integritee_parentchain_blocks_until( + &self, + parentchain_header_hash: &::Hash, + ) -> Result, ConsensusError> { + log::trace!(target: self.logging_target(), "import Integritee blocks until {}", hex_encode(parentchain_header_hash.encode().as_ref())); + let maybe_parentchain_block = self + .parentchain_integritee_import_trigger + .import_until(|parentchain_block| { + parentchain_block.block.hash() == *parentchain_header_hash + }) + .map_err(|e| ConsensusError::Other(e.into()))?; + + Ok(maybe_parentchain_block.map(|b| b.block.header().clone())) + } + + fn import_target_a_parentchain_blocks_until( + &self, + parentchain_header_hash: &::Hash, + ) -> Result, ConsensusError> { + log::trace!(target: self.logging_target(), "import TargetA blocks until {}", hex_encode(parentchain_header_hash.encode().as_ref())); + let maybe_parentchain_block = self + .maybe_parentchain_target_a_import_trigger + .clone() + .ok_or_else(|| ConsensusError::Other("no target_a assigned".into()))? + .import_until(|parentchain_block| { + parentchain_block.block.hash() == *parentchain_header_hash + }) + .map_err(|e| ConsensusError::Other(e.into()))?; + + Ok(maybe_parentchain_block.map(|b| b.block.header().clone())) + } + + fn import_target_b_parentchain_blocks_until( &self, parentchain_header_hash: &::Hash, ) -> Result, ConsensusError> { + log::trace!(target: self.logging_target(), "import TargetB blocks until {}", hex_encode(parentchain_header_hash.encode().as_ref())); let maybe_parentchain_block = self - .parentchain_import_trigger + .maybe_parentchain_target_b_import_trigger + .clone() + .ok_or_else(|| ConsensusError::Other("no target_b assigned".into()))? .import_until(|parentchain_block| { parentchain_block.block.hash() == *parentchain_header_hash }) @@ -211,11 +299,37 @@ where Ok(maybe_parentchain_block.map(|b| b.block.header().clone())) } - fn peek_latest_parentchain_header( + fn peek_latest_integritee_parentchain_header( + &self, + ) -> Result, ConsensusError> { + let maybe_parentchain_block = self + .parentchain_integritee_import_trigger + .peek_latest() + .map_err(|e| ConsensusError::Other(format!("{:?}", e).into()))?; + + Ok(maybe_parentchain_block.map(|b| b.block.header().clone())) + } + + fn peek_latest_target_a_parentchain_header( &self, ) -> Result, ConsensusError> { let maybe_parentchain_block = self - .parentchain_import_trigger + .maybe_parentchain_target_a_import_trigger + .clone() + .ok_or_else(|| ConsensusError::Other("no target_a assigned".into()))? + .peek_latest() + .map_err(|e| ConsensusError::Other(format!("{:?}", e).into()))?; + + Ok(maybe_parentchain_block.map(|b| b.block.header().clone())) + } + + fn peek_latest_target_b_parentchain_header( + &self, + ) -> Result, ConsensusError> { + let maybe_parentchain_block = self + .maybe_parentchain_target_b_import_trigger + .clone() + .ok_or_else(|| ConsensusError::Other("no target_b assigned".into()))? .peek_latest() .map_err(|e| ConsensusError::Other(format!("{:?}", e).into()))?; @@ -261,6 +375,12 @@ where .collect()) } +pub enum AnyImportTrigger { + Integritee(Integritee), + TargetA(TargetA), + TargetB(TargetB), +} + #[cfg(test)] mod tests { use super::*; @@ -283,7 +403,14 @@ mod tests { onchain_mock: OnchainMock, trigger_parentchain_import: Arc>, ) -> TestAura { - Aura::new(Keyring::Alice.pair(), onchain_mock, trigger_parentchain_import, EnvironmentMock) + Aura::new( + Keyring::Alice.pair(), + onchain_mock, + trigger_parentchain_import, + None, + None, + EnvironmentMock, + ) } fn get_default_aura() -> TestAura { @@ -297,7 +424,9 @@ mod tests { timestamp: now, duration: SLOT_DURATION, ends_at: now + SLOT_DURATION, - last_imported_parentchain_head: header.clone(), + last_imported_integritee_parentchain_head: header.clone(), + maybe_last_imported_target_a_parentchain_head: None, + maybe_last_imported_target_b_parentchain_head: None, } } @@ -413,7 +542,9 @@ mod tests { timestamp: now, duration: nano_dur, ends_at: now + nano_dur, - last_imported_parentchain_head: ParentchainHeaderBuilder::default().build(), + last_imported_integritee_parentchain_head: ParentchainHeaderBuilder::default().build(), + maybe_last_imported_target_a_parentchain_head: None, + maybe_last_imported_target_b_parentchain_head: None, }; let result = PerShardSlotWorkerScheduler::on_slot( diff --git a/sidechain/consensus/aura/src/slot_proposer.rs b/sidechain/consensus/aura/src/slot_proposer.rs index 7fd7e64836..4e2950989b 100644 --- a/sidechain/consensus/aura/src/slot_proposer.rs +++ b/sidechain/consensus/aura/src/slot_proposer.rs @@ -124,6 +124,7 @@ where // Remove all not successfully executed operations from the top pool. let failed_operations = batch_execution_result.get_failed_operations(); + let nr_failed_operations = failed_operations.len(); self.top_pool_author.remove_calls_from_pool( self.shard, failed_operations @@ -147,11 +148,13 @@ where ) .map_err(|e| ConsensusError::Other(e.to_string().into()))?; - info!( - "Queue/Timeslot/Transactions: {:?};{};{}", + println!( + "[Sidechain] propose block {} summary: executed {}, failed {}, from {} in queue in {}ms", + sidechain_block.block().header().block_number(), + number_executed_transactions, + nr_failed_operations, trusted_calls.len(), max_duration.as_millis(), - number_executed_transactions ); Ok(Proposal { block: sidechain_block, parentchain_effects: parentchain_extrinsics }) diff --git a/sidechain/consensus/aura/src/test/fixtures/types.rs b/sidechain/consensus/aura/src/test/fixtures/types.rs index 39aa4ef3f4..98cec742ba 100644 --- a/sidechain/consensus/aura/src/test/fixtures/types.rs +++ b/sidechain/consensus/aura/src/test/fixtures/types.rs @@ -40,4 +40,6 @@ pub type TestAura = Aura< EnvironmentMock, OnchainMock, TriggerParentchainBlockImportMock>, + TriggerParentchainBlockImportMock>, + TriggerParentchainBlockImportMock>, >; diff --git a/sidechain/consensus/common/Cargo.toml b/sidechain/consensus/common/Cargo.toml index 226f19d8d3..0d9f33ada5 100644 --- a/sidechain/consensus/common/Cargo.toml +++ b/sidechain/consensus/common/Cargo.toml @@ -6,6 +6,7 @@ edition = "2021" [dependencies] codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false } +itertools = { version = "0.10.1", default-features = false, features = ["use_alloc"] } log = { version = "0.4", default-features = false } thiserror = { version = "1.0.26", optional = true } @@ -20,6 +21,7 @@ itp-ocall-api = { path = "../../../core-primitives/ocall-api", default-features itp-settings = { path = "../../../core-primitives/settings" } itp-sgx-crypto = { path = "../../../core-primitives/sgx/crypto", default-features = false } itp-types = { path = "../../../core-primitives/types", default-features = false } +itp-utils = { path = "../../../core-primitives/utils", default-features = false } its-block-verification = { path = "../../block-verification", optional = true, default-features = false } its-primitives = { path = "../../primitives", default-features = false } its-state = { path = "../../state", default-features = false } @@ -50,6 +52,7 @@ std = [ "thiserror", # local "itc-parentchain-light-client/std", + "itertools/use_std", "itp-import-queue/std", "itp-extrinsics-factory/std", "itp-node-api-metadata/std", @@ -58,14 +61,13 @@ std = [ "itp-sgx-crypto/std", "itp-sgx-externalities/std", "itp-types/std", + "itp-utils/std", "its-primitives/std", "its-block-verification/std", "its-state/std", "fork-tree/std", # substrate "sp-runtime/std", - # scs - "itp-types/std", ] sgx = [ "sgx_tstd", diff --git a/sidechain/consensus/common/src/block_import_confirmation_handler.rs b/sidechain/consensus/common/src/block_import_confirmation_handler.rs index be93feb51c..8bfe21d2ed 100644 --- a/sidechain/consensus/common/src/block_import_confirmation_handler.rs +++ b/sidechain/consensus/common/src/block_import_confirmation_handler.rs @@ -100,13 +100,13 @@ impl< ValidatorAccessor: ValidatorAccess + Send + Sync + 'static, { fn confirm_import(&self, header: &SidechainHeader, shard: &ShardIdentifier) -> Result<()> { - let call = self - .metadata_repository - .get_from_metadata(|m| m.confirm_imported_sidechain_block_indexes()) - .map_err(|e| Error::Other(e.into()))? - .map_err(|e| Error::Other(format!("{:?}", e).into()))?; - if header.block_number() == header.next_finalization_block_number() { + let call = self + .metadata_repository + .get_from_metadata(|m| m.confirm_imported_sidechain_block_indexes()) + .map_err(|e| Error::Other(e.into()))? + .map_err(|e| Error::Other(format!("{:?}", e).into()))?; + let opaque_call = OpaqueCall::from_tuple(&( call, shard, diff --git a/sidechain/consensus/common/src/block_import_queue_worker.rs b/sidechain/consensus/common/src/block_import_queue_worker.rs index fc7d9a23ef..4506c07000 100644 --- a/sidechain/consensus/common/src/block_import_queue_worker.rs +++ b/sidechain/consensus/common/src/block_import_queue_worker.rs @@ -15,13 +15,16 @@ */ -use crate::{Error, Result, SyncBlockFromPeer}; +use crate::{Result, SyncBlockFromPeer}; use core::marker::PhantomData; -use itp_import_queue::PopFromQueue; -use its_primitives::traits::{Block as BlockTrait, SignedBlock as SignedSidechainBlockTrait}; -use log::debug; +use itertools::Itertools; +use itp_import_queue::{PeekQueue, PopFromQueue}; +use its_primitives::traits::{ + Block as BlockTrait, Header, SignedBlock as SignedSidechainBlockTrait, +}; +use log::{debug, trace}; use sp_runtime::traits::Block as ParentchainBlockTrait; -use std::{sync::Arc, time::Instant}; +use std::{sync::Arc, time::Instant, vec::Vec}; /// Trait to trigger working the sidechain block import queue. pub trait ProcessBlockImportQueue { @@ -49,7 +52,7 @@ where ParentchainBlock: ParentchainBlockTrait, SignedSidechainBlock: SignedSidechainBlockTrait, SignedSidechainBlock::Block: BlockTrait, - BlockImportQueue: PopFromQueue, + BlockImportQueue: PopFromQueue + PeekQueue, PeerBlockSyncer: SyncBlockFromPeer, { pub fn new( @@ -85,7 +88,7 @@ impl ParentchainBlock: ParentchainBlockTrait, SignedSidechainBlock: SignedSidechainBlockTrait, SignedSidechainBlock::Block: BlockTrait, - BlockImportQueue: PopFromQueue, + BlockImportQueue: PopFromQueue + PeekQueue, PeerBlockSyncer: SyncBlockFromPeer, { fn process_queue( @@ -93,28 +96,42 @@ impl current_parentchain_header: &ParentchainBlock::Header, ) -> Result { let mut latest_imported_parentchain_header = current_parentchain_header.clone(); - let mut number_of_imported_blocks = 0usize; let start_time = Instant::now(); - loop { - match self.block_import_queue.pop_front() { - Ok(maybe_block) => match maybe_block { - Some(block) => { - latest_imported_parentchain_header = self - .peer_block_syncer - .sync_block(block, &latest_imported_parentchain_header)?; - number_of_imported_blocks += 1; - }, - None => { - Self::record_timings(start_time, number_of_imported_blocks); - return Ok(latest_imported_parentchain_header) - }, - }, - Err(e) => { - Self::record_timings(start_time, number_of_imported_blocks); - return Err(Error::FailedToPopBlockImportQueue(e)) - }, - } - } + trace!( + "processing import queue with {:?} sidechain blocks", + self.block_import_queue.peek_queue_size() + ); + + let number_of_imported_blocks = self + .block_import_queue + .pop_all()? + .iter() + .map(|b| (b.block().header().block_number(), b)) + .sorted_by_key(|a| a.0) + .group_by(|&a| a.0) + .into_iter() + .filter_map(|(block_number, competitors)| { + let mut competitors: Vec<&SignedSidechainBlock> = + competitors.map(|c| c.1).collect(); + // deterministic import order decreases chances for forks + competitors.sort_by_key(|a| a.block().hash()); + trace!("nr of competitors for block {}: {}", block_number, competitors.len()); + + // returns the first block satisfying the predicate + competitors.into_iter().find_map(|block| { + self.peer_block_syncer + .import_or_sync_block(block.clone(), &latest_imported_parentchain_header) + .ok() + .map(|parentchain_header| { + latest_imported_parentchain_header = parentchain_header; + block + }) + }) + }) + .count(); + + Self::record_timings(start_time, number_of_imported_blocks); + Ok(latest_imported_parentchain_header) } } diff --git a/sidechain/consensus/common/src/lib.rs b/sidechain/consensus/common/src/lib.rs index fa2104186f..64391c1bf1 100644 --- a/sidechain/consensus/common/src/lib.rs +++ b/sidechain/consensus/common/src/lib.rs @@ -26,8 +26,8 @@ compile_error!("feature \"std\" and feature \"sgx\" cannot be enabled at the sam #[cfg(all(not(feature = "std"), feature = "sgx"))] #[macro_use] extern crate sgx_tstd as std; +extern crate alloc; -use itp_types::OpaqueCall; use its_primitives::traits::{ShardIdentifierFor, SignedBlock as SignedSidechainBlockTrait}; use sp_runtime::traits::Block as ParentchainBlockTrait; use std::{time::Duration, vec::Vec}; @@ -50,6 +50,7 @@ pub use block_import::*; pub use block_import_confirmation_handler::*; pub use block_import_queue_worker::*; pub use error::*; +use itp_types::parentchain::ParentchainCall; pub use peer_block_sync::*; pub trait Verifier: Send + Sync @@ -110,5 +111,5 @@ pub struct Proposal { /// /// Any sidechain stf that invokes a parentchain stf must not commit its state change /// before the parentchain effect has been finalized. - pub parentchain_effects: Vec, + pub parentchain_effects: Vec, } diff --git a/sidechain/consensus/common/src/peer_block_sync.rs b/sidechain/consensus/common/src/peer_block_sync.rs index 28ab9f4ea9..b1b5419697 100644 --- a/sidechain/consensus/common/src/peer_block_sync.rs +++ b/sidechain/consensus/common/src/peer_block_sync.rs @@ -16,12 +16,14 @@ */ use crate::{BlockImport, ConfirmBlockImport, Error, Result}; -use core::marker::PhantomData; +use codec::Encode; +use core::{fmt::Debug, marker::PhantomData}; use itp_ocall_api::EnclaveSidechainOCallApi; use itp_types::H256; +use itp_utils::hex::hex_encode; use its_primitives::{ traits::{ - Block as BlockTrait, Header as HeaderTrait, ShardIdentifierFor, + Block as BlockTrait, BlockData, Header as HeaderTrait, ShardIdentifierFor, SignedBlock as SignedSidechainBlockTrait, }, types::BlockHash, @@ -39,7 +41,13 @@ where ParentchainHeader: ParentchainHeaderTrait, SignedSidechainBlock: SignedSidechainBlockTrait, { - fn sync_block( + fn import_or_sync_block( + &self, + sidechain_block: SignedSidechainBlock, + last_imported_parentchain_header: &ParentchainHeader, + ) -> Result; + + fn import_block( &self, sidechain_block: SignedSidechainBlock, last_imported_parentchain_header: &ParentchainHeader, @@ -153,18 +161,21 @@ where SignedSidechainBlock: SignedSidechainBlockTrait, <::Block as BlockTrait>::HeaderType: HeaderTrait, + <<::Block as BlockTrait>::BlockDataType as BlockData>::Public: Encode + Debug, BlockImporter: BlockImport, SidechainOCallApi: EnclaveSidechainOCallApi, ImportConfirmationHandler: ConfirmBlockImport<<::Block as BlockTrait>::HeaderType>, { - fn sync_block( + fn import_or_sync_block( &self, sidechain_block: SignedSidechainBlock, current_parentchain_header: &ParentchainBlock::Header, ) -> Result { let shard_identifier = sidechain_block.block().header().shard_id(); let sidechain_block_number = sidechain_block.block().header().block_number(); + let sidechain_block_author = sidechain_block.block().block_data().block_author(); let sidechain_block_hash = sidechain_block.hash(); + trace!("attempt to import block {} with hash {} and author {:?}", sidechain_block_number, hex_encode(sidechain_block_hash.as_ref()), sidechain_block_author); // Attempt to import the block - in case we encounter an ancestry error, we go into // peer fetching mode to fetch sidechain blocks from a peer and import those first. @@ -194,15 +205,16 @@ where self.importer.import_block(sidechain_block, &updated_parentchain_header) }, Error::BlockAlreadyImported(to_import_block_number, last_known_block_number) => { - warn!("Sidechain block from queue (number: {}) was already imported (current block number: {}). Block will be ignored.", + warn!("Sidechain block from queue (number: {}) was already imported (current block number: {}). Block will be ignored.", to_import_block_number, last_known_block_number); Ok(current_parentchain_header.clone()) }, _ => Err(e), }, Ok(latest_parentchain_header) => { - info!("Successfully imported broadcast sidechain block (number: {}), based on parentchain block {:?}", - sidechain_block_number, latest_parentchain_header.number()); + println!("[Sidechain] imported block (number: {}, tcalls: {}, author: {}), based on parentchain block {:?}", + sidechain_block_number, sidechain_block.block().block_data().signed_top_hashes().len(), + hex_encode(sidechain_block.block().block_data().block_author().encode().as_slice()) ,latest_parentchain_header.number()); // We confirm the successful block import. Only in this case, not when we're in // on-boarding and importing blocks that were fetched from a peer. @@ -214,6 +226,14 @@ where }, } } + fn import_block( + &self, + sidechain_block: SignedSidechainBlock, + current_parentchain_header: &ParentchainBlock::Header, + ) -> Result { + self.importer.import_block(sidechain_block, current_parentchain_header) + } + } #[cfg(test)] @@ -255,7 +275,9 @@ mod tests { let peer_syncer = create_peer_syncer(block_importer_mock.clone(), sidechain_ocall_api.clone()); - peer_syncer.sync_block(signed_sidechain_block, &parentchain_header).unwrap(); + peer_syncer + .import_or_sync_block(signed_sidechain_block, &parentchain_header) + .unwrap(); assert_eq!(1, block_importer_mock.get_imported_blocks().len()); assert_eq!(0, sidechain_ocall_api.number_of_fetch_calls()); @@ -277,7 +299,8 @@ mod tests { let parentchain_header = ParentchainHeaderBuilder::default().build(); let signed_sidechain_block = SidechainBlockBuilder::default().build_signed(); - let sync_result = peer_syncer.sync_block(signed_sidechain_block, &parentchain_header); + let sync_result = + peer_syncer.import_or_sync_block(signed_sidechain_block, &parentchain_header); assert_matches!(sync_result, Err(Error::InvalidAuthority(_))); assert_eq!(1, block_importer_mock.get_imported_blocks().len()); @@ -304,7 +327,9 @@ mod tests { let parentchain_header = ParentchainHeaderBuilder::default().build(); let signed_sidechain_block = SidechainBlockBuilder::default().build_signed(); - peer_syncer.sync_block(signed_sidechain_block, &parentchain_header).unwrap(); + peer_syncer + .import_or_sync_block(signed_sidechain_block, &parentchain_header) + .unwrap(); assert_eq!(4, block_importer_mock.get_imported_blocks().len()); assert_eq!(1, sidechain_ocall_api.number_of_fetch_calls()); diff --git a/sidechain/consensus/slots/Cargo.toml b/sidechain/consensus/slots/Cargo.toml index 94ba257cad..3c1a81470d 100644 --- a/sidechain/consensus/slots/Cargo.toml +++ b/sidechain/consensus/slots/Cargo.toml @@ -17,7 +17,6 @@ its-block-verification = { path = "../../block-verification", default-features = its-primitives = { path = "../../primitives", default-features = false } # only for slot-stream -futures = { version = "0.3", optional = true } futures-timer = { version = "3.0", optional = true } # sgx deps @@ -29,7 +28,6 @@ sp-runtime = { default-features = false, git = "https://github.com/paritytech/su # local deps itp-settings = { path = "../../../core-primitives/settings" } -itp-sgx-io = { path = "../../../core-primitives/sgx/io", default-features = false } itp-time-utils = { path = "../../../core-primitives/time-utils", default-features = false } its-consensus-common = { path = "../common", default-features = false } @@ -46,13 +44,11 @@ std = [ "codec/std", "log/std", # only for slot-stream - "futures", "futures-timer", # substrate "sp-consensus-slots/std", "sp-runtime/std", # local - "itp-sgx-io/std", "itp-time-utils/std", "itp-types/std", "its-primitives/std", @@ -60,7 +56,6 @@ std = [ "its-consensus-common/std", ] sgx = [ - "itp-sgx-io/sgx", "itp-time-utils/sgx", "its-consensus-common/sgx", "sgx_tstd", diff --git a/sidechain/consensus/slots/src/lib.rs b/sidechain/consensus/slots/src/lib.rs index cff263fa60..9ac42a412b 100644 --- a/sidechain/consensus/slots/src/lib.rs +++ b/sidechain/consensus/slots/src/lib.rs @@ -34,7 +34,7 @@ extern crate sgx_tstd as std; use codec::Encode; use derive_more::From; use itp_time_utils::{duration_difference, duration_now}; -use itp_types::OpaqueCall; + use its_consensus_common::{Error as ConsensusError, Proposer}; use its_primitives::traits::{ Block as SidechainBlockTrait, Header as HeaderTrait, ShardIdentifierFor, @@ -55,6 +55,7 @@ mod mocks; #[cfg(test)] mod per_shard_slot_worker_tests; +use itp_types::parentchain::ParentchainCall; #[cfg(feature = "std")] pub use slot_stream::*; pub use slots::*; @@ -68,7 +69,7 @@ pub struct SlotResult { /// /// Any sidechain stf that invokes a parentchain stf must not commit its state change /// before the parentchain effect has been finalized. - pub parentchain_effects: Vec, + pub parentchain_effects: Vec, } /// A worker that should be invoked at every new slot for a specific shard. @@ -167,14 +168,32 @@ pub trait SimpleSlotWorker { /// /// Returns the header of the latest imported block. In case no block was imported with this trigger, /// None is returned. - fn import_parentchain_blocks_until( + fn import_integritee_parentchain_blocks_until( + &self, + last_imported_parentchain_header: &::Hash, + ) -> Result, ConsensusError>; + + fn import_target_a_parentchain_blocks_until( + &self, + last_imported_parentchain_header: &::Hash, + ) -> Result, ConsensusError>; + + fn import_target_b_parentchain_blocks_until( &self, last_imported_parentchain_header: &::Hash, ) -> Result, ConsensusError>; /// Peek the parentchain import queue for the latest block in queue. /// Does not perform the import or mutate the queue. - fn peek_latest_parentchain_header( + fn peek_latest_integritee_parentchain_header( + &self, + ) -> Result, ConsensusError>; + + fn peek_latest_target_a_parentchain_header( + &self, + ) -> Result, ConsensusError>; + + fn peek_latest_target_b_parentchain_header( &self, ) -> Result, ConsensusError>; @@ -190,38 +209,63 @@ pub trait SimpleSlotWorker { shard: ShardIdentifierFor, ) -> Option> { let (_timestamp, slot) = (slot_info.timestamp, slot_info.slot); - let logging_target = self.logging_target(); let remaining_duration = self.proposing_remaining_duration(&slot_info); if remaining_duration == Duration::default() { - debug!( - target: logging_target, - "Skipping proposal slot {} since there's no time left to propose", *slot, - ); + debug!("Skipping proposal slot {} since there's no time left to propose", *slot,); return None } - let latest_parentchain_header = match self.peek_latest_parentchain_header() { - Ok(Some(peeked_header)) => peeked_header, - Ok(None) => slot_info.last_imported_parentchain_head.clone(), - Err(e) => { - warn!( - target: logging_target, - "Failed to peek latest parentchain block header: {:?}", e - ); - return None - }, - }; + let latest_integritee_parentchain_header = + match self.peek_latest_integritee_parentchain_header() { + Ok(Some(peeked_header)) => peeked_header, + Ok(None) => slot_info.last_imported_integritee_parentchain_head.clone(), + Err(e) => { + warn!("Failed to peek latest Integritee parentchain block header: {:?}", e); + return None + }, + }; + trace!( + "on_slot: a priori latest Integritee block number: {:?}", + latest_integritee_parentchain_header.number() + ); + // fixme: we need proper error handling here. we just assume there is no target_a if there is an error here, which is very brittle + let maybe_latest_target_a_parentchain_header = + match self.peek_latest_target_a_parentchain_header() { + Ok(Some(peeked_header)) => Some(peeked_header), + Ok(None) => slot_info.maybe_last_imported_target_a_parentchain_head.clone(), + Err(e) => { + debug!("Failed to peek latest target_a_parentchain block header: {:?}", e); + None + }, + }; + trace!( + "on_slot: a priori latest TargetA block number: {:?}", + maybe_latest_target_a_parentchain_header.clone().map(|h| *h.number()) + ); + + let maybe_latest_target_b_parentchain_header = + match self.peek_latest_target_b_parentchain_header() { + Ok(Some(peeked_header)) => Some(peeked_header), + Ok(None) => slot_info.maybe_last_imported_target_b_parentchain_head.clone(), + Err(e) => { + debug!("Failed to peek latest target_a_parentchain block header: {:?}", e); + None + }, + }; + trace!( + "on_slot: a priori latest TargetB block number: {:?}", + maybe_latest_target_b_parentchain_header.clone().map(|h| *h.number()) + ); - let epoch_data = match self.epoch_data(&latest_parentchain_header, shard, slot) { + let epoch_data = match self.epoch_data(&latest_integritee_parentchain_header, shard, slot) { Ok(epoch_data) => epoch_data, Err(e) => { warn!( - target: logging_target, "Unable to fetch epoch data at block {:?}: {:?}", - latest_parentchain_header.hash(), + latest_integritee_parentchain_header.hash(), e, ); @@ -232,31 +276,79 @@ pub trait SimpleSlotWorker { let authorities_len = self.authorities_len(&epoch_data); if !authorities_len.map(|a| a > 0).unwrap_or(false) { - debug!( - target: logging_target, - "Skipping proposal slot. Authorities len {:?}", authorities_len - ); + debug!("Skipping proposal slot. Authorities len {:?}", authorities_len); } - let _claim = self.claim_slot(&latest_parentchain_header, slot, &epoch_data)?; + let _claim = self.claim_slot(&latest_integritee_parentchain_header, slot, &epoch_data)?; // Import the peeked parentchain header(s). - let last_imported_header = - match self.import_parentchain_blocks_until(&latest_parentchain_header.hash()) { - Ok(h) => h, - Err(e) => { - warn!( - target: logging_target, - "Failed to import and retrieve parentchain block header: {:?}", e - ); - return None - }, + let last_imported_integritee_header = match self.import_integritee_parentchain_blocks_until( + &latest_integritee_parentchain_header.hash(), + ) { + Ok(h) => h, + Err(e) => { + debug!( + "Failed to import Integritee blocks until nr{:?}: {:?}", + latest_integritee_parentchain_header.number(), + e + ); + None + }, + }; + trace!( + "on_slot: a posteriori latest Integritee block number (if there is a new one): {:?}", + last_imported_integritee_header.clone().map(|h| *h.number()) + ); + + let maybe_last_imported_target_a_header = + if let Some(ref header) = maybe_latest_target_a_parentchain_header { + match self.import_target_a_parentchain_blocks_until(&header.hash()) { + Ok(Some(h)) => Some(h), + Ok(None) => None, + Err(e) => { + debug!( + "Failed to import TargetA blocks until nr{:?}: {:?}", + header.number(), + e + ); + None + }, + } + } else { + None + }; + trace!( + "on_slot: a posteriori latest TargetA block number: {:?}", + maybe_last_imported_target_a_header.map(|h| *h.number()) + ); + + let maybe_last_imported_target_b_header = + if let Some(ref header) = maybe_latest_target_b_parentchain_header { + match self.import_target_b_parentchain_blocks_until(&header.hash()) { + Ok(Some(h)) => Some(h), + Ok(None) => None, + Err(e) => { + debug!( + "Failed to import TargetB blocks until nr{:?}: {:?}", + header.number(), + e + ); + None + }, + } + } else { + None }; - let proposer = match self.proposer(latest_parentchain_header.clone(), shard) { + trace!( + "on_slot: a posteriori latest TargetB block number: {:?}", + maybe_last_imported_target_b_header.map(|h| *h.number()) + ); + + let proposer = match self.proposer(latest_integritee_parentchain_header.clone(), shard) { Ok(p) => p, Err(e) => { - warn!(target: logging_target, "Could not create proposer: {:?}", e); + warn!("Could not create proposer: {:?}", e); return None }, }; @@ -264,14 +356,14 @@ pub trait SimpleSlotWorker { let proposing = match proposer.propose(remaining_duration) { Ok(p) => p, Err(e) => { - warn!(target: logging_target, "Could not propose: {:?}", e); + warn!("Could not propose: {:?}", e); return None }, }; if !timestamp_within_slot(&slot_info, &proposing.block) { warn!( - target: logging_target, + "⌛️ Discarding proposal for slot {}, block number {}; block production took too long", *slot, proposing.block.block().header().block_number(), ); @@ -279,17 +371,19 @@ pub trait SimpleSlotWorker { return None } - if last_imported_header.is_some() { + if last_imported_integritee_header.is_some() { println!( - "Syncing Parentchain block number {:?} at Sidechain block number {:?} ", - latest_parentchain_header.number(), + "Syncing Parentchains: Integritee: {:?} TargetA: {:?}, TargetB: {:?}, Sidechain: {:?}", + latest_integritee_parentchain_header.number(), + maybe_latest_target_a_parentchain_header.map(|h| *h.number()), + maybe_latest_target_b_parentchain_header.map(|h| *h.number()), proposing.block.block().header().block_number() ); } - info!("Proposing sidechain block (number: {}, hash: {}) based on parentchain block (number: {:?}, hash: {:?})", + info!("Proposing sidechain block (number: {}, hash: {}) based on integritee parentchain block (number: {:?}, hash: {:?})", proposing.block.block().header().block_number(), proposing.block.hash(), - latest_parentchain_header.number(), latest_parentchain_header.hash() + latest_integritee_parentchain_header.number(), latest_integritee_parentchain_header.hash() ); Some(SlotResult { @@ -325,8 +419,6 @@ impl, shards: Vec, ) -> Self::Output { - let logging_target = SimpleSlotWorker::logging_target(self); - let mut remaining_shards = shards.len(); let mut slot_results = Vec::with_capacity(remaining_shards); @@ -339,10 +431,7 @@ impl slot_results.push(res), + match SimpleSlotWorker::on_slot(self, shard_slot.clone(), shard) { + Some(res) => { + slot_results.push(res); + debug!( + "on_slot: produced block for slot: {:?} in shard {:?}", + shard_slot, shard + ) + }, None => info!( - target: logging_target, - "Did not produce a block for slot {} in shard {:?}", *slot_info.slot, shard + "Did not produce a block for slot {} in shard {:?}", + *slot_info.slot, shard ), } diff --git a/sidechain/consensus/slots/src/mocks.rs b/sidechain/consensus/slots/src/mocks.rs index 6664351160..8f4be9ea4f 100644 --- a/sidechain/consensus/slots/src/mocks.rs +++ b/sidechain/consensus/slots/src/mocks.rs @@ -94,14 +94,36 @@ where todo!() } - fn import_parentchain_blocks_until( + fn import_integritee_parentchain_blocks_until( &self, _last_imported_parentchain_header: &::Hash, ) -> Result> { todo!() } - fn peek_latest_parentchain_header(&self) -> Result> { + fn peek_latest_integritee_parentchain_header(&self) -> Result> { + todo!() + } + + fn import_target_a_parentchain_blocks_until( + &self, + _last_imported_parentchain_header: &::Hash, + ) -> Result> { + todo!() + } + + fn peek_latest_target_a_parentchain_header(&self) -> Result> { + todo!() + } + + fn import_target_b_parentchain_blocks_until( + &self, + _last_imported_parentchain_header: &::Hash, + ) -> Result> { + todo!() + } + + fn peek_latest_target_b_parentchain_header(&self) -> Result> { todo!() } diff --git a/sidechain/consensus/slots/src/per_shard_slot_worker_tests.rs b/sidechain/consensus/slots/src/per_shard_slot_worker_tests.rs index 3f6d212b5f..b4856d767c 100644 --- a/sidechain/consensus/slots/src/per_shard_slot_worker_tests.rs +++ b/sidechain/consensus/slots/src/per_shard_slot_worker_tests.rs @@ -86,5 +86,7 @@ fn slot_info_from_now() -> SlotInfo { SLOT_DURATION, slot_ends_at, ParentchainHeaderBuilder::default().build(), + None, + None, ) } diff --git a/sidechain/consensus/slots/src/slots.rs b/sidechain/consensus/slots/src/slots.rs index fa6564bac2..54dcc23349 100644 --- a/sidechain/consensus/slots/src/slots.rs +++ b/sidechain/consensus/slots/src/slots.rs @@ -64,7 +64,11 @@ pub struct SlotInfo { /// The time at which the slot ends. pub ends_at: Duration, /// Last imported parentchain header, potentially outdated. - pub last_imported_parentchain_head: ParentchainBlock::Header, + pub last_imported_integritee_parentchain_head: ParentchainBlock::Header, + /// Last imported parentchain header, potentially outdated. + pub maybe_last_imported_target_a_parentchain_head: Option, + /// Last imported parentchain header, potentially outdated. + pub maybe_last_imported_target_b_parentchain_head: Option, } impl SlotInfo { @@ -76,14 +80,18 @@ impl SlotInfo { timestamp: Duration, duration: Duration, ends_at: Duration, - parentchain_head: ParentchainBlock::Header, + last_imported_integritee_parentchain_head: ParentchainBlock::Header, + maybe_last_imported_target_a_parentchain_head: Option, + maybe_last_imported_target_b_parentchain_head: Option, ) -> Self { Self { slot, timestamp, duration, ends_at, - last_imported_parentchain_head: parentchain_head, + last_imported_integritee_parentchain_head, + maybe_last_imported_target_a_parentchain_head, + maybe_last_imported_target_b_parentchain_head, } } @@ -99,7 +107,7 @@ impl SlotInfo { /// The time at which the slot ends. /// /// !! Slot duration needs to be the 'global' slot duration that is used for the sidechain. -/// Do not use this with 'custom' slot durations, as used e.g. for the shard slots. +/// Do not use this with 'custom' slot durations, as used e.g. for the shard slots. pub fn slot_ends_at(slot: Slot, slot_duration: Duration) -> Duration { Duration::from_millis(*slot.saturating_add(1u64) * (slot_duration.as_millis() as u64)) } @@ -131,7 +139,9 @@ pub(crate) fn timestamp_within_slot< pub fn yield_next_slot( timestamp: Duration, duration: Duration, - header: ParentchainBlock::Header, + integritee_header: ParentchainBlock::Header, + maybe_target_a_header: Option, + maybe_target_b_header: Option, last_slot_getter: &mut SlotGetter, ) -> Result>, ConsensusError> where @@ -152,7 +162,15 @@ where last_slot_getter.set_last_slot(slot)?; let slot_ends_time = slot_ends_at(slot, duration); - Ok(Some(SlotInfo::new(slot, timestamp, duration, slot_ends_time, header))) + Ok(Some(SlotInfo::new( + slot, + timestamp, + duration, + slot_ends_time, + integritee_header, + maybe_target_a_header, + maybe_target_b_header, + ))) } pub trait LastSlotTrait { @@ -213,7 +231,9 @@ mod tests { timestamp: duration_now(), duration: SLOT_DURATION, ends_at: duration_now() + SLOT_DURATION, - last_imported_parentchain_head: ParentchainHeaderBuilder::default().build(), + last_imported_integritee_parentchain_head: ParentchainHeaderBuilder::default().build(), + maybe_last_imported_target_a_parentchain_head: None, + maybe_last_imported_target_b_parentchain_head: None, } } @@ -252,11 +272,18 @@ mod tests { let slot: Slot = 1000.into(); let slot_end_time = slot_ends_at(slot, SLOT_DURATION); - let slot_one: SlotInfo = - SlotInfo::new(slot, timestamp, SLOT_DURATION, slot_end_time, pc_header.clone()); + let slot_one: SlotInfo = SlotInfo::new( + slot, + timestamp, + SLOT_DURATION, + slot_end_time, + pc_header.clone(), + None, + None, + ); thread::sleep(Duration::from_millis(200)); let slot_two: SlotInfo = - SlotInfo::new(slot, timestamp, SLOT_DURATION, slot_end_time, pc_header); + SlotInfo::new(slot, timestamp, SLOT_DURATION, slot_end_time, pc_header, None, None); let difference_of_ends_at = (slot_one.ends_at.as_millis()).abs_diff(slot_two.ends_at.as_millis()); @@ -276,7 +303,9 @@ mod tests { timestamp: duration_now() - Duration::from_secs(5), duration: SLOT_DURATION, ends_at: duration_now() + SLOT_DURATION - Duration::from_secs(5), - last_imported_parentchain_head: ParentchainHeaderBuilder::default().build(), + last_imported_integritee_parentchain_head: ParentchainHeaderBuilder::default().build(), + maybe_last_imported_target_a_parentchain_head: None, + maybe_last_imported_target_b_parentchain_head: None, }; assert!(slot.duration_remaining().is_none()); } @@ -288,7 +317,9 @@ mod tests { timestamp: duration_now() - Duration::from_secs(5), duration: SLOT_DURATION, ends_at: duration_now() + Duration::from_secs(60), - last_imported_parentchain_head: ParentchainHeaderBuilder::default().build(), + last_imported_integritee_parentchain_head: ParentchainHeaderBuilder::default().build(), + maybe_last_imported_target_a_parentchain_head: None, + maybe_last_imported_target_b_parentchain_head: None, }; let maybe_duration_remaining = slot.duration_remaining(); assert!(maybe_duration_remaining.is_some()); @@ -304,7 +335,7 @@ mod tests { thread::sleep(SLOT_DURATION * 2); let slot: SlotInfo = - SlotInfo::new(slot, timestamp, SLOT_DURATION, slot_end_time, pc_header); + SlotInfo::new(slot, timestamp, SLOT_DURATION, slot_end_time, pc_header, None, None); assert!(slot.ends_at < duration_now()); } @@ -348,6 +379,8 @@ mod tests { duration_now(), SLOT_DURATION, ParentchainHeaderBuilder::default().build(), + None, + None, &mut LastSlot, ) .unwrap() @@ -362,6 +395,8 @@ mod tests { duration_now() + SLOT_DURATION, SLOT_DURATION, ParentchainHeaderBuilder::default().build(), + None, + None, &mut LastSlot ) .unwrap() @@ -375,6 +410,8 @@ mod tests { duration_now(), Default::default(), ParentchainHeaderBuilder::default().build(), + None, + None, &mut LastSlot, ), "Tried to yield next slot with 0 duration", diff --git a/sidechain/primitives/Cargo.toml b/sidechain/primitives/Cargo.toml index 45844541a2..79b2a6efca 100644 --- a/sidechain/primitives/Cargo.toml +++ b/sidechain/primitives/Cargo.toml @@ -10,12 +10,11 @@ edition = "2021" [dependencies] codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive", "full"] } itp-types = { path = "../../core-primitives/types", default-features = false } -scale-info = { version = "2.0.1", default-features = false, features = ["derive"] } +scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } serde = { version = "1.0.13", default-features = false } # substrate dependencies sp-core = { default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } -sp-io = { default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } sp-runtime = { default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } sp-std = { default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } @@ -32,7 +31,6 @@ std = [ "itp-types/std", # substrate "sp-core/std", - "sp-io/std", "sp-runtime/std", "sp-std/std", ] diff --git a/sidechain/rpc-handler/Cargo.toml b/sidechain/rpc-handler/Cargo.toml index 32457c48dd..94bf7f090a 100644 --- a/sidechain/rpc-handler/Cargo.toml +++ b/sidechain/rpc-handler/Cargo.toml @@ -7,7 +7,6 @@ edition = "2021" [dependencies] # sgx dependencies sgx_tstd = { branch = "master", git = "https://github.com/apache/teaclave-sgx-sdk.git", optional = true } -sgx_types = { branch = "master", git = "https://github.com/apache/teaclave-sgx-sdk.git" } # local dependencies itp-rpc = { path = "../../core-primitives/rpc", default-features = false } diff --git a/sidechain/rpc-handler/src/direct_top_pool_api.rs b/sidechain/rpc-handler/src/direct_top_pool_api.rs index d2318b6e03..235158ac9e 100644 --- a/sidechain/rpc-handler/src/direct_top_pool_api.rs +++ b/sidechain/rpc-handler/src/direct_top_pool_api.rs @@ -46,10 +46,9 @@ where TCS: PartialEq + Encode + Decode + Debug + Send + Sync + 'static, G: PartialEq + Encode + Decode + Debug + Send + Sync + 'static, { - // author_submitAndWatchExtrinsic - let author_submit_and_watch_extrinsic_name: &str = "author_submitAndWatchExtrinsic"; let watch_author = top_pool_author.clone(); - io_handler.add_sync_method(author_submit_and_watch_extrinsic_name, move |params: Params| { + io_handler.add_sync_method("author_submitAndWatchExtrinsic", move |params: Params| { + debug!("worker_api_direct rpc was called: author_submitAndWatchExtrinsic"); let json_value = match author_submit_extrinsic_inner(watch_author.clone(), params) { Ok(hash_value) => RpcReturnValue { do_watch: true, @@ -64,10 +63,9 @@ where Ok(json!(json_value)) }); - // author_submitExtrinsic - let author_submit_extrinsic_name: &str = "author_submitExtrinsic"; let submit_author = top_pool_author.clone(); - io_handler.add_sync_method(author_submit_extrinsic_name, move |params: Params| { + io_handler.add_sync_method("author_submitExtrinsic", move |params: Params| { + debug!("worker_api_direct rpc was called: author_submitExtrinsic"); let json_value = match author_submit_extrinsic_inner(submit_author.clone(), params) { Ok(hash_value) => RpcReturnValue { do_watch: false, @@ -82,10 +80,9 @@ where Ok(json!(json_value)) }); - // author_pendingExtrinsics - let author_pending_extrinsic_name: &str = "author_pendingExtrinsics"; let pending_author = top_pool_author.clone(); - io_handler.add_sync_method(author_pending_extrinsic_name, move |params: Params| { + io_handler.add_sync_method("author_pendingExtrinsics", move |params: Params| { + debug!("worker_api_direct rpc was called: author_pendingExtrinsics"); match params.parse::>() { Ok(shards) => { let mut retrieved_operations = vec![]; @@ -116,10 +113,9 @@ where } }); - // author_pendingTrustedCallsFor - let author_pending_trusted_calls_for_name: &str = "author_pendingTrustedCallsFor"; let pending_author = top_pool_author; - io_handler.add_sync_method(author_pending_trusted_calls_for_name, move |params: Params| { + io_handler.add_sync_method("author_pendingTrustedCallsFor", move |params: Params| { + debug!("worker_api_direct rpc was called: author_pendingTrustedCallsFor"); match params.parse::<(String, String)>() { Ok((shard_base58, account_hex)) => { let shard = match decode_shard_from_base58(shard_base58.as_str()) { diff --git a/sidechain/state/Cargo.toml b/sidechain/state/Cargo.toml index 96b1fda3f1..d8d5d5a030 100644 --- a/sidechain/state/Cargo.toml +++ b/sidechain/state/Cargo.toml @@ -8,7 +8,6 @@ edition = "2021" codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive", "chain-error"] } frame-support = { default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } log = { version = "0.4", default-features = false } -serde = { version = "1.0", default-features = false, features = ["alloc", "derive"] } # optional std deps thiserror = { version = "1.0.9", optional = true } @@ -27,7 +26,6 @@ sp-io = { optional = true, default-features = false, features = ["disable_oom", # substrate deps sp-core = { default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } -sp-std = { default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } # test deps [dev-dependencies] @@ -37,9 +35,7 @@ sp-runtime = { default-features = false, git = "https://github.com/paritytech/su default = ["std"] std = [ "log/std", - "serde/std", # substrate - "sp-std/std", "sp-core/std", # local crates "itp-sgx-externalities/std", diff --git a/sidechain/storage/src/storage.rs b/sidechain/storage/src/storage.rs index 92c3f13201..0313abfee8 100644 --- a/sidechain/storage/src/storage.rs +++ b/sidechain/storage/src/storage.rs @@ -216,8 +216,13 @@ impl SidechainStorage { block_number: BlockNumber, ) -> Result<()> { let last_block = self.get_last_block_of_shard(shard)?; + trace!("pruning sidechain blocks older than {} for shard {:?}", block_number, shard); if last_block.number == block_number { // given block number is last block of chain - purge whole shard + info!( + "pruning entire sidechain shard no new blocks after {}, shard: {:?}", + block_number, shard + ); self.purge_shard(shard) } else { // iterate through chain and add all blocks to WriteBatch (delete cmd) diff --git a/sidechain/test/Cargo.toml b/sidechain/test/Cargo.toml index 002349141f..b25bae25b7 100644 --- a/sidechain/test/Cargo.toml +++ b/sidechain/test/Cargo.toml @@ -8,7 +8,6 @@ license = "Apache-2.0" edition = "2021" [dependencies] -codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false } # sgx dependencies sgx_tstd = { branch = "master", git = "https://github.com/apache/teaclave-sgx-sdk.git", features = ["untrusted_time"], optional = true } @@ -23,7 +22,6 @@ its-primitives = { path = "../primitives", default_features = false, features = [features] default = ["std"] std = [ - "codec/std", "itp-types/std", "its-primitives/std", # substrate diff --git a/sidechain/validateer-fetch/Cargo.toml b/sidechain/validateer-fetch/Cargo.toml index 01988d59ce..e39a8076b0 100644 --- a/sidechain/validateer-fetch/Cargo.toml +++ b/sidechain/validateer-fetch/Cargo.toml @@ -8,10 +8,8 @@ edition = "2021" codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive", "chain-error"] } derive_more = "0.99.16" log = "0.4" -thiserror = "1.0.26" # substrate deps -frame-support = { default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } sp-core = { default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } sp-runtime = { default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } sp-std = { default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } @@ -19,8 +17,6 @@ sp-std = { default-features = false, git = "https://github.com/paritytech/substr # local deps itp-enclave-bridge-storage = { path = "../../core-primitives/enclave-bridge-storage", default-features = false } itp-ocall-api = { path = "../../core-primitives/ocall-api", default-features = false } -itp-storage = { path = "../../core-primitives/storage", default-features = false } -itp-teerex-storage = { path = "../../core-primitives/teerex-storage", default-features = false } itp-types = { path = "../../core-primitives/types", default-features = false } its-primitives = { path = "../primitives", default-features = false } @@ -32,7 +28,6 @@ std = [ "sp-runtime/std", "sp-std/std", "itp-types/std", - "itp-storage/std", "itp-ocall-api/std", "its-primitives/std", "itp-enclave-bridge-storage/std",