├── .cargo └── zepter.yaml ├── .github └── workflows │ └── ci.yml ├── .gitignore ├── .taplo.toml ├── Cargo.lock ├── Cargo.toml ├── LICENSE ├── README.md ├── about.hbs ├── about.toml ├── asset-registry ├── Cargo.toml ├── README.md └── src │ ├── benchmarking.rs │ ├── lib.rs │ ├── mock.rs │ ├── tests.rs │ └── weights.rs ├── claims ├── Cargo.toml └── src │ └── lib.rs ├── enclave-bridge ├── Cargo.toml ├── LICENSE ├── README.md └── src │ ├── benchmarking.rs │ ├── lib.rs │ ├── mock.rs │ ├── tests │ ├── mod.rs │ ├── test_indirect_invocation.rs │ ├── test_publish_hash.rs │ ├── test_shard_config.rs │ └── test_shard_status.rs │ └── weights.rs ├── primitives ├── claims │ ├── Cargo.toml │ └── src │ │ └── lib.rs ├── common │ ├── Cargo.toml │ └── src │ │ └── lib.rs ├── enclave-bridge │ ├── Cargo.toml │ └── src │ │ └── lib.rs ├── sidechain │ ├── Cargo.toml │ └── src │ │ └── lib.rs ├── teeracle │ ├── Cargo.toml │ └── src │ │ └── lib.rs ├── teerdays │ ├── Cargo.toml │ └── src │ │ └── lib.rs ├── teerex │ ├── Cargo.toml │ └── src │ │ └── lib.rs ├── xcm-transactor │ ├── Cargo.toml │ └── src │ │ └── lib.rs └── xcm │ ├── Cargo.toml │ └── src │ └── lib.rs ├── rust-toolchain.toml ├── rustfmt.toml ├── scripts └── run_for_all_no_std_crates.sh ├── sidechain ├── Cargo.toml ├── LICENSE ├── README.md └── src │ ├── benchmarking.rs │ ├── lib.rs │ ├── mock.rs │ ├── tests.rs │ └── weights.rs ├── teeracle ├── Cargo.toml ├── README.md └── src │ ├── benchmarking.rs │ ├── lib.rs │ ├── mock.rs │ ├── tests.rs │ └── weights.rs ├── teerdays ├── Cargo.toml └── src │ ├── benchmarking.rs │ ├── lib.rs │ ├── mock.rs │ ├── tests.rs │ └── weights.rs ├── teerex ├── Cargo.toml ├── LICENSE ├── README.md ├── scripts │ ├── benchmark_teerex_full_info.sh │ └── frame-weight-template-full-info.hbs ├── sgx-verify │ ├── AttestationReportSigningCACert.pem │ ├── Cargo.toml │ ├── fuzz │ │ ├── Cargo.lock │ │ ├── Cargo.toml │ │ └── fuzz_targets │ │ │ ├── decode_quote.rs │ │ │ ├── deserialize_json.rs │ │ │ ├── extract_tcb_info.rs │ │ │ ├── signature_check.rs │ │ │ └── verify_ias_report.rs │ ├── src │ │ ├── collateral.rs │ │ ├── ephemeral_key.rs │ │ ├── lib.rs │ │ ├── netscape_comment.rs │ │ ├── test_data.rs │ │ ├── tests.rs │ │ └── utils.rs │ └── test-data │ │ ├── dcap │ │ ├── dcap_quote_cert.der │ │ ├── pck_crl.der │ │ ├── pck_crl_issuer_chain.pem │ │ ├── qe_identity.json │ │ ├── qe_identity_cert.pem │ │ ├── qe_identity_issuer_chain.pem │ │ ├── root_ca_crl.der │ │ ├── tcb_info.json │ │ ├── tcb_info_issuer_chain.pem │ │ ├── test2_dcap_quote.hex │ │ └── test2_tcb_info.json │ │ ├── enclave-signing-pubkey-TEST4.bin │ │ ├── enclave-signing-pubkey-TEST5.bin │ │ ├── enclave-signing-pubkey-TEST6.bin │ │ ├── enclave-signing-pubkey-TEST7.bin │ │ ├── enclave-signing-pubkey-TEST8-PRODUCTION.bin │ │ ├── ra_dcap_dump_quote.ra │ │ ├── ra_dump_cert_TEST4.der │ │ ├── ra_dump_cert_TEST5.der │ │ ├── ra_dump_cert_TEST6.der │ │ ├── ra_dump_cert_TEST7.der │ │ └── ra_dump_cert_TEST8_PRODUCTION.der └── src │ ├── benchmarking.rs │ ├── lib.rs │ ├── migrations.rs │ ├── mock.rs │ ├── test_helpers.rs │ ├── tests │ ├── mod.rs │ └── test_cases.rs │ └── weights.rs ├── test-utils ├── Cargo.toml └── src │ └── lib.rs └── xcm-transactor ├── Cargo.toml └── src ├── lib.rs ├── mock.rs └── tests.rs /.cargo/zepter.yaml: -------------------------------------------------------------------------------- 1 | version: 2 | format: 1 3 | # Minimum version of the binary that is expected to work. This is just for printing a nice error 4 | # message when someone tries to use an older version. 5 | binary: 0.13.2 6 | 7 | # The examples in this file assume crate `A` to have a dependency on crate `B`. 8 | workflows: 9 | check: 10 | - [ 11 | 'lint', 12 | # Check that `A` activates the features of `B`. 13 | 'propagate-feature', 14 | # These are the features to check: 15 | '--features=try-runtime,runtime-benchmarks,std', 16 | # Do not try to add a new section into `[features]` of `A` only because `B` expose that feature. There are edge-cases where this is still needed, but we can add them manually. 17 | '--left-side-feature-missing=ignore', 18 | # Ignore the case that `A` it outside of the workspace. Otherwise it will report errors in external dependencies that we have no influence on. 19 | '--left-side-outside-workspace=ignore', 20 | # Some features imply that they activate a specific dependency as non-optional. Otherwise the default behaviour with a `?` is used. 21 | '--feature-enables-dep=try-runtime:frame-try-runtime,runtime-benchmarks:frame-benchmarking', 22 | # Auxillary flags: 23 | '--offline', 24 | '--locked', 25 | '--show-path', 26 | '--quiet', 27 | ] 28 | # Same as `check`, but with the `--fix` flag. 29 | default: 30 | - [ $check.0, '--fix' ] 31 | 32 | # Will be displayed when any workflow fails: 33 | help: 34 | text: | 35 | This repo uses the Zepter CLI to detect abnormalities in the feature configuration. 36 | It looks like one more more checks failed; please check the console output. You can try to automatically address them by running `zepter`. 37 | Otherwise please ask directly in the Merge Request, GitHub Discussions or on Matrix Chat, thank you. 38 | links: 39 | - "https://github.com/ggwpez/zepter" 40 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: Build and Test 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | - 'sdk-v[0-9]+.[0-9]+.[0-9]+-*' 8 | - 'polkadot-v[0-9]+.[0-9]+.[0-9]+-*' 9 | tags: 10 | - '[0-9]+.[0-9]+.[0-9]+' 11 | pull_request: 12 | branches: 13 | - master 14 | - 'sdk-v[0-9]+.[0-9]+.[0-9]+-*' 15 | - 'polkadot-v[0-9]+.[0-9]+.[0-9]+-*' 16 | 17 | env: 18 | CARGO_TERM_COLOR: always 19 | 20 | # Cancel a currently running workflow from the same PR, branch or tag when a new workflow is 21 | # triggered (ref https://stackoverflow.com/a/72408109) 22 | concurrency: 23 | group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} 24 | cancel-in-progress: true 25 | 26 | jobs: 27 | check: 28 | name: Rust check ${{ matrix.check }} 29 | runs-on: ${{ matrix.os }} 30 | strategy: 31 | matrix: 32 | os: [ ubuntu-latest ] 33 | check: [ cargo build --release, 34 | cargo build --release --features dot, 35 | cargo build --release --features ksm, 36 | cargo test --all --features runtime-benchmarks, 37 | cargo test --all --features dot, 38 | cargo test --all --features ksm, 39 | cargo +nightly fmt --all -- --check, 40 | cargo clippy --all-features --all-targets -- -D warnings 41 | ] 42 | steps: 43 | - uses: actions/checkout@v3 44 | 45 | - name: Install nightly toolchain 46 | run: rustup toolchain install nightly --profile minimal --component rustfmt 47 | 48 | # With rustup's nice new toml format, we just need to run rustup show to install the toolchain 49 | # https://github.com/actions-rs/toolchain/issues/126#issuecomment-782989659 50 | - name: Setup Rust toolchain 51 | run: rustup show 52 | 53 | - uses: Swatinem/rust-cache@v2 54 | with: 55 | key: ${{ matrix.rust-target }}-${{ matrix.check }} 56 | 57 | - name: ${{ matrix.check }} 58 | run: ${{ matrix.check }} 59 | 60 | license-check: 61 | runs-on: ubuntu-latest 62 | steps: 63 | - uses: actions/checkout@v3 64 | 65 | - name: Install cargo-about 66 | uses: baptiste0928/cargo-install@v2 67 | with: 68 | crate: cargo-about 69 | version: "0.6.6" 70 | 71 | - name: Run license check 72 | # Explicitly use stable because otherwise cargo will trigger a download of 73 | # the nightly version specified in rust-toolchain.toml 74 | run: cargo +stable about generate about.hbs > license.html 75 | 76 | - name: Archive license file 77 | uses: actions/upload-artifact@v4 78 | with: 79 | name: license 80 | path: license.html 81 | 82 | cargo-zepter: 83 | name: Cargo Zepter 84 | runs-on: ubuntu-latest 85 | 86 | steps: 87 | - name: Install stable Rust 88 | uses: actions-rs/toolchain@v1 89 | with: 90 | profile: minimal 91 | toolchain: stable 92 | 93 | - name: Install Zepter 94 | run: cargo install --locked -q zepter && zepter --version 95 | 96 | - name: Checkout 97 | uses: actions/checkout@v4 98 | with: 99 | fetch-depth: 0 # Don't clone historic commits. 100 | 101 | - name: Check features 102 | run: zepter run check 103 | 104 | cargo-toml-fmt: 105 | runs-on: ubuntu-latest 106 | container: "tamasfe/taplo:0.7.0-alpine" 107 | steps: 108 | - uses: actions/checkout@v3 109 | 110 | - name: Run Taplo fmt 111 | run: taplo fmt --check 112 | 113 | - name: Fail-fast; cancel other jobs 114 | if: failure() 115 | uses: andymckay/cancel-action@0.2 116 | 117 | check-wasm: 118 | if: ${{ !startsWith(github.head_ref, 'release/') }} 119 | name: Check wasm build 120 | runs-on: ubuntu-latest 121 | continue-on-error: false 122 | steps: 123 | - uses: actions/checkout@v3 124 | - run: sudo apt-get install -y protobuf-compiler 125 | - uses: Swatinem/rust-cache@v2 126 | with: 127 | key: check-debug-cache 128 | - run: ./scripts/run_for_all_no_std_crates.sh check --no-default-features --target=wasm32-unknown-unknown 129 | 130 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Generated by Cargo 2 | # will have compiled files and executables 3 | /target/ 4 | 5 | # These are backup files generated by rustfmt 6 | **/*.rs.bk 7 | 8 | /.idea/* 9 | -------------------------------------------------------------------------------- /.taplo.toml: -------------------------------------------------------------------------------- 1 | include = ["**/Cargo.toml"] 2 | 3 | [formatting] 4 | array_auto_expand = false 5 | array_auto_collapse = false 6 | indent_string = " " 7 | inline_table_expand = false 8 | 9 | [[rule]] 10 | include = ["**/Cargo.toml"] 11 | keys = ["dependencies", "target", "patch"] 12 | 13 | [rule.formatting] 14 | reorder_keys = true 15 | 16 | [[rule]] 17 | include = ["**/Cargo.toml"] 18 | keys = ["features"] 19 | 20 | [rule.formatting] 21 | array_auto_expand = true -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [workspace] 2 | resolver = "2" 3 | members = [ 4 | "asset-registry", 5 | "claims", 6 | "enclave-bridge", 7 | "primitives/claims", 8 | "primitives/common", 9 | "primitives/enclave-bridge", 10 | "primitives/teeracle", 11 | "primitives/teerdays", 12 | "primitives/teerex", 13 | "primitives/xcm", 14 | "primitives/xcm-transactor", 15 | "sidechain", 16 | "teeracle", 17 | "teerdays", 18 | "teerex", 19 | "teerex/sgx-verify", 20 | "test-utils", 21 | "xcm-transactor", 22 | ] 23 | 24 | [workspace.lints.clippy] 25 | manual_inspect = { level = "allow", priority = 2 } # Needs substrate fix in `#[pallet]` 26 | multiple_bound_locations = { level = "allow", priority = 2 } # Needs substrate fix in `#[benchmark]` 27 | 28 | [workspace.dependencies] 29 | base64 = { version = "0.13.1", default-features = false, features = ["alloc"] } 30 | chrono = { version = "0.4.31", default-features = false, features = ["serde"] } 31 | derive_more = "0.99.16" 32 | env_logger = "0.9.0" 33 | hex = { version = "0.4.3", default-features = false, features = ["alloc"] } 34 | hex-literal = "0.4.1" 35 | log = { version = "0.4.20", default-features = false } 36 | rustc-hex = { version = "2.1.0", default-features = false } 37 | serde = { version = "1.0.195", default-features = false, features = ["alloc", "derive"] } 38 | serde_derive = { version = "1.0.195" } 39 | serde_json = { version = "1.0.111", default-features = false } 40 | 41 | # crypto [no_std] 42 | der = { version = "0.6.0", default-features = false } 43 | libsecp256k1 = { version = "0.7.0", default-features = false } 44 | ring = { version = "0.16.20", default-features = false, features = ["alloc"] } 45 | webpki = { version = "=0.102.0-alpha.3", default-features = false, features = ["alloc", "ring"], git = "https://github.com/rustls/webpki", rev = "da923ed", package = "rustls-webpki" } 46 | x509-cert = { version = "0.1.0", default-features = false, features = ["alloc"] } 47 | 48 | # polkadot-sdk and ecosystem crates [no_std] 49 | cumulus-pallet-dmp-queue = { version = "0.20.0", default-features = false } 50 | cumulus-pallet-xcmp-queue = { version = "0.20.0", default-features = false } 51 | cumulus-primitives-core = { version = "0.18.1", default-features = false } 52 | frame-benchmarking = { version = "40.2.0", default-features = false } 53 | frame-support = { version = "40.1.0", default-features = false } 54 | frame-system = { version = "40.1.0", default-features = false } 55 | pallet-assets = { version = "42.0.0", default-features = false } 56 | pallet-aura = { version = "39.0.0", default-features = false } 57 | pallet-balances = { version = "41.1.0", default-features = false } 58 | pallet-timestamp = { version = "39.0.0", default-features = false } 59 | pallet-vesting = { version = "40.1.0", default-features = false } 60 | pallet-xcm = { version = "19.1.2", default-features = false } 61 | parachains-common = { version = "21.0.0", default-features = false } 62 | parity-scale-codec = { version = "3.6.5", default-features = false, features = ["derive"] } 63 | polkadot-core-primitives = { version = "17.1.0", default-features = false } 64 | polkadot-parachain-primitives = { version = "16.1.0", default-features = false } 65 | scale-info = { version = "2.10.0", default-features = false, features = ["derive", "serde"] } 66 | sp-core = { version = "36.1.0", default-features = false } 67 | sp-io = { version = "40.0.1", default-features = false } 68 | sp-runtime = { version = "41.1.0", default-features = false } 69 | sp-std = { version = "14.0.0", default-features = false } 70 | staging-parachain-info = { version = "0.20.0", default-features = false } 71 | staging-xcm = { version = "16.2.0", default-features = false } 72 | staging-xcm-builder = { version = "20.1.1", default-features = false } 73 | staging-xcm-executor = { version = "19.1.2", default-features = false } 74 | substrate-fixed = { version = "0.6.0", default-features = false } 75 | 76 | # dev-deps [std] 77 | sp-keyring = { version = "41.0.0", default-features = false } 78 | sp-externalities = { version = "0.30.0", default-features = false } 79 | sp-consensus-aura = { version = "0.42.0", default-features = false } 80 | polkadot-runtime-parachains = { version = "19.1.0" } 81 | xcm-simulator = { version = "20.1.0" } 82 | 83 | [patch.crates-io] 84 | ring = { git = "https://github.com/betrusted-io/ring-xous", branch = "0.16.20-cleanup" } 85 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # pallets 2 | 3 | This repository contains all custom pallets used by the integritee netowork, a parachain to Polkadot and Kusama 4 | 5 | ## Licensing 6 | 7 | Please note that while all pallets utilized in the Integritee network are open-sourced, 8 | it is important to be aware that certain pallets are licensed under MS-RSL (Microsoft Reference Source License) 9 | solely for reference purposes. 10 | If you are interested in using these pallets in chains other than the Integritee network, 11 | we kindly request you to [contact us](hello@integritee.network) to inquire about the conditions for licensing. 12 | -------------------------------------------------------------------------------- /about.hbs: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 36 | 37 | 38 | 39 |
40 |
41 |

Third Party Licenses

42 |

This page lists the licenses of the projects used in 'Integritee Networks Pallets' repository.

43 |
44 | 45 |

Overview of licenses:

46 | 51 | 52 |

All license text:

