├── .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 |
47 | {{#each overview}}
48 | - {{name}} ({{count}})
49 | {{/each}}
50 |
51 |
52 | All license text:
53 |
54 | {{#each licenses}}
55 | -
56 |
{{name}}
57 | Used by:
58 |
63 | {{text}}
64 |
65 | {{/each}}
66 |
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