53 | 67 |
68 | 69 | 70 | 71 | -------------------------------------------------------------------------------- /about.toml: -------------------------------------------------------------------------------- 1 | accepted = [ 2 | "Apache-2.0", 3 | "Apache-2.0 WITH LLVM-exception", 4 | "MIT", 5 | "BSD-2-Clause", 6 | "CC0-1.0", 7 | "BSD-3-Clause", 8 | "MPL-2.0", 9 | "ISC", 10 | "Zlib", 11 | "OpenSSL", 12 | "Unicode-DFS-2016", 13 | # The xcm-transactor needs this because of the polkadot dependencies. 14 | "GPL-3.0" 15 | ] 16 | ignore-dev-dependencies = true 17 | ignore-build-dependencies = true 18 | workarounds = [ 19 | "ring", 20 | ] 21 | -------------------------------------------------------------------------------- /asset-registry/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "pallet-asset-registry" 3 | version = "0.0.1" 4 | description = "pallet for XCM Asset Registry." 5 | authors = ["Parity Technologies "] 6 | license = "Apache-2.0" 7 | edition = "2021" 8 | 9 | [package.metadata.docs.rs] 10 | targets = ["x86_64-unknown-linux-gnu"] 11 | 12 | [dependencies] 13 | frame-benchmarking = { workspace = true } 14 | frame-support = { workspace = true } 15 | frame-system = { workspace = true } 16 | pallet-assets = { workspace = true } 17 | pallet-balances = { workspace = true } 18 | parity-scale-codec = { workspace = true, features = ["derive"] } 19 | scale-info = { workspace = true } 20 | sp-runtime = { workspace = true } 21 | sp-std = { workspace = true } 22 | staging-xcm = { workspace = true } 23 | xcm-primitives = { path = "../primitives/xcm", default-features = false } 24 | 25 | [dev-dependencies] 26 | cumulus-pallet-dmp-queue = { workspace = true } 27 | cumulus-pallet-xcmp-queue = { workspace = true } 28 | cumulus-primitives-core = { workspace = true } 29 | pallet-xcm = { workspace = true } 30 | parachains-common = { workspace = true } 31 | polkadot-core-primitives = { workspace = true } 32 | polkadot-parachain-primitives = { workspace = true } 33 | polkadot-runtime-parachains = { workspace = true } 34 | sp-core = { workspace = true } 35 | sp-io = { workspace = true } 36 | sp-runtime = { workspace = true } 37 | staging-parachain-info = { workspace = true } 38 | staging-xcm = { workspace = true } 39 | staging-xcm-builder = { workspace = true } 40 | staging-xcm-executor = { workspace = true } 41 | 42 | [lints] 43 | workspace = true 44 | 45 | [features] 46 | default = ["std"] 47 | std = [ 48 | "cumulus-pallet-dmp-queue/std", 49 | "cumulus-pallet-xcmp-queue/std", 50 | "cumulus-primitives-core/std", 51 | "frame-benchmarking/std", 52 | "frame-support/std", 53 | "frame-system/std", 54 | "pallet-assets/std", 55 | "pallet-balances/std", 56 | "pallet-xcm/std", 57 | "parachains-common/std", 58 | "parity-scale-codec/std", 59 | "polkadot-core-primitives/std", 60 | "polkadot-parachain-primitives/std", 61 | "polkadot-runtime-parachains/std", 62 | "scale-info/std", 63 | "sp-runtime/std", 64 | "sp-std/std", 65 | "staging-parachain-info/std", 66 | "staging-xcm-builder/std", 67 | "staging-xcm-executor/std", 68 | "staging-xcm/std", 69 | "xcm-primitives/std", 70 | "sp-core/std", 71 | "sp-io/std", 72 | ] 73 | runtime-benchmarks = [ 74 | "frame-benchmarking/runtime-benchmarks", 75 | "pallet-assets/runtime-benchmarks", 76 | "pallet-xcm/runtime-benchmarks", 77 | "staging-xcm-builder/runtime-benchmarks", 78 | "cumulus-pallet-dmp-queue/runtime-benchmarks", 79 | "cumulus-pallet-xcmp-queue/runtime-benchmarks", 80 | "cumulus-primitives-core/runtime-benchmarks", 81 | "frame-support/runtime-benchmarks", 82 | "frame-system/runtime-benchmarks", 83 | "pallet-balances/runtime-benchmarks", 84 | "parachains-common/runtime-benchmarks", 85 | "polkadot-parachain-primitives/runtime-benchmarks", 86 | "polkadot-runtime-parachains/runtime-benchmarks", 87 | "sp-runtime/runtime-benchmarks", 88 | "staging-xcm-executor/runtime-benchmarks", 89 | "staging-xcm/runtime-benchmarks", 90 | ] 91 | try-runtime = [ 92 | "frame-support/try-runtime", 93 | "cumulus-pallet-dmp-queue/try-runtime", 94 | "cumulus-pallet-xcmp-queue/try-runtime", 95 | "frame-system/try-runtime", 96 | "pallet-assets/try-runtime", 97 | "pallet-balances/try-runtime", 98 | "pallet-xcm/try-runtime", 99 | "polkadot-runtime-parachains/try-runtime", 100 | "sp-runtime/try-runtime", 101 | "staging-parachain-info/try-runtime", 102 | ] 103 | -------------------------------------------------------------------------------- /asset-registry/src/benchmarking.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Trappist. 2 | // Copyright (C) Parity Technologies (UK) Ltd. 3 | // SPDX-License-Identifier: Apache-2.0 4 | 5 | // Licensed under the Apache License, Version 2.0 (the "License"); 6 | // you may not use this file except in compliance with the License. 7 | // You may obtain a copy of the License at 8 | // 9 | // http://www.apache.org/licenses/LICENSE-2.0 10 | // 11 | // Unless required by applicable law or agreed to in writing, software 12 | // distributed under the License is distributed on an "AS IS" BASIS, 13 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | // See the License for the specific language governing permissions and 15 | // limitations under the License. 16 | 17 | //! Benchmarking setup for pallet-asset-registry 18 | use super::*; 19 | 20 | #[allow(unused)] 21 | use crate::Pallet as AssetRegistry; 22 | use frame_benchmarking::benchmarks; 23 | use frame_support::assert_ok; 24 | use frame_system::RawOrigin; 25 | use staging_xcm::opaque::latest::{ 26 | Junction::{GeneralIndex, PalletInstance, Parachain}, 27 | Location, 28 | }; 29 | 30 | benchmarks! { 31 | register_reserve_asset { 32 | let asset_id = T::BenchmarkHelper::get_registered_asset(); 33 | let asset_location = Location { 34 | parents: 1, 35 | interior: [Parachain(Default::default()), PalletInstance(Default::default()), GeneralIndex(Default::default())].into() 36 | }; 37 | }: _(RawOrigin::Root, asset_id.clone(), asset_location.clone()) 38 | verify { 39 | assert_eq!(AssetIdLocation::::get(asset_id), Some(asset_location)); 40 | } 41 | 42 | unregister_reserve_asset { 43 | let asset_id = T::BenchmarkHelper::get_registered_asset(); 44 | let asset_location = Location { 45 | parents: 1, 46 | interior: [Parachain(Default::default()), PalletInstance(Default::default()), GeneralIndex(Default::default())].into() 47 | }; 48 | assert_ok!(AssetRegistry::::register_reserve_asset(RawOrigin::Root.into(), asset_id.clone(), asset_location)); 49 | assert!(AssetIdLocation::::contains_key(asset_id.clone())); 50 | }: _(RawOrigin::Root, asset_id.clone()) 51 | verify { 52 | assert_eq!(AssetIdLocation::::get(asset_id), None); 53 | } 54 | 55 | impl_benchmark_test_suite!(AssetRegistry, crate::mock::new_test_ext(), crate::mock::Test); 56 | } 57 | -------------------------------------------------------------------------------- /asset-registry/src/mock.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Trappist. 2 | 3 | // Copyright (C) Parity Technologies (UK) Ltd. 4 | // SPDX-License-Identifier: Apache-2.0 5 | 6 | // Licensed under the Apache License, Version 2.0 (the "License"); 7 | // you may not use this file except in compliance with the License. 8 | // You may obtain a copy of the License at 9 | // 10 | // http://www.apache.org/licenses/LICENSE-2.0 11 | // 12 | // Unless required by applicable law or agreed to in writing, software 13 | // distributed under the License is distributed on an "AS IS" BASIS, 14 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | // See the License for the specific language governing permissions and 16 | // limitations under the License. 17 | 18 | use crate as pallet_asset_registry; 19 | use frame_support::{ 20 | derive_impl, 21 | traits::{AsEnsureOriginWithArg, ConstU16, ConstU64}, 22 | }; 23 | use frame_system as system; 24 | use sp_core::H256; 25 | use sp_runtime::{ 26 | traits::{BlakeTwo256, ConstU32, IdentityLookup}, 27 | BuildStorage, 28 | }; 29 | 30 | type Block = frame_system::mocking::MockBlock; 31 | 32 | frame_support::parameter_types! { 33 | pub const StatemineParaIdInfo: u32 = 1000u32; 34 | pub const StatemineAssetsInstanceInfo: u8 = 50u8; 35 | pub const StatemineAssetIdInfo: u128 = 1u128; 36 | } 37 | 38 | // Configure a mock runtime to test the pallet. 39 | frame_support::construct_runtime!( 40 | pub struct Test { 41 | System: frame_system, 42 | AssetRegistry: pallet_asset_registry::{Pallet, Call, Storage, Event}, 43 | Assets: pallet_assets::{Pallet, Call, Storage, Event}, 44 | Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, 45 | } 46 | ); 47 | 48 | #[derive_impl(frame_system::config_preludes::SolochainDefaultConfig as frame_system::DefaultConfig)] 49 | impl system::Config for Test { 50 | type RuntimeEvent = RuntimeEvent; 51 | type BaseCallFilter = frame_support::traits::Everything; 52 | type BlockWeights = (); 53 | type BlockLength = (); 54 | type RuntimeOrigin = RuntimeOrigin; 55 | type RuntimeCall = RuntimeCall; 56 | type RuntimeTask = RuntimeTask; 57 | type Nonce = u64; 58 | type Hash = H256; 59 | type Hashing = BlakeTwo256; 60 | type AccountId = u64; 61 | type Lookup = IdentityLookup; 62 | type Block = Block; 63 | type BlockHashCount = ConstU64<250>; 64 | type DbWeight = (); 65 | type Version = (); 66 | type PalletInfo = PalletInfo; 67 | type AccountData = pallet_balances::AccountData; 68 | type OnNewAccount = (); 69 | type OnKilledAccount = (); 70 | type SystemWeightInfo = (); 71 | type SS58Prefix = ConstU16<42>; 72 | type OnSetCode = (); 73 | type MaxConsumers = ConstU32<16>; 74 | } 75 | 76 | #[cfg(feature = "runtime-benchmarks")] 77 | pub struct MockAssetRegistryBenchmarkHelper; 78 | #[cfg(feature = "runtime-benchmarks")] 79 | impl pallet_asset_registry::BenchmarkHelper for MockAssetRegistryBenchmarkHelper { 80 | fn get_registered_asset() -> u32 { 81 | LOCAL_ASSET_ID 82 | } 83 | } 84 | 85 | impl pallet_asset_registry::Config for Test { 86 | type RuntimeEvent = RuntimeEvent; 87 | type ReserveAssetModifierOrigin = frame_system::EnsureRoot; 88 | type Assets = Assets; 89 | type WeightInfo = pallet_asset_registry::weights::SubstrateWeight; 90 | #[cfg(feature = "runtime-benchmarks")] 91 | type BenchmarkHelper = MockAssetRegistryBenchmarkHelper; 92 | } 93 | 94 | impl pallet_balances::Config for Test { 95 | type RuntimeEvent = RuntimeEvent; 96 | type WeightInfo = (); 97 | type Balance = u64; 98 | type DustRemoval = (); 99 | type ExistentialDeposit = ConstU64<1>; 100 | type AccountStore = System; 101 | type ReserveIdentifier = [u8; 8]; 102 | type RuntimeHoldReason = (); 103 | type FreezeIdentifier = (); 104 | type RuntimeFreezeReason = (); 105 | type MaxLocks = (); 106 | type MaxReserves = (); 107 | type MaxFreezes = ConstU32<0>; 108 | type DoneSlashHandler = (); 109 | } 110 | 111 | impl pallet_assets::Config for Test { 112 | type RuntimeEvent = RuntimeEvent; 113 | type Balance = u64; 114 | type RemoveItemsLimit = ConstU32<5>; 115 | type AssetId = u32; 116 | type AssetIdParameter = u32; 117 | type Currency = Balances; 118 | type CreateOrigin = AsEnsureOriginWithArg>; 119 | type ForceOrigin = frame_system::EnsureRoot; 120 | type AssetDeposit = ConstU64<1>; 121 | type AssetAccountDeposit = ConstU64<10>; 122 | type MetadataDepositBase = ConstU64<1>; 123 | type MetadataDepositPerByte = ConstU64<1>; 124 | type ApprovalDeposit = ConstU64<1>; 125 | type StringLimit = ConstU32<50>; 126 | type Freezer = (); 127 | type Holder = (); 128 | type Extra = (); 129 | type CallbackHandle = (); 130 | type WeightInfo = (); 131 | #[cfg(feature = "runtime-benchmarks")] 132 | type BenchmarkHelper = (); 133 | } 134 | 135 | pub const LOCAL_ASSET_ID: u32 = 10; 136 | 137 | // Build genesis storage according to the mock runtime. 138 | pub fn new_test_ext() -> sp_io::TestExternalities { 139 | let mut storage = system::GenesisConfig::::default().build_storage().unwrap(); 140 | 141 | let config: pallet_assets::GenesisConfig = pallet_assets::GenesisConfig { 142 | assets: vec![ 143 | // id, owner, is_sufficient, min_balance 144 | (LOCAL_ASSET_ID, 0, true, 1), 145 | ], 146 | metadata: vec![ 147 | // id, name, symbol, decimals 148 | (LOCAL_ASSET_ID, "Token Name".into(), "TOKEN".into(), 10), 149 | ], 150 | accounts: vec![ 151 | // id, account_id, balance 152 | (LOCAL_ASSET_ID, 1, 100), 153 | ], 154 | next_asset_id: Some(1), 155 | }; 156 | config.assimilate_storage(&mut storage).unwrap(); 157 | storage.into() 158 | } 159 | -------------------------------------------------------------------------------- /asset-registry/src/weights.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Trappist. 2 | 3 | // Copyright (C) Parity Technologies (UK) Ltd. 4 | // SPDX-License-Identifier: Apache-2.0 5 | 6 | // Licensed under the Apache License, Version 2.0 (the "License"); 7 | // you may not use this file except in compliance with the License. 8 | // You may obtain a copy of the License at 9 | // 10 | // http://www.apache.org/licenses/LICENSE-2.0 11 | // 12 | // Unless required by applicable law or agreed to in writing, software 13 | // distributed under the License is distributed on an "AS IS" BASIS, 14 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | // See the License for the specific language governing permissions and 16 | // limitations under the License. 17 | 18 | //! Autogenerated weights for `pallet_asset_registry` 19 | //! 20 | //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev 21 | //! DATE: 2023-05-18, STEPS: `20`, REPEAT: `10`, LOW RANGE: `[]`, HIGH RANGE: `[]` 22 | //! WORST CASE MAP SIZE: `1000000` 23 | //! HOSTNAME: `vale`, CPU: `11th Gen Intel(R) Core(TM) i7-1165G7 @ 2.80GHz` 24 | //! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 1024 25 | 26 | // Executed Command: 27 | // ./target/release/trappist-collator 28 | // benchmark 29 | // pallet 30 | // --chain 31 | // dev 32 | // --pallet 33 | // pallet_asset_registry 34 | // --execution=wasm 35 | // --wasm-execution=compiled 36 | // --extrinsic 37 | // * 38 | // --steps 39 | // 20 40 | // --repeat 41 | // 10 42 | // --output 43 | // pallets/asset-registry/src/weights.rs 44 | 45 | #![cfg_attr(rustfmt, rustfmt_skip)] 46 | #![allow(unused_parens)] 47 | #![allow(unused_imports)] 48 | 49 | use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; 50 | use sp_std::marker::PhantomData; 51 | 52 | pub trait WeightInfo { 53 | fn register_reserve_asset() -> Weight; 54 | fn unregister_reserve_asset() -> Weight; 55 | } 56 | 57 | /// Weight functions for `pallet_asset_registry`. 58 | pub struct SubstrateWeight(PhantomData); 59 | impl WeightInfo for SubstrateWeight { 60 | /// Storage: Assets Asset (r:1 w:0) 61 | /// Proof: Assets Asset (max_values: None, max_size: Some(210), added: 2685, mode: MaxEncodedLen) 62 | /// Storage: AssetRegistry AssetIdLocation (r:1 w:1) 63 | /// Proof: AssetRegistry AssetIdLocation (max_values: None, max_size: Some(622), added: 3097, mode: MaxEncodedLen) 64 | /// Storage: AssetRegistry AssetLocationId (r:0 w:1) 65 | /// Proof: AssetRegistry AssetLocationId (max_values: None, max_size: Some(622), added: 3097, mode: MaxEncodedLen) 66 | fn register_reserve_asset() -> Weight { 67 | // Proof Size summary in bytes: 68 | // Measured: `123` 69 | // Estimated: `7762` 70 | // Minimum execution time: 21_998_000 picoseconds. 71 | Weight::from_parts(22_970_000, 0) 72 | .saturating_add(Weight::from_parts(0, 7762)) 73 | .saturating_add(T::DbWeight::get().reads(2)) 74 | .saturating_add(T::DbWeight::get().writes(2)) 75 | } 76 | /// Storage: AssetRegistry AssetIdLocation (r:1 w:1) 77 | /// Proof: AssetRegistry AssetIdLocation (max_values: None, max_size: Some(622), added: 3097, mode: MaxEncodedLen) 78 | /// Storage: AssetRegistry AssetLocationId (r:0 w:1) 79 | /// Proof: AssetRegistry AssetLocationId (max_values: None, max_size: Some(622), added: 3097, mode: MaxEncodedLen) 80 | fn unregister_reserve_asset() -> Weight { 81 | // Proof Size summary in bytes: 82 | // Measured: `107` 83 | // Estimated: `4087` 84 | // Minimum execution time: 17_862_000 picoseconds. 85 | Weight::from_parts(18_454_000, 0) 86 | .saturating_add(Weight::from_parts(0, 4087)) 87 | .saturating_add(T::DbWeight::get().reads(1)) 88 | .saturating_add(T::DbWeight::get().writes(2)) 89 | } 90 | } 91 | 92 | impl WeightInfo for () { 93 | /// Storage: Assets Asset (r:1 w:0) 94 | /// Proof: Assets Asset (max_values: None, max_size: Some(210), added: 2685, mode: MaxEncodedLen) 95 | /// Storage: AssetRegistry AssetIdLocation (r:1 w:1) 96 | /// Proof: AssetRegistry AssetIdLocation (max_values: None, max_size: Some(622), added: 3097, mode: MaxEncodedLen) 97 | /// Storage: AssetRegistry AssetLocationId (r:0 w:1) 98 | /// Proof: AssetRegistry AssetLocationId (max_values: None, max_size: Some(622), added: 3097, mode: MaxEncodedLen) 99 | fn register_reserve_asset() -> Weight { 100 | // Proof Size summary in bytes: 101 | // Measured: `123` 102 | // Estimated: `7762` 103 | // Minimum execution time: 21_998_000 picoseconds. 104 | Weight::from_parts(22_970_000, 0) 105 | .saturating_add(Weight::from_parts(0, 7762)) 106 | .saturating_add(RocksDbWeight::get().reads(2)) 107 | .saturating_add(RocksDbWeight::get().writes(2)) 108 | } 109 | /// Storage: AssetRegistry AssetIdLocation (r:1 w:1) 110 | /// Proof: AssetRegistry AssetIdLocation (max_values: None, max_size: Some(622), added: 3097, mode: MaxEncodedLen) 111 | /// Storage: AssetRegistry AssetLocationId (r:0 w:1) 112 | /// Proof: AssetRegistry AssetLocationId (max_values: None, max_size: Some(622), added: 3097, mode: MaxEncodedLen) 113 | fn unregister_reserve_asset() -> Weight { 114 | // Proof Size summary in bytes: 115 | // Measured: `107` 116 | // Estimated: `4087` 117 | // Minimum execution time: 17_862_000 picoseconds. 118 | Weight::from_parts(18_454_000, 0) 119 | .saturating_add(Weight::from_parts(0, 4087)) 120 | .saturating_add(RocksDbWeight::get().reads(1)) 121 | .saturating_add(RocksDbWeight::get().writes(2)) 122 | } 123 | } 124 | -------------------------------------------------------------------------------- /claims/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "pallet-claims" 3 | version = "0.9.12" 4 | authors = ["Parity Technologies "] 5 | license = "Apache-2.0" 6 | edition = "2021" 7 | 8 | [lints] 9 | workspace = true 10 | 11 | [dependencies] 12 | libsecp256k1 = { workspace = true, optional = true } 13 | parity-scale-codec = { workspace = true } 14 | rustc-hex = { workspace = true } 15 | scale-info = { workspace = true } 16 | serde = { workspace = true } 17 | serde_derive = { workspace = true, optional = true } 18 | 19 | # substrate dependencies 20 | frame-benchmarking = { workspace = true, optional = true } 21 | frame-support = { workspace = true } 22 | frame-system = { workspace = true } 23 | sp-io = { workspace = true } 24 | sp-runtime = { workspace = true } 25 | sp-std = { workspace = true } 26 | 27 | # local 28 | claims-primitives = { package = "claims-primitives", path = "../primitives/claims", default-features = false } 29 | 30 | [dev-dependencies] 31 | hex-literal = { workspace = true } 32 | libsecp256k1 = { workspace = true, features = ["std"] } 33 | pallet-balances = { workspace = true, features = ["std"] } 34 | pallet-vesting = { workspace = true, features = ["std"] } 35 | serde_json = { workspace = true, features = ["std"] } 36 | sp-core = { workspace = true, features = ["std"] } 37 | 38 | [features] 39 | default = ["std"] 40 | 41 | std = [ 42 | "claims-primitives/std", 43 | "frame-benchmarking?/std", 44 | "frame-support/std", 45 | "frame-system/std", 46 | "pallet-balances/std", 47 | "parity-scale-codec/std", 48 | "rustc-hex/std", 49 | "scale-info/std", 50 | "serde/std", 51 | "serde_derive", 52 | "sp-io/std", 53 | "sp-runtime/std", 54 | "sp-std/std", 55 | "libsecp256k1?/std", 56 | "pallet-vesting/std", 57 | "serde_json/std", 58 | "sp-core/std", 59 | ] 60 | runtime-benchmarks = [ 61 | "frame-benchmarking/runtime-benchmarks", 62 | "frame-support/runtime-benchmarks", 63 | "frame-system/runtime-benchmarks", 64 | "libsecp256k1/hmac", 65 | "libsecp256k1/static-context", 66 | "pallet-balances/runtime-benchmarks", 67 | "pallet-vesting/runtime-benchmarks", 68 | "sp-runtime/runtime-benchmarks", 69 | ] 70 | 71 | try-runtime = [ 72 | "frame-support/try-runtime", 73 | "frame-system/try-runtime", 74 | "pallet-balances/try-runtime", 75 | "pallet-vesting/try-runtime", 76 | "sp-runtime/try-runtime", 77 | ] 78 | -------------------------------------------------------------------------------- /enclave-bridge/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "pallet-enclave-bridge" 3 | description = "The bridge between L1(integritee network) and L2(enclaves) for integritee blockchains and parachains" 4 | version = "0.12.0" 5 | authors = ["Integritee AG "] 6 | homepage = "https://integritee.network/" 7 | repository = "https://github.com/integritee-network/pallets/" 8 | license = "MS-RSL" 9 | edition = "2021" 10 | 11 | [lints] 12 | workspace = true 13 | 14 | [dependencies] 15 | log = { workspace = true } 16 | parity-scale-codec = { workspace = true } 17 | scale-info = { workspace = true } 18 | serde = { workspace = true, optional = true } 19 | 20 | # local 21 | enclave-bridge-primitives = { path = "../primitives/enclave-bridge", default-features = false } 22 | pallet-teerex = { path = "../teerex", default-features = false } 23 | teerex-primitives = { path = "../primitives/teerex", default-features = false } 24 | 25 | # substrate dependencies 26 | frame-support = { workspace = true } 27 | frame-system = { workspace = true } 28 | pallet-timestamp = { workspace = true } 29 | sp-core = { workspace = true } 30 | sp-io = { workspace = true } 31 | sp-runtime = { workspace = true } 32 | sp-std = { workspace = true } 33 | 34 | # benchmarking 35 | frame-benchmarking = { workspace = true, optional = true } 36 | hex-literal = { workspace = true, optional = true } 37 | pallet-balances = { workspace = true, optional = true } 38 | test-utils = { default-features = false, path = "../test-utils", optional = true } 39 | 40 | [dev-dependencies] 41 | env_logger = { workspace = true } 42 | sp-externalities = { workspace = true } 43 | frame-benchmarking = { workspace = true, features = ["std"] } 44 | hex-literal = { workspace = true } 45 | pallet-balances = { workspace = true, features = ["std"] } 46 | sp-keyring = { workspace = true } 47 | test-utils = { path = "../test-utils" } 48 | 49 | [features] 50 | default = ["std"] 51 | std = [ 52 | "enclave-bridge-primitives/std", 53 | "frame-benchmarking?/std", 54 | "frame-support/std", 55 | "frame-system/std", 56 | "log/std", 57 | "pallet-teerex/std", 58 | "pallet-timestamp/std", 59 | "parity-scale-codec/std", 60 | "scale-info/std", 61 | "serde/std", 62 | "sp-core/std", 63 | "sp-io/std", 64 | "sp-runtime/std", 65 | "sp-std/std", 66 | "teerex-primitives/std", 67 | "pallet-balances?/std", 68 | "sp-externalities/std", 69 | "sp-keyring/std", 70 | ] 71 | runtime-benchmarks = [ 72 | "frame-benchmarking/runtime-benchmarks", 73 | "hex-literal", 74 | "pallet-balances", 75 | "pallet-timestamp/runtime-benchmarks", 76 | "test-utils", 77 | "pallet-teerex/runtime-benchmarks", 78 | "frame-support/runtime-benchmarks", 79 | "frame-system/runtime-benchmarks", 80 | "pallet-balances?/runtime-benchmarks", 81 | "sp-runtime/runtime-benchmarks", 82 | ] 83 | 84 | try-runtime = [ 85 | "frame-support/try-runtime", 86 | "pallet-teerex/try-runtime", 87 | "frame-system/try-runtime", 88 | "pallet-balances?/try-runtime", 89 | "pallet-timestamp/try-runtime", 90 | "sp-runtime/try-runtime", 91 | ] 92 | -------------------------------------------------------------------------------- /enclave-bridge/LICENSE: -------------------------------------------------------------------------------- 1 | MICROSOFT REFERENCE SOURCE LICENSE (MS-RSL) 2 | 3 | This license governs use of the accompanying software. If you use the software, you accept this license. If you do not accept the license, do not use the software. 4 | 5 | 1. Definitions 6 | The terms "reproduce," "reproduction" and "distribution" have the same meaning here as under U.S. copyright law. 7 | 8 | "You" means the licensee of the software. 9 | 10 | "Your company" means the company you worked for when you downloaded the software. 11 | 12 | "Reference use" means use of the software within your company as a reference, in read only form, for the sole purposes of debugging your products, maintaining your products, or enhancing the interoperability of your products with the software, and specifically excludes the right to distribute the software outside of your company. 13 | 14 | "Licensed patents" means any Licensor patent claims which read directly on the software as distributed by the Licensor under this license. 15 | 16 | 2. Grant of Rights 17 | (A) Copyright Grant- Subject to the terms of this license, the Licensor grants you a non-transferable, non-exclusive, worldwide, royalty-free copyright license to reproduce the software for reference use. 18 | 19 | (B) Patent Grant- Subject to the terms of this license, the Licensor grants you a non-transferable, non-exclusive, worldwide, royalty-free patent license under licensed patents for reference use. 20 | 21 | 3. Limitations 22 | (A) No Trademark License- This license does not grant you any rights to use the Licensor's name, logo, or trademarks. 23 | 24 | (B) If you begin patent litigation against the Licensor over patents that you think may apply to the software (including a cross-claim or counterclaim in a lawsuit), your license to the software ends automatically. 25 | 26 | (C) The software is licensed "as-is." You bear the risk of using it. The Licensor gives no express warranties, guarantees or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent permitted under your local laws, the Licensor excludes the implied warranties of merchantability, fitness for a particular purpose and non-infringement. 27 | -------------------------------------------------------------------------------- /enclave-bridge/README.md: -------------------------------------------------------------------------------- 1 | # pallet-enclave-bridge 2 | 3 | Please note this pallet has a different [license](./LICENSE) than the rest of this repository: MS-RSL 4 | 5 | A pallet for [Integritee](https://integritee.network) that acts as a bridge between L1(integritee network) and L2(enclaves). 6 | * indirect-invocation proxy for calls to the confidential state transition function executed in SGX enclaves off-chain. 7 | 8 | More documentation available at: 9 | * High-level: https://www.integritee.network/for-developer 10 | * In-depth: https://book.integritee.network/ 11 | 12 | ## Test 13 | 14 | Run all unit tests with 15 | 16 | ``` 17 | cargo test --all 18 | ``` 19 | 20 | -------------------------------------------------------------------------------- /enclave-bridge/src/mock.rs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2021 Integritee AG and Supercomputing Systems AG 3 | 4 | Licensed under the MICROSOFT REFERENCE SOURCE LICENSE (MS-RSL) (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | https://referencesource.microsoft.com/license.html 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | 16 | */ 17 | 18 | // Creating mock runtime here 19 | use crate as pallet_enclave_bridge; 20 | use crate::Config; 21 | use frame_support::{self, derive_impl, parameter_types}; 22 | use frame_system as system; 23 | use sp_core::H256; 24 | use sp_keyring::Sr25519Keyring as Keyring; 25 | use sp_runtime::{ 26 | generic, 27 | traits::{BlakeTwo256, IdentifyAccount, IdentityLookup, Verify}, 28 | BuildStorage, 29 | }; 30 | 31 | pub type Signature = sp_runtime::MultiSignature; 32 | pub type AccountId = <::Signer as IdentifyAccount>::AccountId; 33 | pub type Address = sp_runtime::MultiAddress; 34 | 35 | pub type BlockNumber = u32; 36 | pub type Header = generic::Header; 37 | pub type UncheckedExtrinsic = 38 | generic::UncheckedExtrinsic; 39 | 40 | pub type SignedExtra = ( 41 | frame_system::CheckSpecVersion, 42 | frame_system::CheckTxVersion, 43 | frame_system::CheckGenesis, 44 | frame_system::CheckEra, 45 | frame_system::CheckNonce, 46 | frame_system::CheckWeight, 47 | ); 48 | 49 | frame_support::construct_runtime!( 50 | pub enum Test 51 | { 52 | System: frame_system::{Pallet, Call, Config, Storage, Event}, 53 | Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, 54 | Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent}, 55 | Teerex: pallet_teerex::{Pallet, Call, Storage, Event}, 56 | EnclaveBridge: pallet_enclave_bridge::{Pallet, Call, Storage, Event}, 57 | } 58 | ); 59 | 60 | parameter_types! { 61 | pub const BlockHashCount: u32 = 250; 62 | } 63 | #[derive_impl(frame_system::config_preludes::SolochainDefaultConfig as frame_system::DefaultConfig)] 64 | impl frame_system::Config for Test { 65 | type BaseCallFilter = frame_support::traits::Everything; 66 | type BlockWeights = (); 67 | type BlockLength = (); 68 | type Block = generic::Block; 69 | type DbWeight = (); 70 | type RuntimeOrigin = RuntimeOrigin; 71 | type Nonce = u64; 72 | type RuntimeCall = RuntimeCall; 73 | type RuntimeTask = RuntimeTask; 74 | type Hash = H256; 75 | type Hashing = BlakeTwo256; 76 | type AccountId = AccountId; 77 | type Lookup = IdentityLookup; 78 | type RuntimeEvent = RuntimeEvent; 79 | type BlockHashCount = BlockHashCount; 80 | type Version = (); 81 | type PalletInfo = PalletInfo; 82 | type AccountData = pallet_balances::AccountData; 83 | type OnNewAccount = (); 84 | type OnKilledAccount = (); 85 | type SystemWeightInfo = (); 86 | type SS58Prefix = (); 87 | type OnSetCode = (); 88 | type MaxConsumers = frame_support::traits::ConstU32<16>; 89 | } 90 | 91 | pub type Balance = u64; 92 | 93 | parameter_types! { 94 | pub const ExistentialDeposit: u64 = 1; 95 | } 96 | 97 | impl pallet_balances::Config for Test { 98 | type MaxLocks = (); 99 | type Balance = u64; 100 | type DustRemoval = (); 101 | type RuntimeEvent = RuntimeEvent; 102 | type ExistentialDeposit = ExistentialDeposit; 103 | type AccountStore = System; 104 | type WeightInfo = (); 105 | type MaxReserves = (); 106 | type ReserveIdentifier = (); 107 | type RuntimeHoldReason = (); 108 | type RuntimeFreezeReason = (); 109 | type FreezeIdentifier = (); 110 | type MaxFreezes = (); 111 | type DoneSlashHandler = (); 112 | } 113 | 114 | parameter_types! { 115 | pub const MinimumPeriod: u64 = 6000 / 2; 116 | } 117 | 118 | pub type Moment = u64; 119 | 120 | impl pallet_timestamp::Config for Test { 121 | type Moment = Moment; 122 | type OnTimestampSet = (); 123 | type MinimumPeriod = MinimumPeriod; 124 | type WeightInfo = (); 125 | } 126 | 127 | parameter_types! { 128 | pub const MomentsPerDay: u64 = 86_400_000; // [ms/d] 129 | pub const MaxAttestationRenewalPeriod: u64 = 172_800_000; // 48h 130 | } 131 | 132 | impl pallet_teerex::Config for Test { 133 | type RuntimeEvent = RuntimeEvent; 134 | type MomentsPerDay = MomentsPerDay; 135 | type MaxAttestationRenewalPeriod = MaxAttestationRenewalPeriod; 136 | type WeightInfo = (); 137 | } 138 | 139 | impl Config for Test { 140 | type RuntimeEvent = RuntimeEvent; 141 | type Currency = Balances; 142 | type WeightInfo = (); 143 | } 144 | 145 | // This function basically just builds a genesis storage key/value store according to 146 | // our desired mockup. RA from enclave compiled in debug mode is allowed 147 | pub fn new_test_ext() -> sp_io::TestExternalities { 148 | let mut t = system::GenesisConfig::::default().build_storage().unwrap(); 149 | pallet_balances::GenesisConfig:: { 150 | balances: vec![(Keyring::Alice.to_account_id(), 1 << 60)], 151 | ..Default::default() 152 | } 153 | .assimilate_storage(&mut t) 154 | .unwrap(); 155 | pallet_teerex::GenesisConfig:: { 156 | allow_sgx_debug_mode: true, 157 | allow_skipping_attestation: true, 158 | _config: Default::default(), 159 | } 160 | .assimilate_storage(&mut t) 161 | .unwrap(); 162 | 163 | let mut ext: sp_io::TestExternalities = t.into(); 164 | ext.execute_with(|| System::set_block_number(1)); 165 | ext 166 | } 167 | 168 | /// Run until a particular block. 169 | pub fn run_to_block(n: u32) { 170 | use frame_support::traits::{OnFinalize, OnInitialize}; 171 | while System::block_number() < n { 172 | if System::block_number() > 1 { 173 | System::on_finalize(System::block_number()); 174 | } 175 | Timestamp::on_finalize(System::block_number()); 176 | System::set_block_number(System::block_number() + 1); 177 | System::on_initialize(System::block_number()); 178 | } 179 | } 180 | -------------------------------------------------------------------------------- /enclave-bridge/src/tests/mod.rs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2021 Integritee AG and Supercomputing Systems AG 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | 16 | */ 17 | 18 | use crate::mock::*; 19 | use frame_support::assert_ok; 20 | use parity_scale_codec::{Decode, Encode}; 21 | use teerex_primitives::{EnclaveFingerprint, MultiEnclave, SgxEnclave}; 22 | use test_utils::TestEnclave; 23 | 24 | mod test_indirect_invocation; 25 | mod test_publish_hash; 26 | mod test_shard_config; 27 | 28 | mod test_shard_status; 29 | 30 | fn get_bonding_account(enclave: &MultiEnclave>) -> AccountId { 31 | AccountId::decode(&mut enclave.fingerprint().encode().as_ref()).unwrap() 32 | } 33 | 34 | fn now() -> u64 { 35 | >::get() 36 | } 37 | 38 | fn register_sovereign_test_enclave( 39 | signer: &AccountId, 40 | fingerprint: EnclaveFingerprint, 41 | ) -> MultiEnclave> { 42 | let enclave = MultiEnclave::from( 43 | SgxEnclave::test_enclave() 44 | .with_mr_enclave(fingerprint.into()) 45 | .with_pubkey(&signer.encode()[..]) 46 | .with_timestamp(now()), 47 | ); 48 | assert_ok!(Teerex::add_enclave(signer, enclave.clone())); 49 | enclave 50 | } 51 | 52 | pub const NOW: u64 = 1587899785000; 53 | -------------------------------------------------------------------------------- /enclave-bridge/src/tests/test_publish_hash.rs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2021 Integritee AG and Supercomputing Systems AG 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | 16 | */ 17 | 18 | use super::*; 19 | use crate::{Error, Event as EnclaveBridgeEvent, DATA_LENGTH_LIMIT}; 20 | use frame_support::{assert_err, assert_ok}; 21 | use sp_core::H256; 22 | use sp_keyring::Sr25519Keyring as Keyring; 23 | 24 | #[test] 25 | fn publish_hash_works() { 26 | use frame_system::{EventRecord, Phase}; 27 | 28 | new_test_ext().execute_with(|| { 29 | let enclave_signer = Keyring::Eve.to_account_id(); 30 | let _enclave = 31 | register_sovereign_test_enclave(&enclave_signer, EnclaveFingerprint::default()); 32 | 33 | // There are no events emitted at the genesis block. 34 | System::set_block_number(1); 35 | System::reset_events(); 36 | 37 | let hash = H256::from([1u8; 32]); 38 | let extra_topics = vec![H256::from([2u8; 32]), H256::from([3u8; 32])]; 39 | let data = b"hello world".to_vec(); 40 | 41 | // publish with extra topics and data 42 | assert_ok!(EnclaveBridge::publish_hash( 43 | RuntimeOrigin::signed(enclave_signer.clone()), 44 | hash, 45 | extra_topics.clone(), 46 | data.clone() 47 | )); 48 | 49 | // publish without extra topics and data 50 | assert_ok!(EnclaveBridge::publish_hash( 51 | RuntimeOrigin::signed(enclave_signer.clone()), 52 | hash, 53 | vec![], 54 | vec![] 55 | )); 56 | 57 | let fingerprint = Teerex::sovereign_enclaves(&enclave_signer).unwrap().fingerprint(); 58 | let mut topics = extra_topics; 59 | topics.push(fingerprint); 60 | 61 | // Check that topics are reflected in the event record. 62 | assert_eq!( 63 | System::events(), 64 | vec![ 65 | EventRecord { 66 | phase: Phase::Initialization, 67 | event: EnclaveBridgeEvent::PublishedHash { 68 | enclave_fingerprint: fingerprint, 69 | hash, 70 | data 71 | } 72 | .into(), 73 | topics, 74 | }, 75 | EventRecord { 76 | phase: Phase::Initialization, 77 | event: EnclaveBridgeEvent::PublishedHash { 78 | enclave_fingerprint: fingerprint, 79 | hash, 80 | data: vec![] 81 | } 82 | .into(), 83 | topics: vec![fingerprint], 84 | }, 85 | ] 86 | ); 87 | }) 88 | } 89 | 90 | #[test] 91 | fn publish_hash_with_unregistered_enclave_fails() { 92 | new_test_ext().execute_with(|| { 93 | let enclave_signer = Keyring::Eve.to_account_id(); 94 | 95 | assert_err!( 96 | EnclaveBridge::publish_hash( 97 | RuntimeOrigin::signed(enclave_signer), 98 | [1u8; 32].into(), 99 | vec![], 100 | vec![] 101 | ), 102 | pallet_teerex::Error::::EnclaveIsNotRegistered 103 | ); 104 | }) 105 | } 106 | 107 | #[test] 108 | fn publish_hash_with_too_many_topics_fails() { 109 | new_test_ext().execute_with(|| { 110 | let enclave_signer = Keyring::Eve.to_account_id(); 111 | let _enclave = 112 | register_sovereign_test_enclave(&enclave_signer, EnclaveFingerprint::default()); 113 | 114 | let hash = H256::from([1u8; 32]); 115 | let extra_topics = vec![ 116 | H256::from([0u8; 32]), 117 | H256::from([1u8; 32]), 118 | H256::from([2u8; 32]), 119 | H256::from([3u8; 32]), 120 | H256::from([4u8; 32]), 121 | H256::from([5u8; 32]), 122 | ]; 123 | 124 | assert_err!( 125 | EnclaveBridge::publish_hash( 126 | RuntimeOrigin::signed(enclave_signer), 127 | hash, 128 | extra_topics, 129 | vec![] 130 | ), 131 | Error::::TooManyTopics 132 | ); 133 | }) 134 | } 135 | 136 | #[test] 137 | fn publish_hash_with_too_much_data_fails() { 138 | new_test_ext().execute_with(|| { 139 | let enclave_signer = Keyring::Eve.to_account_id(); 140 | let _enclave = 141 | register_sovereign_test_enclave(&enclave_signer, EnclaveFingerprint::default()); 142 | 143 | let hash = H256::from([1u8; 32]); 144 | let data = vec![0u8; DATA_LENGTH_LIMIT + 1]; 145 | 146 | assert_err!( 147 | EnclaveBridge::publish_hash(RuntimeOrigin::signed(enclave_signer), hash, vec![], data), 148 | Error::::DataTooLong 149 | ); 150 | }) 151 | } 152 | -------------------------------------------------------------------------------- /enclave-bridge/src/tests/test_shard_status.rs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2021 Integritee AG and Supercomputing Systems AG 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | 16 | */ 17 | 18 | use super::*; 19 | use crate::{Error, Event as EnclaveBridgeEvent}; 20 | use enclave_bridge_primitives::ShardIdentifier; 21 | use frame_support::{assert_noop, assert_ok}; 22 | use sp_keyring::Sr25519Keyring as Keyring; 23 | use teerex_primitives::EnclaveFingerprint; 24 | 25 | #[test] 26 | fn purge_enclave_from_shard_status_works_if_present() { 27 | new_test_ext().execute_with(|| { 28 | Timestamp::set_timestamp(NOW); 29 | let enclave_signer_1 = Keyring::Eve.to_account_id(); 30 | let enclave_signer_2 = Keyring::Ferdie.to_account_id(); 31 | let enclave_fingerprint = EnclaveFingerprint::default(); 32 | let shard = ShardIdentifier::default(); 33 | assert_ok!(EnclaveBridge::touch_shard( 34 | shard, 35 | &enclave_signer_1.clone(), 36 | enclave_fingerprint, 37 | 1 38 | )); 39 | assert_ok!(EnclaveBridge::purge_enclave_from_shard_status( 40 | RuntimeOrigin::root(), 41 | shard, 42 | enclave_signer_1.clone(), 43 | )); 44 | let expected_event = 45 | RuntimeEvent::EnclaveBridge(EnclaveBridgeEvent::PurgedEnclaveFromShardConfig { 46 | shard, 47 | subject: enclave_signer_1.clone(), 48 | }); 49 | println!("events:{:?}", System::events()); 50 | assert!(System::events().iter().any(|a| a.event == expected_event)); 51 | 52 | assert!(EnclaveBridge::shard_status(shard).is_some()); 53 | assert_eq!(EnclaveBridge::shard_status(shard).unwrap().len(), 0); 54 | assert_ok!(EnclaveBridge::touch_shard( 55 | shard, 56 | &enclave_signer_1.clone(), 57 | enclave_fingerprint, 58 | 2 59 | )); 60 | assert_ok!(EnclaveBridge::touch_shard( 61 | shard, 62 | &enclave_signer_2.clone(), 63 | enclave_fingerprint, 64 | 2 65 | )); 66 | assert!(EnclaveBridge::shard_status(shard).is_some()); 67 | assert_eq!(EnclaveBridge::shard_status(shard).unwrap().len(), 2); 68 | 69 | assert_ok!(EnclaveBridge::purge_enclave_from_shard_status( 70 | RuntimeOrigin::root(), 71 | shard, 72 | enclave_signer_1, 73 | )); 74 | 75 | assert!(EnclaveBridge::shard_status(shard).is_some()); 76 | assert_eq!(EnclaveBridge::shard_status(shard).unwrap().len(), 1); 77 | assert_eq!(EnclaveBridge::shard_status(shard).unwrap()[0].signer, enclave_signer_2); 78 | }) 79 | } 80 | 81 | #[test] 82 | fn purge_enclave_from_shard_status_for_inexistent_shard_is_err() { 83 | new_test_ext().execute_with(|| { 84 | Timestamp::set_timestamp(NOW); 85 | let enclave_signer_1 = Keyring::Eve.to_account_id(); 86 | let shard = ShardIdentifier::default(); 87 | 88 | assert_noop!( 89 | EnclaveBridge::purge_enclave_from_shard_status( 90 | RuntimeOrigin::root(), 91 | shard, 92 | enclave_signer_1.clone(), 93 | ), 94 | Error::::ShardNotFound 95 | ); 96 | }) 97 | } 98 | 99 | #[test] 100 | fn purge_enclave_from_shard_status_fails_if_not_root() { 101 | new_test_ext().execute_with(|| { 102 | Timestamp::set_timestamp(NOW); 103 | let enclave_signer_1 = Keyring::Eve.to_account_id(); 104 | let enclave_fingerprint = EnclaveFingerprint::default(); 105 | let shard = ShardIdentifier::default(); 106 | assert_ok!(EnclaveBridge::touch_shard( 107 | shard, 108 | &enclave_signer_1.clone(), 109 | enclave_fingerprint, 110 | 1 111 | )); 112 | assert!(EnclaveBridge::purge_enclave_from_shard_status( 113 | RuntimeOrigin::signed(enclave_signer_1.clone()), 114 | shard, 115 | enclave_signer_1.clone(), 116 | ) 117 | .is_err()); 118 | }) 119 | } 120 | -------------------------------------------------------------------------------- /primitives/claims/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "claims-primitives" 3 | version = "0.1.0" 4 | authors = ["Integritee AG "] 5 | homepage = "https://integritee.network/" 6 | repository = "https://github.com/integritee-network/pallets/" 7 | license = "Apache-2.0" 8 | edition = "2021" 9 | 10 | [lints] 11 | workspace = true 12 | 13 | [dependencies] 14 | parity-scale-codec = { workspace = true } 15 | rustc-hex = { workspace = true } 16 | scale-info = { workspace = true } 17 | serde = { workspace = true } 18 | 19 | # substrate dependencies 20 | sp-io = { workspace = true } 21 | sp-runtime = { workspace = true } 22 | sp-std = { workspace = true } 23 | 24 | [features] 25 | default = ["std"] 26 | std = [ 27 | "parity-scale-codec/std", 28 | "rustc-hex/std", 29 | "scale-info/std", 30 | "serde/std", 31 | "sp-io/std", 32 | "sp-runtime/std", 33 | "sp-std/std", 34 | ] 35 | -------------------------------------------------------------------------------- /primitives/claims/src/lib.rs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2021 Integritee AG and Supercomputing Systems AG 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | 16 | */ 17 | 18 | //!Primitives for claims 19 | #![cfg_attr(not(feature = "std"), no_std)] 20 | 21 | #[cfg(not(feature = "std"))] 22 | extern crate alloc; 23 | #[cfg(not(feature = "std"))] 24 | use alloc::{format, string::String}; 25 | use parity_scale_codec::{Decode, DecodeWithMemTracking, Encode}; 26 | use scale_info::TypeInfo; 27 | use serde::{self, Deserialize, Deserializer, Serialize, Serializer}; 28 | use sp_runtime::RuntimeDebug; 29 | use sp_std::vec::Vec; 30 | /// Copied from https://github.com/paritytech/polkadot/blob/master/primitives/src/v1/mod.rs 31 | /// Custom validity errors used in Polkadot while validating transactions. 32 | #[repr(u8)] 33 | pub enum ValidityError { 34 | /// The Ethereum signature is invalid. 35 | InvalidEthereumSignature = 0, 36 | /// The signer has no claim. 37 | SignerHasNoClaim = 1, 38 | /// No permission to execute the call. 39 | NoPermission = 2, 40 | /// An invalid statement was made for a claim. 41 | InvalidStatement = 3, 42 | } 43 | 44 | impl From for u8 { 45 | fn from(err: ValidityError) -> Self { 46 | err as u8 47 | } 48 | } 49 | 50 | /// The kind of statement an account needs to make for a claim to be valid. 51 | #[derive( 52 | Encode, 53 | Decode, 54 | DecodeWithMemTracking, 55 | Clone, 56 | Copy, 57 | Eq, 58 | PartialEq, 59 | Default, 60 | RuntimeDebug, 61 | TypeInfo, 62 | Serialize, 63 | Deserialize, 64 | )] 65 | pub enum StatementKind { 66 | /// Statement required to be made by non-SAFT holders. 67 | #[default] 68 | Regular, 69 | /// Statement required to be made by SAFT holders. 70 | Saft, 71 | } 72 | 73 | impl StatementKind { 74 | /// Convert this to the (English) statement it represents. 75 | pub fn to_text(self) -> &'static [u8] { 76 | match self { 77 | StatementKind::Regular => 78 | &b"I hereby agree to the terms of the statement whose SHA-256 multihash is \ 79 | Qmc1XYqT6S39WNp2UeiRUrZichUWUPpGEThDE6dAb3f6Ny. (This may be found at the URL: \ 80 | https://statement.polkadot.network/regular.html)"[..], 81 | StatementKind::Saft => 82 | &b"I hereby agree to the terms of the statement whose SHA-256 multihash is \ 83 | QmXEkMahfhHJPzT3RjkXiZVFi77ZeVeuxtAjhojGRNYckz. (This may be found at the URL: \ 84 | https://statement.polkadot.network/saft.html)"[..], 85 | } 86 | } 87 | } 88 | 89 | /// An Ethereum address (i.e. 20 bytes, used to represent an Ethereum account). 90 | /// 91 | /// This gets serialized to the 0x-prefixed hex representation. 92 | #[derive( 93 | Clone, 94 | Copy, 95 | PartialEq, 96 | Eq, 97 | Encode, 98 | Decode, 99 | DecodeWithMemTracking, 100 | Default, 101 | RuntimeDebug, 102 | TypeInfo, 103 | )] 104 | pub struct EthereumAddress(pub [u8; 20]); 105 | 106 | impl Serialize for EthereumAddress { 107 | fn serialize(&self, serializer: S) -> Result 108 | where 109 | S: Serializer, 110 | { 111 | let hex: String = rustc_hex::ToHex::to_hex(&self.0[..]); 112 | serializer.serialize_str(&format!("0x{}", hex)) 113 | } 114 | } 115 | 116 | impl<'de> Deserialize<'de> for EthereumAddress { 117 | fn deserialize(deserializer: D) -> Result 118 | where 119 | D: Deserializer<'de>, 120 | { 121 | let base_string = String::deserialize(deserializer)?; 122 | let offset = if base_string.starts_with("0x") { 2 } else { 0 }; 123 | let s = &base_string[offset..]; 124 | if s.len() != 40 { 125 | Err(serde::de::Error::custom( 126 | "Bad length of Ethereum address (should be 42 including '0x')", 127 | ))?; 128 | } 129 | let raw: Vec = rustc_hex::FromHex::from_hex(s) 130 | .map_err(|e| serde::de::Error::custom(format!("{:?}", e)))?; 131 | let mut r = Self::default(); 132 | r.0.copy_from_slice(&raw); 133 | Ok(r) 134 | } 135 | } 136 | 137 | #[derive(Encode, Decode, DecodeWithMemTracking, Clone, TypeInfo)] 138 | pub struct EcdsaSignature(pub [u8; 65]); 139 | 140 | impl PartialEq for EcdsaSignature { 141 | fn eq(&self, other: &Self) -> bool { 142 | self.0[..] == other.0[..] 143 | } 144 | } 145 | 146 | impl sp_std::fmt::Debug for EcdsaSignature { 147 | fn fmt(&self, f: &mut sp_std::fmt::Formatter<'_>) -> sp_std::fmt::Result { 148 | write!(f, "EcdsaSignature({:?})", &self.0[..]) 149 | } 150 | } 151 | -------------------------------------------------------------------------------- /primitives/common/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "common-primitives" 3 | version = "0.1.0" 4 | authors = ["Integritee AG "] 5 | homepage = "https://integritee.network/" 6 | repository = "https://github.com/integritee-network/pallets/" 7 | license = "Apache-2.0" 8 | edition = "2021" 9 | 10 | [lints] 11 | workspace = true 12 | 13 | [dependencies] 14 | derive_more = { workspace = true } 15 | parity-scale-codec = { workspace = true } 16 | scale-info = { workspace = true } 17 | 18 | # substrate deps 19 | sp-core = { workspace = true } 20 | sp-runtime = { workspace = true } 21 | sp-std = { workspace = true } 22 | 23 | [features] 24 | default = ["std"] 25 | std = [ 26 | "parity-scale-codec/std", 27 | "scale-info/std", 28 | "sp-core/std", 29 | "sp-runtime/std", 30 | "sp-std/std", 31 | ] 32 | -------------------------------------------------------------------------------- /primitives/common/src/lib.rs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2021 Integritee AG and Supercomputing Systems AG 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | 16 | */ 17 | #![cfg_attr(not(feature = "std"), no_std)] 18 | //!Primitives for all pallets 19 | extern crate derive_more; 20 | use derive_more::From; 21 | use parity_scale_codec::{Decode, DecodeWithMemTracking, Encode}; 22 | use scale_info::TypeInfo; 23 | use sp_core::{bounded::BoundedVec, ConstU32, H256}; 24 | use sp_runtime::MultiSigner; 25 | use sp_std::vec; 26 | 27 | #[cfg(not(feature = "std"))] 28 | use sp_std::vec::Vec; 29 | 30 | /// Substrate runtimes provide no string type. Hence, for arbitrary data of varying length the 31 | /// `Vec` is used. In the polkadot-js the typedef `Text` is used to automatically 32 | /// utf8 decode bytes into a string. 33 | #[cfg(not(feature = "std"))] 34 | pub type PalletString = Vec; 35 | #[cfg(feature = "std")] 36 | pub type PalletString = String; 37 | 38 | pub type OpaqueSigner = BoundedVec>; 39 | pub type EnclaveFingerprint = H256; 40 | pub type ShardIdentifier = H256; 41 | 42 | pub trait AsByteOrNoop { 43 | fn as_bytes_or_noop(&self) -> &[u8]; 44 | } 45 | 46 | impl AsByteOrNoop for PalletString { 47 | #[cfg(feature = "std")] 48 | fn as_bytes_or_noop(&self) -> &[u8] { 49 | self.as_bytes() 50 | } 51 | 52 | #[cfg(not(feature = "std"))] 53 | fn as_bytes_or_noop(&self) -> &[u8] { 54 | self 55 | } 56 | } 57 | 58 | #[derive( 59 | Encode, 60 | Decode, 61 | DecodeWithMemTracking, 62 | Clone, 63 | PartialEq, 64 | Eq, 65 | From, 66 | sp_core::RuntimeDebug, 67 | TypeInfo, 68 | )] 69 | pub enum AnySigner { 70 | Opaque(OpaqueSigner), 71 | Known(MultiSigner), 72 | } 73 | impl Default for AnySigner { 74 | fn default() -> Self { 75 | AnySigner::Opaque(OpaqueSigner::default()) 76 | } 77 | } 78 | 79 | impl From<[u8; 32]> for AnySigner { 80 | fn from(pubkey: [u8; 32]) -> Self { 81 | // zero padding is necessary because the chain storage does that anyway for bounded vec 82 | let mut zero_padded_pubkey = pubkey.to_vec(); 83 | zero_padded_pubkey.append(&mut vec![0; 34]); 84 | AnySigner::Opaque( 85 | OpaqueSigner::try_from(zero_padded_pubkey).expect("66 >= 32 + 34. q.e.d."), 86 | ) 87 | } 88 | } 89 | 90 | impl From<[u8; 64]> for AnySigner { 91 | fn from(pubkey: [u8; 64]) -> Self { 92 | // zero padding is necessary because the chain storage does that anyway for bounded vec 93 | let mut zero_padded_pubkey = pubkey.to_vec(); 94 | zero_padded_pubkey.append(&mut vec![0; 2]); 95 | AnySigner::Opaque(OpaqueSigner::try_from(zero_padded_pubkey).expect("66 > 64 + 2. q.e.d.")) 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /primitives/enclave-bridge/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "enclave-bridge-primitives" 3 | version = "0.1.0" 4 | authors = ["Integritee AG "] 5 | homepage = "https://integritee.network/" 6 | repository = "https://github.com/integritee-network/pallets/" 7 | license = "Apache-2.0" 8 | edition = "2021" 9 | 10 | [lints] 11 | workspace = true 12 | 13 | [dependencies] 14 | common-primitives = { path = "../common", default-features = false } 15 | log = { workspace = true } 16 | parity-scale-codec = { workspace = true } 17 | scale-info = { workspace = true } 18 | serde = { workspace = true } 19 | 20 | # substrate dependencies 21 | sp-core = { workspace = true } 22 | sp-io = { workspace = true } 23 | sp-runtime = { workspace = true } 24 | sp-std = { workspace = true } 25 | 26 | [dev-dependencies] 27 | hex-literal = { workspace = true } 28 | 29 | [features] 30 | default = ["std"] 31 | std = [ 32 | "common-primitives/std", 33 | "parity-scale-codec/std", 34 | "scale-info/std", 35 | "serde/std", 36 | "sp-core/std", 37 | "sp-io/std", 38 | "sp-runtime/std", 39 | "sp-std/std", 40 | "log/std", 41 | ] 42 | -------------------------------------------------------------------------------- /primitives/enclave-bridge/src/lib.rs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2021 Integritee AG and Supercomputing Systems AG 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | 16 | */ 17 | 18 | //!Primitives for enclave-bridge 19 | #![cfg_attr(not(feature = "std"), no_std)] 20 | pub use common_primitives::{EnclaveFingerprint, ShardIdentifier}; 21 | use parity_scale_codec::{Decode, DecodeWithMemTracking, Encode}; 22 | use scale_info::TypeInfo; 23 | use sp_std::prelude::*; 24 | 25 | pub const ENCLAVE_BRIDGE: &str = "enclave_bridge"; 26 | 27 | #[derive( 28 | Encode, 29 | Decode, 30 | DecodeWithMemTracking, 31 | Default, 32 | Clone, 33 | PartialEq, 34 | Eq, 35 | sp_core::RuntimeDebug, 36 | TypeInfo, 37 | )] 38 | pub struct Request { 39 | pub shard: ShardIdentifier, 40 | pub cyphertext: Vec, 41 | } 42 | 43 | #[derive( 44 | Encode, 45 | Decode, 46 | DecodeWithMemTracking, 47 | Default, 48 | Clone, 49 | PartialEq, 50 | Eq, 51 | sp_core::RuntimeDebug, 52 | TypeInfo, 53 | )] 54 | pub struct ShardSignerStatus { 55 | pub signer: AccountId, 56 | pub fingerprint: EnclaveFingerprint, 57 | pub last_activity: BlockNumber, 58 | } 59 | pub const MAX_SHARD_STATUS_SIGNER_COUNT: u32 = 10; 60 | 61 | #[derive( 62 | Encode, Decode, DecodeWithMemTracking, Clone, PartialEq, Eq, sp_core::RuntimeDebug, TypeInfo, 63 | )] 64 | pub struct ShardConfig { 65 | /// enclave fingerprint which may perform state transitions on this shard 66 | pub enclave_fingerprint: EnclaveFingerprint, 67 | /// an optional limit on the number of validateers 68 | pub max_instances: Option, 69 | /// an optional set of authorities for permissioned sidechains 70 | pub authorities: Option>, 71 | /// maintenance mode blocks any upcoming state transitions on this shard 72 | pub maintenance_mode: bool, 73 | } 74 | 75 | impl ShardConfig { 76 | pub fn new(fingerprint: EnclaveFingerprint) -> Self { 77 | ShardConfig { 78 | enclave_fingerprint: fingerprint, 79 | max_instances: None, 80 | authorities: None, 81 | maintenance_mode: false, 82 | } 83 | } 84 | } 85 | 86 | #[derive( 87 | Encode, Decode, DecodeWithMemTracking, Clone, PartialEq, Eq, sp_core::RuntimeDebug, TypeInfo, 88 | )] 89 | pub struct UpgradableShardConfig { 90 | /// the currently active config 91 | pub active_config: ShardConfig, 92 | /// temporary store for an upcoming upgraded shard config with enactment time 93 | pub pending_upgrade: Option>, 94 | /// enact after importing this parentchain block on the sidechain 95 | pub upgrade_at: Option, 96 | } 97 | 98 | impl From> 99 | for UpgradableShardConfig 100 | { 101 | fn from(shard_config: ShardConfig) -> Self { 102 | UpgradableShardConfig { 103 | active_config: shard_config, 104 | pending_upgrade: None, 105 | upgrade_at: None, 106 | } 107 | } 108 | } 109 | 110 | impl UpgradableShardConfig { 111 | pub fn with_pending_upgrade( 112 | mut self, 113 | new_shard_config: ShardConfig, 114 | block_number: BlockNumber, 115 | ) -> Self { 116 | self.pending_upgrade = Some(new_shard_config); 117 | self.upgrade_at = Some(block_number); 118 | self 119 | } 120 | } 121 | -------------------------------------------------------------------------------- /primitives/sidechain/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "sidechain-primitives" 3 | version = "0.1.0" 4 | authors = ["Integritee AG "] 5 | homepage = "https://integritee.network/" 6 | repository = "https://github.com/integritee-network/pallets/" 7 | license = "Apache-2.0" 8 | edition = "2021" 9 | 10 | [lints] 11 | workspace = true 12 | 13 | [dependencies] 14 | parity-scale-codec = { workspace = true } 15 | scale-info = { workspace = true } 16 | serde = { workspace = true } 17 | 18 | 19 | # substrate dependencies 20 | sp-core = { workspace = true } 21 | sp-io = { workspace = true } 22 | sp-runtime = { workspace = true } 23 | sp-std = { workspace = true } 24 | 25 | 26 | [features] 27 | default = ["full_crypto", "std"] 28 | full_crypto = ["sp-core/full_crypto"] 29 | std = [ 30 | "parity-scale-codec/std", 31 | "scale-info/std", 32 | "serde/std", 33 | "sp-core/std", 34 | "sp-io/std", 35 | "sp-runtime/std", 36 | "sp-std/std", 37 | ] 38 | -------------------------------------------------------------------------------- /primitives/sidechain/src/lib.rs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2021 Integritee AG and Supercomputing Systems AG 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | 16 | */ 17 | 18 | #![cfg_attr(not(feature = "std"), no_std)] 19 | 20 | use parity_scale_codec::{Decode, DecodeWithMemTracking, Encode}; 21 | use scale_info::TypeInfo; 22 | use sp_core::H256; 23 | 24 | #[cfg(feature = "std")] 25 | use serde::{Deserialize, Serialize}; 26 | 27 | pub type SidechainBlockNumber = u64; 28 | #[derive( 29 | PartialEq, Eq, Clone, Encode, Decode, DecodeWithMemTracking, Debug, Copy, Default, TypeInfo, 30 | )] 31 | #[cfg_attr(feature = "std", derive(Serialize, Deserialize))] 32 | pub struct SidechainBlockConfirmation { 33 | pub block_number: SidechainBlockNumber, 34 | pub block_header_hash: H256, 35 | } 36 | -------------------------------------------------------------------------------- /primitives/teeracle/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "teeracle-primitives" 3 | version = "0.1.0" 4 | authors = ["Integritee AG "] 5 | homepage = "https://integritee.network/" 6 | repository = "https://github.com/integritee-network/pallets/" 7 | license = "Apache-2.0" 8 | edition = "2021" 9 | 10 | [lints] 11 | workspace = true 12 | 13 | [dependencies] 14 | # local 15 | common-primitives = { path = "../common", default-features = false } 16 | 17 | # encointer 18 | substrate-fixed = { workspace = true } 19 | 20 | # substrate 21 | sp-std = { workspace = true } 22 | 23 | 24 | [features] 25 | default = ["std"] 26 | std = ["common-primitives/std", "sp-std/std", "substrate-fixed/std"] 27 | -------------------------------------------------------------------------------- /primitives/teeracle/src/lib.rs: -------------------------------------------------------------------------------- 1 | //!Primitives for teeracle 2 | #![cfg_attr(not(feature = "std"), no_std)] 3 | use common_primitives::PalletString; 4 | use substrate_fixed::types::U32F32; 5 | 6 | pub const MAX_ORACLE_DATA_NAME_LEN: usize = 40; 7 | 8 | pub type ExchangeRate = U32F32; 9 | pub type TradingPairString = PalletString; 10 | pub type MarketDataSourceString = PalletString; 11 | pub type OracleDataName = PalletString; 12 | pub type DataSource = PalletString; 13 | -------------------------------------------------------------------------------- /primitives/teerdays/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "teerdays-primitives" 3 | version = "0.1.0" 4 | authors = ["Integritee AG "] 5 | homepage = "https://integritee.network/" 6 | repository = "https://github.com/integritee-network/pallets/" 7 | license = "Apache-2.0" 8 | edition = "2021" 9 | 10 | [lints] 11 | workspace = true 12 | 13 | [dependencies] 14 | parity-scale-codec = { workspace = true } 15 | scale-info = { workspace = true } 16 | serde = { workspace = true } 17 | sp-core = { workspace = true } 18 | sp-runtime = { workspace = true } 19 | 20 | [features] 21 | default = ["std"] 22 | std = [ 23 | "parity-scale-codec/std", 24 | "scale-info/std", 25 | "serde/std", 26 | "sp-core/std", 27 | "sp-runtime/std", 28 | ] 29 | -------------------------------------------------------------------------------- /primitives/teerdays/src/lib.rs: -------------------------------------------------------------------------------- 1 | #![cfg_attr(not(feature = "std"), no_std)] 2 | use parity_scale_codec::{Decode, DecodeWithMemTracking, Encode}; 3 | use scale_info::TypeInfo; 4 | use sp_runtime::{traits::AtLeast32BitUnsigned, Saturating}; 5 | 6 | #[derive( 7 | Encode, 8 | Decode, 9 | DecodeWithMemTracking, 10 | Copy, 11 | Clone, 12 | PartialEq, 13 | Eq, 14 | Default, 15 | sp_core::RuntimeDebug, 16 | TypeInfo, 17 | )] 18 | pub struct TeerDayBond { 19 | pub value: Balance, 20 | pub last_updated: Moment, 21 | // the unit here is actually balance * moments. 22 | pub accumulated_tokentime: Balance, 23 | } 24 | 25 | impl TeerDayBond 26 | where 27 | Moment: Clone + Copy + Encode + Decode + Saturating, 28 | Balance: AtLeast32BitUnsigned + Clone + Copy + Encode + Decode + Default + From, 29 | { 30 | pub fn update(self, now: Moment) -> Self { 31 | let elapsed: Balance = now.saturating_sub(self.last_updated).into(); 32 | let new_tokentime = 33 | self.accumulated_tokentime.saturating_add(self.value.saturating_mul(elapsed)); 34 | Self { value: self.value, last_updated: now, accumulated_tokentime: new_tokentime } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /primitives/teerex/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "teerex-primitives" 3 | version = "0.1.0" 4 | authors = ["Integritee AG "] 5 | homepage = "https://integritee.network/" 6 | repository = "https://github.com/integritee-network/pallets/" 7 | license = "Apache-2.0" 8 | edition = "2021" 9 | 10 | [lints] 11 | workspace = true 12 | 13 | [dependencies] 14 | common-primitives = { path = "../common", default-features = false } 15 | derive_more = { workspace = true } 16 | log = { workspace = true } 17 | parity-scale-codec = { workspace = true } 18 | scale-info = { workspace = true } 19 | serde = { workspace = true } 20 | 21 | # substrate dependencies 22 | sp-core = { workspace = true } 23 | sp-runtime = { workspace = true } 24 | sp-std = { workspace = true } 25 | 26 | [dev-dependencies] 27 | hex-literal = { workspace = true } 28 | 29 | [features] 30 | default = ["std"] 31 | std = [ 32 | "common-primitives/std", 33 | "log/std", 34 | "parity-scale-codec/std", 35 | "scale-info/std", 36 | "serde/std", 37 | "sp-core/std", 38 | "sp-runtime/std", 39 | "sp-std/std", 40 | ] 41 | -------------------------------------------------------------------------------- /primitives/xcm-transactor/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "xcm-transactor-primitives" 3 | version = "0.1.0" 4 | authors = ["Integritee AG "] 5 | homepage = "https://integritee.network/" 6 | repository = "https://github.com/integritee-network/pallets/" 7 | license = "Apache-2.0" 8 | edition = "2021" 9 | 10 | [lints] 11 | workspace = true 12 | 13 | [dependencies] 14 | parity-scale-codec = { workspace = true } 15 | # local 16 | common-primitives = { path = "../common", default-features = false } 17 | 18 | # substrate 19 | frame-support = { workspace = true } 20 | sp-runtime = { workspace = true } 21 | sp-std = { workspace = true } 22 | 23 | # xcm/polkadot 24 | staging-xcm = { workspace = true } 25 | 26 | # cumulus 27 | cumulus-primitives-core = { workspace = true } 28 | 29 | [features] 30 | default = ["std"] 31 | ksm = [] 32 | dot = [] 33 | std = [ 34 | "common-primitives/std", 35 | "cumulus-primitives-core/std", 36 | "frame-support/std", 37 | "parity-scale-codec/std", 38 | "sp-std/std", 39 | "staging-xcm/std", 40 | "sp-runtime/std", 41 | ] 42 | -------------------------------------------------------------------------------- /primitives/xcm-transactor/src/lib.rs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2021 Integritee AG and Supercomputing Systems AG 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | 16 | */ 17 | #![cfg_attr(not(feature = "std"), no_std)] 18 | 19 | pub use cumulus_primitives_core::ParaId; 20 | use frame_support::pallet_prelude::{Get, PhantomData}; 21 | use parity_scale_codec::{Decode, DecodeWithMemTracking, Encode, FullCodec}; 22 | use sp_runtime::RuntimeDebug; 23 | use sp_std::vec; 24 | use staging_xcm::{latest::Weight as XcmWeight, prelude::*}; 25 | 26 | pub trait BuildRelayCall { 27 | type RelayCall: FullCodec; 28 | /// Constructs the RelayCall RegistrarCall to be fed into 'construct_transact_xcm()' 29 | /// 30 | /// Params: 31 | /// - ParaIds for the parachains involved in swapping 32 | /// 33 | /// Returns: 34 | /// - constructed RelayCall to be fed to `construct_transact_xcm()` 35 | /// 36 | fn swap_call(self_para_id: ParaId, other_para_id: ParaId) -> Self::RelayCall; 37 | 38 | /// Wraps constructed Relaychain Call in an XCM message to be dispatched via 'send_xcm' 39 | /// 40 | /// Params: 41 | /// - RelayCall (Different depending on Kusama or Polkadot) 42 | /// - execution to be purchased via BuyExecution XCM Instruction 43 | /// - Weight required to execute this call. 44 | /// - Amount of execution to buy on the relay chain. This parameter is exposed because it varies 45 | /// depending on the relay chain. 46 | /// 47 | /// Returns: 48 | /// - Corresponding XCM Message for Transacting on this RelayCall 49 | fn construct_transact_xcm( 50 | call: Self::RelayCall, 51 | weight: XcmWeight, 52 | buy_execution_fee: u128, 53 | ) -> Xcm<()>; 54 | } 55 | 56 | #[derive(Encode, Decode, DecodeWithMemTracking, RuntimeDebug)] 57 | pub enum RegistrarCall { 58 | /// Corresponds to the swap extrinsic index within the Registrar Pallet 59 | #[codec(index = 3)] 60 | Swap { this: ParaId, other: ParaId }, 61 | } 62 | 63 | #[cfg(feature = "ksm")] 64 | pub mod ksm { 65 | use crate::*; 66 | #[derive(Encode, Decode, DecodeWithMemTracking, RuntimeDebug)] 67 | pub enum RelayRuntimeCall { 68 | /// Corresponds to the pallet index within the Kusama Runtime 69 | #[codec(index = 70)] 70 | Registrar(RegistrarCall), 71 | } 72 | } 73 | 74 | #[cfg(feature = "dot")] 75 | pub mod dot { 76 | use crate::*; 77 | #[derive(Encode, Decode, DecodeWithMemTracking, RuntimeDebug)] 78 | pub enum RelayRuntimeCall { 79 | /// Corresponds to the pallet index within the Polkadot Runtime 80 | #[codec(index = 70)] 81 | Registrar(RegistrarCall), 82 | } 83 | } 84 | 85 | #[cfg(all(feature = "ksm", not(feature = "dot")))] 86 | pub use ksm::*; 87 | 88 | #[cfg(feature = "dot")] 89 | pub use dot::*; 90 | 91 | pub struct RelayCallBuilder(PhantomData); 92 | impl> BuildRelayCall for RelayCallBuilder { 93 | type RelayCall = RelayRuntimeCall; 94 | 95 | fn swap_call(self_para_id: ParaId, other_para_id: ParaId) -> Self::RelayCall { 96 | Self::RelayCall::Registrar(RegistrarCall::Swap { this: self_para_id, other: other_para_id }) 97 | } 98 | 99 | fn construct_transact_xcm( 100 | call: Self::RelayCall, 101 | weight: XcmWeight, 102 | buy_execution_fee: u128, 103 | ) -> Xcm<()> { 104 | let asset: Asset = (AssetId(Location::new(1, Here)), buy_execution_fee).into(); 105 | Xcm(vec![ 106 | WithdrawAsset(asset.clone().into()), 107 | BuyExecution { fees: asset, weight_limit: Unlimited }, 108 | Transact { 109 | origin_kind: OriginKind::Native, 110 | call: call.encode().into(), 111 | fallback_max_weight: Some(weight), 112 | }, 113 | RefundSurplus, 114 | DepositAsset { 115 | assets: All.into(), 116 | beneficiary: Location::new(1, Parachain(Id::get().into())), 117 | }, 118 | ]) 119 | } 120 | } 121 | -------------------------------------------------------------------------------- /primitives/xcm/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "xcm-primitives" 3 | version = "0.0.1" 4 | edition = "2021" 5 | 6 | [lints] 7 | workspace = true 8 | 9 | [dependencies] 10 | frame-support = { workspace = true } 11 | sp-runtime = { workspace = true } 12 | sp-std = { workspace = true } 13 | 14 | 15 | staging-xcm = { workspace = true } 16 | staging-xcm-executor = { workspace = true } 17 | 18 | [features] 19 | default = ["std"] 20 | std = [ 21 | "sp-std/std", 22 | "frame-support/std", 23 | "sp-runtime/std", 24 | "staging-xcm/std", 25 | "staging-xcm-executor/std", 26 | ] 27 | -------------------------------------------------------------------------------- /primitives/xcm/src/lib.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Trappist. 2 | 3 | // Copyright (C) Parity Technologies (UK) Ltd. 4 | // SPDX-License-Identifier: Apache-2.0 5 | 6 | // Licensed under the Apache License, Version 2.0 (the "License"); 7 | // you may not use this file except in compliance with the License. 8 | // You may obtain a copy of the License at 9 | // 10 | // http://www.apache.org/licenses/LICENSE-2.0 11 | // 12 | // Unless required by applicable law or agreed to in writing, software 13 | // distributed under the License is distributed on an "AS IS" BASIS, 14 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | // See the License for the specific language governing permissions and 16 | // limitations under the License. 17 | 18 | #![cfg_attr(not(feature = "std"), no_std)] 19 | 20 | use frame_support::{ 21 | sp_runtime::SaturatedConversion, 22 | traits::{fungibles::Inspect, Currency}, 23 | weights::Weight, 24 | }; 25 | use sp_runtime::traits::MaybeEquivalence; 26 | #[cfg(not(test))] 27 | use sp_runtime::DispatchResult; 28 | use sp_std::marker::PhantomData; 29 | use staging_xcm::{ 30 | latest::{Asset, AssetId, Fungibility::Fungible, Junctions::Here, Location}, 31 | v5::XcmContext, 32 | }; 33 | use staging_xcm_executor::{ 34 | traits::{DropAssets, Error as MatchError, MatchesFungibles}, 35 | AssetsInHolding, 36 | }; 37 | 38 | pub struct AsAssetLocation(PhantomData<(AssetId, AssetIdInfoGetter)>); 39 | impl MaybeEquivalence 40 | for AsAssetLocation 41 | where 42 | AssetId: Clone, 43 | AssetIdInfoGetter: AssetLocationGetter, 44 | { 45 | fn convert(asset_location: &Location) -> Option { 46 | AssetIdInfoGetter::get_asset_id(asset_location) 47 | } 48 | 49 | fn convert_back(asset_id: &AssetId) -> Option { 50 | AssetIdInfoGetter::get_asset_location(asset_id.clone()) 51 | } 52 | } 53 | 54 | pub trait AssetLocationGetter { 55 | fn get_asset_location(asset_id: AssetId) -> Option; 56 | fn get_asset_id(asset_location: &Location) -> Option; 57 | } 58 | 59 | pub struct ConvertedRegisteredAssetId( 60 | PhantomData<(AssetId, Balance, ConvertAssetId, ConvertBalance)>, 61 | ); 62 | impl< 63 | AssetId: Clone, 64 | Balance: Clone, 65 | ConvertAssetId: MaybeEquivalence, 66 | ConvertBalance: MaybeEquivalence, 67 | > MatchesFungibles 68 | for ConvertedRegisteredAssetId 69 | { 70 | fn matches_fungibles(a: &Asset) -> Result<(AssetId, Balance), MatchError> { 71 | let (amount, id) = match (&a.fun, &a.id) { 72 | (Fungible(ref amount), AssetId(id)) => (amount, id), 73 | _ => return Err(MatchError::AssetNotHandled), 74 | }; 75 | let what = ConvertAssetId::convert(id).ok_or(MatchError::AssetNotHandled)?; 76 | let amount = ConvertBalance::convert_back(amount) 77 | .ok_or(MatchError::AmountToBalanceConversionFailed)?; 78 | Ok((what, amount)) 79 | } 80 | } 81 | 82 | pub trait DropAssetsWeigher { 83 | fn fungible() -> Weight; 84 | fn native() -> Weight; 85 | fn default() -> Weight; 86 | } 87 | 88 | pub struct IntegriteeDropAssets< 89 | AssetId, 90 | AssetIdInfoGetter, 91 | AssetsPallet, 92 | BalancesPallet, 93 | XcmPallet, 94 | AccountId, 95 | Weigher, 96 | >( 97 | PhantomData<( 98 | AssetId, 99 | AssetIdInfoGetter, 100 | AssetsPallet, 101 | BalancesPallet, 102 | XcmPallet, 103 | AccountId, 104 | Weigher, 105 | )>, 106 | ); 107 | 108 | impl 109 | DropAssets 110 | for IntegriteeDropAssets< 111 | AssetId, 112 | AssetIdInfoGetter, 113 | AssetsPallet, 114 | BalancesPallet, 115 | XcmPallet, 116 | AccountId, 117 | Weigher, 118 | > 119 | where 120 | AssetIdInfoGetter: AssetLocationGetter, 121 | AssetsPallet: Inspect, 122 | BalancesPallet: Currency, 123 | XcmPallet: DropAssets, 124 | Weigher: DropAssetsWeigher, 125 | { 126 | // assets are whatever the Holding Register had when XCVM halts 127 | fn drop_assets(origin: &Location, mut assets: AssetsInHolding, context: &XcmContext) -> Weight { 128 | const NATIVE_LOCATION: Location = Location { parents: 0, interior: Here }; 129 | 130 | let mut weight: Weight = { 131 | assets.non_fungible.clear(); 132 | Weigher::default() 133 | }; 134 | 135 | assets.fungible.retain(|id, &mut amount| { 136 | let location = &id.0; 137 | 138 | match AssetIdInfoGetter::get_asset_id(location) { 139 | Some(asset_id) => { 140 | weight.saturating_accrue(Weigher::fungible()); 141 | 142 | // only trap if amount ≥ min_balance 143 | // do nothing otherwise (asset is lost) 144 | amount.saturated_into::() >= 145 | AssetsPallet::minimum_balance(asset_id) 146 | }, 147 | None => { 148 | weight.saturating_accrue(Weigher::native()); 149 | 150 | // only trap if native token and amount ≥ min_balance 151 | // do nothing otherwise (asset is lost) 152 | *location == NATIVE_LOCATION && 153 | amount.saturated_into::() >= 154 | BalancesPallet::minimum_balance() 155 | }, 156 | } 157 | }); 158 | 159 | // we have filtered out non-compliant assets 160 | // insert valid assets into the asset trap implemented by XcmPallet 161 | weight.saturating_add(XcmPallet::drop_assets(origin, assets, context)) 162 | } 163 | } 164 | 165 | /// Pause and resume execution of XCM 166 | #[cfg(not(test))] 167 | pub trait PauseXcmExecution { 168 | fn suspend_xcm_execution() -> DispatchResult; 169 | fn resume_xcm_execution() -> DispatchResult; 170 | } 171 | #[cfg(not(test))] 172 | impl PauseXcmExecution for () { 173 | fn suspend_xcm_execution() -> DispatchResult { 174 | Ok(()) 175 | } 176 | fn resume_xcm_execution() -> DispatchResult { 177 | Ok(()) 178 | } 179 | } 180 | -------------------------------------------------------------------------------- /rust-toolchain.toml: -------------------------------------------------------------------------------- 1 | [toolchain] 2 | channel = "1.84.1" 3 | targets = ["wasm32v1-none"] 4 | profile = "default" # include rustfmt, clippy 5 | -------------------------------------------------------------------------------- /rustfmt.toml: -------------------------------------------------------------------------------- 1 | # Basic 2 | hard_tabs = true 3 | max_width = 100 4 | use_small_heuristics = "Max" 5 | # Imports 6 | imports_granularity = "Crate" 7 | reorder_imports = true 8 | # Consistency 9 | newline_style = "Unix" 10 | # Misc 11 | chain_width = 80 12 | spaces_around_ranges = false 13 | binop_separator = "Back" 14 | reorder_impl_items = false 15 | match_arm_leading_pipes = "Preserve" 16 | match_arm_blocks = false 17 | match_block_trailing_comma = true 18 | trailing_comma = "Vertical" 19 | trailing_semicolon = false 20 | use_field_init_shorthand = true 21 | -------------------------------------------------------------------------------- /scripts/run_for_all_no_std_crates.sh: -------------------------------------------------------------------------------- 1 | find . -name "Cargo.toml" | while read -r CARGO_TOML; do 2 | DIR=$(dirname "$CARGO_TOML") 3 | echo "Checking in directory: $DIR" 4 | 5 | # Skip the loop if the crate does not have a feature `std` 6 | if ! grep -q "\[features\]" "$CARGO_TOML" || ! grep -q "std = \[" "$CARGO_TOML"; then 7 | echo "Feature 'std' not found in $CARGO_TOML. Skipping." 8 | continue 9 | fi 10 | 11 | if grep -q "runtime-benchmarks = \[" "$CARGO_TOML"; then 12 | if grep -q "ksm = \[" "$CARGO_TOML"; then 13 | echo "Features 'runtime-benchmarks' and 'ksm' found, adding both features." 14 | cargo $COMMAND $@ --features "runtime-benchmarks ksm" --manifest-path "$CARGO_TOML" 15 | else 16 | echo "Feature 'runtime-benchmarks' found, adding this feature." 17 | cargo $COMMAND $@ --features runtime-benchmarks --manifest-path "$CARGO_TOML" 18 | fi 19 | else 20 | if grep -q "ksm = \[" "$CARGO_TOML"; then 21 | echo "Feature 'ksm' found, adding this feature." 22 | cargo $COMMAND $@ --features ksm --manifest-path "$CARGO_TOML" 23 | else 24 | echo "No relevant features found, running command without additional features." 25 | cargo $COMMAND $@ --manifest-path "$CARGO_TOML" 26 | fi 27 | fi 28 | done 29 | -------------------------------------------------------------------------------- /sidechain/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "pallet-sidechain" 3 | description = "Pallet for integritee sidechains" 4 | version = "0.11.0" 5 | authors = ["Integritee AG "] 6 | homepage = "https://integritee.network/" 7 | repository = "https://github.com/integritee-network/pallets/" 8 | license = "MS-RSL" 9 | edition = "2021" 10 | 11 | [lints] 12 | workspace = true 13 | 14 | [dependencies] 15 | log = { workspace = true } 16 | parity-scale-codec = { workspace = true, features = ["full"] } 17 | scale-info = { workspace = true } 18 | serde = { workspace = true, optional = true } 19 | 20 | # local 21 | enclave-bridge-primitives = { path = "../primitives/enclave-bridge", default-features = false } 22 | pallet-enclave-bridge = { path = "../enclave-bridge", default-features = false } 23 | pallet-teerex = { path = "../teerex", default-features = false } 24 | sidechain-primitives = { path = "../primitives/sidechain", default-features = false } 25 | 26 | # substrate dependencies 27 | frame-support = { workspace = true } 28 | frame-system = { workspace = true } 29 | pallet-timestamp = { workspace = true } 30 | sp-core = { workspace = true } 31 | sp-io = { workspace = true } 32 | sp-runtime = { workspace = true } 33 | sp-std = { workspace = true } 34 | 35 | # benchmarking 36 | frame-benchmarking = { workspace = true, optional = true } 37 | hex-literal = { workspace = true, optional = true } 38 | pallet-balances = { workspace = true, optional = true } 39 | teerex-primitives = { path = "../primitives/teerex", default-features = false } 40 | test-utils = { default-features = false, path = "../test-utils", optional = true } 41 | 42 | [dev-dependencies] 43 | env_logger = { workspace = true } 44 | sp-externalities = { workspace = true } 45 | frame-benchmarking = { workspace = true, features = ["std"] } 46 | hex-literal = { workspace = true } 47 | pallet-balances = { workspace = true, features = ["std"] } 48 | sp-keyring = { workspace = true } 49 | test-utils = { path = "../test-utils" } 50 | 51 | [features] 52 | default = ["std"] 53 | std = [ 54 | "enclave-bridge-primitives/std", 55 | "frame-benchmarking?/std", 56 | "frame-support/std", 57 | "frame-system/std", 58 | "log/std", 59 | "pallet-enclave-bridge/std", 60 | "pallet-teerex/std", 61 | "pallet-timestamp/std", 62 | "parity-scale-codec/std", 63 | "scale-info/std", 64 | "serde/std", 65 | "sidechain-primitives/std", 66 | "sp-core/std", 67 | "sp-io/std", 68 | "sp-runtime/std", 69 | "sp-std/std", 70 | "teerex-primitives/std", 71 | "pallet-balances?/std", 72 | "sp-externalities/std", 73 | "sp-keyring/std", 74 | ] 75 | runtime-benchmarks = [ 76 | "frame-benchmarking/runtime-benchmarks", 77 | "hex-literal", 78 | "pallet-balances", 79 | "pallet-timestamp/runtime-benchmarks", 80 | "test-utils", 81 | "pallet-enclave-bridge/runtime-benchmarks", 82 | "pallet-teerex/runtime-benchmarks", 83 | "frame-support/runtime-benchmarks", 84 | "frame-system/runtime-benchmarks", 85 | "pallet-balances?/runtime-benchmarks", 86 | "sp-runtime/runtime-benchmarks", 87 | ] 88 | 89 | try-runtime = [ 90 | "frame-support/try-runtime", 91 | "pallet-enclave-bridge/try-runtime", 92 | "pallet-teerex/try-runtime", 93 | "frame-system/try-runtime", 94 | "pallet-balances?/try-runtime", 95 | "pallet-timestamp/try-runtime", 96 | "sp-runtime/try-runtime", 97 | ] 98 | -------------------------------------------------------------------------------- /sidechain/LICENSE: -------------------------------------------------------------------------------- 1 | MICROSOFT REFERENCE SOURCE LICENSE (MS-RSL) 2 | 3 | This license governs use of the accompanying software. If you use the software, you accept this license. If you do not accept the license, do not use the software. 4 | 5 | 1. Definitions 6 | The terms "reproduce," "reproduction" and "distribution" have the same meaning here as under U.S. copyright law. 7 | 8 | "You" means the licensee of the software. 9 | 10 | "Your company" means the company you worked for when you downloaded the software. 11 | 12 | "Reference use" means use of the software within your company as a reference, in read only form, for the sole purposes of debugging your products, maintaining your products, or enhancing the interoperability of your products with the software, and specifically excludes the right to distribute the software outside of your company. 13 | 14 | "Licensed patents" means any Licensor patent claims which read directly on the software as distributed by the Licensor under this license. 15 | 16 | 2. Grant of Rights 17 | (A) Copyright Grant- Subject to the terms of this license, the Licensor grants you a non-transferable, non-exclusive, worldwide, royalty-free copyright license to reproduce the software for reference use. 18 | 19 | (B) Patent Grant- Subject to the terms of this license, the Licensor grants you a non-transferable, non-exclusive, worldwide, royalty-free patent license under licensed patents for reference use. 20 | 21 | 3. Limitations 22 | (A) No Trademark License- This license does not grant you any rights to use the Licensor's name, logo, or trademarks. 23 | 24 | (B) If you begin patent litigation against the Licensor over patents that you think may apply to the software (including a cross-claim or counterclaim in a lawsuit), your license to the software ends automatically. 25 | 26 | (C) The software is licensed "as-is." You bear the risk of using it. The Licensor gives no express warranties, guarantees or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent permitted under your local laws, the Licensor excludes the implied warranties of merchantability, fitness for a particular purpose and non-infringement. 27 | -------------------------------------------------------------------------------- /sidechain/README.md: -------------------------------------------------------------------------------- 1 | # pallet-sidechain 2 | 3 | Please note this pallet has a different [license](./LICENSE) than the rest of this repository: MS-RSL 4 | 5 | A pallet for [Integritee](https://integritee.network) which provides functionality for handling and finalizing sidechain blocks. 6 | -------------------------------------------------------------------------------- /sidechain/src/benchmarking.rs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2021 Integritee AG and Supercomputing Systems AG 3 | 4 | Licensed under the MICROSOFT REFERENCE SOURCE LICENSE (MS-RSL) (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | https://referencesource.microsoft.com/license.html 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | 16 | */ 17 | 18 | //! Sidechain pallet benchmarking 19 | 20 | #![cfg(any(test, feature = "runtime-benchmarks"))] 21 | 22 | use super::*; 23 | use frame_benchmarking::{account, benchmarks}; 24 | use frame_system::RawOrigin; 25 | use pallet_teerex::Pallet as Teerex; 26 | use parity_scale_codec::Encode; 27 | use test_utils::test_data::ias::*; 28 | 29 | fn assert_latest_worker_update(sender: &T::AccountId, shard: &ShardIdentifier) { 30 | assert_eq!(EnclaveBridge::::most_recent_shard_update(shard).unwrap().signer, *sender); 31 | } 32 | 33 | fn generate_accounts(amount: u32) -> Vec { 34 | (0..amount).map(|n| account("dummy name", n, n)).collect() 35 | } 36 | 37 | fn add_enclaves_to_registry(accounts: &[T::AccountId]) { 38 | for a in accounts.iter() { 39 | Teerex::::add_enclave( 40 | a, 41 | MultiEnclave::from( 42 | SgxEnclave::test_enclave() 43 | .with_pubkey(&a.encode()) 44 | .with_mr_enclave(TEST4_SETUP.mrenclave), 45 | ), 46 | ) 47 | .unwrap(); 48 | } 49 | } 50 | 51 | benchmarks! { 52 | // Benchmark `confirm_imported_sidechain_block` with the worst possible conditions: 53 | // * sender enclave is registered 54 | confirm_imported_sidechain_block { 55 | let accounts: Vec = generate_accounts::(1); 56 | add_enclaves_to_registry::(&accounts); 57 | 58 | let shard: ShardIdentifier = H256::from_slice(&TEST4_SETUP.mrenclave); 59 | let ancestor = SidechainBlockConfirmation { 60 | block_number: 2, 61 | block_header_hash: [2; 32].into() 62 | }; 63 | let candidate = SidechainBlockConfirmation { 64 | block_number: 25, 65 | block_header_hash: [25; 32].into() 66 | }; 67 | }: _(RawOrigin::Signed(accounts[0].clone()), shard, Some(ancestor), candidate) 68 | verify { 69 | assert_latest_worker_update::(&accounts[0], &shard) 70 | } 71 | } 72 | 73 | #[cfg(test)] 74 | use crate::{Config, Pallet as PalletModule}; 75 | 76 | #[cfg(test)] 77 | use frame_benchmarking::impl_benchmark_test_suite; 78 | use teerex_primitives::{MultiEnclave, SgxEnclave}; 79 | use test_utils::TestEnclave; 80 | 81 | #[cfg(test)] 82 | impl_benchmark_test_suite!(PalletModule, crate::mock::new_test_ext(), crate::mock::Test,); 83 | -------------------------------------------------------------------------------- /sidechain/src/lib.rs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2021 Integritee AG and Supercomputing Systems AG 3 | 4 | Licensed under the MICROSOFT REFERENCE SOURCE LICENSE (MS-RSL) (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | https://referencesource.microsoft.com/license.html 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | 16 | */ 17 | 18 | #![cfg_attr(not(feature = "std"), no_std)] 19 | 20 | use enclave_bridge_primitives::ShardIdentifier; 21 | use frame_support::dispatch::DispatchResultWithPostInfo; 22 | use frame_system::{self}; 23 | use pallet_enclave_bridge::Pallet as EnclaveBridge; 24 | use sidechain_primitives::{SidechainBlockConfirmation, SidechainBlockNumber}; 25 | use sp_core::H256; 26 | use sp_std::{prelude::*, str, vec}; 27 | 28 | pub use crate::weights::WeightInfo; 29 | 30 | // Disambiguate associated types 31 | pub type AccountId = ::AccountId; 32 | pub type ShardAndBlockNumber = (ShardIdentifier, SidechainBlockNumber); 33 | 34 | pub use pallet::*; 35 | 36 | #[frame_support::pallet] 37 | pub mod pallet { 38 | use super::*; 39 | use frame_support::pallet_prelude::*; 40 | use frame_system::pallet_prelude::*; 41 | 42 | #[pallet::pallet] 43 | #[pallet::without_storage_info] 44 | pub struct Pallet(PhantomData); 45 | 46 | #[pallet::hooks] 47 | impl Hooks> for Pallet {} 48 | 49 | #[pallet::config] 50 | pub trait Config: 51 | frame_system::Config + pallet_teerex::Config + pallet_enclave_bridge::Config 52 | { 53 | type RuntimeEvent: From> + IsType<::RuntimeEvent>; 54 | type WeightInfo: WeightInfo; 55 | } 56 | 57 | #[pallet::event] 58 | #[pallet::generate_deposit(pub(super) fn deposit_event)] 59 | pub enum Event { 60 | /// a sidechain block has been finalized 61 | FinalizedSidechainBlock { 62 | shard: ShardIdentifier, 63 | block_number: SidechainBlockNumber, 64 | block_header_hash: H256, 65 | validateer: T::AccountId, 66 | }, 67 | } 68 | 69 | #[pallet::error] 70 | pub enum Error { 71 | /// A proposed finalization candidate block is outdated 72 | FinalizationCandidateIsOutdated, 73 | /// The provided last finalized ancestor block number doesn't match. 74 | /// This can mean a fork happened or the sender validateer is not up to date with L1 75 | AncestorNumberMismatch, 76 | /// The provided last finalized ancestor block hash doesn't match. 77 | /// This can mean a fork happened or the sender validateer is not up to date with L1 78 | AncestorHashMismatch, 79 | /// sender hasn't provided an ancestor although an ancestor has been finalized 80 | AncestorMissing, 81 | } 82 | 83 | #[pallet::storage] 84 | #[pallet::getter(fn latest_sidechain_block_confirmation)] 85 | pub type LatestSidechainBlockConfirmation = 86 | StorageMap<_, Blake2_128Concat, ShardIdentifier, SidechainBlockConfirmation, OptionQuery>; 87 | 88 | #[pallet::call] 89 | impl Pallet { 90 | /// The integritee worker calls this function for every imported sidechain_block. 91 | #[pallet::call_index(0)] 92 | #[pallet::weight((::WeightInfo::confirm_imported_sidechain_block(), DispatchClass::Normal, Pays::Yes))] 93 | pub fn confirm_imported_sidechain_block( 94 | origin: OriginFor, 95 | shard: ShardIdentifier, 96 | latest_finalized_ancestor: Option, 97 | finalization_candidate: SidechainBlockConfirmation, 98 | ) -> DispatchResultWithPostInfo { 99 | let sender = ensure_signed(origin)?; 100 | let (_enclave, shard_status) = 101 | EnclaveBridge::::get_sovereign_enclave_and_touch_shard( 102 | &sender, 103 | shard, 104 | >::block_number(), 105 | )?; 106 | 107 | // TODO: Simple but robust logic for now: 108 | // https://github.com/integritee-network/pallets/issues/254 109 | // accept only blocks from first validateer in shard_status 110 | if sender != shard_status[0].signer { 111 | log::debug!( 112 | "Ignore block confirmation from registered enclave with index > 1: {:?}", 113 | sender 114 | ); 115 | return Ok(().into()); 116 | } 117 | 118 | if let Some(known_ancestor) = Self::latest_sidechain_block_confirmation(shard) { 119 | let provided_ancestor = 120 | latest_finalized_ancestor.ok_or(Error::::AncestorMissing)?; 121 | ensure!( 122 | finalization_candidate.block_number > known_ancestor.block_number, 123 | >::FinalizationCandidateIsOutdated 124 | ); 125 | ensure!( 126 | known_ancestor.block_number == provided_ancestor.block_number, 127 | >::AncestorNumberMismatch 128 | ); 129 | ensure!( 130 | known_ancestor.block_header_hash == provided_ancestor.block_header_hash, 131 | >::AncestorHashMismatch 132 | ); 133 | } 134 | Self::finalize_block(shard, finalization_candidate, &sender); 135 | Ok(().into()) 136 | } 137 | } 138 | } 139 | 140 | impl Pallet { 141 | fn finalize_block( 142 | shard: ShardIdentifier, 143 | confirmation: SidechainBlockConfirmation, 144 | sender: &T::AccountId, 145 | ) { 146 | >::insert(shard, confirmation); 147 | let block_header_hash = confirmation.block_header_hash; 148 | let block_number = confirmation.block_number; 149 | log::debug!( 150 | "Imported sidechain block {} confirmed with shard {:?}, block header hash {:?}", 151 | block_number, 152 | shard, 153 | block_header_hash 154 | ); 155 | Self::deposit_event(Event::FinalizedSidechainBlock { 156 | shard, 157 | block_number, 158 | block_header_hash, 159 | validateer: sender.clone(), 160 | }); 161 | } 162 | } 163 | 164 | mod benchmarking; 165 | #[cfg(test)] 166 | mod mock; 167 | #[cfg(test)] 168 | mod tests; 169 | pub mod weights; 170 | -------------------------------------------------------------------------------- /sidechain/src/mock.rs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2021 Integritee AG and Supercomputing Systems AG 3 | 4 | Licensed under the MICROSOFT REFERENCE SOURCE LICENSE (MS-RSL) (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | https://referencesource.microsoft.com/license.html 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | 16 | */ 17 | 18 | // Creating mock runtime here 19 | use crate as pallet_sidechain; 20 | use frame_support::{derive_impl, parameter_types}; 21 | use frame_system as system; 22 | use pallet_sidechain::Config; 23 | use sp_core::H256; 24 | use sp_keyring::Sr25519Keyring as Keyring; 25 | use sp_runtime::{ 26 | generic, 27 | traits::{BlakeTwo256, IdentifyAccount, IdentityLookup, Verify}, 28 | BuildStorage, 29 | }; 30 | 31 | pub type Signature = sp_runtime::MultiSignature; 32 | pub type AccountId = <::Signer as IdentifyAccount>::AccountId; 33 | pub type Address = sp_runtime::MultiAddress; 34 | 35 | pub type BlockNumber = u32; 36 | pub type Header = generic::Header; 37 | pub type UncheckedExtrinsic = 38 | generic::UncheckedExtrinsic; 39 | 40 | pub type SignedExtra = ( 41 | frame_system::CheckSpecVersion, 42 | frame_system::CheckTxVersion, 43 | frame_system::CheckGenesis, 44 | frame_system::CheckEra, 45 | frame_system::CheckNonce, 46 | frame_system::CheckWeight, 47 | ); 48 | 49 | frame_support::construct_runtime!( 50 | pub enum Test 51 | { 52 | System: frame_system::{Pallet, Call, Config, Storage, Event}, 53 | Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, 54 | Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent}, 55 | Teerex: pallet_teerex::{Pallet, Call, Storage, Event}, 56 | EnclaveBridge: pallet_enclave_bridge::{Pallet, Call, Storage, Event}, 57 | Sidechain: pallet_sidechain::{Pallet, Call, Storage, Event}, 58 | } 59 | ); 60 | 61 | parameter_types! { 62 | pub const BlockHashCount: u32 = 250; 63 | } 64 | #[derive_impl(frame_system::config_preludes::SolochainDefaultConfig as frame_system::DefaultConfig)] 65 | impl frame_system::Config for Test { 66 | type BaseCallFilter = frame_support::traits::Everything; 67 | type BlockWeights = (); 68 | type BlockLength = (); 69 | type Block = generic::Block; 70 | type DbWeight = (); 71 | type RuntimeOrigin = RuntimeOrigin; 72 | type Nonce = u64; 73 | type RuntimeCall = RuntimeCall; 74 | type RuntimeTask = RuntimeTask; 75 | type Hash = H256; 76 | type Hashing = BlakeTwo256; 77 | type AccountId = AccountId; 78 | type Lookup = IdentityLookup; 79 | type RuntimeEvent = RuntimeEvent; 80 | type BlockHashCount = BlockHashCount; 81 | type Version = (); 82 | type PalletInfo = PalletInfo; 83 | type AccountData = pallet_balances::AccountData; 84 | type OnNewAccount = (); 85 | type OnKilledAccount = (); 86 | type SystemWeightInfo = (); 87 | type SS58Prefix = (); 88 | type OnSetCode = (); 89 | type MaxConsumers = frame_support::traits::ConstU32<16>; 90 | } 91 | 92 | pub type Balance = u64; 93 | 94 | parameter_types! { 95 | pub const ExistentialDeposit: u64 = 1; 96 | } 97 | 98 | impl pallet_balances::Config for Test { 99 | type MaxLocks = (); 100 | type Balance = u64; 101 | type DustRemoval = (); 102 | type RuntimeEvent = RuntimeEvent; 103 | type ExistentialDeposit = ExistentialDeposit; 104 | type AccountStore = System; 105 | type WeightInfo = (); 106 | type MaxReserves = (); 107 | type ReserveIdentifier = (); 108 | type RuntimeFreezeReason = (); 109 | type FreezeIdentifier = (); 110 | type MaxFreezes = (); 111 | type RuntimeHoldReason = (); 112 | type DoneSlashHandler = (); 113 | } 114 | 115 | parameter_types! { 116 | pub const MinimumPeriod: u64 = 6000 / 2; 117 | } 118 | 119 | pub type Moment = u64; 120 | 121 | impl pallet_timestamp::Config for Test { 122 | type Moment = Moment; 123 | type OnTimestampSet = (); 124 | type MinimumPeriod = MinimumPeriod; 125 | type WeightInfo = (); 126 | } 127 | 128 | parameter_types! { 129 | pub const MaxWhitelistedReleases: u32 = 10; 130 | } 131 | 132 | impl pallet_teerex::Config for Test { 133 | type RuntimeEvent = RuntimeEvent; 134 | type MomentsPerDay = MomentsPerDay; 135 | type WeightInfo = (); 136 | type MaxAttestationRenewalPeriod = MaxAttestationRenewalPeriod; 137 | } 138 | 139 | impl pallet_enclave_bridge::Config for Test { 140 | type RuntimeEvent = RuntimeEvent; 141 | type Currency = Balances; 142 | type WeightInfo = (); 143 | } 144 | 145 | parameter_types! { 146 | pub const MomentsPerDay: u64 = 86_400_000; // [ms/d] 147 | pub const MaxAttestationRenewalPeriod: u64 = 172_800_000; // 48h 148 | } 149 | 150 | impl Config for Test { 151 | type RuntimeEvent = RuntimeEvent; 152 | type WeightInfo = (); 153 | } 154 | 155 | // This function basically just builds a genesis storage key/value store according to 156 | // our desired mockup. RA from enclave compiled in debug mode is allowed 157 | pub fn new_test_ext() -> sp_io::TestExternalities { 158 | let mut t = system::GenesisConfig::::default().build_storage().unwrap(); 159 | pallet_balances::GenesisConfig:: { 160 | balances: vec![(Keyring::Alice.to_account_id(), 1 << 60)], 161 | ..Default::default() 162 | } 163 | .assimilate_storage(&mut t) 164 | .unwrap(); 165 | pallet_teerex::GenesisConfig:: { 166 | allow_sgx_debug_mode: true, 167 | allow_skipping_attestation: true, 168 | _config: Default::default(), 169 | } 170 | .assimilate_storage(&mut t) 171 | .unwrap(); 172 | 173 | let mut ext: sp_io::TestExternalities = t.into(); 174 | ext.execute_with(|| System::set_block_number(1)); 175 | ext 176 | } 177 | -------------------------------------------------------------------------------- /sidechain/src/weights.rs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2021 Integritee AG and Supercomputing Systems AG 3 | 4 | Licensed under the MICROSOFT REFERENCE SOURCE LICENSE (MS-RSL) (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | https://referencesource.microsoft.com/license.html 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | 16 | */ 17 | 18 | use frame_support::{ 19 | traits::Get, 20 | weights::{constants::RocksDbWeight, Weight}, 21 | }; 22 | use sp_std::marker::PhantomData; 23 | 24 | /// Weight functions needed for pallet_sidechain. 25 | pub trait WeightInfo { 26 | fn confirm_imported_sidechain_block() -> Weight; 27 | } 28 | 29 | /// Weights for pallet_sidechain using the Integritee parachain node and recommended hardware. 30 | pub struct IntegriteeWeight(PhantomData); 31 | impl WeightInfo for IntegriteeWeight { 32 | fn confirm_imported_sidechain_block() -> Weight { 33 | Weight::from_parts(46_200_000, 0u64) 34 | .saturating_add(T::DbWeight::get().reads(1)) 35 | .saturating_add(T::DbWeight::get().writes(2)) 36 | } 37 | } 38 | 39 | // For tests 40 | impl WeightInfo for () { 41 | fn confirm_imported_sidechain_block() -> Weight { 42 | Weight::from_parts(46_200_000, 0u64) 43 | .saturating_add(RocksDbWeight::get().reads(1)) 44 | .saturating_add(RocksDbWeight::get().writes(2)) 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /teeracle/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "pallet-teeracle" 3 | description = "A pallet to store cryptocurrency market data" 4 | version = "0.1.0" 5 | authors = ["Integritee AG "] 6 | homepage = "https://integritee.network/" 7 | repository = "https://github.com/integritee-network/pallets/" 8 | license = "Apache-2.0" 9 | edition = "2021" 10 | 11 | [lints] 12 | workspace = true 13 | 14 | [dependencies] 15 | log = { workspace = true } 16 | parity-scale-codec = { workspace = true } 17 | scale-info = { workspace = true } 18 | 19 | # local 20 | pallet-teerex = { path = "../teerex", default-features = false } 21 | teeracle-primitives = { path = "../primitives/teeracle", default-features = false } 22 | teerex-primitives = { path = "../primitives/teerex", default-features = false } 23 | 24 | # encointer 25 | substrate-fixed = { workspace = true } 26 | 27 | # substrate 28 | frame-support = { workspace = true } 29 | frame-system = { workspace = true } 30 | sp-core = { workspace = true } 31 | sp-io = { workspace = true } 32 | sp-runtime = { workspace = true } 33 | sp-std = { workspace = true } 34 | 35 | # benchmarking 36 | frame-benchmarking = { workspace = true, optional = true } 37 | hex-literal = { workspace = true, optional = true } 38 | pallet-aura = { workspace = true, optional = true } 39 | pallet-timestamp = { workspace = true, optional = true } 40 | sp-consensus-aura = { workspace = true, optional = true } 41 | test-utils = { default-features = false, path = "../test-utils", optional = true } 42 | 43 | [dev-dependencies] 44 | frame-benchmarking = { workspace = true, features = ["std"] } 45 | hex-literal = { workspace = true } 46 | pallet-aura = { workspace = true } 47 | pallet-balances = { workspace = true, features = ["std"] } 48 | pallet-timestamp = { workspace = true } 49 | sp-consensus-aura = { workspace = true } 50 | sp-externalities = { workspace = true } 51 | sp-keyring = { workspace = true } 52 | test-utils = { path = "../test-utils" } 53 | 54 | 55 | [features] 56 | default = ["std"] 57 | std = [ 58 | "frame-benchmarking?/std", 59 | "frame-support/std", 60 | "frame-system/std", 61 | "log/std", 62 | "pallet-teerex/std", 63 | "parity-scale-codec/std", 64 | "scale-info/std", 65 | "sp-consensus-aura?/std", 66 | "sp-core/std", 67 | "sp-io/std", 68 | "sp-runtime/std", 69 | "sp-std/std", 70 | "substrate-fixed/std", 71 | "teeracle-primitives/std", 72 | "teerex-primitives/std", 73 | "pallet-aura?/std", 74 | "pallet-balances/std", 75 | "pallet-timestamp?/std", 76 | "sp-externalities/std", 77 | "sp-keyring/std", 78 | ] 79 | runtime-benchmarks = [ 80 | "frame-benchmarking/runtime-benchmarks", 81 | "hex-literal", 82 | "pallet-timestamp/runtime-benchmarks", 83 | "pallet-aura", 84 | "test-utils", 85 | "pallet-teerex/runtime-benchmarks", 86 | "frame-support/runtime-benchmarks", 87 | "frame-system/runtime-benchmarks", 88 | "pallet-balances/runtime-benchmarks", 89 | "sp-consensus-aura", 90 | "sp-runtime/runtime-benchmarks", 91 | ] 92 | 93 | try-runtime = [ 94 | "frame-support/try-runtime", 95 | "pallet-teerex/try-runtime", 96 | "frame-system/try-runtime", 97 | "pallet-aura?/try-runtime", 98 | "pallet-balances/try-runtime", 99 | "pallet-timestamp?/try-runtime", 100 | "sp-runtime/try-runtime", 101 | ] 102 | -------------------------------------------------------------------------------- /teeracle/README.md: -------------------------------------------------------------------------------- 1 | # pallet-teeracle 2 | 3 | A pallet for [Integritee](https://integritee.network) which provides functionality for handling exchange rates of the coin (ex: TEER) to different currencies 4 | -------------------------------------------------------------------------------- /teeracle/src/benchmarking.rs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2021 Integritee AG and Supercomputing Systems AG 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | 16 | */ 17 | 18 | //! Teeracle pallet benchmarking 19 | 20 | #![cfg(any(test, feature = "runtime-benchmarks"))] 21 | 22 | use super::*; 23 | 24 | use crate::Pallet as Teeracle; 25 | use frame_benchmarking::benchmarks; 26 | use frame_system::RawOrigin; 27 | use pallet_teerex::Pallet as Teerex; 28 | use sp_runtime::traits::CheckedConversion; 29 | use sp_std::prelude::*; 30 | use teeracle_primitives::{DataSource, OracleDataName, TradingPairString}; 31 | use teerex_primitives::SgxAttestationMethod; 32 | 33 | use test_utils::{ 34 | get_signer, 35 | test_data::{consts::*, ias::*}, 36 | }; 37 | 38 | benchmarks! { 39 | where_clause { 40 | where 41 | T::AccountId: From<[u8; 32]>, 42 | T::Hash: From<[u8; 32]>, 43 | T: pallet_aura::Config, 44 | T::Moment: CheckedConversion, 45 | } 46 | update_exchange_rate { 47 | as StorageValue>::put(Slot::from(TEST4_SETUP.timestamp.saturating_div(T::SlotDuration::get().checked_into().unwrap()))); 48 | pallet_timestamp::Pallet::::set_timestamp(TEST4_SETUP.timestamp.checked_into().unwrap()); 49 | let signer: T::AccountId = get_signer(TEST4_SETUP.signer_pub); 50 | let trading_pair: TradingPairString = "DOT/USD".into(); 51 | let rate = U32F32::from_num(43.65); 52 | let data_source: DataSource = "https://api.coingecko.com".into(); 53 | // simply register the enclave before to make sure it already 54 | // exists when running the benchmark 55 | Teerex::::register_sgx_enclave( 56 | RawOrigin::Signed(signer.clone()).into(), 57 | TEST4_SETUP.cert.to_vec(), 58 | Some(URL.to_vec()), 59 | SgxAttestationMethod::Ias, 60 | ).unwrap(); 61 | let fingerprint = Teerex::::sovereign_enclaves(&signer).unwrap().fingerprint(); 62 | Teeracle::::add_to_whitelist(RawOrigin::Root.into(), data_source.clone(), fingerprint).unwrap(); 63 | 64 | }: _(RawOrigin::Signed(signer), data_source.clone(), trading_pair.clone(), Some(rate)) 65 | verify { 66 | assert_eq!(Teeracle::::exchange_rate(trading_pair, data_source), U32F32::from_num(43.65)); 67 | } 68 | 69 | update_oracle { 70 | as StorageValue>::put(Slot::from(TEST4_SETUP.timestamp.saturating_div(T::SlotDuration::get().checked_into().unwrap()))); 71 | pallet_timestamp::Pallet::::set_timestamp(TEST4_SETUP.timestamp.checked_into().unwrap()); 72 | let signer: T::AccountId = get_signer(TEST4_SETUP.signer_pub); 73 | let oracle_name = OracleDataName::from("Test_Oracle_Name"); 74 | let data_source = DataSource::from("Test_Source_Name"); 75 | let oracle_blob: crate::OracleDataBlob = 76 | vec![1].try_into().expect("Can Convert to OracleDataBlob; QED"); 77 | // simply register the enclave before to make sure it already 78 | // exists when running the benchmark 79 | Teerex::::register_sgx_enclave( 80 | RawOrigin::Signed(signer.clone()).into(), 81 | TEST4_SETUP.cert.to_vec(), 82 | Some(URL.to_vec()), 83 | SgxAttestationMethod::Ias, 84 | ).unwrap(); 85 | let fingerprint = Teerex::::sovereign_enclaves(&signer).unwrap().fingerprint(); 86 | Teeracle::::add_to_whitelist(RawOrigin::Root.into(), data_source.clone(), fingerprint).unwrap(); 87 | }: _(RawOrigin::Signed(signer), oracle_name.clone(), data_source.clone(), oracle_blob.clone()) 88 | verify { 89 | assert_eq!(Teeracle::::oracle_data(oracle_name, data_source), oracle_blob); 90 | } 91 | 92 | add_to_whitelist { 93 | let fingerprint = EnclaveFingerprint::from(TEST4_MRENCLAVE); 94 | let data_source: DataSource = "https://api.coingecko.com".into(); 95 | 96 | }: _(RawOrigin::Root, data_source.clone(), fingerprint) 97 | verify { 98 | assert_eq!(Teeracle::::whitelist(data_source).len(), 1, "mrenclave not added to whitelist") 99 | } 100 | 101 | remove_from_whitelist { 102 | let fingerprint = EnclaveFingerprint::from(TEST4_MRENCLAVE); 103 | let data_source: DataSource = "https://api.coingecko.com".into(); 104 | 105 | Teeracle::::add_to_whitelist(RawOrigin::Root.into(), data_source.clone(), fingerprint).unwrap(); 106 | 107 | }: _(RawOrigin::Root, data_source.clone(), fingerprint) 108 | verify { 109 | assert_eq!(Teeracle::::whitelist(data_source).len(), 0, "mrenclave not removed from whitelist") 110 | } 111 | } 112 | 113 | #[cfg(test)] 114 | use crate::{Config, Pallet as PalletModule}; 115 | 116 | #[cfg(test)] 117 | use frame_benchmarking::impl_benchmark_test_suite; 118 | use frame_support::{traits::Get, StorageValue}; 119 | use sp_consensus_aura::Slot; 120 | 121 | #[cfg(test)] 122 | impl_benchmark_test_suite!(PalletModule, crate::mock::new_test_ext(), crate::mock::Test,); 123 | -------------------------------------------------------------------------------- /teeracle/src/mock.rs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2021 Integritee AG and Supercomputing Systems AG 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | 16 | */ 17 | use crate as pallet_teeracle; 18 | use frame_support::{derive_impl, parameter_types, traits::ConstBool}; 19 | use frame_system as system; 20 | use pallet_teeracle::Config; 21 | use sp_consensus_aura::sr25519::AuthorityId as AuraId; 22 | use sp_core::{ConstU32, H256}; 23 | use sp_keyring::Sr25519Keyring as Keyring; 24 | use sp_runtime::{ 25 | generic, 26 | traits::{BlakeTwo256, IdentifyAccount, IdentityLookup, Verify}, 27 | BuildStorage, 28 | }; 29 | 30 | pub type Signature = sp_runtime::MultiSignature; 31 | pub type AccountId = <::Signer as IdentifyAccount>::AccountId; 32 | pub type Address = sp_runtime::MultiAddress; 33 | 34 | pub type BlockNumber = u32; 35 | pub type Header = generic::Header; 36 | pub type UncheckedExtrinsic = 37 | generic::UncheckedExtrinsic; 38 | 39 | pub type SignedExtra = ( 40 | frame_system::CheckSpecVersion, 41 | frame_system::CheckTxVersion, 42 | frame_system::CheckGenesis, 43 | frame_system::CheckEra, 44 | frame_system::CheckNonce, 45 | frame_system::CheckWeight, 46 | ); 47 | 48 | frame_support::construct_runtime!( 49 | pub enum Test 50 | { 51 | Aura: pallet_aura, 52 | System: frame_system, 53 | Balances: pallet_balances, 54 | Timestamp: pallet_timestamp, 55 | Teerex: pallet_teerex, 56 | Teeracle: pallet_teeracle, 57 | } 58 | ); 59 | 60 | parameter_types! { 61 | pub const BlockHashCount: u32 = 250; 62 | } 63 | 64 | #[derive_impl(frame_system::config_preludes::SolochainDefaultConfig as frame_system::DefaultConfig)] 65 | impl frame_system::Config for Test { 66 | type BaseCallFilter = frame_support::traits::Everything; 67 | type BlockWeights = (); 68 | type BlockLength = (); 69 | type Block = generic::Block; 70 | type DbWeight = (); 71 | type RuntimeOrigin = RuntimeOrigin; 72 | type Nonce = u64; 73 | type RuntimeCall = RuntimeCall; 74 | type RuntimeTask = RuntimeTask; 75 | type Hash = H256; 76 | type Hashing = BlakeTwo256; 77 | type AccountId = AccountId; 78 | type Lookup = IdentityLookup; 79 | type RuntimeEvent = RuntimeEvent; 80 | type BlockHashCount = BlockHashCount; 81 | type Version = (); 82 | type PalletInfo = PalletInfo; 83 | type AccountData = pallet_balances::AccountData; 84 | type OnNewAccount = (); 85 | type OnKilledAccount = (); 86 | type SystemWeightInfo = (); 87 | type SS58Prefix = (); 88 | type OnSetCode = (); 89 | type MaxConsumers = frame_support::traits::ConstU32<16>; 90 | } 91 | 92 | parameter_types! { 93 | pub const SlotDuration: u64 = 6000; 94 | } 95 | impl pallet_aura::Config for Test { 96 | type AuthorityId = AuraId; 97 | type DisabledValidators = (); 98 | type MaxAuthorities = ConstU32<32>; 99 | type AllowMultipleBlocksPerSlot = ConstBool; 100 | type SlotDuration = SlotDuration; 101 | } 102 | pub type Balance = u64; 103 | 104 | parameter_types! { 105 | pub const ExistentialDeposit: u64 = 1; 106 | } 107 | 108 | impl pallet_balances::Config for Test { 109 | type MaxLocks = (); 110 | type Balance = u64; 111 | type DustRemoval = (); 112 | type RuntimeEvent = RuntimeEvent; 113 | type ExistentialDeposit = ExistentialDeposit; 114 | type AccountStore = System; 115 | type WeightInfo = (); 116 | type MaxReserves = (); 117 | type ReserveIdentifier = (); 118 | type RuntimeFreezeReason = (); 119 | type FreezeIdentifier = (); 120 | type MaxFreezes = (); 121 | type RuntimeHoldReason = (); 122 | type DoneSlashHandler = (); 123 | } 124 | 125 | parameter_types! { 126 | pub const MinimumPeriod: u64 = 6000 / 2; 127 | } 128 | 129 | pub type Moment = u64; 130 | 131 | impl pallet_timestamp::Config for Test { 132 | type Moment = Moment; 133 | type OnTimestampSet = Aura; 134 | type MinimumPeriod = MinimumPeriod; 135 | type WeightInfo = (); 136 | } 137 | 138 | parameter_types! { 139 | pub const MomentsPerDay: u64 = 86_400_000; // [ms/d] 140 | pub const MaxAttestationRenewalPeriod: u64 = 172_800_000; // 48h 141 | pub const MaxWhitelistedReleases: u32 = 10; 142 | pub const MaxOracleBlobLen: u32 = 4096; 143 | } 144 | 145 | impl pallet_teerex::Config for Test { 146 | type RuntimeEvent = RuntimeEvent; 147 | type MomentsPerDay = MomentsPerDay; 148 | type WeightInfo = (); 149 | type MaxAttestationRenewalPeriod = MaxAttestationRenewalPeriod; 150 | } 151 | 152 | impl Config for Test { 153 | type RuntimeEvent = RuntimeEvent; 154 | type WeightInfo = (); 155 | type MaxWhitelistedReleases = MaxWhitelistedReleases; 156 | type MaxOracleBlobLen = MaxOracleBlobLen; 157 | } 158 | 159 | // This function basically just builds a genesis storage key/value store according to 160 | // our desired mockup. RA from enclave compiled in debug mode is allowed 161 | pub fn new_test_ext() -> sp_io::TestExternalities { 162 | let mut t = system::GenesisConfig::::default().build_storage().unwrap(); 163 | pallet_balances::GenesisConfig:: { 164 | balances: vec![(Keyring::Alice.to_account_id(), 1 << 60)], 165 | ..Default::default() 166 | } 167 | .assimilate_storage(&mut t) 168 | .unwrap(); 169 | pallet_teerex::GenesisConfig:: { 170 | allow_sgx_debug_mode: true, 171 | allow_skipping_attestation: true, 172 | _config: Default::default(), 173 | } 174 | .assimilate_storage(&mut t) 175 | .unwrap(); 176 | 177 | let mut ext: sp_io::TestExternalities = t.into(); 178 | ext.execute_with(|| System::set_block_number(1)); 179 | ext 180 | } 181 | -------------------------------------------------------------------------------- /teeracle/src/weights.rs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2021 Integritee AG 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | 16 | */ 17 | use frame_support::{traits::Get, weights::Weight}; 18 | use sp_std::marker::PhantomData; 19 | 20 | /// Weight functions needed for pallet_exchange. 21 | pub trait WeightInfo { 22 | fn add_to_whitelist() -> Weight; 23 | fn remove_from_whitelist() -> Weight; 24 | fn update_exchange_rate() -> Weight; 25 | fn update_oracle() -> Weight; 26 | } 27 | 28 | pub struct IntegriteeWeight(PhantomData); 29 | impl WeightInfo for IntegriteeWeight { 30 | /// Storage: `Teerex::SovereignEnclaves` (r:1 w:0) 31 | /// Proof: `Teerex::SovereignEnclaves` (`max_values`: None, `max_size`: None, mode: `Measured`) 32 | /// Storage: `Teeracle::Whitelists` (r:1 w:0) 33 | /// Proof: `Teeracle::Whitelists` (`max_values`: None, `max_size`: None, mode: `Measured`) 34 | /// Storage: `Teeracle::ExchangeRates` (r:1 w:1) 35 | /// Proof: `Teeracle::ExchangeRates` (`max_values`: None, `max_size`: None, mode: `Measured`) 36 | fn update_exchange_rate() -> Weight { 37 | // Proof Size summary in bytes: 38 | // Measured: `454` 39 | // Estimated: `3919` 40 | // Minimum execution time: 44_730_000 picoseconds. 41 | Weight::from_parts(49_230_000, 0) 42 | .saturating_add(Weight::from_parts(0, 3919)) 43 | .saturating_add(T::DbWeight::get().reads(3)) 44 | .saturating_add(T::DbWeight::get().writes(1)) 45 | } 46 | /// Storage: `Teerex::SovereignEnclaves` (r:1 w:0) 47 | /// Proof: `Teerex::SovereignEnclaves` (`max_values`: None, `max_size`: None, mode: `Measured`) 48 | /// Storage: `Teeracle::Whitelists` (r:1 w:0) 49 | /// Proof: `Teeracle::Whitelists` (`max_values`: None, `max_size`: None, mode: `Measured`) 50 | /// Storage: `Teeracle::OracleData` (r:0 w:1) 51 | /// Proof: `Teeracle::OracleData` (`max_values`: None, `max_size`: None, mode: `Measured`) 52 | fn update_oracle() -> Weight { 53 | // Proof Size summary in bytes: 54 | // Measured: `445` 55 | // Estimated: `3910` 56 | // Minimum execution time: 37_526_000 picoseconds. 57 | Weight::from_parts(41_294_000, 0) 58 | .saturating_add(Weight::from_parts(0, 3910)) 59 | .saturating_add(T::DbWeight::get().reads(2)) 60 | .saturating_add(T::DbWeight::get().writes(1)) 61 | } 62 | /// Storage: `Teeracle::Whitelists` (r:1 w:1) 63 | /// Proof: `Teeracle::Whitelists` (`max_values`: None, `max_size`: None, mode: `Measured`) 64 | fn add_to_whitelist() -> Weight { 65 | // Proof Size summary in bytes: 66 | // Measured: `6` 67 | // Estimated: `3471` 68 | // Minimum execution time: 17_640_000 picoseconds. 69 | Weight::from_parts(19_529_000, 0) 70 | .saturating_add(Weight::from_parts(0, 3471)) 71 | .saturating_add(T::DbWeight::get().reads(1)) 72 | .saturating_add(T::DbWeight::get().writes(1)) 73 | } 74 | /// Storage: `Teeracle::Whitelists` (r:1 w:1) 75 | /// Proof: `Teeracle::Whitelists` (`max_values`: None, `max_size`: None, mode: `Measured`) 76 | fn remove_from_whitelist() -> Weight { 77 | // Proof Size summary in bytes: 78 | // Measured: `107` 79 | // Estimated: `3572` 80 | // Minimum execution time: 20_741_000 picoseconds. 81 | Weight::from_parts(21_866_000, 0) 82 | .saturating_add(Weight::from_parts(0, 3572)) 83 | .saturating_add(T::DbWeight::get().reads(1)) 84 | .saturating_add(T::DbWeight::get().writes(1)) 85 | } 86 | } 87 | // For tests 88 | impl WeightInfo for () { 89 | fn add_to_whitelist() -> Weight { 90 | Weight::from_parts(46_200_000, 0u64) 91 | } 92 | fn remove_from_whitelist() -> Weight { 93 | Weight::from_parts(46_200_000, 0u64) 94 | } 95 | fn update_exchange_rate() -> Weight { 96 | Weight::from_parts(46_200_000, 0u64) 97 | } 98 | fn update_oracle() -> Weight { 99 | Weight::from_parts(46_200_000, 0u64) 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /teerdays/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "pallet-teerdays" 3 | version = "0.1.0" 4 | authors = ["Integritee AG "] 5 | homepage = "https://integritee.network/" 6 | repository = "https://github.com/integritee-network/pallets/" 7 | license = "(GPL-3.0-only)" 8 | edition = "2021" 9 | 10 | [lints] 11 | workspace = true 12 | 13 | [dependencies] 14 | log = { workspace = true } 15 | parity-scale-codec = { workspace = true } 16 | scale-info = { workspace = true } 17 | serde = { workspace = true, optional = true } 18 | 19 | teerdays-primitives = { path = "../primitives/teerdays", default-features = false } 20 | 21 | # substrate dependencies 22 | frame-support = { workspace = true } 23 | frame-system = { workspace = true } 24 | pallet-balances = { workspace = true } 25 | pallet-timestamp = { workspace = true } 26 | sp-core = { workspace = true } 27 | sp-io = { workspace = true } 28 | sp-runtime = { workspace = true } 29 | sp-std = { workspace = true } 30 | 31 | # benchmarking 32 | frame-benchmarking = { workspace = true, optional = true } 33 | hex-literal = { workspace = true, optional = true } 34 | 35 | [dev-dependencies] 36 | env_logger = { workspace = true } 37 | sp-keyring = { workspace = true } 38 | 39 | [features] 40 | default = ["std"] 41 | std = [ 42 | "frame-benchmarking?/std", 43 | "frame-support/std", 44 | "frame-system/std", 45 | "log/std", 46 | "pallet-balances/std", 47 | "pallet-timestamp/std", 48 | "parity-scale-codec/std", 49 | "scale-info/std", 50 | "serde/std", 51 | "sp-core/std", 52 | "sp-io/std", 53 | "sp-keyring/std", 54 | "sp-runtime/std", 55 | "sp-std/std", 56 | "teerdays-primitives/std", 57 | ] 58 | 59 | try-runtime = [ 60 | "frame-support/try-runtime", 61 | "frame-system/try-runtime", 62 | "pallet-balances/try-runtime", 63 | "pallet-timestamp/try-runtime", 64 | "sp-runtime/try-runtime", 65 | ] 66 | 67 | runtime-benchmarks = [ 68 | "frame-benchmarking/runtime-benchmarks", 69 | "frame-support/runtime-benchmarks", 70 | "frame-system/runtime-benchmarks", 71 | "hex-literal", 72 | "pallet-balances/runtime-benchmarks", 73 | "pallet-timestamp/runtime-benchmarks", 74 | "sp-runtime/runtime-benchmarks", 75 | ] 76 | -------------------------------------------------------------------------------- /teerdays/src/benchmarking.rs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2021 Integritee AG 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | 16 | */ 17 | 18 | //! TeerDays pallet benchmarking 19 | 20 | #![cfg(any(test, feature = "runtime-benchmarks"))] 21 | 22 | use super::*; 23 | 24 | use crate::Pallet as TeerDays; 25 | use frame_benchmarking::{account, benchmarks}; 26 | use frame_system::RawOrigin; 27 | use sp_std::prelude::*; 28 | 29 | benchmarks! { 30 | where_clause { where T::AccountId: From<[u8; 32]>, T::Hash: From<[u8; 32]> } 31 | bond { 32 | pallet_timestamp::Pallet::::set_timestamp(0u32.into()); 33 | let signer: T::AccountId = account("alice", 1, 1); 34 | T::Currency::make_free_balance_be(&signer, 4_000_000_000u32.into()); 35 | }: _(RawOrigin::Signed(signer.clone()), 2_000_000_000u32.into()) 36 | verify { 37 | assert!(TeerDays::::teerday_bonds(&signer).is_some()); 38 | } 39 | 40 | unbond { 41 | pallet_timestamp::Pallet::::set_timestamp(0u32.into()); 42 | let signer: T::AccountId = account("alice", 1, 1); 43 | T::Currency::make_free_balance_be(&signer, 4_000_000_000u32.into()); 44 | TeerDays::::bond(RawOrigin::Signed(signer.clone()).into(), 2_000_000_000u32.into())?; 45 | }: _(RawOrigin::Signed(signer.clone()), 1_000_000_000u32.into()) 46 | verify { 47 | assert!(TeerDays::::teerday_bonds(&signer).is_some()); 48 | } 49 | 50 | update_other { 51 | pallet_timestamp::Pallet::::set_timestamp(0u32.into()); 52 | let signer: T::AccountId = account("alice", 1, 1); 53 | T::Currency::make_free_balance_be(&signer, 4_000_000_000u32.into()); 54 | TeerDays::::bond(RawOrigin::Signed(signer.clone()).into(), 1_000_000_000u32.into())?; 55 | }: _(RawOrigin::Signed(signer.clone()), signer.clone()) 56 | verify { 57 | assert!(TeerDays::::teerday_bonds(&signer).is_some()); 58 | } 59 | withdraw_unbonded { 60 | pallet_timestamp::Pallet::::set_timestamp(42u32.into()); 61 | let signer: T::AccountId = account("alice", 1, 1); 62 | T::Currency::make_free_balance_be(&signer, 4_000_000_000u32.into()); 63 | T::Currency::set_lock(TEERDAYS_ID, &signer, 1_000_000_000u32.into(), WithdrawReasons::all()); 64 | PendingUnlock::::insert::<_, (T::Moment, BalanceOf)>(&signer, (42u32.into(), 1_000_000_000u32.into())); 65 | }: _(RawOrigin::Signed(signer.clone())) 66 | verify { 67 | assert!(TeerDays::::pending_unlock(&signer).is_none()); 68 | } 69 | 70 | } 71 | 72 | #[cfg(test)] 73 | use crate::{Config, Pallet as PalletModule}; 74 | 75 | #[cfg(test)] 76 | use frame_benchmarking::impl_benchmark_test_suite; 77 | 78 | #[cfg(test)] 79 | impl_benchmark_test_suite!(PalletModule, crate::mock::new_test_ext(), crate::mock::Test,); 80 | -------------------------------------------------------------------------------- /teerdays/src/mock.rs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2021 Integritee AG 3 | 4 | Licenced under GNU General Public License as published by 5 | the Free Software Foundation, either version 3 of the License, or 6 | (at your option) any later version. You may obtain a copy of the 7 | License at 8 | 9 | . 10 | 11 | Unless required by applicable law or agreed to in writing, software 12 | distributed under the License is distributed on an "AS IS" BASIS, 13 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | See the License for the specific language governing permissions and 15 | limitations under the License. 16 | */ 17 | 18 | // Creating mock runtime here 19 | use crate as pallet_teerdays; 20 | use frame_support::{derive_impl, parameter_types}; 21 | use frame_system as system; 22 | use pallet_teerdays::Config; 23 | use sp_core::H256; 24 | use sp_keyring::Sr25519Keyring as Keyring; 25 | use sp_runtime::{ 26 | generic, 27 | traits::{BlakeTwo256, IdentifyAccount, IdentityLookup, Verify}, 28 | BuildStorage, 29 | }; 30 | 31 | pub type Signature = sp_runtime::MultiSignature; 32 | pub type AccountId = <::Signer as IdentifyAccount>::AccountId; 33 | pub type Address = sp_runtime::MultiAddress; 34 | 35 | pub type BlockNumber = u32; 36 | pub type Header = generic::Header; 37 | pub type UncheckedExtrinsic = 38 | generic::UncheckedExtrinsic; 39 | 40 | pub type SignedExtra = ( 41 | frame_system::CheckSpecVersion, 42 | frame_system::CheckTxVersion, 43 | frame_system::CheckGenesis, 44 | frame_system::CheckEra, 45 | frame_system::CheckNonce, 46 | frame_system::CheckWeight, 47 | ); 48 | 49 | frame_support::construct_runtime!( 50 | pub enum Test 51 | { 52 | System: frame_system::{Pallet, Call, Config, Storage, Event}, 53 | Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, 54 | Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent}, 55 | TeerDays: crate::{Pallet, Call, Storage, Event}, 56 | } 57 | ); 58 | 59 | parameter_types! { 60 | pub const BlockHashCount: u32 = 250; 61 | } 62 | #[derive_impl(frame_system::config_preludes::SolochainDefaultConfig as frame_system::DefaultConfig)] 63 | impl frame_system::Config for Test { 64 | type BaseCallFilter = frame_support::traits::Everything; 65 | type BlockWeights = (); 66 | type BlockLength = (); 67 | type Block = generic::Block; 68 | type DbWeight = (); 69 | type RuntimeOrigin = RuntimeOrigin; 70 | type Nonce = u64; 71 | type RuntimeCall = RuntimeCall; 72 | type RuntimeTask = RuntimeTask; 73 | type Hash = H256; 74 | type Hashing = BlakeTwo256; 75 | type AccountId = AccountId; 76 | type Lookup = IdentityLookup; 77 | type RuntimeEvent = RuntimeEvent; 78 | type BlockHashCount = BlockHashCount; 79 | type Version = (); 80 | type PalletInfo = PalletInfo; 81 | type AccountData = pallet_balances::AccountData; 82 | type OnNewAccount = (); 83 | type OnKilledAccount = (); 84 | type SystemWeightInfo = (); 85 | type SS58Prefix = (); 86 | type OnSetCode = (); 87 | type MaxConsumers = frame_support::traits::ConstU32<16>; 88 | } 89 | 90 | pub type Balance = u128; 91 | 92 | parameter_types! { 93 | pub const ExistentialDeposit: u128 = 1; 94 | } 95 | 96 | impl pallet_balances::Config for Test { 97 | type MaxLocks = (); 98 | type Balance = Balance; 99 | type DustRemoval = (); 100 | type RuntimeEvent = RuntimeEvent; 101 | type ExistentialDeposit = ExistentialDeposit; 102 | type AccountStore = System; 103 | type WeightInfo = (); 104 | type MaxReserves = (); 105 | type ReserveIdentifier = (); 106 | type RuntimeFreezeReason = (); 107 | type FreezeIdentifier = (); 108 | type MaxFreezes = (); 109 | type RuntimeHoldReason = (); 110 | type DoneSlashHandler = (); 111 | } 112 | 113 | parameter_types! { 114 | pub const MinimumPeriod: u64 = 6000 / 2; 115 | } 116 | 117 | pub type Moment = u64; 118 | 119 | impl pallet_timestamp::Config for Test { 120 | type Moment = Moment; 121 | type OnTimestampSet = (); 122 | type MinimumPeriod = MinimumPeriod; 123 | type WeightInfo = (); 124 | } 125 | 126 | parameter_types! { 127 | pub const UnlockPeriod: u64 = 86_400_000; // [ms] 128 | } 129 | 130 | impl Config for Test { 131 | type RuntimeEvent = RuntimeEvent; 132 | type UnlockPeriod = UnlockPeriod; 133 | type WeightInfo = (); 134 | type Currency = Balances; 135 | type CurrencyBalance = Balance; 136 | } 137 | 138 | // This function basically just builds a genesis storage key/value store according to 139 | // our desired mockup. RA from enclave compiled in debug mode is allowed 140 | pub fn new_test_ext() -> sp_io::TestExternalities { 141 | let mut t = system::GenesisConfig::::default().build_storage().unwrap(); 142 | pallet_balances::GenesisConfig:: { 143 | balances: vec![(Keyring::Alice.to_account_id(), 1 << 60)], 144 | ..Default::default() 145 | } 146 | .assimilate_storage(&mut t) 147 | .unwrap(); 148 | 149 | let mut ext: sp_io::TestExternalities = t.into(); 150 | ext.execute_with(|| System::set_block_number(1)); 151 | ext 152 | } 153 | -------------------------------------------------------------------------------- /teerdays/src/weights.rs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2021 Integritee AG 3 | 4 | Licenced under GNU General Public License as published by 5 | the Free Software Foundation, either version 3 of the License, or 6 | (at your option) any later version. You may obtain a copy of the 7 | License at 8 | 9 | . 10 | 11 | Unless required by applicable law or agreed to in writing, software 12 | distributed under the License is distributed on an "AS IS" BASIS, 13 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | See the License for the specific language governing permissions and 15 | limitations under the License. 16 | */ 17 | use frame_support::{traits::Get, weights::Weight}; 18 | use sp_std::marker::PhantomData; 19 | 20 | /// Weight functions needed for pallet_teerdays. 21 | pub trait WeightInfo { 22 | fn bond() -> Weight; 23 | fn unbond() -> Weight; 24 | fn update_other() -> Weight; 25 | fn withdraw_unbonded() -> Weight; 26 | } 27 | 28 | /// Weights for pallet_sidechain using the Integritee parachain node and recommended hardware. 29 | pub struct IntegriteeWeight(PhantomData); 30 | impl WeightInfo for IntegriteeWeight { 31 | /// Storage: `TeerDays::TeerDayBonds` (r:1 w:1) 32 | /// Proof: `TeerDays::TeerDayBonds` (`max_values`: None, `max_size`: None, mode: `Measured`) 33 | /// Storage: `System::Account` (r:1 w:1) 34 | /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) 35 | /// Storage: `Balances::Locks` (r:1 w:1) 36 | /// Proof: `Balances::Locks` (`max_values`: None, `max_size`: Some(1299), added: 3774, mode: `MaxEncodedLen`) 37 | /// Storage: `Balances::Freezes` (r:1 w:0) 38 | /// Proof: `Balances::Freezes` (`max_values`: None, `max_size`: Some(49), added: 2524, mode: `MaxEncodedLen`) 39 | /// Storage: `Timestamp::Now` (r:1 w:0) 40 | /// Proof: `Timestamp::Now` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `MaxEncodedLen`) 41 | fn bond() -> Weight { 42 | // Proof Size summary in bytes: 43 | // Measured: `240` 44 | // Estimated: `4764` 45 | // Minimum execution time: 82_957_000 picoseconds. 46 | Weight::from_parts(86_401_000, 0) 47 | .saturating_add(Weight::from_parts(0, 4764)) 48 | .saturating_add(T::DbWeight::get().reads(5)) 49 | .saturating_add(T::DbWeight::get().writes(3)) 50 | } 51 | /// Storage: `TeerDays::PendingUnlock` (r:1 w:1) 52 | /// Proof: `TeerDays::PendingUnlock` (`max_values`: None, `max_size`: None, mode: `Measured`) 53 | /// Storage: `TeerDays::TeerDayBonds` (r:1 w:1) 54 | /// Proof: `TeerDays::TeerDayBonds` (`max_values`: None, `max_size`: None, mode: `Measured`) 55 | /// Storage: `Timestamp::Now` (r:1 w:0) 56 | /// Proof: `Timestamp::Now` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `MaxEncodedLen`) 57 | fn unbond() -> Weight { 58 | // Proof Size summary in bytes: 59 | // Measured: `253` 60 | // Estimated: `3718` 61 | // Minimum execution time: 53_559_000 picoseconds. 62 | Weight::from_parts(56_711_000, 0) 63 | .saturating_add(Weight::from_parts(0, 3718)) 64 | .saturating_add(T::DbWeight::get().reads(3)) 65 | .saturating_add(T::DbWeight::get().writes(2)) 66 | } 67 | /// Storage: `TeerDays::TeerDayBonds` (r:1 w:1) 68 | /// Proof: `TeerDays::TeerDayBonds` (`max_values`: None, `max_size`: None, mode: `Measured`) 69 | /// Storage: `Timestamp::Now` (r:1 w:0) 70 | /// Proof: `Timestamp::Now` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `MaxEncodedLen`) 71 | fn update_other() -> Weight { 72 | // Proof Size summary in bytes: 73 | // Measured: `253` 74 | // Estimated: `3718` 75 | // Minimum execution time: 34_156_000 picoseconds. 76 | Weight::from_parts(37_183_000, 0) 77 | .saturating_add(Weight::from_parts(0, 3718)) 78 | .saturating_add(T::DbWeight::get().reads(2)) 79 | .saturating_add(T::DbWeight::get().writes(1)) 80 | } 81 | /// Storage: `TeerDays::PendingUnlock` (r:1 w:1) 82 | /// Proof: `TeerDays::PendingUnlock` (`max_values`: None, `max_size`: None, mode: `Measured`) 83 | /// Storage: `Timestamp::Now` (r:1 w:0) 84 | /// Proof: `Timestamp::Now` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `MaxEncodedLen`) 85 | /// Storage: `Balances::Locks` (r:1 w:1) 86 | /// Proof: `Balances::Locks` (`max_values`: None, `max_size`: Some(1299), added: 3774, mode: `MaxEncodedLen`) 87 | /// Storage: `Balances::Freezes` (r:1 w:0) 88 | /// Proof: `Balances::Freezes` (`max_values`: None, `max_size`: Some(49), added: 2524, mode: `MaxEncodedLen`) 89 | /// Storage: `System::Account` (r:1 w:1) 90 | /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) 91 | fn withdraw_unbonded() -> Weight { 92 | // Proof Size summary in bytes: 93 | // Measured: `400` 94 | // Estimated: `4764` 95 | // Minimum execution time: 80_293_000 picoseconds. 96 | Weight::from_parts(82_512_000, 0) 97 | .saturating_add(Weight::from_parts(0, 4764)) 98 | .saturating_add(T::DbWeight::get().reads(5)) 99 | .saturating_add(T::DbWeight::get().writes(3)) 100 | } 101 | } 102 | 103 | // For tests 104 | impl WeightInfo for () { 105 | fn bond() -> Weight { 106 | Weight::from_parts(2_591_400_000, 0u64) 107 | } 108 | fn unbond() -> Weight { 109 | Weight::from_parts(2_591_400_000, 0u64) 110 | } 111 | fn update_other() -> Weight { 112 | Weight::from_parts(2_591_400_000, 0u64) 113 | } 114 | 115 | fn withdraw_unbonded() -> Weight { 116 | Weight::from_parts(2_591_400_000, 0u64) 117 | } 118 | } 119 | -------------------------------------------------------------------------------- /teerex/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "pallet-teerex" 3 | description = "The remote attestation registry and verification pallet for integritee blockchains and parachains" 4 | version = "0.10.0" 5 | authors = ["Integritee AG "] 6 | homepage = "https://integritee.network/" 7 | repository = "https://github.com/integritee-network/pallets/" 8 | license = "MS-RSL" 9 | edition = "2021" 10 | 11 | [lints] 12 | workspace = true 13 | 14 | [dependencies] 15 | hex = { workspace = true } 16 | log = { workspace = true } 17 | parity-scale-codec = { workspace = true } 18 | scale-info = { workspace = true } 19 | serde = { workspace = true, optional = true } 20 | webpki = { workspace = true } 21 | 22 | # local 23 | sgx-verify = { path = "sgx-verify", default-features = false } 24 | teerex-primitives = { path = "../primitives/teerex", default-features = false } 25 | 26 | # substrate dependencies 27 | frame-support = { workspace = true } 28 | frame-system = { workspace = true } 29 | pallet-timestamp = { workspace = true } 30 | sp-core = { workspace = true } 31 | sp-io = { workspace = true } 32 | sp-runtime = { workspace = true } 33 | sp-std = { workspace = true } 34 | 35 | # benchmarking 36 | frame-benchmarking = { workspace = true, optional = true } 37 | hex-literal = { workspace = true, optional = true } 38 | pallet-aura = { workspace = true, optional = true } 39 | pallet-balances = { workspace = true, optional = true } 40 | sp-consensus-aura = { workspace = true, optional = true } 41 | test-utils = { default-features = false, path = "../test-utils", optional = true } 42 | 43 | [dev-dependencies] 44 | env_logger = { workspace = true } 45 | frame-benchmarking = { workspace = true, features = ["std"] } 46 | hex-literal = { workspace = true } 47 | pallet-aura = { workspace = true } 48 | pallet-balances = { workspace = true, features = ["std"] } 49 | serde = { workspace = true, features = ["std"] } 50 | serde_json = { workspace = true, features = ["std"] } 51 | sp-consensus-aura = { workspace = true } 52 | sp-externalities = { workspace = true, features = ["std"] } 53 | sp-keyring = { workspace = true } 54 | test-utils = { path = "../test-utils" } 55 | 56 | [features] 57 | default = ["std"] 58 | std = [ 59 | "frame-benchmarking?/std", 60 | "frame-support/std", 61 | "frame-system/std", 62 | "log/std", 63 | "pallet-timestamp/std", 64 | "parity-scale-codec/std", 65 | "scale-info/std", 66 | "serde/std", 67 | "sgx-verify/std", 68 | "sp-consensus-aura?/std", 69 | "sp-core/std", 70 | "sp-io/std", 71 | "sp-runtime/std", 72 | "sp-std/std", 73 | "teerex-primitives/std", 74 | "webpki/std", 75 | "hex/std", 76 | "pallet-aura?/std", 77 | "pallet-balances?/std", 78 | "serde_json/std", 79 | "sp-externalities/std", 80 | "sp-keyring/std", 81 | ] 82 | runtime-benchmarks = [ 83 | "frame-benchmarking/runtime-benchmarks", 84 | "hex-literal", 85 | "pallet-aura", 86 | "pallet-balances", 87 | "pallet-timestamp/runtime-benchmarks", 88 | "test-utils", 89 | "frame-support/runtime-benchmarks", 90 | "frame-system/runtime-benchmarks", 91 | "pallet-balances?/runtime-benchmarks", 92 | "sp-consensus-aura", 93 | "sp-runtime/runtime-benchmarks", 94 | ] 95 | 96 | try-runtime = [ 97 | "frame-support/try-runtime", 98 | "frame-system/try-runtime", 99 | "pallet-aura?/try-runtime", 100 | "pallet-balances?/try-runtime", 101 | "pallet-timestamp/try-runtime", 102 | "sp-runtime/try-runtime", 103 | ] 104 | -------------------------------------------------------------------------------- /teerex/LICENSE: -------------------------------------------------------------------------------- 1 | MICROSOFT REFERENCE SOURCE LICENSE (MS-RSL) 2 | 3 | This license governs use of the accompanying software. If you use the software, you accept this license. If you do not accept the license, do not use the software. 4 | 5 | 1. Definitions 6 | The terms "reproduce," "reproduction" and "distribution" have the same meaning here as under U.S. copyright law. 7 | 8 | "You" means the licensee of the software. 9 | 10 | "Your company" means the company you worked for when you downloaded the software. 11 | 12 | "Reference use" means use of the software within your company as a reference, in read only form, for the sole purposes of debugging your products, maintaining your products, or enhancing the interoperability of your products with the software, and specifically excludes the right to distribute the software outside of your company. 13 | 14 | "Licensed patents" means any Licensor patent claims which read directly on the software as distributed by the Licensor under this license. 15 | 16 | 2. Grant of Rights 17 | (A) Copyright Grant- Subject to the terms of this license, the Licensor grants you a non-transferable, non-exclusive, worldwide, royalty-free copyright license to reproduce the software for reference use. 18 | 19 | (B) Patent Grant- Subject to the terms of this license, the Licensor grants you a non-transferable, non-exclusive, worldwide, royalty-free patent license under licensed patents for reference use. 20 | 21 | 3. Limitations 22 | (A) No Trademark License- This license does not grant you any rights to use the Licensor's name, logo, or trademarks. 23 | 24 | (B) If you begin patent litigation against the Licensor over patents that you think may apply to the software (including a cross-claim or counterclaim in a lawsuit), your license to the software ends automatically. 25 | 26 | (C) The software is licensed "as-is." You bear the risk of using it. The Licensor gives no express warranties, guarantees or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent permitted under your local laws, the Licensor excludes the implied warranties of merchantability, fitness for a particular purpose and non-infringement. 27 | -------------------------------------------------------------------------------- /teerex/README.md: -------------------------------------------------------------------------------- 1 | # pallet-teerex 2 | 3 | Please note this pallet has a different [license](./LICENSE) than the rest of this repository: MS-RSL 4 | 5 | A pallet for [Integritee](https://integritee.network) that acts as a verified registry for SGX enclaves. Its goal is to provide public auditability of remote attestation of SGX enclaves. Given deterministic builds of enclave code, this pallet closes the trust gap from source code to the MRENCLAVE of an enclave running on a genuine Intel SGX platfrom. Without the need for a license with Intel, everyone can verify what code is executed by registered service providers and that it is executed with confidentiality. A blockchain that integrates this pallet will, therefore, act as a public registry of remote attestated services. 6 | 7 | More documentation available at: 8 | * High-level: https://www.integritee.network/for-developer 9 | * In-depth: https://book.integritee.network/ 10 | 11 | ## IAS verify 12 | 13 | A helper crate that verifies IAS report certificates against Intel'x root CA (hard-coded). It also parses IAs reports and extracts information for filtering and registering by pallet-teerex 14 | ## Build 15 | 16 | Install Rust: 17 | ```bash 18 | curl https://sh.rustup.rs -sSf | sh 19 | ``` 20 | 21 | In order to compile *ring* into wasm, you'll need LLVM-9 or above or you'll get linker errors. Here the instructions for Ubuntu 18.04 22 | 23 | ```bash 24 | wget https://apt.llvm.org/llvm.sh 25 | chmod +x llvm.sh 26 | sudo ./llvm.sh 10 27 | export CC=/usr/bin/clang-10 28 | export AR=/usr/bin/llvm-ar-10 29 | # if you already built, make sure to run cargo clean 30 | ``` 31 | 32 | ## Test 33 | 34 | Run all unit tests with 35 | 36 | ``` 37 | cargo test --all 38 | ``` 39 | 40 | ## Overriding 41 | 42 | To use this pallet (directly or indirectly) in no-std, we need to override the ring crate in the workspace root, like: 43 | 44 | ``` 45 | [patch.crates-io] 46 | ring = { git = "https://github.com/betrusted-io/ring-xous", branch = "0.16.20-cleanup" } 47 | ``` -------------------------------------------------------------------------------- /teerex/scripts/benchmark_teerex_full_info.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -eo pipefail 3 | 4 | # This creates an extended weight file that contains: 5 | # * `WeightInfo` trait declaration 6 | # * `WeightInfo` implementation for an `IntegriteeRuntimeWeight` struct 7 | # * `WeightInfo` implementation for `()` used in testing. 8 | # 9 | # The output file is intended to be used in the `pallet_teerex` internally for development only. It contains more 10 | # information than needed for the actual node. 11 | 12 | # use absolute paths to call this from wherever we want 13 | SCRIPTS_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )" 14 | PROJ_ROOT="$(dirname "$SCRIPTS_DIR")" 15 | TEEREX_SRC="$PROJ_ROOT/src" 16 | 17 | echo "PROJ_ROOT: $SCRIPTS_DIR" 18 | echo "SCRIPTS_DIR: $PROJ_ROOT" 19 | echo "TEEREX_SRC: $TEEREX_SRC" 20 | 21 | NODE_BINARY=${1:-../integritee-node/target/release/integritee-node} 22 | CHAIN_SPEC=${2:-integritee-mainnet} 23 | 24 | echo "Generating weights for pallet_teerex" 25 | echo "node: $NODE_BINARY" 26 | echo "chain: $CHAIN_SPEC" 27 | 28 | ./"$NODE_BINARY" \ 29 | benchmark \ 30 | --chain="$CHAIN_SPEC" \ 31 | --steps=50 \ 32 | --repeat=20 \ 33 | --pallet=pallet_teerex \ 34 | --extrinsic="*" \ 35 | --execution=wasm \ 36 | --wasm-execution=compiled \ 37 | --heap-pages=4096 \ 38 | --output="$TEEREX_SRC"/weights.rs \ 39 | --template="$SCRIPTS_DIR"/frame-weight-template-full-info.hbs 40 | 41 | -------------------------------------------------------------------------------- /teerex/scripts/frame-weight-template-full-info.hbs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2021 Integritee AG 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | 16 | */ 17 | 18 | //! Autogenerated weights for {{pallet}} with reference hardware: 19 | //! * 20 | //! * 21 | //! * 22 | //! 23 | //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION {{version}} 24 | //! DATE: {{date}}, STEPS: `{{cmd.steps}}`, REPEAT: {{cmd.repeat}}, LOW RANGE: `{{cmd.lowest_range_values}}`, HIGH RANGE: `{{cmd.highest_range_values}}` 25 | //! EXECUTION: {{cmd.execution}}, WASM-EXECUTION: {{cmd.wasm_execution}}, CHAIN: {{cmd.chain}}, DB CACHE: {{cmd.db_cache}} 26 | 27 | // Executed Command: 28 | {{#each args as |arg|~}} 29 | // {{arg}} 30 | {{/each}} 31 | 32 | #![allow(unused_parens)] 33 | #![allow(unused_imports)] 34 | 35 | use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; 36 | use sp_std::marker::PhantomData; 37 | 38 | /// Weight functions needed for {{pallet}}. 39 | pub trait WeightInfo { 40 | {{~#each benchmarks as |benchmark|}} 41 | fn {{benchmark.name~}} 42 | ( 43 | {{~#each benchmark.components as |c| ~}} 44 | {{c.name}}: u32, {{/each~}} 45 | ) -> Weight; 46 | {{~/each}} 47 | } 48 | 49 | /// Weights for {{pallet}} using the Integritee parachain node and recommended hardware. 50 | pub struct IntegriteeWeight(PhantomData); 51 | impl WeightInfo for IntegriteeWeight { 52 | {{~#each benchmarks as |benchmark|}} 53 | fn {{benchmark.name~}} 54 | ( 55 | {{~#each benchmark.components as |c| ~}} 56 | {{~#if (not c.is_used)}}_{{/if}}{{c.name}}: u32, {{/each~}} 57 | ) -> Weight { 58 | Weight::from_ref_time({{underscore benchmark.base_weight}}) 59 | {{~#each benchmark.component_weight as |cw|}} 60 | // Standard Error: {{underscore cw.error}} 61 | .saturating_add(Weight::from_ref_time({{underscore cw.slope}}).saturating_mul({{cw.name}}.into())) 62 | {{~/each}} 63 | {{~#if (ne benchmark.base_reads "0")}} 64 | .saturating_add(T::DbWeight::get().reads({{benchmark.base_reads}})) 65 | {{~/if}} 66 | {{~#each benchmark.component_reads as |cr|}} 67 | .saturating_add(T::DbWeight::get().reads(Weight::from_ref_time({{cr.slope}}).saturating_mul({{cr.name}}.into()).ref_time()))) 68 | {{~/each}} 69 | {{~#if (ne benchmark.base_writes "0")}} 70 | .saturating_add(T::DbWeight::get().writes({{benchmark.base_writes}})) 71 | {{~/if}} 72 | {{~#each benchmark.component_writes as |cw|}} 73 | .saturating_add(T::DbWeight::get().writes(Weight::from_ref_time({{cw.slope}}).saturating_mul({{cw.name}}.into()).ref_time()))) 74 | {{~/each}} 75 | } 76 | {{~/each}} 77 | } 78 | 79 | // For tests 80 | impl WeightInfo for () { 81 | {{~#each benchmarks as |benchmark|}} 82 | fn {{benchmark.name~}} 83 | ( 84 | {{~#each benchmark.components as |c| ~}} 85 | {{~#if (not c.is_used)}}_{{/if}}{{c.name}}: u32, {{/each~}} 86 | ) -> Weight { 87 | Weight::from_ref_time({{underscore benchmark.base_weight}}) 88 | {{~#each benchmark.component_weight as |cw|}} 89 | // Standard Error: {{underscore cw.error}} 90 | .saturating_add(Weight::from_ref_time({{underscore cw.slope}}).saturating_mul({{cw.name}}.into())) 91 | {{~/each}} 92 | {{~#if (ne benchmark.base_reads "0")}} 93 | .saturating_add(RocksDbWeight::get().reads({{benchmark.base_reads}})) 94 | {{~/if}} 95 | {{~#each benchmark.component_reads as |cr|}} 96 | .saturating_add(RocksDbWeight::get().reads(Weight::from_ref_time({{cr.slope}}).saturating_mul({{cr.name}}.into()).ref_time()))) 97 | {{~/each}} 98 | {{~#if (ne benchmark.base_writes "0")}} 99 | .saturating_add(RocksDbWeight::get().writes({{benchmark.base_writes}})) 100 | {{~/if}} 101 | {{~#each benchmark.component_writes as |cw|}} 102 | .saturating_add(RocksDbWeight::get().writes(Weight::from_ref_time({{cw.slope}}).saturating_mul({{cw.name}}.into()).ref_time()))) 103 | {{~/each}} 104 | } 105 | {{~/each}} 106 | } 107 | -------------------------------------------------------------------------------- /teerex/sgx-verify/AttestationReportSigningCACert.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN CERTIFICATE----- 2 | MIIFSzCCA7OgAwIBAgIJANEHdl0yo7CUMA0GCSqGSIb3DQEBCwUAMH4xCzAJBgNV 3 | BAYTAlVTMQswCQYDVQQIDAJDQTEUMBIGA1UEBwwLU2FudGEgQ2xhcmExGjAYBgNV 4 | BAoMEUludGVsIENvcnBvcmF0aW9uMTAwLgYDVQQDDCdJbnRlbCBTR1ggQXR0ZXN0 5 | YXRpb24gUmVwb3J0IFNpZ25pbmcgQ0EwIBcNMTYxMTE0MTUzNzMxWhgPMjA0OTEy 6 | MzEyMzU5NTlaMH4xCzAJBgNVBAYTAlVTMQswCQYDVQQIDAJDQTEUMBIGA1UEBwwL 7 | U2FudGEgQ2xhcmExGjAYBgNVBAoMEUludGVsIENvcnBvcmF0aW9uMTAwLgYDVQQD 8 | DCdJbnRlbCBTR1ggQXR0ZXN0YXRpb24gUmVwb3J0IFNpZ25pbmcgQ0EwggGiMA0G 9 | CSqGSIb3DQEBAQUAA4IBjwAwggGKAoIBgQCfPGR+tXc8u1EtJzLA10Feu1Wg+p7e 10 | LmSRmeaCHbkQ1TF3Nwl3RmpqXkeGzNLd69QUnWovYyVSndEMyYc3sHecGgfinEeh 11 | rgBJSEdsSJ9FpaFdesjsxqzGRa20PYdnnfWcCTvFoulpbFR4VBuXnnVLVzkUvlXT 12 | L/TAnd8nIZk0zZkFJ7P5LtePvykkar7LcSQO85wtcQe0R1Raf/sQ6wYKaKmFgCGe 13 | NpEJUmg4ktal4qgIAxk+QHUxQE42sxViN5mqglB0QJdUot/o9a/V/mMeH8KvOAiQ 14 | byinkNndn+Bgk5sSV5DFgF0DffVqmVMblt5p3jPtImzBIH0QQrXJq39AT8cRwP5H 15 | afuVeLHcDsRp6hol4P+ZFIhu8mmbI1u0hH3W/0C2BuYXB5PC+5izFFh/nP0lc2Lf 16 | 6rELO9LZdnOhpL1ExFOq9H/B8tPQ84T3Sgb4nAifDabNt/zu6MmCGo5U8lwEFtGM 17 | RoOaX4AS+909x00lYnmtwsDVWv9vBiJCXRsCAwEAAaOByTCBxjBgBgNVHR8EWTBX 18 | MFWgU6BRhk9odHRwOi8vdHJ1c3RlZHNlcnZpY2VzLmludGVsLmNvbS9jb250ZW50 19 | L0NSTC9TR1gvQXR0ZXN0YXRpb25SZXBvcnRTaWduaW5nQ0EuY3JsMB0GA1UdDgQW 20 | BBR4Q3t2pn680K9+QjfrNXw7hwFRPDAfBgNVHSMEGDAWgBR4Q3t2pn680K9+Qjfr 21 | NXw7hwFRPDAOBgNVHQ8BAf8EBAMCAQYwEgYDVR0TAQH/BAgwBgEB/wIBADANBgkq 22 | hkiG9w0BAQsFAAOCAYEAeF8tYMXICvQqeXYQITkV2oLJsp6J4JAqJabHWxYJHGir 23 | IEqucRiJSSx+HjIJEUVaj8E0QjEud6Y5lNmXlcjqRXaCPOqK0eGRz6hi+ripMtPZ 24 | sFNaBwLQVV905SDjAzDzNIDnrcnXyB4gcDFCvwDFKKgLRjOB/WAqgscDUoGq5ZVi 25 | zLUzTqiQPmULAQaB9c6Oti6snEFJiCQ67JLyW/E83/frzCmO5Ru6WjU4tmsmy8Ra 26 | Ud4APK0wZTGtfPXU7w+IBdG5Ez0kE1qzxGQaL4gINJ1zMyleDnbuS8UicjJijvqA 27 | 152Sq049ESDz+1rRGc2NVEqh1KaGXmtXvqxXcTB+Ljy5Bw2ke0v8iGngFBPqCTVB 28 | 3op5KBG3RjbF6RRSzwzuWfL7QErNC8WEy5yDVARzTA5+xmBc388v9Dm21HGfcC8O 29 | DD+gT9sSpssq0ascmvH49MOgjt1yoysLtdCtJW/9FZpoOypaHx0R+mJTLwPXVMrv 30 | DaVzWh5aiEx+idkSGMnX 31 | -----END CERTIFICATE----- 32 | -------------------------------------------------------------------------------- /teerex/sgx-verify/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "sgx-verify" 3 | version = "0.1.4" 4 | description = "a certificate verification and IAS report parser crate for the teerex pallet" 5 | authors = ["Integritee AG "] 6 | homepage = "https://integritee.network/" 7 | repository = "https://github.com/integritee-network/pallets/" 8 | license = "GPL-3.0" 9 | edition = "2021" 10 | 11 | [lints] 12 | workspace = true 13 | 14 | [dependencies] 15 | base64 = { workspace = true } 16 | chrono = { workspace = true } 17 | der = { workspace = true } 18 | hex = { workspace = true } 19 | hex-literal = { workspace = true } 20 | log = { workspace = true } 21 | parity-scale-codec = { workspace = true } 22 | ring = { workspace = true } 23 | scale-info = { workspace = true } 24 | serde = { workspace = true } 25 | serde_json = { workspace = true, features = ["alloc"] } 26 | webpki = { workspace = true } 27 | x509-cert = { workspace = true } 28 | 29 | # local 30 | teerex-primitives = { path = "../../primitives/teerex", default-features = false } 31 | 32 | # substrate dependencies 33 | frame-support = { workspace = true } 34 | sp-core = { workspace = true } 35 | sp-io = { workspace = true } 36 | sp-std = { workspace = true } 37 | 38 | [dev-dependencies] 39 | hex-literal = { workspace = true } 40 | 41 | [features] 42 | default = ["std"] 43 | std = [ 44 | "base64/std", 45 | "chrono/std", 46 | "der/std", 47 | # substrate 48 | "frame-support/std", 49 | "hex/std", 50 | "log/std", 51 | "parity-scale-codec/std", 52 | "ring/std", 53 | "scale-info/std", 54 | "serde/std", 55 | "serde_json/std", 56 | "sp-core/std", 57 | "sp-io/std", 58 | "sp-std/std", 59 | # local 60 | "teerex-primitives/std", 61 | "webpki/std", 62 | "x509-cert/std", 63 | ] 64 | # Export ias/dcap data when we want to use them 65 | # in tests/benchmarks in the pallets. 66 | test-data = [] 67 | -------------------------------------------------------------------------------- /teerex/sgx-verify/fuzz/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "sgx-verify-fuzz" 3 | version = "0.0.0" 4 | publish = false 5 | edition = "2021" 6 | 7 | [package.metadata] 8 | cargo-fuzz = true 9 | 10 | [dependencies] 11 | base64 = { version = "0.13", default-features = false, features = ["alloc"] } 12 | codec = { version = "3.6.1", default-features = false, features = ["derive"], package = "parity-scale-codec" } 13 | hex-literal = "0.3.4" 14 | libfuzzer-sys = "0.4" 15 | serde_json = { version = "1.0" } 16 | webpki = { git = "https://github.com/rustls/webpki", version = "=0.102.0-alpha.3", rev = "da923ed", package = "rustls-webpki", default-features = false, features = ["alloc", "ring"] } 17 | 18 | [dependencies.sgx-verify] 19 | path = ".." 20 | 21 | # Prevent this from interfering with workspaces 22 | [workspace] 23 | members = ["."] 24 | 25 | [profile.release] 26 | debug = 1 27 | 28 | [[bin]] 29 | name = "decode_quote" 30 | path = "fuzz_targets/decode_quote.rs" 31 | test = false 32 | doc = false 33 | 34 | [[bin]] 35 | name = "deserialize_json" 36 | path = "fuzz_targets/deserialize_json.rs" 37 | test = false 38 | doc = false 39 | 40 | [[bin]] 41 | name = "signature_check" 42 | path = "fuzz_targets/signature_check.rs" 43 | test = false 44 | doc = false 45 | 46 | [[bin]] 47 | name = "extract_tcb_info" 48 | path = "fuzz_targets/extract_tcb_info.rs" 49 | test = false 50 | doc = false 51 | 52 | [[bin]] 53 | name = "verify_ias_report" 54 | path = "fuzz_targets/verify_ias_report.rs" 55 | test = false 56 | doc = false 57 | 58 | [patch.crates-io] 59 | ring = { git = "https://github.com/betrusted-io/ring-xous", branch = "0.16.20-cleanup" } 60 | -------------------------------------------------------------------------------- /teerex/sgx-verify/fuzz/fuzz_targets/decode_quote.rs: -------------------------------------------------------------------------------- 1 | #![no_main] 2 | 3 | use libfuzzer_sys::fuzz_target; 4 | use parity_scale_codec::Decode; 5 | use sgx_verify::DcapQuote; 6 | 7 | fuzz_target!(|data: &[u8]| { 8 | let mut copy = data; 9 | let _quote: Result = Decode::decode(&mut copy); 10 | 11 | // This assert is commented out because the fuzzer manages to find a "valid" quote that can 12 | // at least be decoded into memory. We would need additional verification steps (for example signature) 13 | // to enable this check. 14 | //assert!(quote.is_err()); 15 | }); 16 | -------------------------------------------------------------------------------- /teerex/sgx-verify/fuzz/fuzz_targets/deserialize_json.rs: -------------------------------------------------------------------------------- 1 | #![no_main] 2 | 3 | use libfuzzer_sys::fuzz_target; 4 | use sgx_verify::collateral::{EnclaveIdentity, TcbInfo}; 5 | 6 | fuzz_target!(|data: &[u8]| { 7 | let enclave: Result = serde_json::from_slice(data); 8 | assert!(enclave.is_err()); 9 | let tcb_info: Result = serde_json::from_slice(data); 10 | assert!(tcb_info.is_err()); 11 | }); 12 | -------------------------------------------------------------------------------- /teerex/sgx-verify/fuzz/fuzz_targets/extract_tcb_info.rs: -------------------------------------------------------------------------------- 1 | #![no_main] 2 | 3 | use libfuzzer_sys::fuzz_target; 4 | use sgx_verify::extract_tcb_info; 5 | 6 | fuzz_target!(|data: &[u8]| { 7 | assert!(extract_tcb_info(data).is_err()); 8 | }); 9 | -------------------------------------------------------------------------------- /teerex/sgx-verify/fuzz/fuzz_targets/signature_check.rs: -------------------------------------------------------------------------------- 1 | #![no_main] 2 | #![feature(core_panic)] 3 | 4 | pub extern crate alloc; 5 | extern crate core; 6 | 7 | use libfuzzer_sys::fuzz_target; 8 | use sgx_verify::deserialize_enclave_identity; 9 | 10 | fuzz_target!(|data: &[u8]| { 11 | if data.len() < 64 { 12 | return 13 | } 14 | 15 | let cert = include_str!("../../test-data/dcap/qe_identity_cert.pem"); 16 | let cert = cert.replace('\n', ""); 17 | let decoded_cert = base64::decode(&cert).unwrap(); 18 | let cert_der = webpki::types::CertificateDer::from(decoded_cert.as_slice()); 19 | let cert = webpki::EndEntityCert::try_from(&cert_der).unwrap(); 20 | 21 | let quoting_enclave = br#"{"id":"QE","version":2,"issueDate":"2022-10-18T21:55:07Z","nextUpdate":"2022-11-17T21:55:07Z","tcbEvaluationDataNumber":12,"miscselect":"00000000","miscselectMask":"FFFFFFFF","attributes":"11000000000000000000000000000000","attributesMask":"FBFFFFFFFFFFFFFF0000000000000000","mrsigner":"8C4F5775D796503E96137F77C68A829A0056AC8DED70140B081B094490C57BFF","isvprodid":1,"tcbLevels":[{"tcb":{"isvsvn":6},"tcbDate":"2021-11-10T00:00:00Z","tcbStatus":"UpToDate"},{"tcb":{"isvsvn":5},"tcbDate":"2020-11-11T00:00:00Z","tcbStatus":"OutOfDate"},{"tcb":{"isvsvn":4},"tcbDate":"2019-11-13T00:00:00Z","tcbStatus":"OutOfDate"},{"tcb":{"isvsvn":2},"tcbDate":"2019-05-15T00:00:00Z","tcbStatus":"OutOfDate"},{"tcb":{"isvsvn":1},"tcbDate":"2018-08-15T00:00:00Z","tcbStatus":"OutOfDate"}]}"#; 22 | let signature = &data[0..64]; 23 | 24 | let res = deserialize_enclave_identity("ing_enclave[..], &signature, &cert); 25 | assert!(res.is_err(), "Found a valid signature"); 26 | }); 27 | -------------------------------------------------------------------------------- /teerex/sgx-verify/fuzz/fuzz_targets/verify_ias_report.rs: -------------------------------------------------------------------------------- 1 | #![no_main] 2 | 3 | use libfuzzer_sys::fuzz_target; 4 | use sgx_verify::verify_ias_report; 5 | 6 | fuzz_target!(|data: &[u8]| { 7 | // Check test that there is now panic and that the provided data is not a valid IAS report 8 | assert!(verify_ias_report(data).is_err()); 9 | }); 10 | -------------------------------------------------------------------------------- /teerex/sgx-verify/src/ephemeral_key.rs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2021 Integritee AG and Supercomputing Systems AG 3 | 4 | Licensed under the MICROSOFT REFERENCE SOURCE LICENSE (MS-RSL) (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | https://referencesource.microsoft.com/license.html 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | 16 | */ 17 | 18 | use crate::{utils::length_from_raw_data, CertDer}; 19 | use sp_std::convert::TryFrom; 20 | 21 | #[allow(dead_code)] 22 | pub struct EphemeralKey<'a>(&'a [u8]); 23 | 24 | pub const PRIME256V1_OID: &[u8; 10] = &[0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x07]; 25 | impl<'a> TryFrom> for EphemeralKey<'a> { 26 | type Error = &'static str; 27 | 28 | fn try_from(value: CertDer<'a>) -> Result { 29 | let cert_der = value.0; 30 | 31 | let mut offset = cert_der 32 | .windows(PRIME256V1_OID.len()) 33 | .position(|window| window == PRIME256V1_OID) 34 | .ok_or("Certificate does not contain 'PRIME256V1_OID'")?; 35 | 36 | offset += PRIME256V1_OID.len() + 1; // OID length + TAG (0x03) 37 | 38 | // Obtain Public Key length 39 | let len = length_from_raw_data(cert_der, &mut offset)?; 40 | 41 | // Obtain Public Key 42 | offset += 1; 43 | let pub_k = cert_der.get(offset + 2..offset + len).ok_or("Index out of bounds")?; // skip "00 04" 44 | 45 | #[cfg(test)] 46 | println!("verifyRA ephemeral public key: {:x?}", pub_k); 47 | Ok(EphemeralKey(pub_k)) 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /teerex/sgx-verify/src/netscape_comment.rs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2021 Integritee AG and Supercomputing Systems AG 3 | 4 | Licensed under the MICROSOFT REFERENCE SOURCE LICENSE (MS-RSL) (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | https://referencesource.microsoft.com/license.html 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | 16 | */ 17 | 18 | use crate::{utils::length_from_raw_data, CertDer}; 19 | use frame_support::ensure; 20 | use sp_std::{convert::TryFrom, prelude::Vec}; 21 | 22 | pub struct NetscapeComment<'a> { 23 | pub attestation_raw: &'a [u8], 24 | pub sig: Vec, 25 | pub sig_cert: Vec, 26 | } 27 | 28 | pub const NS_CMT_OID: &[u8; 11] = 29 | &[0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x86, 0xF8, 0x42, 0x01, 0x0D]; 30 | 31 | impl<'a> TryFrom> for NetscapeComment<'a> { 32 | type Error = &'static str; 33 | 34 | fn try_from(value: CertDer<'a>) -> Result { 35 | // Search for Netscape Comment OID 36 | let cert_der = value.0; 37 | 38 | let mut offset = cert_der 39 | .windows(NS_CMT_OID.len()) 40 | .position(|window| window == NS_CMT_OID) 41 | .ok_or("Certificate does not contain 'ns_cmt_oid'")?; 42 | 43 | offset += 12; // 11 + TAG (0x04) 44 | 45 | #[cfg(test)] 46 | println!("netscape"); 47 | // Obtain Netscape Comment length 48 | let len = length_from_raw_data(cert_der, &mut offset)?; 49 | // Obtain Netscape Comment 50 | offset += 1; 51 | let netscape_raw = cert_der 52 | .get(offset..offset + len) 53 | .ok_or("Index out of bounds")? 54 | .split(|x| *x == 0x7C) // 0x7C is the character '|' 55 | .collect::>(); 56 | ensure!(netscape_raw.len() == 3, "Invalid netscape payload"); 57 | 58 | let sig = base64::decode(netscape_raw[1]).map_err(|_| "Signature Decoding Error")?; 59 | 60 | let sig_cert = base64::decode_config(netscape_raw[2], base64::STANDARD) 61 | .map_err(|_| "Cert Decoding Error")?; 62 | 63 | Ok(NetscapeComment { attestation_raw: netscape_raw[0], sig, sig_cert }) 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /teerex/sgx-verify/src/utils.rs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2021 Integritee AG and Supercomputing Systems AG 3 | 4 | Licensed under the MICROSOFT REFERENCE SOURCE LICENSE (MS-RSL) (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | https://referencesource.microsoft.com/license.html 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | 16 | */ 17 | 18 | fn safe_indexing_one(data: &[u8], idx: usize) -> Result { 19 | let elt = data.get(idx).ok_or("Index out of bounds")?; 20 | Ok(*elt as usize) 21 | } 22 | 23 | pub fn length_from_raw_data(data: &[u8], offset: &mut usize) -> Result { 24 | let mut len = safe_indexing_one(data, *offset)?; 25 | if len > 0x80 { 26 | len = (safe_indexing_one(data, *offset + 1)?) * 0x100 + 27 | (safe_indexing_one(data, *offset + 2)?); 28 | *offset += 2; 29 | } 30 | Ok(len) 31 | } 32 | 33 | #[cfg(test)] 34 | mod test { 35 | use super::*; 36 | use frame_support::assert_err; 37 | 38 | #[test] 39 | fn index_equal_length_returns_err() { 40 | // It was discovered a panic occurs if `index == data.len()` due to out of bound 41 | // indexing. Here the fix is tested. 42 | // 43 | // For context see: https://github.com/integritee-network/pallet-teerex/issues/34 44 | let data: [u8; 7] = [0, 1, 2, 3, 4, 5, 6]; 45 | assert_err!(safe_indexing_one(&data, data.len()), "Index out of bounds"); 46 | } 47 | 48 | #[test] 49 | fn safe_indexing_works() { 50 | let data: [u8; 7] = [0, 1, 2, 3, 4, 5, 6]; 51 | assert_eq!(safe_indexing_one(&data, 0), Ok(0)); 52 | assert_eq!(safe_indexing_one(&data, 3), Ok(3)); 53 | assert!(safe_indexing_one(&data, 10).is_err()); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /teerex/sgx-verify/test-data/dcap/dcap_quote_cert.der: -------------------------------------------------------------------------------- 1 | MIIEjjCCBDSgAwIBAgIVAMyWqlD3mkxu2FhYuPtrCp2bId06MAoGCCqGSM49BAMC 2 | MHExIzAhBgNVBAMMGkludGVsIFNHWCBQQ0sgUHJvY2Vzc29yIENBMRowGAYDVQQK 3 | DBFJbnRlbCBDb3Jwb3JhdGlvbjEUMBIGA1UEBwwLU2FudGEgQ2xhcmExCzAJBgNV 4 | BAgMAkNBMQswCQYDVQQGEwJVUzAeFw0yMjA1MjMxNTA3MDRaFw0yOTA1MjMxNTA3 5 | MDRaMHAxIjAgBgNVBAMMGUludGVsIFNHWCBQQ0sgQ2VydGlmaWNhdGUxGjAYBgNV 6 | BAoMEUludGVsIENvcnBvcmF0aW9uMRQwEgYDVQQHDAtTYW50YSBDbGFyYTELMAkG 7 | A1UECAwCQ0ExCzAJBgNVBAYTAlVTMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE 8 | 7pMyqXdHOoVduZAG8j3Wliu0FYWhT+tjjYj9Tdlmr51x8iudHDGTxVU2oeZCnhea 9 | tQuqCBJ0hV7A6gLn5fvXbqOCAqgwggKkMB8GA1UdIwQYMBaAFNDoqtp11/kuSReY 10 | PHsUZdDV8llNMGwGA1UdHwRlMGMwYaBfoF2GW2h0dHBzOi8vYXBpLnRydXN0ZWRz 11 | ZXJ2aWNlcy5pbnRlbC5jb20vc2d4L2NlcnRpZmljYXRpb24vdjMvcGNrY3JsP2Nh 12 | PXByb2Nlc3NvciZlbmNvZGluZz1kZXIwHQYDVR0OBBYEFPW1Uov5Ucy1jHgCeBpx 13 | b6/tkgpoMA4GA1UdDwEB/wQEAwIGwDAMBgNVHRMBAf8EAjAAMIIB1AYJKoZIhvhN 14 | AQ0BBIIBxTCCAcEwHgYKKoZIhvhNAQ0BAQQQs95DBukqMBDQJyrEH4oTxDCCAWQG 15 | CiqGSIb4TQENAQIwggFUMBAGCyqGSIb4TQENAQIBAgERMBAGCyqGSIb4TQENAQIC 16 | AgERMBAGCyqGSIb4TQENAQIDAgECMBAGCyqGSIb4TQENAQIEAgEEMBAGCyqGSIb4 17 | TQENAQIFAgEBMBEGCyqGSIb4TQENAQIGAgIAgDAQBgsqhkiG+E0BDQECBwIBBzAQ 18 | BgsqhkiG+E0BDQECCAIBADAQBgsqhkiG+E0BDQECCQIBADAQBgsqhkiG+E0BDQEC 19 | CgIBADAQBgsqhkiG+E0BDQECCwIBADAQBgsqhkiG+E0BDQECDAIBADAQBgsqhkiG 20 | +E0BDQECDQIBADAQBgsqhkiG+E0BDQECDgIBADAQBgsqhkiG+E0BDQECDwIBADAQ 21 | BgsqhkiG+E0BDQECEAIBADAQBgsqhkiG+E0BDQECEQIBCzAfBgsqhkiG+E0BDQEC 22 | EgQQERECBAGABwAAAAAAAAAAADAQBgoqhkiG+E0BDQEDBAIAADAUBgoqhkiG+E0B 23 | DQEEBAYAkG6hAAAwDwYKKoZIhvhNAQ0BBQoBADAKBggqhkjOPQQDAgNIADBFAiB4 24 | 20uxl1Ncxh6j1CtI1cJHsZxvWg00c1eRWWY2prTWPQIhAIhmmQUOcyRxubRUyGHW 25 | /SbMjV5v6ZVVQn2IIuZUWM64 -------------------------------------------------------------------------------- /teerex/sgx-verify/test-data/dcap/pck_crl.der: -------------------------------------------------------------------------------- 1 | 308201cd30820173020101300a06082a8648ce3d04030230703122302006035504030c19496e74656c205347582050434b20506c6174666f726d204341311a3018060355040a0c11496e74656c20436f72706f726174696f6e3114301206035504070c0b53616e746120436c617261310b300906035504080c024341310b3009060355040613025553170d3232313032333231353534345a170d3232313132323231353534345a3081a030330214639f139a5040fdcff191e8a4fb1bf086ed603971170d3232313032333231353534345a300c300a0603551d1504030a01013034021500959d533f9249dc1e513544cdc830bf19b7f1f301170d3232313032333231353534345a300c300a0603551d1504030a0101303302140fda43a00b68ea79b7c2deaeac0b498bdfb2af90170d3232313032333231353534345a300c300a0603551d1504030a0101a02f302d300a0603551d140403020101301f0603551d23041830168014956f5dcdbd1be1e94049c9d4f433ce01570bde54300a06082a8648ce3d040302034800304502200809ebf5477e3129f8efa8f3c67b4c204c879919efa78e08c7510a3631c0fe410221008e9cd32a3a1d97242a46cee7589013d220d7bf426607275af6fd3f17f78282a3 -------------------------------------------------------------------------------- /teerex/sgx-verify/test-data/dcap/pck_crl_issuer_chain.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN CERTIFICATE----- 2 | MIICmDCCAj6gAwIBAgIVANDoqtp11/kuSReYPHsUZdDV8llNMAoGCCqGSM49BAMC 3 | MGgxGjAYBgNVBAMMEUludGVsIFNHWCBSb290IENBMRowGAYDVQQKDBFJbnRlbCBD 4 | b3Jwb3JhdGlvbjEUMBIGA1UEBwwLU2FudGEgQ2xhcmExCzAJBgNVBAgMAkNBMQsw 5 | CQYDVQQGEwJVUzAeFw0xODA1MjExMDUwMTBaFw0zMzA1MjExMDUwMTBaMHExIzAh 6 | BgNVBAMMGkludGVsIFNHWCBQQ0sgUHJvY2Vzc29yIENBMRowGAYDVQQKDBFJbnRl 7 | bCBDb3Jwb3JhdGlvbjEUMBIGA1UEBwwLU2FudGEgQ2xhcmExCzAJBgNVBAgMAkNB 8 | MQswCQYDVQQGEwJVUzBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABL9q+NMp2IOg 9 | tdl1bk/uWZ5+TGQm8aCi8z78fs+fKCQ3d+uDzXnVTAT2ZhDCifyIuJwvN3wNBp9i 10 | HBSSMJMJrBOjgbswgbgwHwYDVR0jBBgwFoAUImUM1lqdNInzg7SVUr9QGzknBqww 11 | UgYDVR0fBEswSTBHoEWgQ4ZBaHR0cHM6Ly9jZXJ0aWZpY2F0ZXMudHJ1c3RlZHNl 12 | cnZpY2VzLmludGVsLmNvbS9JbnRlbFNHWFJvb3RDQS5kZXIwHQYDVR0OBBYEFNDo 13 | qtp11/kuSReYPHsUZdDV8llNMA4GA1UdDwEB/wQEAwIBBjASBgNVHRMBAf8ECDAG 14 | AQH/AgEAMAoGCCqGSM49BAMCA0gAMEUCIQCJgTbtVqOyZ1m3jqiAXM6QYa6r5sWS 15 | 4y/G7y8uIJGxdwIgRqPvBSKzzQagBLQq5s5A70pdoiaRJ8z/0uDz4NgV91k= 16 | -----END CERTIFICATE----- 17 | -----BEGIN CERTIFICATE----- 18 | MIICjzCCAjSgAwIBAgIUImUM1lqdNInzg7SVUr9QGzknBqwwCgYIKoZIzj0EAwIw 19 | aDEaMBgGA1UEAwwRSW50ZWwgU0dYIFJvb3QgQ0ExGjAYBgNVBAoMEUludGVsIENv 20 | cnBvcmF0aW9uMRQwEgYDVQQHDAtTYW50YSBDbGFyYTELMAkGA1UECAwCQ0ExCzAJ 21 | BgNVBAYTAlVTMB4XDTE4MDUyMTEwNDUxMFoXDTQ5MTIzMTIzNTk1OVowaDEaMBgG 22 | A1UEAwwRSW50ZWwgU0dYIFJvb3QgQ0ExGjAYBgNVBAoMEUludGVsIENvcnBvcmF0 23 | aW9uMRQwEgYDVQQHDAtTYW50YSBDbGFyYTELMAkGA1UECAwCQ0ExCzAJBgNVBAYT 24 | AlVTMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEC6nEwMDIYZOj/iPWsCzaEKi7 25 | 1OiOSLRFhWGjbnBVJfVnkY4u3IjkDYYL0MxO4mqsyYjlBalTVYxFP2sJBK5zlKOB 26 | uzCBuDAfBgNVHSMEGDAWgBQiZQzWWp00ifODtJVSv1AbOScGrDBSBgNVHR8ESzBJ 27 | MEegRaBDhkFodHRwczovL2NlcnRpZmljYXRlcy50cnVzdGVkc2VydmljZXMuaW50 28 | ZWwuY29tL0ludGVsU0dYUm9vdENBLmRlcjAdBgNVHQ4EFgQUImUM1lqdNInzg7SV 29 | Ur9QGzknBqwwDgYDVR0PAQH/BAQDAgEGMBIGA1UdEwEB/wQIMAYBAf8CAQEwCgYI 30 | KoZIzj0EAwIDSQAwRgIhAOW/5QkR+S9CiSDcNoowLuPRLsWGf/Yi7GSX94BgwTwg 31 | AiEA4J0lrHoMs+Xo5o/sX6O9QWxHRAvZUGOdRQ7cvqRXaqI= 32 | -----END CERTIFICATE----- -------------------------------------------------------------------------------- /teerex/sgx-verify/test-data/dcap/qe_identity.json: -------------------------------------------------------------------------------- 1 | {"enclaveIdentity":{"id":"QE","version":2,"issueDate":"2022-12-04T22:45:33Z","nextUpdate":"2023-01-03T22:45:33Z","tcbEvaluationDataNumber":13,"miscselect":"00000000","miscselectMask":"FFFFFFFF","attributes":"11000000000000000000000000000000","attributesMask":"FBFFFFFFFFFFFFFF0000000000000000","mrsigner":"8C4F5775D796503E96137F77C68A829A0056AC8DED70140B081B094490C57BFF","isvprodid":1,"tcbLevels":[{"tcb":{"isvsvn":6},"tcbDate":"2022-11-09T00:00:00Z","tcbStatus":"UpToDate"},{"tcb":{"isvsvn":5},"tcbDate":"2020-11-11T00:00:00Z","tcbStatus":"OutOfDate","advisoryIDs":["INTEL-SA-00477"]},{"tcb":{"isvsvn":4},"tcbDate":"2019-11-13T00:00:00Z","tcbStatus":"OutOfDate","advisoryIDs":["INTEL-SA-00334","INTEL-SA-00477"]},{"tcb":{"isvsvn":2},"tcbDate":"2019-05-15T00:00:00Z","tcbStatus":"OutOfDate","advisoryIDs":["INTEL-SA-00219","INTEL-SA-00293","INTEL-SA-00334","INTEL-SA-00477"]},{"tcb":{"isvsvn":1},"tcbDate":"2018-08-15T00:00:00Z","tcbStatus":"OutOfDate","advisoryIDs":["INTEL-SA-00202","INTEL-SA-00219","INTEL-SA-00293","INTEL-SA-00334","INTEL-SA-00477"]}]},"signature":"47accba321e57c20722a0d3d1db11c9b52661239857dc578ca1bde13976ee288cf39f72111ffe445c7389ef56447c79e30e6b83a8863ed9880de5bde4a8d5c91"} -------------------------------------------------------------------------------- /teerex/sgx-verify/test-data/dcap/qe_identity_cert.pem: -------------------------------------------------------------------------------- 1 | MIICizCCAjKgAwIBAgIUfjiC1ftVKUpASY5FhAPpFJG99FUwCgYIKoZIzj0EAwIw 2 | aDEaMBgGA1UEAwwRSW50ZWwgU0dYIFJvb3QgQ0ExGjAYBgNVBAoMEUludGVsIENv 3 | cnBvcmF0aW9uMRQwEgYDVQQHDAtTYW50YSBDbGFyYTELMAkGA1UECAwCQ0ExCzAJ 4 | BgNVBAYTAlVTMB4XDTE4MDUyMTEwNTAxMFoXDTI1MDUyMTEwNTAxMFowbDEeMBwG 5 | A1UEAwwVSW50ZWwgU0dYIFRDQiBTaWduaW5nMRowGAYDVQQKDBFJbnRlbCBDb3Jw 6 | b3JhdGlvbjEUMBIGA1UEBwwLU2FudGEgQ2xhcmExCzAJBgNVBAgMAkNBMQswCQYD 7 | VQQGEwJVUzBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABENFG8xzydWRfK92bmGv 8 | P+mAh91PEyV7Jh6FGJd5ndE9aBH7R3E4A7ubrlh/zN3C4xvpoouGlirMba+W2lju 9 | ypajgbUwgbIwHwYDVR0jBBgwFoAUImUM1lqdNInzg7SVUr9QGzknBqwwUgYDVR0f 10 | BEswSTBHoEWgQ4ZBaHR0cHM6Ly9jZXJ0aWZpY2F0ZXMudHJ1c3RlZHNlcnZpY2Vz 11 | LmludGVsLmNvbS9JbnRlbFNHWFJvb3RDQS5kZXIwHQYDVR0OBBYEFH44gtX7VSlK 12 | QEmORYQD6RSRvfRVMA4GA1UdDwEB/wQEAwIGwDAMBgNVHRMBAf8EAjAAMAoGCCqG 13 | SM49BAMCA0cAMEQCIB9C8wOAN/ImxDtGACV246KcqjagZOR0kyctyBrsGGJVAiAj 14 | ftbrNGsGU8YH211dRiYNoPPu19Zp/ze8JmhujB0oBw== -------------------------------------------------------------------------------- /teerex/sgx-verify/test-data/dcap/qe_identity_issuer_chain.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN CERTIFICATE----- 2 | MIICizCCAjKgAwIBAgIUfjiC1ftVKUpASY5FhAPpFJG99FUwCgYIKoZIzj0EAwIw 3 | aDEaMBgGA1UEAwwRSW50ZWwgU0dYIFJvb3QgQ0ExGjAYBgNVBAoMEUludGVsIENv 4 | cnBvcmF0aW9uMRQwEgYDVQQHDAtTYW50YSBDbGFyYTELMAkGA1UECAwCQ0ExCzAJ 5 | BgNVBAYTAlVTMB4XDTE4MDUyMTEwNTAxMFoXDTI1MDUyMTEwNTAxMFowbDEeMBwG 6 | A1UEAwwVSW50ZWwgU0dYIFRDQiBTaWduaW5nMRowGAYDVQQKDBFJbnRlbCBDb3Jw 7 | b3JhdGlvbjEUMBIGA1UEBwwLU2FudGEgQ2xhcmExCzAJBgNVBAgMAkNBMQswCQYD 8 | VQQGEwJVUzBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABENFG8xzydWRfK92bmGv 9 | P+mAh91PEyV7Jh6FGJd5ndE9aBH7R3E4A7ubrlh/zN3C4xvpoouGlirMba+W2lju 10 | ypajgbUwgbIwHwYDVR0jBBgwFoAUImUM1lqdNInzg7SVUr9QGzknBqwwUgYDVR0f 11 | BEswSTBHoEWgQ4ZBaHR0cHM6Ly9jZXJ0aWZpY2F0ZXMudHJ1c3RlZHNlcnZpY2Vz 12 | LmludGVsLmNvbS9JbnRlbFNHWFJvb3RDQS5kZXIwHQYDVR0OBBYEFH44gtX7VSlK 13 | QEmORYQD6RSRvfRVMA4GA1UdDwEB/wQEAwIGwDAMBgNVHRMBAf8EAjAAMAoGCCqG 14 | SM49BAMCA0cAMEQCIB9C8wOAN/ImxDtGACV246KcqjagZOR0kyctyBrsGGJVAiAj 15 | ftbrNGsGU8YH211dRiYNoPPu19Zp/ze8JmhujB0oBw== 16 | -----END CERTIFICATE----- 17 | -----BEGIN CERTIFICATE----- 18 | MIICjzCCAjSgAwIBAgIUImUM1lqdNInzg7SVUr9QGzknBqwwCgYIKoZIzj0EAwIw 19 | aDEaMBgGA1UEAwwRSW50ZWwgU0dYIFJvb3QgQ0ExGjAYBgNVBAoMEUludGVsIENv 20 | cnBvcmF0aW9uMRQwEgYDVQQHDAtTYW50YSBDbGFyYTELMAkGA1UECAwCQ0ExCzAJ 21 | BgNVBAYTAlVTMB4XDTE4MDUyMTEwNDUxMFoXDTQ5MTIzMTIzNTk1OVowaDEaMBgG 22 | A1UEAwwRSW50ZWwgU0dYIFJvb3QgQ0ExGjAYBgNVBAoMEUludGVsIENvcnBvcmF0 23 | aW9uMRQwEgYDVQQHDAtTYW50YSBDbGFyYTELMAkGA1UECAwCQ0ExCzAJBgNVBAYT 24 | AlVTMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEC6nEwMDIYZOj/iPWsCzaEKi7 25 | 1OiOSLRFhWGjbnBVJfVnkY4u3IjkDYYL0MxO4mqsyYjlBalTVYxFP2sJBK5zlKOB 26 | uzCBuDAfBgNVHSMEGDAWgBQiZQzWWp00ifODtJVSv1AbOScGrDBSBgNVHR8ESzBJ 27 | MEegRaBDhkFodHRwczovL2NlcnRpZmljYXRlcy50cnVzdGVkc2VydmljZXMuaW50 28 | ZWwuY29tL0ludGVsU0dYUm9vdENBLmRlcjAdBgNVHQ4EFgQUImUM1lqdNInzg7SV 29 | Ur9QGzknBqwwDgYDVR0PAQH/BAQDAgEGMBIGA1UdEwEB/wQIMAYBAf8CAQEwCgYI 30 | KoZIzj0EAwIDSQAwRgIhAOW/5QkR+S9CiSDcNoowLuPRLsWGf/Yi7GSX94BgwTwg 31 | AiEA4J0lrHoMs+Xo5o/sX6O9QWxHRAvZUGOdRQ7cvqRXaqI= 32 | -----END CERTIFICATE----- -------------------------------------------------------------------------------- /teerex/sgx-verify/test-data/dcap/root_ca_crl.der: -------------------------------------------------------------------------------- 1 | 308201213081c8020101300a06082a8648ce3d0403023068311a301806035504030c11496e74656c2053475820526f6f74204341311a3018060355040a0c11496e74656c20436f72706f726174696f6e3114301206035504070c0b53616e746120436c617261310b300906035504080c024341310b3009060355040613025553170d3232303431393038333131385a170d3233303431393038333131385aa02f302d300a0603551d140403020101301f0603551d2304183016801422650cd65a9d3489f383b49552bf501b392706ac300a06082a8648ce3d0403020348003045022100b7805acf592113584c45c8b0e11b2b8a9db462a215bbf8d4fd416539d7f5ab7502207ff56984c5199cf2b23d97d37b104ec0ebb5243674f41346887a6bdfbfdfeb42 -------------------------------------------------------------------------------- /teerex/sgx-verify/test-data/dcap/tcb_info_issuer_chain.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN CERTIFICATE----- 2 | MIICizCCAjKgAwIBAgIUfjiC1ftVKUpASY5FhAPpFJG99FUwCgYIKoZIzj0EAwIw 3 | aDEaMBgGA1UEAwwRSW50ZWwgU0dYIFJvb3QgQ0ExGjAYBgNVBAoMEUludGVsIENv 4 | cnBvcmF0aW9uMRQwEgYDVQQHDAtTYW50YSBDbGFyYTELMAkGA1UECAwCQ0ExCzAJ 5 | BgNVBAYTAlVTMB4XDTE4MDUyMTEwNTAxMFoXDTI1MDUyMTEwNTAxMFowbDEeMBwG 6 | A1UEAwwVSW50ZWwgU0dYIFRDQiBTaWduaW5nMRowGAYDVQQKDBFJbnRlbCBDb3Jw 7 | b3JhdGlvbjEUMBIGA1UEBwwLU2FudGEgQ2xhcmExCzAJBgNVBAgMAkNBMQswCQYD 8 | VQQGEwJVUzBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABENFG8xzydWRfK92bmGv 9 | P+mAh91PEyV7Jh6FGJd5ndE9aBH7R3E4A7ubrlh/zN3C4xvpoouGlirMba+W2lju 10 | ypajgbUwgbIwHwYDVR0jBBgwFoAUImUM1lqdNInzg7SVUr9QGzknBqwwUgYDVR0f 11 | BEswSTBHoEWgQ4ZBaHR0cHM6Ly9jZXJ0aWZpY2F0ZXMudHJ1c3RlZHNlcnZpY2Vz 12 | LmludGVsLmNvbS9JbnRlbFNHWFJvb3RDQS5kZXIwHQYDVR0OBBYEFH44gtX7VSlK 13 | QEmORYQD6RSRvfRVMA4GA1UdDwEB/wQEAwIGwDAMBgNVHRMBAf8EAjAAMAoGCCqG 14 | SM49BAMCA0cAMEQCIB9C8wOAN/ImxDtGACV246KcqjagZOR0kyctyBrsGGJVAiAj 15 | ftbrNGsGU8YH211dRiYNoPPu19Zp/ze8JmhujB0oBw== 16 | -----END CERTIFICATE----- 17 | -----BEGIN CERTIFICATE----- 18 | MIICjzCCAjSgAwIBAgIUImUM1lqdNInzg7SVUr9QGzknBqwwCgYIKoZIzj0EAwIw 19 | aDEaMBgGA1UEAwwRSW50ZWwgU0dYIFJvb3QgQ0ExGjAYBgNVBAoMEUludGVsIENv 20 | cnBvcmF0aW9uMRQwEgYDVQQHDAtTYW50YSBDbGFyYTELMAkGA1UECAwCQ0ExCzAJ 21 | BgNVBAYTAlVTMB4XDTE4MDUyMTEwNDUxMFoXDTQ5MTIzMTIzNTk1OVowaDEaMBgG 22 | A1UEAwwRSW50ZWwgU0dYIFJvb3QgQ0ExGjAYBgNVBAoMEUludGVsIENvcnBvcmF0 23 | aW9uMRQwEgYDVQQHDAtTYW50YSBDbGFyYTELMAkGA1UECAwCQ0ExCzAJBgNVBAYT 24 | AlVTMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEC6nEwMDIYZOj/iPWsCzaEKi7 25 | 1OiOSLRFhWGjbnBVJfVnkY4u3IjkDYYL0MxO4mqsyYjlBalTVYxFP2sJBK5zlKOB 26 | uzCBuDAfBgNVHSMEGDAWgBQiZQzWWp00ifODtJVSv1AbOScGrDBSBgNVHR8ESzBJ 27 | MEegRaBDhkFodHRwczovL2NlcnRpZmljYXRlcy50cnVzdGVkc2VydmljZXMuaW50 28 | ZWwuY29tL0ludGVsU0dYUm9vdENBLmRlcjAdBgNVHQ4EFgQUImUM1lqdNInzg7SV 29 | Ur9QGzknBqwwDgYDVR0PAQH/BAQDAgEGMBIGA1UdEwEB/wQIMAYBAf8CAQEwCgYI 30 | KoZIzj0EAwIDSQAwRgIhAOW/5QkR+S9CiSDcNoowLuPRLsWGf/Yi7GSX94BgwTwg 31 | AiEA4J0lrHoMs+Xo5o/sX6O9QWxHRAvZUGOdRQ7cvqRXaqI= 32 | -----END CERTIFICATE----- -------------------------------------------------------------------------------- /teerex/sgx-verify/test-data/dcap/test2_tcb_info.json: -------------------------------------------------------------------------------- 1 | {"tcbInfo":{"id":"SGX","version":3,"issueDate":"2023-09-13T09:19:56Z","nextUpdate":"2023-10-13T09:19:56Z","fmspc":"00606a000000","pceId":"0000","tcbType":0,"tcbEvaluationDataNumber":15,"tcbLevels":[{"tcb":{"sgxtcbcomponents":[{"svn":11,"category":"BIOS","type":"Early Microcode Update"},{"svn":11,"category":"OS/VMM","type":"SGX Late Microcode Update"},{"svn":3,"category":"OS/VMM","type":"TXT SINIT"},{"svn":3,"category":"BIOS"},{"svn":255},{"svn":255},{"svn":1},{"svn":0},{"svn":0},{"svn":0},{"svn":0},{"svn":0},{"svn":0},{"svn":0},{"svn":0},{"svn":0}],"pcesvn":13},"tcbDate":"2023-02-15T00:00:00Z","tcbStatus":"SWHardeningNeeded","advisoryIDs":["INTEL-SA-00615"]},{"tcb":{"sgxtcbcomponents":[{"svn":11,"category":"BIOS","type":"Early Microcode Update"},{"svn":11,"category":"OS/VMM","type":"SGX Late Microcode Update"},{"svn":3,"category":"OS/VMM","type":"TXT SINIT"},{"svn":3,"category":"BIOS"},{"svn":255},{"svn":255},{"svn":0},{"svn":0},{"svn":0},{"svn":0},{"svn":0},{"svn":0},{"svn":0},{"svn":0},{"svn":0},{"svn":0}],"pcesvn":13},"tcbDate":"2023-02-15T00:00:00Z","tcbStatus":"ConfigurationAndSWHardeningNeeded","advisoryIDs":["INTEL-SA-00615"]},{"tcb":{"sgxtcbcomponents":[{"svn":7,"category":"BIOS","type":"Early Microcode Update"},{"svn":9,"category":"OS/VMM","type":"SGX Late Microcode Update"},{"svn":3,"category":"OS/VMM","type":"TXT SINIT"},{"svn":3,"category":"BIOS"},{"svn":255},{"svn":255},{"svn":1},{"svn":0},{"svn":0},{"svn":0},{"svn":0},{"svn":0},{"svn":0},{"svn":0},{"svn":0},{"svn":0}],"pcesvn":13},"tcbDate":"2022-08-10T00:00:00Z","tcbStatus":"OutOfDate","advisoryIDs":["INTEL-SA-00657","INTEL-SA-00730","INTEL-SA-00738","INTEL-SA-00767","INTEL-SA-00615"]},{"tcb":{"sgxtcbcomponents":[{"svn":7,"category":"BIOS","type":"Early Microcode Update"},{"svn":9,"category":"OS/VMM","type":"SGX Late Microcode Update"},{"svn":3,"category":"OS/VMM","type":"TXT SINIT"},{"svn":3,"category":"BIOS"},{"svn":255},{"svn":255},{"svn":0},{"svn":0},{"svn":0},{"svn":0},{"svn":0},{"svn":0},{"svn":0},{"svn":0},{"svn":0},{"svn":0}],"pcesvn":13},"tcbDate":"2022-08-10T00:00:00Z","tcbStatus":"OutOfDateConfigurationNeeded","advisoryIDs":["INTEL-SA-00657","INTEL-SA-00730","INTEL-SA-00738","INTEL-SA-00767","INTEL-SA-00615"]},{"tcb":{"sgxtcbcomponents":[{"svn":4,"category":"BIOS","type":"Early Microcode Update"},{"svn":4,"category":"OS/VMM","type":"SGX Late Microcode Update"},{"svn":3,"category":"OS/VMM","type":"TXT SINIT"},{"svn":3,"category":"BIOS"},{"svn":255},{"svn":255},{"svn":0},{"svn":0},{"svn":0},{"svn":0},{"svn":0},{"svn":0},{"svn":0},{"svn":0},{"svn":0},{"svn":0}],"pcesvn":11},"tcbDate":"2021-11-10T00:00:00Z","tcbStatus":"OutOfDate","advisoryIDs":["INTEL-SA-00586","INTEL-SA-00614","INTEL-SA-00615","INTEL-SA-00657","INTEL-SA-00730","INTEL-SA-00738","INTEL-SA-00767"]},{"tcb":{"sgxtcbcomponents":[{"svn":4,"category":"BIOS","type":"Early Microcode Update"},{"svn":4,"category":"OS/VMM","type":"SGX Late Microcode Update"},{"svn":3,"category":"OS/VMM","type":"TXT SINIT"},{"svn":3,"category":"BIOS"},{"svn":255},{"svn":255},{"svn":0},{"svn":0},{"svn":0},{"svn":0},{"svn":0},{"svn":0},{"svn":0},{"svn":0},{"svn":0},{"svn":0}],"pcesvn":10},"tcbDate":"2020-11-11T00:00:00Z","tcbStatus":"OutOfDate","advisoryIDs":["INTEL-SA-00477","INTEL-SA-00586","INTEL-SA-00614","INTEL-SA-00615","INTEL-SA-00657","INTEL-SA-00730","INTEL-SA-00738","INTEL-SA-00767"]},{"tcb":{"sgxtcbcomponents":[{"svn":4,"category":"BIOS","type":"Early Microcode Update"},{"svn":4,"category":"OS/VMM","type":"SGX Late Microcode Update"},{"svn":3,"category":"OS/VMM","type":"TXT SINIT"},{"svn":3,"category":"BIOS"},{"svn":255},{"svn":255},{"svn":0},{"svn":0},{"svn":0},{"svn":0},{"svn":0},{"svn":0},{"svn":0},{"svn":0},{"svn":0},{"svn":0}],"pcesvn":5},"tcbDate":"2018-01-04T00:00:00Z","tcbStatus":"OutOfDate","advisoryIDs":["INTEL-SA-00106","INTEL-SA-00115","INTEL-SA-00135","INTEL-SA-00203","INTEL-SA-00220","INTEL-SA-00233","INTEL-SA-00270","INTEL-SA-00293","INTEL-SA-00320","INTEL-SA-00329","INTEL-SA-00381","INTEL-SA-00389","INTEL-SA-00477","INTEL-SA-00586","INTEL-SA-00614","INTEL-SA-00615","INTEL-SA-00657","INTEL-SA-00730","INTEL-SA-00738","INTEL-SA-00767"]}]},"signature":"bfedea1485a392d1d8062daa3f6dfd5d072ca9870041aa95150575d59bc5e568afa3c2803fd2c02eb7c018dac9b8137244eddd40fd04ed789f22714b1729b329"} 2 | -------------------------------------------------------------------------------- /teerex/sgx-verify/test-data/enclave-signing-pubkey-TEST4.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/integritee-network/pallets/dbed9bd1968b26359dc8e7a0d0a08c9f3730e939/teerex/sgx-verify/test-data/enclave-signing-pubkey-TEST4.bin -------------------------------------------------------------------------------- /teerex/sgx-verify/test-data/enclave-signing-pubkey-TEST5.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/integritee-network/pallets/dbed9bd1968b26359dc8e7a0d0a08c9f3730e939/teerex/sgx-verify/test-data/enclave-signing-pubkey-TEST5.bin -------------------------------------------------------------------------------- /teerex/sgx-verify/test-data/enclave-signing-pubkey-TEST6.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/integritee-network/pallets/dbed9bd1968b26359dc8e7a0d0a08c9f3730e939/teerex/sgx-verify/test-data/enclave-signing-pubkey-TEST6.bin -------------------------------------------------------------------------------- /teerex/sgx-verify/test-data/enclave-signing-pubkey-TEST7.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/integritee-network/pallets/dbed9bd1968b26359dc8e7a0d0a08c9f3730e939/teerex/sgx-verify/test-data/enclave-signing-pubkey-TEST7.bin -------------------------------------------------------------------------------- /teerex/sgx-verify/test-data/enclave-signing-pubkey-TEST8-PRODUCTION.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/integritee-network/pallets/dbed9bd1968b26359dc8e7a0d0a08c9f3730e939/teerex/sgx-verify/test-data/enclave-signing-pubkey-TEST8-PRODUCTION.bin -------------------------------------------------------------------------------- /teerex/sgx-verify/test-data/ra_dcap_dump_quote.ra: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/integritee-network/pallets/dbed9bd1968b26359dc8e7a0d0a08c9f3730e939/teerex/sgx-verify/test-data/ra_dcap_dump_quote.ra -------------------------------------------------------------------------------- /teerex/sgx-verify/test-data/ra_dump_cert_TEST4.der: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/integritee-network/pallets/dbed9bd1968b26359dc8e7a0d0a08c9f3730e939/teerex/sgx-verify/test-data/ra_dump_cert_TEST4.der -------------------------------------------------------------------------------- /teerex/sgx-verify/test-data/ra_dump_cert_TEST5.der: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/integritee-network/pallets/dbed9bd1968b26359dc8e7a0d0a08c9f3730e939/teerex/sgx-verify/test-data/ra_dump_cert_TEST5.der -------------------------------------------------------------------------------- /teerex/sgx-verify/test-data/ra_dump_cert_TEST6.der: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/integritee-network/pallets/dbed9bd1968b26359dc8e7a0d0a08c9f3730e939/teerex/sgx-verify/test-data/ra_dump_cert_TEST6.der -------------------------------------------------------------------------------- /teerex/sgx-verify/test-data/ra_dump_cert_TEST7.der: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/integritee-network/pallets/dbed9bd1968b26359dc8e7a0d0a08c9f3730e939/teerex/sgx-verify/test-data/ra_dump_cert_TEST7.der -------------------------------------------------------------------------------- /teerex/sgx-verify/test-data/ra_dump_cert_TEST8_PRODUCTION.der: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/integritee-network/pallets/dbed9bd1968b26359dc8e7a0d0a08c9f3730e939/teerex/sgx-verify/test-data/ra_dump_cert_TEST8_PRODUCTION.der -------------------------------------------------------------------------------- /teerex/src/test_helpers.rs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2021 Integritee AG and Supercomputing Systems AG 3 | 4 | Licensed under the MICROSOFT REFERENCE SOURCE LICENSE (MS-RSL) (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | https://referencesource.microsoft.com/license.html 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | 16 | */ 17 | 18 | use crate::{Config, Pallet, SgxTcbInfo}; 19 | use frame_support::assert_ok; 20 | use frame_system::RawOrigin; 21 | use sgx_verify::test_data::dcap::{ 22 | QE_IDENTITY_ISSUER_CHAIN, QUOTING_ENCLAVE, QUOTING_ENCLAVE_SIGNATURE, TCB_INFO, 23 | TCB_INFO_CERTIFICATE_CHAIN, TCB_INFO_FMSPC, TCB_INFO_SIGNATURE, 24 | }; 25 | use teerex_primitives::SgxTcbInfoOnChain; 26 | 27 | /// Registers a predefined quoting enclave. 28 | /// 29 | /// This can be done by any account. 30 | pub fn register_test_quoting_enclave(account: T::AccountId) 31 | where 32 | T: Config, 33 | ::Hash: From<[u8; 32]>, 34 | { 35 | let quoting_enclave = QUOTING_ENCLAVE; 36 | let signature = QUOTING_ENCLAVE_SIGNATURE; 37 | let certificate_chain = QE_IDENTITY_ISSUER_CHAIN; 38 | 39 | assert_ok!(Pallet::::register_quoting_enclave( 40 | RawOrigin::Signed(account).into(), 41 | quoting_enclave.to_vec(), 42 | signature.to_vec(), 43 | certificate_chain.to_vec(), 44 | )); 45 | } 46 | 47 | /// Registers a predefined TCB-Info. 48 | /// 49 | /// This can be done by any account. 50 | pub fn register_test_tcb_info(account: T::AccountId) 51 | where 52 | T: Config, 53 | ::Hash: From<[u8; 32]>, 54 | { 55 | let tcb_info = TCB_INFO; 56 | let signature = TCB_INFO_SIGNATURE; 57 | let certificate_chain = TCB_INFO_CERTIFICATE_CHAIN; 58 | 59 | assert_ok!(Pallet::::register_tcb_info( 60 | RawOrigin::Signed(account).into(), 61 | tcb_info.to_vec(), 62 | signature.to_vec(), 63 | certificate_chain.to_vec(), 64 | )); 65 | } 66 | 67 | /// Gets the above tcb info. 68 | pub fn get_test_tcb_info() -> SgxTcbInfoOnChain 69 | where 70 | T: Config, 71 | ::Hash: From<[u8; 32]>, 72 | { 73 | SgxTcbInfo::::get(TCB_INFO_FMSPC).unwrap() 74 | } 75 | -------------------------------------------------------------------------------- /teerex/src/tests/mod.rs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2021 Integritee AG and Supercomputing Systems AG 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | 16 | */ 17 | mod test_cases; 18 | -------------------------------------------------------------------------------- /test-utils/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "test-utils" 3 | description = "A crate for common utilities for tests" 4 | version = "0.1.0" 5 | authors = ["Integritee AG "] 6 | homepage = "https://integritee.network/" 7 | repository = "https://github.com/integritee-network/pallets/" 8 | license = "Apache-2.0" 9 | edition = "2021" 10 | 11 | [lints] 12 | workspace = true 13 | 14 | [dependencies] 15 | log = { workspace = true } 16 | 17 | sgx-verify = { default-features = false, features = ["test-data"], path = "../teerex/sgx-verify" } 18 | teerex-primitives = { default-features = false, path = "../primitives/teerex" } 19 | 20 | [features] 21 | default = ['std'] 22 | std = ["log/std", "sgx-verify/std", "teerex-primitives/std"] 23 | -------------------------------------------------------------------------------- /test-utils/src/lib.rs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2021 Integritee AG and Supercomputing Systems AG 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | 16 | */ 17 | 18 | #![cfg_attr(not(feature = "std"), no_std)] 19 | 20 | pub use sgx_verify::test_data; 21 | pub use teerex_primitives::{MrEnclave, SgxEnclave}; 22 | 23 | pub fn get_signer>(pubkey: &[u8; 32]) -> AccountId { 24 | AccountId::from(*pubkey) 25 | } 26 | 27 | pub trait TestEnclave { 28 | fn test_enclave() -> SgxEnclave; 29 | fn with_mr_enclave(self, mr_enclave: MrEnclave) -> SgxEnclave; 30 | fn with_timestamp(self, timestamp: u64) -> SgxEnclave; 31 | } 32 | 33 | impl TestEnclave for SgxEnclave { 34 | fn test_enclave() -> Self { 35 | SgxEnclave::default() 36 | } 37 | 38 | fn with_mr_enclave(mut self, mr_enclave: MrEnclave) -> Self { 39 | self.mr_enclave = mr_enclave; 40 | self 41 | } 42 | 43 | fn with_timestamp(mut self, timestamp: u64) -> Self { 44 | self.timestamp = timestamp; 45 | self 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /xcm-transactor/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "pallet-xcm-transactor" 3 | description = "A pallet which can send various transact messages" 4 | version = "0.1.0" 5 | authors = ["Integritee AG "] 6 | homepage = "https://integritee.network/" 7 | repository = "https://github.com/integritee-network/pallets/" 8 | license = "(GPL-3.0-only)" 9 | edition = "2021" 10 | 11 | [lints] 12 | workspace = true 13 | 14 | [dependencies] 15 | log = { workspace = true } 16 | parity-scale-codec = { workspace = true } 17 | scale-info = { workspace = true } 18 | 19 | # Local 20 | xcm-transactor-primitives = { default-features = false, path = "../primitives/xcm-transactor", features = ["dot", "ksm"] } 21 | 22 | # substrate 23 | frame-benchmarking = { workspace = true, optional = true } 24 | frame-support = { workspace = true } 25 | frame-system = { workspace = true } 26 | sp-core = { workspace = true } 27 | sp-io = { workspace = true } 28 | sp-runtime = { workspace = true } 29 | sp-std = { workspace = true } 30 | 31 | # xcm/polkadot 32 | staging-xcm = { workspace = true } 33 | 34 | # cumulus 35 | cumulus-primitives-core = { workspace = true } 36 | 37 | [dev-dependencies] 38 | sp-externalities = { workspace = true } 39 | frame-benchmarking = { workspace = true } 40 | hex-literal = { workspace = true } 41 | pallet-balances = { workspace = true } 42 | test-utils = { path = "../test-utils" } 43 | sp-keyring = { workspace = true } 44 | 45 | # Re-introduce subxt whe we need it, maintaining it is a pain. 46 | # Remove unnecessary wasm stuff by disabling default features, also it lead 47 | # to a linker issue once: https://github.com/integritee-network/pallets/pull/159. 48 | # subxt = { version = "0.29.0", default-features = false } 49 | 50 | 51 | [features] 52 | default = ["std"] 53 | std = [ 54 | "cumulus-primitives-core/std", 55 | "frame-benchmarking?/std", 56 | "frame-support/std", 57 | "frame-system/std", 58 | "log/std", 59 | "parity-scale-codec/std", 60 | "scale-info/std", 61 | "sp-core/std", 62 | "sp-io/std", 63 | "sp-runtime/std", 64 | "sp-std/std", 65 | "xcm-transactor-primitives/std", 66 | "staging-xcm/std", 67 | "pallet-balances/std", 68 | "sp-externalities/std", 69 | "sp-keyring/std", 70 | ] 71 | runtime-benchmarks = [ 72 | "frame-benchmarking/runtime-benchmarks", 73 | "cumulus-primitives-core/runtime-benchmarks", 74 | "frame-support/runtime-benchmarks", 75 | "frame-system/runtime-benchmarks", 76 | "pallet-balances/runtime-benchmarks", 77 | "sp-runtime/runtime-benchmarks", 78 | "staging-xcm/runtime-benchmarks", 79 | ] 80 | 81 | try-runtime = [ 82 | "frame-support/try-runtime", 83 | "frame-system/try-runtime", 84 | "pallet-balances/try-runtime", 85 | "sp-runtime/try-runtime", 86 | ] 87 | -------------------------------------------------------------------------------- /xcm-transactor/src/lib.rs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2021 Integritee AG & Parity Technologies (UK) Ltd. 3 | 4 | Licenced under GNU General Public License as published by 5 | the Free Software Foundation, either version 3 of the License, or 6 | (at your option) any later version. You may obtain a copy of the 7 | License at 8 | 9 | . 10 | 11 | Unless required by applicable law or agreed to in writing, software 12 | distributed under the License is distributed on an "AS IS" BASIS, 13 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | See the License for the specific language governing permissions and 15 | limitations under the License. 16 | */ 17 | 18 | #![cfg_attr(not(feature = "std"), no_std)] 19 | 20 | pub use pallet::*; 21 | 22 | #[cfg(test)] 23 | mod mock; 24 | // Reacivating the tests again when we need them. 25 | // Maintaining subxt is a pain currently. 26 | // #[cfg(test)] 27 | // mod tests; 28 | 29 | const LOG: &str = "xcm-transactor"; 30 | 31 | #[frame_support::pallet] 32 | pub mod pallet { 33 | use super::LOG; 34 | use cumulus_primitives_core::ParaId; 35 | use frame_support::pallet_prelude::*; 36 | use frame_system::pallet_prelude::*; 37 | use sp_std::vec; 38 | use staging_xcm::latest::{prelude::*, Weight as XcmWeight}; 39 | use xcm_transactor_primitives::*; 40 | 41 | #[pallet::pallet] 42 | #[pallet::without_storage_info] 43 | pub struct Pallet(PhantomData); 44 | 45 | #[pallet::config] 46 | pub trait Config: frame_system::Config { 47 | type RuntimeEvent: From> + IsType<::RuntimeEvent>; 48 | 49 | type RelayCallBuilder: BuildRelayCall; 50 | 51 | type XcmSender: SendXcm; 52 | 53 | type SwapOrigin: EnsureOrigin; 54 | 55 | #[pallet::constant] 56 | type ShellRuntimeParaId: Get; 57 | 58 | #[pallet::constant] 59 | type IntegriteeKsmParaId: Get; 60 | 61 | type WeightInfo; 62 | } 63 | 64 | #[pallet::event] 65 | #[pallet::generate_deposit(pub(super) fn deposit_event)] 66 | pub enum Event { 67 | SentXcm { hash: XcmHash }, 68 | SwapTransactSent { para_a: ParaId, para_b: ParaId }, 69 | } 70 | 71 | #[pallet::error] 72 | pub enum Error { 73 | /// The swap IDs do not correspond to the runtime-configured value. 74 | InvalidSwapIds, 75 | /// Swap IDs need to be different. 76 | SwapIdsEqual, 77 | /// The desired destination was unreachable, generally because there is a no way of routing 78 | /// to it. 79 | Unreachable, 80 | /// Destination is routable, but there is some issue with the transport mechanism. This is 81 | /// considered fatal. 82 | Transport, 83 | /// Destination is known to be unroutable. This is considered fatal. 84 | Unroutable, 85 | /// The given message cannot be translated into a format that the destination can be expected 86 | /// to interpret. 87 | DestinationUnsupported, 88 | /// Fees needed to be paid in order to send the message were unavailable. 89 | FeesNotMet, 90 | /// Some XCM send error occurred. 91 | XcmSendError, 92 | } 93 | 94 | impl From for Error { 95 | fn from(e: SendError) -> Self { 96 | // Inspired by https://github.com/paritytech/polkadot/blob/09b61286da11921a3dda0a8e4015ceb9ef9cffca/xcm/pallet-xcm/src/lib.rs#L447 97 | match e { 98 | SendError::NotApplicable => Error::::Unreachable, 99 | SendError::Transport(_) => Error::::Transport, 100 | SendError::Unroutable => Error::::Unroutable, 101 | SendError::DestinationUnsupported => Error::::DestinationUnsupported, 102 | SendError::Fees => Error::::FeesNotMet, 103 | _ => Error::::XcmSendError, 104 | } 105 | } 106 | } 107 | 108 | #[pallet::call] 109 | impl Pallet { 110 | /// Send swap instruction to the relay chain to swap the slot lease of our two parachains. 111 | /// This needs to be done from within a pallet as the `XCM` origin must be the parachain 112 | /// itself. 113 | /// 114 | /// This function should really only be called once via governance, on each chain that 115 | /// performs the slot swap. 116 | /// 117 | /// Sane weight values: 118 | /// Rococo-Local as of 11.01.2022: 119 | /// * xcm_weight: 10_000_000_000 120 | /// * buy_execution_weight: 500_000_000 121 | /// Kusama as of 11.01.2022: 122 | /// * xcm_weight: 10_000_000_000 123 | /// * buy_execution_weight: 5_000_000_000 124 | /// 125 | #[pallet::call_index(0)] 126 | #[pallet::weight({46_200_000})] // Arbitrary weight. 127 | pub fn send_swap_ump( 128 | origin: OriginFor, 129 | self_id: ParaId, 130 | other_id: ParaId, 131 | xcm_weight: XcmWeight, 132 | buy_execution_fee: u128, 133 | ) -> DispatchResult { 134 | T::SwapOrigin::ensure_origin(origin)?; 135 | ensure!(self_id != other_id, Error::::SwapIdsEqual); 136 | 137 | let valid_ids = 138 | [T::ShellRuntimeParaId::get().into(), T::IntegriteeKsmParaId::get().into()]; 139 | 140 | ensure!(valid_ids.contains(&self_id), Error::::InvalidSwapIds); 141 | ensure!(valid_ids.contains(&other_id), Error::::InvalidSwapIds); 142 | 143 | let call = T::RelayCallBuilder::swap_call(self_id, other_id); 144 | let xcm_message = 145 | T::RelayCallBuilder::construct_transact_xcm(call, xcm_weight, buy_execution_fee); 146 | 147 | let (hash, _price) = 148 | send_xcm::(Parent.into(), xcm_message).map_err(|e| { 149 | log::error!(target: LOG, "Error sending xcm: {:?}", e); 150 | Error::::from(e) 151 | })?; 152 | 153 | Self::deposit_event(Event::::SentXcm { hash }); 154 | Self::deposit_event(Event::::SwapTransactSent { para_a: self_id, para_b: other_id }); 155 | Ok(()) 156 | } 157 | } 158 | } 159 | -------------------------------------------------------------------------------- /xcm-transactor/src/mock.rs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2021 Integritee AG & Parity Technologies (UK) Ltd. 3 | 4 | Licenced under GNU General Public License as published by 5 | the Free Software Foundation, either version 3 of the License, or 6 | (at your option) any later version. You may obtain a copy of the 7 | License at 8 | 9 | . 10 | 11 | Unless required by applicable law or agreed to in writing, software 12 | distributed under the License is distributed on an "AS IS" BASIS, 13 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | See the License for the specific language governing permissions and 15 | limitations under the License. 16 | */ 17 | 18 | use crate as pallet_xcm_transactor; 19 | use core::default::Default; 20 | use frame_support::{derive_impl, parameter_types}; 21 | use frame_system::EnsureRoot; 22 | use sp_core::H256; 23 | use sp_runtime::{ 24 | generic, 25 | traits::{BlakeTwo256, IdentifyAccount, IdentityLookup, Verify}, 26 | }; 27 | use staging_xcm::latest::prelude::*; 28 | use xcm_transactor_primitives::*; 29 | 30 | pub type Signature = sp_runtime::MultiSignature; 31 | pub type AccountId = <::Signer as IdentifyAccount>::AccountId; 32 | pub type Address = sp_runtime::MultiAddress; 33 | 34 | pub type BlockNumber = u32; 35 | pub type Header = generic::Header; 36 | pub type UncheckedExtrinsic = 37 | generic::UncheckedExtrinsic; 38 | 39 | pub type SignedExtra = ( 40 | frame_system::CheckSpecVersion, 41 | frame_system::CheckTxVersion, 42 | frame_system::CheckGenesis, 43 | frame_system::CheckEra, 44 | frame_system::CheckNonce, 45 | frame_system::CheckWeight, 46 | ); 47 | 48 | frame_support::construct_runtime!( 49 | pub enum Test 50 | { 51 | System: frame_system, 52 | Balances: pallet_balances, 53 | XcmTransactor: pallet_xcm_transactor, 54 | } 55 | ); 56 | 57 | parameter_types! { 58 | pub const BlockHashCount: u32 = 250; 59 | } 60 | #[derive_impl(frame_system::config_preludes::SolochainDefaultConfig as frame_system::DefaultConfig)] 61 | impl frame_system::Config for Test { 62 | type BaseCallFilter = frame_support::traits::Everything; 63 | type BlockWeights = (); 64 | type BlockLength = (); 65 | type Block = generic::Block; 66 | type DbWeight = (); 67 | type RuntimeOrigin = RuntimeOrigin; 68 | type Nonce = u64; 69 | type RuntimeCall = RuntimeCall; 70 | type RuntimeTask = RuntimeTask; 71 | type Hash = H256; 72 | type Hashing = BlakeTwo256; 73 | type AccountId = AccountId; 74 | type Lookup = IdentityLookup; 75 | type RuntimeEvent = RuntimeEvent; 76 | type BlockHashCount = BlockHashCount; 77 | type Version = (); 78 | type PalletInfo = PalletInfo; 79 | type AccountData = pallet_balances::AccountData; 80 | type OnNewAccount = (); 81 | type OnKilledAccount = (); 82 | type SystemWeightInfo = (); 83 | type SS58Prefix = (); 84 | type OnSetCode = (); 85 | type MaxConsumers = frame_support::traits::ConstU32<16>; 86 | } 87 | 88 | pub type Balance = u64; 89 | 90 | parameter_types! { 91 | pub const ExistentialDeposit: u64 = 1; 92 | } 93 | 94 | impl pallet_balances::Config for Test { 95 | type MaxLocks = (); 96 | type Balance = u64; 97 | type DustRemoval = (); 98 | type RuntimeEvent = RuntimeEvent; 99 | type ExistentialDeposit = ExistentialDeposit; 100 | type AccountStore = System; 101 | type WeightInfo = (); 102 | type MaxReserves = (); 103 | type ReserveIdentifier = (); 104 | type RuntimeFreezeReason = (); 105 | type FreezeIdentifier = (); 106 | type MaxFreezes = (); 107 | type RuntimeHoldReason = (); 108 | type DoneSlashHandler = (); 109 | } 110 | 111 | parameter_types! { 112 | pub const ShellRuntimeParaId: u32 = 2223u32; 113 | pub const IntegriteeKsmParaId: u32 = 2015u32; 114 | } 115 | 116 | pub struct DummySendXcm; 117 | impl SendXcm for DummySendXcm { 118 | type Ticket = (); 119 | 120 | fn validate( 121 | _destination: &mut Option, 122 | _message: &mut Option>, 123 | ) -> SendResult { 124 | Ok(((), Assets::new())) 125 | } 126 | 127 | fn deliver(_ticket: Self::Ticket) -> Result { 128 | Ok([0; 32]) 129 | } 130 | } 131 | 132 | impl pallet_xcm_transactor::Config for Test { 133 | type RuntimeEvent = RuntimeEvent; 134 | type RelayCallBuilder = RelayCallBuilder; 135 | type XcmSender = DummySendXcm; 136 | type SwapOrigin = EnsureRoot; 137 | type ShellRuntimeParaId = ShellRuntimeParaId; 138 | type IntegriteeKsmParaId = IntegriteeKsmParaId; 139 | type WeightInfo = (); 140 | } 141 | -------------------------------------------------------------------------------- /xcm-transactor/src/tests.rs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2021 Integritee AG & Parity Technologies (UK) Ltd. 3 | 4 | Licenced under GNU General Public License as published by 5 | the Free Software Foundation, either version 3 of the License, or 6 | (at your option) any later version. You may obtain a copy of the 7 | License at 8 | 9 | . 10 | 11 | Unless required by applicable law or agreed to in writing, software 12 | distributed under the License is distributed on an "AS IS" BASIS, 13 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | See the License for the specific language governing permissions and 15 | limitations under the License. 16 | */ 17 | 18 | use crate::{mock::*, Config, Error}; 19 | use cumulus_primitives_core::ParaId; 20 | use frame_support::{assert_noop, assert_ok}; 21 | use parity_scale_codec::{Decode, Encode}; 22 | use sp_keyring::Sr25519Keyring as Keyring; 23 | use xcm_transactor_primitives::*; 24 | 25 | #[subxt::subxt(runtime_metadata_url = "wss://kusama-rpc.polkadot.io:443")] 26 | pub mod kusama {} 27 | 28 | use kusama::runtime_types::{ 29 | kusama_runtime::RuntimeCall as KusamaRuntimeCall, 30 | polkadot_runtime_common::paras_registrar::pallet::Call as KsmRegistrarCall, 31 | }; 32 | 33 | #[test] 34 | fn swap_ump_fails_not_privileged() { 35 | new_test_ext().execute_with(|| { 36 | let alice = Keyring::Alice.to_account_id(); 37 | assert_noop!( 38 | XcmTransactor::send_swap_ump( 39 | RuntimeOrigin::signed(alice), 40 | ParaId::from(2015), 41 | ParaId::from(2014), 42 | 10_000_000_000u64.into(), 43 | 10_000_000_000u64.into() 44 | ), 45 | sp_runtime::DispatchError::BadOrigin 46 | ); 47 | }) 48 | } 49 | 50 | #[test] 51 | fn swap_ump_fails_equal_para_ids() { 52 | new_test_ext().execute_with(|| { 53 | assert_noop!( 54 | XcmTransactor::send_swap_ump( 55 | RuntimeOrigin::root(), 56 | ParaId::from(2015), 57 | ParaId::from(2015), 58 | 10_000_000_000u64.into(), 59 | 10_000_000_000u64.into() 60 | ), 61 | Error::::SwapIdsEqual 62 | ); 63 | }) 64 | } 65 | 66 | #[test] 67 | fn swap_ump_fails_1_id_invalid() { 68 | new_test_ext().execute_with(|| { 69 | let shell_id = ::ShellRuntimeParaId::get(); 70 | assert_noop!( 71 | XcmTransactor::send_swap_ump( 72 | RuntimeOrigin::root(), 73 | shell_id.into(), 74 | ParaId::from(20000), 75 | 10_000_000_000u64.into(), 76 | 10_000_000_000u64.into() 77 | ), 78 | Error::::InvalidSwapIds 79 | ); 80 | }) 81 | } 82 | 83 | #[test] 84 | fn swap_ump_fails_2_id_invalid() { 85 | new_test_ext().execute_with(|| { 86 | let integritee_id = ::IntegriteeKsmParaId::get(); 87 | assert_noop!( 88 | XcmTransactor::send_swap_ump( 89 | RuntimeOrigin::root(), 90 | integritee_id.into(), 91 | ParaId::from(20000), 92 | 10_000_000_000u64.into(), 93 | 10_000_000_000u64.into() 94 | ), 95 | Error::::InvalidSwapIds 96 | ); 97 | }) 98 | } 99 | 100 | #[test] 101 | fn swap_ump_success() { 102 | new_test_ext().execute_with(|| { 103 | let shell_id = ::ShellRuntimeParaId::get(); 104 | let integritee_id = ::IntegriteeKsmParaId::get(); 105 | assert_ok!(XcmTransactor::send_swap_ump( 106 | RuntimeOrigin::root(), 107 | shell_id.into(), 108 | integritee_id.into(), 109 | 10_000_000_000u64.into(), 110 | 10_000_000_000u64.into() 111 | )); 112 | assert!(System::events().iter().any(|swap| matches!( 113 | swap.event, 114 | RuntimeEvent::XcmTransactor(crate::Event::SwapTransactSent { .. }) 115 | ))); 116 | }) 117 | } 118 | 119 | #[test] 120 | fn decode_swap_ump_in_kusama_success() { 121 | let shell_id: ParaId = ::ShellRuntimeParaId::get().into(); 122 | let integritee_id: ParaId = ::IntegriteeKsmParaId::get().into(); 123 | let encoded_call = 124 | ::RelayCallBuilder::swap_call(shell_id, integritee_id).encode(); 125 | 126 | let kusama_call = KusamaRuntimeCall::decode(&mut &encoded_call[..]) 127 | .expect("Can Decode into a Kusama Runtime Call; QED"); 128 | if let KusamaRuntimeCall::Registrar(KsmRegistrarCall::swap { id, other }) = kusama_call { 129 | assert_eq!(shell_id, ParaId::from(id.0)); 130 | assert_eq!(integritee_id, ParaId::from(other.0)); 131 | } else { 132 | panic!(); 133 | } 134 | } 135 | --------------------------------------------------------------------------------